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