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