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