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