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