]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/gdb/gdb/infrun.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / gdb / gdb / infrun.c
1 /* Target-struct-independent code to start (run) and stop an inferior
2    process.
3
4    Copyright 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994,
5    1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 Free
6    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 2 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, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330,
23    Boston, MA 02111-1307, USA.  */
24
25 #include "defs.h"
26 #include "gdb_string.h"
27 #include <ctype.h>
28 #include "symtab.h"
29 #include "frame.h"
30 #include "inferior.h"
31 #include "breakpoint.h"
32 #include "gdb_wait.h"
33 #include "gdbcore.h"
34 #include "gdbcmd.h"
35 #include "cli/cli-script.h"
36 #include "target.h"
37 #include "gdbthread.h"
38 #include "annotate.h"
39 #include "symfile.h"
40 #include "top.h"
41 #include <signal.h>
42 #include "inf-loop.h"
43 #include "regcache.h"
44 #include "value.h"
45 #include "observer.h"
46 #include "language.h"
47 #include "gdb_assert.h"
48
49 /* Prototypes for local functions */
50
51 static void signals_info (char *, int);
52
53 static void handle_command (char *, int);
54
55 static void sig_print_info (enum target_signal);
56
57 static void sig_print_header (void);
58
59 static void resume_cleanups (void *);
60
61 static int hook_stop_stub (void *);
62
63 static void delete_breakpoint_current_contents (void *);
64
65 static int restore_selected_frame (void *);
66
67 static void build_infrun (void);
68
69 static int follow_fork (void);
70
71 static void set_schedlock_func (char *args, int from_tty,
72                                 struct cmd_list_element *c);
73
74 struct execution_control_state;
75
76 static int currently_stepping (struct execution_control_state *ecs);
77
78 static void xdb_handle_command (char *args, int from_tty);
79
80 static int prepare_to_proceed (void);
81
82 void _initialize_infrun (void);
83
84 int inferior_ignoring_startup_exec_events = 0;
85 int inferior_ignoring_leading_exec_events = 0;
86
87 /* When set, stop the 'step' command if we enter a function which has
88    no line number information.  The normal behavior is that we step
89    over such function.  */
90 int step_stop_if_no_debug = 0;
91
92 /* In asynchronous mode, but simulating synchronous execution. */
93
94 int sync_execution = 0;
95
96 /* wait_for_inferior and normal_stop use this to notify the user
97    when the inferior stopped in a different thread than it had been
98    running in.  */
99
100 static ptid_t previous_inferior_ptid;
101
102 /* This is true for configurations that may follow through execl() and
103    similar functions.  At present this is only true for HP-UX native.  */
104
105 #ifndef MAY_FOLLOW_EXEC
106 #define MAY_FOLLOW_EXEC (0)
107 #endif
108
109 static int may_follow_exec = MAY_FOLLOW_EXEC;
110
111 /* If the program uses ELF-style shared libraries, then calls to
112    functions in shared libraries go through stubs, which live in a
113    table called the PLT (Procedure Linkage Table).  The first time the
114    function is called, the stub sends control to the dynamic linker,
115    which looks up the function's real address, patches the stub so
116    that future calls will go directly to the function, and then passes
117    control to the function.
118
119    If we are stepping at the source level, we don't want to see any of
120    this --- we just want to skip over the stub and the dynamic linker.
121    The simple approach is to single-step until control leaves the
122    dynamic linker.
123
124    However, on some systems (e.g., Red Hat's 5.2 distribution) the
125    dynamic linker calls functions in the shared C library, so you
126    can't tell from the PC alone whether the dynamic linker is still
127    running.  In this case, we use a step-resume breakpoint to get us
128    past the dynamic linker, as if we were using "next" to step over a
129    function call.
130
131    IN_SOLIB_DYNSYM_RESOLVE_CODE says whether we're in the dynamic
132    linker code or not.  Normally, this means we single-step.  However,
133    if SKIP_SOLIB_RESOLVER then returns non-zero, then its value is an
134    address where we can place a step-resume breakpoint to get past the
135    linker's symbol resolution function.
136
137    IN_SOLIB_DYNSYM_RESOLVE_CODE can generally be implemented in a
138    pretty portable way, by comparing the PC against the address ranges
139    of the dynamic linker's sections.
140
141    SKIP_SOLIB_RESOLVER is generally going to be system-specific, since
142    it depends on internal details of the dynamic linker.  It's usually
143    not too hard to figure out where to put a breakpoint, but it
144    certainly isn't portable.  SKIP_SOLIB_RESOLVER should do plenty of
145    sanity checking.  If it can't figure things out, returning zero and
146    getting the (possibly confusing) stepping behavior is better than
147    signalling an error, which will obscure the change in the
148    inferior's state.  */
149
150 #ifndef IN_SOLIB_DYNSYM_RESOLVE_CODE
151 #define IN_SOLIB_DYNSYM_RESOLVE_CODE(pc) 0
152 #endif
153
154 /* This function returns TRUE if pc is the address of an instruction
155    that lies within the dynamic linker (such as the event hook, or the
156    dld itself).
157
158    This function must be used only when a dynamic linker event has
159    been caught, and the inferior is being stepped out of the hook, or
160    undefined results are guaranteed.  */
161
162 #ifndef SOLIB_IN_DYNAMIC_LINKER
163 #define SOLIB_IN_DYNAMIC_LINKER(pid,pc) 0
164 #endif
165
166 /* On MIPS16, a function that returns a floating point value may call
167    a library helper function to copy the return value to a floating point
168    register.  The IGNORE_HELPER_CALL macro returns non-zero if we
169    should ignore (i.e. step over) this function call.  */
170 #ifndef IGNORE_HELPER_CALL
171 #define IGNORE_HELPER_CALL(pc)  0
172 #endif
173
174 /* On some systems, the PC may be left pointing at an instruction that  won't
175    actually be executed.  This is usually indicated by a bit in the PSW.  If
176    we find ourselves in such a state, then we step the target beyond the
177    nullified instruction before returning control to the user so as to avoid
178    confusion. */
179
180 #ifndef INSTRUCTION_NULLIFIED
181 #define INSTRUCTION_NULLIFIED 0
182 #endif
183
184 /* We can't step off a permanent breakpoint in the ordinary way, because we
185    can't remove it.  Instead, we have to advance the PC to the next
186    instruction.  This macro should expand to a pointer to a function that
187    does that, or zero if we have no such function.  If we don't have a
188    definition for it, we have to report an error.  */
189 #ifndef SKIP_PERMANENT_BREAKPOINT
190 #define SKIP_PERMANENT_BREAKPOINT (default_skip_permanent_breakpoint)
191 static void
192 default_skip_permanent_breakpoint (void)
193 {
194   error ("\
195 The program is stopped at a permanent breakpoint, but GDB does not know\n\
196 how to step past a permanent breakpoint on this architecture.  Try using\n\
197 a command like `return' or `jump' to continue execution.");
198 }
199 #endif
200
201
202 /* Convert the #defines into values.  This is temporary until wfi control
203    flow is completely sorted out.  */
204
205 #ifndef HAVE_STEPPABLE_WATCHPOINT
206 #define HAVE_STEPPABLE_WATCHPOINT 0
207 #else
208 #undef  HAVE_STEPPABLE_WATCHPOINT
209 #define HAVE_STEPPABLE_WATCHPOINT 1
210 #endif
211
212 #ifndef CANNOT_STEP_HW_WATCHPOINTS
213 #define CANNOT_STEP_HW_WATCHPOINTS 0
214 #else
215 #undef  CANNOT_STEP_HW_WATCHPOINTS
216 #define CANNOT_STEP_HW_WATCHPOINTS 1
217 #endif
218
219 /* Tables of how to react to signals; the user sets them.  */
220
221 static unsigned char *signal_stop;
222 static unsigned char *signal_print;
223 static unsigned char *signal_program;
224
225 #define SET_SIGS(nsigs,sigs,flags) \
226   do { \
227     int signum = (nsigs); \
228     while (signum-- > 0) \
229       if ((sigs)[signum]) \
230         (flags)[signum] = 1; \
231   } while (0)
232
233 #define UNSET_SIGS(nsigs,sigs,flags) \
234   do { \
235     int signum = (nsigs); \
236     while (signum-- > 0) \
237       if ((sigs)[signum]) \
238         (flags)[signum] = 0; \
239   } while (0)
240
241 /* Value to pass to target_resume() to cause all threads to resume */
242
243 #define RESUME_ALL (pid_to_ptid (-1))
244
245 /* Command list pointer for the "stop" placeholder.  */
246
247 static struct cmd_list_element *stop_command;
248
249 /* Nonzero if breakpoints are now inserted in the inferior.  */
250
251 static int breakpoints_inserted;
252
253 /* Function inferior was in as of last step command.  */
254
255 static struct symbol *step_start_function;
256
257 /* Nonzero if we are expecting a trace trap and should proceed from it.  */
258
259 static int trap_expected;
260
261 #ifdef SOLIB_ADD
262 /* Nonzero if we want to give control to the user when we're notified
263    of shared library events by the dynamic linker.  */
264 static int stop_on_solib_events;
265 #endif
266
267 #ifdef HP_OS_BUG
268 /* Nonzero if the next time we try to continue the inferior, it will
269    step one instruction and generate a spurious trace trap.
270    This is used to compensate for a bug in HP-UX.  */
271
272 static int trap_expected_after_continue;
273 #endif
274
275 /* Nonzero means expecting a trace trap
276    and should stop the inferior and return silently when it happens.  */
277
278 int stop_after_trap;
279
280 /* Nonzero means expecting a trap and caller will handle it themselves.
281    It is used after attach, due to attaching to a process;
282    when running in the shell before the child program has been exec'd;
283    and when running some kinds of remote stuff (FIXME?).  */
284
285 enum stop_kind stop_soon;
286
287 /* Nonzero if proceed is being used for a "finish" command or a similar
288    situation when stop_registers should be saved.  */
289
290 int proceed_to_finish;
291
292 /* Save register contents here when about to pop a stack dummy frame,
293    if-and-only-if proceed_to_finish is set.
294    Thus this contains the return value from the called function (assuming
295    values are returned in a register).  */
296
297 struct regcache *stop_registers;
298
299 /* Nonzero if program stopped due to error trying to insert breakpoints.  */
300
301 static int breakpoints_failed;
302
303 /* Nonzero after stop if current stack frame should be printed.  */
304
305 static int stop_print_frame;
306
307 static struct breakpoint *step_resume_breakpoint = NULL;
308 static struct breakpoint *through_sigtramp_breakpoint = NULL;
309
310 /* On some platforms (e.g., HP-UX), hardware watchpoints have bad
311    interactions with an inferior that is running a kernel function
312    (aka, a system call or "syscall").  wait_for_inferior therefore
313    may have a need to know when the inferior is in a syscall.  This
314    is a count of the number of inferior threads which are known to
315    currently be running in a syscall. */
316 static int number_of_threads_in_syscalls;
317
318 /* This is a cached copy of the pid/waitstatus of the last event
319    returned by target_wait()/target_wait_hook().  This information is
320    returned by get_last_target_status(). */
321 static ptid_t target_last_wait_ptid;
322 static struct target_waitstatus target_last_waitstatus;
323
324 /* This is used to remember when a fork, vfork or exec event
325    was caught by a catchpoint, and thus the event is to be
326    followed at the next resume of the inferior, and not
327    immediately. */
328 static struct
329 {
330   enum target_waitkind kind;
331   struct
332   {
333     int parent_pid;
334     int child_pid;
335   }
336   fork_event;
337   char *execd_pathname;
338 }
339 pending_follow;
340
341 static const char follow_fork_mode_child[] = "child";
342 static const char follow_fork_mode_parent[] = "parent";
343
344 static const char *follow_fork_mode_kind_names[] = {
345   follow_fork_mode_child,
346   follow_fork_mode_parent,
347   NULL
348 };
349
350 static const char *follow_fork_mode_string = follow_fork_mode_parent;
351 \f
352
353 static int
354 follow_fork (void)
355 {
356   int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
357
358   return target_follow_fork (follow_child);
359 }
360
361 void
362 follow_inferior_reset_breakpoints (void)
363 {
364   /* Was there a step_resume breakpoint?  (There was if the user
365      did a "next" at the fork() call.)  If so, explicitly reset its
366      thread number.
367
368      step_resumes are a form of bp that are made to be per-thread.
369      Since we created the step_resume bp when the parent process
370      was being debugged, and now are switching to the child process,
371      from the breakpoint package's viewpoint, that's a switch of
372      "threads".  We must update the bp's notion of which thread
373      it is for, or it'll be ignored when it triggers.  */
374
375   if (step_resume_breakpoint)
376     breakpoint_re_set_thread (step_resume_breakpoint);
377
378   /* Reinsert all breakpoints in the child.  The user may have set
379      breakpoints after catching the fork, in which case those
380      were never set in the child, but only in the parent.  This makes
381      sure the inserted breakpoints match the breakpoint list.  */
382
383   breakpoint_re_set ();
384   insert_breakpoints ();
385 }
386
387 /* EXECD_PATHNAME is assumed to be non-NULL. */
388
389 static void
390 follow_exec (int pid, char *execd_pathname)
391 {
392   int saved_pid = pid;
393   struct target_ops *tgt;
394
395   if (!may_follow_exec)
396     return;
397
398   /* This is an exec event that we actually wish to pay attention to.
399      Refresh our symbol table to the newly exec'd program, remove any
400      momentary bp's, etc.
401
402      If there are breakpoints, they aren't really inserted now,
403      since the exec() transformed our inferior into a fresh set
404      of instructions.
405
406      We want to preserve symbolic breakpoints on the list, since
407      we have hopes that they can be reset after the new a.out's
408      symbol table is read.
409
410      However, any "raw" breakpoints must be removed from the list
411      (e.g., the solib bp's), since their address is probably invalid
412      now.
413
414      And, we DON'T want to call delete_breakpoints() here, since
415      that may write the bp's "shadow contents" (the instruction
416      value that was overwritten witha TRAP instruction).  Since
417      we now have a new a.out, those shadow contents aren't valid. */
418   update_breakpoints_after_exec ();
419
420   /* If there was one, it's gone now.  We cannot truly step-to-next
421      statement through an exec(). */
422   step_resume_breakpoint = NULL;
423   step_range_start = 0;
424   step_range_end = 0;
425
426   /* If there was one, it's gone now. */
427   through_sigtramp_breakpoint = NULL;
428
429   /* What is this a.out's name? */
430   printf_unfiltered ("Executing new program: %s\n", execd_pathname);
431
432   /* We've followed the inferior through an exec.  Therefore, the
433      inferior has essentially been killed & reborn. */
434
435   /* First collect the run target in effect.  */
436   tgt = find_run_target ();
437   /* If we can't find one, things are in a very strange state...  */
438   if (tgt == NULL)
439     error ("Could find run target to save before following exec");
440
441   gdb_flush (gdb_stdout);
442   target_mourn_inferior ();
443   inferior_ptid = pid_to_ptid (saved_pid);
444   /* Because mourn_inferior resets inferior_ptid. */
445   push_target (tgt);
446
447   /* That a.out is now the one to use. */
448   exec_file_attach (execd_pathname, 0);
449
450   /* And also is where symbols can be found. */
451   symbol_file_add_main (execd_pathname, 0);
452
453   /* Reset the shared library package.  This ensures that we get
454      a shlib event when the child reaches "_start", at which point
455      the dld will have had a chance to initialize the child. */
456 #if defined(SOLIB_RESTART)
457   SOLIB_RESTART ();
458 #endif
459 #ifdef SOLIB_CREATE_INFERIOR_HOOK
460   SOLIB_CREATE_INFERIOR_HOOK (PIDGET (inferior_ptid));
461 #endif
462
463   /* Reinsert all breakpoints.  (Those which were symbolic have
464      been reset to the proper address in the new a.out, thanks
465      to symbol_file_command...) */
466   insert_breakpoints ();
467
468   /* The next resume of this inferior should bring it to the shlib
469      startup breakpoints.  (If the user had also set bp's on
470      "main" from the old (parent) process, then they'll auto-
471      matically get reset there in the new process.) */
472 }
473
474 /* Non-zero if we just simulating a single-step.  This is needed
475    because we cannot remove the breakpoints in the inferior process
476    until after the `wait' in `wait_for_inferior'.  */
477 static int singlestep_breakpoints_inserted_p = 0;
478
479 /* The thread we inserted single-step breakpoints for.  */
480 static ptid_t singlestep_ptid;
481
482 /* If another thread hit the singlestep breakpoint, we save the original
483    thread here so that we can resume single-stepping it later.  */
484 static ptid_t saved_singlestep_ptid;
485 static int stepping_past_singlestep_breakpoint;
486 \f
487
488 /* Things to clean up if we QUIT out of resume ().  */
489 static void
490 resume_cleanups (void *ignore)
491 {
492   normal_stop ();
493 }
494
495 static const char schedlock_off[] = "off";
496 static const char schedlock_on[] = "on";
497 static const char schedlock_step[] = "step";
498 static const char *scheduler_mode = schedlock_off;
499 static const char *scheduler_enums[] = {
500   schedlock_off,
501   schedlock_on,
502   schedlock_step,
503   NULL
504 };
505
506 static void
507 set_schedlock_func (char *args, int from_tty, struct cmd_list_element *c)
508 {
509   /* NOTE: cagney/2002-03-17: The add_show_from_set() function clones
510      the set command passed as a parameter.  The clone operation will
511      include (BUG?) any ``set'' command callback, if present.
512      Commands like ``info set'' call all the ``show'' command
513      callbacks.  Unfortunately, for ``show'' commands cloned from
514      ``set'', this includes callbacks belonging to ``set'' commands.
515      Making this worse, this only occures if add_show_from_set() is
516      called after add_cmd_sfunc() (BUG?).  */
517   if (cmd_type (c) == set_cmd)
518     if (!target_can_lock_scheduler)
519       {
520         scheduler_mode = schedlock_off;
521         error ("Target '%s' cannot support this command.", target_shortname);
522       }
523 }
524
525
526 /* Resume the inferior, but allow a QUIT.  This is useful if the user
527    wants to interrupt some lengthy single-stepping operation
528    (for child processes, the SIGINT goes to the inferior, and so
529    we get a SIGINT random_signal, but for remote debugging and perhaps
530    other targets, that's not true).
531
532    STEP nonzero if we should step (zero to continue instead).
533    SIG is the signal to give the inferior (zero for none).  */
534 void
535 resume (int step, enum target_signal sig)
536 {
537   int should_resume = 1;
538   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
539   QUIT;
540
541   /* FIXME: calling breakpoint_here_p (read_pc ()) three times! */
542
543
544   /* Some targets (e.g. Solaris x86) have a kernel bug when stepping
545      over an instruction that causes a page fault without triggering
546      a hardware watchpoint. The kernel properly notices that it shouldn't
547      stop, because the hardware watchpoint is not triggered, but it forgets
548      the step request and continues the program normally.
549      Work around the problem by removing hardware watchpoints if a step is
550      requested, GDB will check for a hardware watchpoint trigger after the
551      step anyway.  */
552   if (CANNOT_STEP_HW_WATCHPOINTS && step && breakpoints_inserted)
553     remove_hw_watchpoints ();
554
555
556   /* Normally, by the time we reach `resume', the breakpoints are either
557      removed or inserted, as appropriate.  The exception is if we're sitting
558      at a permanent breakpoint; we need to step over it, but permanent
559      breakpoints can't be removed.  So we have to test for it here.  */
560   if (breakpoint_here_p (read_pc ()) == permanent_breakpoint_here)
561     SKIP_PERMANENT_BREAKPOINT ();
562
563   if (SOFTWARE_SINGLE_STEP_P () && step)
564     {
565       /* Do it the hard way, w/temp breakpoints */
566       SOFTWARE_SINGLE_STEP (sig, 1 /*insert-breakpoints */ );
567       /* ...and don't ask hardware to do it.  */
568       step = 0;
569       /* and do not pull these breakpoints until after a `wait' in
570          `wait_for_inferior' */
571       singlestep_breakpoints_inserted_p = 1;
572       singlestep_ptid = inferior_ptid;
573     }
574
575   /* Handle any optimized stores to the inferior NOW...  */
576 #ifdef DO_DEFERRED_STORES
577   DO_DEFERRED_STORES;
578 #endif
579
580   /* If there were any forks/vforks/execs that were caught and are
581      now to be followed, then do so.  */
582   switch (pending_follow.kind)
583     {
584     case TARGET_WAITKIND_FORKED:
585     case TARGET_WAITKIND_VFORKED:
586       pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
587       if (follow_fork ())
588         should_resume = 0;
589       break;
590
591     case TARGET_WAITKIND_EXECD:
592       /* follow_exec is called as soon as the exec event is seen. */
593       pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
594       break;
595
596     default:
597       break;
598     }
599
600   /* Install inferior's terminal modes.  */
601   target_terminal_inferior ();
602
603   if (should_resume)
604     {
605       ptid_t resume_ptid;
606
607       resume_ptid = RESUME_ALL; /* Default */
608
609       if ((step || singlestep_breakpoints_inserted_p) &&
610           (stepping_past_singlestep_breakpoint
611            || (!breakpoints_inserted && breakpoint_here_p (read_pc ()))))
612         {
613           /* Stepping past a breakpoint without inserting breakpoints.
614              Make sure only the current thread gets to step, so that
615              other threads don't sneak past breakpoints while they are
616              not inserted. */
617
618           resume_ptid = inferior_ptid;
619         }
620
621       if ((scheduler_mode == schedlock_on) ||
622           (scheduler_mode == schedlock_step &&
623            (step || singlestep_breakpoints_inserted_p)))
624         {
625           /* User-settable 'scheduler' mode requires solo thread resume. */
626           resume_ptid = inferior_ptid;
627         }
628
629       if (CANNOT_STEP_BREAKPOINT)
630         {
631           /* Most targets can step a breakpoint instruction, thus
632              executing it normally.  But if this one cannot, just
633              continue and we will hit it anyway.  */
634           if (step && breakpoints_inserted && breakpoint_here_p (read_pc ()))
635             step = 0;
636         }
637       target_resume (resume_ptid, step, sig);
638     }
639
640   discard_cleanups (old_cleanups);
641 }
642 \f
643
644 /* Clear out all variables saying what to do when inferior is continued.
645    First do this, then set the ones you want, then call `proceed'.  */
646
647 void
648 clear_proceed_status (void)
649 {
650   trap_expected = 0;
651   step_range_start = 0;
652   step_range_end = 0;
653   step_frame_id = null_frame_id;
654   step_over_calls = STEP_OVER_UNDEBUGGABLE;
655   stop_after_trap = 0;
656   stop_soon = NO_STOP_QUIETLY;
657   proceed_to_finish = 0;
658   breakpoint_proceeded = 1;     /* We're about to proceed... */
659
660   /* Discard any remaining commands or status from previous stop.  */
661   bpstat_clear (&stop_bpstat);
662 }
663
664 /* This should be suitable for any targets that support threads. */
665
666 static int
667 prepare_to_proceed (void)
668 {
669   ptid_t wait_ptid;
670   struct target_waitstatus wait_status;
671
672   /* Get the last target status returned by target_wait().  */
673   get_last_target_status (&wait_ptid, &wait_status);
674
675   /* Make sure we were stopped either at a breakpoint, or because
676      of a Ctrl-C.  */
677   if (wait_status.kind != TARGET_WAITKIND_STOPPED
678       || (wait_status.value.sig != TARGET_SIGNAL_TRAP &&
679           wait_status.value.sig != TARGET_SIGNAL_INT))
680     {
681       return 0;
682     }
683
684   if (!ptid_equal (wait_ptid, minus_one_ptid)
685       && !ptid_equal (inferior_ptid, wait_ptid))
686     {
687       /* Switched over from WAIT_PID.  */
688       CORE_ADDR wait_pc = read_pc_pid (wait_ptid);
689
690       if (wait_pc != read_pc ())
691         {
692           /* Switch back to WAIT_PID thread.  */
693           inferior_ptid = wait_ptid;
694
695           /* FIXME: This stuff came from switch_to_thread() in
696              thread.c (which should probably be a public function).  */
697           flush_cached_frames ();
698           registers_changed ();
699           stop_pc = wait_pc;
700           select_frame (get_current_frame ());
701         }
702
703         /* We return 1 to indicate that there is a breakpoint here,
704            so we need to step over it before continuing to avoid
705            hitting it straight away. */
706         if (breakpoint_here_p (wait_pc))
707            return 1;
708     }
709
710   return 0;
711   
712 }
713
714 /* Record the pc of the program the last time it stopped.  This is
715    just used internally by wait_for_inferior, but need to be preserved
716    over calls to it and cleared when the inferior is started.  */
717 static CORE_ADDR prev_pc;
718
719 /* Basic routine for continuing the program in various fashions.
720
721    ADDR is the address to resume at, or -1 for resume where stopped.
722    SIGGNAL is the signal to give it, or 0 for none,
723    or -1 for act according to how it stopped.
724    STEP is nonzero if should trap after one instruction.
725    -1 means return after that and print nothing.
726    You should probably set various step_... variables
727    before calling here, if you are stepping.
728
729    You should call clear_proceed_status before calling proceed.  */
730
731 void
732 proceed (CORE_ADDR addr, enum target_signal siggnal, int step)
733 {
734   int oneproc = 0;
735
736   if (step > 0)
737     step_start_function = find_pc_function (read_pc ());
738   if (step < 0)
739     stop_after_trap = 1;
740
741   if (addr == (CORE_ADDR) -1)
742     {
743       /* If there is a breakpoint at the address we will resume at,
744          step one instruction before inserting breakpoints
745          so that we do not stop right away (and report a second
746          hit at this breakpoint).  */
747
748       if (read_pc () == stop_pc && breakpoint_here_p (read_pc ()))
749         oneproc = 1;
750
751 #ifndef STEP_SKIPS_DELAY
752 #define STEP_SKIPS_DELAY(pc) (0)
753 #define STEP_SKIPS_DELAY_P (0)
754 #endif
755       /* Check breakpoint_here_p first, because breakpoint_here_p is fast
756          (it just checks internal GDB data structures) and STEP_SKIPS_DELAY
757          is slow (it needs to read memory from the target).  */
758       if (STEP_SKIPS_DELAY_P
759           && breakpoint_here_p (read_pc () + 4)
760           && STEP_SKIPS_DELAY (read_pc ()))
761         oneproc = 1;
762     }
763   else
764     {
765       write_pc (addr);
766     }
767
768   /* In a multi-threaded task we may select another thread
769      and then continue or step.
770
771      But if the old thread was stopped at a breakpoint, it
772      will immediately cause another breakpoint stop without
773      any execution (i.e. it will report a breakpoint hit
774      incorrectly).  So we must step over it first.
775
776      prepare_to_proceed checks the current thread against the thread
777      that reported the most recent event.  If a step-over is required
778      it returns TRUE and sets the current thread to the old thread. */
779   if (prepare_to_proceed () && breakpoint_here_p (read_pc ()))
780     oneproc = 1;
781
782 #ifdef HP_OS_BUG
783   if (trap_expected_after_continue)
784     {
785       /* If (step == 0), a trap will be automatically generated after
786          the first instruction is executed.  Force step one
787          instruction to clear this condition.  This should not occur
788          if step is nonzero, but it is harmless in that case.  */
789       oneproc = 1;
790       trap_expected_after_continue = 0;
791     }
792 #endif /* HP_OS_BUG */
793
794   if (oneproc)
795     /* We will get a trace trap after one instruction.
796        Continue it automatically and insert breakpoints then.  */
797     trap_expected = 1;
798   else
799     {
800       insert_breakpoints ();
801       /* If we get here there was no call to error() in 
802          insert breakpoints -- so they were inserted.  */
803       breakpoints_inserted = 1;
804     }
805
806   if (siggnal != TARGET_SIGNAL_DEFAULT)
807     stop_signal = siggnal;
808   /* If this signal should not be seen by program,
809      give it zero.  Used for debugging signals.  */
810   else if (!signal_program[stop_signal])
811     stop_signal = TARGET_SIGNAL_0;
812
813   annotate_starting ();
814
815   /* Make sure that output from GDB appears before output from the
816      inferior.  */
817   gdb_flush (gdb_stdout);
818
819   /* Refresh prev_pc value just prior to resuming.  This used to be
820      done in stop_stepping, however, setting prev_pc there did not handle
821      scenarios such as inferior function calls or returning from
822      a function via the return command.  In those cases, the prev_pc
823      value was not set properly for subsequent commands.  The prev_pc value 
824      is used to initialize the starting line number in the ecs.  With an 
825      invalid value, the gdb next command ends up stopping at the position
826      represented by the next line table entry past our start position.
827      On platforms that generate one line table entry per line, this
828      is not a problem.  However, on the ia64, the compiler generates
829      extraneous line table entries that do not increase the line number.
830      When we issue the gdb next command on the ia64 after an inferior call
831      or a return command, we often end up a few instructions forward, still 
832      within the original line we started.
833
834      An attempt was made to have init_execution_control_state () refresh
835      the prev_pc value before calculating the line number.  This approach
836      did not work because on platforms that use ptrace, the pc register
837      cannot be read unless the inferior is stopped.  At that point, we
838      are not guaranteed the inferior is stopped and so the read_pc ()
839      call can fail.  Setting the prev_pc value here ensures the value is 
840      updated correctly when the inferior is stopped.  */  
841   prev_pc = read_pc ();
842
843   /* Resume inferior.  */
844   resume (oneproc || step || bpstat_should_step (), stop_signal);
845
846   /* Wait for it to stop (if not standalone)
847      and in any case decode why it stopped, and act accordingly.  */
848   /* Do this only if we are not using the event loop, or if the target
849      does not support asynchronous execution. */
850   if (!event_loop_p || !target_can_async_p ())
851     {
852       wait_for_inferior ();
853       normal_stop ();
854     }
855 }
856 \f
857
858 /* Start remote-debugging of a machine over a serial link.  */
859
860 void
861 start_remote (void)
862 {
863   init_thread_list ();
864   init_wait_for_inferior ();
865   stop_soon = STOP_QUIETLY;
866   trap_expected = 0;
867
868   /* Always go on waiting for the target, regardless of the mode. */
869   /* FIXME: cagney/1999-09-23: At present it isn't possible to
870      indicate to wait_for_inferior that a target should timeout if
871      nothing is returned (instead of just blocking).  Because of this,
872      targets expecting an immediate response need to, internally, set
873      things up so that the target_wait() is forced to eventually
874      timeout. */
875   /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
876      differentiate to its caller what the state of the target is after
877      the initial open has been performed.  Here we're assuming that
878      the target has stopped.  It should be possible to eventually have
879      target_open() return to the caller an indication that the target
880      is currently running and GDB state should be set to the same as
881      for an async run. */
882   wait_for_inferior ();
883   normal_stop ();
884 }
885
886 /* Initialize static vars when a new inferior begins.  */
887
888 void
889 init_wait_for_inferior (void)
890 {
891   /* These are meaningless until the first time through wait_for_inferior.  */
892   prev_pc = 0;
893
894 #ifdef HP_OS_BUG
895   trap_expected_after_continue = 0;
896 #endif
897   breakpoints_inserted = 0;
898   breakpoint_init_inferior (inf_starting);
899
900   /* Don't confuse first call to proceed(). */
901   stop_signal = TARGET_SIGNAL_0;
902
903   /* The first resume is not following a fork/vfork/exec. */
904   pending_follow.kind = TARGET_WAITKIND_SPURIOUS;       /* I.e., none. */
905
906   /* See wait_for_inferior's handling of SYSCALL_ENTRY/RETURN events. */
907   number_of_threads_in_syscalls = 0;
908
909   clear_proceed_status ();
910
911   stepping_past_singlestep_breakpoint = 0;
912 }
913
914 static void
915 delete_breakpoint_current_contents (void *arg)
916 {
917   struct breakpoint **breakpointp = (struct breakpoint **) arg;
918   if (*breakpointp != NULL)
919     {
920       delete_breakpoint (*breakpointp);
921       *breakpointp = NULL;
922     }
923 }
924 \f
925 /* This enum encodes possible reasons for doing a target_wait, so that
926    wfi can call target_wait in one place.  (Ultimately the call will be
927    moved out of the infinite loop entirely.) */
928
929 enum infwait_states
930 {
931   infwait_normal_state,
932   infwait_thread_hop_state,
933   infwait_nullified_state,
934   infwait_nonstep_watch_state
935 };
936
937 /* Why did the inferior stop? Used to print the appropriate messages
938    to the interface from within handle_inferior_event(). */
939 enum inferior_stop_reason
940 {
941   /* We don't know why. */
942   STOP_UNKNOWN,
943   /* Step, next, nexti, stepi finished. */
944   END_STEPPING_RANGE,
945   /* Found breakpoint. */
946   BREAKPOINT_HIT,
947   /* Inferior terminated by signal. */
948   SIGNAL_EXITED,
949   /* Inferior exited. */
950   EXITED,
951   /* Inferior received signal, and user asked to be notified. */
952   SIGNAL_RECEIVED
953 };
954
955 /* This structure contains what used to be local variables in
956    wait_for_inferior.  Probably many of them can return to being
957    locals in handle_inferior_event.  */
958
959 struct execution_control_state
960 {
961   struct target_waitstatus ws;
962   struct target_waitstatus *wp;
963   int another_trap;
964   int random_signal;
965   CORE_ADDR stop_func_start;
966   CORE_ADDR stop_func_end;
967   char *stop_func_name;
968   struct symtab_and_line sal;
969   int remove_breakpoints_on_following_step;
970   int current_line;
971   struct symtab *current_symtab;
972   int handling_longjmp;         /* FIXME */
973   ptid_t ptid;
974   ptid_t saved_inferior_ptid;
975   int update_step_sp;
976   int stepping_through_solib_after_catch;
977   bpstat stepping_through_solib_catchpoints;
978   int enable_hw_watchpoints_after_wait;
979   int stepping_through_sigtramp;
980   int new_thread_event;
981   struct target_waitstatus tmpstatus;
982   enum infwait_states infwait_state;
983   ptid_t waiton_ptid;
984   int wait_some_more;
985 };
986
987 void init_execution_control_state (struct execution_control_state *ecs);
988
989 static void handle_step_into_function (struct execution_control_state *ecs);
990 void handle_inferior_event (struct execution_control_state *ecs);
991
992 static void check_sigtramp2 (struct execution_control_state *ecs);
993 static void step_into_function (struct execution_control_state *ecs);
994 static void step_over_function (struct execution_control_state *ecs);
995 static void stop_stepping (struct execution_control_state *ecs);
996 static void prepare_to_wait (struct execution_control_state *ecs);
997 static void keep_going (struct execution_control_state *ecs);
998 static void print_stop_reason (enum inferior_stop_reason stop_reason,
999                                int stop_info);
1000
1001 /* Wait for control to return from inferior to debugger.
1002    If inferior gets a signal, we may decide to start it up again
1003    instead of returning.  That is why there is a loop in this function.
1004    When this function actually returns it means the inferior
1005    should be left stopped and GDB should read more commands.  */
1006
1007 void
1008 wait_for_inferior (void)
1009 {
1010   struct cleanup *old_cleanups;
1011   struct execution_control_state ecss;
1012   struct execution_control_state *ecs;
1013
1014   old_cleanups = make_cleanup (delete_step_resume_breakpoint,
1015                                &step_resume_breakpoint);
1016   make_cleanup (delete_breakpoint_current_contents,
1017                 &through_sigtramp_breakpoint);
1018
1019   /* wfi still stays in a loop, so it's OK just to take the address of
1020      a local to get the ecs pointer.  */
1021   ecs = &ecss;
1022
1023   /* Fill in with reasonable starting values.  */
1024   init_execution_control_state (ecs);
1025
1026   /* We'll update this if & when we switch to a new thread. */
1027   previous_inferior_ptid = inferior_ptid;
1028
1029   overlay_cache_invalid = 1;
1030
1031   /* We have to invalidate the registers BEFORE calling target_wait
1032      because they can be loaded from the target while in target_wait.
1033      This makes remote debugging a bit more efficient for those
1034      targets that provide critical registers as part of their normal
1035      status mechanism. */
1036
1037   registers_changed ();
1038
1039   while (1)
1040     {
1041       if (target_wait_hook)
1042         ecs->ptid = target_wait_hook (ecs->waiton_ptid, ecs->wp);
1043       else
1044         ecs->ptid = target_wait (ecs->waiton_ptid, ecs->wp);
1045
1046       /* Now figure out what to do with the result of the result.  */
1047       handle_inferior_event (ecs);
1048
1049       if (!ecs->wait_some_more)
1050         break;
1051     }
1052   do_cleanups (old_cleanups);
1053 }
1054
1055 /* Asynchronous version of wait_for_inferior. It is called by the
1056    event loop whenever a change of state is detected on the file
1057    descriptor corresponding to the target. It can be called more than
1058    once to complete a single execution command. In such cases we need
1059    to keep the state in a global variable ASYNC_ECSS. If it is the
1060    last time that this function is called for a single execution
1061    command, then report to the user that the inferior has stopped, and
1062    do the necessary cleanups. */
1063
1064 struct execution_control_state async_ecss;
1065 struct execution_control_state *async_ecs;
1066
1067 void
1068 fetch_inferior_event (void *client_data)
1069 {
1070   static struct cleanup *old_cleanups;
1071
1072   async_ecs = &async_ecss;
1073
1074   if (!async_ecs->wait_some_more)
1075     {
1076       old_cleanups = make_exec_cleanup (delete_step_resume_breakpoint,
1077                                         &step_resume_breakpoint);
1078       make_exec_cleanup (delete_breakpoint_current_contents,
1079                          &through_sigtramp_breakpoint);
1080
1081       /* Fill in with reasonable starting values.  */
1082       init_execution_control_state (async_ecs);
1083
1084       /* We'll update this if & when we switch to a new thread. */
1085       previous_inferior_ptid = inferior_ptid;
1086
1087       overlay_cache_invalid = 1;
1088
1089       /* We have to invalidate the registers BEFORE calling target_wait
1090          because they can be loaded from the target while in target_wait.
1091          This makes remote debugging a bit more efficient for those
1092          targets that provide critical registers as part of their normal
1093          status mechanism. */
1094
1095       registers_changed ();
1096     }
1097
1098   if (target_wait_hook)
1099     async_ecs->ptid =
1100       target_wait_hook (async_ecs->waiton_ptid, async_ecs->wp);
1101   else
1102     async_ecs->ptid = target_wait (async_ecs->waiton_ptid, async_ecs->wp);
1103
1104   /* Now figure out what to do with the result of the result.  */
1105   handle_inferior_event (async_ecs);
1106
1107   if (!async_ecs->wait_some_more)
1108     {
1109       /* Do only the cleanups that have been added by this
1110          function. Let the continuations for the commands do the rest,
1111          if there are any. */
1112       do_exec_cleanups (old_cleanups);
1113       normal_stop ();
1114       if (step_multi && stop_step)
1115         inferior_event_handler (INF_EXEC_CONTINUE, NULL);
1116       else
1117         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
1118     }
1119 }
1120
1121 /* Prepare an execution control state for looping through a
1122    wait_for_inferior-type loop.  */
1123
1124 void
1125 init_execution_control_state (struct execution_control_state *ecs)
1126 {
1127   /* ecs->another_trap? */
1128   ecs->random_signal = 0;
1129   ecs->remove_breakpoints_on_following_step = 0;
1130   ecs->handling_longjmp = 0;    /* FIXME */
1131   ecs->update_step_sp = 0;
1132   ecs->stepping_through_solib_after_catch = 0;
1133   ecs->stepping_through_solib_catchpoints = NULL;
1134   ecs->enable_hw_watchpoints_after_wait = 0;
1135   ecs->stepping_through_sigtramp = 0;
1136   ecs->sal = find_pc_line (prev_pc, 0);
1137   ecs->current_line = ecs->sal.line;
1138   ecs->current_symtab = ecs->sal.symtab;
1139   ecs->infwait_state = infwait_normal_state;
1140   ecs->waiton_ptid = pid_to_ptid (-1);
1141   ecs->wp = &(ecs->ws);
1142 }
1143
1144 /* Call this function before setting step_resume_breakpoint, as a
1145    sanity check.  There should never be more than one step-resume
1146    breakpoint per thread, so we should never be setting a new
1147    step_resume_breakpoint when one is already active.  */
1148 static void
1149 check_for_old_step_resume_breakpoint (void)
1150 {
1151   if (step_resume_breakpoint)
1152     warning
1153       ("GDB bug: infrun.c (wait_for_inferior): dropping old step_resume breakpoint");
1154 }
1155
1156 /* Return the cached copy of the last pid/waitstatus returned by
1157    target_wait()/target_wait_hook().  The data is actually cached by
1158    handle_inferior_event(), which gets called immediately after
1159    target_wait()/target_wait_hook().  */
1160
1161 void
1162 get_last_target_status (ptid_t *ptidp, struct target_waitstatus *status)
1163 {
1164   *ptidp = target_last_wait_ptid;
1165   *status = target_last_waitstatus;
1166 }
1167
1168 /* Switch thread contexts, maintaining "infrun state". */
1169
1170 static void
1171 context_switch (struct execution_control_state *ecs)
1172 {
1173   /* Caution: it may happen that the new thread (or the old one!)
1174      is not in the thread list.  In this case we must not attempt
1175      to "switch context", or we run the risk that our context may
1176      be lost.  This may happen as a result of the target module
1177      mishandling thread creation.  */
1178
1179   if (in_thread_list (inferior_ptid) && in_thread_list (ecs->ptid))
1180     {                           /* Perform infrun state context switch: */
1181       /* Save infrun state for the old thread.  */
1182       save_infrun_state (inferior_ptid, prev_pc,
1183                          trap_expected, step_resume_breakpoint,
1184                          through_sigtramp_breakpoint, step_range_start,
1185                          step_range_end, &step_frame_id,
1186                          ecs->handling_longjmp, ecs->another_trap,
1187                          ecs->stepping_through_solib_after_catch,
1188                          ecs->stepping_through_solib_catchpoints,
1189                          ecs->stepping_through_sigtramp,
1190                          ecs->current_line, ecs->current_symtab, step_sp);
1191
1192       /* Load infrun state for the new thread.  */
1193       load_infrun_state (ecs->ptid, &prev_pc,
1194                          &trap_expected, &step_resume_breakpoint,
1195                          &through_sigtramp_breakpoint, &step_range_start,
1196                          &step_range_end, &step_frame_id,
1197                          &ecs->handling_longjmp, &ecs->another_trap,
1198                          &ecs->stepping_through_solib_after_catch,
1199                          &ecs->stepping_through_solib_catchpoints,
1200                          &ecs->stepping_through_sigtramp,
1201                          &ecs->current_line, &ecs->current_symtab, &step_sp);
1202     }
1203   inferior_ptid = ecs->ptid;
1204 }
1205
1206 /* Wrapper for PC_IN_SIGTRAMP that takes care of the need to find the
1207    function's name.
1208
1209    In a classic example of "left hand VS right hand", "infrun.c" was
1210    trying to improve GDB's performance by caching the result of calls
1211    to calls to find_pc_partial_funtion, while at the same time
1212    find_pc_partial_function was also trying to ramp up performance by
1213    caching its most recent return value.  The below makes the the
1214    function find_pc_partial_function solely responsibile for
1215    performance issues (the local cache that relied on a global
1216    variable - arrrggg - deleted).
1217
1218    Using the testsuite and gcov, it was found that dropping the local
1219    "infrun.c" cache and instead relying on find_pc_partial_function
1220    increased the number of calls to 12000 (from 10000), but the number
1221    of times find_pc_partial_function's cache missed (this is what
1222    matters) was only increased by only 4 (to 3569).  (A quick back of
1223    envelope caculation suggests that the extra 2000 function calls
1224    @1000 extra instructions per call make the 1 MIP VAX testsuite run
1225    take two extra seconds, oops :-)
1226
1227    Long term, this function can be eliminated, replaced by the code:
1228    get_frame_type(current_frame()) == SIGTRAMP_FRAME (for new
1229    architectures this is very cheap).  */
1230
1231 static int
1232 pc_in_sigtramp (CORE_ADDR pc)
1233 {
1234   char *name;
1235   find_pc_partial_function (pc, &name, NULL, NULL);
1236   return PC_IN_SIGTRAMP (pc, name);
1237 }
1238
1239 /* Handle the inferior event in the cases when we just stepped
1240    into a function.  */
1241
1242 static void
1243 handle_step_into_function (struct execution_control_state *ecs)
1244 {
1245   CORE_ADDR real_stop_pc;
1246
1247   if ((step_over_calls == STEP_OVER_NONE)
1248       || ((step_range_end == 1)
1249           && in_prologue (prev_pc, ecs->stop_func_start)))
1250     {
1251       /* I presume that step_over_calls is only 0 when we're
1252          supposed to be stepping at the assembly language level
1253          ("stepi").  Just stop.  */
1254       /* Also, maybe we just did a "nexti" inside a prolog,
1255          so we thought it was a subroutine call but it was not.
1256          Stop as well.  FENN */
1257       stop_step = 1;
1258       print_stop_reason (END_STEPPING_RANGE, 0);
1259       stop_stepping (ecs);
1260       return;
1261     }
1262
1263   if (step_over_calls == STEP_OVER_ALL || IGNORE_HELPER_CALL (stop_pc))
1264     {
1265       /* We're doing a "next".  */
1266
1267       if (pc_in_sigtramp (stop_pc)
1268           && frame_id_inner (step_frame_id,
1269                              frame_id_build (read_sp (), 0)))
1270         /* We stepped out of a signal handler, and into its
1271            calling trampoline.  This is misdetected as a
1272            subroutine call, but stepping over the signal
1273            trampoline isn't such a bad idea.  In order to do that,
1274            we have to ignore the value in step_frame_id, since
1275            that doesn't represent the frame that'll reach when we
1276            return from the signal trampoline.  Otherwise we'll
1277            probably continue to the end of the program.  */
1278         step_frame_id = null_frame_id;
1279
1280       step_over_function (ecs);
1281       keep_going (ecs);
1282       return;
1283     }
1284
1285   /* If we are in a function call trampoline (a stub between
1286      the calling routine and the real function), locate the real
1287      function.  That's what tells us (a) whether we want to step
1288      into it at all, and (b) what prologue we want to run to
1289      the end of, if we do step into it.  */
1290   real_stop_pc = skip_language_trampoline (stop_pc);
1291   if (real_stop_pc == 0)
1292     real_stop_pc = SKIP_TRAMPOLINE_CODE (stop_pc);
1293   if (real_stop_pc != 0)
1294     ecs->stop_func_start = real_stop_pc;
1295
1296   /* If we have line number information for the function we
1297      are thinking of stepping into, step into it.
1298
1299      If there are several symtabs at that PC (e.g. with include
1300      files), just want to know whether *any* of them have line
1301      numbers.  find_pc_line handles this.  */
1302   {
1303     struct symtab_and_line tmp_sal;
1304
1305     tmp_sal = find_pc_line (ecs->stop_func_start, 0);
1306     if (tmp_sal.line != 0)
1307       {
1308         step_into_function (ecs);
1309         return;
1310       }
1311   }
1312
1313   /* If we have no line number and the step-stop-if-no-debug
1314      is set, we stop the step so that the user has a chance to
1315      switch in assembly mode.  */
1316   if (step_over_calls == STEP_OVER_UNDEBUGGABLE && step_stop_if_no_debug)
1317     {
1318       stop_step = 1;
1319       print_stop_reason (END_STEPPING_RANGE, 0);
1320       stop_stepping (ecs);
1321       return;
1322     }
1323
1324   step_over_function (ecs);
1325   keep_going (ecs);
1326   return;
1327 }
1328
1329 static void
1330 adjust_pc_after_break (struct execution_control_state *ecs)
1331 {
1332   CORE_ADDR stop_pc;
1333
1334   /* If this target does not decrement the PC after breakpoints, then
1335      we have nothing to do.  */
1336   if (DECR_PC_AFTER_BREAK == 0)
1337     return;
1338
1339   /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP.  If
1340      we aren't, just return.
1341
1342      We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
1343      affected by DECR_PC_AFTER_BREAK.  Other waitkinds which are implemented
1344      by software breakpoints should be handled through the normal breakpoint
1345      layer.
1346      
1347      NOTE drow/2004-01-31: On some targets, breakpoints may generate
1348      different signals (SIGILL or SIGEMT for instance), but it is less
1349      clear where the PC is pointing afterwards.  It may not match
1350      DECR_PC_AFTER_BREAK.  I don't know any specific target that generates
1351      these signals at breakpoints (the code has been in GDB since at least
1352      1992) so I can not guess how to handle them here.
1353      
1354      In earlier versions of GDB, a target with HAVE_NONSTEPPABLE_WATCHPOINTS
1355      would have the PC after hitting a watchpoint affected by
1356      DECR_PC_AFTER_BREAK.  I haven't found any target with both of these set
1357      in GDB history, and it seems unlikely to be correct, so
1358      HAVE_NONSTEPPABLE_WATCHPOINTS is not checked here.  */
1359
1360   if (ecs->ws.kind != TARGET_WAITKIND_STOPPED)
1361     return;
1362
1363   if (ecs->ws.value.sig != TARGET_SIGNAL_TRAP)
1364     return;
1365
1366   /* Find the location where (if we've hit a breakpoint) the breakpoint would
1367      be.  */
1368   stop_pc = read_pc_pid (ecs->ptid) - DECR_PC_AFTER_BREAK;
1369
1370   /* If we're software-single-stepping, then assume this is a breakpoint.
1371      NOTE drow/2004-01-17: This doesn't check that the PC matches, or that
1372      we're even in the right thread.  The software-single-step code needs
1373      some modernization.
1374
1375      If we're not software-single-stepping, then we first check that there
1376      is an enabled software breakpoint at this address.  If there is, and
1377      we weren't using hardware-single-step, then we've hit the breakpoint.
1378
1379      If we were using hardware-single-step, we check prev_pc; if we just
1380      stepped over an inserted software breakpoint, then we should decrement
1381      the PC and eventually report hitting the breakpoint.  The prev_pc check
1382      prevents us from decrementing the PC if we just stepped over a jump
1383      instruction and landed on the instruction after a breakpoint.
1384
1385      The last bit checks that we didn't hit a breakpoint in a signal handler
1386      without an intervening stop in sigtramp, which is detected by a new
1387      stack pointer value below any usual function calling stack adjustments.
1388
1389      NOTE drow/2004-01-17: I'm not sure that this is necessary.  The check
1390      predates checking for software single step at the same time.  Also,
1391      if we've moved into a signal handler we should have seen the
1392      signal.  */
1393
1394   if ((SOFTWARE_SINGLE_STEP_P () && singlestep_breakpoints_inserted_p)
1395       || (software_breakpoint_inserted_here_p (stop_pc)
1396           && !(currently_stepping (ecs)
1397                && prev_pc != stop_pc
1398 #if 1
1399                && !(step_range_end))))
1400 #else
1401                && !(step_range_end && INNER_THAN (read_sp (), (step_sp - 16))))))
1402 #endif
1403     write_pc_pid (stop_pc, ecs->ptid);
1404 }
1405
1406 /* Given an execution control state that has been freshly filled in
1407    by an event from the inferior, figure out what it means and take
1408    appropriate action.  */
1409
1410 void
1411 handle_inferior_event (struct execution_control_state *ecs)
1412 {
1413   /* NOTE: cagney/2003-03-28: If you're looking at this code and
1414      thinking that the variable stepped_after_stopped_by_watchpoint
1415      isn't used, then you're wrong!  The macro STOPPED_BY_WATCHPOINT,
1416      defined in the file "config/pa/nm-hppah.h", accesses the variable
1417      indirectly.  Mutter something rude about the HP merge.  */
1418   int stepped_after_stopped_by_watchpoint;
1419   int sw_single_step_trap_p = 0;
1420
1421   /* Cache the last pid/waitstatus. */
1422   target_last_wait_ptid = ecs->ptid;
1423   target_last_waitstatus = *ecs->wp;
1424
1425   adjust_pc_after_break (ecs);
1426
1427   switch (ecs->infwait_state)
1428     {
1429     case infwait_thread_hop_state:
1430       /* Cancel the waiton_ptid. */
1431       ecs->waiton_ptid = pid_to_ptid (-1);
1432       /* See comments where a TARGET_WAITKIND_SYSCALL_RETURN event
1433          is serviced in this loop, below. */
1434       if (ecs->enable_hw_watchpoints_after_wait)
1435         {
1436           TARGET_ENABLE_HW_WATCHPOINTS (PIDGET (inferior_ptid));
1437           ecs->enable_hw_watchpoints_after_wait = 0;
1438         }
1439       stepped_after_stopped_by_watchpoint = 0;
1440       break;
1441
1442     case infwait_normal_state:
1443       /* See comments where a TARGET_WAITKIND_SYSCALL_RETURN event
1444          is serviced in this loop, below. */
1445       if (ecs->enable_hw_watchpoints_after_wait)
1446         {
1447           TARGET_ENABLE_HW_WATCHPOINTS (PIDGET (inferior_ptid));
1448           ecs->enable_hw_watchpoints_after_wait = 0;
1449         }
1450       stepped_after_stopped_by_watchpoint = 0;
1451       break;
1452
1453     case infwait_nullified_state:
1454       stepped_after_stopped_by_watchpoint = 0;
1455       break;
1456
1457     case infwait_nonstep_watch_state:
1458       insert_breakpoints ();
1459
1460       /* FIXME-maybe: is this cleaner than setting a flag?  Does it
1461          handle things like signals arriving and other things happening
1462          in combination correctly?  */
1463       stepped_after_stopped_by_watchpoint = 1;
1464       break;
1465
1466     default:
1467       internal_error (__FILE__, __LINE__, "bad switch");
1468     }
1469   ecs->infwait_state = infwait_normal_state;
1470
1471   flush_cached_frames ();
1472
1473   /* If it's a new process, add it to the thread database */
1474
1475   ecs->new_thread_event = (!ptid_equal (ecs->ptid, inferior_ptid)
1476                            && !in_thread_list (ecs->ptid));
1477
1478   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
1479       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED && ecs->new_thread_event)
1480     {
1481       add_thread (ecs->ptid);
1482
1483       ui_out_text (uiout, "[New ");
1484       ui_out_text (uiout, target_pid_or_tid_to_str (ecs->ptid));
1485       ui_out_text (uiout, "]\n");
1486
1487 #if 0
1488       /* NOTE: This block is ONLY meant to be invoked in case of a
1489          "thread creation event"!  If it is invoked for any other
1490          sort of event (such as a new thread landing on a breakpoint),
1491          the event will be discarded, which is almost certainly
1492          a bad thing!
1493
1494          To avoid this, the low-level module (eg. target_wait)
1495          should call in_thread_list and add_thread, so that the
1496          new thread is known by the time we get here.  */
1497
1498       /* We may want to consider not doing a resume here in order
1499          to give the user a chance to play with the new thread.
1500          It might be good to make that a user-settable option.  */
1501
1502       /* At this point, all threads are stopped (happens
1503          automatically in either the OS or the native code).
1504          Therefore we need to continue all threads in order to
1505          make progress.  */
1506
1507       target_resume (RESUME_ALL, 0, TARGET_SIGNAL_0);
1508       prepare_to_wait (ecs);
1509       return;
1510 #endif
1511     }
1512
1513   switch (ecs->ws.kind)
1514     {
1515     case TARGET_WAITKIND_LOADED:
1516       /* Ignore gracefully during startup of the inferior, as it
1517          might be the shell which has just loaded some objects,
1518          otherwise add the symbols for the newly loaded objects.  */
1519 #ifdef SOLIB_ADD
1520       if (stop_soon == NO_STOP_QUIETLY)
1521         {
1522           /* Remove breakpoints, SOLIB_ADD might adjust
1523              breakpoint addresses via breakpoint_re_set.  */
1524           if (breakpoints_inserted)
1525             remove_breakpoints ();
1526
1527           /* Check for any newly added shared libraries if we're
1528              supposed to be adding them automatically.  Switch
1529              terminal for any messages produced by
1530              breakpoint_re_set.  */
1531           target_terminal_ours_for_output ();
1532           /* NOTE: cagney/2003-11-25: Make certain that the target
1533              stack's section table is kept up-to-date.  Architectures,
1534              (e.g., PPC64), use the section table to perform
1535              operations such as address => section name and hence
1536              require the table to contain all sections (including
1537              those found in shared libraries).  */
1538           /* NOTE: cagney/2003-11-25: Pass current_target and not
1539              exec_ops to SOLIB_ADD.  This is because current GDB is
1540              only tooled to propagate section_table changes out from
1541              the "current_target" (see target_resize_to_sections), and
1542              not up from the exec stratum.  This, of course, isn't
1543              right.  "infrun.c" should only interact with the
1544              exec/process stratum, instead relying on the target stack
1545              to propagate relevant changes (stop, section table
1546              changed, ...) up to other layers.  */
1547           SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
1548           target_terminal_inferior ();
1549
1550           /* Reinsert breakpoints and continue.  */
1551           if (breakpoints_inserted)
1552             insert_breakpoints ();
1553         }
1554 #endif
1555       resume (0, TARGET_SIGNAL_0);
1556       prepare_to_wait (ecs);
1557       return;
1558
1559     case TARGET_WAITKIND_SPURIOUS:
1560       resume (0, TARGET_SIGNAL_0);
1561       prepare_to_wait (ecs);
1562       return;
1563
1564     case TARGET_WAITKIND_EXITED:
1565       target_terminal_ours ();  /* Must do this before mourn anyway */
1566       print_stop_reason (EXITED, ecs->ws.value.integer);
1567
1568       /* Record the exit code in the convenience variable $_exitcode, so
1569          that the user can inspect this again later.  */
1570       set_internalvar (lookup_internalvar ("_exitcode"),
1571                        value_from_longest (builtin_type_int,
1572                                            (LONGEST) ecs->ws.value.integer));
1573       gdb_flush (gdb_stdout);
1574       target_mourn_inferior ();
1575       singlestep_breakpoints_inserted_p = 0;    /*SOFTWARE_SINGLE_STEP_P() */
1576       stop_print_frame = 0;
1577       stop_stepping (ecs);
1578       return;
1579
1580     case TARGET_WAITKIND_SIGNALLED:
1581       stop_print_frame = 0;
1582       stop_signal = ecs->ws.value.sig;
1583       target_terminal_ours ();  /* Must do this before mourn anyway */
1584
1585       /* Note: By definition of TARGET_WAITKIND_SIGNALLED, we shouldn't
1586          reach here unless the inferior is dead.  However, for years
1587          target_kill() was called here, which hints that fatal signals aren't
1588          really fatal on some systems.  If that's true, then some changes
1589          may be needed. */
1590       target_mourn_inferior ();
1591
1592       print_stop_reason (SIGNAL_EXITED, stop_signal);
1593       singlestep_breakpoints_inserted_p = 0;    /*SOFTWARE_SINGLE_STEP_P() */
1594       stop_stepping (ecs);
1595       return;
1596
1597       /* The following are the only cases in which we keep going;
1598          the above cases end in a continue or goto. */
1599     case TARGET_WAITKIND_FORKED:
1600     case TARGET_WAITKIND_VFORKED:
1601       stop_signal = TARGET_SIGNAL_TRAP;
1602       pending_follow.kind = ecs->ws.kind;
1603
1604       pending_follow.fork_event.parent_pid = PIDGET (ecs->ptid);
1605       pending_follow.fork_event.child_pid = ecs->ws.value.related_pid;
1606
1607       stop_pc = read_pc ();
1608
1609       stop_bpstat = bpstat_stop_status (stop_pc, ecs->ptid);
1610
1611       ecs->random_signal = !bpstat_explains_signal (stop_bpstat);
1612
1613       /* If no catchpoint triggered for this, then keep going.  */
1614       if (ecs->random_signal)
1615         {
1616           stop_signal = TARGET_SIGNAL_0;
1617           keep_going (ecs);
1618           return;
1619         }
1620       goto process_event_stop_test;
1621
1622     case TARGET_WAITKIND_EXECD:
1623       stop_signal = TARGET_SIGNAL_TRAP;
1624
1625       /* NOTE drow/2002-12-05: This code should be pushed down into the
1626          target_wait function.  Until then following vfork on HP/UX 10.20
1627          is probably broken by this.  Of course, it's broken anyway.  */
1628       /* Is this a target which reports multiple exec events per actual
1629          call to exec()?  (HP-UX using ptrace does, for example.)  If so,
1630          ignore all but the last one.  Just resume the exec'r, and wait
1631          for the next exec event. */
1632       if (inferior_ignoring_leading_exec_events)
1633         {
1634           inferior_ignoring_leading_exec_events--;
1635           if (pending_follow.kind == TARGET_WAITKIND_VFORKED)
1636             ENSURE_VFORKING_PARENT_REMAINS_STOPPED (pending_follow.fork_event.
1637                                                     parent_pid);
1638           target_resume (ecs->ptid, 0, TARGET_SIGNAL_0);
1639           prepare_to_wait (ecs);
1640           return;
1641         }
1642       inferior_ignoring_leading_exec_events =
1643         target_reported_exec_events_per_exec_call () - 1;
1644
1645       pending_follow.execd_pathname =
1646         savestring (ecs->ws.value.execd_pathname,
1647                     strlen (ecs->ws.value.execd_pathname));
1648
1649       /* This causes the eventpoints and symbol table to be reset.  Must
1650          do this now, before trying to determine whether to stop. */
1651       follow_exec (PIDGET (inferior_ptid), pending_follow.execd_pathname);
1652       xfree (pending_follow.execd_pathname);
1653
1654       stop_pc = read_pc_pid (ecs->ptid);
1655       ecs->saved_inferior_ptid = inferior_ptid;
1656       inferior_ptid = ecs->ptid;
1657
1658       stop_bpstat = bpstat_stop_status (stop_pc, ecs->ptid);
1659
1660       ecs->random_signal = !bpstat_explains_signal (stop_bpstat);
1661       inferior_ptid = ecs->saved_inferior_ptid;
1662
1663       /* If no catchpoint triggered for this, then keep going.  */
1664       if (ecs->random_signal)
1665         {
1666           stop_signal = TARGET_SIGNAL_0;
1667           keep_going (ecs);
1668           return;
1669         }
1670       goto process_event_stop_test;
1671
1672       /* These syscall events are returned on HP-UX, as part of its
1673          implementation of page-protection-based "hardware" watchpoints.
1674          HP-UX has unfortunate interactions between page-protections and
1675          some system calls.  Our solution is to disable hardware watches
1676          when a system call is entered, and reenable them when the syscall
1677          completes.  The downside of this is that we may miss the precise
1678          point at which a watched piece of memory is modified.  "Oh well."
1679
1680          Note that we may have multiple threads running, which may each
1681          enter syscalls at roughly the same time.  Since we don't have a
1682          good notion currently of whether a watched piece of memory is
1683          thread-private, we'd best not have any page-protections active
1684          when any thread is in a syscall.  Thus, we only want to reenable
1685          hardware watches when no threads are in a syscall.
1686
1687          Also, be careful not to try to gather much state about a thread
1688          that's in a syscall.  It's frequently a losing proposition. */
1689     case TARGET_WAITKIND_SYSCALL_ENTRY:
1690       number_of_threads_in_syscalls++;
1691       if (number_of_threads_in_syscalls == 1)
1692         {
1693           TARGET_DISABLE_HW_WATCHPOINTS (PIDGET (inferior_ptid));
1694         }
1695       resume (0, TARGET_SIGNAL_0);
1696       prepare_to_wait (ecs);
1697       return;
1698
1699       /* Before examining the threads further, step this thread to
1700          get it entirely out of the syscall.  (We get notice of the
1701          event when the thread is just on the verge of exiting a
1702          syscall.  Stepping one instruction seems to get it back
1703          into user code.)
1704
1705          Note that although the logical place to reenable h/w watches
1706          is here, we cannot.  We cannot reenable them before stepping
1707          the thread (this causes the next wait on the thread to hang).
1708
1709          Nor can we enable them after stepping until we've done a wait.
1710          Thus, we simply set the flag ecs->enable_hw_watchpoints_after_wait
1711          here, which will be serviced immediately after the target
1712          is waited on. */
1713     case TARGET_WAITKIND_SYSCALL_RETURN:
1714       target_resume (ecs->ptid, 1, TARGET_SIGNAL_0);
1715
1716       if (number_of_threads_in_syscalls > 0)
1717         {
1718           number_of_threads_in_syscalls--;
1719           ecs->enable_hw_watchpoints_after_wait =
1720             (number_of_threads_in_syscalls == 0);
1721         }
1722       prepare_to_wait (ecs);
1723       return;
1724
1725     case TARGET_WAITKIND_STOPPED:
1726       stop_signal = ecs->ws.value.sig;
1727       break;
1728
1729       /* We had an event in the inferior, but we are not interested
1730          in handling it at this level. The lower layers have already
1731          done what needs to be done, if anything.
1732          
1733          One of the possible circumstances for this is when the
1734          inferior produces output for the console. The inferior has
1735          not stopped, and we are ignoring the event.  Another possible
1736          circumstance is any event which the lower level knows will be
1737          reported multiple times without an intervening resume.  */
1738     case TARGET_WAITKIND_IGNORE:
1739       prepare_to_wait (ecs);
1740       return;
1741     }
1742
1743   /* We may want to consider not doing a resume here in order to give
1744      the user a chance to play with the new thread.  It might be good
1745      to make that a user-settable option.  */
1746
1747   /* At this point, all threads are stopped (happens automatically in
1748      either the OS or the native code).  Therefore we need to continue
1749      all threads in order to make progress.  */
1750   if (ecs->new_thread_event)
1751     {
1752       target_resume (RESUME_ALL, 0, TARGET_SIGNAL_0);
1753       prepare_to_wait (ecs);
1754       return;
1755     }
1756
1757   stop_pc = read_pc_pid (ecs->ptid);
1758
1759   if (stepping_past_singlestep_breakpoint)
1760     {
1761       gdb_assert (SOFTWARE_SINGLE_STEP_P () && singlestep_breakpoints_inserted_p);
1762       gdb_assert (ptid_equal (singlestep_ptid, ecs->ptid));
1763       gdb_assert (!ptid_equal (singlestep_ptid, saved_singlestep_ptid));
1764
1765       stepping_past_singlestep_breakpoint = 0;
1766
1767       /* We've either finished single-stepping past the single-step
1768          breakpoint, or stopped for some other reason.  It would be nice if
1769          we could tell, but we can't reliably.  */
1770       if (stop_signal == TARGET_SIGNAL_TRAP)
1771         {
1772           /* Pull the single step breakpoints out of the target.  */
1773           SOFTWARE_SINGLE_STEP (0, 0);
1774           singlestep_breakpoints_inserted_p = 0;
1775
1776           ecs->random_signal = 0;
1777
1778           ecs->ptid = saved_singlestep_ptid;
1779           context_switch (ecs);
1780           if (context_hook)
1781             context_hook (pid_to_thread_id (ecs->ptid));
1782
1783           resume (1, TARGET_SIGNAL_0);
1784           prepare_to_wait (ecs);
1785           return;
1786         }
1787     }
1788
1789   stepping_past_singlestep_breakpoint = 0;
1790
1791   /* See if a thread hit a thread-specific breakpoint that was meant for
1792      another thread.  If so, then step that thread past the breakpoint,
1793      and continue it.  */
1794
1795   if (stop_signal == TARGET_SIGNAL_TRAP)
1796     {
1797       int thread_hop_needed = 0;
1798
1799       /* Check if a regular breakpoint has been hit before checking
1800          for a potential single step breakpoint. Otherwise, GDB will
1801          not see this breakpoint hit when stepping onto breakpoints.  */
1802       if (breakpoints_inserted && breakpoint_here_p (stop_pc))
1803         {
1804           ecs->random_signal = 0;
1805           if (!breakpoint_thread_match (stop_pc, ecs->ptid))
1806             thread_hop_needed = 1;
1807         }
1808       else if (SOFTWARE_SINGLE_STEP_P () && singlestep_breakpoints_inserted_p)
1809         {
1810           ecs->random_signal = 0;
1811           /* The call to in_thread_list is necessary because PTIDs sometimes
1812              change when we go from single-threaded to multi-threaded.  If
1813              the singlestep_ptid is still in the list, assume that it is
1814              really different from ecs->ptid.  */
1815           if (!ptid_equal (singlestep_ptid, ecs->ptid)
1816               && in_thread_list (singlestep_ptid))
1817             {
1818               thread_hop_needed = 1;
1819               stepping_past_singlestep_breakpoint = 1;
1820               saved_singlestep_ptid = singlestep_ptid;
1821             }
1822         }
1823
1824       if (thread_hop_needed)
1825             {
1826               int remove_status;
1827
1828               /* Saw a breakpoint, but it was hit by the wrong thread.
1829                  Just continue. */
1830
1831               if (SOFTWARE_SINGLE_STEP_P () && singlestep_breakpoints_inserted_p)
1832                 {
1833                   /* Pull the single step breakpoints out of the target. */
1834                   SOFTWARE_SINGLE_STEP (0, 0);
1835                   singlestep_breakpoints_inserted_p = 0;
1836                 }
1837
1838               remove_status = remove_breakpoints ();
1839               /* Did we fail to remove breakpoints?  If so, try
1840                  to set the PC past the bp.  (There's at least
1841                  one situation in which we can fail to remove
1842                  the bp's: On HP-UX's that use ttrace, we can't
1843                  change the address space of a vforking child
1844                  process until the child exits (well, okay, not
1845                  then either :-) or execs. */
1846               if (remove_status != 0)
1847                 {
1848                   /* FIXME!  This is obviously non-portable! */
1849                   write_pc_pid (stop_pc + 4, ecs->ptid);
1850                   /* We need to restart all the threads now,
1851                    * unles we're running in scheduler-locked mode. 
1852                    * Use currently_stepping to determine whether to 
1853                    * step or continue.
1854                    */
1855                   /* FIXME MVS: is there any reason not to call resume()? */
1856                   if (scheduler_mode == schedlock_on)
1857                     target_resume (ecs->ptid,
1858                                    currently_stepping (ecs), TARGET_SIGNAL_0);
1859                   else
1860                     target_resume (RESUME_ALL,
1861                                    currently_stepping (ecs), TARGET_SIGNAL_0);
1862                   prepare_to_wait (ecs);
1863                   return;
1864                 }
1865               else
1866                 {               /* Single step */
1867                   breakpoints_inserted = 0;
1868                   if (!ptid_equal (inferior_ptid, ecs->ptid))
1869                     context_switch (ecs);
1870                   ecs->waiton_ptid = ecs->ptid;
1871                   ecs->wp = &(ecs->ws);
1872                   ecs->another_trap = 1;
1873
1874                   ecs->infwait_state = infwait_thread_hop_state;
1875                   keep_going (ecs);
1876                   registers_changed ();
1877                   return;
1878                 }
1879         }
1880       else if (SOFTWARE_SINGLE_STEP_P () && singlestep_breakpoints_inserted_p)
1881         {
1882           sw_single_step_trap_p = 1;
1883           ecs->random_signal = 0;
1884         }
1885     }
1886   else
1887     ecs->random_signal = 1;
1888
1889   /* See if something interesting happened to the non-current thread.  If
1890      so, then switch to that thread, and eventually give control back to
1891      the user.
1892
1893      Note that if there's any kind of pending follow (i.e., of a fork,
1894      vfork or exec), we don't want to do this now.  Rather, we'll let
1895      the next resume handle it. */
1896   if (!ptid_equal (ecs->ptid, inferior_ptid) &&
1897       (pending_follow.kind == TARGET_WAITKIND_SPURIOUS))
1898     {
1899       int printed = 0;
1900
1901       /* If it's a random signal for a non-current thread, notify user
1902          if he's expressed an interest. */
1903       if (ecs->random_signal && signal_print[stop_signal])
1904         {
1905 /* ??rehrauer: I don't understand the rationale for this code.  If the
1906    inferior will stop as a result of this signal, then the act of handling
1907    the stop ought to print a message that's couches the stoppage in user
1908    terms, e.g., "Stopped for breakpoint/watchpoint".  If the inferior
1909    won't stop as a result of the signal -- i.e., if the signal is merely
1910    a side-effect of something GDB's doing "under the covers" for the
1911    user, such as stepping threads over a breakpoint they shouldn't stop
1912    for -- then the message seems to be a serious annoyance at best.
1913
1914    For now, remove the message altogether. */
1915 #if 0
1916           printed = 1;
1917           target_terminal_ours_for_output ();
1918           printf_filtered ("\nProgram received signal %s, %s.\n",
1919                            target_signal_to_name (stop_signal),
1920                            target_signal_to_string (stop_signal));
1921           gdb_flush (gdb_stdout);
1922 #endif
1923         }
1924
1925       /* If it's not SIGTRAP and not a signal we want to stop for, then
1926          continue the thread. */
1927
1928       if (stop_signal != TARGET_SIGNAL_TRAP && !signal_stop[stop_signal])
1929         {
1930           if (printed)
1931             target_terminal_inferior ();
1932
1933           /* Clear the signal if it should not be passed.  */
1934           if (signal_program[stop_signal] == 0)
1935             stop_signal = TARGET_SIGNAL_0;
1936
1937           target_resume (ecs->ptid, 0, stop_signal);
1938           prepare_to_wait (ecs);
1939           return;
1940         }
1941
1942       /* It's a SIGTRAP or a signal we're interested in.  Switch threads,
1943          and fall into the rest of wait_for_inferior().  */
1944
1945       context_switch (ecs);
1946
1947       if (context_hook)
1948         context_hook (pid_to_thread_id (ecs->ptid));
1949
1950       flush_cached_frames ();
1951     }
1952
1953   if (SOFTWARE_SINGLE_STEP_P () && singlestep_breakpoints_inserted_p)
1954     {
1955       /* Pull the single step breakpoints out of the target. */
1956       SOFTWARE_SINGLE_STEP (0, 0);
1957       singlestep_breakpoints_inserted_p = 0;
1958     }
1959
1960   /* If PC is pointing at a nullified instruction, then step beyond
1961      it so that the user won't be confused when GDB appears to be ready
1962      to execute it. */
1963
1964   /*      if (INSTRUCTION_NULLIFIED && currently_stepping (ecs)) */
1965   if (INSTRUCTION_NULLIFIED)
1966     {
1967       registers_changed ();
1968       target_resume (ecs->ptid, 1, TARGET_SIGNAL_0);
1969
1970       /* We may have received a signal that we want to pass to
1971          the inferior; therefore, we must not clobber the waitstatus
1972          in WS. */
1973
1974       ecs->infwait_state = infwait_nullified_state;
1975       ecs->waiton_ptid = ecs->ptid;
1976       ecs->wp = &(ecs->tmpstatus);
1977       prepare_to_wait (ecs);
1978       return;
1979     }
1980
1981   /* It may not be necessary to disable the watchpoint to stop over
1982      it.  For example, the PA can (with some kernel cooperation)
1983      single step over a watchpoint without disabling the watchpoint.  */
1984   if (HAVE_STEPPABLE_WATCHPOINT && STOPPED_BY_WATCHPOINT (ecs->ws))
1985     {
1986       resume (1, 0);
1987       prepare_to_wait (ecs);
1988       return;
1989     }
1990
1991   /* It is far more common to need to disable a watchpoint to step
1992      the inferior over it.  FIXME.  What else might a debug
1993      register or page protection watchpoint scheme need here?  */
1994   if (HAVE_NONSTEPPABLE_WATCHPOINT && STOPPED_BY_WATCHPOINT (ecs->ws))
1995     {
1996       /* At this point, we are stopped at an instruction which has
1997          attempted to write to a piece of memory under control of
1998          a watchpoint.  The instruction hasn't actually executed
1999          yet.  If we were to evaluate the watchpoint expression
2000          now, we would get the old value, and therefore no change
2001          would seem to have occurred.
2002
2003          In order to make watchpoints work `right', we really need
2004          to complete the memory write, and then evaluate the
2005          watchpoint expression.  The following code does that by
2006          removing the watchpoint (actually, all watchpoints and
2007          breakpoints), single-stepping the target, re-inserting
2008          watchpoints, and then falling through to let normal
2009          single-step processing handle proceed.  Since this
2010          includes evaluating watchpoints, things will come to a
2011          stop in the correct manner.  */
2012
2013       remove_breakpoints ();
2014       registers_changed ();
2015       target_resume (ecs->ptid, 1, TARGET_SIGNAL_0);    /* Single step */
2016
2017       ecs->waiton_ptid = ecs->ptid;
2018       ecs->wp = &(ecs->ws);
2019       ecs->infwait_state = infwait_nonstep_watch_state;
2020       prepare_to_wait (ecs);
2021       return;
2022     }
2023
2024   /* It may be possible to simply continue after a watchpoint.  */
2025   if (HAVE_CONTINUABLE_WATCHPOINT)
2026     STOPPED_BY_WATCHPOINT (ecs->ws);
2027
2028   ecs->stop_func_start = 0;
2029   ecs->stop_func_end = 0;
2030   ecs->stop_func_name = 0;
2031   /* Don't care about return value; stop_func_start and stop_func_name
2032      will both be 0 if it doesn't work.  */
2033   find_pc_partial_function (stop_pc, &ecs->stop_func_name,
2034                             &ecs->stop_func_start, &ecs->stop_func_end);
2035   ecs->stop_func_start += FUNCTION_START_OFFSET;
2036   ecs->another_trap = 0;
2037   bpstat_clear (&stop_bpstat);
2038   stop_step = 0;
2039   stop_stack_dummy = 0;
2040   stop_print_frame = 1;
2041   ecs->random_signal = 0;
2042   stopped_by_random_signal = 0;
2043   breakpoints_failed = 0;
2044
2045   /* Look at the cause of the stop, and decide what to do.
2046      The alternatives are:
2047      1) break; to really stop and return to the debugger,
2048      2) drop through to start up again
2049      (set ecs->another_trap to 1 to single step once)
2050      3) set ecs->random_signal to 1, and the decision between 1 and 2
2051      will be made according to the signal handling tables.  */
2052
2053   /* First, distinguish signals caused by the debugger from signals
2054      that have to do with the program's own actions.  Note that
2055      breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
2056      on the operating system version.  Here we detect when a SIGILL or
2057      SIGEMT is really a breakpoint and change it to SIGTRAP.  We do
2058      something similar for SIGSEGV, since a SIGSEGV will be generated
2059      when we're trying to execute a breakpoint instruction on a
2060      non-executable stack.  This happens for call dummy breakpoints
2061      for architectures like SPARC that place call dummies on the
2062      stack.  */
2063
2064   if (stop_signal == TARGET_SIGNAL_TRAP
2065       || (breakpoints_inserted &&
2066           (stop_signal == TARGET_SIGNAL_ILL
2067            || stop_signal == TARGET_SIGNAL_SEGV
2068            || stop_signal == TARGET_SIGNAL_EMT))
2069       || stop_soon == STOP_QUIETLY
2070       || stop_soon == STOP_QUIETLY_NO_SIGSTOP)
2071     {
2072       if (stop_signal == TARGET_SIGNAL_TRAP && stop_after_trap)
2073         {
2074           stop_print_frame = 0;
2075           stop_stepping (ecs);
2076           return;
2077         }
2078
2079       /* This is originated from start_remote(), start_inferior() and
2080          shared libraries hook functions.  */
2081       if (stop_soon == STOP_QUIETLY)
2082         {
2083           stop_stepping (ecs);
2084           return;
2085         }
2086
2087       /* This originates from attach_command().  We need to overwrite
2088          the stop_signal here, because some kernels don't ignore a
2089          SIGSTOP in a subsequent ptrace(PTRACE_SONT,SOGSTOP) call.
2090          See more comments in inferior.h.  */
2091       if (stop_soon == STOP_QUIETLY_NO_SIGSTOP)
2092         {
2093           stop_stepping (ecs);
2094           if (stop_signal == TARGET_SIGNAL_STOP)
2095             stop_signal = TARGET_SIGNAL_0;
2096           return;
2097         }
2098
2099       /* Don't even think about breakpoints
2100          if just proceeded over a breakpoint.
2101
2102          However, if we are trying to proceed over a breakpoint
2103          and end up in sigtramp, then through_sigtramp_breakpoint
2104          will be set and we should check whether we've hit the
2105          step breakpoint.  */
2106       if (stop_signal == TARGET_SIGNAL_TRAP && trap_expected
2107           && through_sigtramp_breakpoint == NULL)
2108         bpstat_clear (&stop_bpstat);
2109       else
2110         {
2111           /* See if there is a breakpoint at the current PC.  */
2112           stop_bpstat = bpstat_stop_status (stop_pc, ecs->ptid);
2113
2114           /* Following in case break condition called a
2115              function.  */
2116           stop_print_frame = 1;
2117         }
2118
2119       /* NOTE: cagney/2003-03-29: These two checks for a random signal
2120          at one stage in the past included checks for an inferior
2121          function call's call dummy's return breakpoint.  The original
2122          comment, that went with the test, read:
2123
2124          ``End of a stack dummy.  Some systems (e.g. Sony news) give
2125          another signal besides SIGTRAP, so check here as well as
2126          above.''
2127
2128          If someone ever tries to get get call dummys on a
2129          non-executable stack to work (where the target would stop
2130          with something like a SIGSEGV), then those tests might need
2131          to be re-instated.  Given, however, that the tests were only
2132          enabled when momentary breakpoints were not being used, I
2133          suspect that it won't be the case.
2134
2135          NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
2136          be necessary for call dummies on a non-executable stack on
2137          SPARC.  */
2138
2139       if (stop_signal == TARGET_SIGNAL_TRAP)
2140         ecs->random_signal
2141           = !(bpstat_explains_signal (stop_bpstat)
2142               || trap_expected
2143               || (step_range_end && step_resume_breakpoint == NULL));
2144       else
2145         {
2146           ecs->random_signal = !bpstat_explains_signal (stop_bpstat);
2147           if (!ecs->random_signal)
2148             stop_signal = TARGET_SIGNAL_TRAP;
2149         }
2150     }
2151
2152   /* When we reach this point, we've pretty much decided
2153      that the reason for stopping must've been a random
2154      (unexpected) signal. */
2155
2156   else
2157     ecs->random_signal = 1;
2158
2159 process_event_stop_test:
2160   /* For the program's own signals, act according to
2161      the signal handling tables.  */
2162
2163   if (ecs->random_signal)
2164     {
2165       /* Signal not for debugging purposes.  */
2166       int printed = 0;
2167
2168       stopped_by_random_signal = 1;
2169
2170       if (signal_print[stop_signal])
2171         {
2172           printed = 1;
2173           target_terminal_ours_for_output ();
2174           print_stop_reason (SIGNAL_RECEIVED, stop_signal);
2175         }
2176       if (signal_stop[stop_signal])
2177         {
2178           stop_stepping (ecs);
2179           return;
2180         }
2181       /* If not going to stop, give terminal back
2182          if we took it away.  */
2183       else if (printed)
2184         target_terminal_inferior ();
2185
2186       /* Clear the signal if it should not be passed.  */
2187       if (signal_program[stop_signal] == 0)
2188         stop_signal = TARGET_SIGNAL_0;
2189
2190       /* I'm not sure whether this needs to be check_sigtramp2 or
2191          whether it could/should be keep_going.
2192
2193          This used to jump to step_over_function if we are stepping,
2194          which is wrong.
2195
2196          Suppose the user does a `next' over a function call, and while
2197          that call is in progress, the inferior receives a signal for
2198          which GDB does not stop (i.e., signal_stop[SIG] is false).  In
2199          that case, when we reach this point, there is already a
2200          step-resume breakpoint established, right where it should be:
2201          immediately after the function call the user is "next"-ing
2202          over.  If we call step_over_function now, two bad things
2203          happen:
2204
2205          - we'll create a new breakpoint, at wherever the current
2206          frame's return address happens to be.  That could be
2207          anywhere, depending on what function call happens to be on
2208          the top of the stack at that point.  Point is, it's probably
2209          not where we need it.
2210
2211          - the existing step-resume breakpoint (which is at the correct
2212          address) will get orphaned: step_resume_breakpoint will point
2213          to the new breakpoint, and the old step-resume breakpoint
2214          will never be cleaned up.
2215
2216          The old behavior was meant to help HP-UX single-step out of
2217          sigtramps.  It would place the new breakpoint at prev_pc, which
2218          was certainly wrong.  I don't know the details there, so fixing
2219          this probably breaks that.  As with anything else, it's up to
2220          the HP-UX maintainer to furnish a fix that doesn't break other
2221          platforms.  --JimB, 20 May 1999 */
2222       check_sigtramp2 (ecs);
2223       keep_going (ecs);
2224       return;
2225     }
2226
2227   /* Handle cases caused by hitting a breakpoint.  */
2228   {
2229     CORE_ADDR jmp_buf_pc;
2230     struct bpstat_what what;
2231
2232     what = bpstat_what (stop_bpstat);
2233
2234     if (what.call_dummy)
2235       {
2236         stop_stack_dummy = 1;
2237 #ifdef HP_OS_BUG
2238         trap_expected_after_continue = 1;
2239 #endif
2240       }
2241
2242     switch (what.main_action)
2243       {
2244       case BPSTAT_WHAT_SET_LONGJMP_RESUME:
2245         /* If we hit the breakpoint at longjmp, disable it for the
2246            duration of this command.  Then, install a temporary
2247            breakpoint at the target of the jmp_buf. */
2248         disable_longjmp_breakpoint ();
2249         remove_breakpoints ();
2250         breakpoints_inserted = 0;
2251         if (!GET_LONGJMP_TARGET_P () || !GET_LONGJMP_TARGET (&jmp_buf_pc))
2252           {
2253             keep_going (ecs);
2254             return;
2255           }
2256
2257         /* Need to blow away step-resume breakpoint, as it
2258            interferes with us */
2259         if (step_resume_breakpoint != NULL)
2260           {
2261             delete_step_resume_breakpoint (&step_resume_breakpoint);
2262           }
2263         /* Not sure whether we need to blow this away too, but probably
2264            it is like the step-resume breakpoint.  */
2265         if (through_sigtramp_breakpoint != NULL)
2266           {
2267             delete_breakpoint (through_sigtramp_breakpoint);
2268             through_sigtramp_breakpoint = NULL;
2269           }
2270
2271 #if 0
2272         /* FIXME - Need to implement nested temporary breakpoints */
2273         if (step_over_calls > 0)
2274           set_longjmp_resume_breakpoint (jmp_buf_pc, get_current_frame ());
2275         else
2276 #endif /* 0 */
2277           set_longjmp_resume_breakpoint (jmp_buf_pc, null_frame_id);
2278         ecs->handling_longjmp = 1;      /* FIXME */
2279         keep_going (ecs);
2280         return;
2281
2282       case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
2283       case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME_SINGLE:
2284         remove_breakpoints ();
2285         breakpoints_inserted = 0;
2286 #if 0
2287         /* FIXME - Need to implement nested temporary breakpoints */
2288         if (step_over_calls
2289             && (frame_id_inner (get_frame_id (get_current_frame ()),
2290                                 step_frame_id)))
2291           {
2292             ecs->another_trap = 1;
2293             keep_going (ecs);
2294             return;
2295           }
2296 #endif /* 0 */
2297         disable_longjmp_breakpoint ();
2298         ecs->handling_longjmp = 0;      /* FIXME */
2299         if (what.main_action == BPSTAT_WHAT_CLEAR_LONGJMP_RESUME)
2300           break;
2301         /* else fallthrough */
2302
2303       case BPSTAT_WHAT_SINGLE:
2304         if (breakpoints_inserted)
2305           {
2306             remove_breakpoints ();
2307           }
2308         breakpoints_inserted = 0;
2309         ecs->another_trap = 1;
2310         /* Still need to check other stuff, at least the case
2311            where we are stepping and step out of the right range.  */
2312         break;
2313
2314       case BPSTAT_WHAT_STOP_NOISY:
2315         stop_print_frame = 1;
2316
2317         /* We are about to nuke the step_resume_breakpoint and
2318            through_sigtramp_breakpoint via the cleanup chain, so
2319            no need to worry about it here.  */
2320
2321         stop_stepping (ecs);
2322         return;
2323
2324       case BPSTAT_WHAT_STOP_SILENT:
2325         stop_print_frame = 0;
2326
2327         /* We are about to nuke the step_resume_breakpoint and
2328            through_sigtramp_breakpoint via the cleanup chain, so
2329            no need to worry about it here.  */
2330
2331         stop_stepping (ecs);
2332         return;
2333
2334       case BPSTAT_WHAT_STEP_RESUME:
2335         /* This proably demands a more elegant solution, but, yeah
2336            right...
2337
2338            This function's use of the simple variable
2339            step_resume_breakpoint doesn't seem to accomodate
2340            simultaneously active step-resume bp's, although the
2341            breakpoint list certainly can.
2342
2343            If we reach here and step_resume_breakpoint is already
2344            NULL, then apparently we have multiple active
2345            step-resume bp's.  We'll just delete the breakpoint we
2346            stopped at, and carry on.  
2347
2348            Correction: what the code currently does is delete a
2349            step-resume bp, but it makes no effort to ensure that
2350            the one deleted is the one currently stopped at.  MVS  */
2351
2352         if (step_resume_breakpoint == NULL)
2353           {
2354             step_resume_breakpoint =
2355               bpstat_find_step_resume_breakpoint (stop_bpstat);
2356           }
2357         delete_step_resume_breakpoint (&step_resume_breakpoint);
2358         break;
2359
2360       case BPSTAT_WHAT_THROUGH_SIGTRAMP:
2361         if (through_sigtramp_breakpoint)
2362           delete_breakpoint (through_sigtramp_breakpoint);
2363         through_sigtramp_breakpoint = NULL;
2364
2365         /* If were waiting for a trap, hitting the step_resume_break
2366            doesn't count as getting it.  */
2367         if (trap_expected)
2368           ecs->another_trap = 1;
2369         break;
2370
2371       case BPSTAT_WHAT_CHECK_SHLIBS:
2372       case BPSTAT_WHAT_CHECK_SHLIBS_RESUME_FROM_HOOK:
2373 #ifdef SOLIB_ADD
2374         {
2375           /* Remove breakpoints, we eventually want to step over the
2376              shlib event breakpoint, and SOLIB_ADD might adjust
2377              breakpoint addresses via breakpoint_re_set.  */
2378           if (breakpoints_inserted)
2379             remove_breakpoints ();
2380           breakpoints_inserted = 0;
2381
2382           /* Check for any newly added shared libraries if we're
2383              supposed to be adding them automatically.  Switch
2384              terminal for any messages produced by
2385              breakpoint_re_set.  */
2386           target_terminal_ours_for_output ();
2387           /* NOTE: cagney/2003-11-25: Make certain that the target
2388              stack's section table is kept up-to-date.  Architectures,
2389              (e.g., PPC64), use the section table to perform
2390              operations such as address => section name and hence
2391              require the table to contain all sections (including
2392              those found in shared libraries).  */
2393           /* NOTE: cagney/2003-11-25: Pass current_target and not
2394              exec_ops to SOLIB_ADD.  This is because current GDB is
2395              only tooled to propagate section_table changes out from
2396              the "current_target" (see target_resize_to_sections), and
2397              not up from the exec stratum.  This, of course, isn't
2398              right.  "infrun.c" should only interact with the
2399              exec/process stratum, instead relying on the target stack
2400              to propagate relevant changes (stop, section table
2401              changed, ...) up to other layers.  */
2402           SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
2403           target_terminal_inferior ();
2404
2405           /* Try to reenable shared library breakpoints, additional
2406              code segments in shared libraries might be mapped in now. */
2407           re_enable_breakpoints_in_shlibs ();
2408
2409           /* If requested, stop when the dynamic linker notifies
2410              gdb of events.  This allows the user to get control
2411              and place breakpoints in initializer routines for
2412              dynamically loaded objects (among other things).  */
2413           if (stop_on_solib_events || stop_stack_dummy)
2414             {
2415               stop_stepping (ecs);
2416               return;
2417             }
2418
2419           /* If we stopped due to an explicit catchpoint, then the
2420              (see above) call to SOLIB_ADD pulled in any symbols
2421              from a newly-loaded library, if appropriate.
2422
2423              We do want the inferior to stop, but not where it is
2424              now, which is in the dynamic linker callback.  Rather,
2425              we would like it stop in the user's program, just after
2426              the call that caused this catchpoint to trigger.  That
2427              gives the user a more useful vantage from which to
2428              examine their program's state. */
2429           else if (what.main_action ==
2430                    BPSTAT_WHAT_CHECK_SHLIBS_RESUME_FROM_HOOK)
2431             {
2432               /* ??rehrauer: If I could figure out how to get the
2433                  right return PC from here, we could just set a temp
2434                  breakpoint and resume.  I'm not sure we can without
2435                  cracking open the dld's shared libraries and sniffing
2436                  their unwind tables and text/data ranges, and that's
2437                  not a terribly portable notion.
2438
2439                  Until that time, we must step the inferior out of the
2440                  dld callback, and also out of the dld itself (and any
2441                  code or stubs in libdld.sl, such as "shl_load" and
2442                  friends) until we reach non-dld code.  At that point,
2443                  we can stop stepping. */
2444               bpstat_get_triggered_catchpoints (stop_bpstat,
2445                                                 &ecs->
2446                                                 stepping_through_solib_catchpoints);
2447               ecs->stepping_through_solib_after_catch = 1;
2448
2449               /* Be sure to lift all breakpoints, so the inferior does
2450                  actually step past this point... */
2451               ecs->another_trap = 1;
2452               break;
2453             }
2454           else
2455             {
2456               /* We want to step over this breakpoint, then keep going.  */
2457               ecs->another_trap = 1;
2458               break;
2459             }
2460         }
2461 #endif
2462         break;
2463
2464       case BPSTAT_WHAT_LAST:
2465         /* Not a real code, but listed here to shut up gcc -Wall.  */
2466
2467       case BPSTAT_WHAT_KEEP_CHECKING:
2468         break;
2469       }
2470   }
2471
2472   /* We come here if we hit a breakpoint but should not
2473      stop for it.  Possibly we also were stepping
2474      and should stop for that.  So fall through and
2475      test for stepping.  But, if not stepping,
2476      do not stop.  */
2477
2478   /* Are we stepping to get the inferior out of the dynamic
2479      linker's hook (and possibly the dld itself) after catching
2480      a shlib event? */
2481   if (ecs->stepping_through_solib_after_catch)
2482     {
2483 #if defined(SOLIB_ADD)
2484       /* Have we reached our destination?  If not, keep going. */
2485       if (SOLIB_IN_DYNAMIC_LINKER (PIDGET (ecs->ptid), stop_pc))
2486         {
2487           ecs->another_trap = 1;
2488           keep_going (ecs);
2489           return;
2490         }
2491 #endif
2492       /* Else, stop and report the catchpoint(s) whose triggering
2493          caused us to begin stepping. */
2494       ecs->stepping_through_solib_after_catch = 0;
2495       bpstat_clear (&stop_bpstat);
2496       stop_bpstat = bpstat_copy (ecs->stepping_through_solib_catchpoints);
2497       bpstat_clear (&ecs->stepping_through_solib_catchpoints);
2498       stop_print_frame = 1;
2499       stop_stepping (ecs);
2500       return;
2501     }
2502
2503   if (step_resume_breakpoint)
2504     {
2505       /* Having a step-resume breakpoint overrides anything
2506          else having to do with stepping commands until
2507          that breakpoint is reached.  */
2508       /* I'm not sure whether this needs to be check_sigtramp2 or
2509          whether it could/should be keep_going.  */
2510       check_sigtramp2 (ecs);
2511       keep_going (ecs);
2512       return;
2513     }
2514
2515   if (step_range_end == 0)
2516     {
2517       /* Likewise if we aren't even stepping.  */
2518       /* I'm not sure whether this needs to be check_sigtramp2 or
2519          whether it could/should be keep_going.  */
2520       check_sigtramp2 (ecs);
2521       keep_going (ecs);
2522       return;
2523     }
2524
2525   /* If stepping through a line, keep going if still within it.
2526
2527      Note that step_range_end is the address of the first instruction
2528      beyond the step range, and NOT the address of the last instruction
2529      within it! */
2530   if (stop_pc >= step_range_start && stop_pc < step_range_end)
2531     {
2532       /* We might be doing a BPSTAT_WHAT_SINGLE and getting a signal.
2533          So definately need to check for sigtramp here.  */
2534       check_sigtramp2 (ecs);
2535       keep_going (ecs);
2536       return;
2537     }
2538
2539   /* We stepped out of the stepping range.  */
2540
2541   /* If we are stepping at the source level and entered the runtime
2542      loader dynamic symbol resolution code, we keep on single stepping
2543      until we exit the run time loader code and reach the callee's
2544      address.  */
2545   if (step_over_calls == STEP_OVER_UNDEBUGGABLE
2546       && IN_SOLIB_DYNSYM_RESOLVE_CODE (stop_pc))
2547     {
2548       CORE_ADDR pc_after_resolver =
2549         gdbarch_skip_solib_resolver (current_gdbarch, stop_pc);
2550
2551       if (pc_after_resolver)
2552         {
2553           /* Set up a step-resume breakpoint at the address
2554              indicated by SKIP_SOLIB_RESOLVER.  */
2555           struct symtab_and_line sr_sal;
2556           init_sal (&sr_sal);
2557           sr_sal.pc = pc_after_resolver;
2558
2559           check_for_old_step_resume_breakpoint ();
2560           step_resume_breakpoint =
2561             set_momentary_breakpoint (sr_sal, null_frame_id, bp_step_resume);
2562           if (breakpoints_inserted)
2563             insert_breakpoints ();
2564         }
2565
2566       keep_going (ecs);
2567       return;
2568     }
2569
2570   /* We can't update step_sp every time through the loop, because
2571      reading the stack pointer would slow down stepping too much.
2572      But we can update it every time we leave the step range.  */
2573   ecs->update_step_sp = 1;
2574
2575   /* Did we just take a signal?  */
2576   if (pc_in_sigtramp (stop_pc)
2577       && !pc_in_sigtramp (prev_pc)
2578       && INNER_THAN (read_sp (), step_sp))
2579     {
2580       /* We've just taken a signal; go until we are back to
2581          the point where we took it and one more.  */
2582
2583       /* Note: The test above succeeds not only when we stepped
2584          into a signal handler, but also when we step past the last
2585          statement of a signal handler and end up in the return stub
2586          of the signal handler trampoline.  To distinguish between
2587          these two cases, check that the frame is INNER_THAN the
2588          previous one below. pai/1997-09-11 */
2589
2590
2591       {
2592         struct frame_id current_frame = get_frame_id (get_current_frame ());
2593
2594         if (frame_id_inner (current_frame, step_frame_id))
2595           {
2596             /* We have just taken a signal; go until we are back to
2597                the point where we took it and one more.  */
2598
2599             /* This code is needed at least in the following case:
2600                The user types "next" and then a signal arrives (before
2601                the "next" is done).  */
2602
2603             /* Note that if we are stopped at a breakpoint, then we need
2604                the step_resume breakpoint to override any breakpoints at
2605                the same location, so that we will still step over the
2606                breakpoint even though the signal happened.  */
2607             struct symtab_and_line sr_sal;
2608
2609             init_sal (&sr_sal);
2610             sr_sal.symtab = NULL;
2611             sr_sal.line = 0;
2612             sr_sal.pc = prev_pc;
2613             /* We could probably be setting the frame to
2614                step_frame_id; I don't think anyone thought to try it.  */
2615             check_for_old_step_resume_breakpoint ();
2616             step_resume_breakpoint =
2617               set_momentary_breakpoint (sr_sal, null_frame_id, bp_step_resume);
2618             if (breakpoints_inserted)
2619               insert_breakpoints ();
2620           }
2621         else
2622           {
2623             /* We just stepped out of a signal handler and into
2624                its calling trampoline.
2625
2626                Normally, we'd call step_over_function from
2627                here, but for some reason GDB can't unwind the
2628                stack correctly to find the real PC for the point
2629                user code where the signal trampoline will return
2630                -- FRAME_SAVED_PC fails, at least on HP-UX 10.20.
2631                But signal trampolines are pretty small stubs of
2632                code, anyway, so it's OK instead to just
2633                single-step out.  Note: assuming such trampolines
2634                don't exhibit recursion on any platform... */
2635             find_pc_partial_function (stop_pc, &ecs->stop_func_name,
2636                                       &ecs->stop_func_start,
2637                                       &ecs->stop_func_end);
2638             /* Readjust stepping range */
2639             step_range_start = ecs->stop_func_start;
2640             step_range_end = ecs->stop_func_end;
2641             ecs->stepping_through_sigtramp = 1;
2642           }
2643       }
2644
2645
2646       /* If this is stepi or nexti, make sure that the stepping range
2647          gets us past that instruction.  */
2648       if (step_range_end == 1)
2649         /* FIXME: Does this run afoul of the code below which, if
2650            we step into the middle of a line, resets the stepping
2651            range?  */
2652         step_range_end = (step_range_start = prev_pc) + 1;
2653
2654       ecs->remove_breakpoints_on_following_step = 1;
2655       keep_going (ecs);
2656       return;
2657     }
2658
2659   if (((stop_pc == ecs->stop_func_start /* Quick test */
2660         || in_prologue (stop_pc, ecs->stop_func_start))
2661        && !IN_SOLIB_RETURN_TRAMPOLINE (stop_pc, ecs->stop_func_name))
2662       || IN_SOLIB_CALL_TRAMPOLINE (stop_pc, ecs->stop_func_name)
2663       || ecs->stop_func_name == 0)
2664     {
2665       /* It's a subroutine call.  */
2666       handle_step_into_function (ecs);
2667       return;
2668     }
2669
2670   /* We've wandered out of the step range.  */
2671
2672   ecs->sal = find_pc_line (stop_pc, 0);
2673
2674   if (step_range_end == 1)
2675     {
2676       /* It is stepi or nexti.  We always want to stop stepping after
2677          one instruction.  */
2678       stop_step = 1;
2679       print_stop_reason (END_STEPPING_RANGE, 0);
2680       stop_stepping (ecs);
2681       return;
2682     }
2683
2684   /* If we're in the return path from a shared library trampoline,
2685      we want to proceed through the trampoline when stepping.  */
2686   if (IN_SOLIB_RETURN_TRAMPOLINE (stop_pc, ecs->stop_func_name))
2687     {
2688       /* Determine where this trampoline returns.  */
2689       CORE_ADDR real_stop_pc = SKIP_TRAMPOLINE_CODE (stop_pc);
2690
2691       /* Only proceed through if we know where it's going.  */
2692       if (real_stop_pc)
2693         {
2694           /* And put the step-breakpoint there and go until there. */
2695           struct symtab_and_line sr_sal;
2696
2697           init_sal (&sr_sal);   /* initialize to zeroes */
2698           sr_sal.pc = real_stop_pc;
2699           sr_sal.section = find_pc_overlay (sr_sal.pc);
2700           /* Do not specify what the fp should be when we stop
2701              since on some machines the prologue
2702              is where the new fp value is established.  */
2703           check_for_old_step_resume_breakpoint ();
2704           step_resume_breakpoint =
2705             set_momentary_breakpoint (sr_sal, null_frame_id, bp_step_resume);
2706           if (breakpoints_inserted)
2707             insert_breakpoints ();
2708
2709           /* Restart without fiddling with the step ranges or
2710              other state.  */
2711           keep_going (ecs);
2712           return;
2713         }
2714     }
2715
2716   if (ecs->sal.line == 0)
2717     {
2718       /* We have no line number information.  That means to stop
2719          stepping (does this always happen right after one instruction,
2720          when we do "s" in a function with no line numbers,
2721          or can this happen as a result of a return or longjmp?).  */
2722       stop_step = 1;
2723       print_stop_reason (END_STEPPING_RANGE, 0);
2724       stop_stepping (ecs);
2725       return;
2726     }
2727
2728   if ((stop_pc == ecs->sal.pc)
2729       && (ecs->current_line != ecs->sal.line
2730           || ecs->current_symtab != ecs->sal.symtab))
2731     {
2732       /* We are at the start of a different line.  So stop.  Note that
2733          we don't stop if we step into the middle of a different line.
2734          That is said to make things like for (;;) statements work
2735          better.  */
2736       stop_step = 1;
2737       print_stop_reason (END_STEPPING_RANGE, 0);
2738       stop_stepping (ecs);
2739       return;
2740     }
2741
2742   /* We aren't done stepping.
2743
2744      Optimize by setting the stepping range to the line.
2745      (We might not be in the original line, but if we entered a
2746      new line in mid-statement, we continue stepping.  This makes
2747      things like for(;;) statements work better.)  */
2748
2749   if (ecs->stop_func_end && ecs->sal.end >= ecs->stop_func_end)
2750     {
2751       /* If this is the last line of the function, don't keep stepping
2752          (it would probably step us out of the function).
2753          This is particularly necessary for a one-line function,
2754          in which after skipping the prologue we better stop even though
2755          we will be in mid-line.  */
2756       stop_step = 1;
2757       print_stop_reason (END_STEPPING_RANGE, 0);
2758       stop_stepping (ecs);
2759       return;
2760     }
2761   step_range_start = ecs->sal.pc;
2762   step_range_end = ecs->sal.end;
2763   step_frame_id = get_frame_id (get_current_frame ());
2764   ecs->current_line = ecs->sal.line;
2765   ecs->current_symtab = ecs->sal.symtab;
2766
2767   /* In the case where we just stepped out of a function into the
2768      middle of a line of the caller, continue stepping, but
2769      step_frame_id must be modified to current frame */
2770 #if 0
2771   /* NOTE: cagney/2003-10-16: I think this frame ID inner test is too
2772      generous.  It will trigger on things like a step into a frameless
2773      stackless leaf function.  I think the logic should instead look
2774      at the unwound frame ID has that should give a more robust
2775      indication of what happened.  */
2776      if (step-ID == current-ID)
2777        still stepping in same function;
2778      else if (step-ID == unwind (current-ID))
2779        stepped into a function;
2780      else
2781        stepped out of a function;
2782      /* Of course this assumes that the frame ID unwind code is robust
2783         and we're willing to introduce frame unwind logic into this
2784         function.  Fortunately, those days are nearly upon us.  */
2785 #endif
2786   {
2787     struct frame_id current_frame = get_frame_id (get_current_frame ());
2788     if (!(frame_id_inner (current_frame, step_frame_id)))
2789       step_frame_id = current_frame;
2790   }
2791
2792   keep_going (ecs);
2793 }
2794
2795 /* Are we in the middle of stepping?  */
2796
2797 static int
2798 currently_stepping (struct execution_control_state *ecs)
2799 {
2800   return ((through_sigtramp_breakpoint == NULL
2801            && !ecs->handling_longjmp
2802            && ((step_range_end && step_resume_breakpoint == NULL)
2803                || trap_expected))
2804           || ecs->stepping_through_solib_after_catch
2805           || bpstat_should_step ());
2806 }
2807
2808 static void
2809 check_sigtramp2 (struct execution_control_state *ecs)
2810 {
2811   if (trap_expected
2812       && pc_in_sigtramp (stop_pc)
2813       && !pc_in_sigtramp (prev_pc)
2814       && INNER_THAN (read_sp (), step_sp))
2815     {
2816       /* What has happened here is that we have just stepped the
2817          inferior with a signal (because it is a signal which
2818          shouldn't make us stop), thus stepping into sigtramp.
2819
2820          So we need to set a step_resume_break_address breakpoint and
2821          continue until we hit it, and then step.  FIXME: This should
2822          be more enduring than a step_resume breakpoint; we should
2823          know that we will later need to keep going rather than
2824          re-hitting the breakpoint here (see the testsuite,
2825          gdb.base/signals.exp where it says "exceedingly difficult").  */
2826
2827       struct symtab_and_line sr_sal;
2828
2829       init_sal (&sr_sal);       /* initialize to zeroes */
2830       sr_sal.pc = prev_pc;
2831       sr_sal.section = find_pc_overlay (sr_sal.pc);
2832       /* We perhaps could set the frame if we kept track of what the
2833          frame corresponding to prev_pc was.  But we don't, so don't.  */
2834       through_sigtramp_breakpoint =
2835         set_momentary_breakpoint (sr_sal, null_frame_id, bp_through_sigtramp);
2836       if (breakpoints_inserted)
2837         insert_breakpoints ();
2838
2839       ecs->remove_breakpoints_on_following_step = 1;
2840       ecs->another_trap = 1;
2841     }
2842 }
2843
2844 /* Subroutine call with source code we should not step over.  Do step
2845    to the first line of code in it.  */
2846
2847 static void
2848 step_into_function (struct execution_control_state *ecs)
2849 {
2850   struct symtab *s;
2851   struct symtab_and_line sr_sal;
2852
2853   s = find_pc_symtab (stop_pc);
2854   if (s && s->language != language_asm)
2855     ecs->stop_func_start = SKIP_PROLOGUE (ecs->stop_func_start);
2856
2857   ecs->sal = find_pc_line (ecs->stop_func_start, 0);
2858   /* Use the step_resume_break to step until the end of the prologue,
2859      even if that involves jumps (as it seems to on the vax under
2860      4.2).  */
2861   /* If the prologue ends in the middle of a source line, continue to
2862      the end of that source line (if it is still within the function).
2863      Otherwise, just go to end of prologue.  */
2864   if (ecs->sal.end
2865       && ecs->sal.pc != ecs->stop_func_start
2866       && ecs->sal.end < ecs->stop_func_end)
2867     ecs->stop_func_start = ecs->sal.end;
2868
2869   /* Architectures which require breakpoint adjustment might not be able
2870      to place a breakpoint at the computed address.  If so, the test
2871      ``ecs->stop_func_start == stop_pc'' will never succeed.  Adjust
2872      ecs->stop_func_start to an address at which a breakpoint may be
2873      legitimately placed.
2874      
2875      Note:  kevinb/2004-01-19:  On FR-V, if this adjustment is not
2876      made, GDB will enter an infinite loop when stepping through
2877      optimized code consisting of VLIW instructions which contain
2878      subinstructions corresponding to different source lines.  On
2879      FR-V, it's not permitted to place a breakpoint on any but the
2880      first subinstruction of a VLIW instruction.  When a breakpoint is
2881      set, GDB will adjust the breakpoint address to the beginning of
2882      the VLIW instruction.  Thus, we need to make the corresponding
2883      adjustment here when computing the stop address.  */
2884      
2885   if (gdbarch_adjust_breakpoint_address_p (current_gdbarch))
2886     {
2887       ecs->stop_func_start
2888         = gdbarch_adjust_breakpoint_address (current_gdbarch,
2889                                              ecs->stop_func_start);
2890     }
2891
2892   if (ecs->stop_func_start == stop_pc)
2893     {
2894       /* We are already there: stop now.  */
2895       stop_step = 1;
2896       print_stop_reason (END_STEPPING_RANGE, 0);
2897       stop_stepping (ecs);
2898       return;
2899     }
2900   else
2901     {
2902       /* Put the step-breakpoint there and go until there.  */
2903       init_sal (&sr_sal);       /* initialize to zeroes */
2904       sr_sal.pc = ecs->stop_func_start;
2905       sr_sal.section = find_pc_overlay (ecs->stop_func_start);
2906       /* Do not specify what the fp should be when we stop since on
2907          some machines the prologue is where the new fp value is
2908          established.  */
2909       check_for_old_step_resume_breakpoint ();
2910       step_resume_breakpoint =
2911         set_momentary_breakpoint (sr_sal, null_frame_id, bp_step_resume);
2912       if (breakpoints_inserted)
2913         insert_breakpoints ();
2914
2915       /* And make sure stepping stops right away then.  */
2916       step_range_end = step_range_start;
2917     }
2918   keep_going (ecs);
2919 }
2920
2921 /* We've just entered a callee, and we wish to resume until it returns
2922    to the caller.  Setting a step_resume breakpoint on the return
2923    address will catch a return from the callee.
2924      
2925    However, if the callee is recursing, we want to be careful not to
2926    catch returns of those recursive calls, but only of THIS instance
2927    of the call.
2928
2929    To do this, we set the step_resume bp's frame to our current
2930    caller's frame (step_frame_id, which is set by the "next" or
2931    "until" command, before execution begins).  */
2932
2933 static void
2934 step_over_function (struct execution_control_state *ecs)
2935 {
2936   struct symtab_and_line sr_sal;
2937
2938   init_sal (&sr_sal);           /* initialize to zeros */
2939
2940   /* NOTE: cagney/2003-04-06:
2941
2942      At this point the equality get_frame_pc() == get_frame_func()
2943      should hold.  This may make it possible for this code to tell the
2944      frame where it's function is, instead of the reverse.  This would
2945      avoid the need to search for the frame's function, which can get
2946      very messy when there is no debug info available (look at the
2947      heuristic find pc start code found in targets like the MIPS).  */
2948
2949   /* NOTE: cagney/2003-04-06:
2950
2951      The intent of DEPRECATED_SAVED_PC_AFTER_CALL was to:
2952
2953      - provide a very light weight equivalent to frame_unwind_pc()
2954      (nee FRAME_SAVED_PC) that avoids the prologue analyzer
2955
2956      - avoid handling the case where the PC hasn't been saved in the
2957      prologue analyzer
2958
2959      Unfortunately, not five lines further down, is a call to
2960      get_frame_id() and that is guarenteed to trigger the prologue
2961      analyzer.
2962      
2963      The `correct fix' is for the prologe analyzer to handle the case
2964      where the prologue is incomplete (PC in prologue) and,
2965      consequently, the return pc has not yet been saved.  It should be
2966      noted that the prologue analyzer needs to handle this case
2967      anyway: frameless leaf functions that don't save the return PC;
2968      single stepping through a prologue.
2969
2970      The d10v handles all this by bailing out of the prologue analsis
2971      when it reaches the current instruction.  */
2972
2973   if (DEPRECATED_SAVED_PC_AFTER_CALL_P ())
2974     sr_sal.pc = ADDR_BITS_REMOVE (DEPRECATED_SAVED_PC_AFTER_CALL (get_current_frame ()));
2975   else
2976     sr_sal.pc = ADDR_BITS_REMOVE (frame_pc_unwind (get_current_frame ()));
2977   sr_sal.section = find_pc_overlay (sr_sal.pc);
2978
2979   check_for_old_step_resume_breakpoint ();
2980   step_resume_breakpoint =
2981     set_momentary_breakpoint (sr_sal, get_frame_id (get_current_frame ()),
2982                               bp_step_resume);
2983
2984   if (frame_id_p (step_frame_id)
2985       && !IN_SOLIB_DYNSYM_RESOLVE_CODE (sr_sal.pc))
2986     step_resume_breakpoint->frame_id = step_frame_id;
2987
2988   if (breakpoints_inserted)
2989     insert_breakpoints ();
2990 }
2991
2992 static void
2993 stop_stepping (struct execution_control_state *ecs)
2994 {
2995   /* Let callers know we don't want to wait for the inferior anymore.  */
2996   ecs->wait_some_more = 0;
2997 }
2998
2999 /* This function handles various cases where we need to continue
3000    waiting for the inferior.  */
3001 /* (Used to be the keep_going: label in the old wait_for_inferior) */
3002
3003 static void
3004 keep_going (struct execution_control_state *ecs)
3005 {
3006   /* Save the pc before execution, to compare with pc after stop.  */
3007   prev_pc = read_pc ();         /* Might have been DECR_AFTER_BREAK */
3008
3009   if (ecs->update_step_sp)
3010     step_sp = read_sp ();
3011   ecs->update_step_sp = 0;
3012
3013   /* If we did not do break;, it means we should keep running the
3014      inferior and not return to debugger.  */
3015
3016   if (trap_expected && stop_signal != TARGET_SIGNAL_TRAP)
3017     {
3018       /* We took a signal (which we are supposed to pass through to
3019          the inferior, else we'd have done a break above) and we
3020          haven't yet gotten our trap.  Simply continue.  */
3021       resume (currently_stepping (ecs), stop_signal);
3022     }
3023   else
3024     {
3025       /* Either the trap was not expected, but we are continuing
3026          anyway (the user asked that this signal be passed to the
3027          child)
3028          -- or --
3029          The signal was SIGTRAP, e.g. it was our signal, but we
3030          decided we should resume from it.
3031
3032          We're going to run this baby now!
3033
3034          Insert breakpoints now, unless we are trying to one-proceed
3035          past a breakpoint.  */
3036       /* If we've just finished a special step resume and we don't
3037          want to hit a breakpoint, pull em out.  */
3038       if (step_resume_breakpoint == NULL
3039           && through_sigtramp_breakpoint == NULL
3040           && ecs->remove_breakpoints_on_following_step)
3041         {
3042           ecs->remove_breakpoints_on_following_step = 0;
3043           remove_breakpoints ();
3044           breakpoints_inserted = 0;
3045         }
3046       else if (!breakpoints_inserted &&
3047                (through_sigtramp_breakpoint != NULL || !ecs->another_trap))
3048         {
3049           breakpoints_failed = insert_breakpoints ();
3050           if (breakpoints_failed)
3051             {
3052               stop_stepping (ecs);
3053               return;
3054             }
3055           breakpoints_inserted = 1;
3056         }
3057
3058       trap_expected = ecs->another_trap;
3059
3060       /* Do not deliver SIGNAL_TRAP (except when the user explicitly
3061          specifies that such a signal should be delivered to the
3062          target program).
3063
3064          Typically, this would occure when a user is debugging a
3065          target monitor on a simulator: the target monitor sets a
3066          breakpoint; the simulator encounters this break-point and
3067          halts the simulation handing control to GDB; GDB, noteing
3068          that the break-point isn't valid, returns control back to the
3069          simulator; the simulator then delivers the hardware
3070          equivalent of a SIGNAL_TRAP to the program being debugged. */
3071
3072       if (stop_signal == TARGET_SIGNAL_TRAP && !signal_program[stop_signal])
3073         stop_signal = TARGET_SIGNAL_0;
3074
3075
3076       resume (currently_stepping (ecs), stop_signal);
3077     }
3078
3079   prepare_to_wait (ecs);
3080 }
3081
3082 /* This function normally comes after a resume, before
3083    handle_inferior_event exits.  It takes care of any last bits of
3084    housekeeping, and sets the all-important wait_some_more flag.  */
3085
3086 static void
3087 prepare_to_wait (struct execution_control_state *ecs)
3088 {
3089   if (ecs->infwait_state == infwait_normal_state)
3090     {
3091       overlay_cache_invalid = 1;
3092
3093       /* We have to invalidate the registers BEFORE calling
3094          target_wait because they can be loaded from the target while
3095          in target_wait.  This makes remote debugging a bit more
3096          efficient for those targets that provide critical registers
3097          as part of their normal status mechanism. */
3098
3099       registers_changed ();
3100       ecs->waiton_ptid = pid_to_ptid (-1);
3101       ecs->wp = &(ecs->ws);
3102     }
3103   /* This is the old end of the while loop.  Let everybody know we
3104      want to wait for the inferior some more and get called again
3105      soon.  */
3106   ecs->wait_some_more = 1;
3107 }
3108
3109 /* Print why the inferior has stopped. We always print something when
3110    the inferior exits, or receives a signal. The rest of the cases are
3111    dealt with later on in normal_stop() and print_it_typical().  Ideally
3112    there should be a call to this function from handle_inferior_event()
3113    each time stop_stepping() is called.*/
3114 static void
3115 print_stop_reason (enum inferior_stop_reason stop_reason, int stop_info)
3116 {
3117   switch (stop_reason)
3118     {
3119     case STOP_UNKNOWN:
3120       /* We don't deal with these cases from handle_inferior_event()
3121          yet. */
3122       break;
3123     case END_STEPPING_RANGE:
3124       /* We are done with a step/next/si/ni command. */
3125       /* For now print nothing. */
3126       /* Print a message only if not in the middle of doing a "step n"
3127          operation for n > 1 */
3128       if (!step_multi || !stop_step)
3129         if (ui_out_is_mi_like_p (uiout))
3130           ui_out_field_string (uiout, "reason", "end-stepping-range");
3131       break;
3132     case BREAKPOINT_HIT:
3133       /* We found a breakpoint. */
3134       /* For now print nothing. */
3135       break;
3136     case SIGNAL_EXITED:
3137       /* The inferior was terminated by a signal. */
3138       annotate_signalled ();
3139       if (ui_out_is_mi_like_p (uiout))
3140         ui_out_field_string (uiout, "reason", "exited-signalled");
3141       ui_out_text (uiout, "\nProgram terminated with signal ");
3142       annotate_signal_name ();
3143       ui_out_field_string (uiout, "signal-name",
3144                            target_signal_to_name (stop_info));
3145       annotate_signal_name_end ();
3146       ui_out_text (uiout, ", ");
3147       annotate_signal_string ();
3148       ui_out_field_string (uiout, "signal-meaning",
3149                            target_signal_to_string (stop_info));
3150       annotate_signal_string_end ();
3151       ui_out_text (uiout, ".\n");
3152       ui_out_text (uiout, "The program no longer exists.\n");
3153       break;
3154     case EXITED:
3155       /* The inferior program is finished. */
3156       annotate_exited (stop_info);
3157       if (stop_info)
3158         {
3159           if (ui_out_is_mi_like_p (uiout))
3160             ui_out_field_string (uiout, "reason", "exited");
3161           ui_out_text (uiout, "\nProgram exited with code ");
3162           ui_out_field_fmt (uiout, "exit-code", "0%o",
3163                             (unsigned int) stop_info);
3164           ui_out_text (uiout, ".\n");
3165         }
3166       else
3167         {
3168           if (ui_out_is_mi_like_p (uiout))
3169             ui_out_field_string (uiout, "reason", "exited-normally");
3170           ui_out_text (uiout, "\nProgram exited normally.\n");
3171         }
3172       break;
3173     case SIGNAL_RECEIVED:
3174       /* Signal received. The signal table tells us to print about
3175          it. */
3176       annotate_signal ();
3177       ui_out_text (uiout, "\nProgram received signal ");
3178       annotate_signal_name ();
3179       if (ui_out_is_mi_like_p (uiout))
3180         ui_out_field_string (uiout, "reason", "signal-received");
3181       ui_out_field_string (uiout, "signal-name",
3182                            target_signal_to_name (stop_info));
3183       annotate_signal_name_end ();
3184       ui_out_text (uiout, ", ");
3185       annotate_signal_string ();
3186       ui_out_field_string (uiout, "signal-meaning",
3187                            target_signal_to_string (stop_info));
3188       annotate_signal_string_end ();
3189       ui_out_text (uiout, ".\n");
3190       break;
3191     default:
3192       internal_error (__FILE__, __LINE__,
3193                       "print_stop_reason: unrecognized enum value");
3194       break;
3195     }
3196 }
3197 \f
3198
3199 /* Here to return control to GDB when the inferior stops for real.
3200    Print appropriate messages, remove breakpoints, give terminal our modes.
3201
3202    STOP_PRINT_FRAME nonzero means print the executing frame
3203    (pc, function, args, file, line number and line text).
3204    BREAKPOINTS_FAILED nonzero means stop was due to error
3205    attempting to insert breakpoints.  */
3206
3207 void
3208 normal_stop (void)
3209 {
3210   struct target_waitstatus last;
3211   ptid_t last_ptid;
3212
3213   get_last_target_status (&last_ptid, &last);
3214
3215   /* As with the notification of thread events, we want to delay
3216      notifying the user that we've switched thread context until
3217      the inferior actually stops.
3218
3219      There's no point in saying anything if the inferior has exited.
3220      Note that SIGNALLED here means "exited with a signal", not
3221      "received a signal".  */
3222   if (!ptid_equal (previous_inferior_ptid, inferior_ptid)
3223       && target_has_execution
3224       && last.kind != TARGET_WAITKIND_SIGNALLED
3225       && last.kind != TARGET_WAITKIND_EXITED)
3226     {
3227       target_terminal_ours_for_output ();
3228       printf_filtered ("[Switching to %s]\n",
3229                        target_pid_or_tid_to_str (inferior_ptid));
3230       previous_inferior_ptid = inferior_ptid;
3231     }
3232
3233   /* NOTE drow/2004-01-17: Is this still necessary?  */
3234   /* Make sure that the current_frame's pc is correct.  This
3235      is a correction for setting up the frame info before doing
3236      DECR_PC_AFTER_BREAK */
3237   if (target_has_execution)
3238     /* FIXME: cagney/2002-12-06: Has the PC changed?  Thanks to
3239        DECR_PC_AFTER_BREAK, the program counter can change.  Ask the
3240        frame code to check for this and sort out any resultant mess.
3241        DECR_PC_AFTER_BREAK needs to just go away.  */
3242     deprecated_update_frame_pc_hack (get_current_frame (), read_pc ());
3243
3244   if (target_has_execution && breakpoints_inserted)
3245     {
3246       if (remove_breakpoints ())
3247         {
3248           target_terminal_ours_for_output ();
3249           printf_filtered ("Cannot remove breakpoints because ");
3250           printf_filtered ("program is no longer writable.\n");
3251           printf_filtered ("It might be running in another process.\n");
3252           printf_filtered ("Further execution is probably impossible.\n");
3253         }
3254     }
3255   breakpoints_inserted = 0;
3256
3257   /* Delete the breakpoint we stopped at, if it wants to be deleted.
3258      Delete any breakpoint that is to be deleted at the next stop.  */
3259
3260   breakpoint_auto_delete (stop_bpstat);
3261
3262   /* If an auto-display called a function and that got a signal,
3263      delete that auto-display to avoid an infinite recursion.  */
3264
3265   if (stopped_by_random_signal)
3266     disable_current_display ();
3267
3268   /* Don't print a message if in the middle of doing a "step n"
3269      operation for n > 1 */
3270   if (step_multi && stop_step)
3271     goto done;
3272
3273   target_terminal_ours ();
3274
3275   /* Look up the hook_stop and run it (CLI internally handles problem
3276      of stop_command's pre-hook not existing).  */
3277   if (stop_command)
3278     catch_errors (hook_stop_stub, stop_command,
3279                   "Error while running hook_stop:\n", RETURN_MASK_ALL);
3280
3281   if (!target_has_stack)
3282     {
3283
3284       goto done;
3285     }
3286
3287   /* Select innermost stack frame - i.e., current frame is frame 0,
3288      and current location is based on that.
3289      Don't do this on return from a stack dummy routine,
3290      or if the program has exited. */
3291
3292   if (!stop_stack_dummy)
3293     {
3294       select_frame (get_current_frame ());
3295
3296       /* Print current location without a level number, if
3297          we have changed functions or hit a breakpoint.
3298          Print source line if we have one.
3299          bpstat_print() contains the logic deciding in detail
3300          what to print, based on the event(s) that just occurred. */
3301
3302       if (stop_print_frame && deprecated_selected_frame)
3303         {
3304           int bpstat_ret;
3305           int source_flag;
3306           int do_frame_printing = 1;
3307
3308           bpstat_ret = bpstat_print (stop_bpstat);
3309           switch (bpstat_ret)
3310             {
3311             case PRINT_UNKNOWN:
3312               /* FIXME: cagney/2002-12-01: Given that a frame ID does
3313                  (or should) carry around the function and does (or
3314                  should) use that when doing a frame comparison.  */
3315               if (stop_step
3316                   && frame_id_eq (step_frame_id,
3317                                   get_frame_id (get_current_frame ()))
3318                   && step_start_function == find_pc_function (stop_pc))
3319                 source_flag = SRC_LINE; /* finished step, just print source line */
3320               else
3321                 source_flag = SRC_AND_LOC;      /* print location and source line */
3322               break;
3323             case PRINT_SRC_AND_LOC:
3324               source_flag = SRC_AND_LOC;        /* print location and source line */
3325               break;
3326             case PRINT_SRC_ONLY:
3327               source_flag = SRC_LINE;
3328               break;
3329             case PRINT_NOTHING:
3330               source_flag = SRC_LINE;   /* something bogus */
3331               do_frame_printing = 0;
3332               break;
3333             default:
3334               internal_error (__FILE__, __LINE__, "Unknown value.");
3335             }
3336           /* For mi, have the same behavior every time we stop:
3337              print everything but the source line. */
3338           if (ui_out_is_mi_like_p (uiout))
3339             source_flag = LOC_AND_ADDRESS;
3340
3341           if (ui_out_is_mi_like_p (uiout))
3342             ui_out_field_int (uiout, "thread-id",
3343                               pid_to_thread_id (inferior_ptid));
3344           /* The behavior of this routine with respect to the source
3345              flag is:
3346              SRC_LINE: Print only source line
3347              LOCATION: Print only location
3348              SRC_AND_LOC: Print location and source line */
3349           if (do_frame_printing)
3350             print_stack_frame (deprecated_selected_frame, -1, source_flag);
3351
3352           /* Display the auto-display expressions.  */
3353           do_displays ();
3354         }
3355     }
3356
3357   /* Save the function value return registers, if we care.
3358      We might be about to restore their previous contents.  */
3359   if (proceed_to_finish)
3360     /* NB: The copy goes through to the target picking up the value of
3361        all the registers.  */
3362     regcache_cpy (stop_registers, current_regcache);
3363
3364   if (stop_stack_dummy)
3365     {
3366       /* Pop the empty frame that contains the stack dummy.  POP_FRAME
3367          ends with a setting of the current frame, so we can use that
3368          next. */
3369       frame_pop (get_current_frame ());
3370       /* Set stop_pc to what it was before we called the function.
3371          Can't rely on restore_inferior_status because that only gets
3372          called if we don't stop in the called function.  */
3373       stop_pc = read_pc ();
3374       select_frame (get_current_frame ());
3375     }
3376
3377 done:
3378   annotate_stopped ();
3379   observer_notify_normal_stop ();
3380 }
3381
3382 static int
3383 hook_stop_stub (void *cmd)
3384 {
3385   execute_cmd_pre_hook ((struct cmd_list_element *) cmd);
3386   return (0);
3387 }
3388 \f
3389 int
3390 signal_stop_state (int signo)
3391 {
3392   return signal_stop[signo];
3393 }
3394
3395 int
3396 signal_print_state (int signo)
3397 {
3398   return signal_print[signo];
3399 }
3400
3401 int
3402 signal_pass_state (int signo)
3403 {
3404   return signal_program[signo];
3405 }
3406
3407 int
3408 signal_stop_update (int signo, int state)
3409 {
3410   int ret = signal_stop[signo];
3411   signal_stop[signo] = state;
3412   return ret;
3413 }
3414
3415 int
3416 signal_print_update (int signo, int state)
3417 {
3418   int ret = signal_print[signo];
3419   signal_print[signo] = state;
3420   return ret;
3421 }
3422
3423 int
3424 signal_pass_update (int signo, int state)
3425 {
3426   int ret = signal_program[signo];
3427   signal_program[signo] = state;
3428   return ret;
3429 }
3430
3431 static void
3432 sig_print_header (void)
3433 {
3434   printf_filtered ("\
3435 Signal        Stop\tPrint\tPass to program\tDescription\n");
3436 }
3437
3438 static void
3439 sig_print_info (enum target_signal oursig)
3440 {
3441   char *name = target_signal_to_name (oursig);
3442   int name_padding = 13 - strlen (name);
3443
3444   if (name_padding <= 0)
3445     name_padding = 0;
3446
3447   printf_filtered ("%s", name);
3448   printf_filtered ("%*.*s ", name_padding, name_padding, "                 ");
3449   printf_filtered ("%s\t", signal_stop[oursig] ? "Yes" : "No");
3450   printf_filtered ("%s\t", signal_print[oursig] ? "Yes" : "No");
3451   printf_filtered ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
3452   printf_filtered ("%s\n", target_signal_to_string (oursig));
3453 }
3454
3455 /* Specify how various signals in the inferior should be handled.  */
3456
3457 static void
3458 handle_command (char *args, int from_tty)
3459 {
3460   char **argv;
3461   int digits, wordlen;
3462   int sigfirst, signum, siglast;
3463   enum target_signal oursig;
3464   int allsigs;
3465   int nsigs;
3466   unsigned char *sigs;
3467   struct cleanup *old_chain;
3468
3469   if (args == NULL)
3470     {
3471       error_no_arg ("signal to handle");
3472     }
3473
3474   /* Allocate and zero an array of flags for which signals to handle. */
3475
3476   nsigs = (int) TARGET_SIGNAL_LAST;
3477   sigs = (unsigned char *) alloca (nsigs);
3478   memset (sigs, 0, nsigs);
3479
3480   /* Break the command line up into args. */
3481
3482   argv = buildargv (args);
3483   if (argv == NULL)
3484     {
3485       nomem (0);
3486     }
3487   old_chain = make_cleanup_freeargv (argv);
3488
3489   /* Walk through the args, looking for signal oursigs, signal names, and
3490      actions.  Signal numbers and signal names may be interspersed with
3491      actions, with the actions being performed for all signals cumulatively
3492      specified.  Signal ranges can be specified as <LOW>-<HIGH>. */
3493
3494   while (*argv != NULL)
3495     {
3496       wordlen = strlen (*argv);
3497       for (digits = 0; isdigit ((*argv)[digits]); digits++)
3498         {;
3499         }
3500       allsigs = 0;
3501       sigfirst = siglast = -1;
3502
3503       if (wordlen >= 1 && !strncmp (*argv, "all", wordlen))
3504         {
3505           /* Apply action to all signals except those used by the
3506              debugger.  Silently skip those. */
3507           allsigs = 1;
3508           sigfirst = 0;
3509           siglast = nsigs - 1;
3510         }
3511       else if (wordlen >= 1 && !strncmp (*argv, "stop", wordlen))
3512         {
3513           SET_SIGS (nsigs, sigs, signal_stop);
3514           SET_SIGS (nsigs, sigs, signal_print);
3515         }
3516       else if (wordlen >= 1 && !strncmp (*argv, "ignore", wordlen))
3517         {
3518           UNSET_SIGS (nsigs, sigs, signal_program);
3519         }
3520       else if (wordlen >= 2 && !strncmp (*argv, "print", wordlen))
3521         {
3522           SET_SIGS (nsigs, sigs, signal_print);
3523         }
3524       else if (wordlen >= 2 && !strncmp (*argv, "pass", wordlen))
3525         {
3526           SET_SIGS (nsigs, sigs, signal_program);
3527         }
3528       else if (wordlen >= 3 && !strncmp (*argv, "nostop", wordlen))
3529         {
3530           UNSET_SIGS (nsigs, sigs, signal_stop);
3531         }
3532       else if (wordlen >= 3 && !strncmp (*argv, "noignore", wordlen))
3533         {
3534           SET_SIGS (nsigs, sigs, signal_program);
3535         }
3536       else if (wordlen >= 4 && !strncmp (*argv, "noprint", wordlen))
3537         {
3538           UNSET_SIGS (nsigs, sigs, signal_print);
3539           UNSET_SIGS (nsigs, sigs, signal_stop);
3540         }
3541       else if (wordlen >= 4 && !strncmp (*argv, "nopass", wordlen))
3542         {
3543           UNSET_SIGS (nsigs, sigs, signal_program);
3544         }
3545       else if (digits > 0)
3546         {
3547           /* It is numeric.  The numeric signal refers to our own
3548              internal signal numbering from target.h, not to host/target
3549              signal  number.  This is a feature; users really should be
3550              using symbolic names anyway, and the common ones like
3551              SIGHUP, SIGINT, SIGALRM, etc. will work right anyway.  */
3552
3553           sigfirst = siglast = (int)
3554             target_signal_from_command (atoi (*argv));
3555           if ((*argv)[digits] == '-')
3556             {
3557               siglast = (int)
3558                 target_signal_from_command (atoi ((*argv) + digits + 1));
3559             }
3560           if (sigfirst > siglast)
3561             {
3562               /* Bet he didn't figure we'd think of this case... */
3563               signum = sigfirst;
3564               sigfirst = siglast;
3565               siglast = signum;
3566             }
3567         }
3568       else
3569         {
3570           oursig = target_signal_from_name (*argv);
3571           if (oursig != TARGET_SIGNAL_UNKNOWN)
3572             {
3573               sigfirst = siglast = (int) oursig;
3574             }
3575           else
3576             {
3577               /* Not a number and not a recognized flag word => complain.  */
3578               error ("Unrecognized or ambiguous flag word: \"%s\".", *argv);
3579             }
3580         }
3581
3582       /* If any signal numbers or symbol names were found, set flags for
3583          which signals to apply actions to. */
3584
3585       for (signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
3586         {
3587           switch ((enum target_signal) signum)
3588             {
3589             case TARGET_SIGNAL_TRAP:
3590             case TARGET_SIGNAL_INT:
3591               if (!allsigs && !sigs[signum])
3592                 {
3593                   if (query ("%s is used by the debugger.\n\
3594 Are you sure you want to change it? ", target_signal_to_name ((enum target_signal) signum)))
3595                     {
3596                       sigs[signum] = 1;
3597                     }
3598                   else
3599                     {
3600                       printf_unfiltered ("Not confirmed, unchanged.\n");
3601                       gdb_flush (gdb_stdout);
3602                     }
3603                 }
3604               break;
3605             case TARGET_SIGNAL_0:
3606             case TARGET_SIGNAL_DEFAULT:
3607             case TARGET_SIGNAL_UNKNOWN:
3608               /* Make sure that "all" doesn't print these.  */
3609               break;
3610             default:
3611               sigs[signum] = 1;
3612               break;
3613             }
3614         }
3615
3616       argv++;
3617     }
3618
3619   target_notice_signals (inferior_ptid);
3620
3621   if (from_tty)
3622     {
3623       /* Show the results.  */
3624       sig_print_header ();
3625       for (signum = 0; signum < nsigs; signum++)
3626         {
3627           if (sigs[signum])
3628             {
3629               sig_print_info (signum);
3630             }
3631         }
3632     }
3633
3634   do_cleanups (old_chain);
3635 }
3636
3637 static void
3638 xdb_handle_command (char *args, int from_tty)
3639 {
3640   char **argv;
3641   struct cleanup *old_chain;
3642
3643   /* Break the command line up into args. */
3644
3645   argv = buildargv (args);
3646   if (argv == NULL)
3647     {
3648       nomem (0);
3649     }
3650   old_chain = make_cleanup_freeargv (argv);
3651   if (argv[1] != (char *) NULL)
3652     {
3653       char *argBuf;
3654       int bufLen;
3655
3656       bufLen = strlen (argv[0]) + 20;
3657       argBuf = (char *) xmalloc (bufLen);
3658       if (argBuf)
3659         {
3660           int validFlag = 1;
3661           enum target_signal oursig;
3662
3663           oursig = target_signal_from_name (argv[0]);
3664           memset (argBuf, 0, bufLen);
3665           if (strcmp (argv[1], "Q") == 0)
3666             sprintf (argBuf, "%s %s", argv[0], "noprint");
3667           else
3668             {
3669               if (strcmp (argv[1], "s") == 0)
3670                 {
3671                   if (!signal_stop[oursig])
3672                     sprintf (argBuf, "%s %s", argv[0], "stop");
3673                   else
3674                     sprintf (argBuf, "%s %s", argv[0], "nostop");
3675                 }
3676               else if (strcmp (argv[1], "i") == 0)
3677                 {
3678                   if (!signal_program[oursig])
3679                     sprintf (argBuf, "%s %s", argv[0], "pass");
3680                   else
3681                     sprintf (argBuf, "%s %s", argv[0], "nopass");
3682                 }
3683               else if (strcmp (argv[1], "r") == 0)
3684                 {
3685                   if (!signal_print[oursig])
3686                     sprintf (argBuf, "%s %s", argv[0], "print");
3687                   else
3688                     sprintf (argBuf, "%s %s", argv[0], "noprint");
3689                 }
3690               else
3691                 validFlag = 0;
3692             }
3693           if (validFlag)
3694             handle_command (argBuf, from_tty);
3695           else
3696             printf_filtered ("Invalid signal handling flag.\n");
3697           if (argBuf)
3698             xfree (argBuf);
3699         }
3700     }
3701   do_cleanups (old_chain);
3702 }
3703
3704 /* Print current contents of the tables set by the handle command.
3705    It is possible we should just be printing signals actually used
3706    by the current target (but for things to work right when switching
3707    targets, all signals should be in the signal tables).  */
3708
3709 static void
3710 signals_info (char *signum_exp, int from_tty)
3711 {
3712   enum target_signal oursig;
3713   sig_print_header ();
3714
3715   if (signum_exp)
3716     {
3717       /* First see if this is a symbol name.  */
3718       oursig = target_signal_from_name (signum_exp);
3719       if (oursig == TARGET_SIGNAL_UNKNOWN)
3720         {
3721           /* No, try numeric.  */
3722           oursig =
3723             target_signal_from_command (parse_and_eval_long (signum_exp));
3724         }
3725       sig_print_info (oursig);
3726       return;
3727     }
3728
3729   printf_filtered ("\n");
3730   /* These ugly casts brought to you by the native VAX compiler.  */
3731   for (oursig = TARGET_SIGNAL_FIRST;
3732        (int) oursig < (int) TARGET_SIGNAL_LAST;
3733        oursig = (enum target_signal) ((int) oursig + 1))
3734     {
3735       QUIT;
3736
3737       if (oursig != TARGET_SIGNAL_UNKNOWN
3738           && oursig != TARGET_SIGNAL_DEFAULT && oursig != TARGET_SIGNAL_0)
3739         sig_print_info (oursig);
3740     }
3741
3742   printf_filtered ("\nUse the \"handle\" command to change these tables.\n");
3743 }
3744 \f
3745 struct inferior_status
3746 {
3747   enum target_signal stop_signal;
3748   CORE_ADDR stop_pc;
3749   bpstat stop_bpstat;
3750   int stop_step;
3751   int stop_stack_dummy;
3752   int stopped_by_random_signal;
3753   int trap_expected;
3754   CORE_ADDR step_range_start;
3755   CORE_ADDR step_range_end;
3756   struct frame_id step_frame_id;
3757   enum step_over_calls_kind step_over_calls;
3758   CORE_ADDR step_resume_break_address;
3759   int stop_after_trap;
3760   int stop_soon;
3761   struct regcache *stop_registers;
3762
3763   /* These are here because if call_function_by_hand has written some
3764      registers and then decides to call error(), we better not have changed
3765      any registers.  */
3766   struct regcache *registers;
3767
3768   /* A frame unique identifier.  */
3769   struct frame_id selected_frame_id;
3770
3771   int breakpoint_proceeded;
3772   int restore_stack_info;
3773   int proceed_to_finish;
3774 };
3775
3776 void
3777 write_inferior_status_register (struct inferior_status *inf_status, int regno,
3778                                 LONGEST val)
3779 {
3780   int size = DEPRECATED_REGISTER_RAW_SIZE (regno);
3781   void *buf = alloca (size);
3782   store_signed_integer (buf, size, val);
3783   regcache_raw_write (inf_status->registers, regno, buf);
3784 }
3785
3786 /* Save all of the information associated with the inferior<==>gdb
3787    connection.  INF_STATUS is a pointer to a "struct inferior_status"
3788    (defined in inferior.h).  */
3789
3790 struct inferior_status *
3791 save_inferior_status (int restore_stack_info)
3792 {
3793   struct inferior_status *inf_status = XMALLOC (struct inferior_status);
3794
3795   inf_status->stop_signal = stop_signal;
3796   inf_status->stop_pc = stop_pc;
3797   inf_status->stop_step = stop_step;
3798   inf_status->stop_stack_dummy = stop_stack_dummy;
3799   inf_status->stopped_by_random_signal = stopped_by_random_signal;
3800   inf_status->trap_expected = trap_expected;
3801   inf_status->step_range_start = step_range_start;
3802   inf_status->step_range_end = step_range_end;
3803   inf_status->step_frame_id = step_frame_id;
3804   inf_status->step_over_calls = step_over_calls;
3805   inf_status->stop_after_trap = stop_after_trap;
3806   inf_status->stop_soon = stop_soon;
3807   /* Save original bpstat chain here; replace it with copy of chain.
3808      If caller's caller is walking the chain, they'll be happier if we
3809      hand them back the original chain when restore_inferior_status is
3810      called.  */
3811   inf_status->stop_bpstat = stop_bpstat;
3812   stop_bpstat = bpstat_copy (stop_bpstat);
3813   inf_status->breakpoint_proceeded = breakpoint_proceeded;
3814   inf_status->restore_stack_info = restore_stack_info;
3815   inf_status->proceed_to_finish = proceed_to_finish;
3816
3817   inf_status->stop_registers = regcache_dup_no_passthrough (stop_registers);
3818
3819   inf_status->registers = regcache_dup (current_regcache);
3820
3821   inf_status->selected_frame_id = get_frame_id (deprecated_selected_frame);
3822   return inf_status;
3823 }
3824
3825 static int
3826 restore_selected_frame (void *args)
3827 {
3828   struct frame_id *fid = (struct frame_id *) args;
3829   struct frame_info *frame;
3830
3831   frame = frame_find_by_id (*fid);
3832
3833   /* If inf_status->selected_frame_id is NULL, there was no previously
3834      selected frame.  */
3835   if (frame == NULL)
3836     {
3837       warning ("Unable to restore previously selected frame.\n");
3838       return 0;
3839     }
3840
3841   select_frame (frame);
3842
3843   return (1);
3844 }
3845
3846 void
3847 restore_inferior_status (struct inferior_status *inf_status)
3848 {
3849   stop_signal = inf_status->stop_signal;
3850   stop_pc = inf_status->stop_pc;
3851   stop_step = inf_status->stop_step;
3852   stop_stack_dummy = inf_status->stop_stack_dummy;
3853   stopped_by_random_signal = inf_status->stopped_by_random_signal;
3854   trap_expected = inf_status->trap_expected;
3855   step_range_start = inf_status->step_range_start;
3856   step_range_end = inf_status->step_range_end;
3857   step_frame_id = inf_status->step_frame_id;
3858   step_over_calls = inf_status->step_over_calls;
3859   stop_after_trap = inf_status->stop_after_trap;
3860   stop_soon = inf_status->stop_soon;
3861   bpstat_clear (&stop_bpstat);
3862   stop_bpstat = inf_status->stop_bpstat;
3863   breakpoint_proceeded = inf_status->breakpoint_proceeded;
3864   proceed_to_finish = inf_status->proceed_to_finish;
3865
3866   /* FIXME: Is the restore of stop_registers always needed. */
3867   regcache_xfree (stop_registers);
3868   stop_registers = inf_status->stop_registers;
3869
3870   /* The inferior can be gone if the user types "print exit(0)"
3871      (and perhaps other times).  */
3872   if (target_has_execution)
3873     /* NB: The register write goes through to the target.  */
3874     regcache_cpy (current_regcache, inf_status->registers);
3875   regcache_xfree (inf_status->registers);
3876
3877   /* FIXME: If we are being called after stopping in a function which
3878      is called from gdb, we should not be trying to restore the
3879      selected frame; it just prints a spurious error message (The
3880      message is useful, however, in detecting bugs in gdb (like if gdb
3881      clobbers the stack)).  In fact, should we be restoring the
3882      inferior status at all in that case?  .  */
3883
3884   if (target_has_stack && inf_status->restore_stack_info)
3885     {
3886       /* The point of catch_errors is that if the stack is clobbered,
3887          walking the stack might encounter a garbage pointer and
3888          error() trying to dereference it.  */
3889       if (catch_errors
3890           (restore_selected_frame, &inf_status->selected_frame_id,
3891            "Unable to restore previously selected frame:\n",
3892            RETURN_MASK_ERROR) == 0)
3893         /* Error in restoring the selected frame.  Select the innermost
3894            frame.  */
3895         select_frame (get_current_frame ());
3896
3897     }
3898
3899   xfree (inf_status);
3900 }
3901
3902 static void
3903 do_restore_inferior_status_cleanup (void *sts)
3904 {
3905   restore_inferior_status (sts);
3906 }
3907
3908 struct cleanup *
3909 make_cleanup_restore_inferior_status (struct inferior_status *inf_status)
3910 {
3911   return make_cleanup (do_restore_inferior_status_cleanup, inf_status);
3912 }
3913
3914 void
3915 discard_inferior_status (struct inferior_status *inf_status)
3916 {
3917   /* See save_inferior_status for info on stop_bpstat. */
3918   bpstat_clear (&inf_status->stop_bpstat);
3919   regcache_xfree (inf_status->registers);
3920   regcache_xfree (inf_status->stop_registers);
3921   xfree (inf_status);
3922 }
3923
3924 int
3925 inferior_has_forked (int pid, int *child_pid)
3926 {
3927   struct target_waitstatus last;
3928   ptid_t last_ptid;
3929
3930   get_last_target_status (&last_ptid, &last);
3931
3932   if (last.kind != TARGET_WAITKIND_FORKED)
3933     return 0;
3934
3935   if (ptid_get_pid (last_ptid) != pid)
3936     return 0;
3937
3938   *child_pid = last.value.related_pid;
3939   return 1;
3940 }
3941
3942 int
3943 inferior_has_vforked (int pid, int *child_pid)
3944 {
3945   struct target_waitstatus last;
3946   ptid_t last_ptid;
3947
3948   get_last_target_status (&last_ptid, &last);
3949
3950   if (last.kind != TARGET_WAITKIND_VFORKED)
3951     return 0;
3952
3953   if (ptid_get_pid (last_ptid) != pid)
3954     return 0;
3955
3956   *child_pid = last.value.related_pid;
3957   return 1;
3958 }
3959
3960 int
3961 inferior_has_execd (int pid, char **execd_pathname)
3962 {
3963   struct target_waitstatus last;
3964   ptid_t last_ptid;
3965
3966   get_last_target_status (&last_ptid, &last);
3967
3968   if (last.kind != TARGET_WAITKIND_EXECD)
3969     return 0;
3970
3971   if (ptid_get_pid (last_ptid) != pid)
3972     return 0;
3973
3974   *execd_pathname = xstrdup (last.value.execd_pathname);
3975   return 1;
3976 }
3977
3978 /* Oft used ptids */
3979 ptid_t null_ptid;
3980 ptid_t minus_one_ptid;
3981
3982 /* Create a ptid given the necessary PID, LWP, and TID components.  */
3983
3984 ptid_t
3985 ptid_build (int pid, long lwp, long tid)
3986 {
3987   ptid_t ptid;
3988
3989   ptid.pid = pid;
3990   ptid.lwp = lwp;
3991   ptid.tid = tid;
3992   return ptid;
3993 }
3994
3995 /* Create a ptid from just a pid.  */
3996
3997 ptid_t
3998 pid_to_ptid (int pid)
3999 {
4000   return ptid_build (pid, 0, 0);
4001 }
4002
4003 /* Fetch the pid (process id) component from a ptid.  */
4004
4005 int
4006 ptid_get_pid (ptid_t ptid)
4007 {
4008   return ptid.pid;
4009 }
4010
4011 /* Fetch the lwp (lightweight process) component from a ptid.  */
4012
4013 long
4014 ptid_get_lwp (ptid_t ptid)
4015 {
4016   return ptid.lwp;
4017 }
4018
4019 /* Fetch the tid (thread id) component from a ptid.  */
4020
4021 long
4022 ptid_get_tid (ptid_t ptid)
4023 {
4024   return ptid.tid;
4025 }
4026
4027 /* ptid_equal() is used to test equality of two ptids.  */
4028
4029 int
4030 ptid_equal (ptid_t ptid1, ptid_t ptid2)
4031 {
4032   return (ptid1.pid == ptid2.pid && ptid1.lwp == ptid2.lwp
4033           && ptid1.tid == ptid2.tid);
4034 }
4035
4036 /* restore_inferior_ptid() will be used by the cleanup machinery
4037    to restore the inferior_ptid value saved in a call to
4038    save_inferior_ptid().  */
4039
4040 static void
4041 restore_inferior_ptid (void *arg)
4042 {
4043   ptid_t *saved_ptid_ptr = arg;
4044   inferior_ptid = *saved_ptid_ptr;
4045   xfree (arg);
4046 }
4047
4048 /* Save the value of inferior_ptid so that it may be restored by a
4049    later call to do_cleanups().  Returns the struct cleanup pointer
4050    needed for later doing the cleanup.  */
4051
4052 struct cleanup *
4053 save_inferior_ptid (void)
4054 {
4055   ptid_t *saved_ptid_ptr;
4056
4057   saved_ptid_ptr = xmalloc (sizeof (ptid_t));
4058   *saved_ptid_ptr = inferior_ptid;
4059   return make_cleanup (restore_inferior_ptid, saved_ptid_ptr);
4060 }
4061 \f
4062
4063 static void
4064 build_infrun (void)
4065 {
4066   stop_registers = regcache_xmalloc (current_gdbarch);
4067 }
4068
4069 void
4070 _initialize_infrun (void)
4071 {
4072   int i;
4073   int numsigs;
4074   struct cmd_list_element *c;
4075
4076   DEPRECATED_REGISTER_GDBARCH_SWAP (stop_registers);
4077   deprecated_register_gdbarch_swap (NULL, 0, build_infrun);
4078
4079   add_info ("signals", signals_info,
4080             "What debugger does when program gets various signals.\n\
4081 Specify a signal as argument to print info on that signal only.");
4082   add_info_alias ("handle", "signals", 0);
4083
4084   add_com ("handle", class_run, handle_command,
4085            concat ("Specify how to handle a signal.\n\
4086 Args are signals and actions to apply to those signals.\n\
4087 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
4088 from 1-15 are allowed for compatibility with old versions of GDB.\n\
4089 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
4090 The special arg \"all\" is recognized to mean all signals except those\n\
4091 used by the debugger, typically SIGTRAP and SIGINT.\n", "Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
4092 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
4093 Stop means reenter debugger if this signal happens (implies print).\n\
4094 Print means print a message if this signal happens.\n\
4095 Pass means let program see this signal; otherwise program doesn't know.\n\
4096 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
4097 Pass and Stop may be combined.", NULL));
4098   if (xdb_commands)
4099     {
4100       add_com ("lz", class_info, signals_info,
4101                "What debugger does when program gets various signals.\n\
4102 Specify a signal as argument to print info on that signal only.");
4103       add_com ("z", class_run, xdb_handle_command,
4104                concat ("Specify how to handle a signal.\n\
4105 Args are signals and actions to apply to those signals.\n\
4106 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
4107 from 1-15 are allowed for compatibility with old versions of GDB.\n\
4108 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
4109 The special arg \"all\" is recognized to mean all signals except those\n\
4110 used by the debugger, typically SIGTRAP and SIGINT.\n", "Recognized actions include \"s\" (toggles between stop and nostop), \n\
4111 \"r\" (toggles between print and noprint), \"i\" (toggles between pass and \
4112 nopass), \"Q\" (noprint)\n\
4113 Stop means reenter debugger if this signal happens (implies print).\n\
4114 Print means print a message if this signal happens.\n\
4115 Pass means let program see this signal; otherwise program doesn't know.\n\
4116 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
4117 Pass and Stop may be combined.", NULL));
4118     }
4119
4120   if (!dbx_commands)
4121     stop_command =
4122       add_cmd ("stop", class_obscure, not_just_help_class_command, "There is no `stop' command, but you can set a hook on `stop'.\n\
4123 This allows you to set a list of commands to be run each time execution\n\
4124 of the program stops.", &cmdlist);
4125
4126   numsigs = (int) TARGET_SIGNAL_LAST;
4127   signal_stop = (unsigned char *) xmalloc (sizeof (signal_stop[0]) * numsigs);
4128   signal_print = (unsigned char *)
4129     xmalloc (sizeof (signal_print[0]) * numsigs);
4130   signal_program = (unsigned char *)
4131     xmalloc (sizeof (signal_program[0]) * numsigs);
4132   for (i = 0; i < numsigs; i++)
4133     {
4134       signal_stop[i] = 1;
4135       signal_print[i] = 1;
4136       signal_program[i] = 1;
4137     }
4138
4139   /* Signals caused by debugger's own actions
4140      should not be given to the program afterwards.  */
4141   signal_program[TARGET_SIGNAL_TRAP] = 0;
4142   signal_program[TARGET_SIGNAL_INT] = 0;
4143
4144   /* Signals that are not errors should not normally enter the debugger.  */
4145   signal_stop[TARGET_SIGNAL_ALRM] = 0;
4146   signal_print[TARGET_SIGNAL_ALRM] = 0;
4147   signal_stop[TARGET_SIGNAL_VTALRM] = 0;
4148   signal_print[TARGET_SIGNAL_VTALRM] = 0;
4149   signal_stop[TARGET_SIGNAL_PROF] = 0;
4150   signal_print[TARGET_SIGNAL_PROF] = 0;
4151   signal_stop[TARGET_SIGNAL_CHLD] = 0;
4152   signal_print[TARGET_SIGNAL_CHLD] = 0;
4153   signal_stop[TARGET_SIGNAL_IO] = 0;
4154   signal_print[TARGET_SIGNAL_IO] = 0;
4155   signal_stop[TARGET_SIGNAL_POLL] = 0;
4156   signal_print[TARGET_SIGNAL_POLL] = 0;
4157   signal_stop[TARGET_SIGNAL_URG] = 0;
4158   signal_print[TARGET_SIGNAL_URG] = 0;
4159   signal_stop[TARGET_SIGNAL_WINCH] = 0;
4160   signal_print[TARGET_SIGNAL_WINCH] = 0;
4161
4162   /* These signals are used internally by user-level thread
4163      implementations.  (See signal(5) on Solaris.)  Like the above
4164      signals, a healthy program receives and handles them as part of
4165      its normal operation.  */
4166   signal_stop[TARGET_SIGNAL_LWP] = 0;
4167   signal_print[TARGET_SIGNAL_LWP] = 0;
4168   signal_stop[TARGET_SIGNAL_WAITING] = 0;
4169   signal_print[TARGET_SIGNAL_WAITING] = 0;
4170   signal_stop[TARGET_SIGNAL_CANCEL] = 0;
4171   signal_print[TARGET_SIGNAL_CANCEL] = 0;
4172
4173 #ifdef SOLIB_ADD
4174   add_show_from_set
4175     (add_set_cmd ("stop-on-solib-events", class_support, var_zinteger,
4176                   (char *) &stop_on_solib_events,
4177                   "Set stopping for shared library events.\n\
4178 If nonzero, gdb will give control to the user when the dynamic linker\n\
4179 notifies gdb of shared library events.  The most common event of interest\n\
4180 to the user would be loading/unloading of a new library.\n", &setlist), &showlist);
4181 #endif
4182
4183   c = add_set_enum_cmd ("follow-fork-mode",
4184                         class_run,
4185                         follow_fork_mode_kind_names, &follow_fork_mode_string,
4186                         "Set debugger response to a program call of fork \
4187 or vfork.\n\
4188 A fork or vfork creates a new process.  follow-fork-mode can be:\n\
4189   parent  - the original process is debugged after a fork\n\
4190   child   - the new process is debugged after a fork\n\
4191 The unfollowed process will continue to run.\n\
4192 By default, the debugger will follow the parent process.", &setlist);
4193   add_show_from_set (c, &showlist);
4194
4195   c = add_set_enum_cmd ("scheduler-locking", class_run, scheduler_enums,        /* array of string names */
4196                         &scheduler_mode,        /* current mode  */
4197                         "Set mode for locking scheduler during execution.\n\
4198 off  == no locking (threads may preempt at any time)\n\
4199 on   == full locking (no thread except the current thread may run)\n\
4200 step == scheduler locked during every single-step operation.\n\
4201         In this mode, no other thread may run during a step command.\n\
4202         Other threads may run while stepping over a function call ('next').", &setlist);
4203
4204   set_cmd_sfunc (c, set_schedlock_func);        /* traps on target vector */
4205   add_show_from_set (c, &showlist);
4206
4207   c = add_set_cmd ("step-mode", class_run,
4208                    var_boolean, (char *) &step_stop_if_no_debug,
4209                    "Set mode of the step operation. When set, doing a step over a\n\
4210 function without debug line information will stop at the first\n\
4211 instruction of that function. Otherwise, the function is skipped and\n\
4212 the step command stops at a different source line.", &setlist);
4213   add_show_from_set (c, &showlist);
4214
4215   /* ptid initializations */
4216   null_ptid = ptid_build (0, 0, 0);
4217   minus_one_ptid = ptid_build (-1, 0, 0);
4218   inferior_ptid = null_ptid;
4219   target_last_wait_ptid = minus_one_ptid;
4220 }