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