OSDN Git Service

gdb/
[pf3gnuchains/pf3gnuchains4x.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 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 "gdb_assert.h"
49 #include "mi/mi-common.h"
50 #include "event-top.h"
51
52 /* Prototypes for local functions */
53
54 static void signals_info (char *, int);
55
56 static void handle_command (char *, int);
57
58 static void sig_print_info (enum target_signal);
59
60 static void sig_print_header (void);
61
62 static void resume_cleanups (void *);
63
64 static int hook_stop_stub (void *);
65
66 static int restore_selected_frame (void *);
67
68 static void build_infrun (void);
69
70 static int follow_fork (void);
71
72 static void set_schedlock_func (char *args, int from_tty,
73                                 struct cmd_list_element *c);
74
75 static int currently_stepping (struct thread_info *tp);
76
77 static int currently_stepping_callback (struct thread_info *tp, void *data);
78
79 static void xdb_handle_command (char *args, int from_tty);
80
81 static int prepare_to_proceed (int);
82
83 void _initialize_infrun (void);
84
85 /* When set, stop the 'step' command if we enter a function which has
86    no line number information.  The normal behavior is that we step
87    over such function.  */
88 int step_stop_if_no_debug = 0;
89 static void
90 show_step_stop_if_no_debug (struct ui_file *file, int from_tty,
91                             struct cmd_list_element *c, const char *value)
92 {
93   fprintf_filtered (file, _("Mode of the step operation is %s.\n"), value);
94 }
95
96 /* In asynchronous mode, but simulating synchronous execution. */
97
98 int sync_execution = 0;
99
100 /* wait_for_inferior and normal_stop use this to notify the user
101    when the inferior stopped in a different thread than it had been
102    running in.  */
103
104 static ptid_t previous_inferior_ptid;
105
106 int debug_displaced = 0;
107 static void
108 show_debug_displaced (struct ui_file *file, int from_tty,
109                       struct cmd_list_element *c, const char *value)
110 {
111   fprintf_filtered (file, _("Displace stepping debugging is %s.\n"), value);
112 }
113
114 static int debug_infrun = 0;
115 static void
116 show_debug_infrun (struct ui_file *file, int from_tty,
117                    struct cmd_list_element *c, const char *value)
118 {
119   fprintf_filtered (file, _("Inferior debugging is %s.\n"), value);
120 }
121
122 /* If the program uses ELF-style shared libraries, then calls to
123    functions in shared libraries go through stubs, which live in a
124    table called the PLT (Procedure Linkage Table).  The first time the
125    function is called, the stub sends control to the dynamic linker,
126    which looks up the function's real address, patches the stub so
127    that future calls will go directly to the function, and then passes
128    control to the function.
129
130    If we are stepping at the source level, we don't want to see any of
131    this --- we just want to skip over the stub and the dynamic linker.
132    The simple approach is to single-step until control leaves the
133    dynamic linker.
134
135    However, on some systems (e.g., Red Hat's 5.2 distribution) the
136    dynamic linker calls functions in the shared C library, so you
137    can't tell from the PC alone whether the dynamic linker is still
138    running.  In this case, we use a step-resume breakpoint to get us
139    past the dynamic linker, as if we were using "next" to step over a
140    function call.
141
142    in_solib_dynsym_resolve_code() says whether we're in the dynamic
143    linker code or not.  Normally, this means we single-step.  However,
144    if SKIP_SOLIB_RESOLVER then returns non-zero, then its value is an
145    address where we can place a step-resume breakpoint to get past the
146    linker's symbol resolution function.
147
148    in_solib_dynsym_resolve_code() can generally be implemented in a
149    pretty portable way, by comparing the PC against the address ranges
150    of the dynamic linker's sections.
151
152    SKIP_SOLIB_RESOLVER is generally going to be system-specific, since
153    it depends on internal details of the dynamic linker.  It's usually
154    not too hard to figure out where to put a breakpoint, but it
155    certainly isn't portable.  SKIP_SOLIB_RESOLVER should do plenty of
156    sanity checking.  If it can't figure things out, returning zero and
157    getting the (possibly confusing) stepping behavior is better than
158    signalling an error, which will obscure the change in the
159    inferior's state.  */
160
161 /* This function returns TRUE if pc is the address of an instruction
162    that lies within the dynamic linker (such as the event hook, or the
163    dld itself).
164
165    This function must be used only when a dynamic linker event has
166    been caught, and the inferior is being stepped out of the hook, or
167    undefined results are guaranteed.  */
168
169 #ifndef SOLIB_IN_DYNAMIC_LINKER
170 #define SOLIB_IN_DYNAMIC_LINKER(pid,pc) 0
171 #endif
172
173
174 /* Convert the #defines into values.  This is temporary until wfi control
175    flow is completely sorted out.  */
176
177 #ifndef CANNOT_STEP_HW_WATCHPOINTS
178 #define CANNOT_STEP_HW_WATCHPOINTS 0
179 #else
180 #undef  CANNOT_STEP_HW_WATCHPOINTS
181 #define CANNOT_STEP_HW_WATCHPOINTS 1
182 #endif
183
184 /* Tables of how to react to signals; the user sets them.  */
185
186 static unsigned char *signal_stop;
187 static unsigned char *signal_print;
188 static unsigned char *signal_program;
189
190 #define SET_SIGS(nsigs,sigs,flags) \
191   do { \
192     int signum = (nsigs); \
193     while (signum-- > 0) \
194       if ((sigs)[signum]) \
195         (flags)[signum] = 1; \
196   } while (0)
197
198 #define UNSET_SIGS(nsigs,sigs,flags) \
199   do { \
200     int signum = (nsigs); \
201     while (signum-- > 0) \
202       if ((sigs)[signum]) \
203         (flags)[signum] = 0; \
204   } while (0)
205
206 /* Value to pass to target_resume() to cause all threads to resume */
207
208 #define RESUME_ALL (pid_to_ptid (-1))
209
210 /* Command list pointer for the "stop" placeholder.  */
211
212 static struct cmd_list_element *stop_command;
213
214 /* Function inferior was in as of last step command.  */
215
216 static struct symbol *step_start_function;
217
218 /* Nonzero if we want to give control to the user when we're notified
219    of shared library events by the dynamic linker.  */
220 static int stop_on_solib_events;
221 static void
222 show_stop_on_solib_events (struct ui_file *file, int from_tty,
223                            struct cmd_list_element *c, const char *value)
224 {
225   fprintf_filtered (file, _("Stopping for shared library events is %s.\n"),
226                     value);
227 }
228
229 /* Nonzero means expecting a trace trap
230    and should stop the inferior and return silently when it happens.  */
231
232 int stop_after_trap;
233
234 /* Save register contents here when executing a "finish" command or are
235    about to pop a stack dummy frame, if-and-only-if proceed_to_finish is set.
236    Thus this contains the return value from the called function (assuming
237    values are returned in a register).  */
238
239 struct regcache *stop_registers;
240
241 /* Nonzero after stop if current stack frame should be printed.  */
242
243 static int stop_print_frame;
244
245 /* This is a cached copy of the pid/waitstatus of the last event
246    returned by target_wait()/deprecated_target_wait_hook().  This
247    information is returned by get_last_target_status().  */
248 static ptid_t target_last_wait_ptid;
249 static struct target_waitstatus target_last_waitstatus;
250
251 static void context_switch (ptid_t ptid);
252
253 void init_thread_stepping_state (struct thread_info *tss);
254
255 void init_infwait_state (void);
256
257 /* This is used to remember when a fork, vfork or exec event
258    was caught by a catchpoint, and thus the event is to be
259    followed at the next resume of the inferior, and not
260    immediately. */
261 static struct
262 {
263   enum target_waitkind kind;
264   struct
265   {
266     ptid_t parent_pid;
267     ptid_t child_pid;
268   }
269   fork_event;
270   char *execd_pathname;
271 }
272 pending_follow;
273
274 static const char follow_fork_mode_child[] = "child";
275 static const char follow_fork_mode_parent[] = "parent";
276
277 static const char *follow_fork_mode_kind_names[] = {
278   follow_fork_mode_child,
279   follow_fork_mode_parent,
280   NULL
281 };
282
283 static const char *follow_fork_mode_string = follow_fork_mode_parent;
284 static void
285 show_follow_fork_mode_string (struct ui_file *file, int from_tty,
286                               struct cmd_list_element *c, const char *value)
287 {
288   fprintf_filtered (file, _("\
289 Debugger response to a program call of fork or vfork is \"%s\".\n"),
290                     value);
291 }
292 \f
293
294 static int
295 follow_fork (void)
296 {
297   int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
298
299   return target_follow_fork (follow_child);
300 }
301
302 void
303 follow_inferior_reset_breakpoints (void)
304 {
305   struct thread_info *tp = inferior_thread ();
306
307   /* Was there a step_resume breakpoint?  (There was if the user
308      did a "next" at the fork() call.)  If so, explicitly reset its
309      thread number.
310
311      step_resumes are a form of bp that are made to be per-thread.
312      Since we created the step_resume bp when the parent process
313      was being debugged, and now are switching to the child process,
314      from the breakpoint package's viewpoint, that's a switch of
315      "threads".  We must update the bp's notion of which thread
316      it is for, or it'll be ignored when it triggers.  */
317
318   if (tp->step_resume_breakpoint)
319     breakpoint_re_set_thread (tp->step_resume_breakpoint);
320
321   /* Reinsert all breakpoints in the child.  The user may have set
322      breakpoints after catching the fork, in which case those
323      were never set in the child, but only in the parent.  This makes
324      sure the inserted breakpoints match the breakpoint list.  */
325
326   breakpoint_re_set ();
327   insert_breakpoints ();
328 }
329
330 /* EXECD_PATHNAME is assumed to be non-NULL. */
331
332 static void
333 follow_exec (ptid_t pid, char *execd_pathname)
334 {
335   struct target_ops *tgt;
336   struct thread_info *th = inferior_thread ();
337
338   /* This is an exec event that we actually wish to pay attention to.
339      Refresh our symbol table to the newly exec'd program, remove any
340      momentary bp's, etc.
341
342      If there are breakpoints, they aren't really inserted now,
343      since the exec() transformed our inferior into a fresh set
344      of instructions.
345
346      We want to preserve symbolic breakpoints on the list, since
347      we have hopes that they can be reset after the new a.out's
348      symbol table is read.
349
350      However, any "raw" breakpoints must be removed from the list
351      (e.g., the solib bp's), since their address is probably invalid
352      now.
353
354      And, we DON'T want to call delete_breakpoints() here, since
355      that may write the bp's "shadow contents" (the instruction
356      value that was overwritten witha TRAP instruction).  Since
357      we now have a new a.out, those shadow contents aren't valid. */
358   update_breakpoints_after_exec ();
359
360   /* If there was one, it's gone now.  We cannot truly step-to-next
361      statement through an exec(). */
362   th->step_resume_breakpoint = NULL;
363   th->step_range_start = 0;
364   th->step_range_end = 0;
365
366   /* What is this a.out's name? */
367   printf_unfiltered (_("Executing new program: %s\n"), execd_pathname);
368
369   /* We've followed the inferior through an exec.  Therefore, the
370      inferior has essentially been killed & reborn. */
371
372   gdb_flush (gdb_stdout);
373
374   breakpoint_init_inferior (inf_execd);
375
376   if (gdb_sysroot && *gdb_sysroot)
377     {
378       char *name = alloca (strlen (gdb_sysroot)
379                             + strlen (execd_pathname)
380                             + 1);
381       strcpy (name, gdb_sysroot);
382       strcat (name, execd_pathname);
383       execd_pathname = name;
384     }
385
386   /* That a.out is now the one to use. */
387   exec_file_attach (execd_pathname, 0);
388
389   /* Reset the shared library package.  This ensures that we get a
390      shlib event when the child reaches "_start", at which point the
391      dld will have had a chance to initialize the child.  */
392   /* Also, loading a symbol file below may trigger symbol lookups, and
393      we don't want those to be satisfied by the libraries of the
394      previous incarnation of this process.  */
395   no_shared_libraries (NULL, 0);
396
397   /* Load the main file's symbols.  */
398   symbol_file_add_main (execd_pathname, 0);
399
400 #ifdef SOLIB_CREATE_INFERIOR_HOOK
401   SOLIB_CREATE_INFERIOR_HOOK (PIDGET (inferior_ptid));
402 #else
403   solib_create_inferior_hook ();
404 #endif
405
406   /* Reinsert all breakpoints.  (Those which were symbolic have
407      been reset to the proper address in the new a.out, thanks
408      to symbol_file_command...) */
409   insert_breakpoints ();
410
411   /* The next resume of this inferior should bring it to the shlib
412      startup breakpoints.  (If the user had also set bp's on
413      "main" from the old (parent) process, then they'll auto-
414      matically get reset there in the new process.) */
415 }
416
417 /* Non-zero if we just simulating a single-step.  This is needed
418    because we cannot remove the breakpoints in the inferior process
419    until after the `wait' in `wait_for_inferior'.  */
420 static int singlestep_breakpoints_inserted_p = 0;
421
422 /* The thread we inserted single-step breakpoints for.  */
423 static ptid_t singlestep_ptid;
424
425 /* PC when we started this single-step.  */
426 static CORE_ADDR singlestep_pc;
427
428 /* If another thread hit the singlestep breakpoint, we save the original
429    thread here so that we can resume single-stepping it later.  */
430 static ptid_t saved_singlestep_ptid;
431 static int stepping_past_singlestep_breakpoint;
432
433 /* If not equal to null_ptid, this means that after stepping over breakpoint
434    is finished, we need to switch to deferred_step_ptid, and step it.
435
436    The use case is when one thread has hit a breakpoint, and then the user 
437    has switched to another thread and issued 'step'. We need to step over
438    breakpoint in the thread which hit the breakpoint, but then continue
439    stepping the thread user has selected.  */
440 static ptid_t deferred_step_ptid;
441 \f
442 /* Displaced stepping.  */
443
444 /* In non-stop debugging mode, we must take special care to manage
445    breakpoints properly; in particular, the traditional strategy for
446    stepping a thread past a breakpoint it has hit is unsuitable.
447    'Displaced stepping' is a tactic for stepping one thread past a
448    breakpoint it has hit while ensuring that other threads running
449    concurrently will hit the breakpoint as they should.
450
451    The traditional way to step a thread T off a breakpoint in a
452    multi-threaded program in all-stop mode is as follows:
453
454    a0) Initially, all threads are stopped, and breakpoints are not
455        inserted.
456    a1) We single-step T, leaving breakpoints uninserted.
457    a2) We insert breakpoints, and resume all threads.
458
459    In non-stop debugging, however, this strategy is unsuitable: we
460    don't want to have to stop all threads in the system in order to
461    continue or step T past a breakpoint.  Instead, we use displaced
462    stepping:
463
464    n0) Initially, T is stopped, other threads are running, and
465        breakpoints are inserted.
466    n1) We copy the instruction "under" the breakpoint to a separate
467        location, outside the main code stream, making any adjustments
468        to the instruction, register, and memory state as directed by
469        T's architecture.
470    n2) We single-step T over the instruction at its new location.
471    n3) We adjust the resulting register and memory state as directed
472        by T's architecture.  This includes resetting T's PC to point
473        back into the main instruction stream.
474    n4) We resume T.
475
476    This approach depends on the following gdbarch methods:
477
478    - gdbarch_max_insn_length and gdbarch_displaced_step_location
479      indicate where to copy the instruction, and how much space must
480      be reserved there.  We use these in step n1.
481
482    - gdbarch_displaced_step_copy_insn copies a instruction to a new
483      address, and makes any necessary adjustments to the instruction,
484      register contents, and memory.  We use this in step n1.
485
486    - gdbarch_displaced_step_fixup adjusts registers and memory after
487      we have successfuly single-stepped the instruction, to yield the
488      same effect the instruction would have had if we had executed it
489      at its original address.  We use this in step n3.
490
491    - gdbarch_displaced_step_free_closure provides cleanup.
492
493    The gdbarch_displaced_step_copy_insn and
494    gdbarch_displaced_step_fixup functions must be written so that
495    copying an instruction with gdbarch_displaced_step_copy_insn,
496    single-stepping across the copied instruction, and then applying
497    gdbarch_displaced_insn_fixup should have the same effects on the
498    thread's memory and registers as stepping the instruction in place
499    would have.  Exactly which responsibilities fall to the copy and
500    which fall to the fixup is up to the author of those functions.
501
502    See the comments in gdbarch.sh for details.
503
504    Note that displaced stepping and software single-step cannot
505    currently be used in combination, although with some care I think
506    they could be made to.  Software single-step works by placing
507    breakpoints on all possible subsequent instructions; if the
508    displaced instruction is a PC-relative jump, those breakpoints
509    could fall in very strange places --- on pages that aren't
510    executable, or at addresses that are not proper instruction
511    boundaries.  (We do generally let other threads run while we wait
512    to hit the software single-step breakpoint, and they might
513    encounter such a corrupted instruction.)  One way to work around
514    this would be to have gdbarch_displaced_step_copy_insn fully
515    simulate the effect of PC-relative instructions (and return NULL)
516    on architectures that use software single-stepping.
517
518    In non-stop mode, we can have independent and simultaneous step
519    requests, so more than one thread may need to simultaneously step
520    over a breakpoint.  The current implementation assumes there is
521    only one scratch space per process.  In this case, we have to
522    serialize access to the scratch space.  If thread A wants to step
523    over a breakpoint, but we are currently waiting for some other
524    thread to complete a displaced step, we leave thread A stopped and
525    place it in the displaced_step_request_queue.  Whenever a displaced
526    step finishes, we pick the next thread in the queue and start a new
527    displaced step operation on it.  See displaced_step_prepare and
528    displaced_step_fixup for details.  */
529
530 /* If this is not null_ptid, this is the thread carrying out a
531    displaced single-step.  This thread's state will require fixing up
532    once it has completed its step.  */
533 static ptid_t displaced_step_ptid;
534
535 struct displaced_step_request
536 {
537   ptid_t ptid;
538   struct displaced_step_request *next;
539 };
540
541 /* A queue of pending displaced stepping requests.  */
542 struct displaced_step_request *displaced_step_request_queue;
543
544 /* The architecture the thread had when we stepped it.  */
545 static struct gdbarch *displaced_step_gdbarch;
546
547 /* The closure provided gdbarch_displaced_step_copy_insn, to be used
548    for post-step cleanup.  */
549 static struct displaced_step_closure *displaced_step_closure;
550
551 /* The address of the original instruction, and the copy we made.  */
552 static CORE_ADDR displaced_step_original, displaced_step_copy;
553
554 /* Saved contents of copy area.  */
555 static gdb_byte *displaced_step_saved_copy;
556
557 /* Enum strings for "set|show displaced-stepping".  */
558
559 static const char can_use_displaced_stepping_auto[] = "auto";
560 static const char can_use_displaced_stepping_on[] = "on";
561 static const char can_use_displaced_stepping_off[] = "off";
562 static const char *can_use_displaced_stepping_enum[] =
563 {
564   can_use_displaced_stepping_auto,
565   can_use_displaced_stepping_on,
566   can_use_displaced_stepping_off,
567   NULL,
568 };
569
570 /* If ON, and the architecture supports it, GDB will use displaced
571    stepping to step over breakpoints.  If OFF, or if the architecture
572    doesn't support it, GDB will instead use the traditional
573    hold-and-step approach.  If AUTO (which is the default), GDB will
574    decide which technique to use to step over breakpoints depending on
575    which of all-stop or non-stop mode is active --- displaced stepping
576    in non-stop mode; hold-and-step in all-stop mode.  */
577
578 static const char *can_use_displaced_stepping =
579   can_use_displaced_stepping_auto;
580
581 static void
582 show_can_use_displaced_stepping (struct ui_file *file, int from_tty,
583                                  struct cmd_list_element *c,
584                                  const char *value)
585 {
586   if (can_use_displaced_stepping == can_use_displaced_stepping_auto)
587     fprintf_filtered (file, _("\
588 Debugger's willingness to use displaced stepping to step over \
589 breakpoints is %s (currently %s).\n"),
590                       value, non_stop ? "on" : "off");
591   else
592     fprintf_filtered (file, _("\
593 Debugger's willingness to use displaced stepping to step over \
594 breakpoints is %s.\n"), value);
595 }
596
597 /* Return non-zero if displaced stepping can/should be used to step
598    over breakpoints.  */
599
600 static int
601 use_displaced_stepping (struct gdbarch *gdbarch)
602 {
603   return (((can_use_displaced_stepping == can_use_displaced_stepping_auto
604             && non_stop)
605            || can_use_displaced_stepping == can_use_displaced_stepping_on)
606           && gdbarch_displaced_step_copy_insn_p (gdbarch));
607 }
608
609 /* Clean out any stray displaced stepping state.  */
610 static void
611 displaced_step_clear (void)
612 {
613   /* Indicate that there is no cleanup pending.  */
614   displaced_step_ptid = null_ptid;
615
616   if (displaced_step_closure)
617     {
618       gdbarch_displaced_step_free_closure (displaced_step_gdbarch,
619                                            displaced_step_closure);
620       displaced_step_closure = NULL;
621     }
622 }
623
624 static void
625 cleanup_displaced_step_closure (void *ptr)
626 {
627   struct displaced_step_closure *closure = ptr;
628
629   gdbarch_displaced_step_free_closure (current_gdbarch, closure);
630 }
631
632 /* Dump LEN bytes at BUF in hex to FILE, followed by a newline.  */
633 void
634 displaced_step_dump_bytes (struct ui_file *file,
635                            const gdb_byte *buf,
636                            size_t len)
637 {
638   int i;
639
640   for (i = 0; i < len; i++)
641     fprintf_unfiltered (file, "%02x ", buf[i]);
642   fputs_unfiltered ("\n", file);
643 }
644
645 /* Prepare to single-step, using displaced stepping.
646
647    Note that we cannot use displaced stepping when we have a signal to
648    deliver.  If we have a signal to deliver and an instruction to step
649    over, then after the step, there will be no indication from the
650    target whether the thread entered a signal handler or ignored the
651    signal and stepped over the instruction successfully --- both cases
652    result in a simple SIGTRAP.  In the first case we mustn't do a
653    fixup, and in the second case we must --- but we can't tell which.
654    Comments in the code for 'random signals' in handle_inferior_event
655    explain how we handle this case instead.
656
657    Returns 1 if preparing was successful -- this thread is going to be
658    stepped now; or 0 if displaced stepping this thread got queued.  */
659 static int
660 displaced_step_prepare (ptid_t ptid)
661 {
662   struct cleanup *old_cleanups, *ignore_cleanups;
663   struct regcache *regcache = get_thread_regcache (ptid);
664   struct gdbarch *gdbarch = get_regcache_arch (regcache);
665   CORE_ADDR original, copy;
666   ULONGEST len;
667   struct displaced_step_closure *closure;
668
669   /* We should never reach this function if the architecture does not
670      support displaced stepping.  */
671   gdb_assert (gdbarch_displaced_step_copy_insn_p (gdbarch));
672
673   /* For the first cut, we're displaced stepping one thread at a
674      time.  */
675
676   if (!ptid_equal (displaced_step_ptid, null_ptid))
677     {
678       /* Already waiting for a displaced step to finish.  Defer this
679          request and place in queue.  */
680       struct displaced_step_request *req, *new_req;
681
682       if (debug_displaced)
683         fprintf_unfiltered (gdb_stdlog,
684                             "displaced: defering step of %s\n",
685                             target_pid_to_str (ptid));
686
687       new_req = xmalloc (sizeof (*new_req));
688       new_req->ptid = ptid;
689       new_req->next = NULL;
690
691       if (displaced_step_request_queue)
692         {
693           for (req = displaced_step_request_queue;
694                req && req->next;
695                req = req->next)
696             ;
697           req->next = new_req;
698         }
699       else
700         displaced_step_request_queue = new_req;
701
702       return 0;
703     }
704   else
705     {
706       if (debug_displaced)
707         fprintf_unfiltered (gdb_stdlog,
708                             "displaced: stepping %s now\n",
709                             target_pid_to_str (ptid));
710     }
711
712   displaced_step_clear ();
713
714   old_cleanups = save_inferior_ptid ();
715   inferior_ptid = ptid;
716
717   original = regcache_read_pc (regcache);
718
719   copy = gdbarch_displaced_step_location (gdbarch);
720   len = gdbarch_max_insn_length (gdbarch);
721
722   /* Save the original contents of the copy area.  */
723   displaced_step_saved_copy = xmalloc (len);
724   ignore_cleanups = make_cleanup (free_current_contents,
725                                   &displaced_step_saved_copy);
726   read_memory (copy, displaced_step_saved_copy, len);
727   if (debug_displaced)
728     {
729       fprintf_unfiltered (gdb_stdlog, "displaced: saved 0x%s: ",
730                           paddr_nz (copy));
731       displaced_step_dump_bytes (gdb_stdlog, displaced_step_saved_copy, len);
732     };
733
734   closure = gdbarch_displaced_step_copy_insn (gdbarch,
735                                               original, copy, regcache);
736
737   /* We don't support the fully-simulated case at present.  */
738   gdb_assert (closure);
739
740   make_cleanup (cleanup_displaced_step_closure, closure);
741
742   /* Resume execution at the copy.  */
743   regcache_write_pc (regcache, copy);
744
745   discard_cleanups (ignore_cleanups);
746
747   do_cleanups (old_cleanups);
748
749   if (debug_displaced)
750     fprintf_unfiltered (gdb_stdlog, "displaced: displaced pc to 0x%s\n",
751                         paddr_nz (copy));
752
753   /* Save the information we need to fix things up if the step
754      succeeds.  */
755   displaced_step_ptid = ptid;
756   displaced_step_gdbarch = gdbarch;
757   displaced_step_closure = closure;
758   displaced_step_original = original;
759   displaced_step_copy = copy;
760   return 1;
761 }
762
763 static void
764 displaced_step_clear_cleanup (void *ignore)
765 {
766   displaced_step_clear ();
767 }
768
769 static void
770 write_memory_ptid (ptid_t ptid, CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
771 {
772   struct cleanup *ptid_cleanup = save_inferior_ptid ();
773   inferior_ptid = ptid;
774   write_memory (memaddr, myaddr, len);
775   do_cleanups (ptid_cleanup);
776 }
777
778 static void
779 displaced_step_fixup (ptid_t event_ptid, enum target_signal signal)
780 {
781   struct cleanup *old_cleanups;
782
783   /* Was this event for the pid we displaced?  */
784   if (ptid_equal (displaced_step_ptid, null_ptid)
785       || ! ptid_equal (displaced_step_ptid, event_ptid))
786     return;
787
788   old_cleanups = make_cleanup (displaced_step_clear_cleanup, 0);
789
790   /* Restore the contents of the copy area.  */
791   {
792     ULONGEST len = gdbarch_max_insn_length (displaced_step_gdbarch);
793     write_memory_ptid (displaced_step_ptid, displaced_step_copy,
794                        displaced_step_saved_copy, len);
795     if (debug_displaced)
796       fprintf_unfiltered (gdb_stdlog, "displaced: restored 0x%s\n",
797                           paddr_nz (displaced_step_copy));
798   }
799
800   /* Did the instruction complete successfully?  */
801   if (signal == TARGET_SIGNAL_TRAP)
802     {
803       /* Fix up the resulting state.  */
804       gdbarch_displaced_step_fixup (displaced_step_gdbarch,
805                                     displaced_step_closure,
806                                     displaced_step_original,
807                                     displaced_step_copy,
808                                     get_thread_regcache (displaced_step_ptid));
809     }
810   else
811     {
812       /* Since the instruction didn't complete, all we can do is
813          relocate the PC.  */
814       struct regcache *regcache = get_thread_regcache (event_ptid);
815       CORE_ADDR pc = regcache_read_pc (regcache);
816       pc = displaced_step_original + (pc - displaced_step_copy);
817       regcache_write_pc (regcache, pc);
818     }
819
820   do_cleanups (old_cleanups);
821
822   displaced_step_ptid = null_ptid;
823
824   /* Are there any pending displaced stepping requests?  If so, run
825      one now.  */
826   while (displaced_step_request_queue)
827     {
828       struct displaced_step_request *head;
829       ptid_t ptid;
830       CORE_ADDR actual_pc;
831
832       head = displaced_step_request_queue;
833       ptid = head->ptid;
834       displaced_step_request_queue = head->next;
835       xfree (head);
836
837       context_switch (ptid);
838
839       actual_pc = read_pc ();
840
841       if (breakpoint_here_p (actual_pc))
842         {
843           if (debug_displaced)
844             fprintf_unfiltered (gdb_stdlog,
845                                 "displaced: stepping queued %s now\n",
846                                 target_pid_to_str (ptid));
847
848           displaced_step_prepare (ptid);
849
850           if (debug_displaced)
851             {
852               gdb_byte buf[4];
853
854               fprintf_unfiltered (gdb_stdlog, "displaced: run 0x%s: ",
855                                   paddr_nz (actual_pc));
856               read_memory (actual_pc, buf, sizeof (buf));
857               displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
858             }
859
860           target_resume (ptid, 1, TARGET_SIGNAL_0);
861
862           /* Done, we're stepping a thread.  */
863           break;
864         }
865       else
866         {
867           int step;
868           struct thread_info *tp = inferior_thread ();
869
870           /* The breakpoint we were sitting under has since been
871              removed.  */
872           tp->trap_expected = 0;
873
874           /* Go back to what we were trying to do.  */
875           step = currently_stepping (tp);
876
877           if (debug_displaced)
878             fprintf_unfiltered (gdb_stdlog, "breakpoint is gone %s: step(%d)\n",
879                                 target_pid_to_str (tp->ptid), step);
880
881           target_resume (ptid, step, TARGET_SIGNAL_0);
882           tp->stop_signal = TARGET_SIGNAL_0;
883
884           /* This request was discarded.  See if there's any other
885              thread waiting for its turn.  */
886         }
887     }
888 }
889
890 /* Update global variables holding ptids to hold NEW_PTID if they were
891    holding OLD_PTID.  */
892 static void
893 infrun_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
894 {
895   struct displaced_step_request *it;
896
897   if (ptid_equal (inferior_ptid, old_ptid))
898     inferior_ptid = new_ptid;
899
900   if (ptid_equal (singlestep_ptid, old_ptid))
901     singlestep_ptid = new_ptid;
902
903   if (ptid_equal (displaced_step_ptid, old_ptid))
904     displaced_step_ptid = new_ptid;
905
906   if (ptid_equal (deferred_step_ptid, old_ptid))
907     deferred_step_ptid = new_ptid;
908
909   for (it = displaced_step_request_queue; it; it = it->next)
910     if (ptid_equal (it->ptid, old_ptid))
911       it->ptid = new_ptid;
912 }
913
914 \f
915 /* Resuming.  */
916
917 /* Things to clean up if we QUIT out of resume ().  */
918 static void
919 resume_cleanups (void *ignore)
920 {
921   normal_stop ();
922 }
923
924 static const char schedlock_off[] = "off";
925 static const char schedlock_on[] = "on";
926 static const char schedlock_step[] = "step";
927 static const char *scheduler_enums[] = {
928   schedlock_off,
929   schedlock_on,
930   schedlock_step,
931   NULL
932 };
933 static const char *scheduler_mode = schedlock_off;
934 static void
935 show_scheduler_mode (struct ui_file *file, int from_tty,
936                      struct cmd_list_element *c, const char *value)
937 {
938   fprintf_filtered (file, _("\
939 Mode for locking scheduler during execution is \"%s\".\n"),
940                     value);
941 }
942
943 static void
944 set_schedlock_func (char *args, int from_tty, struct cmd_list_element *c)
945 {
946   if (!target_can_lock_scheduler)
947     {
948       scheduler_mode = schedlock_off;
949       error (_("Target '%s' cannot support this command."), target_shortname);
950     }
951 }
952
953
954 /* Resume the inferior, but allow a QUIT.  This is useful if the user
955    wants to interrupt some lengthy single-stepping operation
956    (for child processes, the SIGINT goes to the inferior, and so
957    we get a SIGINT random_signal, but for remote debugging and perhaps
958    other targets, that's not true).
959
960    STEP nonzero if we should step (zero to continue instead).
961    SIG is the signal to give the inferior (zero for none).  */
962 void
963 resume (int step, enum target_signal sig)
964 {
965   int should_resume = 1;
966   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
967
968   /* Note that these must be reset if we follow a fork below.  */
969   struct regcache *regcache = get_current_regcache ();
970   struct gdbarch *gdbarch = get_regcache_arch (regcache);
971   struct thread_info *tp = inferior_thread ();
972   CORE_ADDR pc = regcache_read_pc (regcache);
973
974   QUIT;
975
976   if (debug_infrun)
977     fprintf_unfiltered (gdb_stdlog,
978                         "infrun: resume (step=%d, signal=%d), "
979                         "trap_expected=%d\n",
980                         step, sig, tp->trap_expected);
981
982   /* Some targets (e.g. Solaris x86) have a kernel bug when stepping
983      over an instruction that causes a page fault without triggering
984      a hardware watchpoint. The kernel properly notices that it shouldn't
985      stop, because the hardware watchpoint is not triggered, but it forgets
986      the step request and continues the program normally.
987      Work around the problem by removing hardware watchpoints if a step is
988      requested, GDB will check for a hardware watchpoint trigger after the
989      step anyway.  */
990   if (CANNOT_STEP_HW_WATCHPOINTS && step)
991     remove_hw_watchpoints ();
992
993
994   /* Normally, by the time we reach `resume', the breakpoints are either
995      removed or inserted, as appropriate.  The exception is if we're sitting
996      at a permanent breakpoint; we need to step over it, but permanent
997      breakpoints can't be removed.  So we have to test for it here.  */
998   if (breakpoint_here_p (pc) == permanent_breakpoint_here)
999     {
1000       if (gdbarch_skip_permanent_breakpoint_p (gdbarch))
1001         gdbarch_skip_permanent_breakpoint (gdbarch, regcache);
1002       else
1003         error (_("\
1004 The program is stopped at a permanent breakpoint, but GDB does not know\n\
1005 how to step past a permanent breakpoint on this architecture.  Try using\n\
1006 a command like `return' or `jump' to continue execution."));
1007     }
1008
1009   /* If enabled, step over breakpoints by executing a copy of the
1010      instruction at a different address.
1011
1012      We can't use displaced stepping when we have a signal to deliver;
1013      the comments for displaced_step_prepare explain why.  The
1014      comments in the handle_inferior event for dealing with 'random
1015      signals' explain what we do instead.  */
1016   if (use_displaced_stepping (gdbarch)
1017       && tp->trap_expected
1018       && sig == TARGET_SIGNAL_0)
1019     {
1020       if (!displaced_step_prepare (inferior_ptid))
1021         {
1022           /* Got placed in displaced stepping queue.  Will be resumed
1023              later when all the currently queued displaced stepping
1024              requests finish.  The thread is not executing at this point,
1025              and the call to set_executing will be made later.  But we
1026              need to call set_running here, since from frontend point of view,
1027              the thread is running.  */
1028           set_running (inferior_ptid, 1);
1029           discard_cleanups (old_cleanups);
1030           return;
1031         }
1032     }
1033
1034   if (step && gdbarch_software_single_step_p (gdbarch))
1035     {
1036       /* Do it the hard way, w/temp breakpoints */
1037       if (gdbarch_software_single_step (gdbarch, get_current_frame ()))
1038         {
1039           /* ...and don't ask hardware to do it.  */
1040           step = 0;
1041           /* and do not pull these breakpoints until after a `wait' in
1042           `wait_for_inferior' */
1043           singlestep_breakpoints_inserted_p = 1;
1044           singlestep_ptid = inferior_ptid;
1045           singlestep_pc = pc;
1046         }
1047     }
1048
1049   /* If there were any forks/vforks/execs that were caught and are
1050      now to be followed, then do so.  */
1051   switch (pending_follow.kind)
1052     {
1053     case TARGET_WAITKIND_FORKED:
1054     case TARGET_WAITKIND_VFORKED:
1055       pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
1056       if (follow_fork ())
1057         should_resume = 0;
1058
1059       /* Following a child fork will change our notion of current
1060          thread.  */
1061       tp = inferior_thread ();
1062       regcache = get_current_regcache ();
1063       gdbarch = get_regcache_arch (regcache);
1064       pc = regcache_read_pc (regcache);
1065       break;
1066
1067     case TARGET_WAITKIND_EXECD:
1068       /* follow_exec is called as soon as the exec event is seen. */
1069       pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
1070       break;
1071
1072     default:
1073       break;
1074     }
1075
1076   /* Install inferior's terminal modes.  */
1077   target_terminal_inferior ();
1078
1079   if (should_resume)
1080     {
1081       ptid_t resume_ptid;
1082
1083       resume_ptid = RESUME_ALL; /* Default */
1084
1085       /* If STEP is set, it's a request to use hardware stepping
1086          facilities.  But in that case, we should never
1087          use singlestep breakpoint.  */
1088       gdb_assert (!(singlestep_breakpoints_inserted_p && step));
1089
1090       if (singlestep_breakpoints_inserted_p
1091           && stepping_past_singlestep_breakpoint)
1092         {
1093           /* The situation here is as follows.  In thread T1 we wanted to
1094              single-step.  Lacking hardware single-stepping we've
1095              set breakpoint at the PC of the next instruction -- call it
1096              P.  After resuming, we've hit that breakpoint in thread T2.
1097              Now we've removed original breakpoint, inserted breakpoint
1098              at P+1, and try to step to advance T2 past breakpoint.
1099              We need to step only T2, as if T1 is allowed to freely run,
1100              it can run past P, and if other threads are allowed to run,
1101              they can hit breakpoint at P+1, and nested hits of single-step
1102              breakpoints is not something we'd want -- that's complicated
1103              to support, and has no value.  */
1104           resume_ptid = inferior_ptid;
1105         }
1106
1107       if ((step || singlestep_breakpoints_inserted_p)
1108           && tp->trap_expected)
1109         {
1110           /* We're allowing a thread to run past a breakpoint it has
1111              hit, by single-stepping the thread with the breakpoint
1112              removed.  In which case, we need to single-step only this
1113              thread, and keep others stopped, as they can miss this
1114              breakpoint if allowed to run.
1115
1116              The current code actually removes all breakpoints when
1117              doing this, not just the one being stepped over, so if we
1118              let other threads run, we can actually miss any
1119              breakpoint, not just the one at PC.  */
1120           resume_ptid = inferior_ptid;
1121         }
1122
1123       if (non_stop)
1124         {
1125           /* With non-stop mode on, threads are always handled
1126              individually.  */
1127           resume_ptid = inferior_ptid;
1128         }
1129       else if ((scheduler_mode == schedlock_on)
1130                || (scheduler_mode == schedlock_step
1131                    && (step || singlestep_breakpoints_inserted_p)))
1132         {
1133           /* User-settable 'scheduler' mode requires solo thread resume. */
1134           resume_ptid = inferior_ptid;
1135         }
1136
1137       if (gdbarch_cannot_step_breakpoint (gdbarch))
1138         {
1139           /* Most targets can step a breakpoint instruction, thus
1140              executing it normally.  But if this one cannot, just
1141              continue and we will hit it anyway.  */
1142           if (step && breakpoint_inserted_here_p (pc))
1143             step = 0;
1144         }
1145
1146       if (debug_displaced
1147           && use_displaced_stepping (gdbarch)
1148           && tp->trap_expected)
1149         {
1150           struct regcache *resume_regcache = get_thread_regcache (resume_ptid);
1151           CORE_ADDR actual_pc = regcache_read_pc (resume_regcache);
1152           gdb_byte buf[4];
1153
1154           fprintf_unfiltered (gdb_stdlog, "displaced: run 0x%s: ",
1155                               paddr_nz (actual_pc));
1156           read_memory (actual_pc, buf, sizeof (buf));
1157           displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
1158         }
1159
1160       /* Avoid confusing the next resume, if the next stop/resume
1161          happens to apply to another thread.  */
1162       tp->stop_signal = TARGET_SIGNAL_0;
1163
1164       target_resume (resume_ptid, step, sig);
1165     }
1166
1167   discard_cleanups (old_cleanups);
1168 }
1169 \f
1170 /* Proceeding.  */
1171
1172 /* Clear out all variables saying what to do when inferior is continued.
1173    First do this, then set the ones you want, then call `proceed'.  */
1174
1175 static void
1176 clear_proceed_status_thread (struct thread_info *tp)
1177 {
1178   if (debug_infrun)
1179     fprintf_unfiltered (gdb_stdlog,
1180                         "infrun: clear_proceed_status_thread (%s)\n",
1181                         target_pid_to_str (tp->ptid));
1182
1183   tp->trap_expected = 0;
1184   tp->step_range_start = 0;
1185   tp->step_range_end = 0;
1186   tp->step_frame_id = null_frame_id;
1187   tp->step_over_calls = STEP_OVER_UNDEBUGGABLE;
1188   tp->stop_requested = 0;
1189
1190   tp->stop_step = 0;
1191
1192   tp->proceed_to_finish = 0;
1193
1194   /* Discard any remaining commands or status from previous stop.  */
1195   bpstat_clear (&tp->stop_bpstat);
1196 }
1197
1198 static int
1199 clear_proceed_status_callback (struct thread_info *tp, void *data)
1200 {
1201   if (is_exited (tp->ptid))
1202     return 0;
1203
1204   clear_proceed_status_thread (tp);
1205   return 0;
1206 }
1207
1208 void
1209 clear_proceed_status (void)
1210 {
1211   if (!ptid_equal (inferior_ptid, null_ptid))
1212     {
1213       struct inferior *inferior;
1214
1215       if (non_stop)
1216         {
1217           /* If in non-stop mode, only delete the per-thread status
1218              of the current thread.  */
1219           clear_proceed_status_thread (inferior_thread ());
1220         }
1221       else
1222         {
1223           /* In all-stop mode, delete the per-thread status of
1224              *all* threads.  */
1225           iterate_over_threads (clear_proceed_status_callback, NULL);
1226         }
1227   
1228       inferior = current_inferior ();
1229       inferior->stop_soon = NO_STOP_QUIETLY;
1230     }
1231
1232   stop_after_trap = 0;
1233   breakpoint_proceeded = 1;     /* We're about to proceed... */
1234
1235   if (stop_registers)
1236     {
1237       regcache_xfree (stop_registers);
1238       stop_registers = NULL;
1239     }
1240 }
1241
1242 /* This should be suitable for any targets that support threads. */
1243
1244 static int
1245 prepare_to_proceed (int step)
1246 {
1247   ptid_t wait_ptid;
1248   struct target_waitstatus wait_status;
1249
1250   /* Get the last target status returned by target_wait().  */
1251   get_last_target_status (&wait_ptid, &wait_status);
1252
1253   /* Make sure we were stopped at a breakpoint.  */
1254   if (wait_status.kind != TARGET_WAITKIND_STOPPED
1255       || wait_status.value.sig != TARGET_SIGNAL_TRAP)
1256     {
1257       return 0;
1258     }
1259
1260   /* Switched over from WAIT_PID.  */
1261   if (!ptid_equal (wait_ptid, minus_one_ptid)
1262       && !ptid_equal (inferior_ptid, wait_ptid))
1263     {
1264       struct regcache *regcache = get_thread_regcache (wait_ptid);
1265
1266       if (breakpoint_here_p (regcache_read_pc (regcache)))
1267         {
1268           /* If stepping, remember current thread to switch back to.  */
1269           if (step)
1270             deferred_step_ptid = inferior_ptid;
1271
1272           /* Switch back to WAIT_PID thread.  */
1273           switch_to_thread (wait_ptid);
1274
1275           /* We return 1 to indicate that there is a breakpoint here,
1276              so we need to step over it before continuing to avoid
1277              hitting it straight away. */
1278           return 1;
1279         }
1280     }
1281
1282   return 0;
1283 }
1284
1285 /* Basic routine for continuing the program in various fashions.
1286
1287    ADDR is the address to resume at, or -1 for resume where stopped.
1288    SIGGNAL is the signal to give it, or 0 for none,
1289    or -1 for act according to how it stopped.
1290    STEP is nonzero if should trap after one instruction.
1291    -1 means return after that and print nothing.
1292    You should probably set various step_... variables
1293    before calling here, if you are stepping.
1294
1295    You should call clear_proceed_status before calling proceed.  */
1296
1297 void
1298 proceed (CORE_ADDR addr, enum target_signal siggnal, int step)
1299 {
1300   struct regcache *regcache = get_current_regcache ();
1301   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1302   struct thread_info *tp;
1303   CORE_ADDR pc = regcache_read_pc (regcache);
1304   int oneproc = 0;
1305
1306   if (step > 0)
1307     step_start_function = find_pc_function (pc);
1308   if (step < 0)
1309     stop_after_trap = 1;
1310
1311   if (addr == (CORE_ADDR) -1)
1312     {
1313       if (pc == stop_pc && breakpoint_here_p (pc) 
1314           && execution_direction != EXEC_REVERSE)
1315         /* There is a breakpoint at the address we will resume at,
1316            step one instruction before inserting breakpoints so that
1317            we do not stop right away (and report a second hit at this
1318            breakpoint).
1319
1320            Note, we don't do this in reverse, because we won't
1321            actually be executing the breakpoint insn anyway.
1322            We'll be (un-)executing the previous instruction.  */
1323
1324         oneproc = 1;
1325       else if (gdbarch_single_step_through_delay_p (gdbarch)
1326                && gdbarch_single_step_through_delay (gdbarch,
1327                                                      get_current_frame ()))
1328         /* We stepped onto an instruction that needs to be stepped
1329            again before re-inserting the breakpoint, do so.  */
1330         oneproc = 1;
1331     }
1332   else
1333     {
1334       regcache_write_pc (regcache, addr);
1335     }
1336
1337   if (debug_infrun)
1338     fprintf_unfiltered (gdb_stdlog,
1339                         "infrun: proceed (addr=0x%s, signal=%d, step=%d)\n",
1340                         paddr_nz (addr), siggnal, step);
1341
1342   if (non_stop)
1343     /* In non-stop, each thread is handled individually.  The context
1344        must already be set to the right thread here.  */
1345     ;
1346   else
1347     {
1348       /* In a multi-threaded task we may select another thread and
1349          then continue or step.
1350
1351          But if the old thread was stopped at a breakpoint, it will
1352          immediately cause another breakpoint stop without any
1353          execution (i.e. it will report a breakpoint hit incorrectly).
1354          So we must step over it first.
1355
1356          prepare_to_proceed checks the current thread against the
1357          thread that reported the most recent event.  If a step-over
1358          is required it returns TRUE and sets the current thread to
1359          the old thread. */
1360       if (prepare_to_proceed (step))
1361         oneproc = 1;
1362     }
1363
1364   /* prepare_to_proceed may change the current thread.  */
1365   tp = inferior_thread ();
1366
1367   if (oneproc)
1368     {
1369       tp->trap_expected = 1;
1370       /* If displaced stepping is enabled, we can step over the
1371          breakpoint without hitting it, so leave all breakpoints
1372          inserted.  Otherwise we need to disable all breakpoints, step
1373          one instruction, and then re-add them when that step is
1374          finished.  */
1375       if (!use_displaced_stepping (gdbarch))
1376         remove_breakpoints ();
1377     }
1378
1379   /* We can insert breakpoints if we're not trying to step over one,
1380      or if we are stepping over one but we're using displaced stepping
1381      to do so.  */
1382   if (! tp->trap_expected || use_displaced_stepping (gdbarch))
1383     insert_breakpoints ();
1384
1385   if (!non_stop)
1386     {
1387       /* Pass the last stop signal to the thread we're resuming,
1388          irrespective of whether the current thread is the thread that
1389          got the last event or not.  This was historically GDB's
1390          behaviour before keeping a stop_signal per thread.  */
1391
1392       struct thread_info *last_thread;
1393       ptid_t last_ptid;
1394       struct target_waitstatus last_status;
1395
1396       get_last_target_status (&last_ptid, &last_status);
1397       if (!ptid_equal (inferior_ptid, last_ptid)
1398           && !ptid_equal (last_ptid, null_ptid)
1399           && !ptid_equal (last_ptid, minus_one_ptid))
1400         {
1401           last_thread = find_thread_pid (last_ptid);
1402           if (last_thread)
1403             {
1404               tp->stop_signal = last_thread->stop_signal;
1405               last_thread->stop_signal = TARGET_SIGNAL_0;
1406             }
1407         }
1408     }
1409
1410   if (siggnal != TARGET_SIGNAL_DEFAULT)
1411     tp->stop_signal = siggnal;
1412   /* If this signal should not be seen by program,
1413      give it zero.  Used for debugging signals.  */
1414   else if (!signal_program[tp->stop_signal])
1415     tp->stop_signal = TARGET_SIGNAL_0;
1416
1417   annotate_starting ();
1418
1419   /* Make sure that output from GDB appears before output from the
1420      inferior.  */
1421   gdb_flush (gdb_stdout);
1422
1423   /* Refresh prev_pc value just prior to resuming.  This used to be
1424      done in stop_stepping, however, setting prev_pc there did not handle
1425      scenarios such as inferior function calls or returning from
1426      a function via the return command.  In those cases, the prev_pc
1427      value was not set properly for subsequent commands.  The prev_pc value 
1428      is used to initialize the starting line number in the ecs.  With an 
1429      invalid value, the gdb next command ends up stopping at the position
1430      represented by the next line table entry past our start position.
1431      On platforms that generate one line table entry per line, this
1432      is not a problem.  However, on the ia64, the compiler generates
1433      extraneous line table entries that do not increase the line number.
1434      When we issue the gdb next command on the ia64 after an inferior call
1435      or a return command, we often end up a few instructions forward, still 
1436      within the original line we started.
1437
1438      An attempt was made to have init_execution_control_state () refresh
1439      the prev_pc value before calculating the line number.  This approach
1440      did not work because on platforms that use ptrace, the pc register
1441      cannot be read unless the inferior is stopped.  At that point, we
1442      are not guaranteed the inferior is stopped and so the regcache_read_pc ()
1443      call can fail.  Setting the prev_pc value here ensures the value is 
1444      updated correctly when the inferior is stopped.  */
1445   tp->prev_pc = regcache_read_pc (get_current_regcache ());
1446
1447   /* Fill in with reasonable starting values.  */
1448   init_thread_stepping_state (tp);
1449
1450   /* Reset to normal state.  */
1451   init_infwait_state ();
1452
1453   /* Resume inferior.  */
1454   resume (oneproc || step || bpstat_should_step (), tp->stop_signal);
1455
1456   /* Wait for it to stop (if not standalone)
1457      and in any case decode why it stopped, and act accordingly.  */
1458   /* Do this only if we are not using the event loop, or if the target
1459      does not support asynchronous execution. */
1460   if (!target_can_async_p ())
1461     {
1462       wait_for_inferior (0);
1463       normal_stop ();
1464     }
1465 }
1466 \f
1467
1468 /* Start remote-debugging of a machine over a serial link.  */
1469
1470 void
1471 start_remote (int from_tty)
1472 {
1473   struct inferior *inferior;
1474   init_wait_for_inferior ();
1475
1476   inferior = current_inferior ();
1477   inferior->stop_soon = STOP_QUIETLY_REMOTE;
1478
1479   /* Always go on waiting for the target, regardless of the mode. */
1480   /* FIXME: cagney/1999-09-23: At present it isn't possible to
1481      indicate to wait_for_inferior that a target should timeout if
1482      nothing is returned (instead of just blocking).  Because of this,
1483      targets expecting an immediate response need to, internally, set
1484      things up so that the target_wait() is forced to eventually
1485      timeout. */
1486   /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
1487      differentiate to its caller what the state of the target is after
1488      the initial open has been performed.  Here we're assuming that
1489      the target has stopped.  It should be possible to eventually have
1490      target_open() return to the caller an indication that the target
1491      is currently running and GDB state should be set to the same as
1492      for an async run. */
1493   wait_for_inferior (0);
1494
1495   /* Now that the inferior has stopped, do any bookkeeping like
1496      loading shared libraries.  We want to do this before normal_stop,
1497      so that the displayed frame is up to date.  */
1498   post_create_inferior (&current_target, from_tty);
1499
1500   normal_stop ();
1501 }
1502
1503 /* Initialize static vars when a new inferior begins.  */
1504
1505 void
1506 init_wait_for_inferior (void)
1507 {
1508   /* These are meaningless until the first time through wait_for_inferior.  */
1509
1510   breakpoint_init_inferior (inf_starting);
1511
1512   /* The first resume is not following a fork/vfork/exec. */
1513   pending_follow.kind = TARGET_WAITKIND_SPURIOUS;       /* I.e., none. */
1514
1515   clear_proceed_status ();
1516
1517   stepping_past_singlestep_breakpoint = 0;
1518   deferred_step_ptid = null_ptid;
1519
1520   target_last_wait_ptid = minus_one_ptid;
1521
1522   previous_inferior_ptid = null_ptid;
1523   init_infwait_state ();
1524
1525   displaced_step_clear ();
1526 }
1527
1528 \f
1529 /* This enum encodes possible reasons for doing a target_wait, so that
1530    wfi can call target_wait in one place.  (Ultimately the call will be
1531    moved out of the infinite loop entirely.) */
1532
1533 enum infwait_states
1534 {
1535   infwait_normal_state,
1536   infwait_thread_hop_state,
1537   infwait_step_watch_state,
1538   infwait_nonstep_watch_state
1539 };
1540
1541 /* Why did the inferior stop? Used to print the appropriate messages
1542    to the interface from within handle_inferior_event(). */
1543 enum inferior_stop_reason
1544 {
1545   /* Step, next, nexti, stepi finished. */
1546   END_STEPPING_RANGE,
1547   /* Inferior terminated by signal. */
1548   SIGNAL_EXITED,
1549   /* Inferior exited. */
1550   EXITED,
1551   /* Inferior received signal, and user asked to be notified. */
1552   SIGNAL_RECEIVED,
1553   /* Reverse execution -- target ran out of history info.  */
1554   NO_HISTORY
1555 };
1556
1557 /* The PTID we'll do a target_wait on.*/
1558 ptid_t waiton_ptid;
1559
1560 /* Current inferior wait state.  */
1561 enum infwait_states infwait_state;
1562
1563 /* Data to be passed around while handling an event.  This data is
1564    discarded between events.  */
1565 struct execution_control_state
1566 {
1567   ptid_t ptid;
1568   /* The thread that got the event, if this was a thread event; NULL
1569      otherwise.  */
1570   struct thread_info *event_thread;
1571
1572   struct target_waitstatus ws;
1573   int random_signal;
1574   CORE_ADDR stop_func_start;
1575   CORE_ADDR stop_func_end;
1576   char *stop_func_name;
1577   int new_thread_event;
1578   int wait_some_more;
1579 };
1580
1581 void init_execution_control_state (struct execution_control_state *ecs);
1582
1583 void handle_inferior_event (struct execution_control_state *ecs);
1584
1585 static void handle_step_into_function (struct execution_control_state *ecs);
1586 static void handle_step_into_function_backward (struct execution_control_state *ecs);
1587 static void insert_step_resume_breakpoint_at_frame (struct frame_info *step_frame);
1588 static void insert_step_resume_breakpoint_at_caller (struct frame_info *);
1589 static void insert_step_resume_breakpoint_at_sal (struct symtab_and_line sr_sal,
1590                                                   struct frame_id sr_id);
1591 static void insert_longjmp_resume_breakpoint (CORE_ADDR);
1592
1593 static void stop_stepping (struct execution_control_state *ecs);
1594 static void prepare_to_wait (struct execution_control_state *ecs);
1595 static void keep_going (struct execution_control_state *ecs);
1596 static void print_stop_reason (enum inferior_stop_reason stop_reason,
1597                                int stop_info);
1598
1599 /* Callback for iterate over threads.  If the thread is stopped, but
1600    the user/frontend doesn't know about that yet, go through
1601    normal_stop, as if the thread had just stopped now.  ARG points at
1602    a ptid.  If PTID is MINUS_ONE_PTID, applies to all threads.  If
1603    ptid_is_pid(PTID) is true, applies to all threads of the process
1604    pointed at by PTID.  Otherwise, apply only to the thread pointed by
1605    PTID.  */
1606
1607 static int
1608 infrun_thread_stop_requested_callback (struct thread_info *info, void *arg)
1609 {
1610   ptid_t ptid = * (ptid_t *) arg;
1611
1612   if ((ptid_equal (info->ptid, ptid)
1613        || ptid_equal (minus_one_ptid, ptid)
1614        || (ptid_is_pid (ptid)
1615            && ptid_get_pid (ptid) == ptid_get_pid (info->ptid)))
1616       && is_running (info->ptid)
1617       && !is_executing (info->ptid))
1618     {
1619       struct cleanup *old_chain;
1620       struct execution_control_state ecss;
1621       struct execution_control_state *ecs = &ecss;
1622
1623       memset (ecs, 0, sizeof (*ecs));
1624
1625       old_chain = make_cleanup_restore_current_thread ();
1626
1627       switch_to_thread (info->ptid);
1628
1629       /* Go through handle_inferior_event/normal_stop, so we always
1630          have consistent output as if the stop event had been
1631          reported.  */
1632       ecs->ptid = info->ptid;
1633       ecs->event_thread = find_thread_pid (info->ptid);
1634       ecs->ws.kind = TARGET_WAITKIND_STOPPED;
1635       ecs->ws.value.sig = TARGET_SIGNAL_0;
1636
1637       handle_inferior_event (ecs);
1638
1639       if (!ecs->wait_some_more)
1640         {
1641           struct thread_info *tp;
1642
1643           normal_stop ();
1644
1645           /* Finish off the continuations.  The continations
1646              themselves are responsible for realising the thread
1647              didn't finish what it was supposed to do.  */
1648           tp = inferior_thread ();
1649           do_all_intermediate_continuations_thread (tp);
1650           do_all_continuations_thread (tp);
1651         }
1652
1653       do_cleanups (old_chain);
1654     }
1655
1656   return 0;
1657 }
1658
1659 /* This function is attached as a "thread_stop_requested" observer.
1660    Cleanup local state that assumed the PTID was to be resumed, and
1661    report the stop to the frontend.  */
1662
1663 void
1664 infrun_thread_stop_requested (ptid_t ptid)
1665 {
1666   struct displaced_step_request *it, *next, *prev = NULL;
1667
1668   /* PTID was requested to stop.  Remove it from the displaced
1669      stepping queue, so we don't try to resume it automatically.  */
1670   for (it = displaced_step_request_queue; it; it = next)
1671     {
1672       next = it->next;
1673
1674       if (ptid_equal (it->ptid, ptid)
1675           || ptid_equal (minus_one_ptid, ptid)
1676           || (ptid_is_pid (ptid)
1677               && ptid_get_pid (ptid) == ptid_get_pid (it->ptid)))
1678         {
1679           if (displaced_step_request_queue == it)
1680             displaced_step_request_queue = it->next;
1681           else
1682             prev->next = it->next;
1683
1684           xfree (it);
1685         }
1686       else
1687         prev = it;
1688     }
1689
1690   iterate_over_threads (infrun_thread_stop_requested_callback, &ptid);
1691 }
1692
1693 /* Callback for iterate_over_threads.  */
1694
1695 static int
1696 delete_step_resume_breakpoint_callback (struct thread_info *info, void *data)
1697 {
1698   if (is_exited (info->ptid))
1699     return 0;
1700
1701   delete_step_resume_breakpoint (info);
1702   return 0;
1703 }
1704
1705 /* In all-stop, delete the step resume breakpoint of any thread that
1706    had one.  In non-stop, delete the step resume breakpoint of the
1707    thread that just stopped.  */
1708
1709 static void
1710 delete_step_thread_step_resume_breakpoint (void)
1711 {
1712   if (!target_has_execution
1713       || ptid_equal (inferior_ptid, null_ptid))
1714     /* If the inferior has exited, we have already deleted the step
1715        resume breakpoints out of GDB's lists.  */
1716     return;
1717
1718   if (non_stop)
1719     {
1720       /* If in non-stop mode, only delete the step-resume or
1721          longjmp-resume breakpoint of the thread that just stopped
1722          stepping.  */
1723       struct thread_info *tp = inferior_thread ();
1724       delete_step_resume_breakpoint (tp);
1725     }
1726   else
1727     /* In all-stop mode, delete all step-resume and longjmp-resume
1728        breakpoints of any thread that had them.  */
1729     iterate_over_threads (delete_step_resume_breakpoint_callback, NULL);
1730 }
1731
1732 /* A cleanup wrapper. */
1733
1734 static void
1735 delete_step_thread_step_resume_breakpoint_cleanup (void *arg)
1736 {
1737   delete_step_thread_step_resume_breakpoint ();
1738 }
1739
1740 /* Wait for control to return from inferior to debugger.
1741
1742    If TREAT_EXEC_AS_SIGTRAP is non-zero, then handle EXEC signals
1743    as if they were SIGTRAP signals.  This can be useful during
1744    the startup sequence on some targets such as HP/UX, where
1745    we receive an EXEC event instead of the expected SIGTRAP.
1746
1747    If inferior gets a signal, we may decide to start it up again
1748    instead of returning.  That is why there is a loop in this function.
1749    When this function actually returns it means the inferior
1750    should be left stopped and GDB should read more commands.  */
1751
1752 void
1753 wait_for_inferior (int treat_exec_as_sigtrap)
1754 {
1755   struct cleanup *old_cleanups;
1756   struct execution_control_state ecss;
1757   struct execution_control_state *ecs;
1758
1759   if (debug_infrun)
1760     fprintf_unfiltered
1761       (gdb_stdlog, "infrun: wait_for_inferior (treat_exec_as_sigtrap=%d)\n",
1762        treat_exec_as_sigtrap);
1763
1764   old_cleanups =
1765     make_cleanup (delete_step_thread_step_resume_breakpoint_cleanup, NULL);
1766
1767   ecs = &ecss;
1768   memset (ecs, 0, sizeof (*ecs));
1769
1770   overlay_cache_invalid = 1;
1771
1772   /* We'll update this if & when we switch to a new thread.  */
1773   previous_inferior_ptid = inferior_ptid;
1774
1775   /* We have to invalidate the registers BEFORE calling target_wait
1776      because they can be loaded from the target while in target_wait.
1777      This makes remote debugging a bit more efficient for those
1778      targets that provide critical registers as part of their normal
1779      status mechanism. */
1780
1781   registers_changed ();
1782
1783   while (1)
1784     {
1785       struct cleanup *old_chain;
1786
1787       if (deprecated_target_wait_hook)
1788         ecs->ptid = deprecated_target_wait_hook (waiton_ptid, &ecs->ws);
1789       else
1790         ecs->ptid = target_wait (waiton_ptid, &ecs->ws);
1791
1792       if (debug_infrun)
1793         {
1794           char *status_string = target_waitstatus_to_string (&ecs->ws);
1795           fprintf_unfiltered (gdb_stdlog,
1796                               "infrun: target_wait (%d, status) = %d, %s\n",
1797                               PIDGET (waiton_ptid), PIDGET (ecs->ptid),
1798                               status_string);
1799           xfree (status_string);
1800         }
1801
1802       if (treat_exec_as_sigtrap && ecs->ws.kind == TARGET_WAITKIND_EXECD)
1803         {
1804           xfree (ecs->ws.value.execd_pathname);
1805           ecs->ws.kind = TARGET_WAITKIND_STOPPED;
1806           ecs->ws.value.sig = TARGET_SIGNAL_TRAP;
1807         }
1808
1809       /* If an error happens while handling the event, propagate GDB's
1810          knowledge of the executing state to the frontend/user running
1811          state.  */
1812       old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
1813
1814       /* Now figure out what to do with the result of the result.  */
1815       handle_inferior_event (ecs);
1816
1817       /* No error, don't finish the state yet.  */
1818       discard_cleanups (old_chain);
1819
1820       if (!ecs->wait_some_more)
1821         break;
1822     }
1823
1824   do_cleanups (old_cleanups);
1825 }
1826
1827 /* Asynchronous version of wait_for_inferior. It is called by the
1828    event loop whenever a change of state is detected on the file
1829    descriptor corresponding to the target. It can be called more than
1830    once to complete a single execution command. In such cases we need
1831    to keep the state in a global variable ECSS. If it is the last time
1832    that this function is called for a single execution command, then
1833    report to the user that the inferior has stopped, and do the
1834    necessary cleanups. */
1835
1836 void
1837 fetch_inferior_event (void *client_data)
1838 {
1839   struct execution_control_state ecss;
1840   struct execution_control_state *ecs = &ecss;
1841   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
1842   struct cleanup *ts_old_chain;
1843   int was_sync = sync_execution;
1844
1845   memset (ecs, 0, sizeof (*ecs));
1846
1847   overlay_cache_invalid = 1;
1848
1849   /* We can only rely on wait_for_more being correct before handling
1850      the event in all-stop, but previous_inferior_ptid isn't used in
1851      non-stop.  */
1852   if (!ecs->wait_some_more)
1853     /* We'll update this if & when we switch to a new thread.  */
1854     previous_inferior_ptid = inferior_ptid;
1855
1856   if (non_stop)
1857     /* In non-stop mode, the user/frontend should not notice a thread
1858        switch due to internal events.  Make sure we reverse to the
1859        user selected thread and frame after handling the event and
1860        running any breakpoint commands.  */
1861     make_cleanup_restore_current_thread ();
1862
1863   /* We have to invalidate the registers BEFORE calling target_wait
1864      because they can be loaded from the target while in target_wait.
1865      This makes remote debugging a bit more efficient for those
1866      targets that provide critical registers as part of their normal
1867      status mechanism. */
1868
1869   registers_changed ();
1870
1871   if (deprecated_target_wait_hook)
1872     ecs->ptid =
1873       deprecated_target_wait_hook (waiton_ptid, &ecs->ws);
1874   else
1875     ecs->ptid = target_wait (waiton_ptid, &ecs->ws);
1876
1877   if (debug_infrun)
1878     {
1879       char *status_string = target_waitstatus_to_string (&ecs->ws);
1880       fprintf_unfiltered (gdb_stdlog,
1881                           "infrun: target_wait (%d, status) = %d, %s\n",
1882                           PIDGET (waiton_ptid), PIDGET (ecs->ptid),
1883                           status_string);
1884       xfree (status_string);
1885     }
1886
1887   if (non_stop
1888       && ecs->ws.kind != TARGET_WAITKIND_IGNORE
1889       && ecs->ws.kind != TARGET_WAITKIND_EXITED
1890       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
1891     /* In non-stop mode, each thread is handled individually.  Switch
1892        early, so the global state is set correctly for this
1893        thread.  */
1894     context_switch (ecs->ptid);
1895
1896   /* If an error happens while handling the event, propagate GDB's
1897      knowledge of the executing state to the frontend/user running
1898      state.  */
1899   if (!non_stop)
1900     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
1901   else
1902     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &ecs->ptid);
1903
1904   /* Now figure out what to do with the result of the result.  */
1905   handle_inferior_event (ecs);
1906
1907   if (!ecs->wait_some_more)
1908     {
1909       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
1910
1911       delete_step_thread_step_resume_breakpoint ();
1912
1913       /* We may not find an inferior if this was a process exit.  */
1914       if (inf == NULL || inf->stop_soon == NO_STOP_QUIETLY)
1915         normal_stop ();
1916
1917       if (target_has_execution
1918           && ecs->ws.kind != TARGET_WAITKIND_EXITED
1919           && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
1920           && ecs->event_thread->step_multi
1921           && ecs->event_thread->stop_step)
1922         inferior_event_handler (INF_EXEC_CONTINUE, NULL);
1923       else
1924         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
1925     }
1926
1927   /* No error, don't finish the thread states yet.  */
1928   discard_cleanups (ts_old_chain);
1929
1930   /* Revert thread and frame.  */
1931   do_cleanups (old_chain);
1932
1933   /* If the inferior was in sync execution mode, and now isn't,
1934      restore the prompt.  */
1935   if (was_sync && !sync_execution)
1936     display_gdb_prompt (0);
1937 }
1938
1939 /* Prepare an execution control state for looping through a
1940    wait_for_inferior-type loop.  */
1941
1942 void
1943 init_execution_control_state (struct execution_control_state *ecs)
1944 {
1945   ecs->random_signal = 0;
1946 }
1947
1948 /* Clear context switchable stepping state.  */
1949
1950 void
1951 init_thread_stepping_state (struct thread_info *tss)
1952 {
1953   struct symtab_and_line sal;
1954
1955   tss->stepping_over_breakpoint = 0;
1956   tss->step_after_step_resume_breakpoint = 0;
1957   tss->stepping_through_solib_after_catch = 0;
1958   tss->stepping_through_solib_catchpoints = NULL;
1959
1960   sal = find_pc_line (tss->prev_pc, 0);
1961   tss->current_line = sal.line;
1962   tss->current_symtab = sal.symtab;
1963 }
1964
1965 /* Return the cached copy of the last pid/waitstatus returned by
1966    target_wait()/deprecated_target_wait_hook().  The data is actually
1967    cached by handle_inferior_event(), which gets called immediately
1968    after target_wait()/deprecated_target_wait_hook().  */
1969
1970 void
1971 get_last_target_status (ptid_t *ptidp, struct target_waitstatus *status)
1972 {
1973   *ptidp = target_last_wait_ptid;
1974   *status = target_last_waitstatus;
1975 }
1976
1977 void
1978 nullify_last_target_wait_ptid (void)
1979 {
1980   target_last_wait_ptid = minus_one_ptid;
1981 }
1982
1983 /* Switch thread contexts.  */
1984
1985 static void
1986 context_switch (ptid_t ptid)
1987 {
1988   if (debug_infrun)
1989     {
1990       fprintf_unfiltered (gdb_stdlog, "infrun: Switching context from %s ",
1991                           target_pid_to_str (inferior_ptid));
1992       fprintf_unfiltered (gdb_stdlog, "to %s\n",
1993                           target_pid_to_str (ptid));
1994     }
1995
1996   switch_to_thread (ptid);
1997 }
1998
1999 static void
2000 adjust_pc_after_break (struct execution_control_state *ecs)
2001 {
2002   struct regcache *regcache;
2003   struct gdbarch *gdbarch;
2004   CORE_ADDR breakpoint_pc;
2005
2006   /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP.  If
2007      we aren't, just return.
2008
2009      We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
2010      affected by gdbarch_decr_pc_after_break.  Other waitkinds which are
2011      implemented by software breakpoints should be handled through the normal
2012      breakpoint layer.
2013
2014      NOTE drow/2004-01-31: On some targets, breakpoints may generate
2015      different signals (SIGILL or SIGEMT for instance), but it is less
2016      clear where the PC is pointing afterwards.  It may not match
2017      gdbarch_decr_pc_after_break.  I don't know any specific target that
2018      generates these signals at breakpoints (the code has been in GDB since at
2019      least 1992) so I can not guess how to handle them here.
2020
2021      In earlier versions of GDB, a target with 
2022      gdbarch_have_nonsteppable_watchpoint would have the PC after hitting a
2023      watchpoint affected by gdbarch_decr_pc_after_break.  I haven't found any
2024      target with both of these set in GDB history, and it seems unlikely to be
2025      correct, so gdbarch_have_nonsteppable_watchpoint is not checked here.  */
2026
2027   if (ecs->ws.kind != TARGET_WAITKIND_STOPPED)
2028     return;
2029
2030   if (ecs->ws.value.sig != TARGET_SIGNAL_TRAP)
2031     return;
2032
2033   /* In reverse execution, when a breakpoint is hit, the instruction
2034      under it has already been de-executed.  The reported PC always
2035      points at the breakpoint address, so adjusting it further would
2036      be wrong.  E.g., consider this case on a decr_pc_after_break == 1
2037      architecture:
2038
2039        B1         0x08000000 :   INSN1
2040        B2         0x08000001 :   INSN2
2041                   0x08000002 :   INSN3
2042             PC -> 0x08000003 :   INSN4
2043
2044      Say you're stopped at 0x08000003 as above.  Reverse continuing
2045      from that point should hit B2 as below.  Reading the PC when the
2046      SIGTRAP is reported should read 0x08000001 and INSN2 should have
2047      been de-executed already.
2048
2049        B1         0x08000000 :   INSN1
2050        B2   PC -> 0x08000001 :   INSN2
2051                   0x08000002 :   INSN3
2052                   0x08000003 :   INSN4
2053
2054      We can't apply the same logic as for forward execution, because
2055      we would wrongly adjust the PC to 0x08000000, since there's a
2056      breakpoint at PC - 1.  We'd then report a hit on B1, although
2057      INSN1 hadn't been de-executed yet.  Doing nothing is the correct
2058      behaviour.  */
2059   if (execution_direction == EXEC_REVERSE)
2060     return;
2061
2062   /* If this target does not decrement the PC after breakpoints, then
2063      we have nothing to do.  */
2064   regcache = get_thread_regcache (ecs->ptid);
2065   gdbarch = get_regcache_arch (regcache);
2066   if (gdbarch_decr_pc_after_break (gdbarch) == 0)
2067     return;
2068
2069   /* Find the location where (if we've hit a breakpoint) the
2070      breakpoint would be.  */
2071   breakpoint_pc = regcache_read_pc (regcache)
2072                   - gdbarch_decr_pc_after_break (gdbarch);
2073
2074   /* Check whether there actually is a software breakpoint inserted at
2075      that location.
2076
2077      If in non-stop mode, a race condition is possible where we've
2078      removed a breakpoint, but stop events for that breakpoint were
2079      already queued and arrive later.  To suppress those spurious
2080      SIGTRAPs, we keep a list of such breakpoint locations for a bit,
2081      and retire them after a number of stop events are reported.  */
2082   if (software_breakpoint_inserted_here_p (breakpoint_pc)
2083       || (non_stop && moribund_breakpoint_here_p (breakpoint_pc)))
2084     {
2085       /* When using hardware single-step, a SIGTRAP is reported for both
2086          a completed single-step and a software breakpoint.  Need to
2087          differentiate between the two, as the latter needs adjusting
2088          but the former does not.
2089
2090          The SIGTRAP can be due to a completed hardware single-step only if 
2091           - we didn't insert software single-step breakpoints
2092           - the thread to be examined is still the current thread
2093           - this thread is currently being stepped
2094
2095          If any of these events did not occur, we must have stopped due
2096          to hitting a software breakpoint, and have to back up to the
2097          breakpoint address.
2098
2099          As a special case, we could have hardware single-stepped a
2100          software breakpoint.  In this case (prev_pc == breakpoint_pc),
2101          we also need to back up to the breakpoint address.  */
2102
2103       if (singlestep_breakpoints_inserted_p
2104           || !ptid_equal (ecs->ptid, inferior_ptid)
2105           || !currently_stepping (ecs->event_thread)
2106           || ecs->event_thread->prev_pc == breakpoint_pc)
2107         regcache_write_pc (regcache, breakpoint_pc);
2108     }
2109 }
2110
2111 void
2112 init_infwait_state (void)
2113 {
2114   waiton_ptid = pid_to_ptid (-1);
2115   infwait_state = infwait_normal_state;
2116 }
2117
2118 void
2119 error_is_running (void)
2120 {
2121   error (_("\
2122 Cannot execute this command while the selected thread is running."));
2123 }
2124
2125 void
2126 ensure_not_running (void)
2127 {
2128   if (is_running (inferior_ptid))
2129     error_is_running ();
2130 }
2131
2132 /* Given an execution control state that has been freshly filled in
2133    by an event from the inferior, figure out what it means and take
2134    appropriate action.  */
2135
2136 void
2137 handle_inferior_event (struct execution_control_state *ecs)
2138 {
2139   int sw_single_step_trap_p = 0;
2140   int stopped_by_watchpoint;
2141   int stepped_after_stopped_by_watchpoint = 0;
2142   struct symtab_and_line stop_pc_sal;
2143   enum stop_kind stop_soon;
2144
2145   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
2146       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
2147       && ecs->ws.kind != TARGET_WAITKIND_IGNORE)
2148     {
2149       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
2150       gdb_assert (inf);
2151       stop_soon = inf->stop_soon;
2152     }
2153   else
2154     stop_soon = NO_STOP_QUIETLY;
2155
2156   /* Cache the last pid/waitstatus. */
2157   target_last_wait_ptid = ecs->ptid;
2158   target_last_waitstatus = ecs->ws;
2159
2160   /* Always clear state belonging to the previous time we stopped.  */
2161   stop_stack_dummy = 0;
2162
2163   /* If it's a new process, add it to the thread database */
2164
2165   ecs->new_thread_event = (!ptid_equal (ecs->ptid, inferior_ptid)
2166                            && !ptid_equal (ecs->ptid, minus_one_ptid)
2167                            && !in_thread_list (ecs->ptid));
2168
2169   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
2170       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED && ecs->new_thread_event)
2171     add_thread (ecs->ptid);
2172
2173   ecs->event_thread = find_thread_pid (ecs->ptid);
2174
2175   /* Dependent on valid ECS->EVENT_THREAD.  */
2176   adjust_pc_after_break (ecs);
2177
2178   /* Dependent on the current PC value modified by adjust_pc_after_break.  */
2179   reinit_frame_cache ();
2180
2181   if (ecs->ws.kind != TARGET_WAITKIND_IGNORE)
2182     {
2183       breakpoint_retire_moribund ();
2184
2185       /* Mark the non-executing threads accordingly.  In all-stop, all
2186          threads of all processes are stopped when we get any event
2187          reported.  In non-stop mode, only the event thread stops.  If
2188          we're handling a process exit in non-stop mode, there's
2189          nothing to do, as threads of the dead process are gone, and
2190          threads of any other process were left running.  */
2191       if (!non_stop)
2192         set_executing (minus_one_ptid, 0);
2193       else if (ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
2194                && ecs->ws.kind != TARGET_WAITKIND_EXITED)
2195         set_executing (inferior_ptid, 0);
2196     }
2197
2198   switch (infwait_state)
2199     {
2200     case infwait_thread_hop_state:
2201       if (debug_infrun)
2202         fprintf_unfiltered (gdb_stdlog, "infrun: infwait_thread_hop_state\n");
2203       /* Cancel the waiton_ptid. */
2204       waiton_ptid = pid_to_ptid (-1);
2205       break;
2206
2207     case infwait_normal_state:
2208       if (debug_infrun)
2209         fprintf_unfiltered (gdb_stdlog, "infrun: infwait_normal_state\n");
2210       break;
2211
2212     case infwait_step_watch_state:
2213       if (debug_infrun)
2214         fprintf_unfiltered (gdb_stdlog,
2215                             "infrun: infwait_step_watch_state\n");
2216
2217       stepped_after_stopped_by_watchpoint = 1;
2218       break;
2219
2220     case infwait_nonstep_watch_state:
2221       if (debug_infrun)
2222         fprintf_unfiltered (gdb_stdlog,
2223                             "infrun: infwait_nonstep_watch_state\n");
2224       insert_breakpoints ();
2225
2226       /* FIXME-maybe: is this cleaner than setting a flag?  Does it
2227          handle things like signals arriving and other things happening
2228          in combination correctly?  */
2229       stepped_after_stopped_by_watchpoint = 1;
2230       break;
2231
2232     default:
2233       internal_error (__FILE__, __LINE__, _("bad switch"));
2234     }
2235   infwait_state = infwait_normal_state;
2236
2237   switch (ecs->ws.kind)
2238     {
2239     case TARGET_WAITKIND_LOADED:
2240       if (debug_infrun)
2241         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_LOADED\n");
2242       /* Ignore gracefully during startup of the inferior, as it might
2243          be the shell which has just loaded some objects, otherwise
2244          add the symbols for the newly loaded objects.  Also ignore at
2245          the beginning of an attach or remote session; we will query
2246          the full list of libraries once the connection is
2247          established.  */
2248       if (stop_soon == NO_STOP_QUIETLY)
2249         {
2250           /* Check for any newly added shared libraries if we're
2251              supposed to be adding them automatically.  Switch
2252              terminal for any messages produced by
2253              breakpoint_re_set.  */
2254           target_terminal_ours_for_output ();
2255           /* NOTE: cagney/2003-11-25: Make certain that the target
2256              stack's section table is kept up-to-date.  Architectures,
2257              (e.g., PPC64), use the section table to perform
2258              operations such as address => section name and hence
2259              require the table to contain all sections (including
2260              those found in shared libraries).  */
2261           /* NOTE: cagney/2003-11-25: Pass current_target and not
2262              exec_ops to SOLIB_ADD.  This is because current GDB is
2263              only tooled to propagate section_table changes out from
2264              the "current_target" (see target_resize_to_sections), and
2265              not up from the exec stratum.  This, of course, isn't
2266              right.  "infrun.c" should only interact with the
2267              exec/process stratum, instead relying on the target stack
2268              to propagate relevant changes (stop, section table
2269              changed, ...) up to other layers.  */
2270 #ifdef SOLIB_ADD
2271           SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
2272 #else
2273           solib_add (NULL, 0, &current_target, auto_solib_add);
2274 #endif
2275           target_terminal_inferior ();
2276
2277           /* If requested, stop when the dynamic linker notifies
2278              gdb of events.  This allows the user to get control
2279              and place breakpoints in initializer routines for
2280              dynamically loaded objects (among other things).  */
2281           if (stop_on_solib_events)
2282             {
2283               stop_stepping (ecs);
2284               return;
2285             }
2286
2287           /* NOTE drow/2007-05-11: This might be a good place to check
2288              for "catch load".  */
2289         }
2290
2291       /* If we are skipping through a shell, or through shared library
2292          loading that we aren't interested in, resume the program.  If
2293          we're running the program normally, also resume.  But stop if
2294          we're attaching or setting up a remote connection.  */
2295       if (stop_soon == STOP_QUIETLY || stop_soon == NO_STOP_QUIETLY)
2296         {
2297           /* Loading of shared libraries might have changed breakpoint
2298              addresses.  Make sure new breakpoints are inserted.  */
2299           if (stop_soon == NO_STOP_QUIETLY
2300               && !breakpoints_always_inserted_mode ())
2301             insert_breakpoints ();
2302           resume (0, TARGET_SIGNAL_0);
2303           prepare_to_wait (ecs);
2304           return;
2305         }
2306
2307       break;
2308
2309     case TARGET_WAITKIND_SPURIOUS:
2310       if (debug_infrun)
2311         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SPURIOUS\n");
2312       resume (0, TARGET_SIGNAL_0);
2313       prepare_to_wait (ecs);
2314       return;
2315
2316     case TARGET_WAITKIND_EXITED:
2317       if (debug_infrun)
2318         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXITED\n");
2319       inferior_ptid = ecs->ptid;
2320       target_terminal_ours ();  /* Must do this before mourn anyway */
2321       print_stop_reason (EXITED, ecs->ws.value.integer);
2322
2323       /* Record the exit code in the convenience variable $_exitcode, so
2324          that the user can inspect this again later.  */
2325       set_internalvar (lookup_internalvar ("_exitcode"),
2326                        value_from_longest (builtin_type_int32,
2327                                            (LONGEST) ecs->ws.value.integer));
2328       gdb_flush (gdb_stdout);
2329       target_mourn_inferior ();
2330       singlestep_breakpoints_inserted_p = 0;
2331       stop_print_frame = 0;
2332       stop_stepping (ecs);
2333       return;
2334
2335     case TARGET_WAITKIND_SIGNALLED:
2336       if (debug_infrun)
2337         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SIGNALLED\n");
2338       inferior_ptid = ecs->ptid;
2339       stop_print_frame = 0;
2340       target_terminal_ours ();  /* Must do this before mourn anyway */
2341
2342       /* Note: By definition of TARGET_WAITKIND_SIGNALLED, we shouldn't
2343          reach here unless the inferior is dead.  However, for years
2344          target_kill() was called here, which hints that fatal signals aren't
2345          really fatal on some systems.  If that's true, then some changes
2346          may be needed. */
2347       target_mourn_inferior ();
2348
2349       print_stop_reason (SIGNAL_EXITED, ecs->ws.value.sig);
2350       singlestep_breakpoints_inserted_p = 0;
2351       stop_stepping (ecs);
2352       return;
2353
2354       /* The following are the only cases in which we keep going;
2355          the above cases end in a continue or goto. */
2356     case TARGET_WAITKIND_FORKED:
2357     case TARGET_WAITKIND_VFORKED:
2358       if (debug_infrun)
2359         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_FORKED\n");
2360       pending_follow.kind = ecs->ws.kind;
2361
2362       pending_follow.fork_event.parent_pid = ecs->ptid;
2363       pending_follow.fork_event.child_pid = ecs->ws.value.related_pid;
2364
2365       if (!ptid_equal (ecs->ptid, inferior_ptid))
2366         {
2367           context_switch (ecs->ptid);
2368           reinit_frame_cache ();
2369         }
2370
2371       stop_pc = read_pc ();
2372
2373       ecs->event_thread->stop_bpstat = bpstat_stop_status (stop_pc, ecs->ptid);
2374
2375       ecs->random_signal = !bpstat_explains_signal (ecs->event_thread->stop_bpstat);
2376
2377       /* If no catchpoint triggered for this, then keep going.  */
2378       if (ecs->random_signal)
2379         {
2380           ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
2381           keep_going (ecs);
2382           return;
2383         }
2384       ecs->event_thread->stop_signal = TARGET_SIGNAL_TRAP;
2385       goto process_event_stop_test;
2386
2387     case TARGET_WAITKIND_EXECD:
2388       if (debug_infrun)
2389         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXECD\n");
2390       pending_follow.execd_pathname =
2391         savestring (ecs->ws.value.execd_pathname,
2392                     strlen (ecs->ws.value.execd_pathname));
2393
2394       if (!ptid_equal (ecs->ptid, inferior_ptid))
2395         {
2396           context_switch (ecs->ptid);
2397           reinit_frame_cache ();
2398         }
2399
2400       stop_pc = read_pc ();
2401
2402       /* This causes the eventpoints and symbol table to be reset.
2403          Must do this now, before trying to determine whether to
2404          stop.  */
2405       follow_exec (inferior_ptid, pending_follow.execd_pathname);
2406       xfree (pending_follow.execd_pathname);
2407
2408       ecs->event_thread->stop_bpstat = bpstat_stop_status (stop_pc, ecs->ptid);
2409       ecs->random_signal = !bpstat_explains_signal (ecs->event_thread->stop_bpstat);
2410
2411       /* If no catchpoint triggered for this, then keep going.  */
2412       if (ecs->random_signal)
2413         {
2414           ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
2415           keep_going (ecs);
2416           return;
2417         }
2418       ecs->event_thread->stop_signal = TARGET_SIGNAL_TRAP;
2419       goto process_event_stop_test;
2420
2421       /* Be careful not to try to gather much state about a thread
2422          that's in a syscall.  It's frequently a losing proposition.  */
2423     case TARGET_WAITKIND_SYSCALL_ENTRY:
2424       if (debug_infrun)
2425         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SYSCALL_ENTRY\n");
2426       resume (0, TARGET_SIGNAL_0);
2427       prepare_to_wait (ecs);
2428       return;
2429
2430       /* Before examining the threads further, step this thread to
2431          get it entirely out of the syscall.  (We get notice of the
2432          event when the thread is just on the verge of exiting a
2433          syscall.  Stepping one instruction seems to get it back
2434          into user code.)  */
2435     case TARGET_WAITKIND_SYSCALL_RETURN:
2436       if (debug_infrun)
2437         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SYSCALL_RETURN\n");
2438       target_resume (ecs->ptid, 1, TARGET_SIGNAL_0);
2439       prepare_to_wait (ecs);
2440       return;
2441
2442     case TARGET_WAITKIND_STOPPED:
2443       if (debug_infrun)
2444         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_STOPPED\n");
2445       ecs->event_thread->stop_signal = ecs->ws.value.sig;
2446       break;
2447
2448     case TARGET_WAITKIND_NO_HISTORY:
2449       /* Reverse execution: target ran out of history info.  */
2450       stop_pc = read_pc ();
2451       print_stop_reason (NO_HISTORY, 0);
2452       stop_stepping (ecs);
2453       return;
2454
2455       /* We had an event in the inferior, but we are not interested
2456          in handling it at this level. The lower layers have already
2457          done what needs to be done, if anything.
2458
2459          One of the possible circumstances for this is when the
2460          inferior produces output for the console. The inferior has
2461          not stopped, and we are ignoring the event.  Another possible
2462          circumstance is any event which the lower level knows will be
2463          reported multiple times without an intervening resume.  */
2464     case TARGET_WAITKIND_IGNORE:
2465       if (debug_infrun)
2466         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_IGNORE\n");
2467       prepare_to_wait (ecs);
2468       return;
2469     }
2470
2471   if (ecs->new_thread_event)
2472     {
2473       if (non_stop)
2474         /* Non-stop assumes that the target handles adding new threads
2475            to the thread list.  */
2476         internal_error (__FILE__, __LINE__, "\
2477 targets should add new threads to the thread list themselves in non-stop mode.");
2478
2479       /* We may want to consider not doing a resume here in order to
2480          give the user a chance to play with the new thread.  It might
2481          be good to make that a user-settable option.  */
2482
2483       /* At this point, all threads are stopped (happens automatically
2484          in either the OS or the native code).  Therefore we need to
2485          continue all threads in order to make progress.  */
2486
2487       target_resume (RESUME_ALL, 0, TARGET_SIGNAL_0);
2488       prepare_to_wait (ecs);
2489       return;
2490     }
2491
2492   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED)
2493     {
2494       /* Do we need to clean up the state of a thread that has
2495          completed a displaced single-step?  (Doing so usually affects
2496          the PC, so do it here, before we set stop_pc.)  */
2497       displaced_step_fixup (ecs->ptid, ecs->event_thread->stop_signal);
2498
2499       /* If we either finished a single-step or hit a breakpoint, but
2500          the user wanted this thread to be stopped, pretend we got a
2501          SIG0 (generic unsignaled stop).  */
2502
2503       if (ecs->event_thread->stop_requested
2504           && ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP)
2505         ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
2506     }
2507
2508   stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
2509
2510   if (debug_infrun)
2511     {
2512       fprintf_unfiltered (gdb_stdlog, "infrun: stop_pc = 0x%s\n",
2513                           paddr_nz (stop_pc));
2514       if (STOPPED_BY_WATCHPOINT (&ecs->ws))
2515         {
2516           CORE_ADDR addr;
2517           fprintf_unfiltered (gdb_stdlog, "infrun: stopped by watchpoint\n");
2518
2519           if (target_stopped_data_address (&current_target, &addr))
2520             fprintf_unfiltered (gdb_stdlog,
2521                                 "infrun: stopped data address = 0x%s\n",
2522                                 paddr_nz (addr));
2523           else
2524             fprintf_unfiltered (gdb_stdlog,
2525                                 "infrun: (no data address available)\n");
2526         }
2527     }
2528
2529   if (stepping_past_singlestep_breakpoint)
2530     {
2531       gdb_assert (singlestep_breakpoints_inserted_p);
2532       gdb_assert (ptid_equal (singlestep_ptid, ecs->ptid));
2533       gdb_assert (!ptid_equal (singlestep_ptid, saved_singlestep_ptid));
2534
2535       stepping_past_singlestep_breakpoint = 0;
2536
2537       /* We've either finished single-stepping past the single-step
2538          breakpoint, or stopped for some other reason.  It would be nice if
2539          we could tell, but we can't reliably.  */
2540       if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP)
2541         {
2542           if (debug_infrun)
2543             fprintf_unfiltered (gdb_stdlog, "infrun: stepping_past_singlestep_breakpoint\n");
2544           /* Pull the single step breakpoints out of the target.  */
2545           remove_single_step_breakpoints ();
2546           singlestep_breakpoints_inserted_p = 0;
2547
2548           ecs->random_signal = 0;
2549
2550           context_switch (saved_singlestep_ptid);
2551           if (deprecated_context_hook)
2552             deprecated_context_hook (pid_to_thread_id (ecs->ptid));
2553
2554           resume (1, TARGET_SIGNAL_0);
2555           prepare_to_wait (ecs);
2556           return;
2557         }
2558     }
2559
2560   if (!ptid_equal (deferred_step_ptid, null_ptid))
2561     {
2562       /* In non-stop mode, there's never a deferred_step_ptid set.  */
2563       gdb_assert (!non_stop);
2564
2565       /* If we stopped for some other reason than single-stepping, ignore
2566          the fact that we were supposed to switch back.  */
2567       if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP)
2568         {
2569           if (debug_infrun)
2570             fprintf_unfiltered (gdb_stdlog,
2571                                 "infrun: handling deferred step\n");
2572
2573           /* Pull the single step breakpoints out of the target.  */
2574           if (singlestep_breakpoints_inserted_p)
2575             {
2576               remove_single_step_breakpoints ();
2577               singlestep_breakpoints_inserted_p = 0;
2578             }
2579
2580           /* Note: We do not call context_switch at this point, as the
2581              context is already set up for stepping the original thread.  */
2582           switch_to_thread (deferred_step_ptid);
2583           deferred_step_ptid = null_ptid;
2584           /* Suppress spurious "Switching to ..." message.  */
2585           previous_inferior_ptid = inferior_ptid;
2586
2587           resume (1, TARGET_SIGNAL_0);
2588           prepare_to_wait (ecs);
2589           return;
2590         }
2591
2592       deferred_step_ptid = null_ptid;
2593     }
2594
2595   /* See if a thread hit a thread-specific breakpoint that was meant for
2596      another thread.  If so, then step that thread past the breakpoint,
2597      and continue it.  */
2598
2599   if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP)
2600     {
2601       int thread_hop_needed = 0;
2602
2603       /* Check if a regular breakpoint has been hit before checking
2604          for a potential single step breakpoint. Otherwise, GDB will
2605          not see this breakpoint hit when stepping onto breakpoints.  */
2606       if (regular_breakpoint_inserted_here_p (stop_pc))
2607         {
2608           ecs->random_signal = 0;
2609           if (!breakpoint_thread_match (stop_pc, ecs->ptid))
2610             thread_hop_needed = 1;
2611         }
2612       else if (singlestep_breakpoints_inserted_p)
2613         {
2614           /* We have not context switched yet, so this should be true
2615              no matter which thread hit the singlestep breakpoint.  */
2616           gdb_assert (ptid_equal (inferior_ptid, singlestep_ptid));
2617           if (debug_infrun)
2618             fprintf_unfiltered (gdb_stdlog, "infrun: software single step "
2619                                 "trap for %s\n",
2620                                 target_pid_to_str (ecs->ptid));
2621
2622           ecs->random_signal = 0;
2623           /* The call to in_thread_list is necessary because PTIDs sometimes
2624              change when we go from single-threaded to multi-threaded.  If
2625              the singlestep_ptid is still in the list, assume that it is
2626              really different from ecs->ptid.  */
2627           if (!ptid_equal (singlestep_ptid, ecs->ptid)
2628               && in_thread_list (singlestep_ptid))
2629             {
2630               /* If the PC of the thread we were trying to single-step
2631                  has changed, discard this event (which we were going
2632                  to ignore anyway), and pretend we saw that thread
2633                  trap.  This prevents us continuously moving the
2634                  single-step breakpoint forward, one instruction at a
2635                  time.  If the PC has changed, then the thread we were
2636                  trying to single-step has trapped or been signalled,
2637                  but the event has not been reported to GDB yet.
2638
2639                  There might be some cases where this loses signal
2640                  information, if a signal has arrived at exactly the
2641                  same time that the PC changed, but this is the best
2642                  we can do with the information available.  Perhaps we
2643                  should arrange to report all events for all threads
2644                  when they stop, or to re-poll the remote looking for
2645                  this particular thread (i.e. temporarily enable
2646                  schedlock).  */
2647
2648              CORE_ADDR new_singlestep_pc
2649                = regcache_read_pc (get_thread_regcache (singlestep_ptid));
2650
2651              if (new_singlestep_pc != singlestep_pc)
2652                {
2653                  enum target_signal stop_signal;
2654
2655                  if (debug_infrun)
2656                    fprintf_unfiltered (gdb_stdlog, "infrun: unexpected thread,"
2657                                        " but expected thread advanced also\n");
2658
2659                  /* The current context still belongs to
2660                     singlestep_ptid.  Don't swap here, since that's
2661                     the context we want to use.  Just fudge our
2662                     state and continue.  */
2663                  stop_signal = ecs->event_thread->stop_signal;
2664                  ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
2665                  ecs->ptid = singlestep_ptid;
2666                  ecs->event_thread = find_thread_pid (ecs->ptid);
2667                  ecs->event_thread->stop_signal = stop_signal;
2668                  stop_pc = new_singlestep_pc;
2669                }
2670              else
2671                {
2672                  if (debug_infrun)
2673                    fprintf_unfiltered (gdb_stdlog,
2674                                        "infrun: unexpected thread\n");
2675
2676                  thread_hop_needed = 1;
2677                  stepping_past_singlestep_breakpoint = 1;
2678                  saved_singlestep_ptid = singlestep_ptid;
2679                }
2680             }
2681         }
2682
2683       if (thread_hop_needed)
2684         {
2685           int remove_status = 0;
2686
2687           if (debug_infrun)
2688             fprintf_unfiltered (gdb_stdlog, "infrun: thread_hop_needed\n");
2689
2690           /* Saw a breakpoint, but it was hit by the wrong thread.
2691              Just continue. */
2692
2693           if (singlestep_breakpoints_inserted_p)
2694             {
2695               /* Pull the single step breakpoints out of the target. */
2696               remove_single_step_breakpoints ();
2697               singlestep_breakpoints_inserted_p = 0;
2698             }
2699
2700           /* If the arch can displace step, don't remove the
2701              breakpoints.  */
2702           if (!use_displaced_stepping (current_gdbarch))
2703             remove_status = remove_breakpoints ();
2704
2705           /* Did we fail to remove breakpoints?  If so, try
2706              to set the PC past the bp.  (There's at least
2707              one situation in which we can fail to remove
2708              the bp's: On HP-UX's that use ttrace, we can't
2709              change the address space of a vforking child
2710              process until the child exits (well, okay, not
2711              then either :-) or execs. */
2712           if (remove_status != 0)
2713             error (_("Cannot step over breakpoint hit in wrong thread"));
2714           else
2715             {                   /* Single step */
2716               if (!ptid_equal (inferior_ptid, ecs->ptid))
2717                 context_switch (ecs->ptid);
2718
2719               if (!non_stop)
2720                 {
2721                   /* Only need to require the next event from this
2722                      thread in all-stop mode.  */
2723                   waiton_ptid = ecs->ptid;
2724                   infwait_state = infwait_thread_hop_state;
2725                 }
2726
2727               ecs->event_thread->stepping_over_breakpoint = 1;
2728               keep_going (ecs);
2729               registers_changed ();
2730               return;
2731             }
2732         }
2733       else if (singlestep_breakpoints_inserted_p)
2734         {
2735           sw_single_step_trap_p = 1;
2736           ecs->random_signal = 0;
2737         }
2738     }
2739   else
2740     ecs->random_signal = 1;
2741
2742   /* See if something interesting happened to the non-current thread.  If
2743      so, then switch to that thread.  */
2744   if (!ptid_equal (ecs->ptid, inferior_ptid))
2745     {
2746       if (debug_infrun)
2747         fprintf_unfiltered (gdb_stdlog, "infrun: context switch\n");
2748
2749       context_switch (ecs->ptid);
2750
2751       if (deprecated_context_hook)
2752         deprecated_context_hook (pid_to_thread_id (ecs->ptid));
2753     }
2754
2755   if (singlestep_breakpoints_inserted_p)
2756     {
2757       /* Pull the single step breakpoints out of the target. */
2758       remove_single_step_breakpoints ();
2759       singlestep_breakpoints_inserted_p = 0;
2760     }
2761
2762   if (stepped_after_stopped_by_watchpoint)
2763     stopped_by_watchpoint = 0;
2764   else
2765     stopped_by_watchpoint = watchpoints_triggered (&ecs->ws);
2766
2767   /* If necessary, step over this watchpoint.  We'll be back to display
2768      it in a moment.  */
2769   if (stopped_by_watchpoint
2770       && (HAVE_STEPPABLE_WATCHPOINT
2771           || gdbarch_have_nonsteppable_watchpoint (current_gdbarch)))
2772     {
2773       /* At this point, we are stopped at an instruction which has
2774          attempted to write to a piece of memory under control of
2775          a watchpoint.  The instruction hasn't actually executed
2776          yet.  If we were to evaluate the watchpoint expression
2777          now, we would get the old value, and therefore no change
2778          would seem to have occurred.
2779
2780          In order to make watchpoints work `right', we really need
2781          to complete the memory write, and then evaluate the
2782          watchpoint expression.  We do this by single-stepping the
2783          target.
2784
2785          It may not be necessary to disable the watchpoint to stop over
2786          it.  For example, the PA can (with some kernel cooperation)
2787          single step over a watchpoint without disabling the watchpoint.
2788
2789          It is far more common to need to disable a watchpoint to step
2790          the inferior over it.  If we have non-steppable watchpoints,
2791          we must disable the current watchpoint; it's simplest to
2792          disable all watchpoints and breakpoints.  */
2793          
2794       if (!HAVE_STEPPABLE_WATCHPOINT)
2795         remove_breakpoints ();
2796       registers_changed ();
2797       target_resume (ecs->ptid, 1, TARGET_SIGNAL_0);    /* Single step */
2798       waiton_ptid = ecs->ptid;
2799       if (HAVE_STEPPABLE_WATCHPOINT)
2800         infwait_state = infwait_step_watch_state;
2801       else
2802         infwait_state = infwait_nonstep_watch_state;
2803       prepare_to_wait (ecs);
2804       return;
2805     }
2806
2807   ecs->stop_func_start = 0;
2808   ecs->stop_func_end = 0;
2809   ecs->stop_func_name = 0;
2810   /* Don't care about return value; stop_func_start and stop_func_name
2811      will both be 0 if it doesn't work.  */
2812   find_pc_partial_function (stop_pc, &ecs->stop_func_name,
2813                             &ecs->stop_func_start, &ecs->stop_func_end);
2814   ecs->stop_func_start
2815     += gdbarch_deprecated_function_start_offset (current_gdbarch);
2816   ecs->event_thread->stepping_over_breakpoint = 0;
2817   bpstat_clear (&ecs->event_thread->stop_bpstat);
2818   ecs->event_thread->stop_step = 0;
2819   stop_print_frame = 1;
2820   ecs->random_signal = 0;
2821   stopped_by_random_signal = 0;
2822
2823   if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP
2824       && ecs->event_thread->trap_expected
2825       && gdbarch_single_step_through_delay_p (current_gdbarch)
2826       && currently_stepping (ecs->event_thread))
2827     {
2828       /* We're trying to step off a breakpoint.  Turns out that we're
2829          also on an instruction that needs to be stepped multiple
2830          times before it's been fully executing. E.g., architectures
2831          with a delay slot.  It needs to be stepped twice, once for
2832          the instruction and once for the delay slot.  */
2833       int step_through_delay
2834         = gdbarch_single_step_through_delay (current_gdbarch,
2835                                              get_current_frame ());
2836       if (debug_infrun && step_through_delay)
2837         fprintf_unfiltered (gdb_stdlog, "infrun: step through delay\n");
2838       if (ecs->event_thread->step_range_end == 0 && step_through_delay)
2839         {
2840           /* The user issued a continue when stopped at a breakpoint.
2841              Set up for another trap and get out of here.  */
2842          ecs->event_thread->stepping_over_breakpoint = 1;
2843          keep_going (ecs);
2844          return;
2845         }
2846       else if (step_through_delay)
2847         {
2848           /* The user issued a step when stopped at a breakpoint.
2849              Maybe we should stop, maybe we should not - the delay
2850              slot *might* correspond to a line of source.  In any
2851              case, don't decide that here, just set 
2852              ecs->stepping_over_breakpoint, making sure we 
2853              single-step again before breakpoints are re-inserted.  */
2854           ecs->event_thread->stepping_over_breakpoint = 1;
2855         }
2856     }
2857
2858   /* Look at the cause of the stop, and decide what to do.
2859      The alternatives are:
2860      1) stop_stepping and return; to really stop and return to the debugger,
2861      2) keep_going and return to start up again
2862      (set ecs->event_thread->stepping_over_breakpoint to 1 to single step once)
2863      3) set ecs->random_signal to 1, and the decision between 1 and 2
2864      will be made according to the signal handling tables.  */
2865
2866   /* First, distinguish signals caused by the debugger from signals
2867      that have to do with the program's own actions.  Note that
2868      breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
2869      on the operating system version.  Here we detect when a SIGILL or
2870      SIGEMT is really a breakpoint and change it to SIGTRAP.  We do
2871      something similar for SIGSEGV, since a SIGSEGV will be generated
2872      when we're trying to execute a breakpoint instruction on a
2873      non-executable stack.  This happens for call dummy breakpoints
2874      for architectures like SPARC that place call dummies on the
2875      stack.
2876
2877      If we're doing a displaced step past a breakpoint, then the
2878      breakpoint is always inserted at the original instruction;
2879      non-standard signals can't be explained by the breakpoint.  */
2880   if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP
2881       || (! ecs->event_thread->trap_expected
2882           && breakpoint_inserted_here_p (stop_pc)
2883           && (ecs->event_thread->stop_signal == TARGET_SIGNAL_ILL
2884               || ecs->event_thread->stop_signal == TARGET_SIGNAL_SEGV
2885               || ecs->event_thread->stop_signal == TARGET_SIGNAL_EMT))
2886       || stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_NO_SIGSTOP
2887       || stop_soon == STOP_QUIETLY_REMOTE)
2888     {
2889       if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP && stop_after_trap)
2890         {
2891           if (debug_infrun)
2892             fprintf_unfiltered (gdb_stdlog, "infrun: stopped\n");
2893           stop_print_frame = 0;
2894           stop_stepping (ecs);
2895           return;
2896         }
2897
2898       /* This is originated from start_remote(), start_inferior() and
2899          shared libraries hook functions.  */
2900       if (stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_REMOTE)
2901         {
2902           if (debug_infrun)
2903             fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
2904           stop_stepping (ecs);
2905           return;
2906         }
2907
2908       /* This originates from attach_command().  We need to overwrite
2909          the stop_signal here, because some kernels don't ignore a
2910          SIGSTOP in a subsequent ptrace(PTRACE_CONT,SIGSTOP) call.
2911          See more comments in inferior.h.  On the other hand, if we
2912          get a non-SIGSTOP, report it to the user - assume the backend
2913          will handle the SIGSTOP if it should show up later.
2914
2915          Also consider that the attach is complete when we see a
2916          SIGTRAP.  Some systems (e.g. Windows), and stubs supporting
2917          target extended-remote report it instead of a SIGSTOP
2918          (e.g. gdbserver).  We already rely on SIGTRAP being our
2919          signal, so this is no exception.
2920
2921          Also consider that the attach is complete when we see a
2922          TARGET_SIGNAL_0.  In non-stop mode, GDB will explicitly tell
2923          the target to stop all threads of the inferior, in case the
2924          low level attach operation doesn't stop them implicitly.  If
2925          they weren't stopped implicitly, then the stub will report a
2926          TARGET_SIGNAL_0, meaning: stopped for no particular reason
2927          other than GDB's request.  */
2928       if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
2929           && (ecs->event_thread->stop_signal == TARGET_SIGNAL_STOP
2930               || ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP
2931               || ecs->event_thread->stop_signal == TARGET_SIGNAL_0))
2932         {
2933           stop_stepping (ecs);
2934           ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
2935           return;
2936         }
2937
2938       /* See if there is a breakpoint at the current PC.  */
2939       ecs->event_thread->stop_bpstat = bpstat_stop_status (stop_pc, ecs->ptid);
2940       
2941       /* Following in case break condition called a
2942          function.  */
2943       stop_print_frame = 1;
2944
2945       /* NOTE: cagney/2003-03-29: These two checks for a random signal
2946          at one stage in the past included checks for an inferior
2947          function call's call dummy's return breakpoint.  The original
2948          comment, that went with the test, read:
2949
2950          ``End of a stack dummy.  Some systems (e.g. Sony news) give
2951          another signal besides SIGTRAP, so check here as well as
2952          above.''
2953
2954          If someone ever tries to get call dummys on a
2955          non-executable stack to work (where the target would stop
2956          with something like a SIGSEGV), then those tests might need
2957          to be re-instated.  Given, however, that the tests were only
2958          enabled when momentary breakpoints were not being used, I
2959          suspect that it won't be the case.
2960
2961          NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
2962          be necessary for call dummies on a non-executable stack on
2963          SPARC.  */
2964
2965       if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP)
2966         ecs->random_signal
2967           = !(bpstat_explains_signal (ecs->event_thread->stop_bpstat)
2968               || ecs->event_thread->trap_expected
2969               || (ecs->event_thread->step_range_end
2970                   && ecs->event_thread->step_resume_breakpoint == NULL));
2971       else
2972         {
2973           ecs->random_signal = !bpstat_explains_signal (ecs->event_thread->stop_bpstat);
2974           if (!ecs->random_signal)
2975             ecs->event_thread->stop_signal = TARGET_SIGNAL_TRAP;
2976         }
2977     }
2978
2979   /* When we reach this point, we've pretty much decided
2980      that the reason for stopping must've been a random
2981      (unexpected) signal. */
2982
2983   else
2984     ecs->random_signal = 1;
2985
2986 process_event_stop_test:
2987   /* For the program's own signals, act according to
2988      the signal handling tables.  */
2989
2990   if (ecs->random_signal)
2991     {
2992       /* Signal not for debugging purposes.  */
2993       int printed = 0;
2994
2995       if (debug_infrun)
2996          fprintf_unfiltered (gdb_stdlog, "infrun: random signal %d\n",
2997                              ecs->event_thread->stop_signal);
2998
2999       stopped_by_random_signal = 1;
3000
3001       if (signal_print[ecs->event_thread->stop_signal])
3002         {
3003           printed = 1;
3004           target_terminal_ours_for_output ();
3005           print_stop_reason (SIGNAL_RECEIVED, ecs->event_thread->stop_signal);
3006         }
3007       /* Always stop on signals if we're either just gaining control
3008          of the program, or the user explicitly requested this thread
3009          to remain stopped.  */
3010       if (stop_soon != NO_STOP_QUIETLY
3011           || ecs->event_thread->stop_requested
3012           || signal_stop_state (ecs->event_thread->stop_signal))
3013         {
3014           stop_stepping (ecs);
3015           return;
3016         }
3017       /* If not going to stop, give terminal back
3018          if we took it away.  */
3019       else if (printed)
3020         target_terminal_inferior ();
3021
3022       /* Clear the signal if it should not be passed.  */
3023       if (signal_program[ecs->event_thread->stop_signal] == 0)
3024         ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
3025
3026       if (ecs->event_thread->prev_pc == read_pc ()
3027           && ecs->event_thread->trap_expected
3028           && ecs->event_thread->step_resume_breakpoint == NULL)
3029         {
3030           /* We were just starting a new sequence, attempting to
3031              single-step off of a breakpoint and expecting a SIGTRAP.
3032              Instead this signal arrives.  This signal will take us out
3033              of the stepping range so GDB needs to remember to, when
3034              the signal handler returns, resume stepping off that
3035              breakpoint.  */
3036           /* To simplify things, "continue" is forced to use the same
3037              code paths as single-step - set a breakpoint at the
3038              signal return address and then, once hit, step off that
3039              breakpoint.  */
3040           if (debug_infrun)
3041             fprintf_unfiltered (gdb_stdlog,
3042                                 "infrun: signal arrived while stepping over "
3043                                 "breakpoint\n");
3044
3045           insert_step_resume_breakpoint_at_frame (get_current_frame ());
3046           ecs->event_thread->step_after_step_resume_breakpoint = 1;
3047           keep_going (ecs);
3048           return;
3049         }
3050
3051       if (ecs->event_thread->step_range_end != 0
3052           && ecs->event_thread->stop_signal != TARGET_SIGNAL_0
3053           && (ecs->event_thread->step_range_start <= stop_pc
3054               && stop_pc < ecs->event_thread->step_range_end)
3055           && frame_id_eq (get_frame_id (get_current_frame ()),
3056                           ecs->event_thread->step_frame_id)
3057           && ecs->event_thread->step_resume_breakpoint == NULL)
3058         {
3059           /* The inferior is about to take a signal that will take it
3060              out of the single step range.  Set a breakpoint at the
3061              current PC (which is presumably where the signal handler
3062              will eventually return) and then allow the inferior to
3063              run free.
3064
3065              Note that this is only needed for a signal delivered
3066              while in the single-step range.  Nested signals aren't a
3067              problem as they eventually all return.  */
3068           if (debug_infrun)
3069             fprintf_unfiltered (gdb_stdlog,
3070                                 "infrun: signal may take us out of "
3071                                 "single-step range\n");
3072
3073           insert_step_resume_breakpoint_at_frame (get_current_frame ());
3074           keep_going (ecs);
3075           return;
3076         }
3077
3078       /* Note: step_resume_breakpoint may be non-NULL.  This occures
3079          when either there's a nested signal, or when there's a
3080          pending signal enabled just as the signal handler returns
3081          (leaving the inferior at the step-resume-breakpoint without
3082          actually executing it).  Either way continue until the
3083          breakpoint is really hit.  */
3084       keep_going (ecs);
3085       return;
3086     }
3087
3088   /* Handle cases caused by hitting a breakpoint.  */
3089   {
3090     CORE_ADDR jmp_buf_pc;
3091     struct bpstat_what what;
3092
3093     what = bpstat_what (ecs->event_thread->stop_bpstat);
3094
3095     if (what.call_dummy)
3096       {
3097         stop_stack_dummy = 1;
3098       }
3099
3100     switch (what.main_action)
3101       {
3102       case BPSTAT_WHAT_SET_LONGJMP_RESUME:
3103         /* If we hit the breakpoint at longjmp while stepping, we
3104            install a momentary breakpoint at the target of the
3105            jmp_buf.  */
3106
3107         if (debug_infrun)
3108           fprintf_unfiltered (gdb_stdlog,
3109                               "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME\n");
3110
3111         ecs->event_thread->stepping_over_breakpoint = 1;
3112
3113         if (!gdbarch_get_longjmp_target_p (current_gdbarch)
3114             || !gdbarch_get_longjmp_target (current_gdbarch,
3115                                             get_current_frame (), &jmp_buf_pc))
3116           {
3117             if (debug_infrun)
3118               fprintf_unfiltered (gdb_stdlog, "\
3119 infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME (!gdbarch_get_longjmp_target)\n");
3120             keep_going (ecs);
3121             return;
3122           }
3123
3124         /* We're going to replace the current step-resume breakpoint
3125            with a longjmp-resume breakpoint.  */
3126         delete_step_resume_breakpoint (ecs->event_thread);
3127
3128         /* Insert a breakpoint at resume address.  */
3129         insert_longjmp_resume_breakpoint (jmp_buf_pc);
3130
3131         keep_going (ecs);
3132         return;
3133
3134       case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
3135         if (debug_infrun)
3136           fprintf_unfiltered (gdb_stdlog,
3137                               "infrun: BPSTAT_WHAT_CLEAR_LONGJMP_RESUME\n");
3138
3139         gdb_assert (ecs->event_thread->step_resume_breakpoint != NULL);
3140         delete_step_resume_breakpoint (ecs->event_thread);
3141
3142         ecs->event_thread->stop_step = 1;
3143         print_stop_reason (END_STEPPING_RANGE, 0);
3144         stop_stepping (ecs);
3145         return;
3146
3147       case BPSTAT_WHAT_SINGLE:
3148         if (debug_infrun)
3149           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_SINGLE\n");
3150         ecs->event_thread->stepping_over_breakpoint = 1;
3151         /* Still need to check other stuff, at least the case
3152            where we are stepping and step out of the right range.  */
3153         break;
3154
3155       case BPSTAT_WHAT_STOP_NOISY:
3156         if (debug_infrun)
3157           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_NOISY\n");
3158         stop_print_frame = 1;
3159
3160         /* We are about to nuke the step_resume_breakpointt via the
3161            cleanup chain, so no need to worry about it here.  */
3162
3163         stop_stepping (ecs);
3164         return;
3165
3166       case BPSTAT_WHAT_STOP_SILENT:
3167         if (debug_infrun)
3168           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_SILENT\n");
3169         stop_print_frame = 0;
3170
3171         /* We are about to nuke the step_resume_breakpoin via the
3172            cleanup chain, so no need to worry about it here.  */
3173
3174         stop_stepping (ecs);
3175         return;
3176
3177       case BPSTAT_WHAT_STEP_RESUME:
3178         if (debug_infrun)
3179           fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STEP_RESUME\n");
3180
3181         delete_step_resume_breakpoint (ecs->event_thread);
3182         if (ecs->event_thread->step_after_step_resume_breakpoint)
3183           {
3184             /* Back when the step-resume breakpoint was inserted, we
3185                were trying to single-step off a breakpoint.  Go back
3186                to doing that.  */
3187             ecs->event_thread->step_after_step_resume_breakpoint = 0;
3188             ecs->event_thread->stepping_over_breakpoint = 1;
3189             keep_going (ecs);
3190             return;
3191           }
3192         if (stop_pc == ecs->stop_func_start
3193             && execution_direction == EXEC_REVERSE)
3194           {
3195             /* We are stepping over a function call in reverse, and
3196                just hit the step-resume breakpoint at the start
3197                address of the function.  Go back to single-stepping,
3198                which should take us back to the function call.  */
3199             ecs->event_thread->stepping_over_breakpoint = 1;
3200             keep_going (ecs);
3201             return;
3202           }
3203         break;
3204
3205       case BPSTAT_WHAT_CHECK_SHLIBS:
3206         {
3207           if (debug_infrun)
3208             fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_CHECK_SHLIBS\n");
3209
3210           /* Check for any newly added shared libraries if we're
3211              supposed to be adding them automatically.  Switch
3212              terminal for any messages produced by
3213              breakpoint_re_set.  */
3214           target_terminal_ours_for_output ();
3215           /* NOTE: cagney/2003-11-25: Make certain that the target
3216              stack's section table is kept up-to-date.  Architectures,
3217              (e.g., PPC64), use the section table to perform
3218              operations such as address => section name and hence
3219              require the table to contain all sections (including
3220              those found in shared libraries).  */
3221           /* NOTE: cagney/2003-11-25: Pass current_target and not
3222              exec_ops to SOLIB_ADD.  This is because current GDB is
3223              only tooled to propagate section_table changes out from
3224              the "current_target" (see target_resize_to_sections), and
3225              not up from the exec stratum.  This, of course, isn't
3226              right.  "infrun.c" should only interact with the
3227              exec/process stratum, instead relying on the target stack
3228              to propagate relevant changes (stop, section table
3229              changed, ...) up to other layers.  */
3230 #ifdef SOLIB_ADD
3231           SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
3232 #else
3233           solib_add (NULL, 0, &current_target, auto_solib_add);
3234 #endif
3235           target_terminal_inferior ();
3236
3237           /* If requested, stop when the dynamic linker notifies
3238              gdb of events.  This allows the user to get control
3239              and place breakpoints in initializer routines for
3240              dynamically loaded objects (among other things).  */
3241           if (stop_on_solib_events || stop_stack_dummy)
3242             {
3243               stop_stepping (ecs);
3244               return;
3245             }
3246           else
3247             {
3248               /* We want to step over this breakpoint, then keep going.  */
3249               ecs->event_thread->stepping_over_breakpoint = 1;
3250               break;
3251             }
3252         }
3253         break;
3254
3255       case BPSTAT_WHAT_LAST:
3256         /* Not a real code, but listed here to shut up gcc -Wall.  */
3257
3258       case BPSTAT_WHAT_KEEP_CHECKING:
3259         break;
3260       }
3261   }
3262
3263   /* We come here if we hit a breakpoint but should not
3264      stop for it.  Possibly we also were stepping
3265      and should stop for that.  So fall through and
3266      test for stepping.  But, if not stepping,
3267      do not stop.  */
3268
3269   /* In all-stop mode, if we're currently stepping but have stopped in
3270      some other thread, we need to switch back to the stepped thread.  */
3271   if (!non_stop)
3272     {
3273       struct thread_info *tp;
3274       tp = iterate_over_threads (currently_stepping_callback,
3275                                  ecs->event_thread);
3276       if (tp)
3277         {
3278           /* However, if the current thread is blocked on some internal
3279              breakpoint, and we simply need to step over that breakpoint
3280              to get it going again, do that first.  */
3281           if ((ecs->event_thread->trap_expected
3282                && ecs->event_thread->stop_signal != TARGET_SIGNAL_TRAP)
3283               || ecs->event_thread->stepping_over_breakpoint)
3284             {
3285               keep_going (ecs);
3286               return;
3287             }
3288
3289           /* Otherwise, we no longer expect a trap in the current thread.
3290              Clear the trap_expected flag before switching back -- this is
3291              what keep_going would do as well, if we called it.  */
3292           ecs->event_thread->trap_expected = 0;
3293
3294           if (debug_infrun)
3295             fprintf_unfiltered (gdb_stdlog,
3296                                 "infrun: switching back to stepped thread\n");
3297
3298           ecs->event_thread = tp;
3299           ecs->ptid = tp->ptid;
3300           context_switch (ecs->ptid);
3301           keep_going (ecs);
3302           return;
3303         }
3304     }
3305
3306   /* Are we stepping to get the inferior out of the dynamic linker's
3307      hook (and possibly the dld itself) after catching a shlib
3308      event?  */
3309   if (ecs->event_thread->stepping_through_solib_after_catch)
3310     {
3311 #if defined(SOLIB_ADD)
3312       /* Have we reached our destination?  If not, keep going. */
3313       if (SOLIB_IN_DYNAMIC_LINKER (PIDGET (ecs->ptid), stop_pc))
3314         {
3315           if (debug_infrun)
3316             fprintf_unfiltered (gdb_stdlog, "infrun: stepping in dynamic linker\n");
3317           ecs->event_thread->stepping_over_breakpoint = 1;
3318           keep_going (ecs);
3319           return;
3320         }
3321 #endif
3322       if (debug_infrun)
3323          fprintf_unfiltered (gdb_stdlog, "infrun: step past dynamic linker\n");
3324       /* Else, stop and report the catchpoint(s) whose triggering
3325          caused us to begin stepping. */
3326       ecs->event_thread->stepping_through_solib_after_catch = 0;
3327       bpstat_clear (&ecs->event_thread->stop_bpstat);
3328       ecs->event_thread->stop_bpstat
3329         = bpstat_copy (ecs->event_thread->stepping_through_solib_catchpoints);
3330       bpstat_clear (&ecs->event_thread->stepping_through_solib_catchpoints);
3331       stop_print_frame = 1;
3332       stop_stepping (ecs);
3333       return;
3334     }
3335
3336   if (ecs->event_thread->step_resume_breakpoint)
3337     {
3338       if (debug_infrun)
3339          fprintf_unfiltered (gdb_stdlog,
3340                              "infrun: step-resume breakpoint is inserted\n");
3341
3342       /* Having a step-resume breakpoint overrides anything
3343          else having to do with stepping commands until
3344          that breakpoint is reached.  */
3345       keep_going (ecs);
3346       return;
3347     }
3348
3349   if (ecs->event_thread->step_range_end == 0)
3350     {
3351       if (debug_infrun)
3352          fprintf_unfiltered (gdb_stdlog, "infrun: no stepping, continue\n");
3353       /* Likewise if we aren't even stepping.  */
3354       keep_going (ecs);
3355       return;
3356     }
3357
3358   /* If stepping through a line, keep going if still within it.
3359
3360      Note that step_range_end is the address of the first instruction
3361      beyond the step range, and NOT the address of the last instruction
3362      within it! */
3363   if (stop_pc >= ecs->event_thread->step_range_start
3364       && stop_pc < ecs->event_thread->step_range_end)
3365     {
3366       if (debug_infrun)
3367         fprintf_unfiltered (gdb_stdlog, "infrun: stepping inside range [0x%s-0x%s]\n",
3368                             paddr_nz (ecs->event_thread->step_range_start),
3369                             paddr_nz (ecs->event_thread->step_range_end));
3370
3371       /* When stepping backward, stop at beginning of line range
3372          (unless it's the function entry point, in which case
3373          keep going back to the call point).  */
3374       if (stop_pc == ecs->event_thread->step_range_start
3375           && stop_pc != ecs->stop_func_start
3376           && execution_direction == EXEC_REVERSE)
3377         {
3378           ecs->event_thread->stop_step = 1;
3379           print_stop_reason (END_STEPPING_RANGE, 0);
3380           stop_stepping (ecs);
3381         }
3382       else
3383         keep_going (ecs);
3384
3385       return;
3386     }
3387
3388   /* We stepped out of the stepping range.  */
3389
3390   /* If we are stepping at the source level and entered the runtime
3391      loader dynamic symbol resolution code, we keep on single stepping
3392      until we exit the run time loader code and reach the callee's
3393      address.  */
3394   if (ecs->event_thread->step_over_calls == STEP_OVER_UNDEBUGGABLE
3395       && in_solib_dynsym_resolve_code (stop_pc))
3396     {
3397       CORE_ADDR pc_after_resolver =
3398         gdbarch_skip_solib_resolver (current_gdbarch, stop_pc);
3399
3400       if (debug_infrun)
3401          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into dynsym resolve code\n");
3402
3403       if (pc_after_resolver)
3404         {
3405           /* Set up a step-resume breakpoint at the address
3406              indicated by SKIP_SOLIB_RESOLVER.  */
3407           struct symtab_and_line sr_sal;
3408           init_sal (&sr_sal);
3409           sr_sal.pc = pc_after_resolver;
3410
3411           insert_step_resume_breakpoint_at_sal (sr_sal, null_frame_id);
3412         }
3413
3414       keep_going (ecs);
3415       return;
3416     }
3417
3418   if (ecs->event_thread->step_range_end != 1
3419       && (ecs->event_thread->step_over_calls == STEP_OVER_UNDEBUGGABLE
3420           || ecs->event_thread->step_over_calls == STEP_OVER_ALL)
3421       && get_frame_type (get_current_frame ()) == SIGTRAMP_FRAME)
3422     {
3423       if (debug_infrun)
3424          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into signal trampoline\n");
3425       /* The inferior, while doing a "step" or "next", has ended up in
3426          a signal trampoline (either by a signal being delivered or by
3427          the signal handler returning).  Just single-step until the
3428          inferior leaves the trampoline (either by calling the handler
3429          or returning).  */
3430       keep_going (ecs);
3431       return;
3432     }
3433
3434   /* Check for subroutine calls.  The check for the current frame
3435      equalling the step ID is not necessary - the check of the
3436      previous frame's ID is sufficient - but it is a common case and
3437      cheaper than checking the previous frame's ID.
3438
3439      NOTE: frame_id_eq will never report two invalid frame IDs as
3440      being equal, so to get into this block, both the current and
3441      previous frame must have valid frame IDs.  */
3442   if (!frame_id_eq (get_frame_id (get_current_frame ()),
3443                     ecs->event_thread->step_frame_id)
3444       && (frame_id_eq (frame_unwind_id (get_current_frame ()),
3445                        ecs->event_thread->step_frame_id)
3446           || execution_direction == EXEC_REVERSE))
3447     {
3448       CORE_ADDR real_stop_pc;
3449
3450       if (debug_infrun)
3451          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into subroutine\n");
3452
3453       if ((ecs->event_thread->step_over_calls == STEP_OVER_NONE)
3454           || ((ecs->event_thread->step_range_end == 1)
3455               && in_prologue (ecs->event_thread->prev_pc,
3456                               ecs->stop_func_start)))
3457         {
3458           /* I presume that step_over_calls is only 0 when we're
3459              supposed to be stepping at the assembly language level
3460              ("stepi").  Just stop.  */
3461           /* Also, maybe we just did a "nexti" inside a prolog, so we
3462              thought it was a subroutine call but it was not.  Stop as
3463              well.  FENN */
3464           ecs->event_thread->stop_step = 1;
3465           print_stop_reason (END_STEPPING_RANGE, 0);
3466           stop_stepping (ecs);
3467           return;
3468         }
3469
3470       if (ecs->event_thread->step_over_calls == STEP_OVER_ALL)
3471         {
3472           /* We're doing a "next".
3473
3474              Normal (forward) execution: set a breakpoint at the
3475              callee's return address (the address at which the caller
3476              will resume).
3477
3478              Reverse (backward) execution.  set the step-resume
3479              breakpoint at the start of the function that we just
3480              stepped into (backwards), and continue to there.  When we
3481              get there, we'll need to single-step back to the caller.  */
3482
3483           if (execution_direction == EXEC_REVERSE)
3484             {
3485               struct symtab_and_line sr_sal;
3486
3487               if (ecs->stop_func_start == 0 
3488                   && in_solib_dynsym_resolve_code (stop_pc))
3489                 {
3490                   /* Stepped into runtime loader dynamic symbol
3491                      resolution code.  Since we're in reverse, 
3492                      we have already backed up through the runtime
3493                      loader and the dynamic function.  This is just
3494                      the trampoline (jump table).
3495
3496                      Just keep stepping, we'll soon be home.
3497                   */
3498                   keep_going (ecs);
3499                   return;
3500                 }
3501               /* Normal (staticly linked) function call return.  */
3502               init_sal (&sr_sal);
3503               sr_sal.pc = ecs->stop_func_start;
3504               insert_step_resume_breakpoint_at_sal (sr_sal, null_frame_id);
3505             }
3506           else
3507             insert_step_resume_breakpoint_at_caller (get_current_frame ());
3508
3509           keep_going (ecs);
3510           return;
3511         }
3512
3513       /* If we are in a function call trampoline (a stub between the
3514          calling routine and the real function), locate the real
3515          function.  That's what tells us (a) whether we want to step
3516          into it at all, and (b) what prologue we want to run to the
3517          end of, if we do step into it.  */
3518       real_stop_pc = skip_language_trampoline (get_current_frame (), stop_pc);
3519       if (real_stop_pc == 0)
3520         real_stop_pc = gdbarch_skip_trampoline_code
3521                          (current_gdbarch, get_current_frame (), stop_pc);
3522       if (real_stop_pc != 0)
3523         ecs->stop_func_start = real_stop_pc;
3524
3525       if (real_stop_pc != 0 && in_solib_dynsym_resolve_code (real_stop_pc))
3526         {
3527           struct symtab_and_line sr_sal;
3528           init_sal (&sr_sal);
3529           sr_sal.pc = ecs->stop_func_start;
3530
3531           insert_step_resume_breakpoint_at_sal (sr_sal, null_frame_id);
3532           keep_going (ecs);
3533           return;
3534         }
3535
3536       /* If we have line number information for the function we are
3537          thinking of stepping into, step into it.
3538
3539          If there are several symtabs at that PC (e.g. with include
3540          files), just want to know whether *any* of them have line
3541          numbers.  find_pc_line handles this.  */
3542       {
3543         struct symtab_and_line tmp_sal;
3544
3545         tmp_sal = find_pc_line (ecs->stop_func_start, 0);
3546         if (tmp_sal.line != 0)
3547           {
3548             if (execution_direction == EXEC_REVERSE)
3549               handle_step_into_function_backward (ecs);
3550             else
3551               handle_step_into_function (ecs);
3552             return;
3553           }
3554       }
3555
3556       /* If we have no line number and the step-stop-if-no-debug is
3557          set, we stop the step so that the user has a chance to switch
3558          in assembly mode.  */
3559       if (ecs->event_thread->step_over_calls == STEP_OVER_UNDEBUGGABLE
3560           && step_stop_if_no_debug)
3561         {
3562           ecs->event_thread->stop_step = 1;
3563           print_stop_reason (END_STEPPING_RANGE, 0);
3564           stop_stepping (ecs);
3565           return;
3566         }
3567
3568       if (execution_direction == EXEC_REVERSE)
3569         {
3570           /* Set a breakpoint at callee's start address.
3571              From there we can step once and be back in the caller.  */
3572           struct symtab_and_line sr_sal;
3573           init_sal (&sr_sal);
3574           sr_sal.pc = ecs->stop_func_start;
3575           insert_step_resume_breakpoint_at_sal (sr_sal, null_frame_id);
3576         }
3577       else
3578         /* Set a breakpoint at callee's return address (the address
3579            at which the caller will resume).  */
3580         insert_step_resume_breakpoint_at_caller (get_current_frame ());
3581
3582       keep_going (ecs);
3583       return;
3584     }
3585
3586   /* If we're in the return path from a shared library trampoline,
3587      we want to proceed through the trampoline when stepping.  */
3588   if (gdbarch_in_solib_return_trampoline (current_gdbarch,
3589                                           stop_pc, ecs->stop_func_name))
3590     {
3591       /* Determine where this trampoline returns.  */
3592       CORE_ADDR real_stop_pc;
3593       real_stop_pc = gdbarch_skip_trampoline_code
3594                        (current_gdbarch, get_current_frame (), stop_pc);
3595
3596       if (debug_infrun)
3597          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into solib return tramp\n");
3598
3599       /* Only proceed through if we know where it's going.  */
3600       if (real_stop_pc)
3601         {
3602           /* And put the step-breakpoint there and go until there. */
3603           struct symtab_and_line sr_sal;
3604
3605           init_sal (&sr_sal);   /* initialize to zeroes */
3606           sr_sal.pc = real_stop_pc;
3607           sr_sal.section = find_pc_overlay (sr_sal.pc);
3608
3609           /* Do not specify what the fp should be when we stop since
3610              on some machines the prologue is where the new fp value
3611              is established.  */
3612           insert_step_resume_breakpoint_at_sal (sr_sal, null_frame_id);
3613
3614           /* Restart without fiddling with the step ranges or
3615              other state.  */
3616           keep_going (ecs);
3617           return;
3618         }
3619     }
3620
3621   stop_pc_sal = find_pc_line (stop_pc, 0);
3622
3623   /* NOTE: tausq/2004-05-24: This if block used to be done before all
3624      the trampoline processing logic, however, there are some trampolines 
3625      that have no names, so we should do trampoline handling first.  */
3626   if (ecs->event_thread->step_over_calls == STEP_OVER_UNDEBUGGABLE
3627       && ecs->stop_func_name == NULL
3628       && stop_pc_sal.line == 0)
3629     {
3630       if (debug_infrun)
3631          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into undebuggable function\n");
3632
3633       /* The inferior just stepped into, or returned to, an
3634          undebuggable function (where there is no debugging information
3635          and no line number corresponding to the address where the
3636          inferior stopped).  Since we want to skip this kind of code,
3637          we keep going until the inferior returns from this
3638          function - unless the user has asked us not to (via
3639          set step-mode) or we no longer know how to get back
3640          to the call site.  */
3641       if (step_stop_if_no_debug
3642           || !frame_id_p (frame_unwind_id (get_current_frame ())))
3643         {
3644           /* If we have no line number and the step-stop-if-no-debug
3645              is set, we stop the step so that the user has a chance to
3646              switch in assembly mode.  */
3647           ecs->event_thread->stop_step = 1;
3648           print_stop_reason (END_STEPPING_RANGE, 0);
3649           stop_stepping (ecs);
3650           return;
3651         }
3652       else
3653         {
3654           /* Set a breakpoint at callee's return address (the address
3655              at which the caller will resume).  */
3656           insert_step_resume_breakpoint_at_caller (get_current_frame ());
3657           keep_going (ecs);
3658           return;
3659         }
3660     }
3661
3662   if (ecs->event_thread->step_range_end == 1)
3663     {
3664       /* It is stepi or nexti.  We always want to stop stepping after
3665          one instruction.  */
3666       if (debug_infrun)
3667          fprintf_unfiltered (gdb_stdlog, "infrun: stepi/nexti\n");
3668       ecs->event_thread->stop_step = 1;
3669       print_stop_reason (END_STEPPING_RANGE, 0);
3670       stop_stepping (ecs);
3671       return;
3672     }
3673
3674   if (stop_pc_sal.line == 0)
3675     {
3676       /* We have no line number information.  That means to stop
3677          stepping (does this always happen right after one instruction,
3678          when we do "s" in a function with no line numbers,
3679          or can this happen as a result of a return or longjmp?).  */
3680       if (debug_infrun)
3681          fprintf_unfiltered (gdb_stdlog, "infrun: no line number info\n");
3682       ecs->event_thread->stop_step = 1;
3683       print_stop_reason (END_STEPPING_RANGE, 0);
3684       stop_stepping (ecs);
3685       return;
3686     }
3687
3688   if ((stop_pc == stop_pc_sal.pc)
3689       && (ecs->event_thread->current_line != stop_pc_sal.line
3690           || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
3691     {
3692       /* We are at the start of a different line.  So stop.  Note that
3693          we don't stop if we step into the middle of a different line.
3694          That is said to make things like for (;;) statements work
3695          better.  */
3696       if (debug_infrun)
3697          fprintf_unfiltered (gdb_stdlog, "infrun: stepped to a different line\n");
3698       ecs->event_thread->stop_step = 1;
3699       print_stop_reason (END_STEPPING_RANGE, 0);
3700       stop_stepping (ecs);
3701       return;
3702     }
3703
3704   /* We aren't done stepping.
3705
3706      Optimize by setting the stepping range to the line.
3707      (We might not be in the original line, but if we entered a
3708      new line in mid-statement, we continue stepping.  This makes
3709      things like for(;;) statements work better.)  */
3710
3711   ecs->event_thread->step_range_start = stop_pc_sal.pc;
3712   ecs->event_thread->step_range_end = stop_pc_sal.end;
3713   ecs->event_thread->step_frame_id = get_frame_id (get_current_frame ());
3714   ecs->event_thread->current_line = stop_pc_sal.line;
3715   ecs->event_thread->current_symtab = stop_pc_sal.symtab;
3716
3717   if (debug_infrun)
3718      fprintf_unfiltered (gdb_stdlog, "infrun: keep going\n");
3719   keep_going (ecs);
3720 }
3721
3722 /* Are we in the middle of stepping?  */
3723
3724 static int
3725 currently_stepping_thread (struct thread_info *tp)
3726 {
3727   return (tp->step_range_end && tp->step_resume_breakpoint == NULL)
3728          || tp->trap_expected
3729          || tp->stepping_through_solib_after_catch;
3730 }
3731
3732 static int
3733 currently_stepping_callback (struct thread_info *tp, void *data)
3734 {
3735   /* Return true if any thread *but* the one passed in "data" is
3736      in the middle of stepping.  */
3737   return tp != data && currently_stepping_thread (tp);
3738 }
3739
3740 static int
3741 currently_stepping (struct thread_info *tp)
3742 {
3743   return currently_stepping_thread (tp) || bpstat_should_step ();
3744 }
3745
3746 /* Inferior has stepped into a subroutine call with source code that
3747    we should not step over.  Do step to the first line of code in
3748    it.  */
3749
3750 static void
3751 handle_step_into_function (struct execution_control_state *ecs)
3752 {
3753   struct symtab *s;
3754   struct symtab_and_line stop_func_sal, sr_sal;
3755
3756   s = find_pc_symtab (stop_pc);
3757   if (s && s->language != language_asm)
3758     ecs->stop_func_start = gdbarch_skip_prologue (current_gdbarch, 
3759                                                   ecs->stop_func_start);
3760
3761   stop_func_sal = find_pc_line (ecs->stop_func_start, 0);
3762   /* Use the step_resume_break to step until the end of the prologue,
3763      even if that involves jumps (as it seems to on the vax under
3764      4.2).  */
3765   /* If the prologue ends in the middle of a source line, continue to
3766      the end of that source line (if it is still within the function).
3767      Otherwise, just go to end of prologue.  */
3768   if (stop_func_sal.end
3769       && stop_func_sal.pc != ecs->stop_func_start
3770       && stop_func_sal.end < ecs->stop_func_end)
3771     ecs->stop_func_start = stop_func_sal.end;
3772
3773   /* Architectures which require breakpoint adjustment might not be able
3774      to place a breakpoint at the computed address.  If so, the test
3775      ``ecs->stop_func_start == stop_pc'' will never succeed.  Adjust
3776      ecs->stop_func_start to an address at which a breakpoint may be
3777      legitimately placed.
3778
3779      Note:  kevinb/2004-01-19:  On FR-V, if this adjustment is not
3780      made, GDB will enter an infinite loop when stepping through
3781      optimized code consisting of VLIW instructions which contain
3782      subinstructions corresponding to different source lines.  On
3783      FR-V, it's not permitted to place a breakpoint on any but the
3784      first subinstruction of a VLIW instruction.  When a breakpoint is
3785      set, GDB will adjust the breakpoint address to the beginning of
3786      the VLIW instruction.  Thus, we need to make the corresponding
3787      adjustment here when computing the stop address.  */
3788
3789   if (gdbarch_adjust_breakpoint_address_p (current_gdbarch))
3790     {
3791       ecs->stop_func_start
3792         = gdbarch_adjust_breakpoint_address (current_gdbarch,
3793                                              ecs->stop_func_start);
3794     }
3795
3796   if (ecs->stop_func_start == stop_pc)
3797     {
3798       /* We are already there: stop now.  */
3799       ecs->event_thread->stop_step = 1;
3800       print_stop_reason (END_STEPPING_RANGE, 0);
3801       stop_stepping (ecs);
3802       return;
3803     }
3804   else
3805     {
3806       /* Put the step-breakpoint there and go until there.  */
3807       init_sal (&sr_sal);       /* initialize to zeroes */
3808       sr_sal.pc = ecs->stop_func_start;
3809       sr_sal.section = find_pc_overlay (ecs->stop_func_start);
3810
3811       /* Do not specify what the fp should be when we stop since on
3812          some machines the prologue is where the new fp value is
3813          established.  */
3814       insert_step_resume_breakpoint_at_sal (sr_sal, null_frame_id);
3815
3816       /* And make sure stepping stops right away then.  */
3817       ecs->event_thread->step_range_end = ecs->event_thread->step_range_start;
3818     }
3819   keep_going (ecs);
3820 }
3821
3822 /* Inferior has stepped backward into a subroutine call with source
3823    code that we should not step over.  Do step to the beginning of the
3824    last line of code in it.  */
3825
3826 static void
3827 handle_step_into_function_backward (struct execution_control_state *ecs)
3828 {
3829   struct symtab *s;
3830   struct symtab_and_line stop_func_sal, sr_sal;
3831
3832   s = find_pc_symtab (stop_pc);
3833   if (s && s->language != language_asm)
3834     ecs->stop_func_start = gdbarch_skip_prologue (current_gdbarch, 
3835                                                   ecs->stop_func_start);
3836
3837   stop_func_sal = find_pc_line (stop_pc, 0);
3838
3839   /* OK, we're just going to keep stepping here.  */
3840   if (stop_func_sal.pc == stop_pc)
3841     {
3842       /* We're there already.  Just stop stepping now.  */
3843       ecs->event_thread->stop_step = 1;
3844       print_stop_reason (END_STEPPING_RANGE, 0);
3845       stop_stepping (ecs);
3846     }
3847   else
3848     {
3849       /* Else just reset the step range and keep going.
3850          No step-resume breakpoint, they don't work for
3851          epilogues, which can have multiple entry paths.  */
3852       ecs->event_thread->step_range_start = stop_func_sal.pc;
3853       ecs->event_thread->step_range_end = stop_func_sal.end;
3854       keep_going (ecs);
3855     }
3856   return;
3857 }
3858
3859 /* Insert a "step-resume breakpoint" at SR_SAL with frame ID SR_ID.
3860    This is used to both functions and to skip over code.  */
3861
3862 static void
3863 insert_step_resume_breakpoint_at_sal (struct symtab_and_line sr_sal,
3864                                       struct frame_id sr_id)
3865 {
3866   /* There should never be more than one step-resume or longjmp-resume
3867      breakpoint per thread, so we should never be setting a new
3868      step_resume_breakpoint when one is already active.  */
3869   gdb_assert (inferior_thread ()->step_resume_breakpoint == NULL);
3870
3871   if (debug_infrun)
3872     fprintf_unfiltered (gdb_stdlog,
3873                         "infrun: inserting step-resume breakpoint at 0x%s\n",
3874                         paddr_nz (sr_sal.pc));
3875
3876   inferior_thread ()->step_resume_breakpoint
3877     = set_momentary_breakpoint (sr_sal, sr_id, bp_step_resume);
3878 }
3879
3880 /* Insert a "step-resume breakpoint" at RETURN_FRAME.pc.  This is used
3881    to skip a potential signal handler.
3882
3883    This is called with the interrupted function's frame.  The signal
3884    handler, when it returns, will resume the interrupted function at
3885    RETURN_FRAME.pc.  */
3886
3887 static void
3888 insert_step_resume_breakpoint_at_frame (struct frame_info *return_frame)
3889 {
3890   struct symtab_and_line sr_sal;
3891
3892   gdb_assert (return_frame != NULL);
3893   init_sal (&sr_sal);           /* initialize to zeros */
3894
3895   sr_sal.pc = gdbarch_addr_bits_remove
3896                 (current_gdbarch, get_frame_pc (return_frame));
3897   sr_sal.section = find_pc_overlay (sr_sal.pc);
3898
3899   insert_step_resume_breakpoint_at_sal (sr_sal, get_frame_id (return_frame));
3900 }
3901
3902 /* Similar to insert_step_resume_breakpoint_at_frame, except
3903    but a breakpoint at the previous frame's PC.  This is used to
3904    skip a function after stepping into it (for "next" or if the called
3905    function has no debugging information).
3906
3907    The current function has almost always been reached by single
3908    stepping a call or return instruction.  NEXT_FRAME belongs to the
3909    current function, and the breakpoint will be set at the caller's
3910    resume address.
3911
3912    This is a separate function rather than reusing
3913    insert_step_resume_breakpoint_at_frame in order to avoid
3914    get_prev_frame, which may stop prematurely (see the implementation
3915    of frame_unwind_id for an example).  */
3916
3917 static void
3918 insert_step_resume_breakpoint_at_caller (struct frame_info *next_frame)
3919 {
3920   struct symtab_and_line sr_sal;
3921
3922   /* We shouldn't have gotten here if we don't know where the call site
3923      is.  */
3924   gdb_assert (frame_id_p (frame_unwind_id (next_frame)));
3925
3926   init_sal (&sr_sal);           /* initialize to zeros */
3927
3928   sr_sal.pc = gdbarch_addr_bits_remove
3929                 (current_gdbarch, frame_pc_unwind (next_frame));
3930   sr_sal.section = find_pc_overlay (sr_sal.pc);
3931
3932   insert_step_resume_breakpoint_at_sal (sr_sal, frame_unwind_id (next_frame));
3933 }
3934
3935 /* Insert a "longjmp-resume" breakpoint at PC.  This is used to set a
3936    new breakpoint at the target of a jmp_buf.  The handling of
3937    longjmp-resume uses the same mechanisms used for handling
3938    "step-resume" breakpoints.  */
3939
3940 static void
3941 insert_longjmp_resume_breakpoint (CORE_ADDR pc)
3942 {
3943   /* There should never be more than one step-resume or longjmp-resume
3944      breakpoint per thread, so we should never be setting a new
3945      longjmp_resume_breakpoint when one is already active.  */
3946   gdb_assert (inferior_thread ()->step_resume_breakpoint == NULL);
3947
3948   if (debug_infrun)
3949     fprintf_unfiltered (gdb_stdlog,
3950                         "infrun: inserting longjmp-resume breakpoint at 0x%s\n",
3951                         paddr_nz (pc));
3952
3953   inferior_thread ()->step_resume_breakpoint =
3954     set_momentary_breakpoint_at_pc (pc, bp_longjmp_resume);
3955 }
3956
3957 static void
3958 stop_stepping (struct execution_control_state *ecs)
3959 {
3960   if (debug_infrun)
3961     fprintf_unfiltered (gdb_stdlog, "infrun: stop_stepping\n");
3962
3963   /* Let callers know we don't want to wait for the inferior anymore.  */
3964   ecs->wait_some_more = 0;
3965 }
3966
3967 /* This function handles various cases where we need to continue
3968    waiting for the inferior.  */
3969 /* (Used to be the keep_going: label in the old wait_for_inferior) */
3970
3971 static void
3972 keep_going (struct execution_control_state *ecs)
3973 {
3974   /* Save the pc before execution, to compare with pc after stop.  */
3975   ecs->event_thread->prev_pc = read_pc ();              /* Might have been DECR_AFTER_BREAK */
3976
3977   /* If we did not do break;, it means we should keep running the
3978      inferior and not return to debugger.  */
3979
3980   if (ecs->event_thread->trap_expected
3981       && ecs->event_thread->stop_signal != TARGET_SIGNAL_TRAP)
3982     {
3983       /* We took a signal (which we are supposed to pass through to
3984          the inferior, else we'd not get here) and we haven't yet
3985          gotten our trap.  Simply continue.  */
3986       resume (currently_stepping (ecs->event_thread),
3987               ecs->event_thread->stop_signal);
3988     }
3989   else
3990     {
3991       /* Either the trap was not expected, but we are continuing
3992          anyway (the user asked that this signal be passed to the
3993          child)
3994          -- or --
3995          The signal was SIGTRAP, e.g. it was our signal, but we
3996          decided we should resume from it.
3997
3998          We're going to run this baby now!  
3999
4000          Note that insert_breakpoints won't try to re-insert
4001          already inserted breakpoints.  Therefore, we don't
4002          care if breakpoints were already inserted, or not.  */
4003       
4004       if (ecs->event_thread->stepping_over_breakpoint)
4005         {
4006           if (! use_displaced_stepping (current_gdbarch))
4007             /* Since we can't do a displaced step, we have to remove
4008                the breakpoint while we step it.  To keep things
4009                simple, we remove them all.  */
4010             remove_breakpoints ();
4011         }
4012       else
4013         {
4014           struct gdb_exception e;
4015           /* Stop stepping when inserting breakpoints
4016              has failed.  */
4017           TRY_CATCH (e, RETURN_MASK_ERROR)
4018             {
4019               insert_breakpoints ();
4020             }
4021           if (e.reason < 0)
4022             {
4023               stop_stepping (ecs);
4024               return;
4025             }
4026         }
4027
4028       ecs->event_thread->trap_expected = ecs->event_thread->stepping_over_breakpoint;
4029
4030       /* Do not deliver SIGNAL_TRAP (except when the user explicitly
4031          specifies that such a signal should be delivered to the
4032          target program).
4033
4034          Typically, this would occure when a user is debugging a
4035          target monitor on a simulator: the target monitor sets a
4036          breakpoint; the simulator encounters this break-point and
4037          halts the simulation handing control to GDB; GDB, noteing
4038          that the break-point isn't valid, returns control back to the
4039          simulator; the simulator then delivers the hardware
4040          equivalent of a SIGNAL_TRAP to the program being debugged. */
4041
4042       if (ecs->event_thread->stop_signal == TARGET_SIGNAL_TRAP
4043           && !signal_program[ecs->event_thread->stop_signal])
4044         ecs->event_thread->stop_signal = TARGET_SIGNAL_0;
4045
4046       resume (currently_stepping (ecs->event_thread),
4047               ecs->event_thread->stop_signal);
4048     }
4049
4050   prepare_to_wait (ecs);
4051 }
4052
4053 /* This function normally comes after a resume, before
4054    handle_inferior_event exits.  It takes care of any last bits of
4055    housekeeping, and sets the all-important wait_some_more flag.  */
4056
4057 static void
4058 prepare_to_wait (struct execution_control_state *ecs)
4059 {
4060   if (debug_infrun)
4061     fprintf_unfiltered (gdb_stdlog, "infrun: prepare_to_wait\n");
4062   if (infwait_state == infwait_normal_state)
4063     {
4064       overlay_cache_invalid = 1;
4065
4066       /* We have to invalidate the registers BEFORE calling
4067          target_wait because they can be loaded from the target while
4068          in target_wait.  This makes remote debugging a bit more
4069          efficient for those targets that provide critical registers
4070          as part of their normal status mechanism. */
4071
4072       registers_changed ();
4073       waiton_ptid = pid_to_ptid (-1);
4074     }
4075   /* This is the old end of the while loop.  Let everybody know we
4076      want to wait for the inferior some more and get called again
4077      soon.  */
4078   ecs->wait_some_more = 1;
4079 }
4080
4081 /* Print why the inferior has stopped. We always print something when
4082    the inferior exits, or receives a signal. The rest of the cases are
4083    dealt with later on in normal_stop() and print_it_typical().  Ideally
4084    there should be a call to this function from handle_inferior_event()
4085    each time stop_stepping() is called.*/
4086 static void
4087 print_stop_reason (enum inferior_stop_reason stop_reason, int stop_info)
4088 {
4089   switch (stop_reason)
4090     {
4091     case END_STEPPING_RANGE:
4092       /* We are done with a step/next/si/ni command. */
4093       /* For now print nothing. */
4094       /* Print a message only if not in the middle of doing a "step n"
4095          operation for n > 1 */
4096       if (!inferior_thread ()->step_multi
4097           || !inferior_thread ()->stop_step)
4098         if (ui_out_is_mi_like_p (uiout))
4099           ui_out_field_string
4100             (uiout, "reason",
4101              async_reason_lookup (EXEC_ASYNC_END_STEPPING_RANGE));
4102       break;
4103     case SIGNAL_EXITED:
4104       /* The inferior was terminated by a signal. */
4105       annotate_signalled ();
4106       if (ui_out_is_mi_like_p (uiout))
4107         ui_out_field_string
4108           (uiout, "reason",
4109            async_reason_lookup (EXEC_ASYNC_EXITED_SIGNALLED));
4110       ui_out_text (uiout, "\nProgram terminated with signal ");
4111       annotate_signal_name ();
4112       ui_out_field_string (uiout, "signal-name",
4113                            target_signal_to_name (stop_info));
4114       annotate_signal_name_end ();
4115       ui_out_text (uiout, ", ");
4116       annotate_signal_string ();
4117       ui_out_field_string (uiout, "signal-meaning",
4118                            target_signal_to_string (stop_info));
4119       annotate_signal_string_end ();
4120       ui_out_text (uiout, ".\n");
4121       ui_out_text (uiout, "The program no longer exists.\n");
4122       break;
4123     case EXITED:
4124       /* The inferior program is finished. */
4125       annotate_exited (stop_info);
4126       if (stop_info)
4127         {
4128           if (ui_out_is_mi_like_p (uiout))
4129             ui_out_field_string (uiout, "reason", 
4130                                  async_reason_lookup (EXEC_ASYNC_EXITED));
4131           ui_out_text (uiout, "\nProgram exited with code ");
4132           ui_out_field_fmt (uiout, "exit-code", "0%o",
4133                             (unsigned int) stop_info);
4134           ui_out_text (uiout, ".\n");
4135         }
4136       else
4137         {
4138           if (ui_out_is_mi_like_p (uiout))
4139             ui_out_field_string
4140               (uiout, "reason",
4141                async_reason_lookup (EXEC_ASYNC_EXITED_NORMALLY));
4142           ui_out_text (uiout, "\nProgram exited normally.\n");
4143         }
4144       /* Support the --return-child-result option.  */
4145       return_child_result_value = stop_info;
4146       break;
4147     case SIGNAL_RECEIVED:
4148       /* Signal received.  The signal table tells us to print about
4149          it. */
4150       annotate_signal ();
4151
4152       if (stop_info == TARGET_SIGNAL_0 && !ui_out_is_mi_like_p (uiout))
4153         {
4154           struct thread_info *t = inferior_thread ();
4155
4156           ui_out_text (uiout, "\n[");
4157           ui_out_field_string (uiout, "thread-name",
4158                                target_pid_to_str (t->ptid));
4159           ui_out_field_fmt (uiout, "thread-id", "] #%d", t->num);
4160           ui_out_text (uiout, " stopped");
4161         }
4162       else
4163         {
4164           ui_out_text (uiout, "\nProgram received signal ");
4165           annotate_signal_name ();
4166           if (ui_out_is_mi_like_p (uiout))
4167             ui_out_field_string
4168               (uiout, "reason", async_reason_lookup (EXEC_ASYNC_SIGNAL_RECEIVED));
4169           ui_out_field_string (uiout, "signal-name",
4170                                target_signal_to_name (stop_info));
4171           annotate_signal_name_end ();
4172           ui_out_text (uiout, ", ");
4173           annotate_signal_string ();
4174           ui_out_field_string (uiout, "signal-meaning",
4175                                target_signal_to_string (stop_info));
4176           annotate_signal_string_end ();
4177         }
4178       ui_out_text (uiout, ".\n");
4179       break;
4180     case NO_HISTORY:
4181       /* Reverse execution: target ran out of history info.  */
4182       ui_out_text (uiout, "\nNo more reverse-execution history.\n");
4183       break;
4184     default:
4185       internal_error (__FILE__, __LINE__,
4186                       _("print_stop_reason: unrecognized enum value"));
4187       break;
4188     }
4189 }
4190 \f
4191
4192 /* Here to return control to GDB when the inferior stops for real.
4193    Print appropriate messages, remove breakpoints, give terminal our modes.
4194
4195    STOP_PRINT_FRAME nonzero means print the executing frame
4196    (pc, function, args, file, line number and line text).
4197    BREAKPOINTS_FAILED nonzero means stop was due to error
4198    attempting to insert breakpoints.  */
4199
4200 void
4201 normal_stop (void)
4202 {
4203   struct target_waitstatus last;
4204   ptid_t last_ptid;
4205   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
4206
4207   get_last_target_status (&last_ptid, &last);
4208
4209   /* If an exception is thrown from this point on, make sure to
4210      propagate GDB's knowledge of the executing state to the
4211      frontend/user running state.  A QUIT is an easy exception to see
4212      here, so do this before any filtered output.  */
4213   if (target_has_execution)
4214     {
4215       if (!non_stop)
4216         old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
4217       else if (last.kind != TARGET_WAITKIND_SIGNALLED
4218                && last.kind != TARGET_WAITKIND_EXITED)
4219         old_chain = make_cleanup (finish_thread_state_cleanup, &inferior_ptid);
4220     }
4221
4222   /* In non-stop mode, we don't want GDB to switch threads behind the
4223      user's back, to avoid races where the user is typing a command to
4224      apply to thread x, but GDB switches to thread y before the user
4225      finishes entering the command.  */
4226
4227   /* As with the notification of thread events, we want to delay
4228      notifying the user that we've switched thread context until
4229      the inferior actually stops.
4230
4231      There's no point in saying anything if the inferior has exited.
4232      Note that SIGNALLED here means "exited with a signal", not
4233      "received a signal".  */
4234   if (!non_stop
4235       && !ptid_equal (previous_inferior_ptid, inferior_ptid)
4236       && target_has_execution
4237       && last.kind != TARGET_WAITKIND_SIGNALLED
4238       && last.kind != TARGET_WAITKIND_EXITED)
4239     {
4240       target_terminal_ours_for_output ();
4241       printf_filtered (_("[Switching to %s]\n"),
4242                        target_pid_to_str (inferior_ptid));
4243       annotate_thread_changed ();
4244       previous_inferior_ptid = inferior_ptid;
4245     }
4246
4247   if (!breakpoints_always_inserted_mode () && target_has_execution)
4248     {
4249       if (remove_breakpoints ())
4250         {
4251           target_terminal_ours_for_output ();
4252           printf_filtered (_("\
4253 Cannot remove breakpoints because program is no longer writable.\n\
4254 Further execution is probably impossible.\n"));
4255         }
4256     }
4257
4258   /* If an auto-display called a function and that got a signal,
4259      delete that auto-display to avoid an infinite recursion.  */
4260
4261   if (stopped_by_random_signal)
4262     disable_current_display ();
4263
4264   /* Don't print a message if in the middle of doing a "step n"
4265      operation for n > 1 */
4266   if (target_has_execution
4267       && last.kind != TARGET_WAITKIND_SIGNALLED
4268       && last.kind != TARGET_WAITKIND_EXITED
4269       && inferior_thread ()->step_multi
4270       && inferior_thread ()->stop_step)
4271     goto done;
4272
4273   target_terminal_ours ();
4274
4275   /* Set the current source location.  This will also happen if we
4276      display the frame below, but the current SAL will be incorrect
4277      during a user hook-stop function.  */
4278   if (target_has_stack && !stop_stack_dummy)
4279     set_current_sal_from_frame (get_current_frame (), 1);
4280
4281   /* Let the user/frontend see the threads as stopped.  */
4282   do_cleanups (old_chain);
4283
4284   /* Look up the hook_stop and run it (CLI internally handles problem
4285      of stop_command's pre-hook not existing).  */
4286   if (stop_command)
4287     catch_errors (hook_stop_stub, stop_command,
4288                   "Error while running hook_stop:\n", RETURN_MASK_ALL);
4289
4290   if (!target_has_stack)
4291     goto done;
4292
4293   if (last.kind == TARGET_WAITKIND_SIGNALLED
4294       || last.kind == TARGET_WAITKIND_EXITED)
4295     goto done;
4296
4297   /* Select innermost stack frame - i.e., current frame is frame 0,
4298      and current location is based on that.
4299      Don't do this on return from a stack dummy routine,
4300      or if the program has exited. */
4301
4302   if (!stop_stack_dummy)
4303     {
4304       select_frame (get_current_frame ());
4305
4306       /* Print current location without a level number, if
4307          we have changed functions or hit a breakpoint.
4308          Print source line if we have one.
4309          bpstat_print() contains the logic deciding in detail
4310          what to print, based on the event(s) that just occurred. */
4311
4312       /* If --batch-silent is enabled then there's no need to print the current
4313          source location, and to try risks causing an error message about
4314          missing source files.  */
4315       if (stop_print_frame && !batch_silent)
4316         {
4317           int bpstat_ret;
4318           int source_flag;
4319           int do_frame_printing = 1;
4320           struct thread_info *tp = inferior_thread ();
4321
4322           bpstat_ret = bpstat_print (tp->stop_bpstat);
4323           switch (bpstat_ret)
4324             {
4325             case PRINT_UNKNOWN:
4326               /* If we had hit a shared library event breakpoint,
4327                  bpstat_print would print out this message.  If we hit
4328                  an OS-level shared library event, do the same
4329                  thing.  */
4330               if (last.kind == TARGET_WAITKIND_LOADED)
4331                 {
4332                   printf_filtered (_("Stopped due to shared library event\n"));
4333                   source_flag = SRC_LINE;       /* something bogus */
4334                   do_frame_printing = 0;
4335                   break;
4336                 }
4337
4338               /* FIXME: cagney/2002-12-01: Given that a frame ID does
4339                  (or should) carry around the function and does (or
4340                  should) use that when doing a frame comparison.  */
4341               if (tp->stop_step
4342                   && frame_id_eq (tp->step_frame_id,
4343                                   get_frame_id (get_current_frame ()))
4344                   && step_start_function == find_pc_function (stop_pc))
4345                 source_flag = SRC_LINE; /* finished step, just print source line */
4346               else
4347                 source_flag = SRC_AND_LOC;      /* print location and source line */
4348               break;
4349             case PRINT_SRC_AND_LOC:
4350               source_flag = SRC_AND_LOC;        /* print location and source line */
4351               break;
4352             case PRINT_SRC_ONLY:
4353               source_flag = SRC_LINE;
4354               break;
4355             case PRINT_NOTHING:
4356               source_flag = SRC_LINE;   /* something bogus */
4357               do_frame_printing = 0;
4358               break;
4359             default:
4360               internal_error (__FILE__, __LINE__, _("Unknown value."));
4361             }
4362
4363           if (ui_out_is_mi_like_p (uiout))
4364             {
4365
4366               ui_out_field_int (uiout, "thread-id",
4367                                 pid_to_thread_id (inferior_ptid));
4368               if (non_stop)
4369                 {
4370                   struct cleanup *back_to = make_cleanup_ui_out_list_begin_end 
4371                     (uiout, "stopped-threads");
4372                   ui_out_field_int (uiout, NULL,
4373                                     pid_to_thread_id (inferior_ptid));                            
4374                   do_cleanups (back_to);
4375                 }
4376               else
4377                 ui_out_field_string (uiout, "stopped-threads", "all");
4378             }
4379           /* The behavior of this routine with respect to the source
4380              flag is:
4381              SRC_LINE: Print only source line
4382              LOCATION: Print only location
4383              SRC_AND_LOC: Print location and source line */
4384           if (do_frame_printing)
4385             print_stack_frame (get_selected_frame (NULL), 0, source_flag);
4386
4387           /* Display the auto-display expressions.  */
4388           do_displays ();
4389         }
4390     }
4391
4392   /* Save the function value return registers, if we care.
4393      We might be about to restore their previous contents.  */
4394   if (inferior_thread ()->proceed_to_finish)
4395     {
4396       /* This should not be necessary.  */
4397       if (stop_registers)
4398         regcache_xfree (stop_registers);
4399
4400       /* NB: The copy goes through to the target picking up the value of
4401          all the registers.  */
4402       stop_registers = regcache_dup (get_current_regcache ());
4403     }
4404
4405   if (stop_stack_dummy)
4406     {
4407       /* Pop the empty frame that contains the stack dummy.
4408          This also restores inferior state prior to the call
4409          (struct inferior_thread_state).  */
4410       struct frame_info *frame = get_current_frame ();
4411       gdb_assert (get_frame_type (frame) == DUMMY_FRAME);
4412       frame_pop (frame);
4413       /* frame_pop() calls reinit_frame_cache as the last thing it does
4414          which means there's currently no selected frame.  We don't need
4415          to re-establish a selected frame if the dummy call returns normally,
4416          that will be done by restore_inferior_status.  However, we do have
4417          to handle the case where the dummy call is returning after being
4418          stopped (e.g. the dummy call previously hit a breakpoint).  We
4419          can't know which case we have so just always re-establish a
4420          selected frame here.  */
4421       select_frame (get_current_frame ());
4422     }
4423
4424 done:
4425   annotate_stopped ();
4426   if (!suppress_stop_observer
4427       && !(target_has_execution
4428            && last.kind != TARGET_WAITKIND_SIGNALLED
4429            && last.kind != TARGET_WAITKIND_EXITED
4430            && inferior_thread ()->step_multi))
4431     {
4432       if (!ptid_equal (inferior_ptid, null_ptid))
4433         observer_notify_normal_stop (inferior_thread ()->stop_bpstat);
4434       else
4435         observer_notify_normal_stop (NULL);
4436     }
4437
4438   if (target_has_execution)
4439     {
4440       if (last.kind != TARGET_WAITKIND_SIGNALLED
4441           && last.kind != TARGET_WAITKIND_EXITED)
4442         /* Delete the breakpoint we stopped at, if it wants to be deleted.
4443            Delete any breakpoint that is to be deleted at the next stop.  */
4444         breakpoint_auto_delete (inferior_thread ()->stop_bpstat);
4445     }
4446 }
4447
4448 static int
4449 hook_stop_stub (void *cmd)
4450 {
4451   execute_cmd_pre_hook ((struct cmd_list_element *) cmd);
4452   return (0);
4453 }
4454 \f
4455 int
4456 signal_stop_state (int signo)
4457 {
4458   return signal_stop[signo];
4459 }
4460
4461 int
4462 signal_print_state (int signo)
4463 {
4464   return signal_print[signo];
4465 }
4466
4467 int
4468 signal_pass_state (int signo)
4469 {
4470   return signal_program[signo];
4471 }
4472
4473 int
4474 signal_stop_update (int signo, int state)
4475 {
4476   int ret = signal_stop[signo];
4477   signal_stop[signo] = state;
4478   return ret;
4479 }
4480
4481 int
4482 signal_print_update (int signo, int state)
4483 {
4484   int ret = signal_print[signo];
4485   signal_print[signo] = state;
4486   return ret;
4487 }
4488
4489 int
4490 signal_pass_update (int signo, int state)
4491 {
4492   int ret = signal_program[signo];
4493   signal_program[signo] = state;
4494   return ret;
4495 }
4496
4497 static void
4498 sig_print_header (void)
4499 {
4500   printf_filtered (_("\
4501 Signal        Stop\tPrint\tPass to program\tDescription\n"));
4502 }
4503
4504 static void
4505 sig_print_info (enum target_signal oursig)
4506 {
4507   const char *name = target_signal_to_name (oursig);
4508   int name_padding = 13 - strlen (name);
4509
4510   if (name_padding <= 0)
4511     name_padding = 0;
4512
4513   printf_filtered ("%s", name);
4514   printf_filtered ("%*.*s ", name_padding, name_padding, "                 ");
4515   printf_filtered ("%s\t", signal_stop[oursig] ? "Yes" : "No");
4516   printf_filtered ("%s\t", signal_print[oursig] ? "Yes" : "No");
4517   printf_filtered ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
4518   printf_filtered ("%s\n", target_signal_to_string (oursig));
4519 }
4520
4521 /* Specify how various signals in the inferior should be handled.  */
4522
4523 static void
4524 handle_command (char *args, int from_tty)
4525 {
4526   char **argv;
4527   int digits, wordlen;
4528   int sigfirst, signum, siglast;
4529   enum target_signal oursig;
4530   int allsigs;
4531   int nsigs;
4532   unsigned char *sigs;
4533   struct cleanup *old_chain;
4534
4535   if (args == NULL)
4536     {
4537       error_no_arg (_("signal to handle"));
4538     }
4539
4540   /* Allocate and zero an array of flags for which signals to handle. */
4541
4542   nsigs = (int) TARGET_SIGNAL_LAST;
4543   sigs = (unsigned char *) alloca (nsigs);
4544   memset (sigs, 0, nsigs);
4545
4546   /* Break the command line up into args. */
4547
4548   argv = gdb_buildargv (args);
4549   old_chain = make_cleanup_freeargv (argv);
4550
4551   /* Walk through the args, looking for signal oursigs, signal names, and
4552      actions.  Signal numbers and signal names may be interspersed with
4553      actions, with the actions being performed for all signals cumulatively
4554      specified.  Signal ranges can be specified as <LOW>-<HIGH>. */
4555
4556   while (*argv != NULL)
4557     {
4558       wordlen = strlen (*argv);
4559       for (digits = 0; isdigit ((*argv)[digits]); digits++)
4560         {;
4561         }
4562       allsigs = 0;
4563       sigfirst = siglast = -1;
4564
4565       if (wordlen >= 1 && !strncmp (*argv, "all", wordlen))
4566         {
4567           /* Apply action to all signals except those used by the
4568              debugger.  Silently skip those. */
4569           allsigs = 1;
4570           sigfirst = 0;
4571           siglast = nsigs - 1;
4572         }
4573       else if (wordlen >= 1 && !strncmp (*argv, "stop", wordlen))
4574         {
4575           SET_SIGS (nsigs, sigs, signal_stop);
4576           SET_SIGS (nsigs, sigs, signal_print);
4577         }
4578       else if (wordlen >= 1 && !strncmp (*argv, "ignore", wordlen))
4579         {
4580           UNSET_SIGS (nsigs, sigs, signal_program);
4581         }
4582       else if (wordlen >= 2 && !strncmp (*argv, "print", wordlen))
4583         {
4584           SET_SIGS (nsigs, sigs, signal_print);
4585         }
4586       else if (wordlen >= 2 && !strncmp (*argv, "pass", wordlen))
4587         {
4588           SET_SIGS (nsigs, sigs, signal_program);
4589         }
4590       else if (wordlen >= 3 && !strncmp (*argv, "nostop", wordlen))
4591         {
4592           UNSET_SIGS (nsigs, sigs, signal_stop);
4593         }
4594       else if (wordlen >= 3 && !strncmp (*argv, "noignore", wordlen))
4595         {
4596           SET_SIGS (nsigs, sigs, signal_program);
4597         }
4598       else if (wordlen >= 4 && !strncmp (*argv, "noprint", wordlen))
4599         {
4600           UNSET_SIGS (nsigs, sigs, signal_print);
4601           UNSET_SIGS (nsigs, sigs, signal_stop);
4602         }
4603       else if (wordlen >= 4 && !strncmp (*argv, "nopass", wordlen))
4604         {
4605           UNSET_SIGS (nsigs, sigs, signal_program);
4606         }
4607       else if (digits > 0)
4608         {
4609           /* It is numeric.  The numeric signal refers to our own
4610              internal signal numbering from target.h, not to host/target
4611              signal  number.  This is a feature; users really should be
4612              using symbolic names anyway, and the common ones like
4613              SIGHUP, SIGINT, SIGALRM, etc. will work right anyway.  */
4614
4615           sigfirst = siglast = (int)
4616             target_signal_from_command (atoi (*argv));
4617           if ((*argv)[digits] == '-')
4618             {
4619               siglast = (int)
4620                 target_signal_from_command (atoi ((*argv) + digits + 1));
4621             }
4622           if (sigfirst > siglast)
4623             {
4624               /* Bet he didn't figure we'd think of this case... */
4625               signum = sigfirst;
4626               sigfirst = siglast;
4627               siglast = signum;
4628             }
4629         }
4630       else
4631         {
4632           oursig = target_signal_from_name (*argv);
4633           if (oursig != TARGET_SIGNAL_UNKNOWN)
4634             {
4635               sigfirst = siglast = (int) oursig;
4636             }
4637           else
4638             {
4639               /* Not a number and not a recognized flag word => complain.  */
4640               error (_("Unrecognized or ambiguous flag word: \"%s\"."), *argv);
4641             }
4642         }
4643
4644       /* If any signal numbers or symbol names were found, set flags for
4645          which signals to apply actions to. */
4646
4647       for (signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
4648         {
4649           switch ((enum target_signal) signum)
4650             {
4651             case TARGET_SIGNAL_TRAP:
4652             case TARGET_SIGNAL_INT:
4653               if (!allsigs && !sigs[signum])
4654                 {
4655                   if (query ("%s is used by the debugger.\n\
4656 Are you sure you want to change it? ", target_signal_to_name ((enum target_signal) signum)))
4657                     {
4658                       sigs[signum] = 1;
4659                     }
4660                   else
4661                     {
4662                       printf_unfiltered (_("Not confirmed, unchanged.\n"));
4663                       gdb_flush (gdb_stdout);
4664                     }
4665                 }
4666               break;
4667             case TARGET_SIGNAL_0:
4668             case TARGET_SIGNAL_DEFAULT:
4669             case TARGET_SIGNAL_UNKNOWN:
4670               /* Make sure that "all" doesn't print these.  */
4671               break;
4672             default:
4673               sigs[signum] = 1;
4674               break;
4675             }
4676         }
4677
4678       argv++;
4679     }
4680
4681   for (signum = 0; signum < nsigs; signum++)
4682     if (sigs[signum])
4683       {
4684         target_notice_signals (inferior_ptid);
4685
4686         if (from_tty)
4687           {
4688             /* Show the results.  */
4689             sig_print_header ();
4690             for (; signum < nsigs; signum++)
4691               if (sigs[signum])
4692                 sig_print_info (signum);
4693           }
4694
4695         break;
4696       }
4697
4698   do_cleanups (old_chain);
4699 }
4700
4701 static void
4702 xdb_handle_command (char *args, int from_tty)
4703 {
4704   char **argv;
4705   struct cleanup *old_chain;
4706
4707   if (args == NULL)
4708     error_no_arg (_("xdb command"));
4709
4710   /* Break the command line up into args. */
4711
4712   argv = gdb_buildargv (args);
4713   old_chain = make_cleanup_freeargv (argv);
4714   if (argv[1] != (char *) NULL)
4715     {
4716       char *argBuf;
4717       int bufLen;
4718
4719       bufLen = strlen (argv[0]) + 20;
4720       argBuf = (char *) xmalloc (bufLen);
4721       if (argBuf)
4722         {
4723           int validFlag = 1;
4724           enum target_signal oursig;
4725
4726           oursig = target_signal_from_name (argv[0]);
4727           memset (argBuf, 0, bufLen);
4728           if (strcmp (argv[1], "Q") == 0)
4729             sprintf (argBuf, "%s %s", argv[0], "noprint");
4730           else
4731             {
4732               if (strcmp (argv[1], "s") == 0)
4733                 {
4734                   if (!signal_stop[oursig])
4735                     sprintf (argBuf, "%s %s", argv[0], "stop");
4736                   else
4737                     sprintf (argBuf, "%s %s", argv[0], "nostop");
4738                 }
4739               else if (strcmp (argv[1], "i") == 0)
4740                 {
4741                   if (!signal_program[oursig])
4742                     sprintf (argBuf, "%s %s", argv[0], "pass");
4743                   else
4744                     sprintf (argBuf, "%s %s", argv[0], "nopass");
4745                 }
4746               else if (strcmp (argv[1], "r") == 0)
4747                 {
4748                   if (!signal_print[oursig])
4749                     sprintf (argBuf, "%s %s", argv[0], "print");
4750                   else
4751                     sprintf (argBuf, "%s %s", argv[0], "noprint");
4752                 }
4753               else
4754                 validFlag = 0;
4755             }
4756           if (validFlag)
4757             handle_command (argBuf, from_tty);
4758           else
4759             printf_filtered (_("Invalid signal handling flag.\n"));
4760           if (argBuf)
4761             xfree (argBuf);
4762         }
4763     }
4764   do_cleanups (old_chain);
4765 }
4766
4767 /* Print current contents of the tables set by the handle command.
4768    It is possible we should just be printing signals actually used
4769    by the current target (but for things to work right when switching
4770    targets, all signals should be in the signal tables).  */
4771
4772 static void
4773 signals_info (char *signum_exp, int from_tty)
4774 {
4775   enum target_signal oursig;
4776   sig_print_header ();
4777
4778   if (signum_exp)
4779     {
4780       /* First see if this is a symbol name.  */
4781       oursig = target_signal_from_name (signum_exp);
4782       if (oursig == TARGET_SIGNAL_UNKNOWN)
4783         {
4784           /* No, try numeric.  */
4785           oursig =
4786             target_signal_from_command (parse_and_eval_long (signum_exp));
4787         }
4788       sig_print_info (oursig);
4789       return;
4790     }
4791
4792   printf_filtered ("\n");
4793   /* These ugly casts brought to you by the native VAX compiler.  */
4794   for (oursig = TARGET_SIGNAL_FIRST;
4795        (int) oursig < (int) TARGET_SIGNAL_LAST;
4796        oursig = (enum target_signal) ((int) oursig + 1))
4797     {
4798       QUIT;
4799
4800       if (oursig != TARGET_SIGNAL_UNKNOWN
4801           && oursig != TARGET_SIGNAL_DEFAULT && oursig != TARGET_SIGNAL_0)
4802         sig_print_info (oursig);
4803     }
4804
4805   printf_filtered (_("\nUse the \"handle\" command to change these tables.\n"));
4806 }
4807 \f
4808 /* Inferior thread state.
4809    These are details related to the inferior itself, and don't include
4810    things like what frame the user had selected or what gdb was doing
4811    with the target at the time.
4812    For inferior function calls these are things we want to restore
4813    regardless of whether the function call successfully completes
4814    or the dummy frame has to be manually popped.  */
4815
4816 struct inferior_thread_state
4817 {
4818   enum target_signal stop_signal;
4819   CORE_ADDR stop_pc;
4820   struct regcache *registers;
4821 };
4822
4823 struct inferior_thread_state *
4824 save_inferior_thread_state (void)
4825 {
4826   struct inferior_thread_state *inf_state = XMALLOC (struct inferior_thread_state);
4827   struct thread_info *tp = inferior_thread ();
4828
4829   inf_state->stop_signal = tp->stop_signal;
4830   inf_state->stop_pc = stop_pc;
4831
4832   inf_state->registers = regcache_dup (get_current_regcache ());
4833
4834   return inf_state;
4835 }
4836
4837 /* Restore inferior session state to INF_STATE.  */
4838
4839 void
4840 restore_inferior_thread_state (struct inferior_thread_state *inf_state)
4841 {
4842   struct thread_info *tp = inferior_thread ();
4843
4844   tp->stop_signal = inf_state->stop_signal;
4845   stop_pc = inf_state->stop_pc;
4846
4847   /* The inferior can be gone if the user types "print exit(0)"
4848      (and perhaps other times).  */
4849   if (target_has_execution)
4850     /* NB: The register write goes through to the target.  */
4851     regcache_cpy (get_current_regcache (), inf_state->registers);
4852   regcache_xfree (inf_state->registers);
4853   xfree (inf_state);
4854 }
4855
4856 static void
4857 do_restore_inferior_thread_state_cleanup (void *state)
4858 {
4859   restore_inferior_thread_state (state);
4860 }
4861
4862 struct cleanup *
4863 make_cleanup_restore_inferior_thread_state (struct inferior_thread_state *inf_state)
4864 {
4865   return make_cleanup (do_restore_inferior_thread_state_cleanup, inf_state);
4866 }
4867
4868 void
4869 discard_inferior_thread_state (struct inferior_thread_state *inf_state)
4870 {
4871   regcache_xfree (inf_state->registers);
4872   xfree (inf_state);
4873 }
4874
4875 struct regcache *
4876 get_inferior_thread_state_regcache (struct inferior_thread_state *inf_state)
4877 {
4878   return inf_state->registers;
4879 }
4880
4881 /* Session related state for inferior function calls.
4882    These are the additional bits of state that need to be restored
4883    when an inferior function call successfully completes.  */
4884
4885 struct inferior_status
4886 {
4887   bpstat stop_bpstat;
4888   int stop_step;
4889   int stop_stack_dummy;
4890   int stopped_by_random_signal;
4891   int stepping_over_breakpoint;
4892   CORE_ADDR step_range_start;
4893   CORE_ADDR step_range_end;
4894   struct frame_id step_frame_id;
4895   enum step_over_calls_kind step_over_calls;
4896   CORE_ADDR step_resume_break_address;
4897   int stop_after_trap;
4898   int stop_soon;
4899
4900   /* ID if the selected frame when the inferior function call was made.  */
4901   struct frame_id selected_frame_id;
4902
4903   int breakpoint_proceeded;
4904   int proceed_to_finish;
4905 };
4906
4907 /* Save all of the information associated with the inferior<==>gdb
4908    connection.  */
4909
4910 struct inferior_status *
4911 save_inferior_status (void)
4912 {
4913   struct inferior_status *inf_status = XMALLOC (struct inferior_status);
4914   struct thread_info *tp = inferior_thread ();
4915   struct inferior *inf = current_inferior ();
4916
4917   inf_status->stop_step = tp->stop_step;
4918   inf_status->stop_stack_dummy = stop_stack_dummy;
4919   inf_status->stopped_by_random_signal = stopped_by_random_signal;
4920   inf_status->stepping_over_breakpoint = tp->trap_expected;
4921   inf_status->step_range_start = tp->step_range_start;
4922   inf_status->step_range_end = tp->step_range_end;
4923   inf_status->step_frame_id = tp->step_frame_id;
4924   inf_status->step_over_calls = tp->step_over_calls;
4925   inf_status->stop_after_trap = stop_after_trap;
4926   inf_status->stop_soon = inf->stop_soon;
4927   /* Save original bpstat chain here; replace it with copy of chain.
4928      If caller's caller is walking the chain, they'll be happier if we
4929      hand them back the original chain when restore_inferior_status is
4930      called.  */
4931   inf_status->stop_bpstat = tp->stop_bpstat;
4932   tp->stop_bpstat = bpstat_copy (tp->stop_bpstat);
4933   inf_status->breakpoint_proceeded = breakpoint_proceeded;
4934   inf_status->proceed_to_finish = tp->proceed_to_finish;
4935
4936   inf_status->selected_frame_id = get_frame_id (get_selected_frame (NULL));
4937
4938   return inf_status;
4939 }
4940
4941 static int
4942 restore_selected_frame (void *args)
4943 {
4944   struct frame_id *fid = (struct frame_id *) args;
4945   struct frame_info *frame;
4946
4947   frame = frame_find_by_id (*fid);
4948
4949   /* If inf_status->selected_frame_id is NULL, there was no previously
4950      selected frame.  */
4951   if (frame == NULL)
4952     {
4953       warning (_("Unable to restore previously selected frame."));
4954       return 0;
4955     }
4956
4957   select_frame (frame);
4958
4959   return (1);
4960 }
4961
4962 /* Restore inferior session state to INF_STATUS.  */
4963
4964 void
4965 restore_inferior_status (struct inferior_status *inf_status)
4966 {
4967   struct thread_info *tp = inferior_thread ();
4968   struct inferior *inf = current_inferior ();
4969
4970   tp->stop_step = inf_status->stop_step;
4971   stop_stack_dummy = inf_status->stop_stack_dummy;
4972   stopped_by_random_signal = inf_status->stopped_by_random_signal;
4973   tp->trap_expected = inf_status->stepping_over_breakpoint;
4974   tp->step_range_start = inf_status->step_range_start;
4975   tp->step_range_end = inf_status->step_range_end;
4976   tp->step_frame_id = inf_status->step_frame_id;
4977   tp->step_over_calls = inf_status->step_over_calls;
4978   stop_after_trap = inf_status->stop_after_trap;
4979   inf->stop_soon = inf_status->stop_soon;
4980   bpstat_clear (&tp->stop_bpstat);
4981   tp->stop_bpstat = inf_status->stop_bpstat;
4982   inf_status->stop_bpstat = NULL;
4983   breakpoint_proceeded = inf_status->breakpoint_proceeded;
4984   tp->proceed_to_finish = inf_status->proceed_to_finish;
4985
4986   if (target_has_stack)
4987     {
4988       /* The point of catch_errors is that if the stack is clobbered,
4989          walking the stack might encounter a garbage pointer and
4990          error() trying to dereference it.  */
4991       if (catch_errors
4992           (restore_selected_frame, &inf_status->selected_frame_id,
4993            "Unable to restore previously selected frame:\n",
4994            RETURN_MASK_ERROR) == 0)
4995         /* Error in restoring the selected frame.  Select the innermost
4996            frame.  */
4997         select_frame (get_current_frame ());
4998     }
4999
5000   xfree (inf_status);
5001 }
5002
5003 static void
5004 do_restore_inferior_status_cleanup (void *sts)
5005 {
5006   restore_inferior_status (sts);
5007 }
5008
5009 struct cleanup *
5010 make_cleanup_restore_inferior_status (struct inferior_status *inf_status)
5011 {
5012   return make_cleanup (do_restore_inferior_status_cleanup, inf_status);
5013 }
5014
5015 void
5016 discard_inferior_status (struct inferior_status *inf_status)
5017 {
5018   /* See save_inferior_status for info on stop_bpstat. */
5019   bpstat_clear (&inf_status->stop_bpstat);
5020   xfree (inf_status);
5021 }
5022 \f
5023 int
5024 inferior_has_forked (ptid_t pid, ptid_t *child_pid)
5025 {
5026   struct target_waitstatus last;
5027   ptid_t last_ptid;
5028
5029   get_last_target_status (&last_ptid, &last);
5030
5031   if (last.kind != TARGET_WAITKIND_FORKED)
5032     return 0;
5033
5034   if (!ptid_equal (last_ptid, pid))
5035     return 0;
5036
5037   *child_pid = last.value.related_pid;
5038   return 1;
5039 }
5040
5041 int
5042 inferior_has_vforked (ptid_t pid, ptid_t *child_pid)
5043 {
5044   struct target_waitstatus last;
5045   ptid_t last_ptid;
5046
5047   get_last_target_status (&last_ptid, &last);
5048
5049   if (last.kind != TARGET_WAITKIND_VFORKED)
5050     return 0;
5051
5052   if (!ptid_equal (last_ptid, pid))
5053     return 0;
5054
5055   *child_pid = last.value.related_pid;
5056   return 1;
5057 }
5058
5059 int
5060 inferior_has_execd (ptid_t pid, char **execd_pathname)
5061 {
5062   struct target_waitstatus last;
5063   ptid_t last_ptid;
5064
5065   get_last_target_status (&last_ptid, &last);
5066
5067   if (last.kind != TARGET_WAITKIND_EXECD)
5068     return 0;
5069
5070   if (!ptid_equal (last_ptid, pid))
5071     return 0;
5072
5073   *execd_pathname = xstrdup (last.value.execd_pathname);
5074   return 1;
5075 }
5076
5077 /* Oft used ptids */
5078 ptid_t null_ptid;
5079 ptid_t minus_one_ptid;
5080
5081 /* Create a ptid given the necessary PID, LWP, and TID components.  */
5082
5083 ptid_t
5084 ptid_build (int pid, long lwp, long tid)
5085 {
5086   ptid_t ptid;
5087
5088   ptid.pid = pid;
5089   ptid.lwp = lwp;
5090   ptid.tid = tid;
5091   return ptid;
5092 }
5093
5094 /* Create a ptid from just a pid.  */
5095
5096 ptid_t
5097 pid_to_ptid (int pid)
5098 {
5099   return ptid_build (pid, 0, 0);
5100 }
5101
5102 /* Fetch the pid (process id) component from a ptid.  */
5103
5104 int
5105 ptid_get_pid (ptid_t ptid)
5106 {
5107   return ptid.pid;
5108 }
5109
5110 /* Fetch the lwp (lightweight process) component from a ptid.  */
5111
5112 long
5113 ptid_get_lwp (ptid_t ptid)
5114 {
5115   return ptid.lwp;
5116 }
5117
5118 /* Fetch the tid (thread id) component from a ptid.  */
5119
5120 long
5121 ptid_get_tid (ptid_t ptid)
5122 {
5123   return ptid.tid;
5124 }
5125
5126 /* ptid_equal() is used to test equality of two ptids.  */
5127
5128 int
5129 ptid_equal (ptid_t ptid1, ptid_t ptid2)
5130 {
5131   return (ptid1.pid == ptid2.pid && ptid1.lwp == ptid2.lwp
5132           && ptid1.tid == ptid2.tid);
5133 }
5134
5135 /* Returns true if PTID represents a process.  */
5136
5137 int
5138 ptid_is_pid (ptid_t ptid)
5139 {
5140   if (ptid_equal (minus_one_ptid, ptid))
5141     return 0;
5142   if (ptid_equal (null_ptid, ptid))
5143     return 0;
5144
5145   return (ptid_get_lwp (ptid) == 0 && ptid_get_tid (ptid) == 0);
5146 }
5147
5148 /* restore_inferior_ptid() will be used by the cleanup machinery
5149    to restore the inferior_ptid value saved in a call to
5150    save_inferior_ptid().  */
5151
5152 static void
5153 restore_inferior_ptid (void *arg)
5154 {
5155   ptid_t *saved_ptid_ptr = arg;
5156   inferior_ptid = *saved_ptid_ptr;
5157   xfree (arg);
5158 }
5159
5160 /* Save the value of inferior_ptid so that it may be restored by a
5161    later call to do_cleanups().  Returns the struct cleanup pointer
5162    needed for later doing the cleanup.  */
5163
5164 struct cleanup *
5165 save_inferior_ptid (void)
5166 {
5167   ptid_t *saved_ptid_ptr;
5168
5169   saved_ptid_ptr = xmalloc (sizeof (ptid_t));
5170   *saved_ptid_ptr = inferior_ptid;
5171   return make_cleanup (restore_inferior_ptid, saved_ptid_ptr);
5172 }
5173 \f
5174
5175 /* User interface for reverse debugging:
5176    Set exec-direction / show exec-direction commands
5177    (returns error unless target implements to_set_exec_direction method).  */
5178
5179 enum exec_direction_kind execution_direction = EXEC_FORWARD;
5180 static const char exec_forward[] = "forward";
5181 static const char exec_reverse[] = "reverse";
5182 static const char *exec_direction = exec_forward;
5183 static const char *exec_direction_names[] = {
5184   exec_forward,
5185   exec_reverse,
5186   NULL
5187 };
5188
5189 static void
5190 set_exec_direction_func (char *args, int from_tty,
5191                          struct cmd_list_element *cmd)
5192 {
5193   if (target_can_execute_reverse)
5194     {
5195       if (!strcmp (exec_direction, exec_forward))
5196         execution_direction = EXEC_FORWARD;
5197       else if (!strcmp (exec_direction, exec_reverse))
5198         execution_direction = EXEC_REVERSE;
5199     }
5200 }
5201
5202 static void
5203 show_exec_direction_func (struct ui_file *out, int from_tty,
5204                           struct cmd_list_element *cmd, const char *value)
5205 {
5206   switch (execution_direction) {
5207   case EXEC_FORWARD:
5208     fprintf_filtered (out, _("Forward.\n"));
5209     break;
5210   case EXEC_REVERSE:
5211     fprintf_filtered (out, _("Reverse.\n"));
5212     break;
5213   case EXEC_ERROR:
5214   default:
5215     fprintf_filtered (out, 
5216                       _("Forward (target `%s' does not support exec-direction).\n"),
5217                       target_shortname);
5218     break;
5219   }
5220 }
5221
5222 /* User interface for non-stop mode.  */
5223
5224 int non_stop = 0;
5225 static int non_stop_1 = 0;
5226
5227 static void
5228 set_non_stop (char *args, int from_tty,
5229               struct cmd_list_element *c)
5230 {
5231   if (target_has_execution)
5232     {
5233       non_stop_1 = non_stop;
5234       error (_("Cannot change this setting while the inferior is running."));
5235     }
5236
5237   non_stop = non_stop_1;
5238 }
5239
5240 static void
5241 show_non_stop (struct ui_file *file, int from_tty,
5242                struct cmd_list_element *c, const char *value)
5243 {
5244   fprintf_filtered (file,
5245                     _("Controlling the inferior in non-stop mode is %s.\n"),
5246                     value);
5247 }
5248
5249
5250 void
5251 _initialize_infrun (void)
5252 {
5253   int i;
5254   int numsigs;
5255   struct cmd_list_element *c;
5256
5257   add_info ("signals", signals_info, _("\
5258 What debugger does when program gets various signals.\n\
5259 Specify a signal as argument to print info on that signal only."));
5260   add_info_alias ("handle", "signals", 0);
5261
5262   add_com ("handle", class_run, handle_command, _("\
5263 Specify how to handle a signal.\n\
5264 Args are signals and actions to apply to those signals.\n\
5265 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
5266 from 1-15 are allowed for compatibility with old versions of GDB.\n\
5267 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
5268 The special arg \"all\" is recognized to mean all signals except those\n\
5269 used by the debugger, typically SIGTRAP and SIGINT.\n\
5270 Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
5271 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
5272 Stop means reenter debugger if this signal happens (implies print).\n\
5273 Print means print a message if this signal happens.\n\
5274 Pass means let program see this signal; otherwise program doesn't know.\n\
5275 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
5276 Pass and Stop may be combined."));
5277   if (xdb_commands)
5278     {
5279       add_com ("lz", class_info, signals_info, _("\
5280 What debugger does when program gets various signals.\n\
5281 Specify a signal as argument to print info on that signal only."));
5282       add_com ("z", class_run, xdb_handle_command, _("\
5283 Specify how to handle a signal.\n\
5284 Args are signals and actions to apply to those signals.\n\
5285 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
5286 from 1-15 are allowed for compatibility with old versions of GDB.\n\
5287 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
5288 The special arg \"all\" is recognized to mean all signals except those\n\
5289 used by the debugger, typically SIGTRAP and SIGINT.\n\
5290 Recognized actions include \"s\" (toggles between stop and nostop), \n\
5291 \"r\" (toggles between print and noprint), \"i\" (toggles between pass and \
5292 nopass), \"Q\" (noprint)\n\
5293 Stop means reenter debugger if this signal happens (implies print).\n\
5294 Print means print a message if this signal happens.\n\
5295 Pass means let program see this signal; otherwise program doesn't know.\n\
5296 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
5297 Pass and Stop may be combined."));
5298     }
5299
5300   if (!dbx_commands)
5301     stop_command = add_cmd ("stop", class_obscure,
5302                             not_just_help_class_command, _("\
5303 There is no `stop' command, but you can set a hook on `stop'.\n\
5304 This allows you to set a list of commands to be run each time execution\n\
5305 of the program stops."), &cmdlist);
5306
5307   add_setshow_zinteger_cmd ("infrun", class_maintenance, &debug_infrun, _("\
5308 Set inferior debugging."), _("\
5309 Show inferior debugging."), _("\
5310 When non-zero, inferior specific debugging is enabled."),
5311                             NULL,
5312                             show_debug_infrun,
5313                             &setdebuglist, &showdebuglist);
5314
5315   add_setshow_boolean_cmd ("displaced", class_maintenance, &debug_displaced, _("\
5316 Set displaced stepping debugging."), _("\
5317 Show displaced stepping debugging."), _("\
5318 When non-zero, displaced stepping specific debugging is enabled."),
5319                             NULL,
5320                             show_debug_displaced,
5321                             &setdebuglist, &showdebuglist);
5322
5323   add_setshow_boolean_cmd ("non-stop", no_class,
5324                            &non_stop_1, _("\
5325 Set whether gdb controls the inferior in non-stop mode."), _("\
5326 Show whether gdb controls the inferior in non-stop mode."), _("\
5327 When debugging a multi-threaded program and this setting is\n\
5328 off (the default, also called all-stop mode), when one thread stops\n\
5329 (for a breakpoint, watchpoint, exception, or similar events), GDB stops\n\
5330 all other threads in the program while you interact with the thread of\n\
5331 interest.  When you continue or step a thread, you can allow the other\n\
5332 threads to run, or have them remain stopped, but while you inspect any\n\
5333 thread's state, all threads stop.\n\
5334 \n\
5335 In non-stop mode, when one thread stops, other threads can continue\n\
5336 to run freely.  You'll be able to step each thread independently,\n\
5337 leave it stopped or free to run as needed."),
5338                            set_non_stop,
5339                            show_non_stop,
5340                            &setlist,
5341                            &showlist);
5342
5343   numsigs = (int) TARGET_SIGNAL_LAST;
5344   signal_stop = (unsigned char *) xmalloc (sizeof (signal_stop[0]) * numsigs);
5345   signal_print = (unsigned char *)
5346     xmalloc (sizeof (signal_print[0]) * numsigs);
5347   signal_program = (unsigned char *)
5348     xmalloc (sizeof (signal_program[0]) * numsigs);
5349   for (i = 0; i < numsigs; i++)
5350     {
5351       signal_stop[i] = 1;
5352       signal_print[i] = 1;
5353       signal_program[i] = 1;
5354     }
5355
5356   /* Signals caused by debugger's own actions
5357      should not be given to the program afterwards.  */
5358   signal_program[TARGET_SIGNAL_TRAP] = 0;
5359   signal_program[TARGET_SIGNAL_INT] = 0;
5360
5361   /* Signals that are not errors should not normally enter the debugger.  */
5362   signal_stop[TARGET_SIGNAL_ALRM] = 0;
5363   signal_print[TARGET_SIGNAL_ALRM] = 0;
5364   signal_stop[TARGET_SIGNAL_VTALRM] = 0;
5365   signal_print[TARGET_SIGNAL_VTALRM] = 0;
5366   signal_stop[TARGET_SIGNAL_PROF] = 0;
5367   signal_print[TARGET_SIGNAL_PROF] = 0;
5368   signal_stop[TARGET_SIGNAL_CHLD] = 0;
5369   signal_print[TARGET_SIGNAL_CHLD] = 0;
5370   signal_stop[TARGET_SIGNAL_IO] = 0;
5371   signal_print[TARGET_SIGNAL_IO] = 0;
5372   signal_stop[TARGET_SIGNAL_POLL] = 0;
5373   signal_print[TARGET_SIGNAL_POLL] = 0;
5374   signal_stop[TARGET_SIGNAL_URG] = 0;
5375   signal_print[TARGET_SIGNAL_URG] = 0;
5376   signal_stop[TARGET_SIGNAL_WINCH] = 0;
5377   signal_print[TARGET_SIGNAL_WINCH] = 0;
5378
5379   /* These signals are used internally by user-level thread
5380      implementations.  (See signal(5) on Solaris.)  Like the above
5381      signals, a healthy program receives and handles them as part of
5382      its normal operation.  */
5383   signal_stop[TARGET_SIGNAL_LWP] = 0;
5384   signal_print[TARGET_SIGNAL_LWP] = 0;
5385   signal_stop[TARGET_SIGNAL_WAITING] = 0;
5386   signal_print[TARGET_SIGNAL_WAITING] = 0;
5387   signal_stop[TARGET_SIGNAL_CANCEL] = 0;
5388   signal_print[TARGET_SIGNAL_CANCEL] = 0;
5389
5390   add_setshow_zinteger_cmd ("stop-on-solib-events", class_support,
5391                             &stop_on_solib_events, _("\
5392 Set stopping for shared library events."), _("\
5393 Show stopping for shared library events."), _("\
5394 If nonzero, gdb will give control to the user when the dynamic linker\n\
5395 notifies gdb of shared library events.  The most common event of interest\n\
5396 to the user would be loading/unloading of a new library."),
5397                             NULL,
5398                             show_stop_on_solib_events,
5399                             &setlist, &showlist);
5400
5401   add_setshow_enum_cmd ("follow-fork-mode", class_run,
5402                         follow_fork_mode_kind_names,
5403                         &follow_fork_mode_string, _("\
5404 Set debugger response to a program call of fork or vfork."), _("\
5405 Show debugger response to a program call of fork or vfork."), _("\
5406 A fork or vfork creates a new process.  follow-fork-mode can be:\n\
5407   parent  - the original process is debugged after a fork\n\
5408   child   - the new process is debugged after a fork\n\
5409 The unfollowed process will continue to run.\n\
5410 By default, the debugger will follow the parent process."),
5411                         NULL,
5412                         show_follow_fork_mode_string,
5413                         &setlist, &showlist);
5414
5415   add_setshow_enum_cmd ("scheduler-locking", class_run, 
5416                         scheduler_enums, &scheduler_mode, _("\
5417 Set mode for locking scheduler during execution."), _("\
5418 Show mode for locking scheduler during execution."), _("\
5419 off  == no locking (threads may preempt at any time)\n\
5420 on   == full locking (no thread except the current thread may run)\n\
5421 step == scheduler locked during every single-step operation.\n\
5422         In this mode, no other thread may run during a step command.\n\
5423         Other threads may run while stepping over a function call ('next')."), 
5424                         set_schedlock_func,     /* traps on target vector */
5425                         show_scheduler_mode,
5426                         &setlist, &showlist);
5427
5428   add_setshow_boolean_cmd ("step-mode", class_run, &step_stop_if_no_debug, _("\
5429 Set mode of the step operation."), _("\
5430 Show mode of the step operation."), _("\
5431 When set, doing a step over a function without debug line information\n\
5432 will stop at the first instruction of that function. Otherwise, the\n\
5433 function is skipped and the step command stops at a different source line."),
5434                            NULL,
5435                            show_step_stop_if_no_debug,
5436                            &setlist, &showlist);
5437
5438   add_setshow_enum_cmd ("displaced-stepping", class_run,
5439                         can_use_displaced_stepping_enum,
5440                         &can_use_displaced_stepping, _("\
5441 Set debugger's willingness to use displaced stepping."), _("\
5442 Show debugger's willingness to use displaced stepping."), _("\
5443 If on, gdb will use displaced stepping to step over breakpoints if it is\n\
5444 supported by the target architecture.  If off, gdb will not use displaced\n\
5445 stepping to step over breakpoints, even if such is supported by the target\n\
5446 architecture.  If auto (which is the default), gdb will use displaced stepping\n\
5447 if the target architecture supports it and non-stop mode is active, but will not\n\
5448 use it in all-stop mode (see help set non-stop)."),
5449                         NULL,
5450                         show_can_use_displaced_stepping,
5451                         &setlist, &showlist);
5452
5453   add_setshow_enum_cmd ("exec-direction", class_run, exec_direction_names,
5454                         &exec_direction, _("Set direction of execution.\n\
5455 Options are 'forward' or 'reverse'."),
5456                         _("Show direction of execution (forward/reverse)."),
5457                         _("Tells gdb whether to execute forward or backward."),
5458                         set_exec_direction_func, show_exec_direction_func,
5459                         &setlist, &showlist);
5460
5461   /* ptid initializations */
5462   null_ptid = ptid_build (0, 0, 0);
5463   minus_one_ptid = ptid_build (-1, 0, 0);
5464   inferior_ptid = null_ptid;
5465   target_last_wait_ptid = minus_one_ptid;
5466   displaced_step_ptid = null_ptid;
5467
5468   observer_attach_thread_ptid_changed (infrun_thread_ptid_changed);
5469   observer_attach_thread_stop_requested (infrun_thread_stop_requested);
5470 }