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