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