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