]> Git Repo - binutils.git/blob - gdb/infrun.c
gdb
[binutils.git] / gdb / infrun.c
1 /* Target-struct-independent code to start (run) and stop an inferior
2    process.
3
4    Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
5    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
6    2008, 2009, 2010 Free Software Foundation, Inc.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "gdb_string.h"
25 #include <ctype.h>
26 #include "symtab.h"
27 #include "frame.h"
28 #include "inferior.h"
29 #include "exceptions.h"
30 #include "breakpoint.h"
31 #include "gdb_wait.h"
32 #include "gdbcore.h"
33 #include "gdbcmd.h"
34 #include "cli/cli-script.h"
35 #include "target.h"
36 #include "gdbthread.h"
37 #include "annotate.h"
38 #include "symfile.h"
39 #include "top.h"
40 #include <signal.h>
41 #include "inf-loop.h"
42 #include "regcache.h"
43 #include "value.h"
44 #include "observer.h"
45 #include "language.h"
46 #include "solib.h"
47 #include "main.h"
48 #include "dictionary.h"
49 #include "block.h"
50 #include "gdb_assert.h"
51 #include "mi/mi-common.h"
52 #include "event-top.h"
53 #include "record.h"
54 #include "inline-frame.h"
55 #include "jit.h"
56 #include "tracepoint.h"
57
58 /* Prototypes for local functions */
59
60 static void signals_info (char *, int);
61
62 static void handle_command (char *, int);
63
64 static void sig_print_info (enum target_signal);
65
66 static void sig_print_header (void);
67
68 static void resume_cleanups (void *);
69
70 static int hook_stop_stub (void *);
71
72 static int restore_selected_frame (void *);
73
74 static int follow_fork (void);
75
76 static void set_schedlock_func (char *args, int from_tty,
77                                 struct cmd_list_element *c);
78
79 static int currently_stepping (struct thread_info *tp);
80
81 static int currently_stepping_or_nexting_callback (struct thread_info *tp,
82                                                    void *data);
83
84 static void xdb_handle_command (char *args, int from_tty);
85
86 static int prepare_to_proceed (int);
87
88 static void print_exited_reason (int exitstatus);
89
90 static void print_signal_exited_reason (enum target_signal siggnal);
91
92 static void print_no_history_reason (void);
93
94 static void print_signal_received_reason (enum target_signal siggnal);
95
96 static void print_end_stepping_range_reason (void);
97
98 void _initialize_infrun (void);
99
100 void nullify_last_target_wait_ptid (void);
101
102 /* When set, stop the 'step' command if we enter a function which has
103    no line number information.  The normal behavior is that we step
104    over such function.  */
105 int step_stop_if_no_debug = 0;
106 static void
107 show_step_stop_if_no_debug (struct ui_file *file, int from_tty,
108                             struct cmd_list_element *c, const char *value)
109 {
110   fprintf_filtered (file, _("Mode of the step operation is %s.\n"), value);
111 }
112
113 /* In asynchronous mode, but simulating synchronous execution. */
114
115 int sync_execution = 0;
116
117 /* wait_for_inferior and normal_stop use this to notify the user
118    when the inferior stopped in a different thread than it had been
119    running in.  */
120
121 static ptid_t previous_inferior_ptid;
122
123 /* Default behavior is to detach newly forked processes (legacy).  */
124 int detach_fork = 1;
125
126 int debug_displaced = 0;
127 static void
128 show_debug_displaced (struct ui_file *file, int from_tty,
129                       struct cmd_list_element *c, const char *value)
130 {
131   fprintf_filtered (file, _("Displace stepping debugging is %s.\n"), value);
132 }
133
134 int debug_infrun = 0;
135 static void
136 show_debug_infrun (struct ui_file *file, int from_tty,
137                    struct cmd_list_element *c, const char *value)
138 {
139   fprintf_filtered (file, _("Inferior debugging is %s.\n"), value);
140 }
141
142 /* If the program uses ELF-style shared libraries, then calls to
143    functions in shared libraries go through stubs, which live in a
144    table called the PLT (Procedure Linkage Table).  The first time the
145    function is called, the stub sends control to the dynamic linker,
146    which looks up the function's real address, patches the stub so
147    that future calls will go directly to the function, and then passes
148    control to the function.
149
150    If we are stepping at the source level, we don't want to see any of
151    this --- we just want to skip over the stub and the dynamic linker.
152    The simple approach is to single-step until control leaves the
153    dynamic linker.
154
155    However, on some systems (e.g., Red Hat's 5.2 distribution) the
156    dynamic linker calls functions in the shared C library, so you
157    can't tell from the PC alone whether the dynamic linker is still
158    running.  In this case, we use a step-resume breakpoint to get us
159    past the dynamic linker, as if we were using "next" to step over a
160    function call.
161
162    in_solib_dynsym_resolve_code() says whether we're in the dynamic
163    linker code or not.  Normally, this means we single-step.  However,
164    if SKIP_SOLIB_RESOLVER then returns non-zero, then its value is an
165    address where we can place a step-resume breakpoint to get past the
166    linker's symbol resolution function.
167
168    in_solib_dynsym_resolve_code() can generally be implemented in a
169    pretty portable way, by comparing the PC against the address ranges
170    of the dynamic linker's sections.
171
172    SKIP_SOLIB_RESOLVER is generally going to be system-specific, since
173    it depends on internal details of the dynamic linker.  It's usually
174    not too hard to figure out where to put a breakpoint, but it
175    certainly isn't portable.  SKIP_SOLIB_RESOLVER should do plenty of
176    sanity checking.  If it can't figure things out, returning zero and
177    getting the (possibly confusing) stepping behavior is better than
178    signalling an error, which will obscure the change in the
179    inferior's state.  */
180
181 /* This function returns TRUE if pc is the address of an instruction
182    that lies within the dynamic linker (such as the event hook, or the
183    dld itself).
184
185    This function must be used only when a dynamic linker event has
186    been caught, and the inferior is being stepped out of the hook, or
187    undefined results are guaranteed.  */
188
189 #ifndef SOLIB_IN_DYNAMIC_LINKER
190 #define SOLIB_IN_DYNAMIC_LINKER(pid,pc) 0
191 #endif
192
193 /* "Observer mode" is somewhat like a more extreme version of
194    non-stop, in which all GDB operations that might affect the
195    target's execution have been disabled.  */
196
197 static int non_stop_1 = 0;
198
199 int observer_mode = 0;
200 static int observer_mode_1 = 0;
201
202 static void
203 set_observer_mode (char *args, int from_tty,
204                    struct cmd_list_element *c)
205 {
206   extern int pagination_enabled;
207
208   if (target_has_execution)
209     {
210       observer_mode_1 = observer_mode;
211       error (_("Cannot change this setting while the inferior is running."));
212     }
213
214   observer_mode = observer_mode_1;
215
216   may_write_registers = !observer_mode;
217   may_write_memory = !observer_mode;
218   may_insert_breakpoints = !observer_mode;
219   may_insert_tracepoints = !observer_mode;
220   /* We can insert fast tracepoints in or out of observer mode,
221      but enable them if we're going into this mode.  */
222   if (observer_mode)
223     may_insert_fast_tracepoints = 1;
224   may_stop = !observer_mode;
225   update_target_permissions ();
226
227   /* Going *into* observer mode we must force non-stop, then
228      going out we leave it that way.  */
229   if (observer_mode)
230     {
231       target_async_permitted = 1;
232       pagination_enabled = 0;
233       non_stop = non_stop_1 = 1;
234     }
235
236   if (from_tty)
237     printf_filtered (_("Observer mode is now %s.\n"),
238                      (observer_mode ? "on" : "off"));
239 }
240
241 static void
242 show_observer_mode (struct ui_file *file, int from_tty,
243                     struct cmd_list_element *c, const char *value)
244 {
245   fprintf_filtered (file, _("Observer mode is %s.\n"), value);
246 }
247
248 /* This updates the value of observer mode based on changes in
249    permissions.  Note that we are deliberately ignoring the values of
250    may-write-registers and may-write-memory, since the user may have
251    reason to enable these during a session, for instance to turn on a
252    debugging-related global.  */
253
254 void
255 update_observer_mode (void)
256 {
257   int newval;
258
259   newval = (!may_insert_breakpoints
260             && !may_insert_tracepoints
261             && may_insert_fast_tracepoints
262             && !may_stop
263             && non_stop);
264
265   /* Let the user know if things change.  */
266   if (newval != observer_mode)
267     printf_filtered (_("Observer mode is now %s.\n"),
268                      (newval ? "on" : "off"));
269
270   observer_mode = observer_mode_1 = newval;
271 }
272
273 /* Tables of how to react to signals; the user sets them.  */
274
275 static unsigned char *signal_stop;
276 static unsigned char *signal_print;
277 static unsigned char *signal_program;
278
279 #define SET_SIGS(nsigs,sigs,flags) \
280   do { \
281     int signum = (nsigs); \
282     while (signum-- > 0) \
283       if ((sigs)[signum]) \
284         (flags)[signum] = 1; \
285   } while (0)
286
287 #define UNSET_SIGS(nsigs,sigs,flags) \
288   do { \
289     int signum = (nsigs); \
290     while (signum-- > 0) \
291       if ((sigs)[signum]) \
292         (flags)[signum] = 0; \
293   } while (0)
294
295 /* Value to pass to target_resume() to cause all threads to resume */
296
297 #define RESUME_ALL minus_one_ptid
298
299 /* Command list pointer for the "stop" placeholder.  */
300
301 static struct cmd_list_element *stop_command;
302
303 /* Function inferior was in as of last step command.  */
304
305 static struct symbol *step_start_function;
306
307 /* Nonzero if we want to give control to the user when we're notified
308    of shared library events by the dynamic linker.  */
309 int stop_on_solib_events;
310 static void
311 show_stop_on_solib_events (struct ui_file *file, int from_tty,
312                            struct cmd_list_element *c, const char *value)
313 {
314   fprintf_filtered (file, _("Stopping for shared library events is %s.\n"),
315                     value);
316 }
317
318 /* Nonzero means expecting a trace trap
319    and should stop the inferior and return silently when it happens.  */
320
321 int stop_after_trap;
322
323 /* Save register contents here when executing a "finish" command or are
324    about to pop a stack dummy frame, if-and-only-if proceed_to_finish is set.
325    Thus this contains the return value from the called function (assuming
326    values are returned in a register).  */
327
328 struct regcache *stop_registers;
329
330 /* Nonzero after stop if current stack frame should be printed.  */
331
332 static int stop_print_frame;
333
334 /* This is a cached copy of the pid/waitstatus of the last event
335    returned by target_wait()/deprecated_target_wait_hook().  This
336    information is returned by get_last_target_status().  */
337 static ptid_t target_last_wait_ptid;
338 static struct target_waitstatus target_last_waitstatus;
339
340 static void context_switch (ptid_t ptid);
341
342 void init_thread_stepping_state (struct thread_info *tss);
343
344 void init_infwait_state (void);
345
346 static const char follow_fork_mode_child[] = "child";
347 static const char follow_fork_mode_parent[] = "parent";
348
349 static const char *follow_fork_mode_kind_names[] = {
350   follow_fork_mode_child,
351   follow_fork_mode_parent,
352   NULL
353 };
354
355 static const char *follow_fork_mode_string = follow_fork_mode_parent;
356 static void
357 show_follow_fork_mode_string (struct ui_file *file, int from_tty,
358                               struct cmd_list_element *c, const char *value)
359 {
360   fprintf_filtered (file, _("\
361 Debugger response to a program call of fork or vfork is \"%s\".\n"),
362                     value);
363 }
364 \f
365
366 /* Tell the target to follow the fork we're stopped at.  Returns true
367    if the inferior should be resumed; false, if the target for some
368    reason decided it's best not to resume.  */
369
370 static int
371 follow_fork (void)
372 {
373   int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
374   int should_resume = 1;
375   struct thread_info *tp;
376
377   /* Copy user stepping state to the new inferior thread.  FIXME: the
378      followed fork child thread should have a copy of most of the
379      parent thread structure's run control related fields, not just these.
380      Initialized to avoid "may be used uninitialized" warnings from gcc.  */
381   struct breakpoint *step_resume_breakpoint = NULL;
382   struct breakpoint *exception_resume_breakpoint = NULL;
383   CORE_ADDR step_range_start = 0;
384   CORE_ADDR step_range_end = 0;
385   struct frame_id step_frame_id = { 0 };
386
387   if (!non_stop)
388     {
389       ptid_t wait_ptid;
390       struct target_waitstatus wait_status;
391
392       /* Get the last target status returned by target_wait().  */
393       get_last_target_status (&wait_ptid, &wait_status);
394
395       /* If not stopped at a fork event, then there's nothing else to
396          do.  */
397       if (wait_status.kind != TARGET_WAITKIND_FORKED
398           && wait_status.kind != TARGET_WAITKIND_VFORKED)
399         return 1;
400
401       /* Check if we switched over from WAIT_PTID, since the event was
402          reported.  */
403       if (!ptid_equal (wait_ptid, minus_one_ptid)
404           && !ptid_equal (inferior_ptid, wait_ptid))
405         {
406           /* We did.  Switch back to WAIT_PTID thread, to tell the
407              target to follow it (in either direction).  We'll
408              afterwards refuse to resume, and inform the user what
409              happened.  */
410           switch_to_thread (wait_ptid);
411           should_resume = 0;
412         }
413     }
414
415   tp = inferior_thread ();
416
417   /* If there were any forks/vforks that were caught and are now to be
418      followed, then do so now.  */
419   switch (tp->pending_follow.kind)
420     {
421     case TARGET_WAITKIND_FORKED:
422     case TARGET_WAITKIND_VFORKED:
423       {
424         ptid_t parent, child;
425
426         /* If the user did a next/step, etc, over a fork call,
427            preserve the stepping state in the fork child.  */
428         if (follow_child && should_resume)
429           {
430             step_resume_breakpoint = clone_momentary_breakpoint
431                                          (tp->control.step_resume_breakpoint);
432             step_range_start = tp->control.step_range_start;
433             step_range_end = tp->control.step_range_end;
434             step_frame_id = tp->control.step_frame_id;
435             exception_resume_breakpoint
436               = clone_momentary_breakpoint (tp->control.exception_resume_breakpoint);
437
438             /* For now, delete the parent's sr breakpoint, otherwise,
439                parent/child sr breakpoints are considered duplicates,
440                and the child version will not be installed.  Remove
441                this when the breakpoints module becomes aware of
442                inferiors and address spaces.  */
443             delete_step_resume_breakpoint (tp);
444             tp->control.step_range_start = 0;
445             tp->control.step_range_end = 0;
446             tp->control.step_frame_id = null_frame_id;
447             delete_exception_resume_breakpoint (tp);
448           }
449
450         parent = inferior_ptid;
451         child = tp->pending_follow.value.related_pid;
452
453         /* Tell the target to do whatever is necessary to follow
454            either parent or child.  */
455         if (target_follow_fork (follow_child))
456           {
457             /* Target refused to follow, or there's some other reason
458                we shouldn't resume.  */
459             should_resume = 0;
460           }
461         else
462           {
463             /* This pending follow fork event is now handled, one way
464                or another.  The previous selected thread may be gone
465                from the lists by now, but if it is still around, need
466                to clear the pending follow request.  */
467             tp = find_thread_ptid (parent);
468             if (tp)
469               tp->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
470
471             /* This makes sure we don't try to apply the "Switched
472                over from WAIT_PID" logic above.  */
473             nullify_last_target_wait_ptid ();
474
475             /* If we followed the child, switch to it... */
476             if (follow_child)
477               {
478                 switch_to_thread (child);
479
480                 /* ... and preserve the stepping state, in case the
481                    user was stepping over the fork call.  */
482                 if (should_resume)
483                   {
484                     tp = inferior_thread ();
485                     tp->control.step_resume_breakpoint
486                       = step_resume_breakpoint;
487                     tp->control.step_range_start = step_range_start;
488                     tp->control.step_range_end = step_range_end;
489                     tp->control.step_frame_id = step_frame_id;
490                     tp->control.exception_resume_breakpoint
491                       = exception_resume_breakpoint;
492                   }
493                 else
494                   {
495                     /* If we get here, it was because we're trying to
496                        resume from a fork catchpoint, but, the user
497                        has switched threads away from the thread that
498                        forked.  In that case, the resume command
499                        issued is most likely not applicable to the
500                        child, so just warn, and refuse to resume.  */
501                     warning (_("\
502 Not resuming: switched threads before following fork child.\n"));
503                   }
504
505                 /* Reset breakpoints in the child as appropriate.  */
506                 follow_inferior_reset_breakpoints ();
507               }
508             else
509               switch_to_thread (parent);
510           }
511       }
512       break;
513     case TARGET_WAITKIND_SPURIOUS:
514       /* Nothing to follow.  */
515       break;
516     default:
517       internal_error (__FILE__, __LINE__,
518                       "Unexpected pending_follow.kind %d\n",
519                       tp->pending_follow.kind);
520       break;
521     }
522
523   return should_resume;
524 }
525
526 void
527 follow_inferior_reset_breakpoints (void)
528 {
529   struct thread_info *tp = inferior_thread ();
530
531   /* Was there a step_resume breakpoint?  (There was if the user
532      did a "next" at the fork() call.)  If so, explicitly reset its
533      thread number.
534
535      step_resumes are a form of bp that are made to be per-thread.
536      Since we created the step_resume bp when the parent process
537      was being debugged, and now are switching to the child process,
538      from the breakpoint package's viewpoint, that's a switch of
539      "threads".  We must update the bp's notion of which thread
540      it is for, or it'll be ignored when it triggers.  */
541
542   if (tp->control.step_resume_breakpoint)
543     breakpoint_re_set_thread (tp->control.step_resume_breakpoint);
544
545   if (tp->control.exception_resume_breakpoint)
546     breakpoint_re_set_thread (tp->control.exception_resume_breakpoint);
547
548   /* Reinsert all breakpoints in the child.  The user may have set
549      breakpoints after catching the fork, in which case those
550      were never set in the child, but only in the parent.  This makes
551      sure the inserted breakpoints match the breakpoint list.  */
552
553   breakpoint_re_set ();
554   insert_breakpoints ();
555 }
556
557 /* The child has exited or execed: resume threads of the parent the
558    user wanted to be executing.  */
559
560 static int
561 proceed_after_vfork_done (struct thread_info *thread,
562                           void *arg)
563 {
564   int pid = * (int *) arg;
565
566   if (ptid_get_pid (thread->ptid) == pid
567       && is_running (thread->ptid)
568       && !is_executing (thread->ptid)
569       && !thread->stop_requested
570       && thread->suspend.stop_signal == TARGET_SIGNAL_0)
571     {
572       if (debug_infrun)
573         fprintf_unfiltered (gdb_stdlog,
574                             "infrun: resuming vfork parent thread %s\n",
575                             target_pid_to_str (thread->ptid));
576
577       switch_to_thread (thread->ptid);
578       clear_proceed_status ();
579       proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
580     }
581
582   return 0;
583 }
584
585 /* Called whenever we notice an exec or exit event, to handle
586    detaching or resuming a vfork parent.  */
587
588 static void
589 handle_vfork_child_exec_or_exit (int exec)
590 {
591   struct inferior *inf = current_inferior ();
592
593   if (inf->vfork_parent)
594     {
595       int resume_parent = -1;
596
597       /* This exec or exit marks the end of the shared memory region
598          between the parent and the child.  If the user wanted to
599          detach from the parent, now is the time.  */
600
601       if (inf->vfork_parent->pending_detach)
602         {
603           struct thread_info *tp;
604           struct cleanup *old_chain;
605           struct program_space *pspace;
606           struct address_space *aspace;
607
608           /* follow-fork child, detach-on-fork on */
609
610           old_chain = make_cleanup_restore_current_thread ();
611
612           /* We're letting loose of the parent.  */
613           tp = any_live_thread_of_process (inf->vfork_parent->pid);
614           switch_to_thread (tp->ptid);
615
616           /* We're about to detach from the parent, which implicitly
617              removes breakpoints from its address space.  There's a
618              catch here: we want to reuse the spaces for the child,
619              but, parent/child are still sharing the pspace at this
620              point, although the exec in reality makes the kernel give
621              the child a fresh set of new pages.  The problem here is
622              that the breakpoints module being unaware of this, would
623              likely chose the child process to write to the parent
624              address space.  Swapping the child temporarily away from
625              the spaces has the desired effect.  Yes, this is "sort
626              of" a hack.  */
627
628           pspace = inf->pspace;
629           aspace = inf->aspace;
630           inf->aspace = NULL;
631           inf->pspace = NULL;
632
633           if (debug_infrun || info_verbose)
634             {
635               target_terminal_ours ();
636
637               if (exec)
638                 fprintf_filtered (gdb_stdlog,
639                                   "Detaching vfork parent process %d after child exec.\n",
640                                   inf->vfork_parent->pid);
641               else
642                 fprintf_filtered (gdb_stdlog,
643                                   "Detaching vfork parent process %d after child exit.\n",
644                                   inf->vfork_parent->pid);
645             }
646
647           target_detach (NULL, 0);
648
649           /* Put it back.  */
650           inf->pspace = pspace;
651           inf->aspace = aspace;
652
653           do_cleanups (old_chain);
654         }
655       else if (exec)
656         {
657           /* We're staying attached to the parent, so, really give the
658              child a new address space.  */
659           inf->pspace = add_program_space (maybe_new_address_space ());
660           inf->aspace = inf->pspace->aspace;
661           inf->removable = 1;
662           set_current_program_space (inf->pspace);
663
664           resume_parent = inf->vfork_parent->pid;
665
666           /* Break the bonds.  */
667           inf->vfork_parent->vfork_child = NULL;
668         }
669       else
670         {
671           struct cleanup *old_chain;
672           struct program_space *pspace;
673
674           /* If this is a vfork child exiting, then the pspace and
675              aspaces were shared with the parent.  Since we're
676              reporting the process exit, we'll be mourning all that is
677              found in the address space, and switching to null_ptid,
678              preparing to start a new inferior.  But, since we don't
679              want to clobber the parent's address/program spaces, we
680              go ahead and create a new one for this exiting
681              inferior.  */
682
683           /* Switch to null_ptid, so that clone_program_space doesn't want
684              to read the selected frame of a dead process.  */
685           old_chain = save_inferior_ptid ();
686           inferior_ptid = null_ptid;
687
688           /* This inferior is dead, so avoid giving the breakpoints
689              module the option to write through to it (cloning a
690              program space resets breakpoints).  */
691           inf->aspace = NULL;
692           inf->pspace = NULL;
693           pspace = add_program_space (maybe_new_address_space ());
694           set_current_program_space (pspace);
695           inf->removable = 1;
696           clone_program_space (pspace, inf->vfork_parent->pspace);
697           inf->pspace = pspace;
698           inf->aspace = pspace->aspace;
699
700           /* Put back inferior_ptid.  We'll continue mourning this
701              inferior. */
702           do_cleanups (old_chain);
703
704           resume_parent = inf->vfork_parent->pid;
705           /* Break the bonds.  */
706           inf->vfork_parent->vfork_child = NULL;
707         }
708
709       inf->vfork_parent = NULL;
710
711       gdb_assert (current_program_space == inf->pspace);
712
713       if (non_stop && resume_parent != -1)
714         {
715           /* If the user wanted the parent to be running, let it go
716              free now.  */
717           struct cleanup *old_chain = make_cleanup_restore_current_thread ();
718
719           if (debug_infrun)
720             fprintf_unfiltered (gdb_stdlog, "infrun: resuming vfork parent process %d\n",
721                                 resume_parent);
722
723           iterate_over_threads (proceed_after_vfork_done, &resume_parent);
724
725           do_cleanups (old_chain);
726         }
727     }
728 }
729
730 /* Enum strings for "set|show displaced-stepping".  */
731
732 static const char follow_exec_mode_new[] = "new";
733 static const char follow_exec_mode_same[] = "same";
734 static const char *follow_exec_mode_names[] =
735 {
736   follow_exec_mode_new,
737   follow_exec_mode_same,
738   NULL,
739 };
740
741 static const char *follow_exec_mode_string = follow_exec_mode_same;
742 static void
743 show_follow_exec_mode_string (struct ui_file *file, int from_tty,
744                               struct cmd_list_element *c, const char *value)
745 {
746   fprintf_filtered (file, _("Follow exec mode is \"%s\".\n"),  value);
747 }
748
749 /* EXECD_PATHNAME is assumed to be non-NULL. */
750
751 static void
752 follow_exec (ptid_t pid, char *execd_pathname)
753 {
754   struct thread_info *th = inferior_thread ();
755   struct inferior *inf = current_inferior ();
756
757   /* This is an exec event that we actually wish to pay attention to.
758      Refresh our symbol table to the newly exec'd program, remove any
759      momentary bp's, etc.
760
761      If there are breakpoints, they aren't really inserted now,
762      since the exec() transformed our inferior into a fresh set
763      of instructions.
764
765      We want to preserve symbolic breakpoints on the list, since
766      we have hopes that they can be reset after the new a.out's
767      symbol table is read.
768
769      However, any "raw" breakpoints must be removed from the list
770      (e.g., the solib bp's), since their address is probably invalid
771      now.
772
773      And, we DON'T want to call delete_breakpoints() here, since
774      that may write the bp's "shadow contents" (the instruction
775      value that was overwritten witha TRAP instruction).  Since
776      we now have a new a.out, those shadow contents aren't valid. */
777
778   mark_breakpoints_out ();
779
780   update_breakpoints_after_exec ();
781
782   /* If there was one, it's gone now.  We cannot truly step-to-next
783      statement through an exec(). */
784   th->control.step_resume_breakpoint = NULL;
785   th->control.exception_resume_breakpoint = NULL;
786   th->control.step_range_start = 0;
787   th->control.step_range_end = 0;
788
789   /* The target reports the exec event to the main thread, even if
790      some other thread does the exec, and even if the main thread was
791      already stopped --- if debugging in non-stop mode, it's possible
792      the user had the main thread held stopped in the previous image
793      --- release it now.  This is the same behavior as step-over-exec
794      with scheduler-locking on in all-stop mode.  */
795   th->stop_requested = 0;
796
797   /* What is this a.out's name? */
798   printf_unfiltered (_("%s is executing new program: %s\n"),
799                      target_pid_to_str (inferior_ptid),
800                      execd_pathname);
801
802   /* We've followed the inferior through an exec.  Therefore, the
803      inferior has essentially been killed & reborn. */
804
805   gdb_flush (gdb_stdout);
806
807   breakpoint_init_inferior (inf_execd);
808
809   if (gdb_sysroot && *gdb_sysroot)
810     {
811       char *name = alloca (strlen (gdb_sysroot)
812                             + strlen (execd_pathname)
813                             + 1);
814
815       strcpy (name, gdb_sysroot);
816       strcat (name, execd_pathname);
817       execd_pathname = name;
818     }
819
820   /* Reset the shared library package.  This ensures that we get a
821      shlib event when the child reaches "_start", at which point the
822      dld will have had a chance to initialize the child.  */
823   /* Also, loading a symbol file below may trigger symbol lookups, and
824      we don't want those to be satisfied by the libraries of the
825      previous incarnation of this process.  */
826   no_shared_libraries (NULL, 0);
827
828   if (follow_exec_mode_string == follow_exec_mode_new)
829     {
830       struct program_space *pspace;
831
832       /* The user wants to keep the old inferior and program spaces
833          around.  Create a new fresh one, and switch to it.  */
834
835       inf = add_inferior (current_inferior ()->pid);
836       pspace = add_program_space (maybe_new_address_space ());
837       inf->pspace = pspace;
838       inf->aspace = pspace->aspace;
839
840       exit_inferior_num_silent (current_inferior ()->num);
841
842       set_current_inferior (inf);
843       set_current_program_space (pspace);
844     }
845
846   gdb_assert (current_program_space == inf->pspace);
847
848   /* That a.out is now the one to use. */
849   exec_file_attach (execd_pathname, 0);
850
851   /* SYMFILE_DEFER_BP_RESET is used as the proper displacement for PIE
852      (Position Independent Executable) main symbol file will get applied by
853      solib_create_inferior_hook below.  breakpoint_re_set would fail to insert
854      the breakpoints with the zero displacement.  */
855
856   symbol_file_add (execd_pathname, SYMFILE_MAINLINE | SYMFILE_DEFER_BP_RESET,
857                    NULL, 0);
858
859   set_initial_language ();
860
861 #ifdef SOLIB_CREATE_INFERIOR_HOOK
862   SOLIB_CREATE_INFERIOR_HOOK (PIDGET (inferior_ptid));
863 #else
864   solib_create_inferior_hook (0);
865 #endif
866
867   jit_inferior_created_hook ();
868
869   breakpoint_re_set ();
870
871   /* Reinsert all breakpoints.  (Those which were symbolic have
872      been reset to the proper address in the new a.out, thanks
873      to symbol_file_command...) */
874   insert_breakpoints ();
875
876   /* The next resume of this inferior should bring it to the shlib
877      startup breakpoints.  (If the user had also set bp's on
878      "main" from the old (parent) process, then they'll auto-
879      matically get reset there in the new process.) */
880 }
881
882 /* Non-zero if we just simulating a single-step.  This is needed
883    because we cannot remove the breakpoints in the inferior process
884    until after the `wait' in `wait_for_inferior'.  */
885 static int singlestep_breakpoints_inserted_p = 0;
886
887 /* The thread we inserted single-step breakpoints for.  */
888 static ptid_t singlestep_ptid;
889
890 /* PC when we started this single-step.  */
891 static CORE_ADDR singlestep_pc;
892
893 /* If another thread hit the singlestep breakpoint, we save the original
894    thread here so that we can resume single-stepping it later.  */
895 static ptid_t saved_singlestep_ptid;
896 static int stepping_past_singlestep_breakpoint;
897
898 /* If not equal to null_ptid, this means that after stepping over breakpoint
899    is finished, we need to switch to deferred_step_ptid, and step it.
900
901    The use case is when one thread has hit a breakpoint, and then the user 
902    has switched to another thread and issued 'step'. We need to step over
903    breakpoint in the thread which hit the breakpoint, but then continue
904    stepping the thread user has selected.  */
905 static ptid_t deferred_step_ptid;
906 \f
907 /* Displaced stepping.  */
908
909 /* In non-stop debugging mode, we must take special care to manage
910    breakpoints properly; in particular, the traditional strategy for
911    stepping a thread past a breakpoint it has hit is unsuitable.
912    'Displaced stepping' is a tactic for stepping one thread past a
913    breakpoint it has hit while ensuring that other threads running
914    concurrently will hit the breakpoint as they should.
915
916    The traditional way to step a thread T off a breakpoint in a
917    multi-threaded program in all-stop mode is as follows:
918
919    a0) Initially, all threads are stopped, and breakpoints are not
920        inserted.
921    a1) We single-step T, leaving breakpoints uninserted.
922    a2) We insert breakpoints, and resume all threads.
923
924    In non-stop debugging, however, this strategy is unsuitable: we
925    don't want to have to stop all threads in the system in order to
926    continue or step T past a breakpoint.  Instead, we use displaced
927    stepping:
928
929    n0) Initially, T is stopped, other threads are running, and
930        breakpoints are inserted.
931    n1) We copy the instruction "under" the breakpoint to a separate
932        location, outside the main code stream, making any adjustments
933        to the instruction, register, and memory state as directed by
934        T's architecture.
935    n2) We single-step T over the instruction at its new location.
936    n3) We adjust the resulting register and memory state as directed
937        by T's architecture.  This includes resetting T's PC to point
938        back into the main instruction stream.
939    n4) We resume T.
940
941    This approach depends on the following gdbarch methods:
942
943    - gdbarch_max_insn_length and gdbarch_displaced_step_location
944      indicate where to copy the instruction, and how much space must
945      be reserved there.  We use these in step n1.
946
947    - gdbarch_displaced_step_copy_insn copies a instruction to a new
948      address, and makes any necessary adjustments to the instruction,
949      register contents, and memory.  We use this in step n1.
950
951    - gdbarch_displaced_step_fixup adjusts registers and memory after
952      we have successfuly single-stepped the instruction, to yield the
953      same effect the instruction would have had if we had executed it
954      at its original address.  We use this in step n3.
955
956    - gdbarch_displaced_step_free_closure provides cleanup.
957
958    The gdbarch_displaced_step_copy_insn and
959    gdbarch_displaced_step_fixup functions must be written so that
960    copying an instruction with gdbarch_displaced_step_copy_insn,
961    single-stepping across the copied instruction, and then applying
962    gdbarch_displaced_insn_fixup should have the same effects on the
963    thread's memory and registers as stepping the instruction in place
964    would have.  Exactly which responsibilities fall to the copy and
965    which fall to the fixup is up to the author of those functions.
966
967    See the comments in gdbarch.sh for details.
968
969    Note that displaced stepping and software single-step cannot
970    currently be used in combination, although with some care I think
971    they could be made to.  Software single-step works by placing
972    breakpoints on all possible subsequent instructions; if the
973    displaced instruction is a PC-relative jump, those breakpoints
974    could fall in very strange places --- on pages that aren't
975    executable, or at addresses that are not proper instruction
976    boundaries.  (We do generally let other threads run while we wait
977    to hit the software single-step breakpoint, and they might
978    encounter such a corrupted instruction.)  One way to work around
979    this would be to have gdbarch_displaced_step_copy_insn fully
980    simulate the effect of PC-relative instructions (and return NULL)
981    on architectures that use software single-stepping.
982
983    In non-stop mode, we can have independent and simultaneous step
984    requests, so more than one thread may need to simultaneously step
985    over a breakpoint.  The current implementation assumes there is
986    only one scratch space per process.  In this case, we have to
987    serialize access to the scratch space.  If thread A wants to step
988    over a breakpoint, but we are currently waiting for some other
989    thread to complete a displaced step, we leave thread A stopped and
990    place it in the displaced_step_request_queue.  Whenever a displaced
991    step finishes, we pick the next thread in the queue and start a new
992    displaced step operation on it.  See displaced_step_prepare and
993    displaced_step_fixup for details.  */
994
995 struct displaced_step_request
996 {
997   ptid_t ptid;
998   struct displaced_step_request *next;
999 };
1000
1001 /* Per-inferior displaced stepping state.  */
1002 struct displaced_step_inferior_state
1003 {
1004   /* Pointer to next in linked list.  */
1005   struct displaced_step_inferior_state *next;
1006
1007   /* The process this displaced step state refers to.  */
1008   int pid;
1009
1010   /* A queue of pending displaced stepping requests.  One entry per
1011      thread that needs to do a displaced step.  */
1012   struct displaced_step_request *step_request_queue;
1013
1014   /* If this is not null_ptid, this is the thread carrying out a
1015      displaced single-step in process PID.  This thread's state will
1016      require fixing up once it has completed its step.  */
1017   ptid_t step_ptid;
1018
1019   /* The architecture the thread had when we stepped it.  */
1020   struct gdbarch *step_gdbarch;
1021
1022   /* The closure provided gdbarch_displaced_step_copy_insn, to be used
1023      for post-step cleanup.  */
1024   struct displaced_step_closure *step_closure;
1025
1026   /* The address of the original instruction, and the copy we
1027      made.  */
1028   CORE_ADDR step_original, step_copy;
1029
1030   /* Saved contents of copy area.  */
1031   gdb_byte *step_saved_copy;
1032 };
1033
1034 /* The list of states of processes involved in displaced stepping
1035    presently.  */
1036 static struct displaced_step_inferior_state *displaced_step_inferior_states;
1037
1038 /* Get the displaced stepping state of process PID.  */
1039
1040 static struct displaced_step_inferior_state *
1041 get_displaced_stepping_state (int pid)
1042 {
1043   struct displaced_step_inferior_state *state;
1044
1045   for (state = displaced_step_inferior_states;
1046        state != NULL;
1047        state = state->next)
1048     if (state->pid == pid)
1049       return state;
1050
1051   return NULL;
1052 }
1053
1054 /* Add a new displaced stepping state for process PID to the displaced
1055    stepping state list, or return a pointer to an already existing
1056    entry, if it already exists.  Never returns NULL.  */
1057
1058 static struct displaced_step_inferior_state *
1059 add_displaced_stepping_state (int pid)
1060 {
1061   struct displaced_step_inferior_state *state;
1062
1063   for (state = displaced_step_inferior_states;
1064        state != NULL;
1065        state = state->next)
1066     if (state->pid == pid)
1067       return state;
1068
1069   state = xcalloc (1, sizeof (*state));
1070   state->pid = pid;
1071   state->next = displaced_step_inferior_states;
1072   displaced_step_inferior_states = state;
1073
1074   return state;
1075 }
1076
1077 /* Remove the displaced stepping state of process PID.  */
1078
1079 static void
1080 remove_displaced_stepping_state (int pid)
1081 {
1082   struct displaced_step_inferior_state *it, **prev_next_p;
1083
1084   gdb_assert (pid != 0);
1085
1086   it = displaced_step_inferior_states;
1087   prev_next_p = &displaced_step_inferior_states;
1088   while (it)
1089     {
1090       if (it->pid == pid)
1091         {
1092           *prev_next_p = it->next;
1093           xfree (it);
1094           return;
1095         }
1096
1097       prev_next_p = &it->next;
1098       it = *prev_next_p;
1099     }
1100 }
1101
1102 static void
1103 infrun_inferior_exit (struct inferior *inf)
1104 {
1105   remove_displaced_stepping_state (inf->pid);
1106 }
1107
1108 /* Enum strings for "set|show displaced-stepping".  */
1109
1110 static const char can_use_displaced_stepping_auto[] = "auto";
1111 static const char can_use_displaced_stepping_on[] = "on";
1112 static const char can_use_displaced_stepping_off[] = "off";
1113 static const char *can_use_displaced_stepping_enum[] =
1114 {
1115   can_use_displaced_stepping_auto,
1116   can_use_displaced_stepping_on,
1117   can_use_displaced_stepping_off,
1118   NULL,
1119 };
1120
1121 /* If ON, and the architecture supports it, GDB will use displaced
1122    stepping to step over breakpoints.  If OFF, or if the architecture
1123    doesn't support it, GDB will instead use the traditional
1124    hold-and-step approach.  If AUTO (which is the default), GDB will
1125    decide which technique to use to step over breakpoints depending on
1126    which of all-stop or non-stop mode is active --- displaced stepping
1127    in non-stop mode; hold-and-step in all-stop mode.  */
1128
1129 static const char *can_use_displaced_stepping =
1130   can_use_displaced_stepping_auto;
1131
1132 static void
1133 show_can_use_displaced_stepping (struct ui_file *file, int from_tty,
1134                                  struct cmd_list_element *c,
1135                                  const char *value)
1136 {
1137   if (can_use_displaced_stepping == can_use_displaced_stepping_auto)
1138     fprintf_filtered (file, _("\
1139 Debugger's willingness to use displaced stepping to step over \
1140 breakpoints is %s (currently %s).\n"),
1141                       value, non_stop ? "on" : "off");
1142   else
1143     fprintf_filtered (file, _("\
1144 Debugger's willingness to use displaced stepping to step over \
1145 breakpoints is %s.\n"), value);
1146 }
1147
1148 /* Return non-zero if displaced stepping can/should be used to step
1149    over breakpoints.  */
1150
1151 static int
1152 use_displaced_stepping (struct gdbarch *gdbarch)
1153 {
1154   return (((can_use_displaced_stepping == can_use_displaced_stepping_auto
1155             && non_stop)
1156            || can_use_displaced_stepping == can_use_displaced_stepping_on)
1157           && gdbarch_displaced_step_copy_insn_p (gdbarch)
1158           && !RECORD_IS_USED);
1159 }
1160
1161 /* Clean out any stray displaced stepping state.  */
1162 static void
1163 displaced_step_clear (struct displaced_step_inferior_state *displaced)
1164 {
1165   /* Indicate that there is no cleanup pending.  */
1166   displaced->step_ptid = null_ptid;
1167
1168   if (displaced->step_closure)
1169     {
1170       gdbarch_displaced_step_free_closure (displaced->step_gdbarch,
1171                                            displaced->step_closure);
1172       displaced->step_closure = NULL;
1173     }
1174 }
1175
1176 static void
1177 displaced_step_clear_cleanup (void *arg)
1178 {
1179   struct displaced_step_inferior_state *state = arg;
1180
1181   displaced_step_clear (state);
1182 }
1183
1184 /* Dump LEN bytes at BUF in hex to FILE, followed by a newline.  */
1185 void
1186 displaced_step_dump_bytes (struct ui_file *file,
1187                            const gdb_byte *buf,
1188                            size_t len)
1189 {
1190   int i;
1191
1192   for (i = 0; i < len; i++)
1193     fprintf_unfiltered (file, "%02x ", buf[i]);
1194   fputs_unfiltered ("\n", file);
1195 }
1196
1197 /* Prepare to single-step, using displaced stepping.
1198
1199    Note that we cannot use displaced stepping when we have a signal to
1200    deliver.  If we have a signal to deliver and an instruction to step
1201    over, then after the step, there will be no indication from the
1202    target whether the thread entered a signal handler or ignored the
1203    signal and stepped over the instruction successfully --- both cases
1204    result in a simple SIGTRAP.  In the first case we mustn't do a
1205    fixup, and in the second case we must --- but we can't tell which.
1206    Comments in the code for 'random signals' in handle_inferior_event
1207    explain how we handle this case instead.
1208
1209    Returns 1 if preparing was successful -- this thread is going to be
1210    stepped now; or 0 if displaced stepping this thread got queued.  */
1211 static int
1212 displaced_step_prepare (ptid_t ptid)
1213 {
1214   struct cleanup *old_cleanups, *ignore_cleanups;
1215   struct regcache *regcache = get_thread_regcache (ptid);
1216   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1217   CORE_ADDR original, copy;
1218   ULONGEST len;
1219   struct displaced_step_closure *closure;
1220   struct displaced_step_inferior_state *displaced;
1221
1222   /* We should never reach this function if the architecture does not
1223      support displaced stepping.  */
1224   gdb_assert (gdbarch_displaced_step_copy_insn_p (gdbarch));
1225
1226   /* We have to displaced step one thread at a time, as we only have
1227      access to a single scratch space per inferior.  */
1228
1229   displaced = add_displaced_stepping_state (ptid_get_pid (ptid));
1230
1231   if (!ptid_equal (displaced->step_ptid, null_ptid))
1232     {
1233       /* Already waiting for a displaced step to finish.  Defer this
1234          request and place in queue.  */
1235       struct displaced_step_request *req, *new_req;
1236
1237       if (debug_displaced)
1238         fprintf_unfiltered (gdb_stdlog,
1239                             "displaced: defering step of %s\n",
1240                             target_pid_to_str (ptid));
1241
1242       new_req = xmalloc (sizeof (*new_req));
1243       new_req->ptid = ptid;
1244       new_req->next = NULL;
1245
1246       if (displaced->step_request_queue)
1247         {
1248           for (req = displaced->step_request_queue;
1249                req && req->next;
1250                req = req->next)
1251             ;
1252           req->next = new_req;
1253         }
1254       else
1255         displaced->step_request_queue = new_req;
1256
1257       return 0;
1258     }
1259   else
1260     {
1261       if (debug_displaced)
1262         fprintf_unfiltered (gdb_stdlog,
1263                             "displaced: stepping %s now\n",
1264                             target_pid_to_str (ptid));
1265     }
1266
1267   displaced_step_clear (displaced);
1268
1269   old_cleanups = save_inferior_ptid ();
1270   inferior_ptid = ptid;
1271
1272   original = regcache_read_pc (regcache);
1273
1274   copy = gdbarch_displaced_step_location (gdbarch);
1275   len = gdbarch_max_insn_length (gdbarch);
1276
1277   /* Save the original contents of the copy area.  */
1278   displaced->step_saved_copy = xmalloc (len);
1279   ignore_cleanups = make_cleanup (free_current_contents,
1280                                   &displaced->step_saved_copy);
1281   read_memory (copy, displaced->step_saved_copy, len);
1282   if (debug_displaced)
1283     {
1284       fprintf_unfiltered (gdb_stdlog, "displaced: saved %s: ",
1285                           paddress (gdbarch, copy));
1286       displaced_step_dump_bytes (gdb_stdlog,
1287                                  displaced->step_saved_copy,
1288                                  len);
1289     };
1290
1291   closure = gdbarch_displaced_step_copy_insn (gdbarch,
1292                                               original, copy, regcache);
1293
1294   /* We don't support the fully-simulated case at present.  */
1295   gdb_assert (closure);
1296
1297   /* Save the information we need to fix things up if the step
1298      succeeds.  */
1299   displaced->step_ptid = ptid;
1300   displaced->step_gdbarch = gdbarch;
1301   displaced->step_closure = closure;
1302   displaced->step_original = original;
1303   displaced->step_copy = copy;
1304
1305   make_cleanup (displaced_step_clear_cleanup, displaced);
1306
1307   /* Resume execution at the copy.  */
1308   regcache_write_pc (regcache, copy);
1309
1310   discard_cleanups (ignore_cleanups);
1311
1312   do_cleanups (old_cleanups);
1313
1314   if (debug_displaced)
1315     fprintf_unfiltered (gdb_stdlog, "displaced: displaced pc to %s\n",
1316                         paddress (gdbarch, copy));
1317
1318   return 1;
1319 }
1320
1321 static void
1322 write_memory_ptid (ptid_t ptid, CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
1323 {
1324   struct cleanup *ptid_cleanup = save_inferior_ptid ();
1325
1326   inferior_ptid = ptid;
1327   write_memory (memaddr, myaddr, len);
1328   do_cleanups (ptid_cleanup);
1329 }
1330
1331 static void
1332 displaced_step_fixup (ptid_t event_ptid, enum target_signal signal)
1333 {
1334   struct cleanup *old_cleanups;
1335   struct displaced_step_inferior_state *displaced
1336     = get_displaced_stepping_state (ptid_get_pid (event_ptid));
1337
1338   /* Was any thread of this process doing a displaced step?  */
1339   if (displaced == NULL)
1340     return;
1341
1342   /* Was this event for the pid we displaced?  */
1343   if (ptid_equal (displaced->step_ptid, null_ptid)
1344       || ! ptid_equal (displaced->step_ptid, event_ptid))
1345     return;
1346
1347   old_cleanups = make_cleanup (displaced_step_clear_cleanup, displaced);
1348
1349   /* Restore the contents of the copy area.  */
1350   {
1351     ULONGEST len = gdbarch_max_insn_length (displaced->step_gdbarch);
1352
1353     write_memory_ptid (displaced->step_ptid, displaced->step_copy,
1354                        displaced->step_saved_copy, len);
1355     if (debug_displaced)
1356       fprintf_unfiltered (gdb_stdlog, "displaced: restored %s\n",
1357                           paddress (displaced->step_gdbarch,
1358                                     displaced->step_copy));
1359   }
1360
1361   /* Did the instruction complete successfully?  */
1362   if (signal == TARGET_SIGNAL_TRAP)
1363     {
1364       /* Fix up the resulting state.  */
1365       gdbarch_displaced_step_fixup (displaced->step_gdbarch,
1366                                     displaced->step_closure,
1367                                     displaced->step_original,
1368                                     displaced->step_copy,
1369                                     get_thread_regcache (displaced->step_ptid));
1370     }
1371   else
1372     {
1373       /* Since the instruction didn't complete, all we can do is
1374          relocate the PC.  */
1375       struct regcache *regcache = get_thread_regcache (event_ptid);
1376       CORE_ADDR pc = regcache_read_pc (regcache);
1377
1378       pc = displaced->step_original + (pc - displaced->step_copy);
1379       regcache_write_pc (regcache, pc);
1380     }
1381
1382   do_cleanups (old_cleanups);
1383
1384   displaced->step_ptid = null_ptid;
1385
1386   /* Are there any pending displaced stepping requests?  If so, run
1387      one now.  Leave the state object around, since we're likely to
1388      need it again soon.  */
1389   while (displaced->step_request_queue)
1390     {
1391       struct displaced_step_request *head;
1392       ptid_t ptid;
1393       struct regcache *regcache;
1394       struct gdbarch *gdbarch;
1395       CORE_ADDR actual_pc;
1396       struct address_space *aspace;
1397
1398       head = displaced->step_request_queue;
1399       ptid = head->ptid;
1400       displaced->step_request_queue = head->next;
1401       xfree (head);
1402
1403       context_switch (ptid);
1404
1405       regcache = get_thread_regcache (ptid);
1406       actual_pc = regcache_read_pc (regcache);
1407       aspace = get_regcache_aspace (regcache);
1408
1409       if (breakpoint_here_p (aspace, actual_pc))
1410         {
1411           if (debug_displaced)
1412             fprintf_unfiltered (gdb_stdlog,
1413                                 "displaced: stepping queued %s now\n",
1414                                 target_pid_to_str (ptid));
1415
1416           displaced_step_prepare (ptid);
1417
1418           gdbarch = get_regcache_arch (regcache);
1419
1420           if (debug_displaced)
1421             {
1422               CORE_ADDR actual_pc = regcache_read_pc (regcache);
1423               gdb_byte buf[4];
1424
1425               fprintf_unfiltered (gdb_stdlog, "displaced: run %s: ",
1426                                   paddress (gdbarch, actual_pc));
1427               read_memory (actual_pc, buf, sizeof (buf));
1428               displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
1429             }
1430
1431           if (gdbarch_displaced_step_hw_singlestep (gdbarch,
1432                                                     displaced->step_closure))
1433             target_resume (ptid, 1, TARGET_SIGNAL_0);
1434           else
1435             target_resume (ptid, 0, TARGET_SIGNAL_0);
1436
1437           /* Done, we're stepping a thread.  */
1438           break;
1439         }
1440       else
1441         {
1442           int step;
1443           struct thread_info *tp = inferior_thread ();
1444
1445           /* The breakpoint we were sitting under has since been
1446              removed.  */
1447           tp->control.trap_expected = 0;
1448
1449           /* Go back to what we were trying to do.  */
1450           step = currently_stepping (tp);
1451
1452           if (debug_displaced)
1453             fprintf_unfiltered (gdb_stdlog, "breakpoint is gone %s: step(%d)\n",
1454                                 target_pid_to_str (tp->ptid), step);
1455
1456           target_resume (ptid, step, TARGET_SIGNAL_0);
1457           tp->suspend.stop_signal = TARGET_SIGNAL_0;
1458
1459           /* This request was discarded.  See if there's any other
1460              thread waiting for its turn.  */
1461         }
1462     }
1463 }
1464
1465 /* Update global variables holding ptids to hold NEW_PTID if they were
1466    holding OLD_PTID.  */
1467 static void
1468 infrun_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
1469 {
1470   struct displaced_step_request *it;
1471   struct displaced_step_inferior_state *displaced;
1472
1473   if (ptid_equal (inferior_ptid, old_ptid))
1474     inferior_ptid = new_ptid;
1475
1476   if (ptid_equal (singlestep_ptid, old_ptid))
1477     singlestep_ptid = new_ptid;
1478
1479   if (ptid_equal (deferred_step_ptid, old_ptid))
1480     deferred_step_ptid = new_ptid;
1481
1482   for (displaced = displaced_step_inferior_states;
1483        displaced;
1484        displaced = displaced->next)
1485     {
1486       if (ptid_equal (displaced->step_ptid, old_ptid))
1487         displaced->step_ptid = new_ptid;
1488
1489       for (it = displaced->step_request_queue; it; it = it->next)
1490         if (ptid_equal (it->ptid, old_ptid))
1491           it->ptid = new_ptid;
1492     }
1493 }
1494
1495 \f
1496 /* Resuming.  */
1497
1498 /* Things to clean up if we QUIT out of resume ().  */
1499 static void
1500 resume_cleanups (void *ignore)
1501 {
1502   normal_stop ();
1503 }
1504
1505 static const char schedlock_off[] = "off";
1506 static const char schedlock_on[] = "on";
1507 static const char schedlock_step[] = "step";
1508 static const char *scheduler_enums[] = {
1509   schedlock_off,
1510   schedlock_on,
1511   schedlock_step,
1512   NULL
1513 };
1514 static const char *scheduler_mode = schedlock_off;
1515 static void
1516 show_scheduler_mode (struct ui_file *file, int from_tty,
1517                      struct cmd_list_element *c, const char *value)
1518 {
1519   fprintf_filtered (file, _("\
1520 Mode for locking scheduler during execution is \"%s\".\n"),
1521                     value);
1522 }
1523
1524 static void
1525 set_schedlock_func (char *args, int from_tty, struct cmd_list_element *c)
1526 {
1527   if (!target_can_lock_scheduler)
1528     {
1529       scheduler_mode = schedlock_off;
1530       error (_("Target '%s' cannot support this command."), target_shortname);
1531     }
1532 }
1533
1534 /* True if execution commands resume all threads of all processes by
1535    default; otherwise, resume only threads of the current inferior
1536    process.  */
1537 int sched_multi = 0;
1538
1539 /* Try to setup for software single stepping over the specified location.
1540    Return 1 if target_resume() should use hardware single step.
1541
1542    GDBARCH the current gdbarch.
1543    PC the location to step over.  */
1544
1545 static int
1546 maybe_software_singlestep (struct gdbarch *gdbarch, CORE_ADDR pc)
1547 {
1548   int hw_step = 1;
1549
1550   if (execution_direction == EXEC_FORWARD
1551       && gdbarch_software_single_step_p (gdbarch)
1552       && gdbarch_software_single_step (gdbarch, get_current_frame ()))
1553     {
1554       hw_step = 0;
1555       /* Do not pull these breakpoints until after a `wait' in
1556          `wait_for_inferior' */
1557       singlestep_breakpoints_inserted_p = 1;
1558       singlestep_ptid = inferior_ptid;
1559       singlestep_pc = pc;
1560     }
1561   return hw_step;
1562 }
1563
1564 /* Resume the inferior, but allow a QUIT.  This is useful if the user
1565    wants to interrupt some lengthy single-stepping operation
1566    (for child processes, the SIGINT goes to the inferior, and so
1567    we get a SIGINT random_signal, but for remote debugging and perhaps
1568    other targets, that's not true).
1569
1570    STEP nonzero if we should step (zero to continue instead).
1571    SIG is the signal to give the inferior (zero for none).  */
1572 void
1573 resume (int step, enum target_signal sig)
1574 {
1575   int should_resume = 1;
1576   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
1577   struct regcache *regcache = get_current_regcache ();
1578   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1579   struct thread_info *tp = inferior_thread ();
1580   CORE_ADDR pc = regcache_read_pc (regcache);
1581   struct address_space *aspace = get_regcache_aspace (regcache);
1582
1583   QUIT;
1584
1585   if (current_inferior ()->waiting_for_vfork_done)
1586     {
1587       /* Don't try to single-step a vfork parent that is waiting for
1588          the child to get out of the shared memory region (by exec'ing
1589          or exiting).  This is particularly important on software
1590          single-step archs, as the child process would trip on the
1591          software single step breakpoint inserted for the parent
1592          process.  Since the parent will not actually execute any
1593          instruction until the child is out of the shared region (such
1594          are vfork's semantics), it is safe to simply continue it.
1595          Eventually, we'll see a TARGET_WAITKIND_VFORK_DONE event for
1596          the parent, and tell it to `keep_going', which automatically
1597          re-sets it stepping.  */
1598       if (debug_infrun)
1599         fprintf_unfiltered (gdb_stdlog,
1600                             "infrun: resume : clear step\n");
1601       step = 0;
1602     }
1603
1604   if (debug_infrun)
1605     fprintf_unfiltered (gdb_stdlog,
1606                         "infrun: resume (step=%d, signal=%d), "
1607                         "trap_expected=%d\n",
1608                         step, sig, tp->control.trap_expected);
1609
1610   /* Normally, by the time we reach `resume', the breakpoints are either
1611      removed or inserted, as appropriate.  The exception is if we're sitting
1612      at a permanent breakpoint; we need to step over it, but permanent
1613      breakpoints can't be removed.  So we have to test for it here.  */
1614   if (breakpoint_here_p (aspace, pc) == permanent_breakpoint_here)
1615     {
1616       if (gdbarch_skip_permanent_breakpoint_p (gdbarch))
1617         gdbarch_skip_permanent_breakpoint (gdbarch, regcache);
1618       else
1619         error (_("\
1620 The program is stopped at a permanent breakpoint, but GDB does not know\n\
1621 how to step past a permanent breakpoint on this architecture.  Try using\n\
1622 a command like `return' or `jump' to continue execution."));
1623     }
1624
1625   /* If enabled, step over breakpoints by executing a copy of the
1626      instruction at a different address.
1627
1628      We can't use displaced stepping when we have a signal to deliver;
1629      the comments for displaced_step_prepare explain why.  The
1630      comments in the handle_inferior event for dealing with 'random
1631      signals' explain what we do instead.
1632
1633      We can't use displaced stepping when we are waiting for vfork_done
1634      event, displaced stepping breaks the vfork child similarly as single
1635      step software breakpoint.  */
1636   if (use_displaced_stepping (gdbarch)
1637       && (tp->control.trap_expected
1638           || (step && gdbarch_software_single_step_p (gdbarch)))
1639       && sig == TARGET_SIGNAL_0
1640       && !current_inferior ()->waiting_for_vfork_done)
1641     {
1642       struct displaced_step_inferior_state *displaced;
1643
1644       if (!displaced_step_prepare (inferior_ptid))
1645         {
1646           /* Got placed in displaced stepping queue.  Will be resumed
1647              later when all the currently queued displaced stepping
1648              requests finish.  The thread is not executing at this point,
1649              and the call to set_executing will be made later.  But we
1650              need to call set_running here, since from frontend point of view,
1651              the thread is running.  */
1652           set_running (inferior_ptid, 1);
1653           discard_cleanups (old_cleanups);
1654           return;
1655         }
1656
1657       displaced = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
1658       step = gdbarch_displaced_step_hw_singlestep (gdbarch,
1659                                                    displaced->step_closure);
1660     }
1661
1662   /* Do we need to do it the hard way, w/temp breakpoints?  */
1663   else if (step)
1664     step = maybe_software_singlestep (gdbarch, pc);
1665
1666   if (should_resume)
1667     {
1668       ptid_t resume_ptid;
1669
1670       /* If STEP is set, it's a request to use hardware stepping
1671          facilities.  But in that case, we should never
1672          use singlestep breakpoint.  */
1673       gdb_assert (!(singlestep_breakpoints_inserted_p && step));
1674
1675       /* Decide the set of threads to ask the target to resume.  Start
1676          by assuming everything will be resumed, than narrow the set
1677          by applying increasingly restricting conditions.  */
1678
1679       /* By default, resume all threads of all processes.  */
1680       resume_ptid = RESUME_ALL;
1681
1682       /* Maybe resume only all threads of the current process.  */
1683       if (!sched_multi && target_supports_multi_process ())
1684         {
1685           resume_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
1686         }
1687
1688       /* Maybe resume a single thread after all.  */
1689       if (singlestep_breakpoints_inserted_p
1690           && stepping_past_singlestep_breakpoint)
1691         {
1692           /* The situation here is as follows.  In thread T1 we wanted to
1693              single-step.  Lacking hardware single-stepping we've
1694              set breakpoint at the PC of the next instruction -- call it
1695              P.  After resuming, we've hit that breakpoint in thread T2.
1696              Now we've removed original breakpoint, inserted breakpoint
1697              at P+1, and try to step to advance T2 past breakpoint.
1698              We need to step only T2, as if T1 is allowed to freely run,
1699              it can run past P, and if other threads are allowed to run,
1700              they can hit breakpoint at P+1, and nested hits of single-step
1701              breakpoints is not something we'd want -- that's complicated
1702              to support, and has no value.  */
1703           resume_ptid = inferior_ptid;
1704         }
1705       else if ((step || singlestep_breakpoints_inserted_p)
1706                && tp->control.trap_expected)
1707         {
1708           /* We're allowing a thread to run past a breakpoint it has
1709              hit, by single-stepping the thread with the breakpoint
1710              removed.  In which case, we need to single-step only this
1711              thread, and keep others stopped, as they can miss this
1712              breakpoint if allowed to run.
1713
1714              The current code actually removes all breakpoints when
1715              doing this, not just the one being stepped over, so if we
1716              let other threads run, we can actually miss any
1717              breakpoint, not just the one at PC.  */
1718           resume_ptid = inferior_ptid;
1719         }
1720       else if (non_stop)
1721         {
1722           /* With non-stop mode on, threads are always handled
1723              individually.  */
1724           resume_ptid = inferior_ptid;
1725         }
1726       else if ((scheduler_mode == schedlock_on)
1727                || (scheduler_mode == schedlock_step
1728                    && (step || singlestep_breakpoints_inserted_p)))
1729         {
1730           /* User-settable 'scheduler' mode requires solo thread resume. */
1731           resume_ptid = inferior_ptid;
1732         }
1733
1734       if (gdbarch_cannot_step_breakpoint (gdbarch))
1735         {
1736           /* Most targets can step a breakpoint instruction, thus
1737              executing it normally.  But if this one cannot, just
1738              continue and we will hit it anyway.  */
1739           if (step && breakpoint_inserted_here_p (aspace, pc))
1740             step = 0;
1741         }
1742
1743       if (debug_displaced
1744           && use_displaced_stepping (gdbarch)
1745           && tp->control.trap_expected)
1746         {
1747           struct regcache *resume_regcache = get_thread_regcache (resume_ptid);
1748           struct gdbarch *resume_gdbarch = get_regcache_arch (resume_regcache);
1749           CORE_ADDR actual_pc = regcache_read_pc (resume_regcache);
1750           gdb_byte buf[4];
1751
1752           fprintf_unfiltered (gdb_stdlog, "displaced: run %s: ",
1753                               paddress (resume_gdbarch, actual_pc));
1754           read_memory (actual_pc, buf, sizeof (buf));
1755           displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
1756         }
1757
1758       /* Install inferior's terminal modes.  */
1759       target_terminal_inferior ();
1760
1761       /* Avoid confusing the next resume, if the next stop/resume
1762          happens to apply to another thread.  */
1763       tp->suspend.stop_signal = TARGET_SIGNAL_0;
1764
1765       target_resume (resume_ptid, step, sig);
1766     }
1767
1768   discard_cleanups (old_cleanups);
1769 }
1770 \f
1771 /* Proceeding.  */
1772
1773 /* Clear out all variables saying what to do when inferior is continued.
1774    First do this, then set the ones you want, then call `proceed'.  */
1775
1776 static void
1777 clear_proceed_status_thread (struct thread_info *tp)
1778 {
1779   if (debug_infrun)
1780     fprintf_unfiltered (gdb_stdlog,
1781                         "infrun: clear_proceed_status_thread (%s)\n",
1782                         target_pid_to_str (tp->ptid));
1783
1784   tp->control.trap_expected = 0;
1785   tp->control.step_range_start = 0;
1786   tp->control.step_range_end = 0;
1787   tp->control.step_frame_id = null_frame_id;
1788   tp->control.step_stack_frame_id = null_frame_id;
1789   tp->control.step_over_calls = STEP_OVER_UNDEBUGGABLE;
1790   tp->stop_requested = 0;
1791
1792   tp->control.stop_step = 0;
1793
1794   tp->control.proceed_to_finish = 0;
1795
1796   /* Discard any remaining commands or status from previous stop.  */
1797   bpstat_clear (&tp->control.stop_bpstat);
1798 }
1799
1800 static int
1801 clear_proceed_status_callback (struct thread_info *tp, void *data)
1802 {
1803   if (is_exited (tp->ptid))
1804     return 0;
1805
1806   clear_proceed_status_thread (tp);
1807   return 0;
1808 }
1809
1810 void
1811 clear_proceed_status (void)
1812 {
1813   if (!non_stop)
1814     {
1815       /* In all-stop mode, delete the per-thread status of all
1816          threads, even if inferior_ptid is null_ptid, there may be
1817          threads on the list.  E.g., we may be launching a new
1818          process, while selecting the executable.  */
1819       iterate_over_threads (clear_proceed_status_callback, NULL);
1820     }
1821
1822   if (!ptid_equal (inferior_ptid, null_ptid))
1823     {
1824       struct inferior *inferior;
1825
1826       if (non_stop)
1827         {
1828           /* If in non-stop mode, only delete the per-thread status of
1829              the current thread.  */
1830           clear_proceed_status_thread (inferior_thread ());
1831         }
1832
1833       inferior = current_inferior ();
1834       inferior->control.stop_soon = NO_STOP_QUIETLY;
1835     }
1836
1837   stop_after_trap = 0;
1838
1839   observer_notify_about_to_proceed ();
1840
1841   if (stop_registers)
1842     {
1843       regcache_xfree (stop_registers);
1844       stop_registers = NULL;
1845     }
1846 }
1847
1848 /* Check the current thread against the thread that reported the most recent
1849    event.  If a step-over is required return TRUE and set the current thread
1850    to the old thread.  Otherwise return FALSE.
1851
1852    This should be suitable for any targets that support threads. */
1853
1854 static int
1855 prepare_to_proceed (int step)
1856 {
1857   ptid_t wait_ptid;
1858   struct target_waitstatus wait_status;
1859   int schedlock_enabled;
1860
1861   /* With non-stop mode on, threads are always handled individually.  */
1862   gdb_assert (! non_stop);
1863
1864   /* Get the last target status returned by target_wait().  */
1865   get_last_target_status (&wait_ptid, &wait_status);
1866
1867   /* Make sure we were stopped at a breakpoint.  */
1868   if (wait_status.kind != TARGET_WAITKIND_STOPPED
1869       || (wait_status.value.sig != TARGET_SIGNAL_TRAP
1870           && wait_status.value.sig != TARGET_SIGNAL_ILL
1871           && wait_status.value.sig != TARGET_SIGNAL_SEGV
1872           && wait_status.value.sig != TARGET_SIGNAL_EMT))
1873     {
1874       return 0;
1875     }
1876
1877   schedlock_enabled = (scheduler_mode == schedlock_on
1878                        || (scheduler_mode == schedlock_step
1879                            && step));
1880
1881   /* Don't switch over to WAIT_PTID if scheduler locking is on.  */
1882   if (schedlock_enabled)
1883     return 0;
1884
1885   /* Don't switch over if we're about to resume some other process
1886      other than WAIT_PTID's, and schedule-multiple is off.  */
1887   if (!sched_multi
1888       && ptid_get_pid (wait_ptid) != ptid_get_pid (inferior_ptid))
1889     return 0;
1890
1891   /* Switched over from WAIT_PID.  */
1892   if (!ptid_equal (wait_ptid, minus_one_ptid)
1893       && !ptid_equal (inferior_ptid, wait_ptid))
1894     {
1895       struct regcache *regcache = get_thread_regcache (wait_ptid);
1896
1897       if (breakpoint_here_p (get_regcache_aspace (regcache),
1898                              regcache_read_pc (regcache)))
1899         {
1900           /* If stepping, remember current thread to switch back to.  */
1901           if (step)
1902             deferred_step_ptid = inferior_ptid;
1903
1904           /* Switch back to WAIT_PID thread.  */
1905           switch_to_thread (wait_ptid);
1906
1907           /* We return 1 to indicate that there is a breakpoint here,
1908              so we need to step over it before continuing to avoid
1909              hitting it straight away. */
1910           return 1;
1911         }
1912     }
1913
1914   return 0;
1915 }
1916
1917 /* Basic routine for continuing the program in various fashions.
1918
1919    ADDR is the address to resume at, or -1 for resume where stopped.
1920    SIGGNAL is the signal to give it, or 0 for none,
1921    or -1 for act according to how it stopped.
1922    STEP is nonzero if should trap after one instruction.
1923    -1 means return after that and print nothing.
1924    You should probably set various step_... variables
1925    before calling here, if you are stepping.
1926
1927    You should call clear_proceed_status before calling proceed.  */
1928
1929 void
1930 proceed (CORE_ADDR addr, enum target_signal siggnal, int step)
1931 {
1932   struct regcache *regcache;
1933   struct gdbarch *gdbarch;
1934   struct thread_info *tp;
1935   CORE_ADDR pc;
1936   struct address_space *aspace;
1937   int oneproc = 0;
1938
1939   /* If we're stopped at a fork/vfork, follow the branch set by the
1940      "set follow-fork-mode" command; otherwise, we'll just proceed
1941      resuming the current thread.  */
1942   if (!follow_fork ())
1943     {
1944       /* The target for some reason decided not to resume.  */
1945       normal_stop ();
1946       return;
1947     }
1948
1949   regcache = get_current_regcache ();
1950   gdbarch = get_regcache_arch (regcache);
1951   aspace = get_regcache_aspace (regcache);
1952   pc = regcache_read_pc (regcache);
1953
1954   if (step > 0)
1955     step_start_function = find_pc_function (pc);
1956   if (step < 0)
1957     stop_after_trap = 1;
1958
1959   if (addr == (CORE_ADDR) -1)
1960     {
1961       if (pc == stop_pc && breakpoint_here_p (aspace, pc)
1962           && execution_direction != EXEC_REVERSE)
1963         /* There is a breakpoint at the address we will resume at,
1964            step one instruction before inserting breakpoints so that
1965            we do not stop right away (and report a second hit at this
1966            breakpoint).
1967
1968            Note, we don't do this in reverse, because we won't
1969            actually be executing the breakpoint insn anyway.
1970            We'll be (un-)executing the previous instruction.  */
1971
1972         oneproc = 1;
1973       else if (gdbarch_single_step_through_delay_p (gdbarch)
1974                && gdbarch_single_step_through_delay (gdbarch,
1975                                                      get_current_frame ()))
1976         /* We stepped onto an instruction that needs to be stepped
1977            again before re-inserting the breakpoint, do so.  */
1978         oneproc = 1;
1979     }
1980   else
1981     {
1982       regcache_write_pc (regcache, addr);
1983     }
1984
1985   if (debug_infrun)
1986     fprintf_unfiltered (gdb_stdlog,
1987                         "infrun: proceed (addr=%s, signal=%d, step=%d)\n",
1988                         paddress (gdbarch, addr), siggnal, step);
1989
1990   /* We're handling a live event, so make sure we're doing live
1991      debugging.  If we're looking at traceframes while the target is
1992      running, we're going to need to get back to that mode after
1993      handling the event.  */
1994   if (non_stop)
1995     {
1996       make_cleanup_restore_current_traceframe ();
1997       set_traceframe_number (-1);
1998     }
1999
2000   if (non_stop)
2001     /* In non-stop, each thread is handled individually.  The context
2002        must already be set to the right thread here.  */
2003     ;
2004   else
2005     {
2006       /* In a multi-threaded task we may select another thread and
2007          then continue or step.
2008
2009          But if the old thread was stopped at a breakpoint, it will
2010          immediately cause another breakpoint stop without any
2011          execution (i.e. it will report a breakpoint hit incorrectly).
2012          So we must step over it first.
2013
2014          prepare_to_proceed checks the current thread against the
2015          thread that reported the most recent event.  If a step-over
2016          is required it returns TRUE and sets the current thread to
2017          the old thread. */
2018       if (prepare_to_proceed (step))
2019         oneproc = 1;
2020     }
2021
2022   /* prepare_to_proceed may change the current thread.  */
2023   tp = inferior_thread ();
2024
2025   if (oneproc)
2026     {
2027       tp->control.trap_expected = 1;
2028       /* If displaced stepping is enabled, we can step over the
2029          breakpoint without hitting it, so leave all breakpoints
2030          inserted.  Otherwise we need to disable all breakpoints, step
2031          one instruction, and then re-add them when that step is
2032          finished.  */
2033       if (!use_displaced_stepping (gdbarch))
2034         remove_breakpoints ();
2035     }
2036
2037   /* We can insert breakpoints if we're not trying to step over one,
2038      or if we are stepping over one but we're using displaced stepping
2039      to do so.  */
2040   if (! tp->control.trap_expected || use_displaced_stepping (gdbarch))
2041     insert_breakpoints ();
2042
2043   if (!non_stop)
2044     {
2045       /* Pass the last stop signal to the thread we're resuming,
2046          irrespective of whether the current thread is the thread that
2047          got the last event or not.  This was historically GDB's
2048          behaviour before keeping a stop_signal per thread.  */
2049
2050       struct thread_info *last_thread;
2051       ptid_t last_ptid;
2052       struct target_waitstatus last_status;
2053
2054       get_last_target_status (&last_ptid, &last_status);
2055       if (!ptid_equal (inferior_ptid, last_ptid)
2056           && !ptid_equal (last_ptid, null_ptid)
2057           && !ptid_equal (last_ptid, minus_one_ptid))
2058         {
2059           last_thread = find_thread_ptid (last_ptid);
2060           if (last_thread)
2061             {
2062               tp->suspend.stop_signal = last_thread->suspend.stop_signal;
2063               last_thread->suspend.stop_signal = TARGET_SIGNAL_0;
2064             }
2065         }
2066     }
2067
2068   if (siggnal != TARGET_SIGNAL_DEFAULT)
2069     tp->suspend.stop_signal = siggnal;
2070   /* If this signal should not be seen by program,
2071      give it zero.  Used for debugging signals.  */
2072   else if (!signal_program[tp->suspend.stop_signal])
2073     tp->suspend.stop_signal = TARGET_SIGNAL_0;
2074
2075   annotate_starting ();
2076
2077   /* Make sure that output from GDB appears before output from the
2078      inferior.  */
2079   gdb_flush (gdb_stdout);
2080
2081   /* Refresh prev_pc value just prior to resuming.  This used to be
2082      done in stop_stepping, however, setting prev_pc there did not handle
2083      scenarios such as inferior function calls or returning from
2084      a function via the return command.  In those cases, the prev_pc
2085      value was not set properly for subsequent commands.  The prev_pc value 
2086      is used to initialize the starting line number in the ecs.  With an 
2087      invalid value, the gdb next command ends up stopping at the position
2088      represented by the next line table entry past our start position.
2089      On platforms that generate one line table entry per line, this
2090      is not a problem.  However, on the ia64, the compiler generates
2091      extraneous line table entries that do not increase the line number.
2092      When we issue the gdb next command on the ia64 after an inferior call
2093      or a return command, we often end up a few instructions forward, still 
2094      within the original line we started.
2095
2096      An attempt was made to refresh the prev_pc at the same time the
2097      execution_control_state is initialized (for instance, just before
2098      waiting for an inferior event).  But this approach did not work
2099      because of platforms that use ptrace, where the pc register cannot
2100      be read unless the inferior is stopped.  At that point, we are not
2101      guaranteed the inferior is stopped and so the regcache_read_pc() call
2102      can fail.  Setting the prev_pc value here ensures the value is updated
2103      correctly when the inferior is stopped.  */
2104   tp->prev_pc = regcache_read_pc (get_current_regcache ());
2105
2106   /* Fill in with reasonable starting values.  */
2107   init_thread_stepping_state (tp);
2108
2109   /* Reset to normal state.  */
2110   init_infwait_state ();
2111
2112   /* Resume inferior.  */
2113   resume (oneproc || step || bpstat_should_step (), tp->suspend.stop_signal);
2114
2115   /* Wait for it to stop (if not standalone)
2116      and in any case decode why it stopped, and act accordingly.  */
2117   /* Do this only if we are not using the event loop, or if the target
2118      does not support asynchronous execution. */
2119   if (!target_can_async_p ())
2120     {
2121       wait_for_inferior (0);
2122       normal_stop ();
2123     }
2124 }
2125 \f
2126
2127 /* Start remote-debugging of a machine over a serial link.  */
2128
2129 void
2130 start_remote (int from_tty)
2131 {
2132   struct inferior *inferior;
2133
2134   init_wait_for_inferior ();
2135   inferior = current_inferior ();
2136   inferior->control.stop_soon = STOP_QUIETLY_REMOTE;
2137
2138   /* Always go on waiting for the target, regardless of the mode. */
2139   /* FIXME: cagney/1999-09-23: At present it isn't possible to
2140      indicate to wait_for_inferior that a target should timeout if
2141      nothing is returned (instead of just blocking).  Because of this,
2142      targets expecting an immediate response need to, internally, set
2143      things up so that the target_wait() is forced to eventually
2144      timeout. */
2145   /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
2146      differentiate to its caller what the state of the target is after
2147      the initial open has been performed.  Here we're assuming that
2148      the target has stopped.  It should be possible to eventually have
2149      target_open() return to the caller an indication that the target
2150      is currently running and GDB state should be set to the same as
2151      for an async run. */
2152   wait_for_inferior (0);
2153
2154   /* Now that the inferior has stopped, do any bookkeeping like
2155      loading shared libraries.  We want to do this before normal_stop,
2156      so that the displayed frame is up to date.  */
2157   post_create_inferior (&current_target, from_tty);
2158
2159   normal_stop ();
2160 }
2161
2162 /* Initialize static vars when a new inferior begins.  */
2163
2164 void
2165 init_wait_for_inferior (void)
2166 {
2167   /* These are meaningless until the first time through wait_for_inferior.  */
2168
2169   breakpoint_init_inferior (inf_starting);
2170
2171   clear_proceed_status ();
2172
2173   stepping_past_singlestep_breakpoint = 0;
2174   deferred_step_ptid = null_ptid;
2175
2176   target_last_wait_ptid = minus_one_ptid;
2177
2178   previous_inferior_ptid = null_ptid;
2179   init_infwait_state ();
2180
2181   /* Discard any skipped inlined frames.  */
2182   clear_inline_frame_state (minus_one_ptid);
2183 }
2184
2185 \f
2186 /* This enum encodes possible reasons for doing a target_wait, so that
2187    wfi can call target_wait in one place.  (Ultimately the call will be
2188    moved out of the infinite loop entirely.) */
2189
2190 enum infwait_states
2191 {
2192   infwait_normal_state,
2193   infwait_thread_hop_state,
2194   infwait_step_watch_state,
2195   infwait_nonstep_watch_state
2196 };
2197
2198 /* The PTID we'll do a target_wait on.*/
2199 ptid_t waiton_ptid;
2200
2201 /* Current inferior wait state.  */
2202 enum infwait_states infwait_state;
2203
2204 /* Data to be passed around while handling an event.  This data is
2205    discarded between events.  */
2206 struct execution_control_state
2207 {
2208   ptid_t ptid;
2209   /* The thread that got the event, if this was a thread event; NULL
2210      otherwise.  */
2211   struct thread_info *event_thread;
2212
2213   struct target_waitstatus ws;
2214   int random_signal;
2215   CORE_ADDR stop_func_start;
2216   CORE_ADDR stop_func_end;
2217   char *stop_func_name;
2218   int new_thread_event;
2219   int wait_some_more;
2220 };
2221
2222 static void handle_inferior_event (struct execution_control_state *ecs);
2223
2224 static void handle_step_into_function (struct gdbarch *gdbarch,
2225                                        struct execution_control_state *ecs);
2226 static void handle_step_into_function_backward (struct gdbarch *gdbarch,
2227                                                 struct execution_control_state *ecs);
2228 static void insert_step_resume_breakpoint_at_frame (struct frame_info *step_frame);
2229 static void insert_step_resume_breakpoint_at_caller (struct frame_info *);
2230 static void insert_step_resume_breakpoint_at_sal (struct gdbarch *gdbarch,
2231                                                   struct symtab_and_line sr_sal,
2232                                                   struct frame_id sr_id);
2233 static void insert_longjmp_resume_breakpoint (struct gdbarch *, CORE_ADDR);
2234 static void check_exception_resume (struct execution_control_state *,
2235                                     struct frame_info *, struct symbol *);
2236
2237 static void stop_stepping (struct execution_control_state *ecs);
2238 static void prepare_to_wait (struct execution_control_state *ecs);
2239 static void keep_going (struct execution_control_state *ecs);
2240
2241 /* Callback for iterate over threads.  If the thread is stopped, but
2242    the user/frontend doesn't know about that yet, go through
2243    normal_stop, as if the thread had just stopped now.  ARG points at
2244    a ptid.  If PTID is MINUS_ONE_PTID, applies to all threads.  If
2245    ptid_is_pid(PTID) is true, applies to all threads of the process
2246    pointed at by PTID.  Otherwise, apply only to the thread pointed by
2247    PTID.  */
2248
2249 static int
2250 infrun_thread_stop_requested_callback (struct thread_info *info, void *arg)
2251 {
2252   ptid_t ptid = * (ptid_t *) arg;
2253
2254   if ((ptid_equal (info->ptid, ptid)
2255        || ptid_equal (minus_one_ptid, ptid)
2256        || (ptid_is_pid (ptid)
2257            && ptid_get_pid (ptid) == ptid_get_pid (info->ptid)))
2258       && is_running (info->ptid)
2259       && !is_executing (info->ptid))
2260     {
2261       struct cleanup *old_chain;
2262       struct execution_control_state ecss;
2263       struct execution_control_state *ecs = &ecss;
2264
2265       memset (ecs, 0, sizeof (*ecs));
2266
2267       old_chain = make_cleanup_restore_current_thread ();
2268
2269       switch_to_thread (info->ptid);
2270
2271       /* Go through handle_inferior_event/normal_stop, so we always
2272          have consistent output as if the stop event had been
2273          reported.  */
2274       ecs->ptid = info->ptid;
2275       ecs->event_thread = find_thread_ptid (info->ptid);
2276       ecs->ws.kind = TARGET_WAITKIND_STOPPED;
2277       ecs->ws.value.sig = TARGET_SIGNAL_0;
2278
2279       handle_inferior_event (ecs);
2280
2281       if (!ecs->wait_some_more)
2282         {
2283           struct thread_info *tp;
2284
2285           normal_stop ();
2286
2287           /* Finish off the continuations.  The continations
2288              themselves are responsible for realising the thread
2289              didn't finish what it was supposed to do.  */
2290           tp = inferior_thread ();
2291           do_all_intermediate_continuations_thread (tp);
2292           do_all_continuations_thread (tp);
2293         }
2294
2295       do_cleanups (old_chain);
2296     }
2297
2298   return 0;
2299 }
2300
2301 /* This function is attached as a "thread_stop_requested" observer.
2302    Cleanup local state that assumed the PTID was to be resumed, and
2303    report the stop to the frontend.  */
2304
2305 static void
2306 infrun_thread_stop_requested (ptid_t ptid)
2307 {
2308   struct displaced_step_inferior_state *displaced;
2309
2310   /* PTID was requested to stop.  Remove it from the displaced
2311      stepping queue, so we don't try to resume it automatically.  */
2312
2313   for (displaced = displaced_step_inferior_states;
2314        displaced;
2315        displaced = displaced->next)
2316     {
2317       struct displaced_step_request *it, **prev_next_p;
2318
2319       it = displaced->step_request_queue;
2320       prev_next_p = &displaced->step_request_queue;
2321       while (it)
2322         {
2323           if (ptid_match (it->ptid, ptid))
2324             {
2325               *prev_next_p = it->next;
2326               it->next = NULL;
2327               xfree (it);
2328             }
2329           else
2330             {
2331               prev_next_p = &it->next;
2332             }
2333
2334           it = *prev_next_p;
2335         }
2336     }
2337
2338   iterate_over_threads (infrun_thread_stop_requested_callback, &ptid);
2339 }
2340
2341 static void
2342 infrun_thread_thread_exit (struct thread_info *tp, int silent)
2343 {
2344   if (ptid_equal (target_last_wait_ptid, tp->ptid))
2345     nullify_last_target_wait_ptid ();
2346 }
2347
2348 /* Callback for iterate_over_threads.  */
2349
2350 static int
2351 delete_step_resume_breakpoint_callback (struct thread_info *info, void *data)
2352 {
2353   if (is_exited (info->ptid))
2354     return 0;
2355
2356   delete_step_resume_breakpoint (info);
2357   delete_exception_resume_breakpoint (info);
2358   return 0;
2359 }
2360
2361 /* In all-stop, delete the step resume breakpoint of any thread that
2362    had one.  In non-stop, delete the step resume breakpoint of the
2363    thread that just stopped.  */
2364
2365 static void
2366 delete_step_thread_step_resume_breakpoint (void)
2367 {
2368   if (!target_has_execution
2369       || ptid_equal (inferior_ptid, null_ptid))
2370     /* If the inferior has exited, we have already deleted the step
2371        resume breakpoints out of GDB's lists.  */
2372     return;
2373
2374   if (non_stop)
2375     {
2376       /* If in non-stop mode, only delete the step-resume or
2377          longjmp-resume breakpoint of the thread that just stopped
2378          stepping.  */
2379       struct thread_info *tp = inferior_thread ();
2380
2381       delete_step_resume_breakpoint (tp);
2382       delete_exception_resume_breakpoint (tp);
2383     }
2384   else
2385     /* In all-stop mode, delete all step-resume and longjmp-resume
2386        breakpoints of any thread that had them.  */
2387     iterate_over_threads (delete_step_resume_breakpoint_callback, NULL);
2388 }
2389
2390 /* A cleanup wrapper. */
2391
2392 static void
2393 delete_step_thread_step_resume_breakpoint_cleanup (void *arg)
2394 {
2395   delete_step_thread_step_resume_breakpoint ();
2396 }
2397
2398 /* Pretty print the results of target_wait, for debugging purposes.  */
2399
2400 static void
2401 print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid,
2402                            const struct target_waitstatus *ws)
2403 {
2404   char *status_string = target_waitstatus_to_string (ws);
2405   struct ui_file *tmp_stream = mem_fileopen ();
2406   char *text;
2407
2408   /* The text is split over several lines because it was getting too long.
2409      Call fprintf_unfiltered (gdb_stdlog) once so that the text is still
2410      output as a unit; we want only one timestamp printed if debug_timestamp
2411      is set.  */
2412
2413   fprintf_unfiltered (tmp_stream,
2414                       "infrun: target_wait (%d", PIDGET (waiton_ptid));
2415   if (PIDGET (waiton_ptid) != -1)
2416     fprintf_unfiltered (tmp_stream,
2417                         " [%s]", target_pid_to_str (waiton_ptid));
2418   fprintf_unfiltered (tmp_stream, ", status) =\n");
2419   fprintf_unfiltered (tmp_stream,
2420                       "infrun:   %d [%s],\n",
2421                       PIDGET (result_ptid), target_pid_to_str (result_ptid));
2422   fprintf_unfiltered (tmp_stream,
2423                       "infrun:   %s\n",
2424                       status_string);
2425
2426   text = ui_file_xstrdup (tmp_stream, NULL);
2427
2428   /* This uses %s in part to handle %'s in the text, but also to avoid
2429      a gcc error: the format attribute requires a string literal.  */
2430   fprintf_unfiltered (gdb_stdlog, "%s", text);
2431
2432   xfree (status_string);
2433   xfree (text);
2434   ui_file_delete (tmp_stream);
2435 }
2436
2437 /* Prepare and stabilize the inferior for detaching it.  E.g.,
2438    detaching while a thread is displaced stepping is a recipe for
2439    crashing it, as nothing would readjust the PC out of the scratch
2440    pad.  */
2441
2442 void
2443 prepare_for_detach (void)
2444 {
2445   struct inferior *inf = current_inferior ();
2446   ptid_t pid_ptid = pid_to_ptid (inf->pid);
2447   struct cleanup *old_chain_1;
2448   struct displaced_step_inferior_state *displaced;
2449
2450   displaced = get_displaced_stepping_state (inf->pid);
2451
2452   /* Is any thread of this process displaced stepping?  If not,
2453      there's nothing else to do.  */
2454   if (displaced == NULL || ptid_equal (displaced->step_ptid, null_ptid))
2455     return;
2456
2457   if (debug_infrun)
2458     fprintf_unfiltered (gdb_stdlog,
2459                         "displaced-stepping in-process while detaching");
2460
2461   old_chain_1 = make_cleanup_restore_integer (&inf->detaching);
2462   inf->detaching = 1;
2463
2464   while (!ptid_equal (displaced->step_ptid, null_ptid))
2465     {
2466       struct cleanup *old_chain_2;
2467       struct execution_control_state ecss;
2468       struct execution_control_state *ecs;
2469
2470       ecs = &ecss;
2471       memset (ecs, 0, sizeof (*ecs));
2472
2473       overlay_cache_invalid = 1;
2474
2475       /* We have to invalidate the registers BEFORE calling
2476          target_wait because they can be loaded from the target while
2477          in target_wait.  This makes remote debugging a bit more
2478          efficient for those targets that provide critical registers
2479          as part of their normal status mechanism. */
2480
2481       registers_changed ();
2482
2483       if (deprecated_target_wait_hook)
2484         ecs->ptid = deprecated_target_wait_hook (pid_ptid, &ecs->ws, 0);
2485       else
2486         ecs->ptid = target_wait (pid_ptid, &ecs->ws, 0);
2487
2488       if (debug_infrun)
2489         print_target_wait_results (pid_ptid, ecs->ptid, &ecs->ws);
2490
2491       /* If an error happens while handling the event, propagate GDB's
2492          knowledge of the executing state to the frontend/user running
2493          state.  */
2494       old_chain_2 = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
2495
2496       /* In non-stop mode, each thread is handled individually.
2497          Switch early, so the global state is set correctly for this
2498          thread.  */
2499       if (non_stop
2500           && ecs->ws.kind != TARGET_WAITKIND_EXITED
2501           && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
2502         context_switch (ecs->ptid);
2503
2504       /* Now figure out what to do with the result of the result.  */
2505       handle_inferior_event (ecs);
2506
2507       /* No error, don't finish the state yet.  */
2508       discard_cleanups (old_chain_2);
2509
2510       /* Breakpoints and watchpoints are not installed on the target
2511          at this point, and signals are passed directly to the
2512          inferior, so this must mean the process is gone.  */
2513       if (!ecs->wait_some_more)
2514         {
2515           discard_cleanups (old_chain_1);
2516           error (_("Program exited while detaching"));
2517         }
2518     }
2519
2520   discard_cleanups (old_chain_1);
2521 }
2522
2523 /* Wait for control to return from inferior to debugger.
2524
2525    If TREAT_EXEC_AS_SIGTRAP is non-zero, then handle EXEC signals
2526    as if they were SIGTRAP signals.  This can be useful during
2527    the startup sequence on some targets such as HP/UX, where
2528    we receive an EXEC event instead of the expected SIGTRAP.
2529
2530    If inferior gets a signal, we may decide to start it up again
2531    instead of returning.  That is why there is a loop in this function.
2532    When this function actually returns it means the inferior
2533    should be left stopped and GDB should read more commands.  */
2534
2535 void
2536 wait_for_inferior (int treat_exec_as_sigtrap)
2537 {
2538   struct cleanup *old_cleanups;
2539   struct execution_control_state ecss;
2540   struct execution_control_state *ecs;
2541
2542   if (debug_infrun)
2543     fprintf_unfiltered
2544       (gdb_stdlog, "infrun: wait_for_inferior (treat_exec_as_sigtrap=%d)\n",
2545        treat_exec_as_sigtrap);
2546
2547   old_cleanups =
2548     make_cleanup (delete_step_thread_step_resume_breakpoint_cleanup, NULL);
2549
2550   ecs = &ecss;
2551   memset (ecs, 0, sizeof (*ecs));
2552
2553   /* We'll update this if & when we switch to a new thread.  */
2554   previous_inferior_ptid = inferior_ptid;
2555
2556   while (1)
2557     {
2558       struct cleanup *old_chain;
2559
2560       /* We have to invalidate the registers BEFORE calling target_wait
2561          because they can be loaded from the target while in target_wait.
2562          This makes remote debugging a bit more efficient for those
2563          targets that provide critical registers as part of their normal
2564          status mechanism. */
2565
2566       overlay_cache_invalid = 1;
2567       registers_changed ();
2568
2569       if (deprecated_target_wait_hook)
2570         ecs->ptid = deprecated_target_wait_hook (waiton_ptid, &ecs->ws, 0);
2571       else
2572         ecs->ptid = target_wait (waiton_ptid, &ecs->ws, 0);
2573
2574       if (debug_infrun)
2575         print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
2576
2577       if (treat_exec_as_sigtrap && ecs->ws.kind == TARGET_WAITKIND_EXECD)
2578         {
2579           xfree (ecs->ws.value.execd_pathname);
2580           ecs->ws.kind = TARGET_WAITKIND_STOPPED;
2581           ecs->ws.value.sig = TARGET_SIGNAL_TRAP;
2582         }
2583
2584       /* If an error happens while handling the event, propagate GDB's
2585          knowledge of the executing state to the frontend/user running
2586          state.  */
2587       old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
2588
2589       if (ecs->ws.kind == TARGET_WAITKIND_SYSCALL_ENTRY
2590           || ecs->ws.kind == TARGET_WAITKIND_SYSCALL_RETURN)
2591         ecs->ws.value.syscall_number = UNKNOWN_SYSCALL;
2592
2593       /* Now figure out what to do with the result of the result.  */
2594       handle_inferior_event (ecs);
2595
2596       /* No error, don't finish the state yet.  */
2597       discard_cleanups (old_chain);
2598
2599       if (!ecs->wait_some_more)
2600         break;
2601     }
2602
2603   do_cleanups (old_cleanups);
2604 }
2605
2606 /* Asynchronous version of wait_for_inferior. It is called by the
2607    event loop whenever a change of state is detected on the file
2608    descriptor corresponding to the target. It can be called more than
2609    once to complete a single execution command. In such cases we need
2610    to keep the state in a global variable ECSS. If it is the last time
2611    that this function is called for a single execution command, then
2612    report to the user that the inferior has stopped, and do the
2613    necessary cleanups. */
2614
2615 void
2616 fetch_inferior_event (void *client_data)
2617 {
2618   struct execution_control_state ecss;
2619   struct execution_control_state *ecs = &ecss;
2620   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
2621   struct cleanup *ts_old_chain;
2622   int was_sync = sync_execution;
2623
2624   memset (ecs, 0, sizeof (*ecs));
2625
2626   /* We'll update this if & when we switch to a new thread.  */
2627   previous_inferior_ptid = inferior_ptid;
2628
2629   if (non_stop)
2630     /* In non-stop mode, the user/frontend should not notice a thread
2631        switch due to internal events.  Make sure we reverse to the
2632        user selected thread and frame after handling the event and
2633        running any breakpoint commands.  */
2634     make_cleanup_restore_current_thread ();
2635
2636   /* We have to invalidate the registers BEFORE calling target_wait
2637      because they can be loaded from the target while in target_wait.
2638      This makes remote debugging a bit more efficient for those
2639      targets that provide critical registers as part of their normal
2640      status mechanism. */
2641
2642   overlay_cache_invalid = 1;
2643   registers_changed ();
2644
2645   if (deprecated_target_wait_hook)
2646     ecs->ptid =
2647       deprecated_target_wait_hook (waiton_ptid, &ecs->ws, TARGET_WNOHANG);
2648   else
2649     ecs->ptid = target_wait (waiton_ptid, &ecs->ws, TARGET_WNOHANG);
2650
2651   if (debug_infrun)
2652     print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
2653
2654   if (non_stop
2655       && ecs->ws.kind != TARGET_WAITKIND_IGNORE
2656       && ecs->ws.kind != TARGET_WAITKIND_EXITED
2657       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
2658     /* In non-stop mode, each thread is handled individually.  Switch
2659        early, so the global state is set correctly for this
2660        thread.  */
2661     context_switch (ecs->ptid);
2662
2663   /* If an error happens while handling the event, propagate GDB's
2664      knowledge of the executing state to the frontend/user running
2665      state.  */
2666   if (!non_stop)
2667     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
2668   else
2669     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &ecs->ptid);
2670
2671   /* Now figure out what to do with the result of the result.  */
2672   handle_inferior_event (ecs);
2673
2674   if (!ecs->wait_some_more)
2675     {
2676       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
2677
2678       delete_step_thread_step_resume_breakpoint ();
2679
2680       /* We may not find an inferior if this was a process exit.  */
2681       if (inf == NULL || inf->control.stop_soon == NO_STOP_QUIETLY)
2682         normal_stop ();
2683
2684       if (target_has_execution
2685           && ecs->ws.kind != TARGET_WAITKIND_EXITED
2686           && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
2687           && ecs->event_thread->step_multi
2688           && ecs->event_thread->control.stop_step)
2689         inferior_event_handler (INF_EXEC_CONTINUE, NULL);
2690       else
2691         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
2692     }
2693
2694   /* No error, don't finish the thread states yet.  */
2695   discard_cleanups (ts_old_chain);
2696
2697   /* Revert thread and frame.  */
2698   do_cleanups (old_chain);
2699
2700   /* If the inferior was in sync execution mode, and now isn't,
2701      restore the prompt.  */
2702   if (was_sync && !sync_execution)
2703     display_gdb_prompt (0);
2704 }
2705
2706 /* Record the frame and location we're currently stepping through.  */
2707 void
2708 set_step_info (struct frame_info *frame, struct symtab_and_line sal)
2709 {
2710   struct thread_info *tp = inferior_thread ();
2711
2712   tp->control.step_frame_id = get_frame_id (frame);
2713   tp->control.step_stack_frame_id = get_stack_frame_id (frame);
2714
2715   tp->current_symtab = sal.symtab;
2716   tp->current_line = sal.line;
2717 }
2718
2719 /* Clear context switchable stepping state.  */
2720
2721 void
2722 init_thread_stepping_state (struct thread_info *tss)
2723 {
2724   tss->stepping_over_breakpoint = 0;
2725   tss->step_after_step_resume_breakpoint = 0;
2726   tss->stepping_through_solib_after_catch = 0;
2727   tss->stepping_through_solib_catchpoints = NULL;
2728 }
2729
2730 /* Return the cached copy of the last pid/waitstatus returned by
2731    target_wait()/deprecated_target_wait_hook().  The data is actually
2732    cached by handle_inferior_event(), which gets called immediately
2733    after target_wait()/deprecated_target_wait_hook().  */
2734
2735 void
2736 get_last_target_status (ptid_t *ptidp, struct target_waitstatus *status)
2737 {
2738   *ptidp = target_last_wait_ptid;
2739   *status = target_last_waitstatus;
2740 }
2741
2742 void
2743 nullify_last_target_wait_ptid (void)
2744 {
2745   target_last_wait_ptid = minus_one_ptid;
2746 }
2747
2748 /* Switch thread contexts.  */
2749
2750 static void
2751 context_switch (ptid_t ptid)
2752 {
2753   if (debug_infrun)
2754     {
2755       fprintf_unfiltered (gdb_stdlog, "infrun: Switching context from %s ",
2756                           target_pid_to_str (inferior_ptid));
2757       fprintf_unfiltered (gdb_stdlog, "to %s\n",
2758                           target_pid_to_str (ptid));
2759     }
2760
2761   switch_to_thread (ptid);
2762 }
2763
2764 static void
2765 adjust_pc_after_break (struct execution_control_state *ecs)
2766 {
2767   struct regcache *regcache;
2768   struct gdbarch *gdbarch;
2769   struct address_space *aspace;
2770   CORE_ADDR breakpoint_pc;
2771
2772   /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP.  If
2773      we aren't, just return.
2774
2775      We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
2776      affected by gdbarch_decr_pc_after_break.  Other waitkinds which are
2777      implemented by software breakpoints should be handled through the normal
2778      breakpoint layer.
2779
2780      NOTE drow/2004-01-31: On some targets, breakpoints may generate
2781      different signals (SIGILL or SIGEMT for instance), but it is less
2782      clear where the PC is pointing afterwards.  It may not match
2783      gdbarch_decr_pc_after_break.  I don't know any specific target that
2784      generates these signals at breakpoints (the code has been in GDB since at
2785      least 1992) so I can not guess how to handle them here.
2786
2787      In earlier versions of GDB, a target with 
2788      gdbarch_have_nonsteppable_watchpoint would have the PC after hitting a
2789      watchpoint affected by gdbarch_decr_pc_after_break.  I haven't found any
2790      target with both of these set in GDB history, and it seems unlikely to be
2791      correct, so gdbarch_have_nonsteppable_watchpoint is not checked here.  */
2792
2793   if (ecs->ws.kind != TARGET_WAITKIND_STOPPED)
2794     return;
2795
2796   if (ecs->ws.value.sig != TARGET_SIGNAL_TRAP)
2797     return;
2798
2799   /* In reverse execution, when a breakpoint is hit, the instruction
2800      under it has already been de-executed.  The reported PC always
2801      points at the breakpoint address, so adjusting it further would
2802      be wrong.  E.g., consider this case on a decr_pc_after_break == 1
2803      architecture:
2804
2805        B1         0x08000000 :   INSN1
2806        B2         0x08000001 :   INSN2
2807                   0x08000002 :   INSN3
2808             PC -> 0x08000003 :   INSN4
2809
2810      Say you're stopped at 0x08000003 as above.  Reverse continuing
2811      from that point should hit B2 as below.  Reading the PC when the
2812      SIGTRAP is reported should read 0x08000001 and INSN2 should have
2813      been de-executed already.
2814
2815        B1         0x08000000 :   INSN1
2816        B2   PC -> 0x08000001 :   INSN2
2817                   0x08000002 :   INSN3
2818                   0x08000003 :   INSN4
2819
2820      We can't apply the same logic as for forward execution, because
2821      we would wrongly adjust the PC to 0x08000000, since there's a
2822      breakpoint at PC - 1.  We'd then report a hit on B1, although
2823      INSN1 hadn't been de-executed yet.  Doing nothing is the correct
2824      behaviour.  */
2825   if (execution_direction == EXEC_REVERSE)
2826     return;
2827
2828   /* If this target does not decrement the PC after breakpoints, then
2829      we have nothing to do.  */
2830   regcache = get_thread_regcache (ecs->ptid);
2831   gdbarch = get_regcache_arch (regcache);
2832   if (gdbarch_decr_pc_after_break (gdbarch) == 0)
2833     return;
2834
2835   aspace = get_regcache_aspace (regcache);
2836
2837   /* Find the location where (if we've hit a breakpoint) the
2838      breakpoint would be.  */
2839   breakpoint_pc = regcache_read_pc (regcache)
2840                   - gdbarch_decr_pc_after_break (gdbarch);
2841
2842   /* Check whether there actually is a software breakpoint inserted at
2843      that location.
2844
2845      If in non-stop mode, a race condition is possible where we've
2846      removed a breakpoint, but stop events for that breakpoint were
2847      already queued and arrive later.  To suppress those spurious
2848      SIGTRAPs, we keep a list of such breakpoint locations for a bit,
2849      and retire them after a number of stop events are reported.  */
2850   if (software_breakpoint_inserted_here_p (aspace, breakpoint_pc)
2851       || (non_stop && moribund_breakpoint_here_p (aspace, breakpoint_pc)))
2852     {
2853       struct cleanup *old_cleanups = NULL;
2854
2855       if (RECORD_IS_USED)
2856         old_cleanups = record_gdb_operation_disable_set ();
2857
2858       /* When using hardware single-step, a SIGTRAP is reported for both
2859          a completed single-step and a software breakpoint.  Need to
2860          differentiate between the two, as the latter needs adjusting
2861          but the former does not.
2862
2863          The SIGTRAP can be due to a completed hardware single-step only if 
2864           - we didn't insert software single-step breakpoints
2865           - the thread to be examined is still the current thread
2866           - this thread is currently being stepped
2867
2868          If any of these events did not occur, we must have stopped due
2869          to hitting a software breakpoint, and have to back up to the
2870          breakpoint address.
2871
2872          As a special case, we could have hardware single-stepped a
2873          software breakpoint.  In this case (prev_pc == breakpoint_pc),
2874          we also need to back up to the breakpoint address.  */
2875
2876       if (singlestep_breakpoints_inserted_p
2877           || !ptid_equal (ecs->ptid, inferior_ptid)
2878           || !currently_stepping (ecs->event_thread)
2879           || ecs->event_thread->prev_pc == breakpoint_pc)
2880         regcache_write_pc (regcache, breakpoint_pc);
2881
2882       if (RECORD_IS_USED)
2883         do_cleanups (old_cleanups);
2884     }
2885 }
2886
2887 void
2888 init_infwait_state (void)
2889 {
2890   waiton_ptid = pid_to_ptid (-1);
2891   infwait_state = infwait_normal_state;
2892 }
2893
2894 void
2895 error_is_running (void)
2896 {
2897   error (_("\
2898 Cannot execute this command while the selected thread is running."));
2899 }
2900
2901 void
2902 ensure_not_running (void)
2903 {
2904   if (is_running (inferior_ptid))
2905     error_is_running ();
2906 }
2907
2908 static int
2909 stepped_in_from (struct frame_info *frame, struct frame_id step_frame_id)
2910 {
2911   for (frame = get_prev_frame (frame);
2912        frame != NULL;
2913        frame = get_prev_frame (frame))
2914     {
2915       if (frame_id_eq (get_frame_id (frame), step_frame_id))
2916         return 1;
2917       if (get_frame_type (frame) != INLINE_FRAME)
2918         break;
2919     }
2920
2921   return 0;
2922 }
2923
2924 /* Auxiliary function that handles syscall entry/return events.
2925    It returns 1 if the inferior should keep going (and GDB
2926    should ignore the event), or 0 if the event deserves to be
2927    processed.  */
2928
2929 static int
2930 handle_syscall_event (struct execution_control_state *ecs)
2931 {
2932   struct regcache *regcache;
2933   struct gdbarch *gdbarch;
2934   int syscall_number;
2935
2936   if (!ptid_equal (ecs->ptid, inferior_ptid))
2937     context_switch (ecs->ptid);
2938
2939   regcache = get_thread_regcache (ecs->ptid);
2940   gdbarch = get_regcache_arch (regcache);
2941   syscall_number = gdbarch_get_syscall_number (gdbarch, ecs->ptid);
2942   stop_pc = regcache_read_pc (regcache);
2943
2944   target_last_waitstatus.value.syscall_number = syscall_number;
2945
2946   if (catch_syscall_enabled () > 0
2947       && catching_syscall_number (syscall_number) > 0)
2948     {
2949       if (debug_infrun)
2950         fprintf_unfiltered (gdb_stdlog, "infrun: syscall number = '%d'\n",
2951                             syscall_number);
2952
2953       ecs->event_thread->control.stop_bpstat
2954         = bpstat_stop_status (get_regcache_aspace (regcache),
2955                               stop_pc, ecs->ptid);
2956       ecs->random_signal
2957         = !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat);
2958
2959       if (!ecs->random_signal)
2960         {
2961           /* Catchpoint hit.  */
2962           ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_TRAP;
2963           return 0;
2964         }
2965     }
2966
2967   /* If no catchpoint triggered for this, then keep going.  */
2968   ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
2969   keep_going (ecs);
2970   return 1;
2971 }
2972
2973 /* Given an execution control state that has been freshly filled in
2974    by an event from the inferior, figure out what it means and take
2975    appropriate action.  */
2976
2977 static void
2978 handle_inferior_event (struct execution_control_state *ecs)
2979 {
2980   struct frame_info *frame;
2981   struct gdbarch *gdbarch;
2982   int sw_single_step_trap_p = 0;
2983   int stopped_by_watchpoint;
2984   int stepped_after_stopped_by_watchpoint = 0;
2985   struct symtab_and_line stop_pc_sal;
2986   enum stop_kind stop_soon;
2987
2988   if (ecs->ws.kind == TARGET_WAITKIND_IGNORE)
2989     {
2990       /* We had an event in the inferior, but we are not interested in
2991          handling it at this level.  The lower layers have already
2992          done what needs to be done, if anything.
2993
2994          One of the possible circumstances for this is when the
2995          inferior produces output for the console.  The inferior has
2996          not stopped, and we are ignoring the event.  Another possible
2997          circumstance is any event which the lower level knows will be
2998          reported multiple times without an intervening resume.  */
2999       if (debug_infrun)
3000         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_IGNORE\n");
3001       prepare_to_wait (ecs);
3002       return;
3003     }
3004
3005   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
3006       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
3007     {
3008       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
3009
3010       gdb_assert (inf);
3011       stop_soon = inf->control.stop_soon;
3012     }
3013   else
3014     stop_soon = NO_STOP_QUIETLY;
3015
3016   /* Cache the last pid/waitstatus. */
3017   target_last_wait_ptid = ecs->ptid;
3018   target_last_waitstatus = ecs->ws;
3019
3020   /* Always clear state belonging to the previous time we stopped.  */
3021   stop_stack_dummy = STOP_NONE;
3022
3023   /* If it's a new process, add it to the thread database */
3024
3025   ecs->new_thread_event = (!ptid_equal (ecs->ptid, inferior_ptid)
3026                            && !ptid_equal (ecs->ptid, minus_one_ptid)
3027                            && !in_thread_list (ecs->ptid));
3028
3029   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
3030       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED && ecs->new_thread_event)
3031     add_thread (ecs->ptid);
3032
3033   ecs->event_thread = find_thread_ptid (ecs->ptid);
3034
3035   /* Dependent on valid ECS->EVENT_THREAD.  */
3036   adjust_pc_after_break (ecs);
3037
3038   /* Dependent on the current PC value modified by adjust_pc_after_break.  */
3039   reinit_frame_cache ();
3040
3041   breakpoint_retire_moribund ();
3042
3043   /* First, distinguish signals caused by the debugger from signals
3044      that have to do with the program's own actions.  Note that
3045      breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
3046      on the operating system version.  Here we detect when a SIGILL or
3047      SIGEMT is really a breakpoint and change it to SIGTRAP.  We do
3048      something similar for SIGSEGV, since a SIGSEGV will be generated
3049      when we're trying to execute a breakpoint instruction on a
3050      non-executable stack.  This happens for call dummy breakpoints
3051      for architectures like SPARC that place call dummies on the
3052      stack.  */
3053   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED
3054       && (ecs->ws.value.sig == TARGET_SIGNAL_ILL
3055           || ecs->ws.value.sig == TARGET_SIGNAL_SEGV
3056           || ecs->ws.value.sig == TARGET_SIGNAL_EMT))
3057     {
3058       struct regcache *regcache = get_thread_regcache (ecs->ptid);
3059
3060       if (breakpoint_inserted_here_p (get_regcache_aspace (regcache),
3061                                       regcache_read_pc (regcache)))
3062         {
3063           if (debug_infrun)
3064             fprintf_unfiltered (gdb_stdlog,
3065                                 "infrun: Treating signal as SIGTRAP\n");
3066           ecs->ws.value.sig = TARGET_SIGNAL_TRAP;
3067         }
3068     }
3069
3070   /* Mark the non-executing threads accordingly.  In all-stop, all
3071      threads of all processes are stopped when we get any event
3072      reported.  In non-stop mode, only the event thread stops.  If
3073      we're handling a process exit in non-stop mode, there's nothing
3074      to do, as threads of the dead process are gone, and threads of
3075      any other process were left running.  */
3076   if (!non_stop)
3077     set_executing (minus_one_ptid, 0);
3078   else if (ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
3079            && ecs->ws.kind != TARGET_WAITKIND_EXITED)
3080     set_executing (inferior_ptid, 0);
3081
3082   switch (infwait_state)
3083     {
3084     case infwait_thread_hop_state:
3085       if (debug_infrun)
3086         fprintf_unfiltered (gdb_stdlog, "infrun: infwait_thread_hop_state\n");
3087       break;
3088
3089     case infwait_normal_state:
3090       if (debug_infrun)
3091         fprintf_unfiltered (gdb_stdlog, "infrun: infwait_normal_state\n");
3092       break;
3093
3094     case infwait_step_watch_state:
3095       if (debug_infrun)
3096         fprintf_unfiltered (gdb_stdlog,
3097                             "infrun: infwait_step_watch_state\n");
3098
3099       stepped_after_stopped_by_watchpoint = 1;
3100       break;
3101
3102     case infwait_nonstep_watch_state:
3103       if (debug_infrun)
3104         fprintf_unfiltered (gdb_stdlog,
3105                             "infrun: infwait_nonstep_watch_state\n");
3106       insert_breakpoints ();
3107
3108       /* FIXME-maybe: is this cleaner than setting a flag?  Does it
3109          handle things like signals arriving and other things happening
3110          in combination correctly?  */
3111       stepped_after_stopped_by_watchpoint = 1;
3112       break;
3113
3114     default:
3115       internal_error (__FILE__, __LINE__, _("bad switch"));
3116     }
3117
3118   infwait_state = infwait_normal_state;
3119   waiton_ptid = pid_to_ptid (-1);
3120
3121   switch (ecs->ws.kind)
3122     {
3123     case TARGET_WAITKIND_LOADED:
3124       if (debug_infrun)
3125         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_LOADED\n");
3126       /* Ignore gracefully during startup of the inferior, as it might
3127          be the shell which has just loaded some objects, otherwise
3128          add the symbols for the newly loaded objects.  Also ignore at
3129          the beginning of an attach or remote session; we will query
3130          the full list of libraries once the connection is
3131          established.  */
3132       if (stop_soon == NO_STOP_QUIETLY)
3133         {
3134           /* Check for any newly added shared libraries if we're
3135              supposed to be adding them automatically.  Switch
3136              terminal for any messages produced by
3137              breakpoint_re_set.  */
3138           target_terminal_ours_for_output ();
3139           /* NOTE: cagney/2003-11-25: Make certain that the target
3140              stack's section table is kept up-to-date.  Architectures,
3141              (e.g., PPC64), use the section table to perform
3142              operations such as address => section name and hence
3143              require the table to contain all sections (including
3144              those found in shared libraries).  */
3145 #ifdef SOLIB_ADD
3146           SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
3147 #else
3148           solib_add (NULL, 0, &current_target, auto_solib_add);
3149 #endif
3150           target_terminal_inferior ();
3151
3152           /* If requested, stop when the dynamic linker notifies
3153              gdb of events.  This allows the user to get control
3154              and place breakpoints in initializer routines for
3155              dynamically loaded objects (among other things).  */
3156           if (stop_on_solib_events)
3157             {
3158               /* Make sure we print "Stopped due to solib-event" in
3159                  normal_stop.  */
3160               stop_print_frame = 1;
3161
3162               stop_stepping (ecs);
3163               return;
3164             }
3165
3166           /* NOTE drow/2007-05-11: This might be a good place to check
3167              for "catch load".  */
3168         }
3169
3170       /* If we are skipping through a shell, or through shared library
3171          loading that we aren't interested in, resume the program.  If
3172          we're running the program normally, also resume.  But stop if
3173          we're attaching or setting up a remote connection.  */
3174       if (stop_soon == STOP_QUIETLY || stop_soon == NO_STOP_QUIETLY)
3175         {
3176           /* Loading of shared libraries might have changed breakpoint
3177              addresses.  Make sure new breakpoints are inserted.  */
3178           if (stop_soon == NO_STOP_QUIETLY
3179               && !breakpoints_always_inserted_mode ())
3180             insert_breakpoints ();
3181           resume (0, TARGET_SIGNAL_0);
3182           prepare_to_wait (ecs);
3183           return;
3184         }
3185
3186       break;
3187
3188     case TARGET_WAITKIND_SPURIOUS:
3189       if (debug_infrun)
3190         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SPURIOUS\n");
3191       resume (0, TARGET_SIGNAL_0);
3192       prepare_to_wait (ecs);
3193       return;
3194
3195     case TARGET_WAITKIND_EXITED:
3196       if (debug_infrun)
3197         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXITED\n");
3198       inferior_ptid = ecs->ptid;
3199       set_current_inferior (find_inferior_pid (ptid_get_pid (ecs->ptid)));
3200       set_current_program_space (current_inferior ()->pspace);
3201       handle_vfork_child_exec_or_exit (0);
3202       target_terminal_ours ();  /* Must do this before mourn anyway */
3203       print_exited_reason (ecs->ws.value.integer);
3204
3205       /* Record the exit code in the convenience variable $_exitcode, so
3206          that the user can inspect this again later.  */
3207       set_internalvar_integer (lookup_internalvar ("_exitcode"),
3208                                (LONGEST) ecs->ws.value.integer);
3209       gdb_flush (gdb_stdout);
3210       target_mourn_inferior ();
3211       singlestep_breakpoints_inserted_p = 0;
3212       cancel_single_step_breakpoints ();
3213       stop_print_frame = 0;
3214       stop_stepping (ecs);
3215       return;
3216
3217     case TARGET_WAITKIND_SIGNALLED:
3218       if (debug_infrun)
3219         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SIGNALLED\n");
3220       inferior_ptid = ecs->ptid;
3221       set_current_inferior (find_inferior_pid (ptid_get_pid (ecs->ptid)));
3222       set_current_program_space (current_inferior ()->pspace);
3223       handle_vfork_child_exec_or_exit (0);
3224       stop_print_frame = 0;
3225       target_terminal_ours ();  /* Must do this before mourn anyway */
3226
3227       /* Note: By definition of TARGET_WAITKIND_SIGNALLED, we shouldn't
3228          reach here unless the inferior is dead.  However, for years
3229          target_kill() was called here, which hints that fatal signals aren't
3230          really fatal on some systems.  If that's true, then some changes
3231          may be needed. */
3232       target_mourn_inferior ();
3233
3234       print_signal_exited_reason (ecs->ws.value.sig);
3235       singlestep_breakpoints_inserted_p = 0;
3236       cancel_single_step_breakpoints ();
3237       stop_stepping (ecs);
3238       return;
3239
3240       /* The following are the only cases in which we keep going;
3241          the above cases end in a continue or goto. */
3242     case TARGET_WAITKIND_FORKED:
3243     case TARGET_WAITKIND_VFORKED:
3244       if (debug_infrun)
3245         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_FORKED\n");
3246
3247       if (!ptid_equal (ecs->ptid, inferior_ptid))
3248         {
3249           context_switch (ecs->ptid);
3250           reinit_frame_cache ();
3251         }
3252
3253       /* Immediately detach breakpoints from the child before there's
3254          any chance of letting the user delete breakpoints from the
3255          breakpoint lists.  If we don't do this early, it's easy to
3256          leave left over traps in the child, vis: "break foo; catch
3257          fork; c; <fork>; del; c; <child calls foo>".  We only follow
3258          the fork on the last `continue', and by that time the
3259          breakpoint at "foo" is long gone from the breakpoint table.
3260          If we vforked, then we don't need to unpatch here, since both
3261          parent and child are sharing the same memory pages; we'll
3262          need to unpatch at follow/detach time instead to be certain
3263          that new breakpoints added between catchpoint hit time and
3264          vfork follow are detached.  */
3265       if (ecs->ws.kind != TARGET_WAITKIND_VFORKED)
3266         {
3267           int child_pid = ptid_get_pid (ecs->ws.value.related_pid);
3268
3269           /* This won't actually modify the breakpoint list, but will
3270              physically remove the breakpoints from the child.  */
3271           detach_breakpoints (child_pid);
3272         }
3273
3274       if (singlestep_breakpoints_inserted_p)
3275         {
3276           /* Pull the single step breakpoints out of the target. */
3277           remove_single_step_breakpoints ();
3278           singlestep_breakpoints_inserted_p = 0;
3279         }
3280
3281       /* In case the event is caught by a catchpoint, remember that
3282          the event is to be followed at the next resume of the thread,
3283          and not immediately.  */
3284       ecs->event_thread->pending_follow = ecs->ws;
3285
3286       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3287
3288       ecs->event_thread->control.stop_bpstat
3289         = bpstat_stop_status (get_regcache_aspace (get_current_regcache ()),
3290                               stop_pc, ecs->ptid);
3291
3292       /* Note that we're interested in knowing the bpstat actually
3293          causes a stop, not just if it may explain the signal.
3294          Software watchpoints, for example, always appear in the
3295          bpstat.  */
3296       ecs->random_signal
3297         = !bpstat_causes_stop (ecs->event_thread->control.stop_bpstat);
3298
3299       /* If no catchpoint triggered for this, then keep going.  */
3300       if (ecs->random_signal)
3301         {
3302           ptid_t parent;
3303           ptid_t child;
3304           int should_resume;
3305           int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
3306
3307           ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
3308
3309           should_resume = follow_fork ();
3310
3311           parent = ecs->ptid;
3312           child = ecs->ws.value.related_pid;
3313
3314           /* In non-stop mode, also resume the other branch.  */
3315           if (non_stop && !detach_fork)
3316             {
3317               if (follow_child)
3318                 switch_to_thread (parent);
3319               else
3320                 switch_to_thread (child);
3321
3322               ecs->event_thread = inferior_thread ();
3323               ecs->ptid = inferior_ptid;
3324               keep_going (ecs);
3325             }
3326
3327           if (follow_child)
3328             switch_to_thread (child);
3329           else
3330             switch_to_thread (parent);
3331
3332           ecs->event_thread = inferior_thread ();
3333           ecs->ptid = inferior_ptid;
3334
3335           if (should_resume)
3336             keep_going (ecs);
3337           else
3338             stop_stepping (ecs);
3339           return;
3340         }
3341       ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_TRAP;
3342       goto process_event_stop_test;
3343
3344     case TARGET_WAITKIND_VFORK_DONE:
3345       /* Done with the shared memory region.  Re-insert breakpoints in
3346          the parent, and keep going.  */
3347
3348       if (debug_infrun)
3349         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_VFORK_DONE\n");
3350
3351       if (!ptid_equal (ecs->ptid, inferior_ptid))
3352         context_switch (ecs->ptid);
3353
3354       current_inferior ()->waiting_for_vfork_done = 0;
3355       current_inferior ()->pspace->breakpoints_not_allowed = 0;
3356       /* This also takes care of reinserting breakpoints in the
3357          previously locked inferior.  */
3358       keep_going (ecs);
3359       return;
3360
3361     case TARGET_WAITKIND_EXECD:
3362       if (debug_infrun)
3363         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXECD\n");
3364
3365       if (!ptid_equal (ecs->ptid, inferior_ptid))
3366         {
3367           context_switch (ecs->ptid);
3368           reinit_frame_cache ();
3369         }
3370
3371       singlestep_breakpoints_inserted_p = 0;
3372       cancel_single_step_breakpoints ();
3373
3374       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3375
3376       /* Do whatever is necessary to the parent branch of the vfork.  */
3377       handle_vfork_child_exec_or_exit (1);
3378
3379       /* This causes the eventpoints and symbol table to be reset.
3380          Must do this now, before trying to determine whether to
3381          stop.  */
3382       follow_exec (inferior_ptid, ecs->ws.value.execd_pathname);
3383
3384       ecs->event_thread->control.stop_bpstat
3385         = bpstat_stop_status (get_regcache_aspace (get_current_regcache ()),
3386                               stop_pc, ecs->ptid);
3387       ecs->random_signal
3388         = !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat);
3389
3390       /* Note that this may be referenced from inside
3391          bpstat_stop_status above, through inferior_has_execd.  */
3392       xfree (ecs->ws.value.execd_pathname);
3393       ecs->ws.value.execd_pathname = NULL;
3394
3395       /* If no catchpoint triggered for this, then keep going.  */
3396       if (ecs->random_signal)
3397         {
3398           ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
3399           keep_going (ecs);
3400           return;
3401         }
3402       ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_TRAP;
3403       goto process_event_stop_test;
3404
3405       /* Be careful not to try to gather much state about a thread
3406          that's in a syscall.  It's frequently a losing proposition.  */
3407     case TARGET_WAITKIND_SYSCALL_ENTRY:
3408       if (debug_infrun)
3409         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SYSCALL_ENTRY\n");
3410       /* Getting the current syscall number */
3411       if (handle_syscall_event (ecs) != 0)
3412         return;
3413       goto process_event_stop_test;
3414
3415       /* Before examining the threads further, step this thread to
3416          get it entirely out of the syscall.  (We get notice of the
3417          event when the thread is just on the verge of exiting a
3418          syscall.  Stepping one instruction seems to get it back
3419          into user code.)  */
3420     case TARGET_WAITKIND_SYSCALL_RETURN:
3421       if (debug_infrun)
3422         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SYSCALL_RETURN\n");
3423       if (handle_syscall_event (ecs) != 0)
3424         return;
3425       goto process_event_stop_test;
3426
3427     case TARGET_WAITKIND_STOPPED:
3428       if (debug_infrun)
3429         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_STOPPED\n");
3430       ecs->event_thread->suspend.stop_signal = ecs->ws.value.sig;
3431       break;
3432
3433     case TARGET_WAITKIND_NO_HISTORY:
3434       /* Reverse execution: target ran out of history info.  */
3435       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3436       print_no_history_reason ();
3437       stop_stepping (ecs);
3438       return;
3439     }
3440
3441   if (ecs->new_thread_event)
3442     {
3443       if (non_stop)
3444         /* Non-stop assumes that the target handles adding new threads
3445            to the thread list.  */
3446         internal_error (__FILE__, __LINE__, "\
3447 targets should add new threads to the thread list themselves in non-stop mode.");
3448
3449       /* We may want to consider not doing a resume here in order to
3450          give the user a chance to play with the new thread.  It might
3451          be good to make that a user-settable option.  */
3452
3453       /* At this point, all threads are stopped (happens automatically
3454          in either the OS or the native code).  Therefore we need to
3455          continue all threads in order to make progress.  */
3456
3457       if (!ptid_equal (ecs->ptid, inferior_ptid))
3458         context_switch (ecs->ptid);
3459       target_resume (RESUME_ALL, 0, TARGET_SIGNAL_0);
3460       prepare_to_wait (ecs);
3461       return;
3462     }
3463
3464   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED)
3465     {
3466       /* Do we need to clean up the state of a thread that has
3467          completed a displaced single-step?  (Doing so usually affects
3468          the PC, so do it here, before we set stop_pc.)  */
3469       displaced_step_fixup (ecs->ptid,
3470                             ecs->event_thread->suspend.stop_signal);
3471
3472       /* If we either finished a single-step or hit a breakpoint, but
3473          the user wanted this thread to be stopped, pretend we got a
3474          SIG0 (generic unsignaled stop).  */
3475
3476       if (ecs->event_thread->stop_requested
3477           && ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP)
3478         ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
3479     }
3480
3481   stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3482
3483   if (debug_infrun)
3484     {
3485       struct regcache *regcache = get_thread_regcache (ecs->ptid);
3486       struct gdbarch *gdbarch = get_regcache_arch (regcache);
3487       struct cleanup *old_chain = save_inferior_ptid ();
3488
3489       inferior_ptid = ecs->ptid;
3490
3491       fprintf_unfiltered (gdb_stdlog, "infrun: stop_pc = %s\n",
3492                           paddress (gdbarch, stop_pc));
3493       if (target_stopped_by_watchpoint ())
3494         {
3495           CORE_ADDR addr;
3496
3497           fprintf_unfiltered (gdb_stdlog, "infrun: stopped by watchpoint\n");
3498
3499           if (target_stopped_data_address (&current_target, &addr))
3500             fprintf_unfiltered (gdb_stdlog,
3501                                 "infrun: stopped data address = %s\n",
3502                                 paddress (gdbarch, addr));
3503           else
3504             fprintf_unfiltered (gdb_stdlog,
3505                                 "infrun: (no data address available)\n");
3506         }
3507
3508       do_cleanups (old_chain);
3509     }
3510
3511   if (stepping_past_singlestep_breakpoint)
3512     {
3513       gdb_assert (singlestep_breakpoints_inserted_p);
3514       gdb_assert (ptid_equal (singlestep_ptid, ecs->ptid));
3515       gdb_assert (!ptid_equal (singlestep_ptid, saved_singlestep_ptid));
3516
3517       stepping_past_singlestep_breakpoint = 0;
3518
3519       /* We've either finished single-stepping past the single-step
3520          breakpoint, or stopped for some other reason.  It would be nice if
3521          we could tell, but we can't reliably.  */
3522       if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP)
3523         {
3524           if (debug_infrun)
3525             fprintf_unfiltered (gdb_stdlog, "infrun: stepping_past_singlestep_breakpoint\n");
3526           /* Pull the single step breakpoints out of the target.  */
3527           remove_single_step_breakpoints ();
3528           singlestep_breakpoints_inserted_p = 0;
3529
3530           ecs->random_signal = 0;
3531           ecs->event_thread->control.trap_expected = 0;
3532
3533           context_switch (saved_singlestep_ptid);
3534           if (deprecated_context_hook)
3535             deprecated_context_hook (pid_to_thread_id (ecs->ptid));
3536
3537           resume (1, TARGET_SIGNAL_0);
3538           prepare_to_wait (ecs);
3539           return;
3540         }
3541     }
3542
3543   if (!ptid_equal (deferred_step_ptid, null_ptid))
3544     {
3545       /* In non-stop mode, there's never a deferred_step_ptid set.  */
3546       gdb_assert (!non_stop);
3547
3548       /* If we stopped for some other reason than single-stepping, ignore
3549          the fact that we were supposed to switch back.  */
3550       if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP)
3551         {
3552           if (debug_infrun)
3553             fprintf_unfiltered (gdb_stdlog,
3554                                 "infrun: handling deferred step\n");
3555
3556           /* Pull the single step breakpoints out of the target.  */
3557           if (singlestep_breakpoints_inserted_p)
3558             {
3559               remove_single_step_breakpoints ();
3560               singlestep_breakpoints_inserted_p = 0;
3561             }
3562
3563           /* Note: We do not call context_switch at this point, as the
3564              context is already set up for stepping the original thread.  */
3565           switch_to_thread (deferred_step_ptid);
3566           deferred_step_ptid = null_ptid;
3567           /* Suppress spurious "Switching to ..." message.  */
3568           previous_inferior_ptid = inferior_ptid;
3569
3570           resume (1, TARGET_SIGNAL_0);
3571           prepare_to_wait (ecs);
3572           return;
3573         }
3574
3575       deferred_step_ptid = null_ptid;
3576     }
3577
3578   /* See if a thread hit a thread-specific breakpoint that was meant for
3579      another thread.  If so, then step that thread past the breakpoint,
3580      and continue it.  */
3581
3582   if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP)
3583     {
3584       int thread_hop_needed = 0;
3585       struct address_space *aspace = 
3586         get_regcache_aspace (get_thread_regcache (ecs->ptid));
3587
3588       /* Check if a regular breakpoint has been hit before checking
3589          for a potential single step breakpoint. Otherwise, GDB will
3590          not see this breakpoint hit when stepping onto breakpoints.  */
3591       if (regular_breakpoint_inserted_here_p (aspace, stop_pc))
3592         {
3593           ecs->random_signal = 0;
3594           if (!breakpoint_thread_match (aspace, stop_pc, ecs->ptid))
3595             thread_hop_needed = 1;
3596         }
3597       else if (singlestep_breakpoints_inserted_p)
3598         {
3599           /* We have not context switched yet, so this should be true
3600              no matter which thread hit the singlestep breakpoint.  */
3601           gdb_assert (ptid_equal (inferior_ptid, singlestep_ptid));
3602           if (debug_infrun)
3603             fprintf_unfiltered (gdb_stdlog, "infrun: software single step "
3604                                 "trap for %s\n",
3605                                 target_pid_to_str (ecs->ptid));
3606
3607           ecs->random_signal = 0;
3608           /* The call to in_thread_list is necessary because PTIDs sometimes
3609              change when we go from single-threaded to multi-threaded.  If
3610              the singlestep_ptid is still in the list, assume that it is
3611              really different from ecs->ptid.  */
3612           if (!ptid_equal (singlestep_ptid, ecs->ptid)
3613               && in_thread_list (singlestep_ptid))
3614             {
3615               /* If the PC of the thread we were trying to single-step
3616                  has changed, discard this event (which we were going
3617                  to ignore anyway), and pretend we saw that thread
3618                  trap.  This prevents us continuously moving the
3619                  single-step breakpoint forward, one instruction at a
3620                  time.  If the PC has changed, then the thread we were
3621                  trying to single-step has trapped or been signalled,
3622                  but the event has not been reported to GDB yet.
3623
3624                  There might be some cases where this loses signal
3625                  information, if a signal has arrived at exactly the
3626                  same time that the PC changed, but this is the best
3627                  we can do with the information available.  Perhaps we
3628                  should arrange to report all events for all threads
3629                  when they stop, or to re-poll the remote looking for
3630                  this particular thread (i.e. temporarily enable
3631                  schedlock).  */
3632
3633              CORE_ADDR new_singlestep_pc
3634                = regcache_read_pc (get_thread_regcache (singlestep_ptid));
3635
3636              if (new_singlestep_pc != singlestep_pc)
3637                {
3638                  enum target_signal stop_signal;
3639
3640                  if (debug_infrun)
3641                    fprintf_unfiltered (gdb_stdlog, "infrun: unexpected thread,"
3642                                        " but expected thread advanced also\n");
3643
3644                  /* The current context still belongs to
3645                     singlestep_ptid.  Don't swap here, since that's
3646                     the context we want to use.  Just fudge our
3647                     state and continue.  */
3648                  stop_signal = ecs->event_thread->suspend.stop_signal;
3649                  ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
3650                  ecs->ptid = singlestep_ptid;
3651                  ecs->event_thread = find_thread_ptid (ecs->ptid);
3652                  ecs->event_thread->suspend.stop_signal = stop_signal;
3653                  stop_pc = new_singlestep_pc;
3654                }
3655              else
3656                {
3657                  if (debug_infrun)
3658                    fprintf_unfiltered (gdb_stdlog,
3659                                        "infrun: unexpected thread\n");
3660
3661                  thread_hop_needed = 1;
3662                  stepping_past_singlestep_breakpoint = 1;
3663                  saved_singlestep_ptid = singlestep_ptid;
3664                }
3665             }
3666         }
3667
3668       if (thread_hop_needed)
3669         {
3670           struct regcache *thread_regcache;
3671           int remove_status = 0;
3672
3673           if (debug_infrun)
3674             fprintf_unfiltered (gdb_stdlog, "infrun: thread_hop_needed\n");
3675
3676           /* Switch context before touching inferior memory, the
3677              previous thread may have exited.  */
3678           if (!ptid_equal (inferior_ptid, ecs->ptid))
3679             context_switch (ecs->ptid);
3680
3681           /* Saw a breakpoint, but it was hit by the wrong thread.
3682              Just continue. */
3683
3684           if (singlestep_breakpoints_inserted_p)
3685             {
3686               /* Pull the single step breakpoints out of the target. */
3687               remove_single_step_breakpoints ();
3688               singlestep_breakpoints_inserted_p = 0;
3689             }
3690
3691           /* If the arch can displace step, don't remove the
3692              breakpoints.  */
3693           thread_regcache = get_thread_regcache (ecs->ptid);
3694           if (!use_displaced_stepping (get_regcache_arch (thread_regcache)))
3695             remove_status = remove_breakpoints ();
3696
3697           /* Did we fail to remove breakpoints?  If so, try
3698              to set the PC past the bp.  (There's at least
3699              one situation in which we can fail to remove
3700              the bp's: On HP-UX's that use ttrace, we can't
3701              change the address space of a vforking child
3702              process until the child exits (well, okay, not
3703              then either :-) or execs. */
3704           if (remove_status != 0)
3705             error (_("Cannot step over breakpoint hit in wrong thread"));
3706           else
3707             {                   /* Single step */
3708               if (!non_stop)
3709                 {
3710                   /* Only need to require the next event from this
3711                      thread in all-stop mode.  */
3712                   waiton_ptid = ecs->ptid;
3713                   infwait_state = infwait_thread_hop_state;
3714                 }
3715
3716               ecs->event_thread->stepping_over_breakpoint = 1;
3717               keep_going (ecs);
3718               return;
3719             }
3720         }
3721       else if (singlestep_breakpoints_inserted_p)
3722         {
3723           sw_single_step_trap_p = 1;
3724           ecs->random_signal = 0;
3725         }
3726     }
3727   else
3728     ecs->random_signal = 1;
3729
3730   /* See if something interesting happened to the non-current thread.  If
3731      so, then switch to that thread.  */
3732   if (!ptid_equal (ecs->ptid, inferior_ptid))
3733     {
3734       if (debug_infrun)
3735         fprintf_unfiltered (gdb_stdlog, "infrun: context switch\n");
3736
3737       context_switch (ecs->ptid);
3738
3739       if (deprecated_context_hook)
3740         deprecated_context_hook (pid_to_thread_id (ecs->ptid));
3741     }
3742
3743   /* At this point, get hold of the now-current thread's frame.  */
3744   frame = get_current_frame ();
3745   gdbarch = get_frame_arch (frame);
3746
3747   if (singlestep_breakpoints_inserted_p)
3748     {
3749       /* Pull the single step breakpoints out of the target. */
3750       remove_single_step_breakpoints ();
3751       singlestep_breakpoints_inserted_p = 0;
3752     }
3753
3754   if (stepped_after_stopped_by_watchpoint)
3755     stopped_by_watchpoint = 0;
3756   else
3757     stopped_by_watchpoint = watchpoints_triggered (&ecs->ws);
3758
3759   /* If necessary, step over this watchpoint.  We'll be back to display
3760      it in a moment.  */
3761   if (stopped_by_watchpoint
3762       && (target_have_steppable_watchpoint
3763           || gdbarch_have_nonsteppable_watchpoint (gdbarch)))
3764     {
3765       /* At this point, we are stopped at an instruction which has
3766          attempted to write to a piece of memory under control of
3767          a watchpoint.  The instruction hasn't actually executed
3768          yet.  If we were to evaluate the watchpoint expression
3769          now, we would get the old value, and therefore no change
3770          would seem to have occurred.
3771
3772          In order to make watchpoints work `right', we really need
3773          to complete the memory write, and then evaluate the
3774          watchpoint expression.  We do this by single-stepping the
3775          target.
3776
3777          It may not be necessary to disable the watchpoint to stop over
3778          it.  For example, the PA can (with some kernel cooperation)
3779          single step over a watchpoint without disabling the watchpoint.
3780
3781          It is far more common to need to disable a watchpoint to step
3782          the inferior over it.  If we have non-steppable watchpoints,
3783          we must disable the current watchpoint; it's simplest to
3784          disable all watchpoints and breakpoints.  */
3785       int hw_step = 1;
3786
3787       if (!target_have_steppable_watchpoint)
3788         remove_breakpoints ();
3789         /* Single step */
3790       hw_step = maybe_software_singlestep (gdbarch, stop_pc);
3791       target_resume (ecs->ptid, hw_step, TARGET_SIGNAL_0);
3792       waiton_ptid = ecs->ptid;
3793       if (target_have_steppable_watchpoint)
3794         infwait_state = infwait_step_watch_state;
3795       else
3796         infwait_state = infwait_nonstep_watch_state;
3797       prepare_to_wait (ecs);
3798       return;
3799     }
3800
3801   ecs->stop_func_start = 0;
3802   ecs->stop_func_end = 0;
3803   ecs->stop_func_name = 0;
3804   /* Don't care about return value; stop_func_start and stop_func_name
3805      will both be 0 if it doesn't work.  */
3806   find_pc_partial_function (stop_pc, &ecs->stop_func_name,
3807                             &ecs->stop_func_start, &ecs->stop_func_end);
3808   ecs->stop_func_start
3809     += gdbarch_deprecated_function_start_offset (gdbarch);
3810   ecs->event_thread->stepping_over_breakpoint = 0;
3811   bpstat_clear (&ecs->event_thread->control.stop_bpstat);
3812   ecs->event_thread->control.stop_step = 0;
3813   stop_print_frame = 1;
3814   ecs->random_signal = 0;
3815   stopped_by_random_signal = 0;
3816
3817   /* Hide inlined functions starting here, unless we just performed stepi or
3818      nexti.  After stepi and nexti, always show the innermost frame (not any
3819      inline function call sites).  */
3820   if (ecs->event_thread->control.step_range_end != 1)
3821     skip_inline_frames (ecs->ptid);
3822
3823   if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP
3824       && ecs->event_thread->control.trap_expected
3825       && gdbarch_single_step_through_delay_p (gdbarch)
3826       && currently_stepping (ecs->event_thread))
3827     {
3828       /* We're trying to step off a breakpoint.  Turns out that we're
3829          also on an instruction that needs to be stepped multiple
3830          times before it's been fully executing. E.g., architectures
3831          with a delay slot.  It needs to be stepped twice, once for
3832          the instruction and once for the delay slot.  */
3833       int step_through_delay
3834         = gdbarch_single_step_through_delay (gdbarch, frame);
3835
3836       if (debug_infrun && step_through_delay)
3837         fprintf_unfiltered (gdb_stdlog, "infrun: step through delay\n");
3838       if (ecs->event_thread->control.step_range_end == 0
3839           && step_through_delay)
3840         {
3841           /* The user issued a continue when stopped at a breakpoint.
3842              Set up for another trap and get out of here.  */
3843          ecs->event_thread->stepping_over_breakpoint = 1;
3844          keep_going (ecs);
3845          return;
3846         }
3847       else if (step_through_delay)
3848         {
3849           /* The user issued a step when stopped at a breakpoint.
3850              Maybe we should stop, maybe we should not - the delay
3851              slot *might* correspond to a line of source.  In any
3852              case, don't decide that here, just set 
3853              ecs->stepping_over_breakpoint, making sure we 
3854              single-step again before breakpoints are re-inserted.  */
3855           ecs->event_thread->stepping_over_breakpoint = 1;
3856         }
3857     }
3858
3859   /* Look at the cause of the stop, and decide what to do.
3860      The alternatives are:
3861      1) stop_stepping and return; to really stop and return to the debugger,
3862      2) keep_going and return to start up again
3863      (set ecs->event_thread->stepping_over_breakpoint to 1 to single step once)
3864      3) set ecs->random_signal to 1, and the decision between 1 and 2
3865      will be made according to the signal handling tables.  */
3866
3867   if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP
3868       || stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_NO_SIGSTOP
3869       || stop_soon == STOP_QUIETLY_REMOTE)
3870     {
3871       if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP
3872           && stop_after_trap)
3873         {
3874           if (debug_infrun)
3875             fprintf_unfiltered (gdb_stdlog, "infrun: stopped\n");
3876           stop_print_frame = 0;
3877           stop_stepping (ecs);
3878           return;
3879         }
3880
3881       /* This is originated from start_remote(), start_inferior() and
3882          shared libraries hook functions.  */
3883       if (stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_REMOTE)
3884         {
3885           if (debug_infrun)
3886             fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
3887           stop_stepping (ecs);
3888           return;
3889         }
3890
3891       /* This originates from attach_command().  We need to overwrite
3892          the stop_signal here, because some kernels don't ignore a
3893          SIGSTOP in a subsequent ptrace(PTRACE_CONT,SIGSTOP) call.
3894          See more comments in inferior.h.  On the other hand, if we
3895          get a non-SIGSTOP, report it to the user - assume the backend
3896          will handle the SIGSTOP if it should show up later.
3897
3898          Also consider that the attach is complete when we see a
3899          SIGTRAP.  Some systems (e.g. Windows), and stubs supporting
3900          target extended-remote report it instead of a SIGSTOP
3901          (e.g. gdbserver).  We already rely on SIGTRAP being our
3902          signal, so this is no exception.
3903
3904          Also consider that the attach is complete when we see a
3905          TARGET_SIGNAL_0.  In non-stop mode, GDB will explicitly tell
3906          the target to stop all threads of the inferior, in case the
3907          low level attach operation doesn't stop them implicitly.  If
3908          they weren't stopped implicitly, then the stub will report a
3909          TARGET_SIGNAL_0, meaning: stopped for no particular reason
3910          other than GDB's request.  */
3911       if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
3912           && (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_STOP
3913               || ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP
3914               || ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_0))
3915         {
3916           stop_stepping (ecs);
3917           ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
3918           return;
3919         }
3920
3921       /* See if there is a breakpoint at the current PC.  */
3922       ecs->event_thread->control.stop_bpstat
3923         = bpstat_stop_status (get_regcache_aspace (get_current_regcache ()),
3924                               stop_pc, ecs->ptid);
3925
3926       /* Following in case break condition called a
3927          function.  */
3928       stop_print_frame = 1;
3929
3930       /* This is where we handle "moribund" watchpoints.  Unlike
3931          software breakpoints traps, hardware watchpoint traps are
3932          always distinguishable from random traps.  If no high-level
3933          watchpoint is associated with the reported stop data address
3934          anymore, then the bpstat does not explain the signal ---
3935          simply make sure to ignore it if `stopped_by_watchpoint' is
3936          set.  */
3937
3938       if (debug_infrun
3939           && ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP
3940           && !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat)
3941           && stopped_by_watchpoint)
3942         fprintf_unfiltered (gdb_stdlog, "\
3943 infrun: no user watchpoint explains watchpoint SIGTRAP, ignoring\n");
3944
3945       /* NOTE: cagney/2003-03-29: These two checks for a random signal
3946          at one stage in the past included checks for an inferior
3947          function call's call dummy's return breakpoint.  The original
3948          comment, that went with the test, read:
3949
3950          ``End of a stack dummy.  Some systems (e.g. Sony news) give
3951          another signal besides SIGTRAP, so check here as well as
3952          above.''
3953
3954          If someone ever tries to get call dummys on a
3955          non-executable stack to work (where the target would stop
3956          with something like a SIGSEGV), then those tests might need
3957          to be re-instated.  Given, however, that the tests were only
3958          enabled when momentary breakpoints were not being used, I
3959          suspect that it won't be the case.
3960
3961          NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
3962          be necessary for call dummies on a non-executable stack on
3963          SPARC.  */
3964
3965       if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP)
3966         ecs->random_signal
3967           = !(bpstat_explains_signal (ecs->event_thread->control.stop_bpstat)
3968               || stopped_by_watchpoint
3969               || ecs->event_thread->control.trap_expected
3970               || (ecs->event_thread->control.step_range_end
3971                   && (ecs->event_thread->control.step_resume_breakpoint
3972                       == NULL)));
3973       else
3974         {
3975           ecs->random_signal = !bpstat_explains_signal
3976                                      (ecs->event_thread->control.stop_bpstat);
3977           if (!ecs->random_signal)
3978             ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_TRAP;
3979         }
3980     }
3981
3982   /* When we reach this point, we've pretty much decided
3983      that the reason for stopping must've been a random
3984      (unexpected) signal. */
3985
3986   else
3987     ecs->random_signal = 1;
3988
3989 process_event_stop_test:
3990
3991   /* Re-fetch current thread's frame in case we did a
3992      "goto process_event_stop_test" above.  */
3993   frame = get_current_frame ();
3994   gdbarch = get_frame_arch (frame);
3995
3996   /* For the program's own signals, act according to
3997      the signal handling tables.  */
3998
3999   if (ecs->random_signal)
4000     {
4001       /* Signal not for debugging purposes.  */
4002       int printed = 0;
4003       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
4004
4005       if (debug_infrun)
4006          fprintf_unfiltered (gdb_stdlog, "infrun: random signal %d\n",
4007                              ecs->event_thread->suspend.stop_signal);
4008
4009       stopped_by_random_signal = 1;
4010
4011       if (signal_print[ecs->event_thread->suspend.stop_signal])
4012         {
4013           printed = 1;
4014           target_terminal_ours_for_output ();
4015           print_signal_received_reason
4016                                      (ecs->event_thread->suspend.stop_signal);
4017         }
4018       /* Always stop on signals if we're either just gaining control
4019          of the program, or the user explicitly requested this thread
4020          to remain stopped.  */
4021       if (stop_soon != NO_STOP_QUIETLY
4022           || ecs->event_thread->stop_requested
4023           || (!inf->detaching
4024               && signal_stop_state (ecs->event_thread->suspend.stop_signal)))
4025         {
4026           stop_stepping (ecs);
4027           return;
4028         }
4029       /* If not going to stop, give terminal back
4030          if we took it away.  */
4031       else if (printed)
4032         target_terminal_inferior ();
4033
4034       /* Clear the signal if it should not be passed.  */
4035       if (signal_program[ecs->event_thread->suspend.stop_signal] == 0)
4036         ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
4037
4038       if (ecs->event_thread->prev_pc == stop_pc
4039           && ecs->event_thread->control.trap_expected
4040           && ecs->event_thread->control.step_resume_breakpoint == NULL)
4041         {
4042           /* We were just starting a new sequence, attempting to
4043              single-step off of a breakpoint and expecting a SIGTRAP.
4044              Instead this signal arrives.  This signal will take us out
4045              of the stepping range so GDB needs to remember to, when
4046              the signal handler returns, resume stepping off that
4047              breakpoint.  */
4048           /* To simplify things, "continue" is forced to use the same
4049              code paths as single-step - set a breakpoint at the
4050              signal return address and then, once hit, step off that
4051              breakpoint.  */
4052           if (debug_infrun)
4053             fprintf_unfiltered (gdb_stdlog,
4054                                 "infrun: signal arrived while stepping over "
4055                                 "breakpoint\n");
4056
4057           insert_step_resume_breakpoint_at_frame (frame);
4058           ecs->event_thread->step_after_step_resume_breakpoint = 1;
4059           keep_going (ecs);
4060           return;
4061         }
4062
4063       if (ecs->event_thread->control.step_range_end != 0
4064           && ecs->event_thread->suspend.stop_signal != TARGET_SIGNAL_0
4065           && (ecs->event_thread->control.step_range_start <= stop_pc
4066               && stop_pc < ecs->event_thread->control.step_range_end)
4067           && frame_id_eq (get_stack_frame_id (frame),
4068                           ecs->event_thread->control.step_stack_frame_id)
4069           && ecs->event_thread->control.step_resume_breakpoint == NULL)
4070         {
4071           /* The inferior is about to take a signal that will take it
4072              out of the single step range.  Set a breakpoint at the
4073              current PC (which is presumably where the signal handler
4074              will eventually return) and then allow the inferior to
4075              run free.
4076
4077              Note that this is only needed for a signal delivered
4078              while in the single-step range.  Nested signals aren't a
4079              problem as they eventually all return.  */
4080           if (debug_infrun)
4081             fprintf_unfiltered (gdb_stdlog,
4082                                 "infrun: signal may take us out of "
4083                                 "single-step range\n");
4084
4085           insert_step_resume_breakpoint_at_frame (frame);
4086           keep_going (ecs);
4087           return;
4088         }
4089
4090       /* Note: step_resume_breakpoint may be non-NULL.  This occures
4091          when either there's a nested signal, or when there's a
4092          pending signal enabled just as the signal handler returns
4093          (leaving the inferior at the step-resume-breakpoint without
4094          actually executing it).  Either way continue until the
4095          breakpoint is really hit.  */
4096       keep_going (ecs);
4097       return;
4098     }
4099
4100   /* Handle cases caused by hitting a breakpoint.  */
4101   {
4102     CORE_ADDR jmp_buf_pc;
4103     struct bpstat_what what;
4104
4105     what = bpstat_what (ecs->event_thread->control.stop_bpstat);
4106
4107     if (what.call_dummy)
4108       {
4109         stop_stack_dummy = what.call_dummy;
4110       }
4111
4112     /* If we hit an internal event that triggers symbol changes, the
4113        current frame will be invalidated within bpstat_what (e.g., if
4114        we hit an internal solib event).  Re-fetch it.  */
4115     frame = get_current_frame ();
4116     gdbarch = get_frame_arch (frame);
4117
4118     switch (what.main_action)
4119       {
4120       case BPSTAT_WHAT_SET_LONGJMP_RESUME:
4121         /* If we hit the breakpoint at longjmp while stepping, we
4122            install a momentary breakpoint at the target of the
4123            jmp_buf.  */
4124
4125         if (debug_infrun)
4126           fprintf_unfiltered (gdb_stdlog,
4127                               "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME\n");
4128
4129         ecs->event_thread->stepping_over_breakpoint = 1;
4130
4131         if (what.is_longjmp)
4132           {
4133             if (!gdbarch_get_longjmp_target_p (gdbarch)
4134                 || !gdbarch_get_longjmp_target (gdbarch,
4135                                                 frame, &jmp_buf_pc))
4136               {
4137                 if (debug_infrun)
4138                   fprintf_unfiltered (gdb_stdlog, "\
4139 infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME (!gdbarch_get_longjmp_target)\n");
4140                 keep_going (ecs);
4141                 return;
4142               }
4143
4144             /* We're going to replace the current step-resume breakpoint
4145                with a longjmp-resume breakpoint.  */
4146             delete_step_resume_breakpoint (ecs->event_thread);
4147
4148             /* Insert a breakpoint at resume address.  */
4149             insert_longjmp_resume_breakpoint (gdbarch, jmp_buf_pc);
4150           }
4151         else
4152           {
4153             struct symbol *func = get_frame_function (frame);
4154
4155             if (func)
4156               check_exception_resume (ecs, frame, func);
4157           }
4158         keep_going (ecs);
4159         return;
4160
4161       case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
4162         if (debug_infrun)
4163           fprintf_unfiltered (gdb_stdlog,
4164                               "infrun: BPSTAT_WHAT_CLEAR_LONGJMP_RESUME\n");
4165
4166         if (what.is_longjmp)
4167           {
4168             gdb_assert (ecs->event_thread->control.step_resume_breakpoint
4169                         != NULL);
4170             delete_step_resume_breakpoint (ecs->event_thread);
4171           }
4172         else
4173           {
4174             /* There are several cases to consider.
4175
4176                1. The initiating frame no longer exists.  In this case
4177                we must stop, because the exception has gone too far.
4178
4179                2. The initiating frame exists, and is the same as the
4180                current frame.  We stop, because the exception has been
4181                caught.
4182
4183                3. The initiating frame exists and is different from
4184                the current frame.  This means the exception has been
4185                caught beneath the initiating frame, so keep going.  */
4186             struct frame_info *init_frame
4187               = frame_find_by_id (ecs->event_thread->initiating_frame);
4188
4189             gdb_assert (ecs->event_thread->control.exception_resume_breakpoint
4190                         != NULL);
4191             delete_exception_resume_breakpoint (ecs->event_thread);
4192
4193             if (init_frame)
4194               {
4195                 struct frame_id current_id
4196                   = get_frame_id (get_current_frame ());
4197                 if (frame_id_eq (current_id,
4198                                  ecs->event_thread->initiating_frame))
4199                   {
4200                     /* Case 2.  Fall through.  */
4201                   }
4202                 else
4203                   {
4204                     /* Case 3.  */
4205                     keep_going (ecs);
4206                     return;
4207                   }
4208               }
4209
4210             /* For Cases 1 and 2, remove the step-resume breakpoint,
4211                if it exists.  */
4212             delete_step_resume_breakpoint (ecs->event_thread);
4213           }
4214
4215         ecs->event_thread->control.stop_step = 1;
4216         print_end_stepping_range_reason ();
4217         stop_stepping (ecs);
4218         return;
4219
4220       case BPSTAT_WHAT_SINGLE:
4221         if (debug_infrun)
4222           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_SINGLE\n");
4223         ecs->event_thread->stepping_over_breakpoint = 1;
4224         /* Still need to check other stuff, at least the case
4225            where we are stepping and step out of the right range.  */
4226         break;
4227
4228       case BPSTAT_WHAT_STOP_NOISY:
4229         if (debug_infrun)
4230           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_NOISY\n");
4231         stop_print_frame = 1;
4232
4233         /* We are about to nuke the step_resume_breakpointt via the
4234            cleanup chain, so no need to worry about it here.  */
4235
4236         stop_stepping (ecs);
4237         return;
4238
4239       case BPSTAT_WHAT_STOP_SILENT:
4240         if (debug_infrun)
4241           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_SILENT\n");
4242         stop_print_frame = 0;
4243
4244         /* We are about to nuke the step_resume_breakpoin via the
4245            cleanup chain, so no need to worry about it here.  */
4246
4247         stop_stepping (ecs);
4248         return;
4249
4250       case BPSTAT_WHAT_STEP_RESUME:
4251         if (debug_infrun)
4252           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STEP_RESUME\n");
4253
4254         delete_step_resume_breakpoint (ecs->event_thread);
4255         if (ecs->event_thread->step_after_step_resume_breakpoint)
4256           {
4257             /* Back when the step-resume breakpoint was inserted, we
4258                were trying to single-step off a breakpoint.  Go back
4259                to doing that.  */
4260             ecs->event_thread->step_after_step_resume_breakpoint = 0;
4261             ecs->event_thread->stepping_over_breakpoint = 1;
4262             keep_going (ecs);
4263             return;
4264           }
4265         if (stop_pc == ecs->stop_func_start
4266             && execution_direction == EXEC_REVERSE)
4267           {
4268             /* We are stepping over a function call in reverse, and
4269                just hit the step-resume breakpoint at the start
4270                address of the function.  Go back to single-stepping,
4271                which should take us back to the function call.  */
4272             ecs->event_thread->stepping_over_breakpoint = 1;
4273             keep_going (ecs);
4274             return;
4275           }
4276         break;
4277
4278       case BPSTAT_WHAT_KEEP_CHECKING:
4279         break;
4280       }
4281   }
4282
4283   /* We come here if we hit a breakpoint but should not
4284      stop for it.  Possibly we also were stepping
4285      and should stop for that.  So fall through and
4286      test for stepping.  But, if not stepping,
4287      do not stop.  */
4288
4289   /* In all-stop mode, if we're currently stepping but have stopped in
4290      some other thread, we need to switch back to the stepped thread.  */
4291   if (!non_stop)
4292     {
4293       struct thread_info *tp;
4294
4295       tp = iterate_over_threads (currently_stepping_or_nexting_callback,
4296                                  ecs->event_thread);
4297       if (tp)
4298         {
4299           /* However, if the current thread is blocked on some internal
4300              breakpoint, and we simply need to step over that breakpoint
4301              to get it going again, do that first.  */
4302           if ((ecs->event_thread->control.trap_expected
4303                && ecs->event_thread->suspend.stop_signal != TARGET_SIGNAL_TRAP)
4304               || ecs->event_thread->stepping_over_breakpoint)
4305             {
4306               keep_going (ecs);
4307               return;
4308             }
4309
4310           /* If the stepping thread exited, then don't try to switch
4311              back and resume it, which could fail in several different
4312              ways depending on the target.  Instead, just keep going.
4313
4314              We can find a stepping dead thread in the thread list in
4315              two cases:
4316
4317              - The target supports thread exit events, and when the
4318              target tries to delete the thread from the thread list,
4319              inferior_ptid pointed at the exiting thread.  In such
4320              case, calling delete_thread does not really remove the
4321              thread from the list; instead, the thread is left listed,
4322              with 'exited' state.
4323
4324              - The target's debug interface does not support thread
4325              exit events, and so we have no idea whatsoever if the
4326              previously stepping thread is still alive.  For that
4327              reason, we need to synchronously query the target
4328              now.  */
4329           if (is_exited (tp->ptid)
4330               || !target_thread_alive (tp->ptid))
4331             {
4332               if (debug_infrun)
4333                 fprintf_unfiltered (gdb_stdlog, "\
4334 infrun: not switching back to stepped thread, it has vanished\n");
4335
4336               delete_thread (tp->ptid);
4337               keep_going (ecs);
4338               return;
4339             }
4340
4341           /* Otherwise, we no longer expect a trap in the current thread.
4342              Clear the trap_expected flag before switching back -- this is
4343              what keep_going would do as well, if we called it.  */
4344           ecs->event_thread->control.trap_expected = 0;
4345
4346           if (debug_infrun)
4347             fprintf_unfiltered (gdb_stdlog,
4348                                 "infrun: switching back to stepped thread\n");
4349
4350           ecs->event_thread = tp;
4351           ecs->ptid = tp->ptid;
4352           context_switch (ecs->ptid);
4353           keep_going (ecs);
4354           return;
4355         }
4356     }
4357
4358   /* Are we stepping to get the inferior out of the dynamic linker's
4359      hook (and possibly the dld itself) after catching a shlib
4360      event?  */
4361   if (ecs->event_thread->stepping_through_solib_after_catch)
4362     {
4363 #if defined(SOLIB_ADD)
4364       /* Have we reached our destination?  If not, keep going. */
4365       if (SOLIB_IN_DYNAMIC_LINKER (PIDGET (ecs->ptid), stop_pc))
4366         {
4367           if (debug_infrun)
4368             fprintf_unfiltered (gdb_stdlog, "infrun: stepping in dynamic linker\n");
4369           ecs->event_thread->stepping_over_breakpoint = 1;
4370           keep_going (ecs);
4371           return;
4372         }
4373 #endif
4374       if (debug_infrun)
4375          fprintf_unfiltered (gdb_stdlog, "infrun: step past dynamic linker\n");
4376       /* Else, stop and report the catchpoint(s) whose triggering
4377          caused us to begin stepping. */
4378       ecs->event_thread->stepping_through_solib_after_catch = 0;
4379       bpstat_clear (&ecs->event_thread->control.stop_bpstat);
4380       ecs->event_thread->control.stop_bpstat
4381         = bpstat_copy (ecs->event_thread->stepping_through_solib_catchpoints);
4382       bpstat_clear (&ecs->event_thread->stepping_through_solib_catchpoints);
4383       stop_print_frame = 1;
4384       stop_stepping (ecs);
4385       return;
4386     }
4387
4388   if (ecs->event_thread->control.step_resume_breakpoint)
4389     {
4390       if (debug_infrun)
4391          fprintf_unfiltered (gdb_stdlog,
4392                              "infrun: step-resume breakpoint is inserted\n");
4393
4394       /* Having a step-resume breakpoint overrides anything
4395          else having to do with stepping commands until
4396          that breakpoint is reached.  */
4397       keep_going (ecs);
4398       return;
4399     }
4400
4401   if (ecs->event_thread->control.step_range_end == 0)
4402     {
4403       if (debug_infrun)
4404          fprintf_unfiltered (gdb_stdlog, "infrun: no stepping, continue\n");
4405       /* Likewise if we aren't even stepping.  */
4406       keep_going (ecs);
4407       return;
4408     }
4409
4410   /* Re-fetch current thread's frame in case the code above caused
4411      the frame cache to be re-initialized, making our FRAME variable
4412      a dangling pointer.  */
4413   frame = get_current_frame ();
4414   gdbarch = get_frame_arch (frame);
4415
4416   /* If stepping through a line, keep going if still within it.
4417
4418      Note that step_range_end is the address of the first instruction
4419      beyond the step range, and NOT the address of the last instruction
4420      within it!
4421
4422      Note also that during reverse execution, we may be stepping
4423      through a function epilogue and therefore must detect when
4424      the current-frame changes in the middle of a line.  */
4425
4426   if (stop_pc >= ecs->event_thread->control.step_range_start
4427       && stop_pc < ecs->event_thread->control.step_range_end
4428       && (execution_direction != EXEC_REVERSE
4429           || frame_id_eq (get_frame_id (frame),
4430                           ecs->event_thread->control.step_frame_id)))
4431     {
4432       if (debug_infrun)
4433         fprintf_unfiltered
4434           (gdb_stdlog, "infrun: stepping inside range [%s-%s]\n",
4435            paddress (gdbarch, ecs->event_thread->control.step_range_start),
4436            paddress (gdbarch, ecs->event_thread->control.step_range_end));
4437
4438       /* When stepping backward, stop at beginning of line range
4439          (unless it's the function entry point, in which case
4440          keep going back to the call point).  */
4441       if (stop_pc == ecs->event_thread->control.step_range_start
4442           && stop_pc != ecs->stop_func_start
4443           && execution_direction == EXEC_REVERSE)
4444         {
4445           ecs->event_thread->control.stop_step = 1;
4446           print_end_stepping_range_reason ();
4447           stop_stepping (ecs);
4448         }
4449       else
4450         keep_going (ecs);
4451
4452       return;
4453     }
4454
4455   /* We stepped out of the stepping range.  */
4456
4457   /* If we are stepping at the source level and entered the runtime
4458      loader dynamic symbol resolution code...
4459
4460      EXEC_FORWARD: we keep on single stepping until we exit the run
4461      time loader code and reach the callee's address.
4462
4463      EXEC_REVERSE: we've already executed the callee (backward), and
4464      the runtime loader code is handled just like any other
4465      undebuggable function call.  Now we need only keep stepping
4466      backward through the trampoline code, and that's handled further
4467      down, so there is nothing for us to do here.  */
4468
4469   if (execution_direction != EXEC_REVERSE
4470       && ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4471       && in_solib_dynsym_resolve_code (stop_pc))
4472     {
4473       CORE_ADDR pc_after_resolver =
4474         gdbarch_skip_solib_resolver (gdbarch, stop_pc);
4475
4476       if (debug_infrun)
4477          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into dynsym resolve code\n");
4478
4479       if (pc_after_resolver)
4480         {
4481           /* Set up a step-resume breakpoint at the address
4482              indicated by SKIP_SOLIB_RESOLVER.  */
4483           struct symtab_and_line sr_sal;
4484
4485           init_sal (&sr_sal);
4486           sr_sal.pc = pc_after_resolver;
4487           sr_sal.pspace = get_frame_program_space (frame);
4488
4489           insert_step_resume_breakpoint_at_sal (gdbarch,
4490                                                 sr_sal, null_frame_id);
4491         }
4492
4493       keep_going (ecs);
4494       return;
4495     }
4496
4497   if (ecs->event_thread->control.step_range_end != 1
4498       && (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4499           || ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
4500       && get_frame_type (frame) == SIGTRAMP_FRAME)
4501     {
4502       if (debug_infrun)
4503          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into signal trampoline\n");
4504       /* The inferior, while doing a "step" or "next", has ended up in
4505          a signal trampoline (either by a signal being delivered or by
4506          the signal handler returning).  Just single-step until the
4507          inferior leaves the trampoline (either by calling the handler
4508          or returning).  */
4509       keep_going (ecs);
4510       return;
4511     }
4512
4513   /* Check for subroutine calls.  The check for the current frame
4514      equalling the step ID is not necessary - the check of the
4515      previous frame's ID is sufficient - but it is a common case and
4516      cheaper than checking the previous frame's ID.
4517
4518      NOTE: frame_id_eq will never report two invalid frame IDs as
4519      being equal, so to get into this block, both the current and
4520      previous frame must have valid frame IDs.  */
4521   /* The outer_frame_id check is a heuristic to detect stepping
4522      through startup code.  If we step over an instruction which
4523      sets the stack pointer from an invalid value to a valid value,
4524      we may detect that as a subroutine call from the mythical
4525      "outermost" function.  This could be fixed by marking
4526      outermost frames as !stack_p,code_p,special_p.  Then the
4527      initial outermost frame, before sp was valid, would
4528      have code_addr == &_start.  See the comment in frame_id_eq
4529      for more.  */
4530   if (!frame_id_eq (get_stack_frame_id (frame),
4531                     ecs->event_thread->control.step_stack_frame_id)
4532       && (frame_id_eq (frame_unwind_caller_id (get_current_frame ()),
4533                        ecs->event_thread->control.step_stack_frame_id)
4534           && (!frame_id_eq (ecs->event_thread->control.step_stack_frame_id,
4535                             outer_frame_id)
4536               || step_start_function != find_pc_function (stop_pc))))
4537     {
4538       CORE_ADDR real_stop_pc;
4539
4540       if (debug_infrun)
4541          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into subroutine\n");
4542
4543       if ((ecs->event_thread->control.step_over_calls == STEP_OVER_NONE)
4544           || ((ecs->event_thread->control.step_range_end == 1)
4545               && in_prologue (gdbarch, ecs->event_thread->prev_pc,
4546                               ecs->stop_func_start)))
4547         {
4548           /* I presume that step_over_calls is only 0 when we're
4549              supposed to be stepping at the assembly language level
4550              ("stepi").  Just stop.  */
4551           /* Also, maybe we just did a "nexti" inside a prolog, so we
4552              thought it was a subroutine call but it was not.  Stop as
4553              well.  FENN */
4554           /* And this works the same backward as frontward.  MVS */
4555           ecs->event_thread->control.stop_step = 1;
4556           print_end_stepping_range_reason ();
4557           stop_stepping (ecs);
4558           return;
4559         }
4560
4561       /* Reverse stepping through solib trampolines.  */
4562
4563       if (execution_direction == EXEC_REVERSE
4564           && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE
4565           && (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
4566               || (ecs->stop_func_start == 0
4567                   && in_solib_dynsym_resolve_code (stop_pc))))
4568         {
4569           /* Any solib trampoline code can be handled in reverse
4570              by simply continuing to single-step.  We have already
4571              executed the solib function (backwards), and a few 
4572              steps will take us back through the trampoline to the
4573              caller.  */
4574           keep_going (ecs);
4575           return;
4576         }
4577
4578       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
4579         {
4580           /* We're doing a "next".
4581
4582              Normal (forward) execution: set a breakpoint at the
4583              callee's return address (the address at which the caller
4584              will resume).
4585
4586              Reverse (backward) execution.  set the step-resume
4587              breakpoint at the start of the function that we just
4588              stepped into (backwards), and continue to there.  When we
4589              get there, we'll need to single-step back to the caller.  */
4590
4591           if (execution_direction == EXEC_REVERSE)
4592             {
4593               struct symtab_and_line sr_sal;
4594
4595               /* Normal function call return (static or dynamic).  */
4596               init_sal (&sr_sal);
4597               sr_sal.pc = ecs->stop_func_start;
4598               sr_sal.pspace = get_frame_program_space (frame);
4599               insert_step_resume_breakpoint_at_sal (gdbarch,
4600                                                     sr_sal, null_frame_id);
4601             }
4602           else
4603             insert_step_resume_breakpoint_at_caller (frame);
4604
4605           keep_going (ecs);
4606           return;
4607         }
4608
4609       /* If we are in a function call trampoline (a stub between the
4610          calling routine and the real function), locate the real
4611          function.  That's what tells us (a) whether we want to step
4612          into it at all, and (b) what prologue we want to run to the
4613          end of, if we do step into it.  */
4614       real_stop_pc = skip_language_trampoline (frame, stop_pc);
4615       if (real_stop_pc == 0)
4616         real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
4617       if (real_stop_pc != 0)
4618         ecs->stop_func_start = real_stop_pc;
4619
4620       if (real_stop_pc != 0 && in_solib_dynsym_resolve_code (real_stop_pc))
4621         {
4622           struct symtab_and_line sr_sal;
4623
4624           init_sal (&sr_sal);
4625           sr_sal.pc = ecs->stop_func_start;
4626           sr_sal.pspace = get_frame_program_space (frame);
4627
4628           insert_step_resume_breakpoint_at_sal (gdbarch,
4629                                                 sr_sal, null_frame_id);
4630           keep_going (ecs);
4631           return;
4632         }
4633
4634       /* If we have line number information for the function we are
4635          thinking of stepping into, step into it.
4636
4637          If there are several symtabs at that PC (e.g. with include
4638          files), just want to know whether *any* of them have line
4639          numbers.  find_pc_line handles this.  */
4640       {
4641         struct symtab_and_line tmp_sal;
4642
4643         tmp_sal = find_pc_line (ecs->stop_func_start, 0);
4644         tmp_sal.pspace = get_frame_program_space (frame);
4645         if (tmp_sal.line != 0)
4646           {
4647             if (execution_direction == EXEC_REVERSE)
4648               handle_step_into_function_backward (gdbarch, ecs);
4649             else
4650               handle_step_into_function (gdbarch, ecs);
4651             return;
4652           }
4653       }
4654
4655       /* If we have no line number and the step-stop-if-no-debug is
4656          set, we stop the step so that the user has a chance to switch
4657          in assembly mode.  */
4658       if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4659           && step_stop_if_no_debug)
4660         {
4661           ecs->event_thread->control.stop_step = 1;
4662           print_end_stepping_range_reason ();
4663           stop_stepping (ecs);
4664           return;
4665         }
4666
4667       if (execution_direction == EXEC_REVERSE)
4668         {
4669           /* Set a breakpoint at callee's start address.
4670              From there we can step once and be back in the caller.  */
4671           struct symtab_and_line sr_sal;
4672
4673           init_sal (&sr_sal);
4674           sr_sal.pc = ecs->stop_func_start;
4675           sr_sal.pspace = get_frame_program_space (frame);
4676           insert_step_resume_breakpoint_at_sal (gdbarch,
4677                                                 sr_sal, null_frame_id);
4678         }
4679       else
4680         /* Set a breakpoint at callee's return address (the address
4681            at which the caller will resume).  */
4682         insert_step_resume_breakpoint_at_caller (frame);
4683
4684       keep_going (ecs);
4685       return;
4686     }
4687
4688   /* Reverse stepping through solib trampolines.  */
4689
4690   if (execution_direction == EXEC_REVERSE
4691       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
4692     {
4693       if (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
4694           || (ecs->stop_func_start == 0
4695               && in_solib_dynsym_resolve_code (stop_pc)))
4696         {
4697           /* Any solib trampoline code can be handled in reverse
4698              by simply continuing to single-step.  We have already
4699              executed the solib function (backwards), and a few 
4700              steps will take us back through the trampoline to the
4701              caller.  */
4702           keep_going (ecs);
4703           return;
4704         }
4705       else if (in_solib_dynsym_resolve_code (stop_pc))
4706         {
4707           /* Stepped backward into the solib dynsym resolver.
4708              Set a breakpoint at its start and continue, then
4709              one more step will take us out.  */
4710           struct symtab_and_line sr_sal;
4711
4712           init_sal (&sr_sal);
4713           sr_sal.pc = ecs->stop_func_start;
4714           sr_sal.pspace = get_frame_program_space (frame);
4715           insert_step_resume_breakpoint_at_sal (gdbarch, 
4716                                                 sr_sal, null_frame_id);
4717           keep_going (ecs);
4718           return;
4719         }
4720     }
4721
4722   /* If we're in the return path from a shared library trampoline,
4723      we want to proceed through the trampoline when stepping.  */
4724   if (gdbarch_in_solib_return_trampoline (gdbarch,
4725                                           stop_pc, ecs->stop_func_name))
4726     {
4727       /* Determine where this trampoline returns.  */
4728       CORE_ADDR real_stop_pc;
4729
4730       real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
4731
4732       if (debug_infrun)
4733          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into solib return tramp\n");
4734
4735       /* Only proceed through if we know where it's going.  */
4736       if (real_stop_pc)
4737         {
4738           /* And put the step-breakpoint there and go until there. */
4739           struct symtab_and_line sr_sal;
4740
4741           init_sal (&sr_sal);   /* initialize to zeroes */
4742           sr_sal.pc = real_stop_pc;
4743           sr_sal.section = find_pc_overlay (sr_sal.pc);
4744           sr_sal.pspace = get_frame_program_space (frame);
4745
4746           /* Do not specify what the fp should be when we stop since
4747              on some machines the prologue is where the new fp value
4748              is established.  */
4749           insert_step_resume_breakpoint_at_sal (gdbarch,
4750                                                 sr_sal, null_frame_id);
4751
4752           /* Restart without fiddling with the step ranges or
4753              other state.  */
4754           keep_going (ecs);
4755           return;
4756         }
4757     }
4758
4759   stop_pc_sal = find_pc_line (stop_pc, 0);
4760
4761   /* NOTE: tausq/2004-05-24: This if block used to be done before all
4762      the trampoline processing logic, however, there are some trampolines 
4763      that have no names, so we should do trampoline handling first.  */
4764   if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4765       && ecs->stop_func_name == NULL
4766       && stop_pc_sal.line == 0)
4767     {
4768       if (debug_infrun)
4769          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into undebuggable function\n");
4770
4771       /* The inferior just stepped into, or returned to, an
4772          undebuggable function (where there is no debugging information
4773          and no line number corresponding to the address where the
4774          inferior stopped).  Since we want to skip this kind of code,
4775          we keep going until the inferior returns from this
4776          function - unless the user has asked us not to (via
4777          set step-mode) or we no longer know how to get back
4778          to the call site.  */
4779       if (step_stop_if_no_debug
4780           || !frame_id_p (frame_unwind_caller_id (frame)))
4781         {
4782           /* If we have no line number and the step-stop-if-no-debug
4783              is set, we stop the step so that the user has a chance to
4784              switch in assembly mode.  */
4785           ecs->event_thread->control.stop_step = 1;
4786           print_end_stepping_range_reason ();
4787           stop_stepping (ecs);
4788           return;
4789         }
4790       else
4791         {
4792           /* Set a breakpoint at callee's return address (the address
4793              at which the caller will resume).  */
4794           insert_step_resume_breakpoint_at_caller (frame);
4795           keep_going (ecs);
4796           return;
4797         }
4798     }
4799
4800   if (ecs->event_thread->control.step_range_end == 1)
4801     {
4802       /* It is stepi or nexti.  We always want to stop stepping after
4803          one instruction.  */
4804       if (debug_infrun)
4805          fprintf_unfiltered (gdb_stdlog, "infrun: stepi/nexti\n");
4806       ecs->event_thread->control.stop_step = 1;
4807       print_end_stepping_range_reason ();
4808       stop_stepping (ecs);
4809       return;
4810     }
4811
4812   if (stop_pc_sal.line == 0)
4813     {
4814       /* We have no line number information.  That means to stop
4815          stepping (does this always happen right after one instruction,
4816          when we do "s" in a function with no line numbers,
4817          or can this happen as a result of a return or longjmp?).  */
4818       if (debug_infrun)
4819          fprintf_unfiltered (gdb_stdlog, "infrun: no line number info\n");
4820       ecs->event_thread->control.stop_step = 1;
4821       print_end_stepping_range_reason ();
4822       stop_stepping (ecs);
4823       return;
4824     }
4825
4826   /* Look for "calls" to inlined functions, part one.  If the inline
4827      frame machinery detected some skipped call sites, we have entered
4828      a new inline function.  */
4829
4830   if (frame_id_eq (get_frame_id (get_current_frame ()),
4831                    ecs->event_thread->control.step_frame_id)
4832       && inline_skipped_frames (ecs->ptid))
4833     {
4834       struct symtab_and_line call_sal;
4835
4836       if (debug_infrun)
4837         fprintf_unfiltered (gdb_stdlog,
4838                             "infrun: stepped into inlined function\n");
4839
4840       find_frame_sal (get_current_frame (), &call_sal);
4841
4842       if (ecs->event_thread->control.step_over_calls != STEP_OVER_ALL)
4843         {
4844           /* For "step", we're going to stop.  But if the call site
4845              for this inlined function is on the same source line as
4846              we were previously stepping, go down into the function
4847              first.  Otherwise stop at the call site.  */
4848
4849           if (call_sal.line == ecs->event_thread->current_line
4850               && call_sal.symtab == ecs->event_thread->current_symtab)
4851             step_into_inline_frame (ecs->ptid);
4852
4853           ecs->event_thread->control.stop_step = 1;
4854           print_end_stepping_range_reason ();
4855           stop_stepping (ecs);
4856           return;
4857         }
4858       else
4859         {
4860           /* For "next", we should stop at the call site if it is on a
4861              different source line.  Otherwise continue through the
4862              inlined function.  */
4863           if (call_sal.line == ecs->event_thread->current_line
4864               && call_sal.symtab == ecs->event_thread->current_symtab)
4865             keep_going (ecs);
4866           else
4867             {
4868               ecs->event_thread->control.stop_step = 1;
4869               print_end_stepping_range_reason ();
4870               stop_stepping (ecs);
4871             }
4872           return;
4873         }
4874     }
4875
4876   /* Look for "calls" to inlined functions, part two.  If we are still
4877      in the same real function we were stepping through, but we have
4878      to go further up to find the exact frame ID, we are stepping
4879      through a more inlined call beyond its call site.  */
4880
4881   if (get_frame_type (get_current_frame ()) == INLINE_FRAME
4882       && !frame_id_eq (get_frame_id (get_current_frame ()),
4883                        ecs->event_thread->control.step_frame_id)
4884       && stepped_in_from (get_current_frame (),
4885                           ecs->event_thread->control.step_frame_id))
4886     {
4887       if (debug_infrun)
4888         fprintf_unfiltered (gdb_stdlog,
4889                             "infrun: stepping through inlined function\n");
4890
4891       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
4892         keep_going (ecs);
4893       else
4894         {
4895           ecs->event_thread->control.stop_step = 1;
4896           print_end_stepping_range_reason ();
4897           stop_stepping (ecs);
4898         }
4899       return;
4900     }
4901
4902   if ((stop_pc == stop_pc_sal.pc)
4903       && (ecs->event_thread->current_line != stop_pc_sal.line
4904           || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
4905     {
4906       /* We are at the start of a different line.  So stop.  Note that
4907          we don't stop if we step into the middle of a different line.
4908          That is said to make things like for (;;) statements work
4909          better.  */
4910       if (debug_infrun)
4911          fprintf_unfiltered (gdb_stdlog, "infrun: stepped to a different line\n");
4912       ecs->event_thread->control.stop_step = 1;
4913       print_end_stepping_range_reason ();
4914       stop_stepping (ecs);
4915       return;
4916     }
4917
4918   /* We aren't done stepping.
4919
4920      Optimize by setting the stepping range to the line.
4921      (We might not be in the original line, but if we entered a
4922      new line in mid-statement, we continue stepping.  This makes
4923      things like for(;;) statements work better.)  */
4924
4925   ecs->event_thread->control.step_range_start = stop_pc_sal.pc;
4926   ecs->event_thread->control.step_range_end = stop_pc_sal.end;
4927   set_step_info (frame, stop_pc_sal);
4928
4929   if (debug_infrun)
4930      fprintf_unfiltered (gdb_stdlog, "infrun: keep going\n");
4931   keep_going (ecs);
4932 }
4933
4934 /* Is thread TP in the middle of single-stepping?  */
4935
4936 static int
4937 currently_stepping (struct thread_info *tp)
4938 {
4939   return ((tp->control.step_range_end
4940            && tp->control.step_resume_breakpoint == NULL)
4941           || tp->control.trap_expected
4942           || tp->stepping_through_solib_after_catch
4943           || bpstat_should_step ());
4944 }
4945
4946 /* Returns true if any thread *but* the one passed in "data" is in the
4947    middle of stepping or of handling a "next".  */
4948
4949 static int
4950 currently_stepping_or_nexting_callback (struct thread_info *tp, void *data)
4951 {
4952   if (tp == data)
4953     return 0;
4954
4955   return (tp->control.step_range_end
4956           || tp->control.trap_expected
4957           || tp->stepping_through_solib_after_catch);
4958 }
4959
4960 /* Inferior has stepped into a subroutine call with source code that
4961    we should not step over.  Do step to the first line of code in
4962    it.  */
4963
4964 static void
4965 handle_step_into_function (struct gdbarch *gdbarch,
4966                            struct execution_control_state *ecs)
4967 {
4968   struct symtab *s;
4969   struct symtab_and_line stop_func_sal, sr_sal;
4970
4971   s = find_pc_symtab (stop_pc);
4972   if (s && s->language != language_asm)
4973     ecs->stop_func_start = gdbarch_skip_prologue (gdbarch,
4974                                                   ecs->stop_func_start);
4975
4976   stop_func_sal = find_pc_line (ecs->stop_func_start, 0);
4977   /* Use the step_resume_break to step until the end of the prologue,
4978      even if that involves jumps (as it seems to on the vax under
4979      4.2).  */
4980   /* If the prologue ends in the middle of a source line, continue to
4981      the end of that source line (if it is still within the function).
4982      Otherwise, just go to end of prologue.  */
4983   if (stop_func_sal.end
4984       && stop_func_sal.pc != ecs->stop_func_start
4985       && stop_func_sal.end < ecs->stop_func_end)
4986     ecs->stop_func_start = stop_func_sal.end;
4987
4988   /* Architectures which require breakpoint adjustment might not be able
4989      to place a breakpoint at the computed address.  If so, the test
4990      ``ecs->stop_func_start == stop_pc'' will never succeed.  Adjust
4991      ecs->stop_func_start to an address at which a breakpoint may be
4992      legitimately placed.
4993
4994      Note:  kevinb/2004-01-19:  On FR-V, if this adjustment is not
4995      made, GDB will enter an infinite loop when stepping through
4996      optimized code consisting of VLIW instructions which contain
4997      subinstructions corresponding to different source lines.  On
4998      FR-V, it's not permitted to place a breakpoint on any but the
4999      first subinstruction of a VLIW instruction.  When a breakpoint is
5000      set, GDB will adjust the breakpoint address to the beginning of
5001      the VLIW instruction.  Thus, we need to make the corresponding
5002      adjustment here when computing the stop address.  */
5003
5004   if (gdbarch_adjust_breakpoint_address_p (gdbarch))
5005     {
5006       ecs->stop_func_start
5007         = gdbarch_adjust_breakpoint_address (gdbarch,
5008                                              ecs->stop_func_start);
5009     }
5010
5011   if (ecs->stop_func_start == stop_pc)
5012     {
5013       /* We are already there: stop now.  */
5014       ecs->event_thread->control.stop_step = 1;
5015       print_end_stepping_range_reason ();
5016       stop_stepping (ecs);
5017       return;
5018     }
5019   else
5020     {
5021       /* Put the step-breakpoint there and go until there.  */
5022       init_sal (&sr_sal);       /* initialize to zeroes */
5023       sr_sal.pc = ecs->stop_func_start;
5024       sr_sal.section = find_pc_overlay (ecs->stop_func_start);
5025       sr_sal.pspace = get_frame_program_space (get_current_frame ());
5026
5027       /* Do not specify what the fp should be when we stop since on
5028          some machines the prologue is where the new fp value is
5029          established.  */
5030       insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal, null_frame_id);
5031
5032       /* And make sure stepping stops right away then.  */
5033       ecs->event_thread->control.step_range_end
5034         = ecs->event_thread->control.step_range_start;
5035     }
5036   keep_going (ecs);
5037 }
5038
5039 /* Inferior has stepped backward into a subroutine call with source
5040    code that we should not step over.  Do step to the beginning of the
5041    last line of code in it.  */
5042
5043 static void
5044 handle_step_into_function_backward (struct gdbarch *gdbarch,
5045                                     struct execution_control_state *ecs)
5046 {
5047   struct symtab *s;
5048   struct symtab_and_line stop_func_sal;
5049
5050   s = find_pc_symtab (stop_pc);
5051   if (s && s->language != language_asm)
5052     ecs->stop_func_start = gdbarch_skip_prologue (gdbarch,
5053                                                   ecs->stop_func_start);
5054
5055   stop_func_sal = find_pc_line (stop_pc, 0);
5056
5057   /* OK, we're just going to keep stepping here.  */
5058   if (stop_func_sal.pc == stop_pc)
5059     {
5060       /* We're there already.  Just stop stepping now.  */
5061       ecs->event_thread->control.stop_step = 1;
5062       print_end_stepping_range_reason ();
5063       stop_stepping (ecs);
5064     }
5065   else
5066     {
5067       /* Else just reset the step range and keep going.
5068          No step-resume breakpoint, they don't work for
5069          epilogues, which can have multiple entry paths.  */
5070       ecs->event_thread->control.step_range_start = stop_func_sal.pc;
5071       ecs->event_thread->control.step_range_end = stop_func_sal.end;
5072       keep_going (ecs);
5073     }
5074   return;
5075 }
5076
5077 /* Insert a "step-resume breakpoint" at SR_SAL with frame ID SR_ID.
5078    This is used to both functions and to skip over code.  */
5079
5080 static void
5081 insert_step_resume_breakpoint_at_sal (struct gdbarch *gdbarch,
5082                                       struct symtab_and_line sr_sal,
5083                                       struct frame_id sr_id)
5084 {
5085   /* There should never be more than one step-resume or longjmp-resume
5086      breakpoint per thread, so we should never be setting a new
5087      step_resume_breakpoint when one is already active.  */
5088   gdb_assert (inferior_thread ()->control.step_resume_breakpoint == NULL);
5089
5090   if (debug_infrun)
5091     fprintf_unfiltered (gdb_stdlog,
5092                         "infrun: inserting step-resume breakpoint at %s\n",
5093                         paddress (gdbarch, sr_sal.pc));
5094
5095   inferior_thread ()->control.step_resume_breakpoint
5096     = set_momentary_breakpoint (gdbarch, sr_sal, sr_id, bp_step_resume);
5097 }
5098
5099 /* Insert a "step-resume breakpoint" at RETURN_FRAME.pc.  This is used
5100    to skip a potential signal handler.
5101
5102    This is called with the interrupted function's frame.  The signal
5103    handler, when it returns, will resume the interrupted function at
5104    RETURN_FRAME.pc.  */
5105
5106 static void
5107 insert_step_resume_breakpoint_at_frame (struct frame_info *return_frame)
5108 {
5109   struct symtab_and_line sr_sal;
5110   struct gdbarch *gdbarch;
5111
5112   gdb_assert (return_frame != NULL);
5113   init_sal (&sr_sal);           /* initialize to zeros */
5114
5115   gdbarch = get_frame_arch (return_frame);
5116   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch, get_frame_pc (return_frame));
5117   sr_sal.section = find_pc_overlay (sr_sal.pc);
5118   sr_sal.pspace = get_frame_program_space (return_frame);
5119
5120   insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal,
5121                                         get_stack_frame_id (return_frame));
5122 }
5123
5124 /* Similar to insert_step_resume_breakpoint_at_frame, except
5125    but a breakpoint at the previous frame's PC.  This is used to
5126    skip a function after stepping into it (for "next" or if the called
5127    function has no debugging information).
5128
5129    The current function has almost always been reached by single
5130    stepping a call or return instruction.  NEXT_FRAME belongs to the
5131    current function, and the breakpoint will be set at the caller's
5132    resume address.
5133
5134    This is a separate function rather than reusing
5135    insert_step_resume_breakpoint_at_frame in order to avoid
5136    get_prev_frame, which may stop prematurely (see the implementation
5137    of frame_unwind_caller_id for an example).  */
5138
5139 static void
5140 insert_step_resume_breakpoint_at_caller (struct frame_info *next_frame)
5141 {
5142   struct symtab_and_line sr_sal;
5143   struct gdbarch *gdbarch;
5144
5145   /* We shouldn't have gotten here if we don't know where the call site
5146      is.  */
5147   gdb_assert (frame_id_p (frame_unwind_caller_id (next_frame)));
5148
5149   init_sal (&sr_sal);           /* initialize to zeros */
5150
5151   gdbarch = frame_unwind_caller_arch (next_frame);
5152   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch,
5153                                         frame_unwind_caller_pc (next_frame));
5154   sr_sal.section = find_pc_overlay (sr_sal.pc);
5155   sr_sal.pspace = frame_unwind_program_space (next_frame);
5156
5157   insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal,
5158                                         frame_unwind_caller_id (next_frame));
5159 }
5160
5161 /* Insert a "longjmp-resume" breakpoint at PC.  This is used to set a
5162    new breakpoint at the target of a jmp_buf.  The handling of
5163    longjmp-resume uses the same mechanisms used for handling
5164    "step-resume" breakpoints.  */
5165
5166 static void
5167 insert_longjmp_resume_breakpoint (struct gdbarch *gdbarch, CORE_ADDR pc)
5168 {
5169   /* There should never be more than one step-resume or longjmp-resume
5170      breakpoint per thread, so we should never be setting a new
5171      longjmp_resume_breakpoint when one is already active.  */
5172   gdb_assert (inferior_thread ()->control.step_resume_breakpoint == NULL);
5173
5174   if (debug_infrun)
5175     fprintf_unfiltered (gdb_stdlog,
5176                         "infrun: inserting longjmp-resume breakpoint at %s\n",
5177                         paddress (gdbarch, pc));
5178
5179   inferior_thread ()->control.step_resume_breakpoint =
5180     set_momentary_breakpoint_at_pc (gdbarch, pc, bp_longjmp_resume);
5181 }
5182
5183 /* Insert an exception resume breakpoint.  TP is the thread throwing
5184    the exception.  The block B is the block of the unwinder debug hook
5185    function.  FRAME is the frame corresponding to the call to this
5186    function.  SYM is the symbol of the function argument holding the
5187    target PC of the exception.  */
5188
5189 static void
5190 insert_exception_resume_breakpoint (struct thread_info *tp,
5191                                     struct block *b,
5192                                     struct frame_info *frame,
5193                                     struct symbol *sym)
5194 {
5195   struct gdb_exception e;
5196
5197   /* We want to ignore errors here.  */
5198   TRY_CATCH (e, RETURN_MASK_ERROR)
5199     {
5200       struct symbol *vsym;
5201       struct value *value;
5202       CORE_ADDR handler;
5203       struct breakpoint *bp;
5204
5205       vsym = lookup_symbol (SYMBOL_LINKAGE_NAME (sym), b, VAR_DOMAIN, NULL);
5206       value = read_var_value (vsym, frame);
5207       /* If the value was optimized out, revert to the old behavior.  */
5208       if (! value_optimized_out (value))
5209         {
5210           handler = value_as_address (value);
5211
5212           if (debug_infrun)
5213             fprintf_unfiltered (gdb_stdlog,
5214                                 "infrun: exception resume at %lx\n",
5215                                 (unsigned long) handler);
5216
5217           bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
5218                                                handler, bp_exception_resume);
5219           bp->thread = tp->num;
5220           inferior_thread ()->control.exception_resume_breakpoint = bp;
5221         }
5222     }
5223 }
5224
5225 /* This is called when an exception has been intercepted.  Check to
5226    see whether the exception's destination is of interest, and if so,
5227    set an exception resume breakpoint there.  */
5228
5229 static void
5230 check_exception_resume (struct execution_control_state *ecs,
5231                         struct frame_info *frame, struct symbol *func)
5232 {
5233   struct gdb_exception e;
5234
5235   TRY_CATCH (e, RETURN_MASK_ERROR)
5236     {
5237       struct block *b;
5238       struct dict_iterator iter;
5239       struct symbol *sym;
5240       int argno = 0;
5241
5242       /* The exception breakpoint is a thread-specific breakpoint on
5243          the unwinder's debug hook, declared as:
5244          
5245          void _Unwind_DebugHook (void *cfa, void *handler);
5246          
5247          The CFA argument indicates the frame to which control is
5248          about to be transferred.  HANDLER is the destination PC.
5249          
5250          We ignore the CFA and set a temporary breakpoint at HANDLER.
5251          This is not extremely efficient but it avoids issues in gdb
5252          with computing the DWARF CFA, and it also works even in weird
5253          cases such as throwing an exception from inside a signal
5254          handler.  */
5255
5256       b = SYMBOL_BLOCK_VALUE (func);
5257       ALL_BLOCK_SYMBOLS (b, iter, sym)
5258         {
5259           if (!SYMBOL_IS_ARGUMENT (sym))
5260             continue;
5261
5262           if (argno == 0)
5263             ++argno;
5264           else
5265             {
5266               insert_exception_resume_breakpoint (ecs->event_thread,
5267                                                   b, frame, sym);
5268               break;
5269             }
5270         }
5271     }
5272 }
5273
5274 static void
5275 stop_stepping (struct execution_control_state *ecs)
5276 {
5277   if (debug_infrun)
5278     fprintf_unfiltered (gdb_stdlog, "infrun: stop_stepping\n");
5279
5280   /* Let callers know we don't want to wait for the inferior anymore.  */
5281   ecs->wait_some_more = 0;
5282 }
5283
5284 /* This function handles various cases where we need to continue
5285    waiting for the inferior.  */
5286 /* (Used to be the keep_going: label in the old wait_for_inferior) */
5287
5288 static void
5289 keep_going (struct execution_control_state *ecs)
5290 {
5291   /* Make sure normal_stop is called if we get a QUIT handled before
5292      reaching resume.  */
5293   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
5294
5295   /* Save the pc before execution, to compare with pc after stop.  */
5296   ecs->event_thread->prev_pc
5297     = regcache_read_pc (get_thread_regcache (ecs->ptid));
5298
5299   /* If we did not do break;, it means we should keep running the
5300      inferior and not return to debugger.  */
5301
5302   if (ecs->event_thread->control.trap_expected
5303       && ecs->event_thread->suspend.stop_signal != TARGET_SIGNAL_TRAP)
5304     {
5305       /* We took a signal (which we are supposed to pass through to
5306          the inferior, else we'd not get here) and we haven't yet
5307          gotten our trap.  Simply continue.  */
5308
5309       discard_cleanups (old_cleanups);
5310       resume (currently_stepping (ecs->event_thread),
5311               ecs->event_thread->suspend.stop_signal);
5312     }
5313   else
5314     {
5315       /* Either the trap was not expected, but we are continuing
5316          anyway (the user asked that this signal be passed to the
5317          child)
5318          -- or --
5319          The signal was SIGTRAP, e.g. it was our signal, but we
5320          decided we should resume from it.
5321
5322          We're going to run this baby now!  
5323
5324          Note that insert_breakpoints won't try to re-insert
5325          already inserted breakpoints.  Therefore, we don't
5326          care if breakpoints were already inserted, or not.  */
5327       
5328       if (ecs->event_thread->stepping_over_breakpoint)
5329         {
5330           struct regcache *thread_regcache = get_thread_regcache (ecs->ptid);
5331
5332           if (!use_displaced_stepping (get_regcache_arch (thread_regcache)))
5333             /* Since we can't do a displaced step, we have to remove
5334                the breakpoint while we step it.  To keep things
5335                simple, we remove them all.  */
5336             remove_breakpoints ();
5337         }
5338       else
5339         {
5340           struct gdb_exception e;
5341
5342           /* Stop stepping when inserting breakpoints
5343              has failed.  */
5344           TRY_CATCH (e, RETURN_MASK_ERROR)
5345             {
5346               insert_breakpoints ();
5347             }
5348           if (e.reason < 0)
5349             {
5350               exception_print (gdb_stderr, e);
5351               stop_stepping (ecs);
5352               return;
5353             }
5354         }
5355
5356       ecs->event_thread->control.trap_expected
5357         = ecs->event_thread->stepping_over_breakpoint;
5358
5359       /* Do not deliver SIGNAL_TRAP (except when the user explicitly
5360          specifies that such a signal should be delivered to the
5361          target program).
5362
5363          Typically, this would occure when a user is debugging a
5364          target monitor on a simulator: the target monitor sets a
5365          breakpoint; the simulator encounters this break-point and
5366          halts the simulation handing control to GDB; GDB, noteing
5367          that the break-point isn't valid, returns control back to the
5368          simulator; the simulator then delivers the hardware
5369          equivalent of a SIGNAL_TRAP to the program being debugged. */
5370
5371       if (ecs->event_thread->suspend.stop_signal == TARGET_SIGNAL_TRAP
5372           && !signal_program[ecs->event_thread->suspend.stop_signal])
5373         ecs->event_thread->suspend.stop_signal = TARGET_SIGNAL_0;
5374
5375       discard_cleanups (old_cleanups);
5376       resume (currently_stepping (ecs->event_thread),
5377               ecs->event_thread->suspend.stop_signal);
5378     }
5379
5380   prepare_to_wait (ecs);
5381 }
5382
5383 /* This function normally comes after a resume, before
5384    handle_inferior_event exits.  It takes care of any last bits of
5385    housekeeping, and sets the all-important wait_some_more flag.  */
5386
5387 static void
5388 prepare_to_wait (struct execution_control_state *ecs)
5389 {
5390   if (debug_infrun)
5391     fprintf_unfiltered (gdb_stdlog, "infrun: prepare_to_wait\n");
5392
5393   /* This is the old end of the while loop.  Let everybody know we
5394      want to wait for the inferior some more and get called again
5395      soon.  */
5396   ecs->wait_some_more = 1;
5397 }
5398
5399 /* Several print_*_reason functions to print why the inferior has stopped.
5400    We always print something when the inferior exits, or receives a signal.
5401    The rest of the cases are dealt with later on in normal_stop and
5402    print_it_typical.  Ideally there should be a call to one of these
5403    print_*_reason functions functions from handle_inferior_event each time
5404    stop_stepping is called.  */
5405
5406 /* Print why the inferior has stopped.  
5407    We are done with a step/next/si/ni command, print why the inferior has
5408    stopped.  For now print nothing.  Print a message only if not in the middle
5409    of doing a "step n" operation for n > 1.  */
5410
5411 static void
5412 print_end_stepping_range_reason (void)
5413 {
5414   if ((!inferior_thread ()->step_multi
5415        || !inferior_thread ()->control.stop_step)
5416       && ui_out_is_mi_like_p (uiout))
5417     ui_out_field_string (uiout, "reason",
5418                          async_reason_lookup (EXEC_ASYNC_END_STEPPING_RANGE));
5419 }
5420
5421 /* The inferior was terminated by a signal, print why it stopped.  */
5422
5423 static void
5424 print_signal_exited_reason (enum target_signal siggnal)
5425 {
5426   annotate_signalled ();
5427   if (ui_out_is_mi_like_p (uiout))
5428     ui_out_field_string
5429       (uiout, "reason", async_reason_lookup (EXEC_ASYNC_EXITED_SIGNALLED));
5430   ui_out_text (uiout, "\nProgram terminated with signal ");
5431   annotate_signal_name ();
5432   ui_out_field_string (uiout, "signal-name",
5433                        target_signal_to_name (siggnal));
5434   annotate_signal_name_end ();
5435   ui_out_text (uiout, ", ");
5436   annotate_signal_string ();
5437   ui_out_field_string (uiout, "signal-meaning",
5438                        target_signal_to_string (siggnal));
5439   annotate_signal_string_end ();
5440   ui_out_text (uiout, ".\n");
5441   ui_out_text (uiout, "The program no longer exists.\n");
5442 }
5443
5444 /* The inferior program is finished, print why it stopped.  */
5445
5446 static void
5447 print_exited_reason (int exitstatus)
5448 {
5449   annotate_exited (exitstatus);
5450   if (exitstatus)
5451     {
5452       if (ui_out_is_mi_like_p (uiout))
5453         ui_out_field_string (uiout, "reason", 
5454                              async_reason_lookup (EXEC_ASYNC_EXITED));
5455       ui_out_text (uiout, "\nProgram exited with code ");
5456       ui_out_field_fmt (uiout, "exit-code", "0%o", (unsigned int) exitstatus);
5457       ui_out_text (uiout, ".\n");
5458     }
5459   else
5460     {
5461       if (ui_out_is_mi_like_p (uiout))
5462         ui_out_field_string
5463           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_EXITED_NORMALLY));
5464       ui_out_text (uiout, "\nProgram exited normally.\n");
5465     }
5466   /* Support the --return-child-result option.  */
5467   return_child_result_value = exitstatus;
5468 }
5469
5470 /* Signal received, print why the inferior has stopped.  The signal table
5471    tells us to print about it. */
5472
5473 static void
5474 print_signal_received_reason (enum target_signal siggnal)
5475 {
5476   annotate_signal ();
5477
5478   if (siggnal == TARGET_SIGNAL_0 && !ui_out_is_mi_like_p (uiout))
5479     {
5480       struct thread_info *t = inferior_thread ();
5481
5482       ui_out_text (uiout, "\n[");
5483       ui_out_field_string (uiout, "thread-name",
5484                            target_pid_to_str (t->ptid));
5485       ui_out_field_fmt (uiout, "thread-id", "] #%d", t->num);
5486       ui_out_text (uiout, " stopped");
5487     }
5488   else
5489     {
5490       ui_out_text (uiout, "\nProgram received signal ");
5491       annotate_signal_name ();
5492       if (ui_out_is_mi_like_p (uiout))
5493         ui_out_field_string
5494           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_SIGNAL_RECEIVED));
5495       ui_out_field_string (uiout, "signal-name",
5496                            target_signal_to_name (siggnal));
5497       annotate_signal_name_end ();
5498       ui_out_text (uiout, ", ");
5499       annotate_signal_string ();
5500       ui_out_field_string (uiout, "signal-meaning",
5501                            target_signal_to_string (siggnal));
5502       annotate_signal_string_end ();
5503     }
5504   ui_out_text (uiout, ".\n");
5505 }
5506
5507 /* Reverse execution: target ran out of history info, print why the inferior
5508    has stopped.  */
5509
5510 static void
5511 print_no_history_reason (void)
5512 {
5513   ui_out_text (uiout, "\nNo more reverse-execution history.\n");
5514 }
5515
5516 /* Here to return control to GDB when the inferior stops for real.
5517    Print appropriate messages, remove breakpoints, give terminal our modes.
5518
5519    STOP_PRINT_FRAME nonzero means print the executing frame
5520    (pc, function, args, file, line number and line text).
5521    BREAKPOINTS_FAILED nonzero means stop was due to error
5522    attempting to insert breakpoints.  */
5523
5524 void
5525 normal_stop (void)
5526 {
5527   struct target_waitstatus last;
5528   ptid_t last_ptid;
5529   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
5530
5531   get_last_target_status (&last_ptid, &last);
5532
5533   /* If an exception is thrown from this point on, make sure to
5534      propagate GDB's knowledge of the executing state to the
5535      frontend/user running state.  A QUIT is an easy exception to see
5536      here, so do this before any filtered output.  */
5537   if (!non_stop)
5538     make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
5539   else if (last.kind != TARGET_WAITKIND_SIGNALLED
5540            && last.kind != TARGET_WAITKIND_EXITED)
5541     make_cleanup (finish_thread_state_cleanup, &inferior_ptid);
5542
5543   /* In non-stop mode, we don't want GDB to switch threads behind the
5544      user's back, to avoid races where the user is typing a command to
5545      apply to thread x, but GDB switches to thread y before the user
5546      finishes entering the command.  */
5547
5548   /* As with the notification of thread events, we want to delay
5549      notifying the user that we've switched thread context until
5550      the inferior actually stops.
5551
5552      There's no point in saying anything if the inferior has exited.
5553      Note that SIGNALLED here means "exited with a signal", not
5554      "received a signal".  */
5555   if (!non_stop
5556       && !ptid_equal (previous_inferior_ptid, inferior_ptid)
5557       && target_has_execution
5558       && last.kind != TARGET_WAITKIND_SIGNALLED
5559       && last.kind != TARGET_WAITKIND_EXITED)
5560     {
5561       target_terminal_ours_for_output ();
5562       printf_filtered (_("[Switching to %s]\n"),
5563                        target_pid_to_str (inferior_ptid));
5564       annotate_thread_changed ();
5565       previous_inferior_ptid = inferior_ptid;
5566     }
5567
5568   if (!breakpoints_always_inserted_mode () && target_has_execution)
5569     {
5570       if (remove_breakpoints ())
5571         {
5572           target_terminal_ours_for_output ();
5573           printf_filtered (_("\
5574 Cannot remove breakpoints because program is no longer writable.\n\
5575 Further execution is probably impossible.\n"));
5576         }
5577     }
5578
5579   /* If an auto-display called a function and that got a signal,
5580      delete that auto-display to avoid an infinite recursion.  */
5581
5582   if (stopped_by_random_signal)
5583     disable_current_display ();
5584
5585   /* Don't print a message if in the middle of doing a "step n"
5586      operation for n > 1 */
5587   if (target_has_execution
5588       && last.kind != TARGET_WAITKIND_SIGNALLED
5589       && last.kind != TARGET_WAITKIND_EXITED
5590       && inferior_thread ()->step_multi
5591       && inferior_thread ()->control.stop_step)
5592     goto done;
5593
5594   target_terminal_ours ();
5595
5596   /* Set the current source location.  This will also happen if we
5597      display the frame below, but the current SAL will be incorrect
5598      during a user hook-stop function.  */
5599   if (has_stack_frames () && !stop_stack_dummy)
5600     set_current_sal_from_frame (get_current_frame (), 1);
5601
5602   /* Let the user/frontend see the threads as stopped.  */
5603   do_cleanups (old_chain);
5604
5605   /* Look up the hook_stop and run it (CLI internally handles problem
5606      of stop_command's pre-hook not existing).  */
5607   if (stop_command)
5608     catch_errors (hook_stop_stub, stop_command,
5609                   "Error while running hook_stop:\n", RETURN_MASK_ALL);
5610
5611   if (!has_stack_frames ())
5612     goto done;
5613
5614   if (last.kind == TARGET_WAITKIND_SIGNALLED
5615       || last.kind == TARGET_WAITKIND_EXITED)
5616     goto done;
5617
5618   /* Select innermost stack frame - i.e., current frame is frame 0,
5619      and current location is based on that.
5620      Don't do this on return from a stack dummy routine,
5621      or if the program has exited. */
5622
5623   if (!stop_stack_dummy)
5624     {
5625       select_frame (get_current_frame ());
5626
5627       /* Print current location without a level number, if
5628          we have changed functions or hit a breakpoint.
5629          Print source line if we have one.
5630          bpstat_print() contains the logic deciding in detail
5631          what to print, based on the event(s) that just occurred. */
5632
5633       /* If --batch-silent is enabled then there's no need to print the current
5634          source location, and to try risks causing an error message about
5635          missing source files.  */
5636       if (stop_print_frame && !batch_silent)
5637         {
5638           int bpstat_ret;
5639           int source_flag;
5640           int do_frame_printing = 1;
5641           struct thread_info *tp = inferior_thread ();
5642
5643           bpstat_ret = bpstat_print (tp->control.stop_bpstat);
5644           switch (bpstat_ret)
5645             {
5646             case PRINT_UNKNOWN:
5647               /* If we had hit a shared library event breakpoint,
5648                  bpstat_print would print out this message.  If we hit
5649                  an OS-level shared library event, do the same
5650                  thing.  */
5651               if (last.kind == TARGET_WAITKIND_LOADED)
5652                 {
5653                   printf_filtered (_("Stopped due to shared library event\n"));
5654                   source_flag = SRC_LINE;       /* something bogus */
5655                   do_frame_printing = 0;
5656                   break;
5657                 }
5658
5659               /* FIXME: cagney/2002-12-01: Given that a frame ID does
5660                  (or should) carry around the function and does (or
5661                  should) use that when doing a frame comparison.  */
5662               if (tp->control.stop_step
5663                   && frame_id_eq (tp->control.step_frame_id,
5664                                   get_frame_id (get_current_frame ()))
5665                   && step_start_function == find_pc_function (stop_pc))
5666                 source_flag = SRC_LINE; /* finished step, just print source line */
5667               else
5668                 source_flag = SRC_AND_LOC;      /* print location and source line */
5669               break;
5670             case PRINT_SRC_AND_LOC:
5671               source_flag = SRC_AND_LOC;        /* print location and source line */
5672               break;
5673             case PRINT_SRC_ONLY:
5674               source_flag = SRC_LINE;
5675               break;
5676             case PRINT_NOTHING:
5677               source_flag = SRC_LINE;   /* something bogus */
5678               do_frame_printing = 0;
5679               break;
5680             default:
5681               internal_error (__FILE__, __LINE__, _("Unknown value."));
5682             }
5683
5684           /* The behavior of this routine with respect to the source
5685              flag is:
5686              SRC_LINE: Print only source line
5687              LOCATION: Print only location
5688              SRC_AND_LOC: Print location and source line */
5689           if (do_frame_printing)
5690             print_stack_frame (get_selected_frame (NULL), 0, source_flag);
5691
5692           /* Display the auto-display expressions.  */
5693           do_displays ();
5694         }
5695     }
5696
5697   /* Save the function value return registers, if we care.
5698      We might be about to restore their previous contents.  */
5699   if (inferior_thread ()->control.proceed_to_finish)
5700     {
5701       /* This should not be necessary.  */
5702       if (stop_registers)
5703         regcache_xfree (stop_registers);
5704
5705       /* NB: The copy goes through to the target picking up the value of
5706          all the registers.  */
5707       stop_registers = regcache_dup (get_current_regcache ());
5708     }
5709
5710   if (stop_stack_dummy == STOP_STACK_DUMMY)
5711     {
5712       /* Pop the empty frame that contains the stack dummy.
5713          This also restores inferior state prior to the call
5714          (struct infcall_suspend_state).  */
5715       struct frame_info *frame = get_current_frame ();
5716
5717       gdb_assert (get_frame_type (frame) == DUMMY_FRAME);
5718       frame_pop (frame);
5719       /* frame_pop() calls reinit_frame_cache as the last thing it does
5720          which means there's currently no selected frame.  We don't need
5721          to re-establish a selected frame if the dummy call returns normally,
5722          that will be done by restore_infcall_control_state.  However, we do have
5723          to handle the case where the dummy call is returning after being
5724          stopped (e.g. the dummy call previously hit a breakpoint).  We
5725          can't know which case we have so just always re-establish a
5726          selected frame here.  */
5727       select_frame (get_current_frame ());
5728     }
5729
5730 done:
5731   annotate_stopped ();
5732
5733   /* Suppress the stop observer if we're in the middle of:
5734
5735      - a step n (n > 1), as there still more steps to be done.
5736
5737      - a "finish" command, as the observer will be called in
5738        finish_command_continuation, so it can include the inferior
5739        function's return value.
5740
5741      - calling an inferior function, as we pretend we inferior didn't
5742        run at all.  The return value of the call is handled by the
5743        expression evaluator, through call_function_by_hand.  */
5744
5745   if (!target_has_execution
5746       || last.kind == TARGET_WAITKIND_SIGNALLED
5747       || last.kind == TARGET_WAITKIND_EXITED
5748       || (!inferior_thread ()->step_multi
5749           && !(inferior_thread ()->control.stop_bpstat
5750                && inferior_thread ()->control.proceed_to_finish)
5751           && !inferior_thread ()->control.in_infcall))
5752     {
5753       if (!ptid_equal (inferior_ptid, null_ptid))
5754         observer_notify_normal_stop (inferior_thread ()->control.stop_bpstat,
5755                                      stop_print_frame);
5756       else
5757         observer_notify_normal_stop (NULL, stop_print_frame);
5758     }
5759
5760   if (target_has_execution)
5761     {
5762       if (last.kind != TARGET_WAITKIND_SIGNALLED
5763           && last.kind != TARGET_WAITKIND_EXITED)
5764         /* Delete the breakpoint we stopped at, if it wants to be deleted.
5765            Delete any breakpoint that is to be deleted at the next stop.  */
5766         breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
5767     }
5768
5769   /* Try to get rid of automatically added inferiors that are no
5770      longer needed.  Keeping those around slows down things linearly.
5771      Note that this never removes the current inferior.  */
5772   prune_inferiors ();
5773 }
5774
5775 static int
5776 hook_stop_stub (void *cmd)
5777 {
5778   execute_cmd_pre_hook ((struct cmd_list_element *) cmd);
5779   return (0);
5780 }
5781 \f
5782 int
5783 signal_stop_state (int signo)
5784 {
5785   return signal_stop[signo];
5786 }
5787
5788 int
5789 signal_print_state (int signo)
5790 {
5791   return signal_print[signo];
5792 }
5793
5794 int
5795 signal_pass_state (int signo)
5796 {
5797   return signal_program[signo];
5798 }
5799
5800 int
5801 signal_stop_update (int signo, int state)
5802 {
5803   int ret = signal_stop[signo];
5804
5805   signal_stop[signo] = state;
5806   return ret;
5807 }
5808
5809 int
5810 signal_print_update (int signo, int state)
5811 {
5812   int ret = signal_print[signo];
5813
5814   signal_print[signo] = state;
5815   return ret;
5816 }
5817
5818 int
5819 signal_pass_update (int signo, int state)
5820 {
5821   int ret = signal_program[signo];
5822
5823   signal_program[signo] = state;
5824   return ret;
5825 }
5826
5827 static void
5828 sig_print_header (void)
5829 {
5830   printf_filtered (_("\
5831 Signal        Stop\tPrint\tPass to program\tDescription\n"));
5832 }
5833
5834 static void
5835 sig_print_info (enum target_signal oursig)
5836 {
5837   const char *name = target_signal_to_name (oursig);
5838   int name_padding = 13 - strlen (name);
5839
5840   if (name_padding <= 0)
5841     name_padding = 0;
5842
5843   printf_filtered ("%s", name);
5844   printf_filtered ("%*.*s ", name_padding, name_padding, "                 ");
5845   printf_filtered ("%s\t", signal_stop[oursig] ? "Yes" : "No");
5846   printf_filtered ("%s\t", signal_print[oursig] ? "Yes" : "No");
5847   printf_filtered ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
5848   printf_filtered ("%s\n", target_signal_to_string (oursig));
5849 }
5850
5851 /* Specify how various signals in the inferior should be handled.  */
5852
5853 static void
5854 handle_command (char *args, int from_tty)
5855 {
5856   char **argv;
5857   int digits, wordlen;
5858   int sigfirst, signum, siglast;
5859   enum target_signal oursig;
5860   int allsigs;
5861   int nsigs;
5862   unsigned char *sigs;
5863   struct cleanup *old_chain;
5864
5865   if (args == NULL)
5866     {
5867       error_no_arg (_("signal to handle"));
5868     }
5869
5870   /* Allocate and zero an array of flags for which signals to handle. */
5871
5872   nsigs = (int) TARGET_SIGNAL_LAST;
5873   sigs = (unsigned char *) alloca (nsigs);
5874   memset (sigs, 0, nsigs);
5875
5876   /* Break the command line up into args. */
5877
5878   argv = gdb_buildargv (args);
5879   old_chain = make_cleanup_freeargv (argv);
5880
5881   /* Walk through the args, looking for signal oursigs, signal names, and
5882      actions.  Signal numbers and signal names may be interspersed with
5883      actions, with the actions being performed for all signals cumulatively
5884      specified.  Signal ranges can be specified as <LOW>-<HIGH>. */
5885
5886   while (*argv != NULL)
5887     {
5888       wordlen = strlen (*argv);
5889       for (digits = 0; isdigit ((*argv)[digits]); digits++)
5890         {;
5891         }
5892       allsigs = 0;
5893       sigfirst = siglast = -1;
5894
5895       if (wordlen >= 1 && !strncmp (*argv, "all", wordlen))
5896         {
5897           /* Apply action to all signals except those used by the
5898              debugger.  Silently skip those. */
5899           allsigs = 1;
5900           sigfirst = 0;
5901           siglast = nsigs - 1;
5902         }
5903       else if (wordlen >= 1 && !strncmp (*argv, "stop", wordlen))
5904         {
5905           SET_SIGS (nsigs, sigs, signal_stop);
5906           SET_SIGS (nsigs, sigs, signal_print);
5907         }
5908       else if (wordlen >= 1 && !strncmp (*argv, "ignore", wordlen))
5909         {
5910           UNSET_SIGS (nsigs, sigs, signal_program);
5911         }
5912       else if (wordlen >= 2 && !strncmp (*argv, "print", wordlen))
5913         {
5914           SET_SIGS (nsigs, sigs, signal_print);
5915         }
5916       else if (wordlen >= 2 && !strncmp (*argv, "pass", wordlen))
5917         {
5918           SET_SIGS (nsigs, sigs, signal_program);
5919         }
5920       else if (wordlen >= 3 && !strncmp (*argv, "nostop", wordlen))
5921         {
5922           UNSET_SIGS (nsigs, sigs, signal_stop);
5923         }
5924       else if (wordlen >= 3 && !strncmp (*argv, "noignore", wordlen))
5925         {
5926           SET_SIGS (nsigs, sigs, signal_program);
5927         }
5928       else if (wordlen >= 4 && !strncmp (*argv, "noprint", wordlen))
5929         {
5930           UNSET_SIGS (nsigs, sigs, signal_print);
5931           UNSET_SIGS (nsigs, sigs, signal_stop);
5932         }
5933       else if (wordlen >= 4 && !strncmp (*argv, "nopass", wordlen))
5934         {
5935           UNSET_SIGS (nsigs, sigs, signal_program);
5936         }
5937       else if (digits > 0)
5938         {
5939           /* It is numeric.  The numeric signal refers to our own
5940              internal signal numbering from target.h, not to host/target
5941              signal  number.  This is a feature; users really should be
5942              using symbolic names anyway, and the common ones like
5943              SIGHUP, SIGINT, SIGALRM, etc. will work right anyway.  */
5944
5945           sigfirst = siglast = (int)
5946             target_signal_from_command (atoi (*argv));
5947           if ((*argv)[digits] == '-')
5948             {
5949               siglast = (int)
5950                 target_signal_from_command (atoi ((*argv) + digits + 1));
5951             }
5952           if (sigfirst > siglast)
5953             {
5954               /* Bet he didn't figure we'd think of this case... */
5955               signum = sigfirst;
5956               sigfirst = siglast;
5957               siglast = signum;
5958             }
5959         }
5960       else
5961         {
5962           oursig = target_signal_from_name (*argv);
5963           if (oursig != TARGET_SIGNAL_UNKNOWN)
5964             {
5965               sigfirst = siglast = (int) oursig;
5966             }
5967           else
5968             {
5969               /* Not a number and not a recognized flag word => complain.  */
5970               error (_("Unrecognized or ambiguous flag word: \"%s\"."), *argv);
5971             }
5972         }
5973
5974       /* If any signal numbers or symbol names were found, set flags for
5975          which signals to apply actions to. */
5976
5977       for (signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
5978         {
5979           switch ((enum target_signal) signum)
5980             {
5981             case TARGET_SIGNAL_TRAP:
5982             case TARGET_SIGNAL_INT:
5983               if (!allsigs && !sigs[signum])
5984                 {
5985                   if (query (_("%s is used by the debugger.\n\
5986 Are you sure you want to change it? "), target_signal_to_name ((enum target_signal) signum)))
5987                     {
5988                       sigs[signum] = 1;
5989                     }
5990                   else
5991                     {
5992                       printf_unfiltered (_("Not confirmed, unchanged.\n"));
5993                       gdb_flush (gdb_stdout);
5994                     }
5995                 }
5996               break;
5997             case TARGET_SIGNAL_0:
5998             case TARGET_SIGNAL_DEFAULT:
5999             case TARGET_SIGNAL_UNKNOWN:
6000               /* Make sure that "all" doesn't print these.  */
6001               break;
6002             default:
6003               sigs[signum] = 1;
6004               break;
6005             }
6006         }
6007
6008       argv++;
6009     }
6010
6011   for (signum = 0; signum < nsigs; signum++)
6012     if (sigs[signum])
6013       {
6014         target_notice_signals (inferior_ptid);
6015
6016         if (from_tty)
6017           {
6018             /* Show the results.  */
6019             sig_print_header ();
6020             for (; signum < nsigs; signum++)
6021               if (sigs[signum])
6022                 sig_print_info (signum);
6023           }
6024
6025         break;
6026       }
6027
6028   do_cleanups (old_chain);
6029 }
6030
6031 static void
6032 xdb_handle_command (char *args, int from_tty)
6033 {
6034   char **argv;
6035   struct cleanup *old_chain;
6036
6037   if (args == NULL)
6038     error_no_arg (_("xdb command"));
6039
6040   /* Break the command line up into args. */
6041
6042   argv = gdb_buildargv (args);
6043   old_chain = make_cleanup_freeargv (argv);
6044   if (argv[1] != (char *) NULL)
6045     {
6046       char *argBuf;
6047       int bufLen;
6048
6049       bufLen = strlen (argv[0]) + 20;
6050       argBuf = (char *) xmalloc (bufLen);
6051       if (argBuf)
6052         {
6053           int validFlag = 1;
6054           enum target_signal oursig;
6055
6056           oursig = target_signal_from_name (argv[0]);
6057           memset (argBuf, 0, bufLen);
6058           if (strcmp (argv[1], "Q") == 0)
6059             sprintf (argBuf, "%s %s", argv[0], "noprint");
6060           else
6061             {
6062               if (strcmp (argv[1], "s") == 0)
6063                 {
6064                   if (!signal_stop[oursig])
6065                     sprintf (argBuf, "%s %s", argv[0], "stop");
6066                   else
6067                     sprintf (argBuf, "%s %s", argv[0], "nostop");
6068                 }
6069               else if (strcmp (argv[1], "i") == 0)
6070                 {
6071                   if (!signal_program[oursig])
6072                     sprintf (argBuf, "%s %s", argv[0], "pass");
6073                   else
6074                     sprintf (argBuf, "%s %s", argv[0], "nopass");
6075                 }
6076               else if (strcmp (argv[1], "r") == 0)
6077                 {
6078                   if (!signal_print[oursig])
6079                     sprintf (argBuf, "%s %s", argv[0], "print");
6080                   else
6081                     sprintf (argBuf, "%s %s", argv[0], "noprint");
6082                 }
6083               else
6084                 validFlag = 0;
6085             }
6086           if (validFlag)
6087             handle_command (argBuf, from_tty);
6088           else
6089             printf_filtered (_("Invalid signal handling flag.\n"));
6090           if (argBuf)
6091             xfree (argBuf);
6092         }
6093     }
6094   do_cleanups (old_chain);
6095 }
6096
6097 /* Print current contents of the tables set by the handle command.
6098    It is possible we should just be printing signals actually used
6099    by the current target (but for things to work right when switching
6100    targets, all signals should be in the signal tables).  */
6101
6102 static void
6103 signals_info (char *signum_exp, int from_tty)
6104 {
6105   enum target_signal oursig;
6106
6107   sig_print_header ();
6108
6109   if (signum_exp)
6110     {
6111       /* First see if this is a symbol name.  */
6112       oursig = target_signal_from_name (signum_exp);
6113       if (oursig == TARGET_SIGNAL_UNKNOWN)
6114         {
6115           /* No, try numeric.  */
6116           oursig =
6117             target_signal_from_command (parse_and_eval_long (signum_exp));
6118         }
6119       sig_print_info (oursig);
6120       return;
6121     }
6122
6123   printf_filtered ("\n");
6124   /* These ugly casts brought to you by the native VAX compiler.  */
6125   for (oursig = TARGET_SIGNAL_FIRST;
6126        (int) oursig < (int) TARGET_SIGNAL_LAST;
6127        oursig = (enum target_signal) ((int) oursig + 1))
6128     {
6129       QUIT;
6130
6131       if (oursig != TARGET_SIGNAL_UNKNOWN
6132           && oursig != TARGET_SIGNAL_DEFAULT && oursig != TARGET_SIGNAL_0)
6133         sig_print_info (oursig);
6134     }
6135
6136   printf_filtered (_("\nUse the \"handle\" command to change these tables.\n"));
6137 }
6138
6139 /* The $_siginfo convenience variable is a bit special.  We don't know
6140    for sure the type of the value until we actually have a chance to
6141    fetch the data.  The type can change depending on gdbarch, so it it
6142    also dependent on which thread you have selected.
6143
6144      1. making $_siginfo be an internalvar that creates a new value on
6145      access.
6146
6147      2. making the value of $_siginfo be an lval_computed value.  */
6148
6149 /* This function implements the lval_computed support for reading a
6150    $_siginfo value.  */
6151
6152 static void
6153 siginfo_value_read (struct value *v)
6154 {
6155   LONGEST transferred;
6156
6157   transferred =
6158     target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO,
6159                  NULL,
6160                  value_contents_all_raw (v),
6161                  value_offset (v),
6162                  TYPE_LENGTH (value_type (v)));
6163
6164   if (transferred != TYPE_LENGTH (value_type (v)))
6165     error (_("Unable to read siginfo"));
6166 }
6167
6168 /* This function implements the lval_computed support for writing a
6169    $_siginfo value.  */
6170
6171 static void
6172 siginfo_value_write (struct value *v, struct value *fromval)
6173 {
6174   LONGEST transferred;
6175
6176   transferred = target_write (&current_target,
6177                               TARGET_OBJECT_SIGNAL_INFO,
6178                               NULL,
6179                               value_contents_all_raw (fromval),
6180                               value_offset (v),
6181                               TYPE_LENGTH (value_type (fromval)));
6182
6183   if (transferred != TYPE_LENGTH (value_type (fromval)))
6184     error (_("Unable to write siginfo"));
6185 }
6186
6187 static struct lval_funcs siginfo_value_funcs =
6188   {
6189     siginfo_value_read,
6190     siginfo_value_write
6191   };
6192
6193 /* Return a new value with the correct type for the siginfo object of
6194    the current thread using architecture GDBARCH.  Return a void value
6195    if there's no object available.  */
6196
6197 static struct value *
6198 siginfo_make_value (struct gdbarch *gdbarch, struct internalvar *var)
6199 {
6200   if (target_has_stack
6201       && !ptid_equal (inferior_ptid, null_ptid)
6202       && gdbarch_get_siginfo_type_p (gdbarch))
6203     {
6204       struct type *type = gdbarch_get_siginfo_type (gdbarch);
6205
6206       return allocate_computed_value (type, &siginfo_value_funcs, NULL);
6207     }
6208
6209   return allocate_value (builtin_type (gdbarch)->builtin_void);
6210 }
6211
6212 \f
6213 /* infcall_suspend_state contains state about the program itself like its
6214    registers and any signal it received when it last stopped.
6215    This state must be restored regardless of how the inferior function call
6216    ends (either successfully, or after it hits a breakpoint or signal)
6217    if the program is to properly continue where it left off.  */
6218
6219 struct infcall_suspend_state
6220 {
6221   struct thread_suspend_state thread_suspend;
6222   struct inferior_suspend_state inferior_suspend;
6223
6224   /* Other fields:  */
6225   CORE_ADDR stop_pc;
6226   struct regcache *registers;
6227
6228   /* Format of SIGINFO_DATA or NULL if it is not present.  */
6229   struct gdbarch *siginfo_gdbarch;
6230
6231   /* The inferior format depends on SIGINFO_GDBARCH and it has a length of
6232      TYPE_LENGTH (gdbarch_get_siginfo_type ()).  For different gdbarch the
6233      content would be invalid.  */
6234   gdb_byte *siginfo_data;
6235 };
6236
6237 struct infcall_suspend_state *
6238 save_infcall_suspend_state (void)
6239 {
6240   struct infcall_suspend_state *inf_state;
6241   struct thread_info *tp = inferior_thread ();
6242   struct inferior *inf = current_inferior ();
6243   struct regcache *regcache = get_current_regcache ();
6244   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6245   gdb_byte *siginfo_data = NULL;
6246
6247   if (gdbarch_get_siginfo_type_p (gdbarch))
6248     {
6249       struct type *type = gdbarch_get_siginfo_type (gdbarch);
6250       size_t len = TYPE_LENGTH (type);
6251       struct cleanup *back_to;
6252
6253       siginfo_data = xmalloc (len);
6254       back_to = make_cleanup (xfree, siginfo_data);
6255
6256       if (target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
6257                        siginfo_data, 0, len) == len)
6258         discard_cleanups (back_to);
6259       else
6260         {
6261           /* Errors ignored.  */
6262           do_cleanups (back_to);
6263           siginfo_data = NULL;
6264         }
6265     }
6266
6267   inf_state = XZALLOC (struct infcall_suspend_state);
6268
6269   if (siginfo_data)
6270     {
6271       inf_state->siginfo_gdbarch = gdbarch;
6272       inf_state->siginfo_data = siginfo_data;
6273     }
6274
6275   inf_state->thread_suspend = tp->suspend;
6276   inf_state->inferior_suspend = inf->suspend;
6277
6278   /* run_inferior_call will not use the signal due to its `proceed' call with
6279      TARGET_SIGNAL_0 anyway.  */
6280   tp->suspend.stop_signal = TARGET_SIGNAL_0;
6281
6282   inf_state->stop_pc = stop_pc;
6283
6284   inf_state->registers = regcache_dup (regcache);
6285
6286   return inf_state;
6287 }
6288
6289 /* Restore inferior session state to INF_STATE.  */
6290
6291 void
6292 restore_infcall_suspend_state (struct infcall_suspend_state *inf_state)
6293 {
6294   struct thread_info *tp = inferior_thread ();
6295   struct inferior *inf = current_inferior ();
6296   struct regcache *regcache = get_current_regcache ();
6297   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6298
6299   tp->suspend = inf_state->thread_suspend;
6300   inf->suspend = inf_state->inferior_suspend;
6301
6302   stop_pc = inf_state->stop_pc;
6303
6304   if (inf_state->siginfo_gdbarch == gdbarch)
6305     {
6306       struct type *type = gdbarch_get_siginfo_type (gdbarch);
6307       size_t len = TYPE_LENGTH (type);
6308
6309       /* Errors ignored.  */
6310       target_write (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
6311                     inf_state->siginfo_data, 0, len);
6312     }
6313
6314   /* The inferior can be gone if the user types "print exit(0)"
6315      (and perhaps other times).  */
6316   if (target_has_execution)
6317     /* NB: The register write goes through to the target.  */
6318     regcache_cpy (regcache, inf_state->registers);
6319
6320   discard_infcall_suspend_state (inf_state);
6321 }
6322
6323 static void
6324 do_restore_infcall_suspend_state_cleanup (void *state)
6325 {
6326   restore_infcall_suspend_state (state);
6327 }
6328
6329 struct cleanup *
6330 make_cleanup_restore_infcall_suspend_state
6331   (struct infcall_suspend_state *inf_state)
6332 {
6333   return make_cleanup (do_restore_infcall_suspend_state_cleanup, inf_state);
6334 }
6335
6336 void
6337 discard_infcall_suspend_state (struct infcall_suspend_state *inf_state)
6338 {
6339   regcache_xfree (inf_state->registers);
6340   xfree (inf_state->siginfo_data);
6341   xfree (inf_state);
6342 }
6343
6344 struct regcache *
6345 get_infcall_suspend_state_regcache (struct infcall_suspend_state *inf_state)
6346 {
6347   return inf_state->registers;
6348 }
6349
6350 /* infcall_control_state contains state regarding gdb's control of the
6351    inferior itself like stepping control.  It also contains session state like
6352    the user's currently selected frame.  */
6353
6354 struct infcall_control_state
6355 {
6356   struct thread_control_state thread_control;
6357   struct inferior_control_state inferior_control;
6358
6359   /* Other fields:  */
6360   enum stop_stack_kind stop_stack_dummy;
6361   int stopped_by_random_signal;
6362   int stop_after_trap;
6363
6364   /* ID if the selected frame when the inferior function call was made.  */
6365   struct frame_id selected_frame_id;
6366 };
6367
6368 /* Save all of the information associated with the inferior<==>gdb
6369    connection.  */
6370
6371 struct infcall_control_state *
6372 save_infcall_control_state (void)
6373 {
6374   struct infcall_control_state *inf_status = xmalloc (sizeof (*inf_status));
6375   struct thread_info *tp = inferior_thread ();
6376   struct inferior *inf = current_inferior ();
6377
6378   inf_status->thread_control = tp->control;
6379   inf_status->inferior_control = inf->control;
6380
6381   tp->control.step_resume_breakpoint = NULL;
6382
6383   /* Save original bpstat chain to INF_STATUS; replace it in TP with copy of
6384      chain.  If caller's caller is walking the chain, they'll be happier if we
6385      hand them back the original chain when restore_infcall_control_state is
6386      called.  */
6387   tp->control.stop_bpstat = bpstat_copy (tp->control.stop_bpstat);
6388
6389   /* Other fields:  */
6390   inf_status->stop_stack_dummy = stop_stack_dummy;
6391   inf_status->stopped_by_random_signal = stopped_by_random_signal;
6392   inf_status->stop_after_trap = stop_after_trap;
6393
6394   inf_status->selected_frame_id = get_frame_id (get_selected_frame (NULL));
6395
6396   return inf_status;
6397 }
6398
6399 static int
6400 restore_selected_frame (void *args)
6401 {
6402   struct frame_id *fid = (struct frame_id *) args;
6403   struct frame_info *frame;
6404
6405   frame = frame_find_by_id (*fid);
6406
6407   /* If inf_status->selected_frame_id is NULL, there was no previously
6408      selected frame.  */
6409   if (frame == NULL)
6410     {
6411       warning (_("Unable to restore previously selected frame."));
6412       return 0;
6413     }
6414
6415   select_frame (frame);
6416
6417   return (1);
6418 }
6419
6420 /* Restore inferior session state to INF_STATUS.  */
6421
6422 void
6423 restore_infcall_control_state (struct infcall_control_state *inf_status)
6424 {
6425   struct thread_info *tp = inferior_thread ();
6426   struct inferior *inf = current_inferior ();
6427
6428   if (tp->control.step_resume_breakpoint)
6429     tp->control.step_resume_breakpoint->disposition = disp_del_at_next_stop;
6430
6431   /* Handle the bpstat_copy of the chain.  */
6432   bpstat_clear (&tp->control.stop_bpstat);
6433
6434   tp->control = inf_status->thread_control;
6435   inf->control = inf_status->inferior_control;
6436
6437   /* Other fields:  */
6438   stop_stack_dummy = inf_status->stop_stack_dummy;
6439   stopped_by_random_signal = inf_status->stopped_by_random_signal;
6440   stop_after_trap = inf_status->stop_after_trap;
6441
6442   if (target_has_stack)
6443     {
6444       /* The point of catch_errors is that if the stack is clobbered,
6445          walking the stack might encounter a garbage pointer and
6446          error() trying to dereference it.  */
6447       if (catch_errors
6448           (restore_selected_frame, &inf_status->selected_frame_id,
6449            "Unable to restore previously selected frame:\n",
6450            RETURN_MASK_ERROR) == 0)
6451         /* Error in restoring the selected frame.  Select the innermost
6452            frame.  */
6453         select_frame (get_current_frame ());
6454     }
6455
6456   xfree (inf_status);
6457 }
6458
6459 static void
6460 do_restore_infcall_control_state_cleanup (void *sts)
6461 {
6462   restore_infcall_control_state (sts);
6463 }
6464
6465 struct cleanup *
6466 make_cleanup_restore_infcall_control_state
6467   (struct infcall_control_state *inf_status)
6468 {
6469   return make_cleanup (do_restore_infcall_control_state_cleanup, inf_status);
6470 }
6471
6472 void
6473 discard_infcall_control_state (struct infcall_control_state *inf_status)
6474 {
6475   if (inf_status->thread_control.step_resume_breakpoint)
6476     inf_status->thread_control.step_resume_breakpoint->disposition
6477       = disp_del_at_next_stop;
6478
6479   /* See save_infcall_control_state for info on stop_bpstat. */
6480   bpstat_clear (&inf_status->thread_control.stop_bpstat);
6481
6482   xfree (inf_status);
6483 }
6484 \f
6485 int
6486 inferior_has_forked (ptid_t pid, ptid_t *child_pid)
6487 {
6488   struct target_waitstatus last;
6489   ptid_t last_ptid;
6490
6491   get_last_target_status (&last_ptid, &last);
6492
6493   if (last.kind != TARGET_WAITKIND_FORKED)
6494     return 0;
6495
6496   if (!ptid_equal (last_ptid, pid))
6497     return 0;
6498
6499   *child_pid = last.value.related_pid;
6500   return 1;
6501 }
6502
6503 int
6504 inferior_has_vforked (ptid_t pid, ptid_t *child_pid)
6505 {
6506   struct target_waitstatus last;
6507   ptid_t last_ptid;
6508
6509   get_last_target_status (&last_ptid, &last);
6510
6511   if (last.kind != TARGET_WAITKIND_VFORKED)
6512     return 0;
6513
6514   if (!ptid_equal (last_ptid, pid))
6515     return 0;
6516
6517   *child_pid = last.value.related_pid;
6518   return 1;
6519 }
6520
6521 int
6522 inferior_has_execd (ptid_t pid, char **execd_pathname)
6523 {
6524   struct target_waitstatus last;
6525   ptid_t last_ptid;
6526
6527   get_last_target_status (&last_ptid, &last);
6528
6529   if (last.kind != TARGET_WAITKIND_EXECD)
6530     return 0;
6531
6532   if (!ptid_equal (last_ptid, pid))
6533     return 0;
6534
6535   *execd_pathname = xstrdup (last.value.execd_pathname);
6536   return 1;
6537 }
6538
6539 int
6540 inferior_has_called_syscall (ptid_t pid, int *syscall_number)
6541 {
6542   struct target_waitstatus last;
6543   ptid_t last_ptid;
6544
6545   get_last_target_status (&last_ptid, &last);
6546
6547   if (last.kind != TARGET_WAITKIND_SYSCALL_ENTRY &&
6548       last.kind != TARGET_WAITKIND_SYSCALL_RETURN)
6549     return 0;
6550
6551   if (!ptid_equal (last_ptid, pid))
6552     return 0;
6553
6554   *syscall_number = last.value.syscall_number;
6555   return 1;
6556 }
6557
6558 /* Oft used ptids */
6559 ptid_t null_ptid;
6560 ptid_t minus_one_ptid;
6561
6562 /* Create a ptid given the necessary PID, LWP, and TID components.  */
6563
6564 ptid_t
6565 ptid_build (int pid, long lwp, long tid)
6566 {
6567   ptid_t ptid;
6568
6569   ptid.pid = pid;
6570   ptid.lwp = lwp;
6571   ptid.tid = tid;
6572   return ptid;
6573 }
6574
6575 /* Create a ptid from just a pid.  */
6576
6577 ptid_t
6578 pid_to_ptid (int pid)
6579 {
6580   return ptid_build (pid, 0, 0);
6581 }
6582
6583 /* Fetch the pid (process id) component from a ptid.  */
6584
6585 int
6586 ptid_get_pid (ptid_t ptid)
6587 {
6588   return ptid.pid;
6589 }
6590
6591 /* Fetch the lwp (lightweight process) component from a ptid.  */
6592
6593 long
6594 ptid_get_lwp (ptid_t ptid)
6595 {
6596   return ptid.lwp;
6597 }
6598
6599 /* Fetch the tid (thread id) component from a ptid.  */
6600
6601 long
6602 ptid_get_tid (ptid_t ptid)
6603 {
6604   return ptid.tid;
6605 }
6606
6607 /* ptid_equal() is used to test equality of two ptids.  */
6608
6609 int
6610 ptid_equal (ptid_t ptid1, ptid_t ptid2)
6611 {
6612   return (ptid1.pid == ptid2.pid && ptid1.lwp == ptid2.lwp
6613           && ptid1.tid == ptid2.tid);
6614 }
6615
6616 /* Returns true if PTID represents a process.  */
6617
6618 int
6619 ptid_is_pid (ptid_t ptid)
6620 {
6621   if (ptid_equal (minus_one_ptid, ptid))
6622     return 0;
6623   if (ptid_equal (null_ptid, ptid))
6624     return 0;
6625
6626   return (ptid_get_lwp (ptid) == 0 && ptid_get_tid (ptid) == 0);
6627 }
6628
6629 int
6630 ptid_match (ptid_t ptid, ptid_t filter)
6631 {
6632   /* Since both parameters have the same type, prevent easy mistakes
6633      from happening.  */
6634   gdb_assert (!ptid_equal (ptid, minus_one_ptid)
6635               && !ptid_equal (ptid, null_ptid));
6636
6637   if (ptid_equal (filter, minus_one_ptid))
6638     return 1;
6639   if (ptid_is_pid (filter)
6640       && ptid_get_pid (ptid) == ptid_get_pid (filter))
6641     return 1;
6642   else if (ptid_equal (ptid, filter))
6643     return 1;
6644
6645   return 0;
6646 }
6647
6648 /* restore_inferior_ptid() will be used by the cleanup machinery
6649    to restore the inferior_ptid value saved in a call to
6650    save_inferior_ptid().  */
6651
6652 static void
6653 restore_inferior_ptid (void *arg)
6654 {
6655   ptid_t *saved_ptid_ptr = arg;
6656
6657   inferior_ptid = *saved_ptid_ptr;
6658   xfree (arg);
6659 }
6660
6661 /* Save the value of inferior_ptid so that it may be restored by a
6662    later call to do_cleanups().  Returns the struct cleanup pointer
6663    needed for later doing the cleanup.  */
6664
6665 struct cleanup *
6666 save_inferior_ptid (void)
6667 {
6668   ptid_t *saved_ptid_ptr;
6669
6670   saved_ptid_ptr = xmalloc (sizeof (ptid_t));
6671   *saved_ptid_ptr = inferior_ptid;
6672   return make_cleanup (restore_inferior_ptid, saved_ptid_ptr);
6673 }
6674 \f
6675
6676 /* User interface for reverse debugging:
6677    Set exec-direction / show exec-direction commands
6678    (returns error unless target implements to_set_exec_direction method).  */
6679
6680 enum exec_direction_kind execution_direction = EXEC_FORWARD;
6681 static const char exec_forward[] = "forward";
6682 static const char exec_reverse[] = "reverse";
6683 static const char *exec_direction = exec_forward;
6684 static const char *exec_direction_names[] = {
6685   exec_forward,
6686   exec_reverse,
6687   NULL
6688 };
6689
6690 static void
6691 set_exec_direction_func (char *args, int from_tty,
6692                          struct cmd_list_element *cmd)
6693 {
6694   if (target_can_execute_reverse)
6695     {
6696       if (!strcmp (exec_direction, exec_forward))
6697         execution_direction = EXEC_FORWARD;
6698       else if (!strcmp (exec_direction, exec_reverse))
6699         execution_direction = EXEC_REVERSE;
6700     }
6701   else
6702     {
6703       exec_direction = exec_forward;
6704       error (_("Target does not support this operation."));
6705     }
6706 }
6707
6708 static void
6709 show_exec_direction_func (struct ui_file *out, int from_tty,
6710                           struct cmd_list_element *cmd, const char *value)
6711 {
6712   switch (execution_direction) {
6713   case EXEC_FORWARD:
6714     fprintf_filtered (out, _("Forward.\n"));
6715     break;
6716   case EXEC_REVERSE:
6717     fprintf_filtered (out, _("Reverse.\n"));
6718     break;
6719   case EXEC_ERROR:
6720   default:
6721     fprintf_filtered (out, 
6722                       _("Forward (target `%s' does not support exec-direction).\n"),
6723                       target_shortname);
6724     break;
6725   }
6726 }
6727
6728 /* User interface for non-stop mode.  */
6729
6730 int non_stop = 0;
6731
6732 static void
6733 set_non_stop (char *args, int from_tty,
6734               struct cmd_list_element *c)
6735 {
6736   if (target_has_execution)
6737     {
6738       non_stop_1 = non_stop;
6739       error (_("Cannot change this setting while the inferior is running."));
6740     }
6741
6742   non_stop = non_stop_1;
6743 }
6744
6745 static void
6746 show_non_stop (struct ui_file *file, int from_tty,
6747                struct cmd_list_element *c, const char *value)
6748 {
6749   fprintf_filtered (file,
6750                     _("Controlling the inferior in non-stop mode is %s.\n"),
6751                     value);
6752 }
6753
6754 static void
6755 show_schedule_multiple (struct ui_file *file, int from_tty,
6756                         struct cmd_list_element *c, const char *value)
6757 {
6758   fprintf_filtered (file, _("\
6759 Resuming the execution of threads of all processes is %s.\n"), value);
6760 }
6761
6762 void
6763 _initialize_infrun (void)
6764 {
6765   int i;
6766   int numsigs;
6767
6768   add_info ("signals", signals_info, _("\
6769 What debugger does when program gets various signals.\n\
6770 Specify a signal as argument to print info on that signal only."));
6771   add_info_alias ("handle", "signals", 0);
6772
6773   add_com ("handle", class_run, handle_command, _("\
6774 Specify how to handle a signal.\n\
6775 Args are signals and actions to apply to those signals.\n\
6776 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
6777 from 1-15 are allowed for compatibility with old versions of GDB.\n\
6778 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
6779 The special arg \"all\" is recognized to mean all signals except those\n\
6780 used by the debugger, typically SIGTRAP and SIGINT.\n\
6781 Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
6782 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
6783 Stop means reenter debugger if this signal happens (implies print).\n\
6784 Print means print a message if this signal happens.\n\
6785 Pass means let program see this signal; otherwise program doesn't know.\n\
6786 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
6787 Pass and Stop may be combined."));
6788   if (xdb_commands)
6789     {
6790       add_com ("lz", class_info, signals_info, _("\
6791 What debugger does when program gets various signals.\n\
6792 Specify a signal as argument to print info on that signal only."));
6793       add_com ("z", class_run, xdb_handle_command, _("\
6794 Specify how to handle a signal.\n\
6795 Args are signals and actions to apply to those signals.\n\
6796 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
6797 from 1-15 are allowed for compatibility with old versions of GDB.\n\
6798 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
6799 The special arg \"all\" is recognized to mean all signals except those\n\
6800 used by the debugger, typically SIGTRAP and SIGINT.\n\
6801 Recognized actions include \"s\" (toggles between stop and nostop),\n\
6802 \"r\" (toggles between print and noprint), \"i\" (toggles between pass and \
6803 nopass), \"Q\" (noprint)\n\
6804 Stop means reenter debugger if this signal happens (implies print).\n\
6805 Print means print a message if this signal happens.\n\
6806 Pass means let program see this signal; otherwise program doesn't know.\n\
6807 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
6808 Pass and Stop may be combined."));
6809     }
6810
6811   if (!dbx_commands)
6812     stop_command = add_cmd ("stop", class_obscure,
6813                             not_just_help_class_command, _("\
6814 There is no `stop' command, but you can set a hook on `stop'.\n\
6815 This allows you to set a list of commands to be run each time execution\n\
6816 of the program stops."), &cmdlist);
6817
6818   add_setshow_zinteger_cmd ("infrun", class_maintenance, &debug_infrun, _("\
6819 Set inferior debugging."), _("\
6820 Show inferior debugging."), _("\
6821 When non-zero, inferior specific debugging is enabled."),
6822                             NULL,
6823                             show_debug_infrun,
6824                             &setdebuglist, &showdebuglist);
6825
6826   add_setshow_boolean_cmd ("displaced", class_maintenance, &debug_displaced, _("\
6827 Set displaced stepping debugging."), _("\
6828 Show displaced stepping debugging."), _("\
6829 When non-zero, displaced stepping specific debugging is enabled."),
6830                             NULL,
6831                             show_debug_displaced,
6832                             &setdebuglist, &showdebuglist);
6833
6834   add_setshow_boolean_cmd ("non-stop", no_class,
6835                            &non_stop_1, _("\
6836 Set whether gdb controls the inferior in non-stop mode."), _("\
6837 Show whether gdb controls the inferior in non-stop mode."), _("\
6838 When debugging a multi-threaded program and this setting is\n\
6839 off (the default, also called all-stop mode), when one thread stops\n\
6840 (for a breakpoint, watchpoint, exception, or similar events), GDB stops\n\
6841 all other threads in the program while you interact with the thread of\n\
6842 interest.  When you continue or step a thread, you can allow the other\n\
6843 threads to run, or have them remain stopped, but while you inspect any\n\
6844 thread's state, all threads stop.\n\
6845 \n\
6846 In non-stop mode, when one thread stops, other threads can continue\n\
6847 to run freely.  You'll be able to step each thread independently,\n\
6848 leave it stopped or free to run as needed."),
6849                            set_non_stop,
6850                            show_non_stop,
6851                            &setlist,
6852                            &showlist);
6853
6854   numsigs = (int) TARGET_SIGNAL_LAST;
6855   signal_stop = (unsigned char *) xmalloc (sizeof (signal_stop[0]) * numsigs);
6856   signal_print = (unsigned char *)
6857     xmalloc (sizeof (signal_print[0]) * numsigs);
6858   signal_program = (unsigned char *)
6859     xmalloc (sizeof (signal_program[0]) * numsigs);
6860   for (i = 0; i < numsigs; i++)
6861     {
6862       signal_stop[i] = 1;
6863       signal_print[i] = 1;
6864       signal_program[i] = 1;
6865     }
6866
6867   /* Signals caused by debugger's own actions
6868      should not be given to the program afterwards.  */
6869   signal_program[TARGET_SIGNAL_TRAP] = 0;
6870   signal_program[TARGET_SIGNAL_INT] = 0;
6871
6872   /* Signals that are not errors should not normally enter the debugger.  */
6873   signal_stop[TARGET_SIGNAL_ALRM] = 0;
6874   signal_print[TARGET_SIGNAL_ALRM] = 0;
6875   signal_stop[TARGET_SIGNAL_VTALRM] = 0;
6876   signal_print[TARGET_SIGNAL_VTALRM] = 0;
6877   signal_stop[TARGET_SIGNAL_PROF] = 0;
6878   signal_print[TARGET_SIGNAL_PROF] = 0;
6879   signal_stop[TARGET_SIGNAL_CHLD] = 0;
6880   signal_print[TARGET_SIGNAL_CHLD] = 0;
6881   signal_stop[TARGET_SIGNAL_IO] = 0;
6882   signal_print[TARGET_SIGNAL_IO] = 0;
6883   signal_stop[TARGET_SIGNAL_POLL] = 0;
6884   signal_print[TARGET_SIGNAL_POLL] = 0;
6885   signal_stop[TARGET_SIGNAL_URG] = 0;
6886   signal_print[TARGET_SIGNAL_URG] = 0;
6887   signal_stop[TARGET_SIGNAL_WINCH] = 0;
6888   signal_print[TARGET_SIGNAL_WINCH] = 0;
6889
6890   /* These signals are used internally by user-level thread
6891      implementations.  (See signal(5) on Solaris.)  Like the above
6892      signals, a healthy program receives and handles them as part of
6893      its normal operation.  */
6894   signal_stop[TARGET_SIGNAL_LWP] = 0;
6895   signal_print[TARGET_SIGNAL_LWP] = 0;
6896   signal_stop[TARGET_SIGNAL_WAITING] = 0;
6897   signal_print[TARGET_SIGNAL_WAITING] = 0;
6898   signal_stop[TARGET_SIGNAL_CANCEL] = 0;
6899   signal_print[TARGET_SIGNAL_CANCEL] = 0;
6900
6901   add_setshow_zinteger_cmd ("stop-on-solib-events", class_support,
6902                             &stop_on_solib_events, _("\
6903 Set stopping for shared library events."), _("\
6904 Show stopping for shared library events."), _("\
6905 If nonzero, gdb will give control to the user when the dynamic linker\n\
6906 notifies gdb of shared library events.  The most common event of interest\n\
6907 to the user would be loading/unloading of a new library."),
6908                             NULL,
6909                             show_stop_on_solib_events,
6910                             &setlist, &showlist);
6911
6912   add_setshow_enum_cmd ("follow-fork-mode", class_run,
6913                         follow_fork_mode_kind_names,
6914                         &follow_fork_mode_string, _("\
6915 Set debugger response to a program call of fork or vfork."), _("\
6916 Show debugger response to a program call of fork or vfork."), _("\
6917 A fork or vfork creates a new process.  follow-fork-mode can be:\n\
6918   parent  - the original process is debugged after a fork\n\
6919   child   - the new process is debugged after a fork\n\
6920 The unfollowed process will continue to run.\n\
6921 By default, the debugger will follow the parent process."),
6922                         NULL,
6923                         show_follow_fork_mode_string,
6924                         &setlist, &showlist);
6925
6926   add_setshow_enum_cmd ("follow-exec-mode", class_run,
6927                         follow_exec_mode_names,
6928                         &follow_exec_mode_string, _("\
6929 Set debugger response to a program call of exec."), _("\
6930 Show debugger response to a program call of exec."), _("\
6931 An exec call replaces the program image of a process.\n\
6932 \n\
6933 follow-exec-mode can be:\n\
6934 \n\
6935   new - the debugger creates a new inferior and rebinds the process\n\
6936 to this new inferior.  The program the process was running before\n\
6937 the exec call can be restarted afterwards by restarting the original\n\
6938 inferior.\n\
6939 \n\
6940   same - the debugger keeps the process bound to the same inferior.\n\
6941 The new executable image replaces the previous executable loaded in\n\
6942 the inferior.  Restarting the inferior after the exec call restarts\n\
6943 the executable the process was running after the exec call.\n\
6944 \n\
6945 By default, the debugger will use the same inferior."),
6946                         NULL,
6947                         show_follow_exec_mode_string,
6948                         &setlist, &showlist);
6949
6950   add_setshow_enum_cmd ("scheduler-locking", class_run, 
6951                         scheduler_enums, &scheduler_mode, _("\
6952 Set mode for locking scheduler during execution."), _("\
6953 Show mode for locking scheduler during execution."), _("\
6954 off  == no locking (threads may preempt at any time)\n\
6955 on   == full locking (no thread except the current thread may run)\n\
6956 step == scheduler locked during every single-step operation.\n\
6957         In this mode, no other thread may run during a step command.\n\
6958         Other threads may run while stepping over a function call ('next')."), 
6959                         set_schedlock_func,     /* traps on target vector */
6960                         show_scheduler_mode,
6961                         &setlist, &showlist);
6962
6963   add_setshow_boolean_cmd ("schedule-multiple", class_run, &sched_multi, _("\
6964 Set mode for resuming threads of all processes."), _("\
6965 Show mode for resuming threads of all processes."), _("\
6966 When on, execution commands (such as 'continue' or 'next') resume all\n\
6967 threads of all processes.  When off (which is the default), execution\n\
6968 commands only resume the threads of the current process.  The set of\n\
6969 threads that are resumed is further refined by the scheduler-locking\n\
6970 mode (see help set scheduler-locking)."),
6971                            NULL,
6972                            show_schedule_multiple,
6973                            &setlist, &showlist);
6974
6975   add_setshow_boolean_cmd ("step-mode", class_run, &step_stop_if_no_debug, _("\
6976 Set mode of the step operation."), _("\
6977 Show mode of the step operation."), _("\
6978 When set, doing a step over a function without debug line information\n\
6979 will stop at the first instruction of that function. Otherwise, the\n\
6980 function is skipped and the step command stops at a different source line."),
6981                            NULL,
6982                            show_step_stop_if_no_debug,
6983                            &setlist, &showlist);
6984
6985   add_setshow_enum_cmd ("displaced-stepping", class_run,
6986                         can_use_displaced_stepping_enum,
6987                         &can_use_displaced_stepping, _("\
6988 Set debugger's willingness to use displaced stepping."), _("\
6989 Show debugger's willingness to use displaced stepping."), _("\
6990 If on, gdb will use displaced stepping to step over breakpoints if it is\n\
6991 supported by the target architecture.  If off, gdb will not use displaced\n\
6992 stepping to step over breakpoints, even if such is supported by the target\n\
6993 architecture.  If auto (which is the default), gdb will use displaced stepping\n\
6994 if the target architecture supports it and non-stop mode is active, but will not\n\
6995 use it in all-stop mode (see help set non-stop)."),
6996                         NULL,
6997                         show_can_use_displaced_stepping,
6998                         &setlist, &showlist);
6999
7000   add_setshow_enum_cmd ("exec-direction", class_run, exec_direction_names,
7001                         &exec_direction, _("Set direction of execution.\n\
7002 Options are 'forward' or 'reverse'."),
7003                         _("Show direction of execution (forward/reverse)."),
7004                         _("Tells gdb whether to execute forward or backward."),
7005                         set_exec_direction_func, show_exec_direction_func,
7006                         &setlist, &showlist);
7007
7008   /* Set/show detach-on-fork: user-settable mode.  */
7009
7010   add_setshow_boolean_cmd ("detach-on-fork", class_run, &detach_fork, _("\
7011 Set whether gdb will detach the child of a fork."), _("\
7012 Show whether gdb will detach the child of a fork."), _("\
7013 Tells gdb whether to detach the child of a fork."),
7014                            NULL, NULL, &setlist, &showlist);
7015
7016   /* ptid initializations */
7017   null_ptid = ptid_build (0, 0, 0);
7018   minus_one_ptid = ptid_build (-1, 0, 0);
7019   inferior_ptid = null_ptid;
7020   target_last_wait_ptid = minus_one_ptid;
7021
7022   observer_attach_thread_ptid_changed (infrun_thread_ptid_changed);
7023   observer_attach_thread_stop_requested (infrun_thread_stop_requested);
7024   observer_attach_thread_exit (infrun_thread_thread_exit);
7025   observer_attach_inferior_exit (infrun_inferior_exit);
7026
7027   /* Explicitly create without lookup, since that tries to create a
7028      value with a void typed value, and when we get here, gdbarch
7029      isn't initialized yet.  At this point, we're quite sure there
7030      isn't another convenience variable of the same name.  */
7031   create_internalvar_type_lazy ("_siginfo", siginfo_make_value);
7032
7033   add_setshow_boolean_cmd ("observer", no_class,
7034                            &observer_mode_1, _("\
7035 Set whether gdb controls the inferior in observer mode."), _("\
7036 Show whether gdb controls the inferior in observer mode."), _("\
7037 In observer mode, GDB can get data from the inferior, but not\n\
7038 affect its execution.  Registers and memory may not be changed,\n\
7039 breakpoints may not be set, and the program cannot be interrupted\n\
7040 or signalled."),
7041                            set_observer_mode,
7042                            show_observer_mode,
7043                            &setlist,
7044                            &showlist);
7045 }
This page took 0.427038 seconds and 4 git commands to generate.