Reimplement shared library support on ppc-aix...
[external/binutils.git] / gdb / infrun.c
1 /* Target-struct-independent code to start (run) and stop an inferior
2    process.
3
4    Copyright (C) 1986-2013 Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "gdb_string.h"
23 #include <ctype.h>
24 #include "symtab.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "exceptions.h"
28 #include "breakpoint.h"
29 #include "gdb_wait.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "cli/cli-script.h"
33 #include "target.h"
34 #include "gdbthread.h"
35 #include "annotate.h"
36 #include "symfile.h"
37 #include "top.h"
38 #include <signal.h>
39 #include "inf-loop.h"
40 #include "regcache.h"
41 #include "value.h"
42 #include "observer.h"
43 #include "language.h"
44 #include "solib.h"
45 #include "main.h"
46 #include "dictionary.h"
47 #include "block.h"
48 #include "gdb_assert.h"
49 #include "mi/mi-common.h"
50 #include "event-top.h"
51 #include "record.h"
52 #include "record-full.h"
53 #include "inline-frame.h"
54 #include "jit.h"
55 #include "tracepoint.h"
56 #include "continuations.h"
57 #include "interps.h"
58 #include "skip.h"
59 #include "probe.h"
60 #include "objfiles.h"
61 #include "completer.h"
62 #include "target-descriptions.h"
63
64 /* Prototypes for local functions */
65
66 static void signals_info (char *, int);
67
68 static void handle_command (char *, int);
69
70 static void sig_print_info (enum gdb_signal);
71
72 static void sig_print_header (void);
73
74 static void resume_cleanups (void *);
75
76 static int hook_stop_stub (void *);
77
78 static int restore_selected_frame (void *);
79
80 static int follow_fork (void);
81
82 static void set_schedlock_func (char *args, int from_tty,
83                                 struct cmd_list_element *c);
84
85 static int currently_stepping (struct thread_info *tp);
86
87 static int currently_stepping_or_nexting_callback (struct thread_info *tp,
88                                                    void *data);
89
90 static void xdb_handle_command (char *args, int from_tty);
91
92 static int prepare_to_proceed (int);
93
94 static void print_exited_reason (int exitstatus);
95
96 static void print_signal_exited_reason (enum gdb_signal siggnal);
97
98 static void print_no_history_reason (void);
99
100 static void print_signal_received_reason (enum gdb_signal siggnal);
101
102 static void print_end_stepping_range_reason (void);
103
104 void _initialize_infrun (void);
105
106 void nullify_last_target_wait_ptid (void);
107
108 static void insert_hp_step_resume_breakpoint_at_frame (struct frame_info *);
109
110 static void insert_step_resume_breakpoint_at_caller (struct frame_info *);
111
112 static void insert_longjmp_resume_breakpoint (struct gdbarch *, CORE_ADDR);
113
114 /* When set, stop the 'step' command if we enter a function which has
115    no line number information.  The normal behavior is that we step
116    over such function.  */
117 int step_stop_if_no_debug = 0;
118 static void
119 show_step_stop_if_no_debug (struct ui_file *file, int from_tty,
120                             struct cmd_list_element *c, const char *value)
121 {
122   fprintf_filtered (file, _("Mode of the step operation is %s.\n"), value);
123 }
124
125 /* In asynchronous mode, but simulating synchronous execution.  */
126
127 int sync_execution = 0;
128
129 /* wait_for_inferior and normal_stop use this to notify the user
130    when the inferior stopped in a different thread than it had been
131    running in.  */
132
133 static ptid_t previous_inferior_ptid;
134
135 /* Default behavior is to detach newly forked processes (legacy).  */
136 int detach_fork = 1;
137
138 int debug_displaced = 0;
139 static void
140 show_debug_displaced (struct ui_file *file, int from_tty,
141                       struct cmd_list_element *c, const char *value)
142 {
143   fprintf_filtered (file, _("Displace stepping debugging is %s.\n"), value);
144 }
145
146 unsigned int debug_infrun = 0;
147 static void
148 show_debug_infrun (struct ui_file *file, int from_tty,
149                    struct cmd_list_element *c, const char *value)
150 {
151   fprintf_filtered (file, _("Inferior debugging is %s.\n"), value);
152 }
153
154
155 /* Support for disabling address space randomization.  */
156
157 int disable_randomization = 1;
158
159 static void
160 show_disable_randomization (struct ui_file *file, int from_tty,
161                             struct cmd_list_element *c, const char *value)
162 {
163   if (target_supports_disable_randomization ())
164     fprintf_filtered (file,
165                       _("Disabling randomization of debuggee's "
166                         "virtual address space is %s.\n"),
167                       value);
168   else
169     fputs_filtered (_("Disabling randomization of debuggee's "
170                       "virtual address space is unsupported on\n"
171                       "this platform.\n"), file);
172 }
173
174 static void
175 set_disable_randomization (char *args, int from_tty,
176                            struct cmd_list_element *c)
177 {
178   if (!target_supports_disable_randomization ())
179     error (_("Disabling randomization of debuggee's "
180              "virtual address space is unsupported on\n"
181              "this platform."));
182 }
183
184
185 /* If the program uses ELF-style shared libraries, then calls to
186    functions in shared libraries go through stubs, which live in a
187    table called the PLT (Procedure Linkage Table).  The first time the
188    function is called, the stub sends control to the dynamic linker,
189    which looks up the function's real address, patches the stub so
190    that future calls will go directly to the function, and then passes
191    control to the function.
192
193    If we are stepping at the source level, we don't want to see any of
194    this --- we just want to skip over the stub and the dynamic linker.
195    The simple approach is to single-step until control leaves the
196    dynamic linker.
197
198    However, on some systems (e.g., Red Hat's 5.2 distribution) the
199    dynamic linker calls functions in the shared C library, so you
200    can't tell from the PC alone whether the dynamic linker is still
201    running.  In this case, we use a step-resume breakpoint to get us
202    past the dynamic linker, as if we were using "next" to step over a
203    function call.
204
205    in_solib_dynsym_resolve_code() says whether we're in the dynamic
206    linker code or not.  Normally, this means we single-step.  However,
207    if SKIP_SOLIB_RESOLVER then returns non-zero, then its value is an
208    address where we can place a step-resume breakpoint to get past the
209    linker's symbol resolution function.
210
211    in_solib_dynsym_resolve_code() can generally be implemented in a
212    pretty portable way, by comparing the PC against the address ranges
213    of the dynamic linker's sections.
214
215    SKIP_SOLIB_RESOLVER is generally going to be system-specific, since
216    it depends on internal details of the dynamic linker.  It's usually
217    not too hard to figure out where to put a breakpoint, but it
218    certainly isn't portable.  SKIP_SOLIB_RESOLVER should do plenty of
219    sanity checking.  If it can't figure things out, returning zero and
220    getting the (possibly confusing) stepping behavior is better than
221    signalling an error, which will obscure the change in the
222    inferior's state.  */
223
224 /* This function returns TRUE if pc is the address of an instruction
225    that lies within the dynamic linker (such as the event hook, or the
226    dld itself).
227
228    This function must be used only when a dynamic linker event has
229    been caught, and the inferior is being stepped out of the hook, or
230    undefined results are guaranteed.  */
231
232 #ifndef SOLIB_IN_DYNAMIC_LINKER
233 #define SOLIB_IN_DYNAMIC_LINKER(pid,pc) 0
234 #endif
235
236 /* "Observer mode" is somewhat like a more extreme version of
237    non-stop, in which all GDB operations that might affect the
238    target's execution have been disabled.  */
239
240 static int non_stop_1 = 0;
241
242 int observer_mode = 0;
243 static int observer_mode_1 = 0;
244
245 static void
246 set_observer_mode (char *args, int from_tty,
247                    struct cmd_list_element *c)
248 {
249   extern int pagination_enabled;
250
251   if (target_has_execution)
252     {
253       observer_mode_1 = observer_mode;
254       error (_("Cannot change this setting while the inferior is running."));
255     }
256
257   observer_mode = observer_mode_1;
258
259   may_write_registers = !observer_mode;
260   may_write_memory = !observer_mode;
261   may_insert_breakpoints = !observer_mode;
262   may_insert_tracepoints = !observer_mode;
263   /* We can insert fast tracepoints in or out of observer mode,
264      but enable them if we're going into this mode.  */
265   if (observer_mode)
266     may_insert_fast_tracepoints = 1;
267   may_stop = !observer_mode;
268   update_target_permissions ();
269
270   /* Going *into* observer mode we must force non-stop, then
271      going out we leave it that way.  */
272   if (observer_mode)
273     {
274       target_async_permitted = 1;
275       pagination_enabled = 0;
276       non_stop = non_stop_1 = 1;
277     }
278
279   if (from_tty)
280     printf_filtered (_("Observer mode is now %s.\n"),
281                      (observer_mode ? "on" : "off"));
282 }
283
284 static void
285 show_observer_mode (struct ui_file *file, int from_tty,
286                     struct cmd_list_element *c, const char *value)
287 {
288   fprintf_filtered (file, _("Observer mode is %s.\n"), value);
289 }
290
291 /* This updates the value of observer mode based on changes in
292    permissions.  Note that we are deliberately ignoring the values of
293    may-write-registers and may-write-memory, since the user may have
294    reason to enable these during a session, for instance to turn on a
295    debugging-related global.  */
296
297 void
298 update_observer_mode (void)
299 {
300   int newval;
301
302   newval = (!may_insert_breakpoints
303             && !may_insert_tracepoints
304             && may_insert_fast_tracepoints
305             && !may_stop
306             && non_stop);
307
308   /* Let the user know if things change.  */
309   if (newval != observer_mode)
310     printf_filtered (_("Observer mode is now %s.\n"),
311                      (newval ? "on" : "off"));
312
313   observer_mode = observer_mode_1 = newval;
314 }
315
316 /* Tables of how to react to signals; the user sets them.  */
317
318 static unsigned char *signal_stop;
319 static unsigned char *signal_print;
320 static unsigned char *signal_program;
321
322 /* Table of signals that are registered with "catch signal".  A
323    non-zero entry indicates that the signal is caught by some "catch
324    signal" command.  This has size GDB_SIGNAL_LAST, to accommodate all
325    signals.  */
326 static unsigned char *signal_catch;
327
328 /* Table of signals that the target may silently handle.
329    This is automatically determined from the flags above,
330    and simply cached here.  */
331 static unsigned char *signal_pass;
332
333 #define SET_SIGS(nsigs,sigs,flags) \
334   do { \
335     int signum = (nsigs); \
336     while (signum-- > 0) \
337       if ((sigs)[signum]) \
338         (flags)[signum] = 1; \
339   } while (0)
340
341 #define UNSET_SIGS(nsigs,sigs,flags) \
342   do { \
343     int signum = (nsigs); \
344     while (signum-- > 0) \
345       if ((sigs)[signum]) \
346         (flags)[signum] = 0; \
347   } while (0)
348
349 /* Update the target's copy of SIGNAL_PROGRAM.  The sole purpose of
350    this function is to avoid exporting `signal_program'.  */
351
352 void
353 update_signals_program_target (void)
354 {
355   target_program_signals ((int) GDB_SIGNAL_LAST, signal_program);
356 }
357
358 /* Value to pass to target_resume() to cause all threads to resume.  */
359
360 #define RESUME_ALL minus_one_ptid
361
362 /* Command list pointer for the "stop" placeholder.  */
363
364 static struct cmd_list_element *stop_command;
365
366 /* Function inferior was in as of last step command.  */
367
368 static struct symbol *step_start_function;
369
370 /* Nonzero if we want to give control to the user when we're notified
371    of shared library events by the dynamic linker.  */
372 int stop_on_solib_events;
373 static void
374 show_stop_on_solib_events (struct ui_file *file, int from_tty,
375                            struct cmd_list_element *c, const char *value)
376 {
377   fprintf_filtered (file, _("Stopping for shared library events is %s.\n"),
378                     value);
379 }
380
381 /* Nonzero means expecting a trace trap
382    and should stop the inferior and return silently when it happens.  */
383
384 int stop_after_trap;
385
386 /* Save register contents here when executing a "finish" command or are
387    about to pop a stack dummy frame, if-and-only-if proceed_to_finish is set.
388    Thus this contains the return value from the called function (assuming
389    values are returned in a register).  */
390
391 struct regcache *stop_registers;
392
393 /* Nonzero after stop if current stack frame should be printed.  */
394
395 static int stop_print_frame;
396
397 /* This is a cached copy of the pid/waitstatus of the last event
398    returned by target_wait()/deprecated_target_wait_hook().  This
399    information is returned by get_last_target_status().  */
400 static ptid_t target_last_wait_ptid;
401 static struct target_waitstatus target_last_waitstatus;
402
403 static void context_switch (ptid_t ptid);
404
405 void init_thread_stepping_state (struct thread_info *tss);
406
407 static void init_infwait_state (void);
408
409 static const char follow_fork_mode_child[] = "child";
410 static const char follow_fork_mode_parent[] = "parent";
411
412 static const char *const follow_fork_mode_kind_names[] = {
413   follow_fork_mode_child,
414   follow_fork_mode_parent,
415   NULL
416 };
417
418 static const char *follow_fork_mode_string = follow_fork_mode_parent;
419 static void
420 show_follow_fork_mode_string (struct ui_file *file, int from_tty,
421                               struct cmd_list_element *c, const char *value)
422 {
423   fprintf_filtered (file,
424                     _("Debugger response to a program "
425                       "call of fork or vfork is \"%s\".\n"),
426                     value);
427 }
428 \f
429
430 /* Tell the target to follow the fork we're stopped at.  Returns true
431    if the inferior should be resumed; false, if the target for some
432    reason decided it's best not to resume.  */
433
434 static int
435 follow_fork (void)
436 {
437   int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
438   int should_resume = 1;
439   struct thread_info *tp;
440
441   /* Copy user stepping state to the new inferior thread.  FIXME: the
442      followed fork child thread should have a copy of most of the
443      parent thread structure's run control related fields, not just these.
444      Initialized to avoid "may be used uninitialized" warnings from gcc.  */
445   struct breakpoint *step_resume_breakpoint = NULL;
446   struct breakpoint *exception_resume_breakpoint = NULL;
447   CORE_ADDR step_range_start = 0;
448   CORE_ADDR step_range_end = 0;
449   struct frame_id step_frame_id = { 0 };
450
451   if (!non_stop)
452     {
453       ptid_t wait_ptid;
454       struct target_waitstatus wait_status;
455
456       /* Get the last target status returned by target_wait().  */
457       get_last_target_status (&wait_ptid, &wait_status);
458
459       /* If not stopped at a fork event, then there's nothing else to
460          do.  */
461       if (wait_status.kind != TARGET_WAITKIND_FORKED
462           && wait_status.kind != TARGET_WAITKIND_VFORKED)
463         return 1;
464
465       /* Check if we switched over from WAIT_PTID, since the event was
466          reported.  */
467       if (!ptid_equal (wait_ptid, minus_one_ptid)
468           && !ptid_equal (inferior_ptid, wait_ptid))
469         {
470           /* We did.  Switch back to WAIT_PTID thread, to tell the
471              target to follow it (in either direction).  We'll
472              afterwards refuse to resume, and inform the user what
473              happened.  */
474           switch_to_thread (wait_ptid);
475           should_resume = 0;
476         }
477     }
478
479   tp = inferior_thread ();
480
481   /* If there were any forks/vforks that were caught and are now to be
482      followed, then do so now.  */
483   switch (tp->pending_follow.kind)
484     {
485     case TARGET_WAITKIND_FORKED:
486     case TARGET_WAITKIND_VFORKED:
487       {
488         ptid_t parent, child;
489
490         /* If the user did a next/step, etc, over a fork call,
491            preserve the stepping state in the fork child.  */
492         if (follow_child && should_resume)
493           {
494             step_resume_breakpoint = clone_momentary_breakpoint
495                                          (tp->control.step_resume_breakpoint);
496             step_range_start = tp->control.step_range_start;
497             step_range_end = tp->control.step_range_end;
498             step_frame_id = tp->control.step_frame_id;
499             exception_resume_breakpoint
500               = clone_momentary_breakpoint (tp->control.exception_resume_breakpoint);
501
502             /* For now, delete the parent's sr breakpoint, otherwise,
503                parent/child sr breakpoints are considered duplicates,
504                and the child version will not be installed.  Remove
505                this when the breakpoints module becomes aware of
506                inferiors and address spaces.  */
507             delete_step_resume_breakpoint (tp);
508             tp->control.step_range_start = 0;
509             tp->control.step_range_end = 0;
510             tp->control.step_frame_id = null_frame_id;
511             delete_exception_resume_breakpoint (tp);
512           }
513
514         parent = inferior_ptid;
515         child = tp->pending_follow.value.related_pid;
516
517         /* Tell the target to do whatever is necessary to follow
518            either parent or child.  */
519         if (target_follow_fork (follow_child))
520           {
521             /* Target refused to follow, or there's some other reason
522                we shouldn't resume.  */
523             should_resume = 0;
524           }
525         else
526           {
527             /* This pending follow fork event is now handled, one way
528                or another.  The previous selected thread may be gone
529                from the lists by now, but if it is still around, need
530                to clear the pending follow request.  */
531             tp = find_thread_ptid (parent);
532             if (tp)
533               tp->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
534
535             /* This makes sure we don't try to apply the "Switched
536                over from WAIT_PID" logic above.  */
537             nullify_last_target_wait_ptid ();
538
539             /* If we followed the child, switch to it...  */
540             if (follow_child)
541               {
542                 switch_to_thread (child);
543
544                 /* ... and preserve the stepping state, in case the
545                    user was stepping over the fork call.  */
546                 if (should_resume)
547                   {
548                     tp = inferior_thread ();
549                     tp->control.step_resume_breakpoint
550                       = step_resume_breakpoint;
551                     tp->control.step_range_start = step_range_start;
552                     tp->control.step_range_end = step_range_end;
553                     tp->control.step_frame_id = step_frame_id;
554                     tp->control.exception_resume_breakpoint
555                       = exception_resume_breakpoint;
556                   }
557                 else
558                   {
559                     /* If we get here, it was because we're trying to
560                        resume from a fork catchpoint, but, the user
561                        has switched threads away from the thread that
562                        forked.  In that case, the resume command
563                        issued is most likely not applicable to the
564                        child, so just warn, and refuse to resume.  */
565                     warning (_("Not resuming: switched threads "
566                                "before following fork child.\n"));
567                   }
568
569                 /* Reset breakpoints in the child as appropriate.  */
570                 follow_inferior_reset_breakpoints ();
571               }
572             else
573               switch_to_thread (parent);
574           }
575       }
576       break;
577     case TARGET_WAITKIND_SPURIOUS:
578       /* Nothing to follow.  */
579       break;
580     default:
581       internal_error (__FILE__, __LINE__,
582                       "Unexpected pending_follow.kind %d\n",
583                       tp->pending_follow.kind);
584       break;
585     }
586
587   return should_resume;
588 }
589
590 void
591 follow_inferior_reset_breakpoints (void)
592 {
593   struct thread_info *tp = inferior_thread ();
594
595   /* Was there a step_resume breakpoint?  (There was if the user
596      did a "next" at the fork() call.)  If so, explicitly reset its
597      thread number.
598
599      step_resumes are a form of bp that are made to be per-thread.
600      Since we created the step_resume bp when the parent process
601      was being debugged, and now are switching to the child process,
602      from the breakpoint package's viewpoint, that's a switch of
603      "threads".  We must update the bp's notion of which thread
604      it is for, or it'll be ignored when it triggers.  */
605
606   if (tp->control.step_resume_breakpoint)
607     breakpoint_re_set_thread (tp->control.step_resume_breakpoint);
608
609   if (tp->control.exception_resume_breakpoint)
610     breakpoint_re_set_thread (tp->control.exception_resume_breakpoint);
611
612   /* Reinsert all breakpoints in the child.  The user may have set
613      breakpoints after catching the fork, in which case those
614      were never set in the child, but only in the parent.  This makes
615      sure the inserted breakpoints match the breakpoint list.  */
616
617   breakpoint_re_set ();
618   insert_breakpoints ();
619 }
620
621 /* The child has exited or execed: resume threads of the parent the
622    user wanted to be executing.  */
623
624 static int
625 proceed_after_vfork_done (struct thread_info *thread,
626                           void *arg)
627 {
628   int pid = * (int *) arg;
629
630   if (ptid_get_pid (thread->ptid) == pid
631       && is_running (thread->ptid)
632       && !is_executing (thread->ptid)
633       && !thread->stop_requested
634       && thread->suspend.stop_signal == GDB_SIGNAL_0)
635     {
636       if (debug_infrun)
637         fprintf_unfiltered (gdb_stdlog,
638                             "infrun: resuming vfork parent thread %s\n",
639                             target_pid_to_str (thread->ptid));
640
641       switch_to_thread (thread->ptid);
642       clear_proceed_status ();
643       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT, 0);
644     }
645
646   return 0;
647 }
648
649 /* Called whenever we notice an exec or exit event, to handle
650    detaching or resuming a vfork parent.  */
651
652 static void
653 handle_vfork_child_exec_or_exit (int exec)
654 {
655   struct inferior *inf = current_inferior ();
656
657   if (inf->vfork_parent)
658     {
659       int resume_parent = -1;
660
661       /* This exec or exit marks the end of the shared memory region
662          between the parent and the child.  If the user wanted to
663          detach from the parent, now is the time.  */
664
665       if (inf->vfork_parent->pending_detach)
666         {
667           struct thread_info *tp;
668           struct cleanup *old_chain;
669           struct program_space *pspace;
670           struct address_space *aspace;
671
672           /* follow-fork child, detach-on-fork on.  */
673
674           inf->vfork_parent->pending_detach = 0;
675
676           if (!exec)
677             {
678               /* If we're handling a child exit, then inferior_ptid
679                  points at the inferior's pid, not to a thread.  */
680               old_chain = save_inferior_ptid ();
681               save_current_program_space ();
682               save_current_inferior ();
683             }
684           else
685             old_chain = save_current_space_and_thread ();
686
687           /* We're letting loose of the parent.  */
688           tp = any_live_thread_of_process (inf->vfork_parent->pid);
689           switch_to_thread (tp->ptid);
690
691           /* We're about to detach from the parent, which implicitly
692              removes breakpoints from its address space.  There's a
693              catch here: we want to reuse the spaces for the child,
694              but, parent/child are still sharing the pspace at this
695              point, although the exec in reality makes the kernel give
696              the child a fresh set of new pages.  The problem here is
697              that the breakpoints module being unaware of this, would
698              likely chose the child process to write to the parent
699              address space.  Swapping the child temporarily away from
700              the spaces has the desired effect.  Yes, this is "sort
701              of" a hack.  */
702
703           pspace = inf->pspace;
704           aspace = inf->aspace;
705           inf->aspace = NULL;
706           inf->pspace = NULL;
707
708           if (debug_infrun || info_verbose)
709             {
710               target_terminal_ours ();
711
712               if (exec)
713                 fprintf_filtered (gdb_stdlog,
714                                   "Detaching vfork parent process "
715                                   "%d after child exec.\n",
716                                   inf->vfork_parent->pid);
717               else
718                 fprintf_filtered (gdb_stdlog,
719                                   "Detaching vfork parent process "
720                                   "%d after child exit.\n",
721                                   inf->vfork_parent->pid);
722             }
723
724           target_detach (NULL, 0);
725
726           /* Put it back.  */
727           inf->pspace = pspace;
728           inf->aspace = aspace;
729
730           do_cleanups (old_chain);
731         }
732       else if (exec)
733         {
734           /* We're staying attached to the parent, so, really give the
735              child a new address space.  */
736           inf->pspace = add_program_space (maybe_new_address_space ());
737           inf->aspace = inf->pspace->aspace;
738           inf->removable = 1;
739           set_current_program_space (inf->pspace);
740
741           resume_parent = inf->vfork_parent->pid;
742
743           /* Break the bonds.  */
744           inf->vfork_parent->vfork_child = NULL;
745         }
746       else
747         {
748           struct cleanup *old_chain;
749           struct program_space *pspace;
750
751           /* If this is a vfork child exiting, then the pspace and
752              aspaces were shared with the parent.  Since we're
753              reporting the process exit, we'll be mourning all that is
754              found in the address space, and switching to null_ptid,
755              preparing to start a new inferior.  But, since we don't
756              want to clobber the parent's address/program spaces, we
757              go ahead and create a new one for this exiting
758              inferior.  */
759
760           /* Switch to null_ptid, so that clone_program_space doesn't want
761              to read the selected frame of a dead process.  */
762           old_chain = save_inferior_ptid ();
763           inferior_ptid = null_ptid;
764
765           /* This inferior is dead, so avoid giving the breakpoints
766              module the option to write through to it (cloning a
767              program space resets breakpoints).  */
768           inf->aspace = NULL;
769           inf->pspace = NULL;
770           pspace = add_program_space (maybe_new_address_space ());
771           set_current_program_space (pspace);
772           inf->removable = 1;
773           inf->symfile_flags = SYMFILE_NO_READ;
774           clone_program_space (pspace, inf->vfork_parent->pspace);
775           inf->pspace = pspace;
776           inf->aspace = pspace->aspace;
777
778           /* Put back inferior_ptid.  We'll continue mourning this
779              inferior.  */
780           do_cleanups (old_chain);
781
782           resume_parent = inf->vfork_parent->pid;
783           /* Break the bonds.  */
784           inf->vfork_parent->vfork_child = NULL;
785         }
786
787       inf->vfork_parent = NULL;
788
789       gdb_assert (current_program_space == inf->pspace);
790
791       if (non_stop && resume_parent != -1)
792         {
793           /* If the user wanted the parent to be running, let it go
794              free now.  */
795           struct cleanup *old_chain = make_cleanup_restore_current_thread ();
796
797           if (debug_infrun)
798             fprintf_unfiltered (gdb_stdlog,
799                                 "infrun: resuming vfork parent process %d\n",
800                                 resume_parent);
801
802           iterate_over_threads (proceed_after_vfork_done, &resume_parent);
803
804           do_cleanups (old_chain);
805         }
806     }
807 }
808
809 /* Enum strings for "set|show follow-exec-mode".  */
810
811 static const char follow_exec_mode_new[] = "new";
812 static const char follow_exec_mode_same[] = "same";
813 static const char *const follow_exec_mode_names[] =
814 {
815   follow_exec_mode_new,
816   follow_exec_mode_same,
817   NULL,
818 };
819
820 static const char *follow_exec_mode_string = follow_exec_mode_same;
821 static void
822 show_follow_exec_mode_string (struct ui_file *file, int from_tty,
823                               struct cmd_list_element *c, const char *value)
824 {
825   fprintf_filtered (file, _("Follow exec mode is \"%s\".\n"),  value);
826 }
827
828 /* EXECD_PATHNAME is assumed to be non-NULL.  */
829
830 static void
831 follow_exec (ptid_t pid, char *execd_pathname)
832 {
833   struct thread_info *th = inferior_thread ();
834   struct inferior *inf = current_inferior ();
835
836   /* This is an exec event that we actually wish to pay attention to.
837      Refresh our symbol table to the newly exec'd program, remove any
838      momentary bp's, etc.
839
840      If there are breakpoints, they aren't really inserted now,
841      since the exec() transformed our inferior into a fresh set
842      of instructions.
843
844      We want to preserve symbolic breakpoints on the list, since
845      we have hopes that they can be reset after the new a.out's
846      symbol table is read.
847
848      However, any "raw" breakpoints must be removed from the list
849      (e.g., the solib bp's), since their address is probably invalid
850      now.
851
852      And, we DON'T want to call delete_breakpoints() here, since
853      that may write the bp's "shadow contents" (the instruction
854      value that was overwritten witha TRAP instruction).  Since
855      we now have a new a.out, those shadow contents aren't valid.  */
856
857   mark_breakpoints_out ();
858
859   update_breakpoints_after_exec ();
860
861   /* If there was one, it's gone now.  We cannot truly step-to-next
862      statement through an exec().  */
863   th->control.step_resume_breakpoint = NULL;
864   th->control.exception_resume_breakpoint = NULL;
865   th->control.step_range_start = 0;
866   th->control.step_range_end = 0;
867
868   /* The target reports the exec event to the main thread, even if
869      some other thread does the exec, and even if the main thread was
870      already stopped --- if debugging in non-stop mode, it's possible
871      the user had the main thread held stopped in the previous image
872      --- release it now.  This is the same behavior as step-over-exec
873      with scheduler-locking on in all-stop mode.  */
874   th->stop_requested = 0;
875
876   /* What is this a.out's name?  */
877   printf_unfiltered (_("%s is executing new program: %s\n"),
878                      target_pid_to_str (inferior_ptid),
879                      execd_pathname);
880
881   /* We've followed the inferior through an exec.  Therefore, the
882      inferior has essentially been killed & reborn.  */
883
884   gdb_flush (gdb_stdout);
885
886   breakpoint_init_inferior (inf_execd);
887
888   if (gdb_sysroot && *gdb_sysroot)
889     {
890       char *name = alloca (strlen (gdb_sysroot)
891                             + strlen (execd_pathname)
892                             + 1);
893
894       strcpy (name, gdb_sysroot);
895       strcat (name, execd_pathname);
896       execd_pathname = name;
897     }
898
899   /* Reset the shared library package.  This ensures that we get a
900      shlib event when the child reaches "_start", at which point the
901      dld will have had a chance to initialize the child.  */
902   /* Also, loading a symbol file below may trigger symbol lookups, and
903      we don't want those to be satisfied by the libraries of the
904      previous incarnation of this process.  */
905   no_shared_libraries (NULL, 0);
906
907   if (follow_exec_mode_string == follow_exec_mode_new)
908     {
909       struct program_space *pspace;
910
911       /* The user wants to keep the old inferior and program spaces
912          around.  Create a new fresh one, and switch to it.  */
913
914       inf = add_inferior (current_inferior ()->pid);
915       pspace = add_program_space (maybe_new_address_space ());
916       inf->pspace = pspace;
917       inf->aspace = pspace->aspace;
918
919       exit_inferior_num_silent (current_inferior ()->num);
920
921       set_current_inferior (inf);
922       set_current_program_space (pspace);
923     }
924   else
925     {
926       /* The old description may no longer be fit for the new image.
927          E.g, a 64-bit process exec'ed a 32-bit process.  Clear the
928          old description; we'll read a new one below.  No need to do
929          this on "follow-exec-mode new", as the old inferior stays
930          around (its description is later cleared/refetched on
931          restart).  */
932       target_clear_description ();
933     }
934
935   gdb_assert (current_program_space == inf->pspace);
936
937   /* That a.out is now the one to use.  */
938   exec_file_attach (execd_pathname, 0);
939
940   /* SYMFILE_DEFER_BP_RESET is used as the proper displacement for PIE
941      (Position Independent Executable) main symbol file will get applied by
942      solib_create_inferior_hook below.  breakpoint_re_set would fail to insert
943      the breakpoints with the zero displacement.  */
944
945   symbol_file_add (execd_pathname,
946                    (inf->symfile_flags
947                     | SYMFILE_MAINLINE | SYMFILE_DEFER_BP_RESET),
948                    NULL, 0);
949
950   if ((inf->symfile_flags & SYMFILE_NO_READ) == 0)
951     set_initial_language ();
952
953   /* If the target can specify a description, read it.  Must do this
954      after flipping to the new executable (because the target supplied
955      description must be compatible with the executable's
956      architecture, and the old executable may e.g., be 32-bit, while
957      the new one 64-bit), and before anything involving memory or
958      registers.  */
959   target_find_description ();
960
961   solib_create_inferior_hook (0);
962
963   jit_inferior_created_hook ();
964
965   breakpoint_re_set ();
966
967   /* Reinsert all breakpoints.  (Those which were symbolic have
968      been reset to the proper address in the new a.out, thanks
969      to symbol_file_command...).  */
970   insert_breakpoints ();
971
972   /* The next resume of this inferior should bring it to the shlib
973      startup breakpoints.  (If the user had also set bp's on
974      "main" from the old (parent) process, then they'll auto-
975      matically get reset there in the new process.).  */
976 }
977
978 /* Non-zero if we just simulating a single-step.  This is needed
979    because we cannot remove the breakpoints in the inferior process
980    until after the `wait' in `wait_for_inferior'.  */
981 static int singlestep_breakpoints_inserted_p = 0;
982
983 /* The thread we inserted single-step breakpoints for.  */
984 static ptid_t singlestep_ptid;
985
986 /* PC when we started this single-step.  */
987 static CORE_ADDR singlestep_pc;
988
989 /* If another thread hit the singlestep breakpoint, we save the original
990    thread here so that we can resume single-stepping it later.  */
991 static ptid_t saved_singlestep_ptid;
992 static int stepping_past_singlestep_breakpoint;
993
994 /* If not equal to null_ptid, this means that after stepping over breakpoint
995    is finished, we need to switch to deferred_step_ptid, and step it.
996
997    The use case is when one thread has hit a breakpoint, and then the user 
998    has switched to another thread and issued 'step'.  We need to step over
999    breakpoint in the thread which hit the breakpoint, but then continue
1000    stepping the thread user has selected.  */
1001 static ptid_t deferred_step_ptid;
1002 \f
1003 /* Displaced stepping.  */
1004
1005 /* In non-stop debugging mode, we must take special care to manage
1006    breakpoints properly; in particular, the traditional strategy for
1007    stepping a thread past a breakpoint it has hit is unsuitable.
1008    'Displaced stepping' is a tactic for stepping one thread past a
1009    breakpoint it has hit while ensuring that other threads running
1010    concurrently will hit the breakpoint as they should.
1011
1012    The traditional way to step a thread T off a breakpoint in a
1013    multi-threaded program in all-stop mode is as follows:
1014
1015    a0) Initially, all threads are stopped, and breakpoints are not
1016        inserted.
1017    a1) We single-step T, leaving breakpoints uninserted.
1018    a2) We insert breakpoints, and resume all threads.
1019
1020    In non-stop debugging, however, this strategy is unsuitable: we
1021    don't want to have to stop all threads in the system in order to
1022    continue or step T past a breakpoint.  Instead, we use displaced
1023    stepping:
1024
1025    n0) Initially, T is stopped, other threads are running, and
1026        breakpoints are inserted.
1027    n1) We copy the instruction "under" the breakpoint to a separate
1028        location, outside the main code stream, making any adjustments
1029        to the instruction, register, and memory state as directed by
1030        T's architecture.
1031    n2) We single-step T over the instruction at its new location.
1032    n3) We adjust the resulting register and memory state as directed
1033        by T's architecture.  This includes resetting T's PC to point
1034        back into the main instruction stream.
1035    n4) We resume T.
1036
1037    This approach depends on the following gdbarch methods:
1038
1039    - gdbarch_max_insn_length and gdbarch_displaced_step_location
1040      indicate where to copy the instruction, and how much space must
1041      be reserved there.  We use these in step n1.
1042
1043    - gdbarch_displaced_step_copy_insn copies a instruction to a new
1044      address, and makes any necessary adjustments to the instruction,
1045      register contents, and memory.  We use this in step n1.
1046
1047    - gdbarch_displaced_step_fixup adjusts registers and memory after
1048      we have successfuly single-stepped the instruction, to yield the
1049      same effect the instruction would have had if we had executed it
1050      at its original address.  We use this in step n3.
1051
1052    - gdbarch_displaced_step_free_closure provides cleanup.
1053
1054    The gdbarch_displaced_step_copy_insn and
1055    gdbarch_displaced_step_fixup functions must be written so that
1056    copying an instruction with gdbarch_displaced_step_copy_insn,
1057    single-stepping across the copied instruction, and then applying
1058    gdbarch_displaced_insn_fixup should have the same effects on the
1059    thread's memory and registers as stepping the instruction in place
1060    would have.  Exactly which responsibilities fall to the copy and
1061    which fall to the fixup is up to the author of those functions.
1062
1063    See the comments in gdbarch.sh for details.
1064
1065    Note that displaced stepping and software single-step cannot
1066    currently be used in combination, although with some care I think
1067    they could be made to.  Software single-step works by placing
1068    breakpoints on all possible subsequent instructions; if the
1069    displaced instruction is a PC-relative jump, those breakpoints
1070    could fall in very strange places --- on pages that aren't
1071    executable, or at addresses that are not proper instruction
1072    boundaries.  (We do generally let other threads run while we wait
1073    to hit the software single-step breakpoint, and they might
1074    encounter such a corrupted instruction.)  One way to work around
1075    this would be to have gdbarch_displaced_step_copy_insn fully
1076    simulate the effect of PC-relative instructions (and return NULL)
1077    on architectures that use software single-stepping.
1078
1079    In non-stop mode, we can have independent and simultaneous step
1080    requests, so more than one thread may need to simultaneously step
1081    over a breakpoint.  The current implementation assumes there is
1082    only one scratch space per process.  In this case, we have to
1083    serialize access to the scratch space.  If thread A wants to step
1084    over a breakpoint, but we are currently waiting for some other
1085    thread to complete a displaced step, we leave thread A stopped and
1086    place it in the displaced_step_request_queue.  Whenever a displaced
1087    step finishes, we pick the next thread in the queue and start a new
1088    displaced step operation on it.  See displaced_step_prepare and
1089    displaced_step_fixup for details.  */
1090
1091 struct displaced_step_request
1092 {
1093   ptid_t ptid;
1094   struct displaced_step_request *next;
1095 };
1096
1097 /* Per-inferior displaced stepping state.  */
1098 struct displaced_step_inferior_state
1099 {
1100   /* Pointer to next in linked list.  */
1101   struct displaced_step_inferior_state *next;
1102
1103   /* The process this displaced step state refers to.  */
1104   int pid;
1105
1106   /* A queue of pending displaced stepping requests.  One entry per
1107      thread that needs to do a displaced step.  */
1108   struct displaced_step_request *step_request_queue;
1109
1110   /* If this is not null_ptid, this is the thread carrying out a
1111      displaced single-step in process PID.  This thread's state will
1112      require fixing up once it has completed its step.  */
1113   ptid_t step_ptid;
1114
1115   /* The architecture the thread had when we stepped it.  */
1116   struct gdbarch *step_gdbarch;
1117
1118   /* The closure provided gdbarch_displaced_step_copy_insn, to be used
1119      for post-step cleanup.  */
1120   struct displaced_step_closure *step_closure;
1121
1122   /* The address of the original instruction, and the copy we
1123      made.  */
1124   CORE_ADDR step_original, step_copy;
1125
1126   /* Saved contents of copy area.  */
1127   gdb_byte *step_saved_copy;
1128 };
1129
1130 /* The list of states of processes involved in displaced stepping
1131    presently.  */
1132 static struct displaced_step_inferior_state *displaced_step_inferior_states;
1133
1134 /* Get the displaced stepping state of process PID.  */
1135
1136 static struct displaced_step_inferior_state *
1137 get_displaced_stepping_state (int pid)
1138 {
1139   struct displaced_step_inferior_state *state;
1140
1141   for (state = displaced_step_inferior_states;
1142        state != NULL;
1143        state = state->next)
1144     if (state->pid == pid)
1145       return state;
1146
1147   return NULL;
1148 }
1149
1150 /* Add a new displaced stepping state for process PID to the displaced
1151    stepping state list, or return a pointer to an already existing
1152    entry, if it already exists.  Never returns NULL.  */
1153
1154 static struct displaced_step_inferior_state *
1155 add_displaced_stepping_state (int pid)
1156 {
1157   struct displaced_step_inferior_state *state;
1158
1159   for (state = displaced_step_inferior_states;
1160        state != NULL;
1161        state = state->next)
1162     if (state->pid == pid)
1163       return state;
1164
1165   state = xcalloc (1, sizeof (*state));
1166   state->pid = pid;
1167   state->next = displaced_step_inferior_states;
1168   displaced_step_inferior_states = state;
1169
1170   return state;
1171 }
1172
1173 /* If inferior is in displaced stepping, and ADDR equals to starting address
1174    of copy area, return corresponding displaced_step_closure.  Otherwise,
1175    return NULL.  */
1176
1177 struct displaced_step_closure*
1178 get_displaced_step_closure_by_addr (CORE_ADDR addr)
1179 {
1180   struct displaced_step_inferior_state *displaced
1181     = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
1182
1183   /* If checking the mode of displaced instruction in copy area.  */
1184   if (displaced && !ptid_equal (displaced->step_ptid, null_ptid)
1185      && (displaced->step_copy == addr))
1186     return displaced->step_closure;
1187
1188   return NULL;
1189 }
1190
1191 /* Remove the displaced stepping state of process PID.  */
1192
1193 static void
1194 remove_displaced_stepping_state (int pid)
1195 {
1196   struct displaced_step_inferior_state *it, **prev_next_p;
1197
1198   gdb_assert (pid != 0);
1199
1200   it = displaced_step_inferior_states;
1201   prev_next_p = &displaced_step_inferior_states;
1202   while (it)
1203     {
1204       if (it->pid == pid)
1205         {
1206           *prev_next_p = it->next;
1207           xfree (it);
1208           return;
1209         }
1210
1211       prev_next_p = &it->next;
1212       it = *prev_next_p;
1213     }
1214 }
1215
1216 static void
1217 infrun_inferior_exit (struct inferior *inf)
1218 {
1219   remove_displaced_stepping_state (inf->pid);
1220 }
1221
1222 /* If ON, and the architecture supports it, GDB will use displaced
1223    stepping to step over breakpoints.  If OFF, or if the architecture
1224    doesn't support it, GDB will instead use the traditional
1225    hold-and-step approach.  If AUTO (which is the default), GDB will
1226    decide which technique to use to step over breakpoints depending on
1227    which of all-stop or non-stop mode is active --- displaced stepping
1228    in non-stop mode; hold-and-step in all-stop mode.  */
1229
1230 static enum auto_boolean can_use_displaced_stepping = AUTO_BOOLEAN_AUTO;
1231
1232 static void
1233 show_can_use_displaced_stepping (struct ui_file *file, int from_tty,
1234                                  struct cmd_list_element *c,
1235                                  const char *value)
1236 {
1237   if (can_use_displaced_stepping == AUTO_BOOLEAN_AUTO)
1238     fprintf_filtered (file,
1239                       _("Debugger's willingness to use displaced stepping "
1240                         "to step over breakpoints is %s (currently %s).\n"),
1241                       value, non_stop ? "on" : "off");
1242   else
1243     fprintf_filtered (file,
1244                       _("Debugger's willingness to use displaced stepping "
1245                         "to step over breakpoints is %s.\n"), value);
1246 }
1247
1248 /* Return non-zero if displaced stepping can/should be used to step
1249    over breakpoints.  */
1250
1251 static int
1252 use_displaced_stepping (struct gdbarch *gdbarch)
1253 {
1254   return (((can_use_displaced_stepping == AUTO_BOOLEAN_AUTO && non_stop)
1255            || can_use_displaced_stepping == AUTO_BOOLEAN_TRUE)
1256           && gdbarch_displaced_step_copy_insn_p (gdbarch)
1257           && !RECORD_IS_USED);
1258 }
1259
1260 /* Clean out any stray displaced stepping state.  */
1261 static void
1262 displaced_step_clear (struct displaced_step_inferior_state *displaced)
1263 {
1264   /* Indicate that there is no cleanup pending.  */
1265   displaced->step_ptid = null_ptid;
1266
1267   if (displaced->step_closure)
1268     {
1269       gdbarch_displaced_step_free_closure (displaced->step_gdbarch,
1270                                            displaced->step_closure);
1271       displaced->step_closure = NULL;
1272     }
1273 }
1274
1275 static void
1276 displaced_step_clear_cleanup (void *arg)
1277 {
1278   struct displaced_step_inferior_state *state = arg;
1279
1280   displaced_step_clear (state);
1281 }
1282
1283 /* Dump LEN bytes at BUF in hex to FILE, followed by a newline.  */
1284 void
1285 displaced_step_dump_bytes (struct ui_file *file,
1286                            const gdb_byte *buf,
1287                            size_t len)
1288 {
1289   int i;
1290
1291   for (i = 0; i < len; i++)
1292     fprintf_unfiltered (file, "%02x ", buf[i]);
1293   fputs_unfiltered ("\n", file);
1294 }
1295
1296 /* Prepare to single-step, using displaced stepping.
1297
1298    Note that we cannot use displaced stepping when we have a signal to
1299    deliver.  If we have a signal to deliver and an instruction to step
1300    over, then after the step, there will be no indication from the
1301    target whether the thread entered a signal handler or ignored the
1302    signal and stepped over the instruction successfully --- both cases
1303    result in a simple SIGTRAP.  In the first case we mustn't do a
1304    fixup, and in the second case we must --- but we can't tell which.
1305    Comments in the code for 'random signals' in handle_inferior_event
1306    explain how we handle this case instead.
1307
1308    Returns 1 if preparing was successful -- this thread is going to be
1309    stepped now; or 0 if displaced stepping this thread got queued.  */
1310 static int
1311 displaced_step_prepare (ptid_t ptid)
1312 {
1313   struct cleanup *old_cleanups, *ignore_cleanups;
1314   struct regcache *regcache = get_thread_regcache (ptid);
1315   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1316   CORE_ADDR original, copy;
1317   ULONGEST len;
1318   struct displaced_step_closure *closure;
1319   struct displaced_step_inferior_state *displaced;
1320   int status;
1321
1322   /* We should never reach this function if the architecture does not
1323      support displaced stepping.  */
1324   gdb_assert (gdbarch_displaced_step_copy_insn_p (gdbarch));
1325
1326   /* We have to displaced step one thread at a time, as we only have
1327      access to a single scratch space per inferior.  */
1328
1329   displaced = add_displaced_stepping_state (ptid_get_pid (ptid));
1330
1331   if (!ptid_equal (displaced->step_ptid, null_ptid))
1332     {
1333       /* Already waiting for a displaced step to finish.  Defer this
1334          request and place in queue.  */
1335       struct displaced_step_request *req, *new_req;
1336
1337       if (debug_displaced)
1338         fprintf_unfiltered (gdb_stdlog,
1339                             "displaced: defering step of %s\n",
1340                             target_pid_to_str (ptid));
1341
1342       new_req = xmalloc (sizeof (*new_req));
1343       new_req->ptid = ptid;
1344       new_req->next = NULL;
1345
1346       if (displaced->step_request_queue)
1347         {
1348           for (req = displaced->step_request_queue;
1349                req && req->next;
1350                req = req->next)
1351             ;
1352           req->next = new_req;
1353         }
1354       else
1355         displaced->step_request_queue = new_req;
1356
1357       return 0;
1358     }
1359   else
1360     {
1361       if (debug_displaced)
1362         fprintf_unfiltered (gdb_stdlog,
1363                             "displaced: stepping %s now\n",
1364                             target_pid_to_str (ptid));
1365     }
1366
1367   displaced_step_clear (displaced);
1368
1369   old_cleanups = save_inferior_ptid ();
1370   inferior_ptid = ptid;
1371
1372   original = regcache_read_pc (regcache);
1373
1374   copy = gdbarch_displaced_step_location (gdbarch);
1375   len = gdbarch_max_insn_length (gdbarch);
1376
1377   /* Save the original contents of the copy area.  */
1378   displaced->step_saved_copy = xmalloc (len);
1379   ignore_cleanups = make_cleanup (free_current_contents,
1380                                   &displaced->step_saved_copy);
1381   status = target_read_memory (copy, displaced->step_saved_copy, len);
1382   if (status != 0)
1383     throw_error (MEMORY_ERROR,
1384                  _("Error accessing memory address %s (%s) for "
1385                    "displaced-stepping scratch space."),
1386                  paddress (gdbarch, copy), safe_strerror (status));
1387   if (debug_displaced)
1388     {
1389       fprintf_unfiltered (gdb_stdlog, "displaced: saved %s: ",
1390                           paddress (gdbarch, copy));
1391       displaced_step_dump_bytes (gdb_stdlog,
1392                                  displaced->step_saved_copy,
1393                                  len);
1394     };
1395
1396   closure = gdbarch_displaced_step_copy_insn (gdbarch,
1397                                               original, copy, regcache);
1398
1399   /* We don't support the fully-simulated case at present.  */
1400   gdb_assert (closure);
1401
1402   /* Save the information we need to fix things up if the step
1403      succeeds.  */
1404   displaced->step_ptid = ptid;
1405   displaced->step_gdbarch = gdbarch;
1406   displaced->step_closure = closure;
1407   displaced->step_original = original;
1408   displaced->step_copy = copy;
1409
1410   make_cleanup (displaced_step_clear_cleanup, displaced);
1411
1412   /* Resume execution at the copy.  */
1413   regcache_write_pc (regcache, copy);
1414
1415   discard_cleanups (ignore_cleanups);
1416
1417   do_cleanups (old_cleanups);
1418
1419   if (debug_displaced)
1420     fprintf_unfiltered (gdb_stdlog, "displaced: displaced pc to %s\n",
1421                         paddress (gdbarch, copy));
1422
1423   return 1;
1424 }
1425
1426 static void
1427 write_memory_ptid (ptid_t ptid, CORE_ADDR memaddr,
1428                    const gdb_byte *myaddr, int len)
1429 {
1430   struct cleanup *ptid_cleanup = save_inferior_ptid ();
1431
1432   inferior_ptid = ptid;
1433   write_memory (memaddr, myaddr, len);
1434   do_cleanups (ptid_cleanup);
1435 }
1436
1437 /* Restore the contents of the copy area for thread PTID.  */
1438
1439 static void
1440 displaced_step_restore (struct displaced_step_inferior_state *displaced,
1441                         ptid_t ptid)
1442 {
1443   ULONGEST len = gdbarch_max_insn_length (displaced->step_gdbarch);
1444
1445   write_memory_ptid (ptid, displaced->step_copy,
1446                      displaced->step_saved_copy, len);
1447   if (debug_displaced)
1448     fprintf_unfiltered (gdb_stdlog, "displaced: restored %s %s\n",
1449                         target_pid_to_str (ptid),
1450                         paddress (displaced->step_gdbarch,
1451                                   displaced->step_copy));
1452 }
1453
1454 static void
1455 displaced_step_fixup (ptid_t event_ptid, enum gdb_signal signal)
1456 {
1457   struct cleanup *old_cleanups;
1458   struct displaced_step_inferior_state *displaced
1459     = get_displaced_stepping_state (ptid_get_pid (event_ptid));
1460
1461   /* Was any thread of this process doing a displaced step?  */
1462   if (displaced == NULL)
1463     return;
1464
1465   /* Was this event for the pid we displaced?  */
1466   if (ptid_equal (displaced->step_ptid, null_ptid)
1467       || ! ptid_equal (displaced->step_ptid, event_ptid))
1468     return;
1469
1470   old_cleanups = make_cleanup (displaced_step_clear_cleanup, displaced);
1471
1472   displaced_step_restore (displaced, displaced->step_ptid);
1473
1474   /* Did the instruction complete successfully?  */
1475   if (signal == GDB_SIGNAL_TRAP)
1476     {
1477       /* Fix up the resulting state.  */
1478       gdbarch_displaced_step_fixup (displaced->step_gdbarch,
1479                                     displaced->step_closure,
1480                                     displaced->step_original,
1481                                     displaced->step_copy,
1482                                     get_thread_regcache (displaced->step_ptid));
1483     }
1484   else
1485     {
1486       /* Since the instruction didn't complete, all we can do is
1487          relocate the PC.  */
1488       struct regcache *regcache = get_thread_regcache (event_ptid);
1489       CORE_ADDR pc = regcache_read_pc (regcache);
1490
1491       pc = displaced->step_original + (pc - displaced->step_copy);
1492       regcache_write_pc (regcache, pc);
1493     }
1494
1495   do_cleanups (old_cleanups);
1496
1497   displaced->step_ptid = null_ptid;
1498
1499   /* Are there any pending displaced stepping requests?  If so, run
1500      one now.  Leave the state object around, since we're likely to
1501      need it again soon.  */
1502   while (displaced->step_request_queue)
1503     {
1504       struct displaced_step_request *head;
1505       ptid_t ptid;
1506       struct regcache *regcache;
1507       struct gdbarch *gdbarch;
1508       CORE_ADDR actual_pc;
1509       struct address_space *aspace;
1510
1511       head = displaced->step_request_queue;
1512       ptid = head->ptid;
1513       displaced->step_request_queue = head->next;
1514       xfree (head);
1515
1516       context_switch (ptid);
1517
1518       regcache = get_thread_regcache (ptid);
1519       actual_pc = regcache_read_pc (regcache);
1520       aspace = get_regcache_aspace (regcache);
1521
1522       if (breakpoint_here_p (aspace, actual_pc))
1523         {
1524           if (debug_displaced)
1525             fprintf_unfiltered (gdb_stdlog,
1526                                 "displaced: stepping queued %s now\n",
1527                                 target_pid_to_str (ptid));
1528
1529           displaced_step_prepare (ptid);
1530
1531           gdbarch = get_regcache_arch (regcache);
1532
1533           if (debug_displaced)
1534             {
1535               CORE_ADDR actual_pc = regcache_read_pc (regcache);
1536               gdb_byte buf[4];
1537
1538               fprintf_unfiltered (gdb_stdlog, "displaced: run %s: ",
1539                                   paddress (gdbarch, actual_pc));
1540               read_memory (actual_pc, buf, sizeof (buf));
1541               displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
1542             }
1543
1544           if (gdbarch_displaced_step_hw_singlestep (gdbarch,
1545                                                     displaced->step_closure))
1546             target_resume (ptid, 1, GDB_SIGNAL_0);
1547           else
1548             target_resume (ptid, 0, GDB_SIGNAL_0);
1549
1550           /* Done, we're stepping a thread.  */
1551           break;
1552         }
1553       else
1554         {
1555           int step;
1556           struct thread_info *tp = inferior_thread ();
1557
1558           /* The breakpoint we were sitting under has since been
1559              removed.  */
1560           tp->control.trap_expected = 0;
1561
1562           /* Go back to what we were trying to do.  */
1563           step = currently_stepping (tp);
1564
1565           if (debug_displaced)
1566             fprintf_unfiltered (gdb_stdlog,
1567                                 "displaced: breakpoint is gone: %s, step(%d)\n",
1568                                 target_pid_to_str (tp->ptid), step);
1569
1570           target_resume (ptid, step, GDB_SIGNAL_0);
1571           tp->suspend.stop_signal = GDB_SIGNAL_0;
1572
1573           /* This request was discarded.  See if there's any other
1574              thread waiting for its turn.  */
1575         }
1576     }
1577 }
1578
1579 /* Update global variables holding ptids to hold NEW_PTID if they were
1580    holding OLD_PTID.  */
1581 static void
1582 infrun_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
1583 {
1584   struct displaced_step_request *it;
1585   struct displaced_step_inferior_state *displaced;
1586
1587   if (ptid_equal (inferior_ptid, old_ptid))
1588     inferior_ptid = new_ptid;
1589
1590   if (ptid_equal (singlestep_ptid, old_ptid))
1591     singlestep_ptid = new_ptid;
1592
1593   if (ptid_equal (deferred_step_ptid, old_ptid))
1594     deferred_step_ptid = new_ptid;
1595
1596   for (displaced = displaced_step_inferior_states;
1597        displaced;
1598        displaced = displaced->next)
1599     {
1600       if (ptid_equal (displaced->step_ptid, old_ptid))
1601         displaced->step_ptid = new_ptid;
1602
1603       for (it = displaced->step_request_queue; it; it = it->next)
1604         if (ptid_equal (it->ptid, old_ptid))
1605           it->ptid = new_ptid;
1606     }
1607 }
1608
1609 \f
1610 /* Resuming.  */
1611
1612 /* Things to clean up if we QUIT out of resume ().  */
1613 static void
1614 resume_cleanups (void *ignore)
1615 {
1616   normal_stop ();
1617 }
1618
1619 static const char schedlock_off[] = "off";
1620 static const char schedlock_on[] = "on";
1621 static const char schedlock_step[] = "step";
1622 static const char *const scheduler_enums[] = {
1623   schedlock_off,
1624   schedlock_on,
1625   schedlock_step,
1626   NULL
1627 };
1628 static const char *scheduler_mode = schedlock_off;
1629 static void
1630 show_scheduler_mode (struct ui_file *file, int from_tty,
1631                      struct cmd_list_element *c, const char *value)
1632 {
1633   fprintf_filtered (file,
1634                     _("Mode for locking scheduler "
1635                       "during execution is \"%s\".\n"),
1636                     value);
1637 }
1638
1639 static void
1640 set_schedlock_func (char *args, int from_tty, struct cmd_list_element *c)
1641 {
1642   if (!target_can_lock_scheduler)
1643     {
1644       scheduler_mode = schedlock_off;
1645       error (_("Target '%s' cannot support this command."), target_shortname);
1646     }
1647 }
1648
1649 /* True if execution commands resume all threads of all processes by
1650    default; otherwise, resume only threads of the current inferior
1651    process.  */
1652 int sched_multi = 0;
1653
1654 /* Try to setup for software single stepping over the specified location.
1655    Return 1 if target_resume() should use hardware single step.
1656
1657    GDBARCH the current gdbarch.
1658    PC the location to step over.  */
1659
1660 static int
1661 maybe_software_singlestep (struct gdbarch *gdbarch, CORE_ADDR pc)
1662 {
1663   int hw_step = 1;
1664
1665   if (execution_direction == EXEC_FORWARD
1666       && gdbarch_software_single_step_p (gdbarch)
1667       && gdbarch_software_single_step (gdbarch, get_current_frame ()))
1668     {
1669       hw_step = 0;
1670       /* Do not pull these breakpoints until after a `wait' in
1671          `wait_for_inferior'.  */
1672       singlestep_breakpoints_inserted_p = 1;
1673       singlestep_ptid = inferior_ptid;
1674       singlestep_pc = pc;
1675     }
1676   return hw_step;
1677 }
1678
1679 /* Return a ptid representing the set of threads that we will proceed,
1680    in the perspective of the user/frontend.  We may actually resume
1681    fewer threads at first, e.g., if a thread is stopped at a
1682    breakpoint that needs stepping-off, but that should not be visible
1683    to the user/frontend, and neither should the frontend/user be
1684    allowed to proceed any of the threads that happen to be stopped for
1685    internal run control handling, if a previous command wanted them
1686    resumed.  */
1687
1688 ptid_t
1689 user_visible_resume_ptid (int step)
1690 {
1691   /* By default, resume all threads of all processes.  */
1692   ptid_t resume_ptid = RESUME_ALL;
1693
1694   /* Maybe resume only all threads of the current process.  */
1695   if (!sched_multi && target_supports_multi_process ())
1696     {
1697       resume_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
1698     }
1699
1700   /* Maybe resume a single thread after all.  */
1701   if (non_stop)
1702     {
1703       /* With non-stop mode on, threads are always handled
1704          individually.  */
1705       resume_ptid = inferior_ptid;
1706     }
1707   else if ((scheduler_mode == schedlock_on)
1708            || (scheduler_mode == schedlock_step
1709                && (step || singlestep_breakpoints_inserted_p)))
1710     {
1711       /* User-settable 'scheduler' mode requires solo thread resume.  */
1712       resume_ptid = inferior_ptid;
1713     }
1714
1715   return resume_ptid;
1716 }
1717
1718 /* Resume the inferior, but allow a QUIT.  This is useful if the user
1719    wants to interrupt some lengthy single-stepping operation
1720    (for child processes, the SIGINT goes to the inferior, and so
1721    we get a SIGINT random_signal, but for remote debugging and perhaps
1722    other targets, that's not true).
1723
1724    STEP nonzero if we should step (zero to continue instead).
1725    SIG is the signal to give the inferior (zero for none).  */
1726 void
1727 resume (int step, enum gdb_signal sig)
1728 {
1729   int should_resume = 1;
1730   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
1731   struct regcache *regcache = get_current_regcache ();
1732   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1733   struct thread_info *tp = inferior_thread ();
1734   CORE_ADDR pc = regcache_read_pc (regcache);
1735   struct address_space *aspace = get_regcache_aspace (regcache);
1736
1737   QUIT;
1738
1739   if (current_inferior ()->waiting_for_vfork_done)
1740     {
1741       /* Don't try to single-step a vfork parent that is waiting for
1742          the child to get out of the shared memory region (by exec'ing
1743          or exiting).  This is particularly important on software
1744          single-step archs, as the child process would trip on the
1745          software single step breakpoint inserted for the parent
1746          process.  Since the parent will not actually execute any
1747          instruction until the child is out of the shared region (such
1748          are vfork's semantics), it is safe to simply continue it.
1749          Eventually, we'll see a TARGET_WAITKIND_VFORK_DONE event for
1750          the parent, and tell it to `keep_going', which automatically
1751          re-sets it stepping.  */
1752       if (debug_infrun)
1753         fprintf_unfiltered (gdb_stdlog,
1754                             "infrun: resume : clear step\n");
1755       step = 0;
1756     }
1757
1758   if (debug_infrun)
1759     fprintf_unfiltered (gdb_stdlog,
1760                         "infrun: resume (step=%d, signal=%d), "
1761                         "trap_expected=%d, current thread [%s] at %s\n",
1762                         step, sig, tp->control.trap_expected,
1763                         target_pid_to_str (inferior_ptid),
1764                         paddress (gdbarch, pc));
1765
1766   /* Normally, by the time we reach `resume', the breakpoints are either
1767      removed or inserted, as appropriate.  The exception is if we're sitting
1768      at a permanent breakpoint; we need to step over it, but permanent
1769      breakpoints can't be removed.  So we have to test for it here.  */
1770   if (breakpoint_here_p (aspace, pc) == permanent_breakpoint_here)
1771     {
1772       if (gdbarch_skip_permanent_breakpoint_p (gdbarch))
1773         gdbarch_skip_permanent_breakpoint (gdbarch, regcache);
1774       else
1775         error (_("\
1776 The program is stopped at a permanent breakpoint, but GDB does not know\n\
1777 how to step past a permanent breakpoint on this architecture.  Try using\n\
1778 a command like `return' or `jump' to continue execution."));
1779     }
1780
1781   /* If enabled, step over breakpoints by executing a copy of the
1782      instruction at a different address.
1783
1784      We can't use displaced stepping when we have a signal to deliver;
1785      the comments for displaced_step_prepare explain why.  The
1786      comments in the handle_inferior event for dealing with 'random
1787      signals' explain what we do instead.
1788
1789      We can't use displaced stepping when we are waiting for vfork_done
1790      event, displaced stepping breaks the vfork child similarly as single
1791      step software breakpoint.  */
1792   if (use_displaced_stepping (gdbarch)
1793       && (tp->control.trap_expected
1794           || (step && gdbarch_software_single_step_p (gdbarch)))
1795       && sig == GDB_SIGNAL_0
1796       && !current_inferior ()->waiting_for_vfork_done)
1797     {
1798       struct displaced_step_inferior_state *displaced;
1799
1800       if (!displaced_step_prepare (inferior_ptid))
1801         {
1802           /* Got placed in displaced stepping queue.  Will be resumed
1803              later when all the currently queued displaced stepping
1804              requests finish.  The thread is not executing at this point,
1805              and the call to set_executing will be made later.  But we
1806              need to call set_running here, since from frontend point of view,
1807              the thread is running.  */
1808           set_running (inferior_ptid, 1);
1809           discard_cleanups (old_cleanups);
1810           return;
1811         }
1812
1813       /* Update pc to reflect the new address from which we will execute
1814          instructions due to displaced stepping.  */
1815       pc = regcache_read_pc (get_thread_regcache (inferior_ptid));
1816
1817       displaced = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
1818       step = gdbarch_displaced_step_hw_singlestep (gdbarch,
1819                                                    displaced->step_closure);
1820     }
1821
1822   /* Do we need to do it the hard way, w/temp breakpoints?  */
1823   else if (step)
1824     step = maybe_software_singlestep (gdbarch, pc);
1825
1826   /* Currently, our software single-step implementation leads to different
1827      results than hardware single-stepping in one situation: when stepping
1828      into delivering a signal which has an associated signal handler,
1829      hardware single-step will stop at the first instruction of the handler,
1830      while software single-step will simply skip execution of the handler.
1831
1832      For now, this difference in behavior is accepted since there is no
1833      easy way to actually implement single-stepping into a signal handler
1834      without kernel support.
1835
1836      However, there is one scenario where this difference leads to follow-on
1837      problems: if we're stepping off a breakpoint by removing all breakpoints
1838      and then single-stepping.  In this case, the software single-step
1839      behavior means that even if there is a *breakpoint* in the signal
1840      handler, GDB still would not stop.
1841
1842      Fortunately, we can at least fix this particular issue.  We detect
1843      here the case where we are about to deliver a signal while software
1844      single-stepping with breakpoints removed.  In this situation, we
1845      revert the decisions to remove all breakpoints and insert single-
1846      step breakpoints, and instead we install a step-resume breakpoint
1847      at the current address, deliver the signal without stepping, and
1848      once we arrive back at the step-resume breakpoint, actually step
1849      over the breakpoint we originally wanted to step over.  */
1850   if (singlestep_breakpoints_inserted_p
1851       && tp->control.trap_expected && sig != GDB_SIGNAL_0)
1852     {
1853       /* If we have nested signals or a pending signal is delivered
1854          immediately after a handler returns, might might already have
1855          a step-resume breakpoint set on the earlier handler.  We cannot
1856          set another step-resume breakpoint; just continue on until the
1857          original breakpoint is hit.  */
1858       if (tp->control.step_resume_breakpoint == NULL)
1859         {
1860           insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
1861           tp->step_after_step_resume_breakpoint = 1;
1862         }
1863
1864       remove_single_step_breakpoints ();
1865       singlestep_breakpoints_inserted_p = 0;
1866
1867       insert_breakpoints ();
1868       tp->control.trap_expected = 0;
1869     }
1870
1871   if (should_resume)
1872     {
1873       ptid_t resume_ptid;
1874
1875       /* If STEP is set, it's a request to use hardware stepping
1876          facilities.  But in that case, we should never
1877          use singlestep breakpoint.  */
1878       gdb_assert (!(singlestep_breakpoints_inserted_p && step));
1879
1880       /* Decide the set of threads to ask the target to resume.  Start
1881          by assuming everything will be resumed, than narrow the set
1882          by applying increasingly restricting conditions.  */
1883       resume_ptid = user_visible_resume_ptid (step);
1884
1885       /* Maybe resume a single thread after all.  */
1886       if (singlestep_breakpoints_inserted_p
1887           && stepping_past_singlestep_breakpoint)
1888         {
1889           /* The situation here is as follows.  In thread T1 we wanted to
1890              single-step.  Lacking hardware single-stepping we've
1891              set breakpoint at the PC of the next instruction -- call it
1892              P.  After resuming, we've hit that breakpoint in thread T2.
1893              Now we've removed original breakpoint, inserted breakpoint
1894              at P+1, and try to step to advance T2 past breakpoint.
1895              We need to step only T2, as if T1 is allowed to freely run,
1896              it can run past P, and if other threads are allowed to run,
1897              they can hit breakpoint at P+1, and nested hits of single-step
1898              breakpoints is not something we'd want -- that's complicated
1899              to support, and has no value.  */
1900           resume_ptid = inferior_ptid;
1901         }
1902       else if ((step || singlestep_breakpoints_inserted_p)
1903                && tp->control.trap_expected)
1904         {
1905           /* We're allowing a thread to run past a breakpoint it has
1906              hit, by single-stepping the thread with the breakpoint
1907              removed.  In which case, we need to single-step only this
1908              thread, and keep others stopped, as they can miss this
1909              breakpoint if allowed to run.
1910
1911              The current code actually removes all breakpoints when
1912              doing this, not just the one being stepped over, so if we
1913              let other threads run, we can actually miss any
1914              breakpoint, not just the one at PC.  */
1915           resume_ptid = inferior_ptid;
1916         }
1917
1918       if (gdbarch_cannot_step_breakpoint (gdbarch))
1919         {
1920           /* Most targets can step a breakpoint instruction, thus
1921              executing it normally.  But if this one cannot, just
1922              continue and we will hit it anyway.  */
1923           if (step && breakpoint_inserted_here_p (aspace, pc))
1924             step = 0;
1925         }
1926
1927       if (debug_displaced
1928           && use_displaced_stepping (gdbarch)
1929           && tp->control.trap_expected)
1930         {
1931           struct regcache *resume_regcache = get_thread_regcache (resume_ptid);
1932           struct gdbarch *resume_gdbarch = get_regcache_arch (resume_regcache);
1933           CORE_ADDR actual_pc = regcache_read_pc (resume_regcache);
1934           gdb_byte buf[4];
1935
1936           fprintf_unfiltered (gdb_stdlog, "displaced: run %s: ",
1937                               paddress (resume_gdbarch, actual_pc));
1938           read_memory (actual_pc, buf, sizeof (buf));
1939           displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
1940         }
1941
1942       /* Install inferior's terminal modes.  */
1943       target_terminal_inferior ();
1944
1945       /* Avoid confusing the next resume, if the next stop/resume
1946          happens to apply to another thread.  */
1947       tp->suspend.stop_signal = GDB_SIGNAL_0;
1948
1949       /* Advise target which signals may be handled silently.  If we have
1950          removed breakpoints because we are stepping over one (which can
1951          happen only if we are not using displaced stepping), we need to
1952          receive all signals to avoid accidentally skipping a breakpoint
1953          during execution of a signal handler.  */
1954       if ((step || singlestep_breakpoints_inserted_p)
1955           && tp->control.trap_expected
1956           && !use_displaced_stepping (gdbarch))
1957         target_pass_signals (0, NULL);
1958       else
1959         target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
1960
1961       target_resume (resume_ptid, step, sig);
1962     }
1963
1964   discard_cleanups (old_cleanups);
1965 }
1966 \f
1967 /* Proceeding.  */
1968
1969 /* Clear out all variables saying what to do when inferior is continued.
1970    First do this, then set the ones you want, then call `proceed'.  */
1971
1972 static void
1973 clear_proceed_status_thread (struct thread_info *tp)
1974 {
1975   if (debug_infrun)
1976     fprintf_unfiltered (gdb_stdlog,
1977                         "infrun: clear_proceed_status_thread (%s)\n",
1978                         target_pid_to_str (tp->ptid));
1979
1980   tp->control.trap_expected = 0;
1981   tp->control.step_range_start = 0;
1982   tp->control.step_range_end = 0;
1983   tp->control.step_frame_id = null_frame_id;
1984   tp->control.step_stack_frame_id = null_frame_id;
1985   tp->control.step_over_calls = STEP_OVER_UNDEBUGGABLE;
1986   tp->stop_requested = 0;
1987
1988   tp->control.stop_step = 0;
1989
1990   tp->control.proceed_to_finish = 0;
1991
1992   /* Discard any remaining commands or status from previous stop.  */
1993   bpstat_clear (&tp->control.stop_bpstat);
1994 }
1995
1996 static int
1997 clear_proceed_status_callback (struct thread_info *tp, void *data)
1998 {
1999   if (is_exited (tp->ptid))
2000     return 0;
2001
2002   clear_proceed_status_thread (tp);
2003   return 0;
2004 }
2005
2006 void
2007 clear_proceed_status (void)
2008 {
2009   if (!non_stop)
2010     {
2011       /* In all-stop mode, delete the per-thread status of all
2012          threads, even if inferior_ptid is null_ptid, there may be
2013          threads on the list.  E.g., we may be launching a new
2014          process, while selecting the executable.  */
2015       iterate_over_threads (clear_proceed_status_callback, NULL);
2016     }
2017
2018   if (!ptid_equal (inferior_ptid, null_ptid))
2019     {
2020       struct inferior *inferior;
2021
2022       if (non_stop)
2023         {
2024           /* If in non-stop mode, only delete the per-thread status of
2025              the current thread.  */
2026           clear_proceed_status_thread (inferior_thread ());
2027         }
2028
2029       inferior = current_inferior ();
2030       inferior->control.stop_soon = NO_STOP_QUIETLY;
2031     }
2032
2033   stop_after_trap = 0;
2034
2035   observer_notify_about_to_proceed ();
2036
2037   if (stop_registers)
2038     {
2039       regcache_xfree (stop_registers);
2040       stop_registers = NULL;
2041     }
2042 }
2043
2044 /* Check the current thread against the thread that reported the most recent
2045    event.  If a step-over is required return TRUE and set the current thread
2046    to the old thread.  Otherwise return FALSE.
2047
2048    This should be suitable for any targets that support threads.  */
2049
2050 static int
2051 prepare_to_proceed (int step)
2052 {
2053   ptid_t wait_ptid;
2054   struct target_waitstatus wait_status;
2055   int schedlock_enabled;
2056
2057   /* With non-stop mode on, threads are always handled individually.  */
2058   gdb_assert (! non_stop);
2059
2060   /* Get the last target status returned by target_wait().  */
2061   get_last_target_status (&wait_ptid, &wait_status);
2062
2063   /* Make sure we were stopped at a breakpoint.  */
2064   if (wait_status.kind != TARGET_WAITKIND_STOPPED
2065       || (wait_status.value.sig != GDB_SIGNAL_TRAP
2066           && wait_status.value.sig != GDB_SIGNAL_ILL
2067           && wait_status.value.sig != GDB_SIGNAL_SEGV
2068           && wait_status.value.sig != GDB_SIGNAL_EMT))
2069     {
2070       return 0;
2071     }
2072
2073   schedlock_enabled = (scheduler_mode == schedlock_on
2074                        || (scheduler_mode == schedlock_step
2075                            && step));
2076
2077   /* Don't switch over to WAIT_PTID if scheduler locking is on.  */
2078   if (schedlock_enabled)
2079     return 0;
2080
2081   /* Don't switch over if we're about to resume some other process
2082      other than WAIT_PTID's, and schedule-multiple is off.  */
2083   if (!sched_multi
2084       && ptid_get_pid (wait_ptid) != ptid_get_pid (inferior_ptid))
2085     return 0;
2086
2087   /* Switched over from WAIT_PID.  */
2088   if (!ptid_equal (wait_ptid, minus_one_ptid)
2089       && !ptid_equal (inferior_ptid, wait_ptid))
2090     {
2091       struct regcache *regcache = get_thread_regcache (wait_ptid);
2092
2093       if (breakpoint_here_p (get_regcache_aspace (regcache),
2094                              regcache_read_pc (regcache)))
2095         {
2096           /* If stepping, remember current thread to switch back to.  */
2097           if (step)
2098             deferred_step_ptid = inferior_ptid;
2099
2100           /* Switch back to WAIT_PID thread.  */
2101           switch_to_thread (wait_ptid);
2102
2103           if (debug_infrun)
2104             fprintf_unfiltered (gdb_stdlog,
2105                                 "infrun: prepare_to_proceed (step=%d), "
2106                                 "switched to [%s]\n",
2107                                 step, target_pid_to_str (inferior_ptid));
2108
2109           /* We return 1 to indicate that there is a breakpoint here,
2110              so we need to step over it before continuing to avoid
2111              hitting it straight away.  */
2112           return 1;
2113         }
2114     }
2115
2116   return 0;
2117 }
2118
2119 /* Basic routine for continuing the program in various fashions.
2120
2121    ADDR is the address to resume at, or -1 for resume where stopped.
2122    SIGGNAL is the signal to give it, or 0 for none,
2123    or -1 for act according to how it stopped.
2124    STEP is nonzero if should trap after one instruction.
2125    -1 means return after that and print nothing.
2126    You should probably set various step_... variables
2127    before calling here, if you are stepping.
2128
2129    You should call clear_proceed_status before calling proceed.  */
2130
2131 void
2132 proceed (CORE_ADDR addr, enum gdb_signal siggnal, int step)
2133 {
2134   struct regcache *regcache;
2135   struct gdbarch *gdbarch;
2136   struct thread_info *tp;
2137   CORE_ADDR pc;
2138   struct address_space *aspace;
2139   /* GDB may force the inferior to step due to various reasons.  */
2140   int force_step = 0;
2141
2142   /* If we're stopped at a fork/vfork, follow the branch set by the
2143      "set follow-fork-mode" command; otherwise, we'll just proceed
2144      resuming the current thread.  */
2145   if (!follow_fork ())
2146     {
2147       /* The target for some reason decided not to resume.  */
2148       normal_stop ();
2149       if (target_can_async_p ())
2150         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
2151       return;
2152     }
2153
2154   /* We'll update this if & when we switch to a new thread.  */
2155   previous_inferior_ptid = inferior_ptid;
2156
2157   regcache = get_current_regcache ();
2158   gdbarch = get_regcache_arch (regcache);
2159   aspace = get_regcache_aspace (regcache);
2160   pc = regcache_read_pc (regcache);
2161
2162   if (step > 0)
2163     step_start_function = find_pc_function (pc);
2164   if (step < 0)
2165     stop_after_trap = 1;
2166
2167   if (addr == (CORE_ADDR) -1)
2168     {
2169       if (pc == stop_pc && breakpoint_here_p (aspace, pc)
2170           && execution_direction != EXEC_REVERSE)
2171         /* There is a breakpoint at the address we will resume at,
2172            step one instruction before inserting breakpoints so that
2173            we do not stop right away (and report a second hit at this
2174            breakpoint).
2175
2176            Note, we don't do this in reverse, because we won't
2177            actually be executing the breakpoint insn anyway.
2178            We'll be (un-)executing the previous instruction.  */
2179
2180         force_step = 1;
2181       else if (gdbarch_single_step_through_delay_p (gdbarch)
2182                && gdbarch_single_step_through_delay (gdbarch,
2183                                                      get_current_frame ()))
2184         /* We stepped onto an instruction that needs to be stepped
2185            again before re-inserting the breakpoint, do so.  */
2186         force_step = 1;
2187     }
2188   else
2189     {
2190       regcache_write_pc (regcache, addr);
2191     }
2192
2193   if (debug_infrun)
2194     fprintf_unfiltered (gdb_stdlog,
2195                         "infrun: proceed (addr=%s, signal=%d, step=%d)\n",
2196                         paddress (gdbarch, addr), siggnal, step);
2197
2198   if (non_stop)
2199     /* In non-stop, each thread is handled individually.  The context
2200        must already be set to the right thread here.  */
2201     ;
2202   else
2203     {
2204       /* In a multi-threaded task we may select another thread and
2205          then continue or step.
2206
2207          But if the old thread was stopped at a breakpoint, it will
2208          immediately cause another breakpoint stop without any
2209          execution (i.e. it will report a breakpoint hit incorrectly).
2210          So we must step over it first.
2211
2212          prepare_to_proceed checks the current thread against the
2213          thread that reported the most recent event.  If a step-over
2214          is required it returns TRUE and sets the current thread to
2215          the old thread.  */
2216       if (prepare_to_proceed (step))
2217         force_step = 1;
2218     }
2219
2220   /* prepare_to_proceed may change the current thread.  */
2221   tp = inferior_thread ();
2222
2223   if (force_step)
2224     {
2225       tp->control.trap_expected = 1;
2226       /* If displaced stepping is enabled, we can step over the
2227          breakpoint without hitting it, so leave all breakpoints
2228          inserted.  Otherwise we need to disable all breakpoints, step
2229          one instruction, and then re-add them when that step is
2230          finished.  */
2231       if (!use_displaced_stepping (gdbarch))
2232         remove_breakpoints ();
2233     }
2234
2235   /* We can insert breakpoints if we're not trying to step over one,
2236      or if we are stepping over one but we're using displaced stepping
2237      to do so.  */
2238   if (! tp->control.trap_expected || use_displaced_stepping (gdbarch))
2239     insert_breakpoints ();
2240
2241   if (!non_stop)
2242     {
2243       /* Pass the last stop signal to the thread we're resuming,
2244          irrespective of whether the current thread is the thread that
2245          got the last event or not.  This was historically GDB's
2246          behaviour before keeping a stop_signal per thread.  */
2247
2248       struct thread_info *last_thread;
2249       ptid_t last_ptid;
2250       struct target_waitstatus last_status;
2251
2252       get_last_target_status (&last_ptid, &last_status);
2253       if (!ptid_equal (inferior_ptid, last_ptid)
2254           && !ptid_equal (last_ptid, null_ptid)
2255           && !ptid_equal (last_ptid, minus_one_ptid))
2256         {
2257           last_thread = find_thread_ptid (last_ptid);
2258           if (last_thread)
2259             {
2260               tp->suspend.stop_signal = last_thread->suspend.stop_signal;
2261               last_thread->suspend.stop_signal = GDB_SIGNAL_0;
2262             }
2263         }
2264     }
2265
2266   if (siggnal != GDB_SIGNAL_DEFAULT)
2267     tp->suspend.stop_signal = siggnal;
2268   /* If this signal should not be seen by program,
2269      give it zero.  Used for debugging signals.  */
2270   else if (!signal_program[tp->suspend.stop_signal])
2271     tp->suspend.stop_signal = GDB_SIGNAL_0;
2272
2273   annotate_starting ();
2274
2275   /* Make sure that output from GDB appears before output from the
2276      inferior.  */
2277   gdb_flush (gdb_stdout);
2278
2279   /* Refresh prev_pc value just prior to resuming.  This used to be
2280      done in stop_stepping, however, setting prev_pc there did not handle
2281      scenarios such as inferior function calls or returning from
2282      a function via the return command.  In those cases, the prev_pc
2283      value was not set properly for subsequent commands.  The prev_pc value 
2284      is used to initialize the starting line number in the ecs.  With an 
2285      invalid value, the gdb next command ends up stopping at the position
2286      represented by the next line table entry past our start position.
2287      On platforms that generate one line table entry per line, this
2288      is not a problem.  However, on the ia64, the compiler generates
2289      extraneous line table entries that do not increase the line number.
2290      When we issue the gdb next command on the ia64 after an inferior call
2291      or a return command, we often end up a few instructions forward, still 
2292      within the original line we started.
2293
2294      An attempt was made to refresh the prev_pc at the same time the
2295      execution_control_state is initialized (for instance, just before
2296      waiting for an inferior event).  But this approach did not work
2297      because of platforms that use ptrace, where the pc register cannot
2298      be read unless the inferior is stopped.  At that point, we are not
2299      guaranteed the inferior is stopped and so the regcache_read_pc() call
2300      can fail.  Setting the prev_pc value here ensures the value is updated
2301      correctly when the inferior is stopped.  */
2302   tp->prev_pc = regcache_read_pc (get_current_regcache ());
2303
2304   /* Fill in with reasonable starting values.  */
2305   init_thread_stepping_state (tp);
2306
2307   /* Reset to normal state.  */
2308   init_infwait_state ();
2309
2310   /* Resume inferior.  */
2311   resume (force_step || step || bpstat_should_step (),
2312           tp->suspend.stop_signal);
2313
2314   /* Wait for it to stop (if not standalone)
2315      and in any case decode why it stopped, and act accordingly.  */
2316   /* Do this only if we are not using the event loop, or if the target
2317      does not support asynchronous execution.  */
2318   if (!target_can_async_p ())
2319     {
2320       wait_for_inferior ();
2321       normal_stop ();
2322     }
2323 }
2324 \f
2325
2326 /* Start remote-debugging of a machine over a serial link.  */
2327
2328 void
2329 start_remote (int from_tty)
2330 {
2331   struct inferior *inferior;
2332
2333   inferior = current_inferior ();
2334   inferior->control.stop_soon = STOP_QUIETLY_REMOTE;
2335
2336   /* Always go on waiting for the target, regardless of the mode.  */
2337   /* FIXME: cagney/1999-09-23: At present it isn't possible to
2338      indicate to wait_for_inferior that a target should timeout if
2339      nothing is returned (instead of just blocking).  Because of this,
2340      targets expecting an immediate response need to, internally, set
2341      things up so that the target_wait() is forced to eventually
2342      timeout.  */
2343   /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
2344      differentiate to its caller what the state of the target is after
2345      the initial open has been performed.  Here we're assuming that
2346      the target has stopped.  It should be possible to eventually have
2347      target_open() return to the caller an indication that the target
2348      is currently running and GDB state should be set to the same as
2349      for an async run.  */
2350   wait_for_inferior ();
2351
2352   /* Now that the inferior has stopped, do any bookkeeping like
2353      loading shared libraries.  We want to do this before normal_stop,
2354      so that the displayed frame is up to date.  */
2355   post_create_inferior (&current_target, from_tty);
2356
2357   normal_stop ();
2358 }
2359
2360 /* Initialize static vars when a new inferior begins.  */
2361
2362 void
2363 init_wait_for_inferior (void)
2364 {
2365   /* These are meaningless until the first time through wait_for_inferior.  */
2366
2367   breakpoint_init_inferior (inf_starting);
2368
2369   clear_proceed_status ();
2370
2371   stepping_past_singlestep_breakpoint = 0;
2372   deferred_step_ptid = null_ptid;
2373
2374   target_last_wait_ptid = minus_one_ptid;
2375
2376   previous_inferior_ptid = inferior_ptid;
2377   init_infwait_state ();
2378
2379   /* Discard any skipped inlined frames.  */
2380   clear_inline_frame_state (minus_one_ptid);
2381 }
2382
2383 \f
2384 /* This enum encodes possible reasons for doing a target_wait, so that
2385    wfi can call target_wait in one place.  (Ultimately the call will be
2386    moved out of the infinite loop entirely.) */
2387
2388 enum infwait_states
2389 {
2390   infwait_normal_state,
2391   infwait_thread_hop_state,
2392   infwait_step_watch_state,
2393   infwait_nonstep_watch_state
2394 };
2395
2396 /* The PTID we'll do a target_wait on.*/
2397 ptid_t waiton_ptid;
2398
2399 /* Current inferior wait state.  */
2400 static enum infwait_states infwait_state;
2401
2402 /* Data to be passed around while handling an event.  This data is
2403    discarded between events.  */
2404 struct execution_control_state
2405 {
2406   ptid_t ptid;
2407   /* The thread that got the event, if this was a thread event; NULL
2408      otherwise.  */
2409   struct thread_info *event_thread;
2410
2411   struct target_waitstatus ws;
2412   int random_signal;
2413   int stop_func_filled_in;
2414   CORE_ADDR stop_func_start;
2415   CORE_ADDR stop_func_end;
2416   const char *stop_func_name;
2417   int wait_some_more;
2418 };
2419
2420 static void handle_inferior_event (struct execution_control_state *ecs);
2421
2422 static void handle_step_into_function (struct gdbarch *gdbarch,
2423                                        struct execution_control_state *ecs);
2424 static void handle_step_into_function_backward (struct gdbarch *gdbarch,
2425                                                 struct execution_control_state *ecs);
2426 static void check_exception_resume (struct execution_control_state *,
2427                                     struct frame_info *);
2428
2429 static void stop_stepping (struct execution_control_state *ecs);
2430 static void prepare_to_wait (struct execution_control_state *ecs);
2431 static void keep_going (struct execution_control_state *ecs);
2432
2433 /* Callback for iterate over threads.  If the thread is stopped, but
2434    the user/frontend doesn't know about that yet, go through
2435    normal_stop, as if the thread had just stopped now.  ARG points at
2436    a ptid.  If PTID is MINUS_ONE_PTID, applies to all threads.  If
2437    ptid_is_pid(PTID) is true, applies to all threads of the process
2438    pointed at by PTID.  Otherwise, apply only to the thread pointed by
2439    PTID.  */
2440
2441 static int
2442 infrun_thread_stop_requested_callback (struct thread_info *info, void *arg)
2443 {
2444   ptid_t ptid = * (ptid_t *) arg;
2445
2446   if ((ptid_equal (info->ptid, ptid)
2447        || ptid_equal (minus_one_ptid, ptid)
2448        || (ptid_is_pid (ptid)
2449            && ptid_get_pid (ptid) == ptid_get_pid (info->ptid)))
2450       && is_running (info->ptid)
2451       && !is_executing (info->ptid))
2452     {
2453       struct cleanup *old_chain;
2454       struct execution_control_state ecss;
2455       struct execution_control_state *ecs = &ecss;
2456
2457       memset (ecs, 0, sizeof (*ecs));
2458
2459       old_chain = make_cleanup_restore_current_thread ();
2460
2461       /* Go through handle_inferior_event/normal_stop, so we always
2462          have consistent output as if the stop event had been
2463          reported.  */
2464       ecs->ptid = info->ptid;
2465       ecs->event_thread = find_thread_ptid (info->ptid);
2466       ecs->ws.kind = TARGET_WAITKIND_STOPPED;
2467       ecs->ws.value.sig = GDB_SIGNAL_0;
2468
2469       handle_inferior_event (ecs);
2470
2471       if (!ecs->wait_some_more)
2472         {
2473           struct thread_info *tp;
2474
2475           normal_stop ();
2476
2477           /* Finish off the continuations.  */
2478           tp = inferior_thread ();
2479           do_all_intermediate_continuations_thread (tp, 1);
2480           do_all_continuations_thread (tp, 1);
2481         }
2482
2483       do_cleanups (old_chain);
2484     }
2485
2486   return 0;
2487 }
2488
2489 /* This function is attached as a "thread_stop_requested" observer.
2490    Cleanup local state that assumed the PTID was to be resumed, and
2491    report the stop to the frontend.  */
2492
2493 static void
2494 infrun_thread_stop_requested (ptid_t ptid)
2495 {
2496   struct displaced_step_inferior_state *displaced;
2497
2498   /* PTID was requested to stop.  Remove it from the displaced
2499      stepping queue, so we don't try to resume it automatically.  */
2500
2501   for (displaced = displaced_step_inferior_states;
2502        displaced;
2503        displaced = displaced->next)
2504     {
2505       struct displaced_step_request *it, **prev_next_p;
2506
2507       it = displaced->step_request_queue;
2508       prev_next_p = &displaced->step_request_queue;
2509       while (it)
2510         {
2511           if (ptid_match (it->ptid, ptid))
2512             {
2513               *prev_next_p = it->next;
2514               it->next = NULL;
2515               xfree (it);
2516             }
2517           else
2518             {
2519               prev_next_p = &it->next;
2520             }
2521
2522           it = *prev_next_p;
2523         }
2524     }
2525
2526   iterate_over_threads (infrun_thread_stop_requested_callback, &ptid);
2527 }
2528
2529 static void
2530 infrun_thread_thread_exit (struct thread_info *tp, int silent)
2531 {
2532   if (ptid_equal (target_last_wait_ptid, tp->ptid))
2533     nullify_last_target_wait_ptid ();
2534 }
2535
2536 /* Callback for iterate_over_threads.  */
2537
2538 static int
2539 delete_step_resume_breakpoint_callback (struct thread_info *info, void *data)
2540 {
2541   if (is_exited (info->ptid))
2542     return 0;
2543
2544   delete_step_resume_breakpoint (info);
2545   delete_exception_resume_breakpoint (info);
2546   return 0;
2547 }
2548
2549 /* In all-stop, delete the step resume breakpoint of any thread that
2550    had one.  In non-stop, delete the step resume breakpoint of the
2551    thread that just stopped.  */
2552
2553 static void
2554 delete_step_thread_step_resume_breakpoint (void)
2555 {
2556   if (!target_has_execution
2557       || ptid_equal (inferior_ptid, null_ptid))
2558     /* If the inferior has exited, we have already deleted the step
2559        resume breakpoints out of GDB's lists.  */
2560     return;
2561
2562   if (non_stop)
2563     {
2564       /* If in non-stop mode, only delete the step-resume or
2565          longjmp-resume breakpoint of the thread that just stopped
2566          stepping.  */
2567       struct thread_info *tp = inferior_thread ();
2568
2569       delete_step_resume_breakpoint (tp);
2570       delete_exception_resume_breakpoint (tp);
2571     }
2572   else
2573     /* In all-stop mode, delete all step-resume and longjmp-resume
2574        breakpoints of any thread that had them.  */
2575     iterate_over_threads (delete_step_resume_breakpoint_callback, NULL);
2576 }
2577
2578 /* A cleanup wrapper.  */
2579
2580 static void
2581 delete_step_thread_step_resume_breakpoint_cleanup (void *arg)
2582 {
2583   delete_step_thread_step_resume_breakpoint ();
2584 }
2585
2586 /* Pretty print the results of target_wait, for debugging purposes.  */
2587
2588 static void
2589 print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid,
2590                            const struct target_waitstatus *ws)
2591 {
2592   char *status_string = target_waitstatus_to_string (ws);
2593   struct ui_file *tmp_stream = mem_fileopen ();
2594   char *text;
2595
2596   /* The text is split over several lines because it was getting too long.
2597      Call fprintf_unfiltered (gdb_stdlog) once so that the text is still
2598      output as a unit; we want only one timestamp printed if debug_timestamp
2599      is set.  */
2600
2601   fprintf_unfiltered (tmp_stream,
2602                       "infrun: target_wait (%d", PIDGET (waiton_ptid));
2603   if (PIDGET (waiton_ptid) != -1)
2604     fprintf_unfiltered (tmp_stream,
2605                         " [%s]", target_pid_to_str (waiton_ptid));
2606   fprintf_unfiltered (tmp_stream, ", status) =\n");
2607   fprintf_unfiltered (tmp_stream,
2608                       "infrun:   %d [%s],\n",
2609                       PIDGET (result_ptid), target_pid_to_str (result_ptid));
2610   fprintf_unfiltered (tmp_stream,
2611                       "infrun:   %s\n",
2612                       status_string);
2613
2614   text = ui_file_xstrdup (tmp_stream, NULL);
2615
2616   /* This uses %s in part to handle %'s in the text, but also to avoid
2617      a gcc error: the format attribute requires a string literal.  */
2618   fprintf_unfiltered (gdb_stdlog, "%s", text);
2619
2620   xfree (status_string);
2621   xfree (text);
2622   ui_file_delete (tmp_stream);
2623 }
2624
2625 /* Prepare and stabilize the inferior for detaching it.  E.g.,
2626    detaching while a thread is displaced stepping is a recipe for
2627    crashing it, as nothing would readjust the PC out of the scratch
2628    pad.  */
2629
2630 void
2631 prepare_for_detach (void)
2632 {
2633   struct inferior *inf = current_inferior ();
2634   ptid_t pid_ptid = pid_to_ptid (inf->pid);
2635   struct cleanup *old_chain_1;
2636   struct displaced_step_inferior_state *displaced;
2637
2638   displaced = get_displaced_stepping_state (inf->pid);
2639
2640   /* Is any thread of this process displaced stepping?  If not,
2641      there's nothing else to do.  */
2642   if (displaced == NULL || ptid_equal (displaced->step_ptid, null_ptid))
2643     return;
2644
2645   if (debug_infrun)
2646     fprintf_unfiltered (gdb_stdlog,
2647                         "displaced-stepping in-process while detaching");
2648
2649   old_chain_1 = make_cleanup_restore_integer (&inf->detaching);
2650   inf->detaching = 1;
2651
2652   while (!ptid_equal (displaced->step_ptid, null_ptid))
2653     {
2654       struct cleanup *old_chain_2;
2655       struct execution_control_state ecss;
2656       struct execution_control_state *ecs;
2657
2658       ecs = &ecss;
2659       memset (ecs, 0, sizeof (*ecs));
2660
2661       overlay_cache_invalid = 1;
2662
2663       if (deprecated_target_wait_hook)
2664         ecs->ptid = deprecated_target_wait_hook (pid_ptid, &ecs->ws, 0);
2665       else
2666         ecs->ptid = target_wait (pid_ptid, &ecs->ws, 0);
2667
2668       if (debug_infrun)
2669         print_target_wait_results (pid_ptid, ecs->ptid, &ecs->ws);
2670
2671       /* If an error happens while handling the event, propagate GDB's
2672          knowledge of the executing state to the frontend/user running
2673          state.  */
2674       old_chain_2 = make_cleanup (finish_thread_state_cleanup,
2675                                   &minus_one_ptid);
2676
2677       /* Now figure out what to do with the result of the result.  */
2678       handle_inferior_event (ecs);
2679
2680       /* No error, don't finish the state yet.  */
2681       discard_cleanups (old_chain_2);
2682
2683       /* Breakpoints and watchpoints are not installed on the target
2684          at this point, and signals are passed directly to the
2685          inferior, so this must mean the process is gone.  */
2686       if (!ecs->wait_some_more)
2687         {
2688           discard_cleanups (old_chain_1);
2689           error (_("Program exited while detaching"));
2690         }
2691     }
2692
2693   discard_cleanups (old_chain_1);
2694 }
2695
2696 /* Wait for control to return from inferior to debugger.
2697
2698    If inferior gets a signal, we may decide to start it up again
2699    instead of returning.  That is why there is a loop in this function.
2700    When this function actually returns it means the inferior
2701    should be left stopped and GDB should read more commands.  */
2702
2703 void
2704 wait_for_inferior (void)
2705 {
2706   struct cleanup *old_cleanups;
2707
2708   if (debug_infrun)
2709     fprintf_unfiltered
2710       (gdb_stdlog, "infrun: wait_for_inferior ()\n");
2711
2712   old_cleanups =
2713     make_cleanup (delete_step_thread_step_resume_breakpoint_cleanup, NULL);
2714
2715   while (1)
2716     {
2717       struct execution_control_state ecss;
2718       struct execution_control_state *ecs = &ecss;
2719       struct cleanup *old_chain;
2720
2721       memset (ecs, 0, sizeof (*ecs));
2722
2723       overlay_cache_invalid = 1;
2724
2725       if (deprecated_target_wait_hook)
2726         ecs->ptid = deprecated_target_wait_hook (waiton_ptid, &ecs->ws, 0);
2727       else
2728         ecs->ptid = target_wait (waiton_ptid, &ecs->ws, 0);
2729
2730       if (debug_infrun)
2731         print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
2732
2733       /* If an error happens while handling the event, propagate GDB's
2734          knowledge of the executing state to the frontend/user running
2735          state.  */
2736       old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
2737
2738       /* Now figure out what to do with the result of the result.  */
2739       handle_inferior_event (ecs);
2740
2741       /* No error, don't finish the state yet.  */
2742       discard_cleanups (old_chain);
2743
2744       if (!ecs->wait_some_more)
2745         break;
2746     }
2747
2748   do_cleanups (old_cleanups);
2749 }
2750
2751 /* Asynchronous version of wait_for_inferior.  It is called by the
2752    event loop whenever a change of state is detected on the file
2753    descriptor corresponding to the target.  It can be called more than
2754    once to complete a single execution command.  In such cases we need
2755    to keep the state in a global variable ECSS.  If it is the last time
2756    that this function is called for a single execution command, then
2757    report to the user that the inferior has stopped, and do the
2758    necessary cleanups.  */
2759
2760 void
2761 fetch_inferior_event (void *client_data)
2762 {
2763   struct execution_control_state ecss;
2764   struct execution_control_state *ecs = &ecss;
2765   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
2766   struct cleanup *ts_old_chain;
2767   int was_sync = sync_execution;
2768   int cmd_done = 0;
2769
2770   memset (ecs, 0, sizeof (*ecs));
2771
2772   /* We're handling a live event, so make sure we're doing live
2773      debugging.  If we're looking at traceframes while the target is
2774      running, we're going to need to get back to that mode after
2775      handling the event.  */
2776   if (non_stop)
2777     {
2778       make_cleanup_restore_current_traceframe ();
2779       set_current_traceframe (-1);
2780     }
2781
2782   if (non_stop)
2783     /* In non-stop mode, the user/frontend should not notice a thread
2784        switch due to internal events.  Make sure we reverse to the
2785        user selected thread and frame after handling the event and
2786        running any breakpoint commands.  */
2787     make_cleanup_restore_current_thread ();
2788
2789   overlay_cache_invalid = 1;
2790
2791   make_cleanup_restore_integer (&execution_direction);
2792   execution_direction = target_execution_direction ();
2793
2794   if (deprecated_target_wait_hook)
2795     ecs->ptid =
2796       deprecated_target_wait_hook (waiton_ptid, &ecs->ws, TARGET_WNOHANG);
2797   else
2798     ecs->ptid = target_wait (waiton_ptid, &ecs->ws, TARGET_WNOHANG);
2799
2800   if (debug_infrun)
2801     print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
2802
2803   /* If an error happens while handling the event, propagate GDB's
2804      knowledge of the executing state to the frontend/user running
2805      state.  */
2806   if (!non_stop)
2807     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
2808   else
2809     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &ecs->ptid);
2810
2811   /* Get executed before make_cleanup_restore_current_thread above to apply
2812      still for the thread which has thrown the exception.  */
2813   make_bpstat_clear_actions_cleanup ();
2814
2815   /* Now figure out what to do with the result of the result.  */
2816   handle_inferior_event (ecs);
2817
2818   if (!ecs->wait_some_more)
2819     {
2820       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
2821
2822       delete_step_thread_step_resume_breakpoint ();
2823
2824       /* We may not find an inferior if this was a process exit.  */
2825       if (inf == NULL || inf->control.stop_soon == NO_STOP_QUIETLY)
2826         normal_stop ();
2827
2828       if (target_has_execution
2829           && ecs->ws.kind != TARGET_WAITKIND_NO_RESUMED
2830           && ecs->ws.kind != TARGET_WAITKIND_EXITED
2831           && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
2832           && ecs->event_thread->step_multi
2833           && ecs->event_thread->control.stop_step)
2834         inferior_event_handler (INF_EXEC_CONTINUE, NULL);
2835       else
2836         {
2837           inferior_event_handler (INF_EXEC_COMPLETE, NULL);
2838           cmd_done = 1;
2839         }
2840     }
2841
2842   /* No error, don't finish the thread states yet.  */
2843   discard_cleanups (ts_old_chain);
2844
2845   /* Revert thread and frame.  */
2846   do_cleanups (old_chain);
2847
2848   /* If the inferior was in sync execution mode, and now isn't,
2849      restore the prompt (a synchronous execution command has finished,
2850      and we're ready for input).  */
2851   if (interpreter_async && was_sync && !sync_execution)
2852     display_gdb_prompt (0);
2853
2854   if (cmd_done
2855       && !was_sync
2856       && exec_done_display_p
2857       && (ptid_equal (inferior_ptid, null_ptid)
2858           || !is_running (inferior_ptid)))
2859     printf_unfiltered (_("completed.\n"));
2860 }
2861
2862 /* Record the frame and location we're currently stepping through.  */
2863 void
2864 set_step_info (struct frame_info *frame, struct symtab_and_line sal)
2865 {
2866   struct thread_info *tp = inferior_thread ();
2867
2868   tp->control.step_frame_id = get_frame_id (frame);
2869   tp->control.step_stack_frame_id = get_stack_frame_id (frame);
2870
2871   tp->current_symtab = sal.symtab;
2872   tp->current_line = sal.line;
2873 }
2874
2875 /* Clear context switchable stepping state.  */
2876
2877 void
2878 init_thread_stepping_state (struct thread_info *tss)
2879 {
2880   tss->stepping_over_breakpoint = 0;
2881   tss->step_after_step_resume_breakpoint = 0;
2882 }
2883
2884 /* Return the cached copy of the last pid/waitstatus returned by
2885    target_wait()/deprecated_target_wait_hook().  The data is actually
2886    cached by handle_inferior_event(), which gets called immediately
2887    after target_wait()/deprecated_target_wait_hook().  */
2888
2889 void
2890 get_last_target_status (ptid_t *ptidp, struct target_waitstatus *status)
2891 {
2892   *ptidp = target_last_wait_ptid;
2893   *status = target_last_waitstatus;
2894 }
2895
2896 void
2897 nullify_last_target_wait_ptid (void)
2898 {
2899   target_last_wait_ptid = minus_one_ptid;
2900 }
2901
2902 /* Switch thread contexts.  */
2903
2904 static void
2905 context_switch (ptid_t ptid)
2906 {
2907   if (debug_infrun && !ptid_equal (ptid, inferior_ptid))
2908     {
2909       fprintf_unfiltered (gdb_stdlog, "infrun: Switching context from %s ",
2910                           target_pid_to_str (inferior_ptid));
2911       fprintf_unfiltered (gdb_stdlog, "to %s\n",
2912                           target_pid_to_str (ptid));
2913     }
2914
2915   switch_to_thread (ptid);
2916 }
2917
2918 static void
2919 adjust_pc_after_break (struct execution_control_state *ecs)
2920 {
2921   struct regcache *regcache;
2922   struct gdbarch *gdbarch;
2923   struct address_space *aspace;
2924   CORE_ADDR breakpoint_pc;
2925
2926   /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP.  If
2927      we aren't, just return.
2928
2929      We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
2930      affected by gdbarch_decr_pc_after_break.  Other waitkinds which are
2931      implemented by software breakpoints should be handled through the normal
2932      breakpoint layer.
2933
2934      NOTE drow/2004-01-31: On some targets, breakpoints may generate
2935      different signals (SIGILL or SIGEMT for instance), but it is less
2936      clear where the PC is pointing afterwards.  It may not match
2937      gdbarch_decr_pc_after_break.  I don't know any specific target that
2938      generates these signals at breakpoints (the code has been in GDB since at
2939      least 1992) so I can not guess how to handle them here.
2940
2941      In earlier versions of GDB, a target with 
2942      gdbarch_have_nonsteppable_watchpoint would have the PC after hitting a
2943      watchpoint affected by gdbarch_decr_pc_after_break.  I haven't found any
2944      target with both of these set in GDB history, and it seems unlikely to be
2945      correct, so gdbarch_have_nonsteppable_watchpoint is not checked here.  */
2946
2947   if (ecs->ws.kind != TARGET_WAITKIND_STOPPED)
2948     return;
2949
2950   if (ecs->ws.value.sig != GDB_SIGNAL_TRAP)
2951     return;
2952
2953   /* In reverse execution, when a breakpoint is hit, the instruction
2954      under it has already been de-executed.  The reported PC always
2955      points at the breakpoint address, so adjusting it further would
2956      be wrong.  E.g., consider this case on a decr_pc_after_break == 1
2957      architecture:
2958
2959        B1         0x08000000 :   INSN1
2960        B2         0x08000001 :   INSN2
2961                   0x08000002 :   INSN3
2962             PC -> 0x08000003 :   INSN4
2963
2964      Say you're stopped at 0x08000003 as above.  Reverse continuing
2965      from that point should hit B2 as below.  Reading the PC when the
2966      SIGTRAP is reported should read 0x08000001 and INSN2 should have
2967      been de-executed already.
2968
2969        B1         0x08000000 :   INSN1
2970        B2   PC -> 0x08000001 :   INSN2
2971                   0x08000002 :   INSN3
2972                   0x08000003 :   INSN4
2973
2974      We can't apply the same logic as for forward execution, because
2975      we would wrongly adjust the PC to 0x08000000, since there's a
2976      breakpoint at PC - 1.  We'd then report a hit on B1, although
2977      INSN1 hadn't been de-executed yet.  Doing nothing is the correct
2978      behaviour.  */
2979   if (execution_direction == EXEC_REVERSE)
2980     return;
2981
2982   /* If this target does not decrement the PC after breakpoints, then
2983      we have nothing to do.  */
2984   regcache = get_thread_regcache (ecs->ptid);
2985   gdbarch = get_regcache_arch (regcache);
2986   if (gdbarch_decr_pc_after_break (gdbarch) == 0)
2987     return;
2988
2989   aspace = get_regcache_aspace (regcache);
2990
2991   /* Find the location where (if we've hit a breakpoint) the
2992      breakpoint would be.  */
2993   breakpoint_pc = regcache_read_pc (regcache)
2994                   - gdbarch_decr_pc_after_break (gdbarch);
2995
2996   /* Check whether there actually is a software breakpoint inserted at
2997      that location.
2998
2999      If in non-stop mode, a race condition is possible where we've
3000      removed a breakpoint, but stop events for that breakpoint were
3001      already queued and arrive later.  To suppress those spurious
3002      SIGTRAPs, we keep a list of such breakpoint locations for a bit,
3003      and retire them after a number of stop events are reported.  */
3004   if (software_breakpoint_inserted_here_p (aspace, breakpoint_pc)
3005       || (non_stop && moribund_breakpoint_here_p (aspace, breakpoint_pc)))
3006     {
3007       struct cleanup *old_cleanups = NULL;
3008
3009       if (RECORD_IS_USED)
3010         old_cleanups = record_full_gdb_operation_disable_set ();
3011
3012       /* When using hardware single-step, a SIGTRAP is reported for both
3013          a completed single-step and a software breakpoint.  Need to
3014          differentiate between the two, as the latter needs adjusting
3015          but the former does not.
3016
3017          The SIGTRAP can be due to a completed hardware single-step only if 
3018           - we didn't insert software single-step breakpoints
3019           - the thread to be examined is still the current thread
3020           - this thread is currently being stepped
3021
3022          If any of these events did not occur, we must have stopped due
3023          to hitting a software breakpoint, and have to back up to the
3024          breakpoint address.
3025
3026          As a special case, we could have hardware single-stepped a
3027          software breakpoint.  In this case (prev_pc == breakpoint_pc),
3028          we also need to back up to the breakpoint address.  */
3029
3030       if (singlestep_breakpoints_inserted_p
3031           || !ptid_equal (ecs->ptid, inferior_ptid)
3032           || !currently_stepping (ecs->event_thread)
3033           || ecs->event_thread->prev_pc == breakpoint_pc)
3034         regcache_write_pc (regcache, breakpoint_pc);
3035
3036       if (RECORD_IS_USED)
3037         do_cleanups (old_cleanups);
3038     }
3039 }
3040
3041 static void
3042 init_infwait_state (void)
3043 {
3044   waiton_ptid = pid_to_ptid (-1);
3045   infwait_state = infwait_normal_state;
3046 }
3047
3048 static int
3049 stepped_in_from (struct frame_info *frame, struct frame_id step_frame_id)
3050 {
3051   for (frame = get_prev_frame (frame);
3052        frame != NULL;
3053        frame = get_prev_frame (frame))
3054     {
3055       if (frame_id_eq (get_frame_id (frame), step_frame_id))
3056         return 1;
3057       if (get_frame_type (frame) != INLINE_FRAME)
3058         break;
3059     }
3060
3061   return 0;
3062 }
3063
3064 /* Auxiliary function that handles syscall entry/return events.
3065    It returns 1 if the inferior should keep going (and GDB
3066    should ignore the event), or 0 if the event deserves to be
3067    processed.  */
3068
3069 static int
3070 handle_syscall_event (struct execution_control_state *ecs)
3071 {
3072   struct regcache *regcache;
3073   int syscall_number;
3074
3075   if (!ptid_equal (ecs->ptid, inferior_ptid))
3076     context_switch (ecs->ptid);
3077
3078   regcache = get_thread_regcache (ecs->ptid);
3079   syscall_number = ecs->ws.value.syscall_number;
3080   stop_pc = regcache_read_pc (regcache);
3081
3082   if (catch_syscall_enabled () > 0
3083       && catching_syscall_number (syscall_number) > 0)
3084     {
3085       enum bpstat_signal_value sval;
3086
3087       if (debug_infrun)
3088         fprintf_unfiltered (gdb_stdlog, "infrun: syscall number = '%d'\n",
3089                             syscall_number);
3090
3091       ecs->event_thread->control.stop_bpstat
3092         = bpstat_stop_status (get_regcache_aspace (regcache),
3093                               stop_pc, ecs->ptid, &ecs->ws);
3094
3095       sval = bpstat_explains_signal (ecs->event_thread->control.stop_bpstat);
3096       ecs->random_signal = sval == BPSTAT_SIGNAL_NO;
3097
3098       if (!ecs->random_signal)
3099         {
3100           /* Catchpoint hit.  */
3101           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_TRAP;
3102           return 0;
3103         }
3104     }
3105
3106   /* If no catchpoint triggered for this, then keep going.  */
3107   ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
3108   keep_going (ecs);
3109   return 1;
3110 }
3111
3112 /* Clear the supplied execution_control_state's stop_func_* fields.  */
3113
3114 static void
3115 clear_stop_func (struct execution_control_state *ecs)
3116 {
3117   ecs->stop_func_filled_in = 0;
3118   ecs->stop_func_start = 0;
3119   ecs->stop_func_end = 0;
3120   ecs->stop_func_name = NULL;
3121 }
3122
3123 /* Lazily fill in the execution_control_state's stop_func_* fields.  */
3124
3125 static void
3126 fill_in_stop_func (struct gdbarch *gdbarch,
3127                    struct execution_control_state *ecs)
3128 {
3129   if (!ecs->stop_func_filled_in)
3130     {
3131       /* Don't care about return value; stop_func_start and stop_func_name
3132          will both be 0 if it doesn't work.  */
3133       find_pc_partial_function (stop_pc, &ecs->stop_func_name,
3134                                 &ecs->stop_func_start, &ecs->stop_func_end);
3135       ecs->stop_func_start
3136         += gdbarch_deprecated_function_start_offset (gdbarch);
3137
3138       ecs->stop_func_filled_in = 1;
3139     }
3140 }
3141
3142 /* Given an execution control state that has been freshly filled in
3143    by an event from the inferior, figure out what it means and take
3144    appropriate action.  */
3145
3146 static void
3147 handle_inferior_event (struct execution_control_state *ecs)
3148 {
3149   struct frame_info *frame;
3150   struct gdbarch *gdbarch;
3151   int stopped_by_watchpoint;
3152   int stepped_after_stopped_by_watchpoint = 0;
3153   struct symtab_and_line stop_pc_sal;
3154   enum stop_kind stop_soon;
3155
3156   if (ecs->ws.kind == TARGET_WAITKIND_IGNORE)
3157     {
3158       /* We had an event in the inferior, but we are not interested in
3159          handling it at this level.  The lower layers have already
3160          done what needs to be done, if anything.
3161
3162          One of the possible circumstances for this is when the
3163          inferior produces output for the console.  The inferior has
3164          not stopped, and we are ignoring the event.  Another possible
3165          circumstance is any event which the lower level knows will be
3166          reported multiple times without an intervening resume.  */
3167       if (debug_infrun)
3168         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_IGNORE\n");
3169       prepare_to_wait (ecs);
3170       return;
3171     }
3172
3173   if (ecs->ws.kind == TARGET_WAITKIND_NO_RESUMED
3174       && target_can_async_p () && !sync_execution)
3175     {
3176       /* There were no unwaited-for children left in the target, but,
3177          we're not synchronously waiting for events either.  Just
3178          ignore.  Otherwise, if we were running a synchronous
3179          execution command, we need to cancel it and give the user
3180          back the terminal.  */
3181       if (debug_infrun)
3182         fprintf_unfiltered (gdb_stdlog,
3183                             "infrun: TARGET_WAITKIND_NO_RESUMED (ignoring)\n");
3184       prepare_to_wait (ecs);
3185       return;
3186     }
3187
3188   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
3189       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
3190       && ecs->ws.kind != TARGET_WAITKIND_NO_RESUMED)
3191     {
3192       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
3193
3194       gdb_assert (inf);
3195       stop_soon = inf->control.stop_soon;
3196     }
3197   else
3198     stop_soon = NO_STOP_QUIETLY;
3199
3200   /* Cache the last pid/waitstatus.  */
3201   target_last_wait_ptid = ecs->ptid;
3202   target_last_waitstatus = ecs->ws;
3203
3204   /* Always clear state belonging to the previous time we stopped.  */
3205   stop_stack_dummy = STOP_NONE;
3206
3207   if (ecs->ws.kind == TARGET_WAITKIND_NO_RESUMED)
3208     {
3209       /* No unwaited-for children left.  IOW, all resumed children
3210          have exited.  */
3211       if (debug_infrun)
3212         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_NO_RESUMED\n");
3213
3214       stop_print_frame = 0;
3215       stop_stepping (ecs);
3216       return;
3217     }
3218
3219   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
3220       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
3221     {
3222       ecs->event_thread = find_thread_ptid (ecs->ptid);
3223       /* If it's a new thread, add it to the thread database.  */
3224       if (ecs->event_thread == NULL)
3225         ecs->event_thread = add_thread (ecs->ptid);
3226     }
3227
3228   /* Dependent on valid ECS->EVENT_THREAD.  */
3229   adjust_pc_after_break (ecs);
3230
3231   /* Dependent on the current PC value modified by adjust_pc_after_break.  */
3232   reinit_frame_cache ();
3233
3234   breakpoint_retire_moribund ();
3235
3236   /* First, distinguish signals caused by the debugger from signals
3237      that have to do with the program's own actions.  Note that
3238      breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
3239      on the operating system version.  Here we detect when a SIGILL or
3240      SIGEMT is really a breakpoint and change it to SIGTRAP.  We do
3241      something similar for SIGSEGV, since a SIGSEGV will be generated
3242      when we're trying to execute a breakpoint instruction on a
3243      non-executable stack.  This happens for call dummy breakpoints
3244      for architectures like SPARC that place call dummies on the
3245      stack.  */
3246   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED
3247       && (ecs->ws.value.sig == GDB_SIGNAL_ILL
3248           || ecs->ws.value.sig == GDB_SIGNAL_SEGV
3249           || ecs->ws.value.sig == GDB_SIGNAL_EMT))
3250     {
3251       struct regcache *regcache = get_thread_regcache (ecs->ptid);
3252
3253       if (breakpoint_inserted_here_p (get_regcache_aspace (regcache),
3254                                       regcache_read_pc (regcache)))
3255         {
3256           if (debug_infrun)
3257             fprintf_unfiltered (gdb_stdlog,
3258                                 "infrun: Treating signal as SIGTRAP\n");
3259           ecs->ws.value.sig = GDB_SIGNAL_TRAP;
3260         }
3261     }
3262
3263   /* Mark the non-executing threads accordingly.  In all-stop, all
3264      threads of all processes are stopped when we get any event
3265      reported.  In non-stop mode, only the event thread stops.  If
3266      we're handling a process exit in non-stop mode, there's nothing
3267      to do, as threads of the dead process are gone, and threads of
3268      any other process were left running.  */
3269   if (!non_stop)
3270     set_executing (minus_one_ptid, 0);
3271   else if (ecs->ws.kind != TARGET_WAITKIND_SIGNALLED
3272            && ecs->ws.kind != TARGET_WAITKIND_EXITED)
3273     set_executing (ecs->ptid, 0);
3274
3275   switch (infwait_state)
3276     {
3277     case infwait_thread_hop_state:
3278       if (debug_infrun)
3279         fprintf_unfiltered (gdb_stdlog, "infrun: infwait_thread_hop_state\n");
3280       break;
3281
3282     case infwait_normal_state:
3283       if (debug_infrun)
3284         fprintf_unfiltered (gdb_stdlog, "infrun: infwait_normal_state\n");
3285       break;
3286
3287     case infwait_step_watch_state:
3288       if (debug_infrun)
3289         fprintf_unfiltered (gdb_stdlog,
3290                             "infrun: infwait_step_watch_state\n");
3291
3292       stepped_after_stopped_by_watchpoint = 1;
3293       break;
3294
3295     case infwait_nonstep_watch_state:
3296       if (debug_infrun)
3297         fprintf_unfiltered (gdb_stdlog,
3298                             "infrun: infwait_nonstep_watch_state\n");
3299       insert_breakpoints ();
3300
3301       /* FIXME-maybe: is this cleaner than setting a flag?  Does it
3302          handle things like signals arriving and other things happening
3303          in combination correctly?  */
3304       stepped_after_stopped_by_watchpoint = 1;
3305       break;
3306
3307     default:
3308       internal_error (__FILE__, __LINE__, _("bad switch"));
3309     }
3310
3311   infwait_state = infwait_normal_state;
3312   waiton_ptid = pid_to_ptid (-1);
3313
3314   switch (ecs->ws.kind)
3315     {
3316     case TARGET_WAITKIND_LOADED:
3317       if (debug_infrun)
3318         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_LOADED\n");
3319       /* Ignore gracefully during startup of the inferior, as it might
3320          be the shell which has just loaded some objects, otherwise
3321          add the symbols for the newly loaded objects.  Also ignore at
3322          the beginning of an attach or remote session; we will query
3323          the full list of libraries once the connection is
3324          established.  */
3325       if (stop_soon == NO_STOP_QUIETLY)
3326         {
3327           struct regcache *regcache;
3328           enum bpstat_signal_value sval;
3329
3330           if (!ptid_equal (ecs->ptid, inferior_ptid))
3331             context_switch (ecs->ptid);
3332           regcache = get_thread_regcache (ecs->ptid);
3333
3334           handle_solib_event ();
3335
3336           ecs->event_thread->control.stop_bpstat
3337             = bpstat_stop_status (get_regcache_aspace (regcache),
3338                                   stop_pc, ecs->ptid, &ecs->ws);
3339
3340           sval
3341             = bpstat_explains_signal (ecs->event_thread->control.stop_bpstat);
3342           ecs->random_signal = sval == BPSTAT_SIGNAL_NO;
3343
3344           if (!ecs->random_signal)
3345             {
3346               /* A catchpoint triggered.  */
3347               ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_TRAP;
3348               goto process_event_stop_test;
3349             }
3350
3351           /* If requested, stop when the dynamic linker notifies
3352              gdb of events.  This allows the user to get control
3353              and place breakpoints in initializer routines for
3354              dynamically loaded objects (among other things).  */
3355           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
3356           if (stop_on_solib_events)
3357             {
3358               /* Make sure we print "Stopped due to solib-event" in
3359                  normal_stop.  */
3360               stop_print_frame = 1;
3361
3362               stop_stepping (ecs);
3363               return;
3364             }
3365         }
3366
3367       /* If we are skipping through a shell, or through shared library
3368          loading that we aren't interested in, resume the program.  If
3369          we're running the program normally, also resume.  But stop if
3370          we're attaching or setting up a remote connection.  */
3371       if (stop_soon == STOP_QUIETLY || stop_soon == NO_STOP_QUIETLY)
3372         {
3373           if (!ptid_equal (ecs->ptid, inferior_ptid))
3374             context_switch (ecs->ptid);
3375
3376           /* Loading of shared libraries might have changed breakpoint
3377              addresses.  Make sure new breakpoints are inserted.  */
3378           if (stop_soon == NO_STOP_QUIETLY
3379               && !breakpoints_always_inserted_mode ())
3380             insert_breakpoints ();
3381           resume (0, GDB_SIGNAL_0);
3382           prepare_to_wait (ecs);
3383           return;
3384         }
3385
3386       break;
3387
3388     case TARGET_WAITKIND_SPURIOUS:
3389       if (debug_infrun)
3390         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SPURIOUS\n");
3391       if (!ptid_equal (ecs->ptid, inferior_ptid))
3392         context_switch (ecs->ptid);
3393       resume (0, GDB_SIGNAL_0);
3394       prepare_to_wait (ecs);
3395       return;
3396
3397     case TARGET_WAITKIND_EXITED:
3398     case TARGET_WAITKIND_SIGNALLED:
3399       if (debug_infrun)
3400         {
3401           if (ecs->ws.kind == TARGET_WAITKIND_EXITED)
3402             fprintf_unfiltered (gdb_stdlog,
3403                                 "infrun: TARGET_WAITKIND_EXITED\n");
3404           else
3405             fprintf_unfiltered (gdb_stdlog,
3406                                 "infrun: TARGET_WAITKIND_SIGNALLED\n");
3407         }
3408
3409       inferior_ptid = ecs->ptid;
3410       set_current_inferior (find_inferior_pid (ptid_get_pid (ecs->ptid)));
3411       set_current_program_space (current_inferior ()->pspace);
3412       handle_vfork_child_exec_or_exit (0);
3413       target_terminal_ours ();  /* Must do this before mourn anyway.  */
3414
3415       if (ecs->ws.kind == TARGET_WAITKIND_EXITED)
3416         {
3417           /* Record the exit code in the convenience variable $_exitcode, so
3418              that the user can inspect this again later.  */
3419           set_internalvar_integer (lookup_internalvar ("_exitcode"),
3420                                    (LONGEST) ecs->ws.value.integer);
3421
3422           /* Also record this in the inferior itself.  */
3423           current_inferior ()->has_exit_code = 1;
3424           current_inferior ()->exit_code = (LONGEST) ecs->ws.value.integer;
3425
3426           print_exited_reason (ecs->ws.value.integer);
3427         }
3428       else
3429         print_signal_exited_reason (ecs->ws.value.sig);
3430
3431       gdb_flush (gdb_stdout);
3432       target_mourn_inferior ();
3433       singlestep_breakpoints_inserted_p = 0;
3434       cancel_single_step_breakpoints ();
3435       stop_print_frame = 0;
3436       stop_stepping (ecs);
3437       return;
3438
3439       /* The following are the only cases in which we keep going;
3440          the above cases end in a continue or goto.  */
3441     case TARGET_WAITKIND_FORKED:
3442     case TARGET_WAITKIND_VFORKED:
3443       if (debug_infrun)
3444         {
3445           if (ecs->ws.kind == TARGET_WAITKIND_FORKED)
3446             fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_FORKED\n");
3447           else
3448             fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_VFORKED\n");
3449         }
3450
3451       /* Check whether the inferior is displaced stepping.  */
3452       {
3453         struct regcache *regcache = get_thread_regcache (ecs->ptid);
3454         struct gdbarch *gdbarch = get_regcache_arch (regcache);
3455         struct displaced_step_inferior_state *displaced
3456           = get_displaced_stepping_state (ptid_get_pid (ecs->ptid));
3457
3458         /* If checking displaced stepping is supported, and thread
3459            ecs->ptid is displaced stepping.  */
3460         if (displaced && ptid_equal (displaced->step_ptid, ecs->ptid))
3461           {
3462             struct inferior *parent_inf
3463               = find_inferior_pid (ptid_get_pid (ecs->ptid));
3464             struct regcache *child_regcache;
3465             CORE_ADDR parent_pc;
3466
3467             /* GDB has got TARGET_WAITKIND_FORKED or TARGET_WAITKIND_VFORKED,
3468                indicating that the displaced stepping of syscall instruction
3469                has been done.  Perform cleanup for parent process here.  Note
3470                that this operation also cleans up the child process for vfork,
3471                because their pages are shared.  */
3472             displaced_step_fixup (ecs->ptid, GDB_SIGNAL_TRAP);
3473
3474             if (ecs->ws.kind == TARGET_WAITKIND_FORKED)
3475               {
3476                 /* Restore scratch pad for child process.  */
3477                 displaced_step_restore (displaced, ecs->ws.value.related_pid);
3478               }
3479
3480             /* Since the vfork/fork syscall instruction was executed in the scratchpad,
3481                the child's PC is also within the scratchpad.  Set the child's PC
3482                to the parent's PC value, which has already been fixed up.
3483                FIXME: we use the parent's aspace here, although we're touching
3484                the child, because the child hasn't been added to the inferior
3485                list yet at this point.  */
3486
3487             child_regcache
3488               = get_thread_arch_aspace_regcache (ecs->ws.value.related_pid,
3489                                                  gdbarch,
3490                                                  parent_inf->aspace);
3491             /* Read PC value of parent process.  */
3492             parent_pc = regcache_read_pc (regcache);
3493
3494             if (debug_displaced)
3495               fprintf_unfiltered (gdb_stdlog,
3496                                   "displaced: write child pc from %s to %s\n",
3497                                   paddress (gdbarch,
3498                                             regcache_read_pc (child_regcache)),
3499                                   paddress (gdbarch, parent_pc));
3500
3501             regcache_write_pc (child_regcache, parent_pc);
3502           }
3503       }
3504
3505       if (!ptid_equal (ecs->ptid, inferior_ptid))
3506         context_switch (ecs->ptid);
3507
3508       /* Immediately detach breakpoints from the child before there's
3509          any chance of letting the user delete breakpoints from the
3510          breakpoint lists.  If we don't do this early, it's easy to
3511          leave left over traps in the child, vis: "break foo; catch
3512          fork; c; <fork>; del; c; <child calls foo>".  We only follow
3513          the fork on the last `continue', and by that time the
3514          breakpoint at "foo" is long gone from the breakpoint table.
3515          If we vforked, then we don't need to unpatch here, since both
3516          parent and child are sharing the same memory pages; we'll
3517          need to unpatch at follow/detach time instead to be certain
3518          that new breakpoints added between catchpoint hit time and
3519          vfork follow are detached.  */
3520       if (ecs->ws.kind != TARGET_WAITKIND_VFORKED)
3521         {
3522           /* This won't actually modify the breakpoint list, but will
3523              physically remove the breakpoints from the child.  */
3524           detach_breakpoints (ecs->ws.value.related_pid);
3525         }
3526
3527       if (singlestep_breakpoints_inserted_p)
3528         {
3529           /* Pull the single step breakpoints out of the target.  */
3530           remove_single_step_breakpoints ();
3531           singlestep_breakpoints_inserted_p = 0;
3532         }
3533
3534       /* In case the event is caught by a catchpoint, remember that
3535          the event is to be followed at the next resume of the thread,
3536          and not immediately.  */
3537       ecs->event_thread->pending_follow = ecs->ws;
3538
3539       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3540
3541       ecs->event_thread->control.stop_bpstat
3542         = bpstat_stop_status (get_regcache_aspace (get_current_regcache ()),
3543                               stop_pc, ecs->ptid, &ecs->ws);
3544
3545       /* Note that we're interested in knowing the bpstat actually
3546          causes a stop, not just if it may explain the signal.
3547          Software watchpoints, for example, always appear in the
3548          bpstat.  */
3549       ecs->random_signal
3550         = !bpstat_causes_stop (ecs->event_thread->control.stop_bpstat);
3551
3552       /* If no catchpoint triggered for this, then keep going.  */
3553       if (ecs->random_signal)
3554         {
3555           ptid_t parent;
3556           ptid_t child;
3557           int should_resume;
3558           int follow_child
3559             = (follow_fork_mode_string == follow_fork_mode_child);
3560
3561           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
3562
3563           should_resume = follow_fork ();
3564
3565           parent = ecs->ptid;
3566           child = ecs->ws.value.related_pid;
3567
3568           /* In non-stop mode, also resume the other branch.  */
3569           if (non_stop && !detach_fork)
3570             {
3571               if (follow_child)
3572                 switch_to_thread (parent);
3573               else
3574                 switch_to_thread (child);
3575
3576               ecs->event_thread = inferior_thread ();
3577               ecs->ptid = inferior_ptid;
3578               keep_going (ecs);
3579             }
3580
3581           if (follow_child)
3582             switch_to_thread (child);
3583           else
3584             switch_to_thread (parent);
3585
3586           ecs->event_thread = inferior_thread ();
3587           ecs->ptid = inferior_ptid;
3588
3589           if (should_resume)
3590             keep_going (ecs);
3591           else
3592             stop_stepping (ecs);
3593           return;
3594         }
3595       ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_TRAP;
3596       goto process_event_stop_test;
3597
3598     case TARGET_WAITKIND_VFORK_DONE:
3599       /* Done with the shared memory region.  Re-insert breakpoints in
3600          the parent, and keep going.  */
3601
3602       if (debug_infrun)
3603         fprintf_unfiltered (gdb_stdlog,
3604                             "infrun: TARGET_WAITKIND_VFORK_DONE\n");
3605
3606       if (!ptid_equal (ecs->ptid, inferior_ptid))
3607         context_switch (ecs->ptid);
3608
3609       current_inferior ()->waiting_for_vfork_done = 0;
3610       current_inferior ()->pspace->breakpoints_not_allowed = 0;
3611       /* This also takes care of reinserting breakpoints in the
3612          previously locked inferior.  */
3613       keep_going (ecs);
3614       return;
3615
3616     case TARGET_WAITKIND_EXECD:
3617       if (debug_infrun)
3618         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXECD\n");
3619
3620       if (!ptid_equal (ecs->ptid, inferior_ptid))
3621         context_switch (ecs->ptid);
3622
3623       singlestep_breakpoints_inserted_p = 0;
3624       cancel_single_step_breakpoints ();
3625
3626       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3627
3628       /* Do whatever is necessary to the parent branch of the vfork.  */
3629       handle_vfork_child_exec_or_exit (1);
3630
3631       /* This causes the eventpoints and symbol table to be reset.
3632          Must do this now, before trying to determine whether to
3633          stop.  */
3634       follow_exec (inferior_ptid, ecs->ws.value.execd_pathname);
3635
3636       ecs->event_thread->control.stop_bpstat
3637         = bpstat_stop_status (get_regcache_aspace (get_current_regcache ()),
3638                               stop_pc, ecs->ptid, &ecs->ws);
3639       ecs->random_signal
3640         = (bpstat_explains_signal (ecs->event_thread->control.stop_bpstat)
3641            == BPSTAT_SIGNAL_NO);
3642
3643       /* Note that this may be referenced from inside
3644          bpstat_stop_status above, through inferior_has_execd.  */
3645       xfree (ecs->ws.value.execd_pathname);
3646       ecs->ws.value.execd_pathname = NULL;
3647
3648       /* If no catchpoint triggered for this, then keep going.  */
3649       if (ecs->random_signal)
3650         {
3651           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
3652           keep_going (ecs);
3653           return;
3654         }
3655       ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_TRAP;
3656       goto process_event_stop_test;
3657
3658       /* Be careful not to try to gather much state about a thread
3659          that's in a syscall.  It's frequently a losing proposition.  */
3660     case TARGET_WAITKIND_SYSCALL_ENTRY:
3661       if (debug_infrun)
3662         fprintf_unfiltered (gdb_stdlog,
3663                             "infrun: TARGET_WAITKIND_SYSCALL_ENTRY\n");
3664       /* Getting the current syscall number.  */
3665       if (handle_syscall_event (ecs) != 0)
3666         return;
3667       goto process_event_stop_test;
3668
3669       /* Before examining the threads further, step this thread to
3670          get it entirely out of the syscall.  (We get notice of the
3671          event when the thread is just on the verge of exiting a
3672          syscall.  Stepping one instruction seems to get it back
3673          into user code.)  */
3674     case TARGET_WAITKIND_SYSCALL_RETURN:
3675       if (debug_infrun)
3676         fprintf_unfiltered (gdb_stdlog,
3677                             "infrun: TARGET_WAITKIND_SYSCALL_RETURN\n");
3678       if (handle_syscall_event (ecs) != 0)
3679         return;
3680       goto process_event_stop_test;
3681
3682     case TARGET_WAITKIND_STOPPED:
3683       if (debug_infrun)
3684         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_STOPPED\n");
3685       ecs->event_thread->suspend.stop_signal = ecs->ws.value.sig;
3686       break;
3687
3688     case TARGET_WAITKIND_NO_HISTORY:
3689       if (debug_infrun)
3690         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_NO_HISTORY\n");
3691       /* Reverse execution: target ran out of history info.  */
3692
3693       /* Pull the single step breakpoints out of the target.  */
3694       if (singlestep_breakpoints_inserted_p)
3695         {
3696           if (!ptid_equal (ecs->ptid, inferior_ptid))
3697             context_switch (ecs->ptid);
3698           remove_single_step_breakpoints ();
3699           singlestep_breakpoints_inserted_p = 0;
3700         }
3701       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3702       print_no_history_reason ();
3703       stop_stepping (ecs);
3704       return;
3705     }
3706
3707   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED)
3708     {
3709       /* Do we need to clean up the state of a thread that has
3710          completed a displaced single-step?  (Doing so usually affects
3711          the PC, so do it here, before we set stop_pc.)  */
3712       displaced_step_fixup (ecs->ptid,
3713                             ecs->event_thread->suspend.stop_signal);
3714
3715       /* If we either finished a single-step or hit a breakpoint, but
3716          the user wanted this thread to be stopped, pretend we got a
3717          SIG0 (generic unsignaled stop).  */
3718
3719       if (ecs->event_thread->stop_requested
3720           && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
3721         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
3722     }
3723
3724   stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
3725
3726   if (debug_infrun)
3727     {
3728       struct regcache *regcache = get_thread_regcache (ecs->ptid);
3729       struct gdbarch *gdbarch = get_regcache_arch (regcache);
3730       struct cleanup *old_chain = save_inferior_ptid ();
3731
3732       inferior_ptid = ecs->ptid;
3733
3734       fprintf_unfiltered (gdb_stdlog, "infrun: stop_pc = %s\n",
3735                           paddress (gdbarch, stop_pc));
3736       if (target_stopped_by_watchpoint ())
3737         {
3738           CORE_ADDR addr;
3739
3740           fprintf_unfiltered (gdb_stdlog, "infrun: stopped by watchpoint\n");
3741
3742           if (target_stopped_data_address (&current_target, &addr))
3743             fprintf_unfiltered (gdb_stdlog,
3744                                 "infrun: stopped data address = %s\n",
3745                                 paddress (gdbarch, addr));
3746           else
3747             fprintf_unfiltered (gdb_stdlog,
3748                                 "infrun: (no data address available)\n");
3749         }
3750
3751       do_cleanups (old_chain);
3752     }
3753
3754   if (stepping_past_singlestep_breakpoint)
3755     {
3756       gdb_assert (singlestep_breakpoints_inserted_p);
3757       gdb_assert (ptid_equal (singlestep_ptid, ecs->ptid));
3758       gdb_assert (!ptid_equal (singlestep_ptid, saved_singlestep_ptid));
3759
3760       stepping_past_singlestep_breakpoint = 0;
3761
3762       /* We've either finished single-stepping past the single-step
3763          breakpoint, or stopped for some other reason.  It would be nice if
3764          we could tell, but we can't reliably.  */
3765       if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
3766         {
3767           if (debug_infrun)
3768             fprintf_unfiltered (gdb_stdlog,
3769                                 "infrun: stepping_past_"
3770                                 "singlestep_breakpoint\n");
3771           /* Pull the single step breakpoints out of the target.  */
3772           if (!ptid_equal (ecs->ptid, inferior_ptid))
3773             context_switch (ecs->ptid);
3774           remove_single_step_breakpoints ();
3775           singlestep_breakpoints_inserted_p = 0;
3776
3777           ecs->random_signal = 0;
3778           ecs->event_thread->control.trap_expected = 0;
3779
3780           context_switch (saved_singlestep_ptid);
3781           if (deprecated_context_hook)
3782             deprecated_context_hook (pid_to_thread_id (saved_singlestep_ptid));
3783
3784           resume (1, GDB_SIGNAL_0);
3785           prepare_to_wait (ecs);
3786           return;
3787         }
3788     }
3789
3790   if (!ptid_equal (deferred_step_ptid, null_ptid))
3791     {
3792       /* In non-stop mode, there's never a deferred_step_ptid set.  */
3793       gdb_assert (!non_stop);
3794
3795       /* If we stopped for some other reason than single-stepping, ignore
3796          the fact that we were supposed to switch back.  */
3797       if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
3798         {
3799           if (debug_infrun)
3800             fprintf_unfiltered (gdb_stdlog,
3801                                 "infrun: handling deferred step\n");
3802
3803           /* Pull the single step breakpoints out of the target.  */
3804           if (singlestep_breakpoints_inserted_p)
3805             {
3806               if (!ptid_equal (ecs->ptid, inferior_ptid))
3807                 context_switch (ecs->ptid);
3808               remove_single_step_breakpoints ();
3809               singlestep_breakpoints_inserted_p = 0;
3810             }
3811
3812           ecs->event_thread->control.trap_expected = 0;
3813
3814           context_switch (deferred_step_ptid);
3815           deferred_step_ptid = null_ptid;
3816           /* Suppress spurious "Switching to ..." message.  */
3817           previous_inferior_ptid = inferior_ptid;
3818
3819           resume (1, GDB_SIGNAL_0);
3820           prepare_to_wait (ecs);
3821           return;
3822         }
3823
3824       deferred_step_ptid = null_ptid;
3825     }
3826
3827   /* See if a thread hit a thread-specific breakpoint that was meant for
3828      another thread.  If so, then step that thread past the breakpoint,
3829      and continue it.  */
3830
3831   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
3832     {
3833       int thread_hop_needed = 0;
3834       struct address_space *aspace = 
3835         get_regcache_aspace (get_thread_regcache (ecs->ptid));
3836
3837       /* Check if a regular breakpoint has been hit before checking
3838          for a potential single step breakpoint.  Otherwise, GDB will
3839          not see this breakpoint hit when stepping onto breakpoints.  */
3840       if (regular_breakpoint_inserted_here_p (aspace, stop_pc))
3841         {
3842           ecs->random_signal = 0;
3843           if (!breakpoint_thread_match (aspace, stop_pc, ecs->ptid))
3844             thread_hop_needed = 1;
3845         }
3846       else if (singlestep_breakpoints_inserted_p)
3847         {
3848           /* We have not context switched yet, so this should be true
3849              no matter which thread hit the singlestep breakpoint.  */
3850           gdb_assert (ptid_equal (inferior_ptid, singlestep_ptid));
3851           if (debug_infrun)
3852             fprintf_unfiltered (gdb_stdlog, "infrun: software single step "
3853                                 "trap for %s\n",
3854                                 target_pid_to_str (ecs->ptid));
3855
3856           ecs->random_signal = 0;
3857           /* The call to in_thread_list is necessary because PTIDs sometimes
3858              change when we go from single-threaded to multi-threaded.  If
3859              the singlestep_ptid is still in the list, assume that it is
3860              really different from ecs->ptid.  */
3861           if (!ptid_equal (singlestep_ptid, ecs->ptid)
3862               && in_thread_list (singlestep_ptid))
3863             {
3864               /* If the PC of the thread we were trying to single-step
3865                  has changed, discard this event (which we were going
3866                  to ignore anyway), and pretend we saw that thread
3867                  trap.  This prevents us continuously moving the
3868                  single-step breakpoint forward, one instruction at a
3869                  time.  If the PC has changed, then the thread we were
3870                  trying to single-step has trapped or been signalled,
3871                  but the event has not been reported to GDB yet.
3872
3873                  There might be some cases where this loses signal
3874                  information, if a signal has arrived at exactly the
3875                  same time that the PC changed, but this is the best
3876                  we can do with the information available.  Perhaps we
3877                  should arrange to report all events for all threads
3878                  when they stop, or to re-poll the remote looking for
3879                  this particular thread (i.e. temporarily enable
3880                  schedlock).  */
3881
3882              CORE_ADDR new_singlestep_pc
3883                = regcache_read_pc (get_thread_regcache (singlestep_ptid));
3884
3885              if (new_singlestep_pc != singlestep_pc)
3886                {
3887                  enum gdb_signal stop_signal;
3888
3889                  if (debug_infrun)
3890                    fprintf_unfiltered (gdb_stdlog, "infrun: unexpected thread,"
3891                                        " but expected thread advanced also\n");
3892
3893                  /* The current context still belongs to
3894                     singlestep_ptid.  Don't swap here, since that's
3895                     the context we want to use.  Just fudge our
3896                     state and continue.  */
3897                  stop_signal = ecs->event_thread->suspend.stop_signal;
3898                  ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
3899                  ecs->ptid = singlestep_ptid;
3900                  ecs->event_thread = find_thread_ptid (ecs->ptid);
3901                  ecs->event_thread->suspend.stop_signal = stop_signal;
3902                  stop_pc = new_singlestep_pc;
3903                }
3904              else
3905                {
3906                  if (debug_infrun)
3907                    fprintf_unfiltered (gdb_stdlog,
3908                                        "infrun: unexpected thread\n");
3909
3910                  thread_hop_needed = 1;
3911                  stepping_past_singlestep_breakpoint = 1;
3912                  saved_singlestep_ptid = singlestep_ptid;
3913                }
3914             }
3915         }
3916
3917       if (thread_hop_needed)
3918         {
3919           struct regcache *thread_regcache;
3920           int remove_status = 0;
3921
3922           if (debug_infrun)
3923             fprintf_unfiltered (gdb_stdlog, "infrun: thread_hop_needed\n");
3924
3925           /* Switch context before touching inferior memory, the
3926              previous thread may have exited.  */
3927           if (!ptid_equal (inferior_ptid, ecs->ptid))
3928             context_switch (ecs->ptid);
3929
3930           /* Saw a breakpoint, but it was hit by the wrong thread.
3931              Just continue.  */
3932
3933           if (singlestep_breakpoints_inserted_p)
3934             {
3935               /* Pull the single step breakpoints out of the target.  */
3936               remove_single_step_breakpoints ();
3937               singlestep_breakpoints_inserted_p = 0;
3938             }
3939
3940           /* If the arch can displace step, don't remove the
3941              breakpoints.  */
3942           thread_regcache = get_thread_regcache (ecs->ptid);
3943           if (!use_displaced_stepping (get_regcache_arch (thread_regcache)))
3944             remove_status = remove_breakpoints ();
3945
3946           /* Did we fail to remove breakpoints?  If so, try
3947              to set the PC past the bp.  (There's at least
3948              one situation in which we can fail to remove
3949              the bp's: On HP-UX's that use ttrace, we can't
3950              change the address space of a vforking child
3951              process until the child exits (well, okay, not
3952              then either :-) or execs.  */
3953           if (remove_status != 0)
3954             error (_("Cannot step over breakpoint hit in wrong thread"));
3955           else
3956             {                   /* Single step */
3957               if (!non_stop)
3958                 {
3959                   /* Only need to require the next event from this
3960                      thread in all-stop mode.  */
3961                   waiton_ptid = ecs->ptid;
3962                   infwait_state = infwait_thread_hop_state;
3963                 }
3964
3965               ecs->event_thread->stepping_over_breakpoint = 1;
3966               keep_going (ecs);
3967               return;
3968             }
3969         }
3970       else if (singlestep_breakpoints_inserted_p)
3971         {
3972           ecs->random_signal = 0;
3973         }
3974     }
3975   else
3976     ecs->random_signal = 1;
3977
3978   /* See if something interesting happened to the non-current thread.  If
3979      so, then switch to that thread.  */
3980   if (!ptid_equal (ecs->ptid, inferior_ptid))
3981     {
3982       if (debug_infrun)
3983         fprintf_unfiltered (gdb_stdlog, "infrun: context switch\n");
3984
3985       context_switch (ecs->ptid);
3986
3987       if (deprecated_context_hook)
3988         deprecated_context_hook (pid_to_thread_id (ecs->ptid));
3989     }
3990
3991   /* At this point, get hold of the now-current thread's frame.  */
3992   frame = get_current_frame ();
3993   gdbarch = get_frame_arch (frame);
3994
3995   if (singlestep_breakpoints_inserted_p)
3996     {
3997       /* Pull the single step breakpoints out of the target.  */
3998       remove_single_step_breakpoints ();
3999       singlestep_breakpoints_inserted_p = 0;
4000     }
4001
4002   if (stepped_after_stopped_by_watchpoint)
4003     stopped_by_watchpoint = 0;
4004   else
4005     stopped_by_watchpoint = watchpoints_triggered (&ecs->ws);
4006
4007   /* If necessary, step over this watchpoint.  We'll be back to display
4008      it in a moment.  */
4009   if (stopped_by_watchpoint
4010       && (target_have_steppable_watchpoint
4011           || gdbarch_have_nonsteppable_watchpoint (gdbarch)))
4012     {
4013       /* At this point, we are stopped at an instruction which has
4014          attempted to write to a piece of memory under control of
4015          a watchpoint.  The instruction hasn't actually executed
4016          yet.  If we were to evaluate the watchpoint expression
4017          now, we would get the old value, and therefore no change
4018          would seem to have occurred.
4019
4020          In order to make watchpoints work `right', we really need
4021          to complete the memory write, and then evaluate the
4022          watchpoint expression.  We do this by single-stepping the
4023          target.
4024
4025          It may not be necessary to disable the watchpoint to stop over
4026          it.  For example, the PA can (with some kernel cooperation)
4027          single step over a watchpoint without disabling the watchpoint.
4028
4029          It is far more common to need to disable a watchpoint to step
4030          the inferior over it.  If we have non-steppable watchpoints,
4031          we must disable the current watchpoint; it's simplest to
4032          disable all watchpoints and breakpoints.  */
4033       int hw_step = 1;
4034
4035       if (!target_have_steppable_watchpoint)
4036         {
4037           remove_breakpoints ();
4038           /* See comment in resume why we need to stop bypassing signals
4039              while breakpoints have been removed.  */
4040           target_pass_signals (0, NULL);
4041         }
4042         /* Single step */
4043       hw_step = maybe_software_singlestep (gdbarch, stop_pc);
4044       target_resume (ecs->ptid, hw_step, GDB_SIGNAL_0);
4045       waiton_ptid = ecs->ptid;
4046       if (target_have_steppable_watchpoint)
4047         infwait_state = infwait_step_watch_state;
4048       else
4049         infwait_state = infwait_nonstep_watch_state;
4050       prepare_to_wait (ecs);
4051       return;
4052     }
4053
4054   clear_stop_func (ecs);
4055   ecs->event_thread->stepping_over_breakpoint = 0;
4056   bpstat_clear (&ecs->event_thread->control.stop_bpstat);
4057   ecs->event_thread->control.stop_step = 0;
4058   stop_print_frame = 1;
4059   ecs->random_signal = 0;
4060   stopped_by_random_signal = 0;
4061
4062   /* Hide inlined functions starting here, unless we just performed stepi or
4063      nexti.  After stepi and nexti, always show the innermost frame (not any
4064      inline function call sites).  */
4065   if (ecs->event_thread->control.step_range_end != 1)
4066     {
4067       struct address_space *aspace = 
4068         get_regcache_aspace (get_thread_regcache (ecs->ptid));
4069
4070       /* skip_inline_frames is expensive, so we avoid it if we can
4071          determine that the address is one where functions cannot have
4072          been inlined.  This improves performance with inferiors that
4073          load a lot of shared libraries, because the solib event
4074          breakpoint is defined as the address of a function (i.e. not
4075          inline).  Note that we have to check the previous PC as well
4076          as the current one to catch cases when we have just
4077          single-stepped off a breakpoint prior to reinstating it.
4078          Note that we're assuming that the code we single-step to is
4079          not inline, but that's not definitive: there's nothing
4080          preventing the event breakpoint function from containing
4081          inlined code, and the single-step ending up there.  If the
4082          user had set a breakpoint on that inlined code, the missing
4083          skip_inline_frames call would break things.  Fortunately
4084          that's an extremely unlikely scenario.  */
4085       if (!pc_at_non_inline_function (aspace, stop_pc, &ecs->ws)
4086           && !(ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
4087                && ecs->event_thread->control.trap_expected
4088                && pc_at_non_inline_function (aspace,
4089                                              ecs->event_thread->prev_pc,
4090                                              &ecs->ws)))
4091         {
4092           skip_inline_frames (ecs->ptid);
4093
4094           /* Re-fetch current thread's frame in case that invalidated
4095              the frame cache.  */
4096           frame = get_current_frame ();
4097           gdbarch = get_frame_arch (frame);
4098         }
4099     }
4100
4101   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
4102       && ecs->event_thread->control.trap_expected
4103       && gdbarch_single_step_through_delay_p (gdbarch)
4104       && currently_stepping (ecs->event_thread))
4105     {
4106       /* We're trying to step off a breakpoint.  Turns out that we're
4107          also on an instruction that needs to be stepped multiple
4108          times before it's been fully executing.  E.g., architectures
4109          with a delay slot.  It needs to be stepped twice, once for
4110          the instruction and once for the delay slot.  */
4111       int step_through_delay
4112         = gdbarch_single_step_through_delay (gdbarch, frame);
4113
4114       if (debug_infrun && step_through_delay)
4115         fprintf_unfiltered (gdb_stdlog, "infrun: step through delay\n");
4116       if (ecs->event_thread->control.step_range_end == 0
4117           && step_through_delay)
4118         {
4119           /* The user issued a continue when stopped at a breakpoint.
4120              Set up for another trap and get out of here.  */
4121          ecs->event_thread->stepping_over_breakpoint = 1;
4122          keep_going (ecs);
4123          return;
4124         }
4125       else if (step_through_delay)
4126         {
4127           /* The user issued a step when stopped at a breakpoint.
4128              Maybe we should stop, maybe we should not - the delay
4129              slot *might* correspond to a line of source.  In any
4130              case, don't decide that here, just set 
4131              ecs->stepping_over_breakpoint, making sure we 
4132              single-step again before breakpoints are re-inserted.  */
4133           ecs->event_thread->stepping_over_breakpoint = 1;
4134         }
4135     }
4136
4137   /* Look at the cause of the stop, and decide what to do.
4138      The alternatives are:
4139      1) stop_stepping and return; to really stop and return to the debugger,
4140      2) keep_going and return to start up again
4141      (set ecs->event_thread->stepping_over_breakpoint to 1 to single step once)
4142      3) set ecs->random_signal to 1, and the decision between 1 and 2
4143      will be made according to the signal handling tables.  */
4144
4145   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
4146       && stop_after_trap)
4147     {
4148       if (debug_infrun)
4149         fprintf_unfiltered (gdb_stdlog, "infrun: stopped\n");
4150       stop_print_frame = 0;
4151       stop_stepping (ecs);
4152       return;
4153     }
4154
4155   /* This is originated from start_remote(), start_inferior() and
4156      shared libraries hook functions.  */
4157   if (stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_REMOTE)
4158     {
4159       if (debug_infrun)
4160         fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
4161       stop_stepping (ecs);
4162       return;
4163     }
4164
4165   /* This originates from attach_command().  We need to overwrite
4166      the stop_signal here, because some kernels don't ignore a
4167      SIGSTOP in a subsequent ptrace(PTRACE_CONT,SIGSTOP) call.
4168      See more comments in inferior.h.  On the other hand, if we
4169      get a non-SIGSTOP, report it to the user - assume the backend
4170      will handle the SIGSTOP if it should show up later.
4171
4172      Also consider that the attach is complete when we see a
4173      SIGTRAP.  Some systems (e.g. Windows), and stubs supporting
4174      target extended-remote report it instead of a SIGSTOP
4175      (e.g. gdbserver).  We already rely on SIGTRAP being our
4176      signal, so this is no exception.
4177
4178      Also consider that the attach is complete when we see a
4179      GDB_SIGNAL_0.  In non-stop mode, GDB will explicitly tell
4180      the target to stop all threads of the inferior, in case the
4181      low level attach operation doesn't stop them implicitly.  If
4182      they weren't stopped implicitly, then the stub will report a
4183      GDB_SIGNAL_0, meaning: stopped for no particular reason
4184      other than GDB's request.  */
4185   if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
4186       && (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_STOP
4187           || ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
4188           || ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_0))
4189     {
4190       stop_stepping (ecs);
4191       ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
4192       return;
4193     }
4194
4195   /* See if there is a breakpoint/watchpoint/catchpoint/etc. that
4196      handles this event.  */
4197   ecs->event_thread->control.stop_bpstat
4198     = bpstat_stop_status (get_regcache_aspace (get_current_regcache ()),
4199                           stop_pc, ecs->ptid, &ecs->ws);
4200
4201   /* Following in case break condition called a
4202      function.  */
4203   stop_print_frame = 1;
4204
4205   /* This is where we handle "moribund" watchpoints.  Unlike
4206      software breakpoints traps, hardware watchpoint traps are
4207      always distinguishable from random traps.  If no high-level
4208      watchpoint is associated with the reported stop data address
4209      anymore, then the bpstat does not explain the signal ---
4210      simply make sure to ignore it if `stopped_by_watchpoint' is
4211      set.  */
4212
4213   if (debug_infrun
4214       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
4215       && (bpstat_explains_signal (ecs->event_thread->control.stop_bpstat)
4216           == BPSTAT_SIGNAL_NO)
4217       && stopped_by_watchpoint)
4218     fprintf_unfiltered (gdb_stdlog,
4219                         "infrun: no user watchpoint explains "
4220                         "watchpoint SIGTRAP, ignoring\n");
4221
4222   /* NOTE: cagney/2003-03-29: These two checks for a random signal
4223      at one stage in the past included checks for an inferior
4224      function call's call dummy's return breakpoint.  The original
4225      comment, that went with the test, read:
4226
4227      ``End of a stack dummy.  Some systems (e.g. Sony news) give
4228      another signal besides SIGTRAP, so check here as well as
4229      above.''
4230
4231      If someone ever tries to get call dummys on a
4232      non-executable stack to work (where the target would stop
4233      with something like a SIGSEGV), then those tests might need
4234      to be re-instated.  Given, however, that the tests were only
4235      enabled when momentary breakpoints were not being used, I
4236      suspect that it won't be the case.
4237
4238      NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
4239      be necessary for call dummies on a non-executable stack on
4240      SPARC.  */
4241
4242   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
4243     ecs->random_signal
4244       = !((bpstat_explains_signal (ecs->event_thread->control.stop_bpstat)
4245            != BPSTAT_SIGNAL_NO)
4246           || stopped_by_watchpoint
4247           || ecs->event_thread->control.trap_expected
4248           || (ecs->event_thread->control.step_range_end
4249               && (ecs->event_thread->control.step_resume_breakpoint
4250                   == NULL)));
4251   else
4252     {
4253       enum bpstat_signal_value sval;
4254
4255       sval = bpstat_explains_signal (ecs->event_thread->control.stop_bpstat);
4256       ecs->random_signal = (sval == BPSTAT_SIGNAL_NO);
4257
4258       if (sval == BPSTAT_SIGNAL_HIDE)
4259         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_TRAP;
4260     }
4261
4262 process_event_stop_test:
4263
4264   /* Re-fetch current thread's frame in case we did a
4265      "goto process_event_stop_test" above.  */
4266   frame = get_current_frame ();
4267   gdbarch = get_frame_arch (frame);
4268
4269   /* For the program's own signals, act according to
4270      the signal handling tables.  */
4271
4272   if (ecs->random_signal)
4273     {
4274       /* Signal not for debugging purposes.  */
4275       int printed = 0;
4276       struct inferior *inf = find_inferior_pid (ptid_get_pid (ecs->ptid));
4277
4278       if (debug_infrun)
4279          fprintf_unfiltered (gdb_stdlog, "infrun: random signal %d\n",
4280                              ecs->event_thread->suspend.stop_signal);
4281
4282       stopped_by_random_signal = 1;
4283
4284       if (signal_print[ecs->event_thread->suspend.stop_signal])
4285         {
4286           printed = 1;
4287           target_terminal_ours_for_output ();
4288           print_signal_received_reason
4289                                      (ecs->event_thread->suspend.stop_signal);
4290         }
4291       /* Always stop on signals if we're either just gaining control
4292          of the program, or the user explicitly requested this thread
4293          to remain stopped.  */
4294       if (stop_soon != NO_STOP_QUIETLY
4295           || ecs->event_thread->stop_requested
4296           || (!inf->detaching
4297               && signal_stop_state (ecs->event_thread->suspend.stop_signal)))
4298         {
4299           stop_stepping (ecs);
4300           return;
4301         }
4302       /* If not going to stop, give terminal back
4303          if we took it away.  */
4304       else if (printed)
4305         target_terminal_inferior ();
4306
4307       /* Clear the signal if it should not be passed.  */
4308       if (signal_program[ecs->event_thread->suspend.stop_signal] == 0)
4309         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
4310
4311       if (ecs->event_thread->prev_pc == stop_pc
4312           && ecs->event_thread->control.trap_expected
4313           && ecs->event_thread->control.step_resume_breakpoint == NULL)
4314         {
4315           /* We were just starting a new sequence, attempting to
4316              single-step off of a breakpoint and expecting a SIGTRAP.
4317              Instead this signal arrives.  This signal will take us out
4318              of the stepping range so GDB needs to remember to, when
4319              the signal handler returns, resume stepping off that
4320              breakpoint.  */
4321           /* To simplify things, "continue" is forced to use the same
4322              code paths as single-step - set a breakpoint at the
4323              signal return address and then, once hit, step off that
4324              breakpoint.  */
4325           if (debug_infrun)
4326             fprintf_unfiltered (gdb_stdlog,
4327                                 "infrun: signal arrived while stepping over "
4328                                 "breakpoint\n");
4329
4330           insert_hp_step_resume_breakpoint_at_frame (frame);
4331           ecs->event_thread->step_after_step_resume_breakpoint = 1;
4332           /* Reset trap_expected to ensure breakpoints are re-inserted.  */
4333           ecs->event_thread->control.trap_expected = 0;
4334           keep_going (ecs);
4335           return;
4336         }
4337
4338       if (ecs->event_thread->control.step_range_end != 0
4339           && ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_0
4340           && (ecs->event_thread->control.step_range_start <= stop_pc
4341               && stop_pc < ecs->event_thread->control.step_range_end)
4342           && frame_id_eq (get_stack_frame_id (frame),
4343                           ecs->event_thread->control.step_stack_frame_id)
4344           && ecs->event_thread->control.step_resume_breakpoint == NULL)
4345         {
4346           /* The inferior is about to take a signal that will take it
4347              out of the single step range.  Set a breakpoint at the
4348              current PC (which is presumably where the signal handler
4349              will eventually return) and then allow the inferior to
4350              run free.
4351
4352              Note that this is only needed for a signal delivered
4353              while in the single-step range.  Nested signals aren't a
4354              problem as they eventually all return.  */
4355           if (debug_infrun)
4356             fprintf_unfiltered (gdb_stdlog,
4357                                 "infrun: signal may take us out of "
4358                                 "single-step range\n");
4359
4360           insert_hp_step_resume_breakpoint_at_frame (frame);
4361           /* Reset trap_expected to ensure breakpoints are re-inserted.  */
4362           ecs->event_thread->control.trap_expected = 0;
4363           keep_going (ecs);
4364           return;
4365         }
4366
4367       /* Note: step_resume_breakpoint may be non-NULL.  This occures
4368          when either there's a nested signal, or when there's a
4369          pending signal enabled just as the signal handler returns
4370          (leaving the inferior at the step-resume-breakpoint without
4371          actually executing it).  Either way continue until the
4372          breakpoint is really hit.  */
4373     }
4374   else
4375     {
4376       /* Handle cases caused by hitting a breakpoint.  */
4377
4378       CORE_ADDR jmp_buf_pc;
4379       struct bpstat_what what;
4380
4381       what = bpstat_what (ecs->event_thread->control.stop_bpstat);
4382
4383       if (what.call_dummy)
4384         {
4385           stop_stack_dummy = what.call_dummy;
4386         }
4387
4388       /* If we hit an internal event that triggers symbol changes, the
4389          current frame will be invalidated within bpstat_what (e.g.,
4390          if we hit an internal solib event).  Re-fetch it.  */
4391       frame = get_current_frame ();
4392       gdbarch = get_frame_arch (frame);
4393
4394       switch (what.main_action)
4395         {
4396         case BPSTAT_WHAT_SET_LONGJMP_RESUME:
4397           /* If we hit the breakpoint at longjmp while stepping, we
4398              install a momentary breakpoint at the target of the
4399              jmp_buf.  */
4400
4401           if (debug_infrun)
4402             fprintf_unfiltered (gdb_stdlog,
4403                                 "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME\n");
4404
4405           ecs->event_thread->stepping_over_breakpoint = 1;
4406
4407           if (what.is_longjmp)
4408             {
4409               struct value *arg_value;
4410
4411               /* If we set the longjmp breakpoint via a SystemTap
4412                  probe, then use it to extract the arguments.  The
4413                  destination PC is the third argument to the
4414                  probe.  */
4415               arg_value = probe_safe_evaluate_at_pc (frame, 2);
4416               if (arg_value)
4417                 jmp_buf_pc = value_as_address (arg_value);
4418               else if (!gdbarch_get_longjmp_target_p (gdbarch)
4419                        || !gdbarch_get_longjmp_target (gdbarch,
4420                                                        frame, &jmp_buf_pc))
4421                 {
4422                   if (debug_infrun)
4423                     fprintf_unfiltered (gdb_stdlog,
4424                                         "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME "
4425                                         "(!gdbarch_get_longjmp_target)\n");
4426                   keep_going (ecs);
4427                   return;
4428                 }
4429
4430               /* Insert a breakpoint at resume address.  */
4431               insert_longjmp_resume_breakpoint (gdbarch, jmp_buf_pc);
4432             }
4433           else
4434             check_exception_resume (ecs, frame);
4435           keep_going (ecs);
4436           return;
4437
4438         case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
4439           {
4440             struct frame_info *init_frame;
4441
4442             /* There are several cases to consider.
4443
4444                1. The initiating frame no longer exists.  In this case
4445                we must stop, because the exception or longjmp has gone
4446                too far.
4447
4448                2. The initiating frame exists, and is the same as the
4449                current frame.  We stop, because the exception or
4450                longjmp has been caught.
4451
4452                3. The initiating frame exists and is different from
4453                the current frame.  This means the exception or longjmp
4454                has been caught beneath the initiating frame, so keep
4455                going.
4456
4457                4. longjmp breakpoint has been placed just to protect
4458                against stale dummy frames and user is not interested
4459                in stopping around longjmps.  */
4460
4461             if (debug_infrun)
4462               fprintf_unfiltered (gdb_stdlog,
4463                                   "infrun: BPSTAT_WHAT_CLEAR_LONGJMP_RESUME\n");
4464
4465             gdb_assert (ecs->event_thread->control.exception_resume_breakpoint
4466                         != NULL);
4467             delete_exception_resume_breakpoint (ecs->event_thread);
4468
4469             if (what.is_longjmp)
4470               {
4471                 check_longjmp_breakpoint_for_call_dummy (ecs->event_thread->num);
4472
4473                 if (!frame_id_p (ecs->event_thread->initiating_frame))
4474                   {
4475                     /* Case 4.  */
4476                     keep_going (ecs);
4477                     return;
4478                   }
4479               }
4480
4481             init_frame = frame_find_by_id (ecs->event_thread->initiating_frame);
4482
4483             if (init_frame)
4484               {
4485                 struct frame_id current_id
4486                   = get_frame_id (get_current_frame ());
4487                 if (frame_id_eq (current_id,
4488                                  ecs->event_thread->initiating_frame))
4489                   {
4490                     /* Case 2.  Fall through.  */
4491                   }
4492                 else
4493                   {
4494                     /* Case 3.  */
4495                     keep_going (ecs);
4496                     return;
4497                   }
4498               }
4499
4500             /* For Cases 1 and 2, remove the step-resume breakpoint,
4501                if it exists.  */
4502             delete_step_resume_breakpoint (ecs->event_thread);
4503
4504             ecs->event_thread->control.stop_step = 1;
4505             print_end_stepping_range_reason ();
4506             stop_stepping (ecs);
4507           }
4508           return;
4509
4510         case BPSTAT_WHAT_SINGLE:
4511           if (debug_infrun)
4512             fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_SINGLE\n");
4513           ecs->event_thread->stepping_over_breakpoint = 1;
4514           /* Still need to check other stuff, at least the case where
4515              we are stepping and step out of the right range.  */
4516           break;
4517
4518         case BPSTAT_WHAT_STEP_RESUME:
4519           if (debug_infrun)
4520             fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STEP_RESUME\n");
4521
4522           delete_step_resume_breakpoint (ecs->event_thread);
4523           if (ecs->event_thread->control.proceed_to_finish
4524               && execution_direction == EXEC_REVERSE)
4525             {
4526               struct thread_info *tp = ecs->event_thread;
4527
4528               /* We are finishing a function in reverse, and just hit
4529                  the step-resume breakpoint at the start address of
4530                  the function, and we're almost there -- just need to
4531                  back up by one more single-step, which should take us
4532                  back to the function call.  */
4533               tp->control.step_range_start = tp->control.step_range_end = 1;
4534               keep_going (ecs);
4535               return;
4536             }
4537           fill_in_stop_func (gdbarch, ecs);
4538           if (stop_pc == ecs->stop_func_start
4539               && execution_direction == EXEC_REVERSE)
4540             {
4541               /* We are stepping over a function call in reverse, and
4542                  just hit the step-resume breakpoint at the start
4543                  address of the function.  Go back to single-stepping,
4544                  which should take us back to the function call.  */
4545               ecs->event_thread->stepping_over_breakpoint = 1;
4546               keep_going (ecs);
4547               return;
4548             }
4549           break;
4550
4551         case BPSTAT_WHAT_STOP_NOISY:
4552           if (debug_infrun)
4553             fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_NOISY\n");
4554           stop_print_frame = 1;
4555
4556           /* We are about to nuke the step_resume_breakpointt via the
4557              cleanup chain, so no need to worry about it here.  */
4558
4559           stop_stepping (ecs);
4560           return;
4561
4562         case BPSTAT_WHAT_STOP_SILENT:
4563           if (debug_infrun)
4564             fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_SILENT\n");
4565           stop_print_frame = 0;
4566
4567           /* We are about to nuke the step_resume_breakpoin via the
4568              cleanup chain, so no need to worry about it here.  */
4569
4570           stop_stepping (ecs);
4571           return;
4572
4573         case BPSTAT_WHAT_HP_STEP_RESUME:
4574           if (debug_infrun)
4575             fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_HP_STEP_RESUME\n");
4576
4577           delete_step_resume_breakpoint (ecs->event_thread);
4578           if (ecs->event_thread->step_after_step_resume_breakpoint)
4579             {
4580               /* Back when the step-resume breakpoint was inserted, we
4581                  were trying to single-step off a breakpoint.  Go back
4582                  to doing that.  */
4583               ecs->event_thread->step_after_step_resume_breakpoint = 0;
4584               ecs->event_thread->stepping_over_breakpoint = 1;
4585               keep_going (ecs);
4586               return;
4587             }
4588           break;
4589
4590         case BPSTAT_WHAT_KEEP_CHECKING:
4591           break;
4592         }
4593     }
4594
4595   /* We come here if we hit a breakpoint but should not
4596      stop for it.  Possibly we also were stepping
4597      and should stop for that.  So fall through and
4598      test for stepping.  But, if not stepping,
4599      do not stop.  */
4600
4601   /* In all-stop mode, if we're currently stepping but have stopped in
4602      some other thread, we need to switch back to the stepped thread.  */
4603   if (!non_stop)
4604     {
4605       struct thread_info *tp;
4606
4607       tp = iterate_over_threads (currently_stepping_or_nexting_callback,
4608                                  ecs->event_thread);
4609       if (tp)
4610         {
4611           /* However, if the current thread is blocked on some internal
4612              breakpoint, and we simply need to step over that breakpoint
4613              to get it going again, do that first.  */
4614           if ((ecs->event_thread->control.trap_expected
4615                && ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_TRAP)
4616               || ecs->event_thread->stepping_over_breakpoint)
4617             {
4618               keep_going (ecs);
4619               return;
4620             }
4621
4622           /* If the stepping thread exited, then don't try to switch
4623              back and resume it, which could fail in several different
4624              ways depending on the target.  Instead, just keep going.
4625
4626              We can find a stepping dead thread in the thread list in
4627              two cases:
4628
4629              - The target supports thread exit events, and when the
4630              target tries to delete the thread from the thread list,
4631              inferior_ptid pointed at the exiting thread.  In such
4632              case, calling delete_thread does not really remove the
4633              thread from the list; instead, the thread is left listed,
4634              with 'exited' state.
4635
4636              - The target's debug interface does not support thread
4637              exit events, and so we have no idea whatsoever if the
4638              previously stepping thread is still alive.  For that
4639              reason, we need to synchronously query the target
4640              now.  */
4641           if (is_exited (tp->ptid)
4642               || !target_thread_alive (tp->ptid))
4643             {
4644               if (debug_infrun)
4645                 fprintf_unfiltered (gdb_stdlog,
4646                                     "infrun: not switching back to "
4647                                     "stepped thread, it has vanished\n");
4648
4649               delete_thread (tp->ptid);
4650               keep_going (ecs);
4651               return;
4652             }
4653
4654           /* Otherwise, we no longer expect a trap in the current thread.
4655              Clear the trap_expected flag before switching back -- this is
4656              what keep_going would do as well, if we called it.  */
4657           ecs->event_thread->control.trap_expected = 0;
4658
4659           if (debug_infrun)
4660             fprintf_unfiltered (gdb_stdlog,
4661                                 "infrun: switching back to stepped thread\n");
4662
4663           ecs->event_thread = tp;
4664           ecs->ptid = tp->ptid;
4665           context_switch (ecs->ptid);
4666           keep_going (ecs);
4667           return;
4668         }
4669     }
4670
4671   if (ecs->event_thread->control.step_resume_breakpoint)
4672     {
4673       if (debug_infrun)
4674          fprintf_unfiltered (gdb_stdlog,
4675                              "infrun: step-resume breakpoint is inserted\n");
4676
4677       /* Having a step-resume breakpoint overrides anything
4678          else having to do with stepping commands until
4679          that breakpoint is reached.  */
4680       keep_going (ecs);
4681       return;
4682     }
4683
4684   if (ecs->event_thread->control.step_range_end == 0)
4685     {
4686       if (debug_infrun)
4687          fprintf_unfiltered (gdb_stdlog, "infrun: no stepping, continue\n");
4688       /* Likewise if we aren't even stepping.  */
4689       keep_going (ecs);
4690       return;
4691     }
4692
4693   /* Re-fetch current thread's frame in case the code above caused
4694      the frame cache to be re-initialized, making our FRAME variable
4695      a dangling pointer.  */
4696   frame = get_current_frame ();
4697   gdbarch = get_frame_arch (frame);
4698   fill_in_stop_func (gdbarch, ecs);
4699
4700   /* If stepping through a line, keep going if still within it.
4701
4702      Note that step_range_end is the address of the first instruction
4703      beyond the step range, and NOT the address of the last instruction
4704      within it!
4705
4706      Note also that during reverse execution, we may be stepping
4707      through a function epilogue and therefore must detect when
4708      the current-frame changes in the middle of a line.  */
4709
4710   if (stop_pc >= ecs->event_thread->control.step_range_start
4711       && stop_pc < ecs->event_thread->control.step_range_end
4712       && (execution_direction != EXEC_REVERSE
4713           || frame_id_eq (get_frame_id (frame),
4714                           ecs->event_thread->control.step_frame_id)))
4715     {
4716       if (debug_infrun)
4717         fprintf_unfiltered
4718           (gdb_stdlog, "infrun: stepping inside range [%s-%s]\n",
4719            paddress (gdbarch, ecs->event_thread->control.step_range_start),
4720            paddress (gdbarch, ecs->event_thread->control.step_range_end));
4721
4722       /* When stepping backward, stop at beginning of line range
4723          (unless it's the function entry point, in which case
4724          keep going back to the call point).  */
4725       if (stop_pc == ecs->event_thread->control.step_range_start
4726           && stop_pc != ecs->stop_func_start
4727           && execution_direction == EXEC_REVERSE)
4728         {
4729           ecs->event_thread->control.stop_step = 1;
4730           print_end_stepping_range_reason ();
4731           stop_stepping (ecs);
4732         }
4733       else
4734         keep_going (ecs);
4735
4736       return;
4737     }
4738
4739   /* We stepped out of the stepping range.  */
4740
4741   /* If we are stepping at the source level and entered the runtime
4742      loader dynamic symbol resolution code...
4743
4744      EXEC_FORWARD: we keep on single stepping until we exit the run
4745      time loader code and reach the callee's address.
4746
4747      EXEC_REVERSE: we've already executed the callee (backward), and
4748      the runtime loader code is handled just like any other
4749      undebuggable function call.  Now we need only keep stepping
4750      backward through the trampoline code, and that's handled further
4751      down, so there is nothing for us to do here.  */
4752
4753   if (execution_direction != EXEC_REVERSE
4754       && ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4755       && in_solib_dynsym_resolve_code (stop_pc))
4756     {
4757       CORE_ADDR pc_after_resolver =
4758         gdbarch_skip_solib_resolver (gdbarch, stop_pc);
4759
4760       if (debug_infrun)
4761          fprintf_unfiltered (gdb_stdlog,
4762                              "infrun: stepped into dynsym resolve code\n");
4763
4764       if (pc_after_resolver)
4765         {
4766           /* Set up a step-resume breakpoint at the address
4767              indicated by SKIP_SOLIB_RESOLVER.  */
4768           struct symtab_and_line sr_sal;
4769
4770           init_sal (&sr_sal);
4771           sr_sal.pc = pc_after_resolver;
4772           sr_sal.pspace = get_frame_program_space (frame);
4773
4774           insert_step_resume_breakpoint_at_sal (gdbarch,
4775                                                 sr_sal, null_frame_id);
4776         }
4777
4778       keep_going (ecs);
4779       return;
4780     }
4781
4782   if (ecs->event_thread->control.step_range_end != 1
4783       && (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4784           || ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
4785       && get_frame_type (frame) == SIGTRAMP_FRAME)
4786     {
4787       if (debug_infrun)
4788          fprintf_unfiltered (gdb_stdlog,
4789                              "infrun: stepped into signal trampoline\n");
4790       /* The inferior, while doing a "step" or "next", has ended up in
4791          a signal trampoline (either by a signal being delivered or by
4792          the signal handler returning).  Just single-step until the
4793          inferior leaves the trampoline (either by calling the handler
4794          or returning).  */
4795       keep_going (ecs);
4796       return;
4797     }
4798
4799   /* If we're in the return path from a shared library trampoline,
4800      we want to proceed through the trampoline when stepping.  */
4801   /* macro/2012-04-25: This needs to come before the subroutine
4802      call check below as on some targets return trampolines look
4803      like subroutine calls (MIPS16 return thunks).  */
4804   if (gdbarch_in_solib_return_trampoline (gdbarch,
4805                                           stop_pc, ecs->stop_func_name)
4806       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
4807     {
4808       /* Determine where this trampoline returns.  */
4809       CORE_ADDR real_stop_pc;
4810
4811       real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
4812
4813       if (debug_infrun)
4814          fprintf_unfiltered (gdb_stdlog,
4815                              "infrun: stepped into solib return tramp\n");
4816
4817       /* Only proceed through if we know where it's going.  */
4818       if (real_stop_pc)
4819         {
4820           /* And put the step-breakpoint there and go until there.  */
4821           struct symtab_and_line sr_sal;
4822
4823           init_sal (&sr_sal);   /* initialize to zeroes */
4824           sr_sal.pc = real_stop_pc;
4825           sr_sal.section = find_pc_overlay (sr_sal.pc);
4826           sr_sal.pspace = get_frame_program_space (frame);
4827
4828           /* Do not specify what the fp should be when we stop since
4829              on some machines the prologue is where the new fp value
4830              is established.  */
4831           insert_step_resume_breakpoint_at_sal (gdbarch,
4832                                                 sr_sal, null_frame_id);
4833
4834           /* Restart without fiddling with the step ranges or
4835              other state.  */
4836           keep_going (ecs);
4837           return;
4838         }
4839     }
4840
4841   /* Check for subroutine calls.  The check for the current frame
4842      equalling the step ID is not necessary - the check of the
4843      previous frame's ID is sufficient - but it is a common case and
4844      cheaper than checking the previous frame's ID.
4845
4846      NOTE: frame_id_eq will never report two invalid frame IDs as
4847      being equal, so to get into this block, both the current and
4848      previous frame must have valid frame IDs.  */
4849   /* The outer_frame_id check is a heuristic to detect stepping
4850      through startup code.  If we step over an instruction which
4851      sets the stack pointer from an invalid value to a valid value,
4852      we may detect that as a subroutine call from the mythical
4853      "outermost" function.  This could be fixed by marking
4854      outermost frames as !stack_p,code_p,special_p.  Then the
4855      initial outermost frame, before sp was valid, would
4856      have code_addr == &_start.  See the comment in frame_id_eq
4857      for more.  */
4858   if (!frame_id_eq (get_stack_frame_id (frame),
4859                     ecs->event_thread->control.step_stack_frame_id)
4860       && (frame_id_eq (frame_unwind_caller_id (get_current_frame ()),
4861                        ecs->event_thread->control.step_stack_frame_id)
4862           && (!frame_id_eq (ecs->event_thread->control.step_stack_frame_id,
4863                             outer_frame_id)
4864               || step_start_function != find_pc_function (stop_pc))))
4865     {
4866       CORE_ADDR real_stop_pc;
4867
4868       if (debug_infrun)
4869          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into subroutine\n");
4870
4871       if ((ecs->event_thread->control.step_over_calls == STEP_OVER_NONE)
4872           || ((ecs->event_thread->control.step_range_end == 1)
4873               && in_prologue (gdbarch, ecs->event_thread->prev_pc,
4874                               ecs->stop_func_start)))
4875         {
4876           /* I presume that step_over_calls is only 0 when we're
4877              supposed to be stepping at the assembly language level
4878              ("stepi").  Just stop.  */
4879           /* Also, maybe we just did a "nexti" inside a prolog, so we
4880              thought it was a subroutine call but it was not.  Stop as
4881              well.  FENN */
4882           /* And this works the same backward as frontward.  MVS */
4883           ecs->event_thread->control.stop_step = 1;
4884           print_end_stepping_range_reason ();
4885           stop_stepping (ecs);
4886           return;
4887         }
4888
4889       /* Reverse stepping through solib trampolines.  */
4890
4891       if (execution_direction == EXEC_REVERSE
4892           && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE
4893           && (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
4894               || (ecs->stop_func_start == 0
4895                   && in_solib_dynsym_resolve_code (stop_pc))))
4896         {
4897           /* Any solib trampoline code can be handled in reverse
4898              by simply continuing to single-step.  We have already
4899              executed the solib function (backwards), and a few 
4900              steps will take us back through the trampoline to the
4901              caller.  */
4902           keep_going (ecs);
4903           return;
4904         }
4905
4906       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
4907         {
4908           /* We're doing a "next".
4909
4910              Normal (forward) execution: set a breakpoint at the
4911              callee's return address (the address at which the caller
4912              will resume).
4913
4914              Reverse (backward) execution.  set the step-resume
4915              breakpoint at the start of the function that we just
4916              stepped into (backwards), and continue to there.  When we
4917              get there, we'll need to single-step back to the caller.  */
4918
4919           if (execution_direction == EXEC_REVERSE)
4920             {
4921               /* If we're already at the start of the function, we've either
4922                  just stepped backward into a single instruction function,
4923                  or stepped back out of a signal handler to the first instruction
4924                  of the function.  Just keep going, which will single-step back
4925                  to the caller.  */
4926               if (ecs->stop_func_start != stop_pc)
4927                 {
4928                   struct symtab_and_line sr_sal;
4929
4930                   /* Normal function call return (static or dynamic).  */
4931                   init_sal (&sr_sal);
4932                   sr_sal.pc = ecs->stop_func_start;
4933                   sr_sal.pspace = get_frame_program_space (frame);
4934                   insert_step_resume_breakpoint_at_sal (gdbarch,
4935                                                         sr_sal, null_frame_id);
4936                 }
4937             }
4938           else
4939             insert_step_resume_breakpoint_at_caller (frame);
4940
4941           keep_going (ecs);
4942           return;
4943         }
4944
4945       /* If we are in a function call trampoline (a stub between the
4946          calling routine and the real function), locate the real
4947          function.  That's what tells us (a) whether we want to step
4948          into it at all, and (b) what prologue we want to run to the
4949          end of, if we do step into it.  */
4950       real_stop_pc = skip_language_trampoline (frame, stop_pc);
4951       if (real_stop_pc == 0)
4952         real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
4953       if (real_stop_pc != 0)
4954         ecs->stop_func_start = real_stop_pc;
4955
4956       if (real_stop_pc != 0 && in_solib_dynsym_resolve_code (real_stop_pc))
4957         {
4958           struct symtab_and_line sr_sal;
4959
4960           init_sal (&sr_sal);
4961           sr_sal.pc = ecs->stop_func_start;
4962           sr_sal.pspace = get_frame_program_space (frame);
4963
4964           insert_step_resume_breakpoint_at_sal (gdbarch,
4965                                                 sr_sal, null_frame_id);
4966           keep_going (ecs);
4967           return;
4968         }
4969
4970       /* If we have line number information for the function we are
4971          thinking of stepping into and the function isn't on the skip
4972          list, step into it.
4973
4974          If there are several symtabs at that PC (e.g. with include
4975          files), just want to know whether *any* of them have line
4976          numbers.  find_pc_line handles this.  */
4977       {
4978         struct symtab_and_line tmp_sal;
4979
4980         tmp_sal = find_pc_line (ecs->stop_func_start, 0);
4981         if (tmp_sal.line != 0
4982             && !function_name_is_marked_for_skip (ecs->stop_func_name,
4983                                                   &tmp_sal))
4984           {
4985             if (execution_direction == EXEC_REVERSE)
4986               handle_step_into_function_backward (gdbarch, ecs);
4987             else
4988               handle_step_into_function (gdbarch, ecs);
4989             return;
4990           }
4991       }
4992
4993       /* If we have no line number and the step-stop-if-no-debug is
4994          set, we stop the step so that the user has a chance to switch
4995          in assembly mode.  */
4996       if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
4997           && step_stop_if_no_debug)
4998         {
4999           ecs->event_thread->control.stop_step = 1;
5000           print_end_stepping_range_reason ();
5001           stop_stepping (ecs);
5002           return;
5003         }
5004
5005       if (execution_direction == EXEC_REVERSE)
5006         {
5007           /* If we're already at the start of the function, we've either just
5008              stepped backward into a single instruction function without line
5009              number info, or stepped back out of a signal handler to the first
5010              instruction of the function without line number info.  Just keep
5011              going, which will single-step back to the caller.  */
5012           if (ecs->stop_func_start != stop_pc)
5013             {
5014               /* Set a breakpoint at callee's start address.
5015                  From there we can step once and be back in the caller.  */
5016               struct symtab_and_line sr_sal;
5017
5018               init_sal (&sr_sal);
5019               sr_sal.pc = ecs->stop_func_start;
5020               sr_sal.pspace = get_frame_program_space (frame);
5021               insert_step_resume_breakpoint_at_sal (gdbarch,
5022                                                     sr_sal, null_frame_id);
5023             }
5024         }
5025       else
5026         /* Set a breakpoint at callee's return address (the address
5027            at which the caller will resume).  */
5028         insert_step_resume_breakpoint_at_caller (frame);
5029
5030       keep_going (ecs);
5031       return;
5032     }
5033
5034   /* Reverse stepping through solib trampolines.  */
5035
5036   if (execution_direction == EXEC_REVERSE
5037       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
5038     {
5039       if (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
5040           || (ecs->stop_func_start == 0
5041               && in_solib_dynsym_resolve_code (stop_pc)))
5042         {
5043           /* Any solib trampoline code can be handled in reverse
5044              by simply continuing to single-step.  We have already
5045              executed the solib function (backwards), and a few 
5046              steps will take us back through the trampoline to the
5047              caller.  */
5048           keep_going (ecs);
5049           return;
5050         }
5051       else if (in_solib_dynsym_resolve_code (stop_pc))
5052         {
5053           /* Stepped backward into the solib dynsym resolver.
5054              Set a breakpoint at its start and continue, then
5055              one more step will take us out.  */
5056           struct symtab_and_line sr_sal;
5057
5058           init_sal (&sr_sal);
5059           sr_sal.pc = ecs->stop_func_start;
5060           sr_sal.pspace = get_frame_program_space (frame);
5061           insert_step_resume_breakpoint_at_sal (gdbarch, 
5062                                                 sr_sal, null_frame_id);
5063           keep_going (ecs);
5064           return;
5065         }
5066     }
5067
5068   stop_pc_sal = find_pc_line (stop_pc, 0);
5069
5070   /* NOTE: tausq/2004-05-24: This if block used to be done before all
5071      the trampoline processing logic, however, there are some trampolines 
5072      that have no names, so we should do trampoline handling first.  */
5073   if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
5074       && ecs->stop_func_name == NULL
5075       && stop_pc_sal.line == 0)
5076     {
5077       if (debug_infrun)
5078          fprintf_unfiltered (gdb_stdlog,
5079                              "infrun: stepped into undebuggable function\n");
5080
5081       /* The inferior just stepped into, or returned to, an
5082          undebuggable function (where there is no debugging information
5083          and no line number corresponding to the address where the
5084          inferior stopped).  Since we want to skip this kind of code,
5085          we keep going until the inferior returns from this
5086          function - unless the user has asked us not to (via
5087          set step-mode) or we no longer know how to get back
5088          to the call site.  */
5089       if (step_stop_if_no_debug
5090           || !frame_id_p (frame_unwind_caller_id (frame)))
5091         {
5092           /* If we have no line number and the step-stop-if-no-debug
5093              is set, we stop the step so that the user has a chance to
5094              switch in assembly mode.  */
5095           ecs->event_thread->control.stop_step = 1;
5096           print_end_stepping_range_reason ();
5097           stop_stepping (ecs);
5098           return;
5099         }
5100       else
5101         {
5102           /* Set a breakpoint at callee's return address (the address
5103              at which the caller will resume).  */
5104           insert_step_resume_breakpoint_at_caller (frame);
5105           keep_going (ecs);
5106           return;
5107         }
5108     }
5109
5110   if (ecs->event_thread->control.step_range_end == 1)
5111     {
5112       /* It is stepi or nexti.  We always want to stop stepping after
5113          one instruction.  */
5114       if (debug_infrun)
5115          fprintf_unfiltered (gdb_stdlog, "infrun: stepi/nexti\n");
5116       ecs->event_thread->control.stop_step = 1;
5117       print_end_stepping_range_reason ();
5118       stop_stepping (ecs);
5119       return;
5120     }
5121
5122   if (stop_pc_sal.line == 0)
5123     {
5124       /* We have no line number information.  That means to stop
5125          stepping (does this always happen right after one instruction,
5126          when we do "s" in a function with no line numbers,
5127          or can this happen as a result of a return or longjmp?).  */
5128       if (debug_infrun)
5129          fprintf_unfiltered (gdb_stdlog, "infrun: no line number info\n");
5130       ecs->event_thread->control.stop_step = 1;
5131       print_end_stepping_range_reason ();
5132       stop_stepping (ecs);
5133       return;
5134     }
5135
5136   /* Look for "calls" to inlined functions, part one.  If the inline
5137      frame machinery detected some skipped call sites, we have entered
5138      a new inline function.  */
5139
5140   if (frame_id_eq (get_frame_id (get_current_frame ()),
5141                    ecs->event_thread->control.step_frame_id)
5142       && inline_skipped_frames (ecs->ptid))
5143     {
5144       struct symtab_and_line call_sal;
5145
5146       if (debug_infrun)
5147         fprintf_unfiltered (gdb_stdlog,
5148                             "infrun: stepped into inlined function\n");
5149
5150       find_frame_sal (get_current_frame (), &call_sal);
5151
5152       if (ecs->event_thread->control.step_over_calls != STEP_OVER_ALL)
5153         {
5154           /* For "step", we're going to stop.  But if the call site
5155              for this inlined function is on the same source line as
5156              we were previously stepping, go down into the function
5157              first.  Otherwise stop at the call site.  */
5158
5159           if (call_sal.line == ecs->event_thread->current_line
5160               && call_sal.symtab == ecs->event_thread->current_symtab)
5161             step_into_inline_frame (ecs->ptid);
5162
5163           ecs->event_thread->control.stop_step = 1;
5164           print_end_stepping_range_reason ();
5165           stop_stepping (ecs);
5166           return;
5167         }
5168       else
5169         {
5170           /* For "next", we should stop at the call site if it is on a
5171              different source line.  Otherwise continue through the
5172              inlined function.  */
5173           if (call_sal.line == ecs->event_thread->current_line
5174               && call_sal.symtab == ecs->event_thread->current_symtab)
5175             keep_going (ecs);
5176           else
5177             {
5178               ecs->event_thread->control.stop_step = 1;
5179               print_end_stepping_range_reason ();
5180               stop_stepping (ecs);
5181             }
5182           return;
5183         }
5184     }
5185
5186   /* Look for "calls" to inlined functions, part two.  If we are still
5187      in the same real function we were stepping through, but we have
5188      to go further up to find the exact frame ID, we are stepping
5189      through a more inlined call beyond its call site.  */
5190
5191   if (get_frame_type (get_current_frame ()) == INLINE_FRAME
5192       && !frame_id_eq (get_frame_id (get_current_frame ()),
5193                        ecs->event_thread->control.step_frame_id)
5194       && stepped_in_from (get_current_frame (),
5195                           ecs->event_thread->control.step_frame_id))
5196     {
5197       if (debug_infrun)
5198         fprintf_unfiltered (gdb_stdlog,
5199                             "infrun: stepping through inlined function\n");
5200
5201       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
5202         keep_going (ecs);
5203       else
5204         {
5205           ecs->event_thread->control.stop_step = 1;
5206           print_end_stepping_range_reason ();
5207           stop_stepping (ecs);
5208         }
5209       return;
5210     }
5211
5212   if ((stop_pc == stop_pc_sal.pc)
5213       && (ecs->event_thread->current_line != stop_pc_sal.line
5214           || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
5215     {
5216       /* We are at the start of a different line.  So stop.  Note that
5217          we don't stop if we step into the middle of a different line.
5218          That is said to make things like for (;;) statements work
5219          better.  */
5220       if (debug_infrun)
5221          fprintf_unfiltered (gdb_stdlog,
5222                              "infrun: stepped to a different line\n");
5223       ecs->event_thread->control.stop_step = 1;
5224       print_end_stepping_range_reason ();
5225       stop_stepping (ecs);
5226       return;
5227     }
5228
5229   /* We aren't done stepping.
5230
5231      Optimize by setting the stepping range to the line.
5232      (We might not be in the original line, but if we entered a
5233      new line in mid-statement, we continue stepping.  This makes
5234      things like for(;;) statements work better.)  */
5235
5236   ecs->event_thread->control.step_range_start = stop_pc_sal.pc;
5237   ecs->event_thread->control.step_range_end = stop_pc_sal.end;
5238   set_step_info (frame, stop_pc_sal);
5239
5240   if (debug_infrun)
5241      fprintf_unfiltered (gdb_stdlog, "infrun: keep going\n");
5242   keep_going (ecs);
5243 }
5244
5245 /* Is thread TP in the middle of single-stepping?  */
5246
5247 static int
5248 currently_stepping (struct thread_info *tp)
5249 {
5250   return ((tp->control.step_range_end
5251            && tp->control.step_resume_breakpoint == NULL)
5252           || tp->control.trap_expected
5253           || bpstat_should_step ());
5254 }
5255
5256 /* Returns true if any thread *but* the one passed in "data" is in the
5257    middle of stepping or of handling a "next".  */
5258
5259 static int
5260 currently_stepping_or_nexting_callback (struct thread_info *tp, void *data)
5261 {
5262   if (tp == data)
5263     return 0;
5264
5265   return (tp->control.step_range_end
5266           || tp->control.trap_expected);
5267 }
5268
5269 /* Inferior has stepped into a subroutine call with source code that
5270    we should not step over.  Do step to the first line of code in
5271    it.  */
5272
5273 static void
5274 handle_step_into_function (struct gdbarch *gdbarch,
5275                            struct execution_control_state *ecs)
5276 {
5277   struct symtab *s;
5278   struct symtab_and_line stop_func_sal, sr_sal;
5279
5280   fill_in_stop_func (gdbarch, ecs);
5281
5282   s = find_pc_symtab (stop_pc);
5283   if (s && s->language != language_asm)
5284     ecs->stop_func_start = gdbarch_skip_prologue (gdbarch,
5285                                                   ecs->stop_func_start);
5286
5287   stop_func_sal = find_pc_line (ecs->stop_func_start, 0);
5288   /* Use the step_resume_break to step until the end of the prologue,
5289      even if that involves jumps (as it seems to on the vax under
5290      4.2).  */
5291   /* If the prologue ends in the middle of a source line, continue to
5292      the end of that source line (if it is still within the function).
5293      Otherwise, just go to end of prologue.  */
5294   if (stop_func_sal.end
5295       && stop_func_sal.pc != ecs->stop_func_start
5296       && stop_func_sal.end < ecs->stop_func_end)
5297     ecs->stop_func_start = stop_func_sal.end;
5298
5299   /* Architectures which require breakpoint adjustment might not be able
5300      to place a breakpoint at the computed address.  If so, the test
5301      ``ecs->stop_func_start == stop_pc'' will never succeed.  Adjust
5302      ecs->stop_func_start to an address at which a breakpoint may be
5303      legitimately placed.
5304
5305      Note:  kevinb/2004-01-19:  On FR-V, if this adjustment is not
5306      made, GDB will enter an infinite loop when stepping through
5307      optimized code consisting of VLIW instructions which contain
5308      subinstructions corresponding to different source lines.  On
5309      FR-V, it's not permitted to place a breakpoint on any but the
5310      first subinstruction of a VLIW instruction.  When a breakpoint is
5311      set, GDB will adjust the breakpoint address to the beginning of
5312      the VLIW instruction.  Thus, we need to make the corresponding
5313      adjustment here when computing the stop address.  */
5314
5315   if (gdbarch_adjust_breakpoint_address_p (gdbarch))
5316     {
5317       ecs->stop_func_start
5318         = gdbarch_adjust_breakpoint_address (gdbarch,
5319                                              ecs->stop_func_start);
5320     }
5321
5322   if (ecs->stop_func_start == stop_pc)
5323     {
5324       /* We are already there: stop now.  */
5325       ecs->event_thread->control.stop_step = 1;
5326       print_end_stepping_range_reason ();
5327       stop_stepping (ecs);
5328       return;
5329     }
5330   else
5331     {
5332       /* Put the step-breakpoint there and go until there.  */
5333       init_sal (&sr_sal);       /* initialize to zeroes */
5334       sr_sal.pc = ecs->stop_func_start;
5335       sr_sal.section = find_pc_overlay (ecs->stop_func_start);
5336       sr_sal.pspace = get_frame_program_space (get_current_frame ());
5337
5338       /* Do not specify what the fp should be when we stop since on
5339          some machines the prologue is where the new fp value is
5340          established.  */
5341       insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal, null_frame_id);
5342
5343       /* And make sure stepping stops right away then.  */
5344       ecs->event_thread->control.step_range_end
5345         = ecs->event_thread->control.step_range_start;
5346     }
5347   keep_going (ecs);
5348 }
5349
5350 /* Inferior has stepped backward into a subroutine call with source
5351    code that we should not step over.  Do step to the beginning of the
5352    last line of code in it.  */
5353
5354 static void
5355 handle_step_into_function_backward (struct gdbarch *gdbarch,
5356                                     struct execution_control_state *ecs)
5357 {
5358   struct symtab *s;
5359   struct symtab_and_line stop_func_sal;
5360
5361   fill_in_stop_func (gdbarch, ecs);
5362
5363   s = find_pc_symtab (stop_pc);
5364   if (s && s->language != language_asm)
5365     ecs->stop_func_start = gdbarch_skip_prologue (gdbarch,
5366                                                   ecs->stop_func_start);
5367
5368   stop_func_sal = find_pc_line (stop_pc, 0);
5369
5370   /* OK, we're just going to keep stepping here.  */
5371   if (stop_func_sal.pc == stop_pc)
5372     {
5373       /* We're there already.  Just stop stepping now.  */
5374       ecs->event_thread->control.stop_step = 1;
5375       print_end_stepping_range_reason ();
5376       stop_stepping (ecs);
5377     }
5378   else
5379     {
5380       /* Else just reset the step range and keep going.
5381          No step-resume breakpoint, they don't work for
5382          epilogues, which can have multiple entry paths.  */
5383       ecs->event_thread->control.step_range_start = stop_func_sal.pc;
5384       ecs->event_thread->control.step_range_end = stop_func_sal.end;
5385       keep_going (ecs);
5386     }
5387   return;
5388 }
5389
5390 /* Insert a "step-resume breakpoint" at SR_SAL with frame ID SR_ID.
5391    This is used to both functions and to skip over code.  */
5392
5393 static void
5394 insert_step_resume_breakpoint_at_sal_1 (struct gdbarch *gdbarch,
5395                                         struct symtab_and_line sr_sal,
5396                                         struct frame_id sr_id,
5397                                         enum bptype sr_type)
5398 {
5399   /* There should never be more than one step-resume or longjmp-resume
5400      breakpoint per thread, so we should never be setting a new
5401      step_resume_breakpoint when one is already active.  */
5402   gdb_assert (inferior_thread ()->control.step_resume_breakpoint == NULL);
5403   gdb_assert (sr_type == bp_step_resume || sr_type == bp_hp_step_resume);
5404
5405   if (debug_infrun)
5406     fprintf_unfiltered (gdb_stdlog,
5407                         "infrun: inserting step-resume breakpoint at %s\n",
5408                         paddress (gdbarch, sr_sal.pc));
5409
5410   inferior_thread ()->control.step_resume_breakpoint
5411     = set_momentary_breakpoint (gdbarch, sr_sal, sr_id, sr_type);
5412 }
5413
5414 void
5415 insert_step_resume_breakpoint_at_sal (struct gdbarch *gdbarch,
5416                                       struct symtab_and_line sr_sal,
5417                                       struct frame_id sr_id)
5418 {
5419   insert_step_resume_breakpoint_at_sal_1 (gdbarch,
5420                                           sr_sal, sr_id,
5421                                           bp_step_resume);
5422 }
5423
5424 /* Insert a "high-priority step-resume breakpoint" at RETURN_FRAME.pc.
5425    This is used to skip a potential signal handler.
5426
5427    This is called with the interrupted function's frame.  The signal
5428    handler, when it returns, will resume the interrupted function at
5429    RETURN_FRAME.pc.  */
5430
5431 static void
5432 insert_hp_step_resume_breakpoint_at_frame (struct frame_info *return_frame)
5433 {
5434   struct symtab_and_line sr_sal;
5435   struct gdbarch *gdbarch;
5436
5437   gdb_assert (return_frame != NULL);
5438   init_sal (&sr_sal);           /* initialize to zeros */
5439
5440   gdbarch = get_frame_arch (return_frame);
5441   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch, get_frame_pc (return_frame));
5442   sr_sal.section = find_pc_overlay (sr_sal.pc);
5443   sr_sal.pspace = get_frame_program_space (return_frame);
5444
5445   insert_step_resume_breakpoint_at_sal_1 (gdbarch, sr_sal,
5446                                           get_stack_frame_id (return_frame),
5447                                           bp_hp_step_resume);
5448 }
5449
5450 /* Insert a "step-resume breakpoint" at the previous frame's PC.  This
5451    is used to skip a function after stepping into it (for "next" or if
5452    the called function has no debugging information).
5453
5454    The current function has almost always been reached by single
5455    stepping a call or return instruction.  NEXT_FRAME belongs to the
5456    current function, and the breakpoint will be set at the caller's
5457    resume address.
5458
5459    This is a separate function rather than reusing
5460    insert_hp_step_resume_breakpoint_at_frame in order to avoid
5461    get_prev_frame, which may stop prematurely (see the implementation
5462    of frame_unwind_caller_id for an example).  */
5463
5464 static void
5465 insert_step_resume_breakpoint_at_caller (struct frame_info *next_frame)
5466 {
5467   struct symtab_and_line sr_sal;
5468   struct gdbarch *gdbarch;
5469
5470   /* We shouldn't have gotten here if we don't know where the call site
5471      is.  */
5472   gdb_assert (frame_id_p (frame_unwind_caller_id (next_frame)));
5473
5474   init_sal (&sr_sal);           /* initialize to zeros */
5475
5476   gdbarch = frame_unwind_caller_arch (next_frame);
5477   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch,
5478                                         frame_unwind_caller_pc (next_frame));
5479   sr_sal.section = find_pc_overlay (sr_sal.pc);
5480   sr_sal.pspace = frame_unwind_program_space (next_frame);
5481
5482   insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal,
5483                                         frame_unwind_caller_id (next_frame));
5484 }
5485
5486 /* Insert a "longjmp-resume" breakpoint at PC.  This is used to set a
5487    new breakpoint at the target of a jmp_buf.  The handling of
5488    longjmp-resume uses the same mechanisms used for handling
5489    "step-resume" breakpoints.  */
5490
5491 static void
5492 insert_longjmp_resume_breakpoint (struct gdbarch *gdbarch, CORE_ADDR pc)
5493 {
5494   /* There should never be more than one longjmp-resume breakpoint per
5495      thread, so we should never be setting a new
5496      longjmp_resume_breakpoint when one is already active.  */
5497   gdb_assert (inferior_thread ()->control.exception_resume_breakpoint == NULL);
5498
5499   if (debug_infrun)
5500     fprintf_unfiltered (gdb_stdlog,
5501                         "infrun: inserting longjmp-resume breakpoint at %s\n",
5502                         paddress (gdbarch, pc));
5503
5504   inferior_thread ()->control.exception_resume_breakpoint =
5505     set_momentary_breakpoint_at_pc (gdbarch, pc, bp_longjmp_resume);
5506 }
5507
5508 /* Insert an exception resume breakpoint.  TP is the thread throwing
5509    the exception.  The block B is the block of the unwinder debug hook
5510    function.  FRAME is the frame corresponding to the call to this
5511    function.  SYM is the symbol of the function argument holding the
5512    target PC of the exception.  */
5513
5514 static void
5515 insert_exception_resume_breakpoint (struct thread_info *tp,
5516                                     struct block *b,
5517                                     struct frame_info *frame,
5518                                     struct symbol *sym)
5519 {
5520   volatile struct gdb_exception e;
5521
5522   /* We want to ignore errors here.  */
5523   TRY_CATCH (e, RETURN_MASK_ERROR)
5524     {
5525       struct symbol *vsym;
5526       struct value *value;
5527       CORE_ADDR handler;
5528       struct breakpoint *bp;
5529
5530       vsym = lookup_symbol (SYMBOL_LINKAGE_NAME (sym), b, VAR_DOMAIN, NULL);
5531       value = read_var_value (vsym, frame);
5532       /* If the value was optimized out, revert to the old behavior.  */
5533       if (! value_optimized_out (value))
5534         {
5535           handler = value_as_address (value);
5536
5537           if (debug_infrun)
5538             fprintf_unfiltered (gdb_stdlog,
5539                                 "infrun: exception resume at %lx\n",
5540                                 (unsigned long) handler);
5541
5542           bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
5543                                                handler, bp_exception_resume);
5544
5545           /* set_momentary_breakpoint_at_pc invalidates FRAME.  */
5546           frame = NULL;
5547
5548           bp->thread = tp->num;
5549           inferior_thread ()->control.exception_resume_breakpoint = bp;
5550         }
5551     }
5552 }
5553
5554 /* A helper for check_exception_resume that sets an
5555    exception-breakpoint based on a SystemTap probe.  */
5556
5557 static void
5558 insert_exception_resume_from_probe (struct thread_info *tp,
5559                                     const struct probe *probe,
5560                                     struct frame_info *frame)
5561 {
5562   struct value *arg_value;
5563   CORE_ADDR handler;
5564   struct breakpoint *bp;
5565
5566   arg_value = probe_safe_evaluate_at_pc (frame, 1);
5567   if (!arg_value)
5568     return;
5569
5570   handler = value_as_address (arg_value);
5571
5572   if (debug_infrun)
5573     fprintf_unfiltered (gdb_stdlog,
5574                         "infrun: exception resume at %s\n",
5575                         paddress (get_objfile_arch (probe->objfile),
5576                                   handler));
5577
5578   bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
5579                                        handler, bp_exception_resume);
5580   bp->thread = tp->num;
5581   inferior_thread ()->control.exception_resume_breakpoint = bp;
5582 }
5583
5584 /* This is called when an exception has been intercepted.  Check to
5585    see whether the exception's destination is of interest, and if so,
5586    set an exception resume breakpoint there.  */
5587
5588 static void
5589 check_exception_resume (struct execution_control_state *ecs,
5590                         struct frame_info *frame)
5591 {
5592   volatile struct gdb_exception e;
5593   const struct probe *probe;
5594   struct symbol *func;
5595
5596   /* First see if this exception unwinding breakpoint was set via a
5597      SystemTap probe point.  If so, the probe has two arguments: the
5598      CFA and the HANDLER.  We ignore the CFA, extract the handler, and
5599      set a breakpoint there.  */
5600   probe = find_probe_by_pc (get_frame_pc (frame));
5601   if (probe)
5602     {
5603       insert_exception_resume_from_probe (ecs->event_thread, probe, frame);
5604       return;
5605     }
5606
5607   func = get_frame_function (frame);
5608   if (!func)
5609     return;
5610
5611   TRY_CATCH (e, RETURN_MASK_ERROR)
5612     {
5613       struct block *b;
5614       struct block_iterator iter;
5615       struct symbol *sym;
5616       int argno = 0;
5617
5618       /* The exception breakpoint is a thread-specific breakpoint on
5619          the unwinder's debug hook, declared as:
5620          
5621          void _Unwind_DebugHook (void *cfa, void *handler);
5622          
5623          The CFA argument indicates the frame to which control is
5624          about to be transferred.  HANDLER is the destination PC.
5625          
5626          We ignore the CFA and set a temporary breakpoint at HANDLER.
5627          This is not extremely efficient but it avoids issues in gdb
5628          with computing the DWARF CFA, and it also works even in weird
5629          cases such as throwing an exception from inside a signal
5630          handler.  */
5631
5632       b = SYMBOL_BLOCK_VALUE (func);
5633       ALL_BLOCK_SYMBOLS (b, iter, sym)
5634         {
5635           if (!SYMBOL_IS_ARGUMENT (sym))
5636             continue;
5637
5638           if (argno == 0)
5639             ++argno;
5640           else
5641             {
5642               insert_exception_resume_breakpoint (ecs->event_thread,
5643                                                   b, frame, sym);
5644               break;
5645             }
5646         }
5647     }
5648 }
5649
5650 static void
5651 stop_stepping (struct execution_control_state *ecs)
5652 {
5653   if (debug_infrun)
5654     fprintf_unfiltered (gdb_stdlog, "infrun: stop_stepping\n");
5655
5656   /* Let callers know we don't want to wait for the inferior anymore.  */
5657   ecs->wait_some_more = 0;
5658 }
5659
5660 /* This function handles various cases where we need to continue
5661    waiting for the inferior.  */
5662 /* (Used to be the keep_going: label in the old wait_for_inferior).  */
5663
5664 static void
5665 keep_going (struct execution_control_state *ecs)
5666 {
5667   /* Make sure normal_stop is called if we get a QUIT handled before
5668      reaching resume.  */
5669   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
5670
5671   /* Save the pc before execution, to compare with pc after stop.  */
5672   ecs->event_thread->prev_pc
5673     = regcache_read_pc (get_thread_regcache (ecs->ptid));
5674
5675   /* If we did not do break;, it means we should keep running the
5676      inferior and not return to debugger.  */
5677
5678   if (ecs->event_thread->control.trap_expected
5679       && ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_TRAP)
5680     {
5681       /* We took a signal (which we are supposed to pass through to
5682          the inferior, else we'd not get here) and we haven't yet
5683          gotten our trap.  Simply continue.  */
5684
5685       discard_cleanups (old_cleanups);
5686       resume (currently_stepping (ecs->event_thread),
5687               ecs->event_thread->suspend.stop_signal);
5688     }
5689   else
5690     {
5691       /* Either the trap was not expected, but we are continuing
5692          anyway (the user asked that this signal be passed to the
5693          child)
5694          -- or --
5695          The signal was SIGTRAP, e.g. it was our signal, but we
5696          decided we should resume from it.
5697
5698          We're going to run this baby now!  
5699
5700          Note that insert_breakpoints won't try to re-insert
5701          already inserted breakpoints.  Therefore, we don't
5702          care if breakpoints were already inserted, or not.  */
5703       
5704       if (ecs->event_thread->stepping_over_breakpoint)
5705         {
5706           struct regcache *thread_regcache = get_thread_regcache (ecs->ptid);
5707
5708           if (!use_displaced_stepping (get_regcache_arch (thread_regcache)))
5709             /* Since we can't do a displaced step, we have to remove
5710                the breakpoint while we step it.  To keep things
5711                simple, we remove them all.  */
5712             remove_breakpoints ();
5713         }
5714       else
5715         {
5716           volatile struct gdb_exception e;
5717
5718           /* Stop stepping when inserting breakpoints
5719              has failed.  */
5720           TRY_CATCH (e, RETURN_MASK_ERROR)
5721             {
5722               insert_breakpoints ();
5723             }
5724           if (e.reason < 0)
5725             {
5726               exception_print (gdb_stderr, e);
5727               stop_stepping (ecs);
5728               return;
5729             }
5730         }
5731
5732       ecs->event_thread->control.trap_expected
5733         = ecs->event_thread->stepping_over_breakpoint;
5734
5735       /* Do not deliver SIGNAL_TRAP (except when the user explicitly
5736          specifies that such a signal should be delivered to the
5737          target program).
5738
5739          Typically, this would occure when a user is debugging a
5740          target monitor on a simulator: the target monitor sets a
5741          breakpoint; the simulator encounters this break-point and
5742          halts the simulation handing control to GDB; GDB, noteing
5743          that the break-point isn't valid, returns control back to the
5744          simulator; the simulator then delivers the hardware
5745          equivalent of a SIGNAL_TRAP to the program being debugged.  */
5746
5747       if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5748           && !signal_program[ecs->event_thread->suspend.stop_signal])
5749         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5750
5751       discard_cleanups (old_cleanups);
5752       resume (currently_stepping (ecs->event_thread),
5753               ecs->event_thread->suspend.stop_signal);
5754     }
5755
5756   prepare_to_wait (ecs);
5757 }
5758
5759 /* This function normally comes after a resume, before
5760    handle_inferior_event exits.  It takes care of any last bits of
5761    housekeeping, and sets the all-important wait_some_more flag.  */
5762
5763 static void
5764 prepare_to_wait (struct execution_control_state *ecs)
5765 {
5766   if (debug_infrun)
5767     fprintf_unfiltered (gdb_stdlog, "infrun: prepare_to_wait\n");
5768
5769   /* This is the old end of the while loop.  Let everybody know we
5770      want to wait for the inferior some more and get called again
5771      soon.  */
5772   ecs->wait_some_more = 1;
5773 }
5774
5775 /* Several print_*_reason functions to print why the inferior has stopped.
5776    We always print something when the inferior exits, or receives a signal.
5777    The rest of the cases are dealt with later on in normal_stop and
5778    print_it_typical.  Ideally there should be a call to one of these
5779    print_*_reason functions functions from handle_inferior_event each time
5780    stop_stepping is called.  */
5781
5782 /* Print why the inferior has stopped.  
5783    We are done with a step/next/si/ni command, print why the inferior has
5784    stopped.  For now print nothing.  Print a message only if not in the middle
5785    of doing a "step n" operation for n > 1.  */
5786
5787 static void
5788 print_end_stepping_range_reason (void)
5789 {
5790   if ((!inferior_thread ()->step_multi
5791        || !inferior_thread ()->control.stop_step)
5792       && ui_out_is_mi_like_p (current_uiout))
5793     ui_out_field_string (current_uiout, "reason",
5794                          async_reason_lookup (EXEC_ASYNC_END_STEPPING_RANGE));
5795 }
5796
5797 /* The inferior was terminated by a signal, print why it stopped.  */
5798
5799 static void
5800 print_signal_exited_reason (enum gdb_signal siggnal)
5801 {
5802   struct ui_out *uiout = current_uiout;
5803
5804   annotate_signalled ();
5805   if (ui_out_is_mi_like_p (uiout))
5806     ui_out_field_string
5807       (uiout, "reason", async_reason_lookup (EXEC_ASYNC_EXITED_SIGNALLED));
5808   ui_out_text (uiout, "\nProgram terminated with signal ");
5809   annotate_signal_name ();
5810   ui_out_field_string (uiout, "signal-name",
5811                        gdb_signal_to_name (siggnal));
5812   annotate_signal_name_end ();
5813   ui_out_text (uiout, ", ");
5814   annotate_signal_string ();
5815   ui_out_field_string (uiout, "signal-meaning",
5816                        gdb_signal_to_string (siggnal));
5817   annotate_signal_string_end ();
5818   ui_out_text (uiout, ".\n");
5819   ui_out_text (uiout, "The program no longer exists.\n");
5820 }
5821
5822 /* The inferior program is finished, print why it stopped.  */
5823
5824 static void
5825 print_exited_reason (int exitstatus)
5826 {
5827   struct inferior *inf = current_inferior ();
5828   const char *pidstr = target_pid_to_str (pid_to_ptid (inf->pid));
5829   struct ui_out *uiout = current_uiout;
5830
5831   annotate_exited (exitstatus);
5832   if (exitstatus)
5833     {
5834       if (ui_out_is_mi_like_p (uiout))
5835         ui_out_field_string (uiout, "reason", 
5836                              async_reason_lookup (EXEC_ASYNC_EXITED));
5837       ui_out_text (uiout, "[Inferior ");
5838       ui_out_text (uiout, plongest (inf->num));
5839       ui_out_text (uiout, " (");
5840       ui_out_text (uiout, pidstr);
5841       ui_out_text (uiout, ") exited with code ");
5842       ui_out_field_fmt (uiout, "exit-code", "0%o", (unsigned int) exitstatus);
5843       ui_out_text (uiout, "]\n");
5844     }
5845   else
5846     {
5847       if (ui_out_is_mi_like_p (uiout))
5848         ui_out_field_string
5849           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_EXITED_NORMALLY));
5850       ui_out_text (uiout, "[Inferior ");
5851       ui_out_text (uiout, plongest (inf->num));
5852       ui_out_text (uiout, " (");
5853       ui_out_text (uiout, pidstr);
5854       ui_out_text (uiout, ") exited normally]\n");
5855     }
5856   /* Support the --return-child-result option.  */
5857   return_child_result_value = exitstatus;
5858 }
5859
5860 /* Signal received, print why the inferior has stopped.  The signal table
5861    tells us to print about it.  */
5862
5863 static void
5864 print_signal_received_reason (enum gdb_signal siggnal)
5865 {
5866   struct ui_out *uiout = current_uiout;
5867
5868   annotate_signal ();
5869
5870   if (siggnal == GDB_SIGNAL_0 && !ui_out_is_mi_like_p (uiout))
5871     {
5872       struct thread_info *t = inferior_thread ();
5873
5874       ui_out_text (uiout, "\n[");
5875       ui_out_field_string (uiout, "thread-name",
5876                            target_pid_to_str (t->ptid));
5877       ui_out_field_fmt (uiout, "thread-id", "] #%d", t->num);
5878       ui_out_text (uiout, " stopped");
5879     }
5880   else
5881     {
5882       ui_out_text (uiout, "\nProgram received signal ");
5883       annotate_signal_name ();
5884       if (ui_out_is_mi_like_p (uiout))
5885         ui_out_field_string
5886           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_SIGNAL_RECEIVED));
5887       ui_out_field_string (uiout, "signal-name",
5888                            gdb_signal_to_name (siggnal));
5889       annotate_signal_name_end ();
5890       ui_out_text (uiout, ", ");
5891       annotate_signal_string ();
5892       ui_out_field_string (uiout, "signal-meaning",
5893                            gdb_signal_to_string (siggnal));
5894       annotate_signal_string_end ();
5895     }
5896   ui_out_text (uiout, ".\n");
5897 }
5898
5899 /* Reverse execution: target ran out of history info, print why the inferior
5900    has stopped.  */
5901
5902 static void
5903 print_no_history_reason (void)
5904 {
5905   ui_out_text (current_uiout, "\nNo more reverse-execution history.\n");
5906 }
5907
5908 /* Here to return control to GDB when the inferior stops for real.
5909    Print appropriate messages, remove breakpoints, give terminal our modes.
5910
5911    STOP_PRINT_FRAME nonzero means print the executing frame
5912    (pc, function, args, file, line number and line text).
5913    BREAKPOINTS_FAILED nonzero means stop was due to error
5914    attempting to insert breakpoints.  */
5915
5916 void
5917 normal_stop (void)
5918 {
5919   struct target_waitstatus last;
5920   ptid_t last_ptid;
5921   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
5922
5923   get_last_target_status (&last_ptid, &last);
5924
5925   /* If an exception is thrown from this point on, make sure to
5926      propagate GDB's knowledge of the executing state to the
5927      frontend/user running state.  A QUIT is an easy exception to see
5928      here, so do this before any filtered output.  */
5929   if (!non_stop)
5930     make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
5931   else if (last.kind != TARGET_WAITKIND_SIGNALLED
5932            && last.kind != TARGET_WAITKIND_EXITED
5933            && last.kind != TARGET_WAITKIND_NO_RESUMED)
5934     make_cleanup (finish_thread_state_cleanup, &inferior_ptid);
5935
5936   /* In non-stop mode, we don't want GDB to switch threads behind the
5937      user's back, to avoid races where the user is typing a command to
5938      apply to thread x, but GDB switches to thread y before the user
5939      finishes entering the command.  */
5940
5941   /* As with the notification of thread events, we want to delay
5942      notifying the user that we've switched thread context until
5943      the inferior actually stops.
5944
5945      There's no point in saying anything if the inferior has exited.
5946      Note that SIGNALLED here means "exited with a signal", not
5947      "received a signal".  */
5948   if (!non_stop
5949       && !ptid_equal (previous_inferior_ptid, inferior_ptid)
5950       && target_has_execution
5951       && last.kind != TARGET_WAITKIND_SIGNALLED
5952       && last.kind != TARGET_WAITKIND_EXITED
5953       && last.kind != TARGET_WAITKIND_NO_RESUMED)
5954     {
5955       target_terminal_ours_for_output ();
5956       printf_filtered (_("[Switching to %s]\n"),
5957                        target_pid_to_str (inferior_ptid));
5958       annotate_thread_changed ();
5959       previous_inferior_ptid = inferior_ptid;
5960     }
5961
5962   if (last.kind == TARGET_WAITKIND_NO_RESUMED)
5963     {
5964       gdb_assert (sync_execution || !target_can_async_p ());
5965
5966       target_terminal_ours_for_output ();
5967       printf_filtered (_("No unwaited-for children left.\n"));
5968     }
5969
5970   if (!breakpoints_always_inserted_mode () && target_has_execution)
5971     {
5972       if (remove_breakpoints ())
5973         {
5974           target_terminal_ours_for_output ();
5975           printf_filtered (_("Cannot remove breakpoints because "
5976                              "program is no longer writable.\nFurther "
5977                              "execution is probably impossible.\n"));
5978         }
5979     }
5980
5981   /* If an auto-display called a function and that got a signal,
5982      delete that auto-display to avoid an infinite recursion.  */
5983
5984   if (stopped_by_random_signal)
5985     disable_current_display ();
5986
5987   /* Don't print a message if in the middle of doing a "step n"
5988      operation for n > 1 */
5989   if (target_has_execution
5990       && last.kind != TARGET_WAITKIND_SIGNALLED
5991       && last.kind != TARGET_WAITKIND_EXITED
5992       && inferior_thread ()->step_multi
5993       && inferior_thread ()->control.stop_step)
5994     goto done;
5995
5996   target_terminal_ours ();
5997   async_enable_stdin ();
5998
5999   /* Set the current source location.  This will also happen if we
6000      display the frame below, but the current SAL will be incorrect
6001      during a user hook-stop function.  */
6002   if (has_stack_frames () && !stop_stack_dummy)
6003     set_current_sal_from_frame (get_current_frame (), 1);
6004
6005   /* Let the user/frontend see the threads as stopped.  */
6006   do_cleanups (old_chain);
6007
6008   /* Look up the hook_stop and run it (CLI internally handles problem
6009      of stop_command's pre-hook not existing).  */
6010   if (stop_command)
6011     catch_errors (hook_stop_stub, stop_command,
6012                   "Error while running hook_stop:\n", RETURN_MASK_ALL);
6013
6014   if (!has_stack_frames ())
6015     goto done;
6016
6017   if (last.kind == TARGET_WAITKIND_SIGNALLED
6018       || last.kind == TARGET_WAITKIND_EXITED)
6019     goto done;
6020
6021   /* Select innermost stack frame - i.e., current frame is frame 0,
6022      and current location is based on that.
6023      Don't do this on return from a stack dummy routine,
6024      or if the program has exited.  */
6025
6026   if (!stop_stack_dummy)
6027     {
6028       select_frame (get_current_frame ());
6029
6030       /* Print current location without a level number, if
6031          we have changed functions or hit a breakpoint.
6032          Print source line if we have one.
6033          bpstat_print() contains the logic deciding in detail
6034          what to print, based on the event(s) that just occurred.  */
6035
6036       /* If --batch-silent is enabled then there's no need to print the current
6037          source location, and to try risks causing an error message about
6038          missing source files.  */
6039       if (stop_print_frame && !batch_silent)
6040         {
6041           int bpstat_ret;
6042           int source_flag;
6043           int do_frame_printing = 1;
6044           struct thread_info *tp = inferior_thread ();
6045
6046           bpstat_ret = bpstat_print (tp->control.stop_bpstat, last.kind);
6047           switch (bpstat_ret)
6048             {
6049             case PRINT_UNKNOWN:
6050               /* FIXME: cagney/2002-12-01: Given that a frame ID does
6051                  (or should) carry around the function and does (or
6052                  should) use that when doing a frame comparison.  */
6053               if (tp->control.stop_step
6054                   && frame_id_eq (tp->control.step_frame_id,
6055                                   get_frame_id (get_current_frame ()))
6056                   && step_start_function == find_pc_function (stop_pc))
6057                 source_flag = SRC_LINE;         /* Finished step, just
6058                                                    print source line.  */
6059               else
6060                 source_flag = SRC_AND_LOC;      /* Print location and
6061                                                    source line.  */
6062               break;
6063             case PRINT_SRC_AND_LOC:
6064               source_flag = SRC_AND_LOC;        /* Print location and
6065                                                    source line.  */
6066               break;
6067             case PRINT_SRC_ONLY:
6068               source_flag = SRC_LINE;
6069               break;
6070             case PRINT_NOTHING:
6071               source_flag = SRC_LINE;   /* something bogus */
6072               do_frame_printing = 0;
6073               break;
6074             default:
6075               internal_error (__FILE__, __LINE__, _("Unknown value."));
6076             }
6077
6078           /* The behavior of this routine with respect to the source
6079              flag is:
6080              SRC_LINE: Print only source line
6081              LOCATION: Print only location
6082              SRC_AND_LOC: Print location and source line.  */
6083           if (do_frame_printing)
6084             print_stack_frame (get_selected_frame (NULL), 0, source_flag);
6085
6086           /* Display the auto-display expressions.  */
6087           do_displays ();
6088         }
6089     }
6090
6091   /* Save the function value return registers, if we care.
6092      We might be about to restore their previous contents.  */
6093   if (inferior_thread ()->control.proceed_to_finish
6094       && execution_direction != EXEC_REVERSE)
6095     {
6096       /* This should not be necessary.  */
6097       if (stop_registers)
6098         regcache_xfree (stop_registers);
6099
6100       /* NB: The copy goes through to the target picking up the value of
6101          all the registers.  */
6102       stop_registers = regcache_dup (get_current_regcache ());
6103     }
6104
6105   if (stop_stack_dummy == STOP_STACK_DUMMY)
6106     {
6107       /* Pop the empty frame that contains the stack dummy.
6108          This also restores inferior state prior to the call
6109          (struct infcall_suspend_state).  */
6110       struct frame_info *frame = get_current_frame ();
6111
6112       gdb_assert (get_frame_type (frame) == DUMMY_FRAME);
6113       frame_pop (frame);
6114       /* frame_pop() calls reinit_frame_cache as the last thing it
6115          does which means there's currently no selected frame.  We
6116          don't need to re-establish a selected frame if the dummy call
6117          returns normally, that will be done by
6118          restore_infcall_control_state.  However, we do have to handle
6119          the case where the dummy call is returning after being
6120          stopped (e.g. the dummy call previously hit a breakpoint).
6121          We can't know which case we have so just always re-establish
6122          a selected frame here.  */
6123       select_frame (get_current_frame ());
6124     }
6125
6126 done:
6127   annotate_stopped ();
6128
6129   /* Suppress the stop observer if we're in the middle of:
6130
6131      - a step n (n > 1), as there still more steps to be done.
6132
6133      - a "finish" command, as the observer will be called in
6134        finish_command_continuation, so it can include the inferior
6135        function's return value.
6136
6137      - calling an inferior function, as we pretend we inferior didn't
6138        run at all.  The return value of the call is handled by the
6139        expression evaluator, through call_function_by_hand.  */
6140
6141   if (!target_has_execution
6142       || last.kind == TARGET_WAITKIND_SIGNALLED
6143       || last.kind == TARGET_WAITKIND_EXITED
6144       || last.kind == TARGET_WAITKIND_NO_RESUMED
6145       || (!(inferior_thread ()->step_multi
6146             && inferior_thread ()->control.stop_step)
6147           && !(inferior_thread ()->control.stop_bpstat
6148                && inferior_thread ()->control.proceed_to_finish)
6149           && !inferior_thread ()->control.in_infcall))
6150     {
6151       if (!ptid_equal (inferior_ptid, null_ptid))
6152         observer_notify_normal_stop (inferior_thread ()->control.stop_bpstat,
6153                                      stop_print_frame);
6154       else
6155         observer_notify_normal_stop (NULL, stop_print_frame);
6156     }
6157
6158   if (target_has_execution)
6159     {
6160       if (last.kind != TARGET_WAITKIND_SIGNALLED
6161           && last.kind != TARGET_WAITKIND_EXITED)
6162         /* Delete the breakpoint we stopped at, if it wants to be deleted.
6163            Delete any breakpoint that is to be deleted at the next stop.  */
6164         breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
6165     }
6166
6167   /* Try to get rid of automatically added inferiors that are no
6168      longer needed.  Keeping those around slows down things linearly.
6169      Note that this never removes the current inferior.  */
6170   prune_inferiors ();
6171 }
6172
6173 static int
6174 hook_stop_stub (void *cmd)
6175 {
6176   execute_cmd_pre_hook ((struct cmd_list_element *) cmd);
6177   return (0);
6178 }
6179 \f
6180 int
6181 signal_stop_state (int signo)
6182 {
6183   return signal_stop[signo];
6184 }
6185
6186 int
6187 signal_print_state (int signo)
6188 {
6189   return signal_print[signo];
6190 }
6191
6192 int
6193 signal_pass_state (int signo)
6194 {
6195   return signal_program[signo];
6196 }
6197
6198 static void
6199 signal_cache_update (int signo)
6200 {
6201   if (signo == -1)
6202     {
6203       for (signo = 0; signo < (int) GDB_SIGNAL_LAST; signo++)
6204         signal_cache_update (signo);
6205
6206       return;
6207     }
6208
6209   signal_pass[signo] = (signal_stop[signo] == 0
6210                         && signal_print[signo] == 0
6211                         && signal_program[signo] == 1
6212                         && signal_catch[signo] == 0);
6213 }
6214
6215 int
6216 signal_stop_update (int signo, int state)
6217 {
6218   int ret = signal_stop[signo];
6219
6220   signal_stop[signo] = state;
6221   signal_cache_update (signo);
6222   return ret;
6223 }
6224
6225 int
6226 signal_print_update (int signo, int state)
6227 {
6228   int ret = signal_print[signo];
6229
6230   signal_print[signo] = state;
6231   signal_cache_update (signo);
6232   return ret;
6233 }
6234
6235 int
6236 signal_pass_update (int signo, int state)
6237 {
6238   int ret = signal_program[signo];
6239
6240   signal_program[signo] = state;
6241   signal_cache_update (signo);
6242   return ret;
6243 }
6244
6245 /* Update the global 'signal_catch' from INFO and notify the
6246    target.  */
6247
6248 void
6249 signal_catch_update (const unsigned int *info)
6250 {
6251   int i;
6252
6253   for (i = 0; i < GDB_SIGNAL_LAST; ++i)
6254     signal_catch[i] = info[i] > 0;
6255   signal_cache_update (-1);
6256   target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
6257 }
6258
6259 static void
6260 sig_print_header (void)
6261 {
6262   printf_filtered (_("Signal        Stop\tPrint\tPass "
6263                      "to program\tDescription\n"));
6264 }
6265
6266 static void
6267 sig_print_info (enum gdb_signal oursig)
6268 {
6269   const char *name = gdb_signal_to_name (oursig);
6270   int name_padding = 13 - strlen (name);
6271
6272   if (name_padding <= 0)
6273     name_padding = 0;
6274
6275   printf_filtered ("%s", name);
6276   printf_filtered ("%*.*s ", name_padding, name_padding, "                 ");
6277   printf_filtered ("%s\t", signal_stop[oursig] ? "Yes" : "No");
6278   printf_filtered ("%s\t", signal_print[oursig] ? "Yes" : "No");
6279   printf_filtered ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
6280   printf_filtered ("%s\n", gdb_signal_to_string (oursig));
6281 }
6282
6283 /* Specify how various signals in the inferior should be handled.  */
6284
6285 static void
6286 handle_command (char *args, int from_tty)
6287 {
6288   char **argv;
6289   int digits, wordlen;
6290   int sigfirst, signum, siglast;
6291   enum gdb_signal oursig;
6292   int allsigs;
6293   int nsigs;
6294   unsigned char *sigs;
6295   struct cleanup *old_chain;
6296
6297   if (args == NULL)
6298     {
6299       error_no_arg (_("signal to handle"));
6300     }
6301
6302   /* Allocate and zero an array of flags for which signals to handle.  */
6303
6304   nsigs = (int) GDB_SIGNAL_LAST;
6305   sigs = (unsigned char *) alloca (nsigs);
6306   memset (sigs, 0, nsigs);
6307
6308   /* Break the command line up into args.  */
6309
6310   argv = gdb_buildargv (args);
6311   old_chain = make_cleanup_freeargv (argv);
6312
6313   /* Walk through the args, looking for signal oursigs, signal names, and
6314      actions.  Signal numbers and signal names may be interspersed with
6315      actions, with the actions being performed for all signals cumulatively
6316      specified.  Signal ranges can be specified as <LOW>-<HIGH>.  */
6317
6318   while (*argv != NULL)
6319     {
6320       wordlen = strlen (*argv);
6321       for (digits = 0; isdigit ((*argv)[digits]); digits++)
6322         {;
6323         }
6324       allsigs = 0;
6325       sigfirst = siglast = -1;
6326
6327       if (wordlen >= 1 && !strncmp (*argv, "all", wordlen))
6328         {
6329           /* Apply action to all signals except those used by the
6330              debugger.  Silently skip those.  */
6331           allsigs = 1;
6332           sigfirst = 0;
6333           siglast = nsigs - 1;
6334         }
6335       else if (wordlen >= 1 && !strncmp (*argv, "stop", wordlen))
6336         {
6337           SET_SIGS (nsigs, sigs, signal_stop);
6338           SET_SIGS (nsigs, sigs, signal_print);
6339         }
6340       else if (wordlen >= 1 && !strncmp (*argv, "ignore", wordlen))
6341         {
6342           UNSET_SIGS (nsigs, sigs, signal_program);
6343         }
6344       else if (wordlen >= 2 && !strncmp (*argv, "print", wordlen))
6345         {
6346           SET_SIGS (nsigs, sigs, signal_print);
6347         }
6348       else if (wordlen >= 2 && !strncmp (*argv, "pass", wordlen))
6349         {
6350           SET_SIGS (nsigs, sigs, signal_program);
6351         }
6352       else if (wordlen >= 3 && !strncmp (*argv, "nostop", wordlen))
6353         {
6354           UNSET_SIGS (nsigs, sigs, signal_stop);
6355         }
6356       else if (wordlen >= 3 && !strncmp (*argv, "noignore", wordlen))
6357         {
6358           SET_SIGS (nsigs, sigs, signal_program);
6359         }
6360       else if (wordlen >= 4 && !strncmp (*argv, "noprint", wordlen))
6361         {
6362           UNSET_SIGS (nsigs, sigs, signal_print);
6363           UNSET_SIGS (nsigs, sigs, signal_stop);
6364         }
6365       else if (wordlen >= 4 && !strncmp (*argv, "nopass", wordlen))
6366         {
6367           UNSET_SIGS (nsigs, sigs, signal_program);
6368         }
6369       else if (digits > 0)
6370         {
6371           /* It is numeric.  The numeric signal refers to our own
6372              internal signal numbering from target.h, not to host/target
6373              signal  number.  This is a feature; users really should be
6374              using symbolic names anyway, and the common ones like
6375              SIGHUP, SIGINT, SIGALRM, etc. will work right anyway.  */
6376
6377           sigfirst = siglast = (int)
6378             gdb_signal_from_command (atoi (*argv));
6379           if ((*argv)[digits] == '-')
6380             {
6381               siglast = (int)
6382                 gdb_signal_from_command (atoi ((*argv) + digits + 1));
6383             }
6384           if (sigfirst > siglast)
6385             {
6386               /* Bet he didn't figure we'd think of this case...  */
6387               signum = sigfirst;
6388               sigfirst = siglast;
6389               siglast = signum;
6390             }
6391         }
6392       else
6393         {
6394           oursig = gdb_signal_from_name (*argv);
6395           if (oursig != GDB_SIGNAL_UNKNOWN)
6396             {
6397               sigfirst = siglast = (int) oursig;
6398             }
6399           else
6400             {
6401               /* Not a number and not a recognized flag word => complain.  */
6402               error (_("Unrecognized or ambiguous flag word: \"%s\"."), *argv);
6403             }
6404         }
6405
6406       /* If any signal numbers or symbol names were found, set flags for
6407          which signals to apply actions to.  */
6408
6409       for (signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
6410         {
6411           switch ((enum gdb_signal) signum)
6412             {
6413             case GDB_SIGNAL_TRAP:
6414             case GDB_SIGNAL_INT:
6415               if (!allsigs && !sigs[signum])
6416                 {
6417                   if (query (_("%s is used by the debugger.\n\
6418 Are you sure you want to change it? "),
6419                              gdb_signal_to_name ((enum gdb_signal) signum)))
6420                     {
6421                       sigs[signum] = 1;
6422                     }
6423                   else
6424                     {
6425                       printf_unfiltered (_("Not confirmed, unchanged.\n"));
6426                       gdb_flush (gdb_stdout);
6427                     }
6428                 }
6429               break;
6430             case GDB_SIGNAL_0:
6431             case GDB_SIGNAL_DEFAULT:
6432             case GDB_SIGNAL_UNKNOWN:
6433               /* Make sure that "all" doesn't print these.  */
6434               break;
6435             default:
6436               sigs[signum] = 1;
6437               break;
6438             }
6439         }
6440
6441       argv++;
6442     }
6443
6444   for (signum = 0; signum < nsigs; signum++)
6445     if (sigs[signum])
6446       {
6447         signal_cache_update (-1);
6448         target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
6449         target_program_signals ((int) GDB_SIGNAL_LAST, signal_program);
6450
6451         if (from_tty)
6452           {
6453             /* Show the results.  */
6454             sig_print_header ();
6455             for (; signum < nsigs; signum++)
6456               if (sigs[signum])
6457                 sig_print_info (signum);
6458           }
6459
6460         break;
6461       }
6462
6463   do_cleanups (old_chain);
6464 }
6465
6466 /* Complete the "handle" command.  */
6467
6468 static VEC (char_ptr) *
6469 handle_completer (struct cmd_list_element *ignore,
6470                   const char *text, const char *word)
6471 {
6472   VEC (char_ptr) *vec_signals, *vec_keywords, *return_val;
6473   static const char * const keywords[] =
6474     {
6475       "all",
6476       "stop",
6477       "ignore",
6478       "print",
6479       "pass",
6480       "nostop",
6481       "noignore",
6482       "noprint",
6483       "nopass",
6484       NULL,
6485     };
6486
6487   vec_signals = signal_completer (ignore, text, word);
6488   vec_keywords = complete_on_enum (keywords, word, word);
6489
6490   return_val = VEC_merge (char_ptr, vec_signals, vec_keywords);
6491   VEC_free (char_ptr, vec_signals);
6492   VEC_free (char_ptr, vec_keywords);
6493   return return_val;
6494 }
6495
6496 static void
6497 xdb_handle_command (char *args, int from_tty)
6498 {
6499   char **argv;
6500   struct cleanup *old_chain;
6501
6502   if (args == NULL)
6503     error_no_arg (_("xdb command"));
6504
6505   /* Break the command line up into args.  */
6506
6507   argv = gdb_buildargv (args);
6508   old_chain = make_cleanup_freeargv (argv);
6509   if (argv[1] != (char *) NULL)
6510     {
6511       char *argBuf;
6512       int bufLen;
6513
6514       bufLen = strlen (argv[0]) + 20;
6515       argBuf = (char *) xmalloc (bufLen);
6516       if (argBuf)
6517         {
6518           int validFlag = 1;
6519           enum gdb_signal oursig;
6520
6521           oursig = gdb_signal_from_name (argv[0]);
6522           memset (argBuf, 0, bufLen);
6523           if (strcmp (argv[1], "Q") == 0)
6524             sprintf (argBuf, "%s %s", argv[0], "noprint");
6525           else
6526             {
6527               if (strcmp (argv[1], "s") == 0)
6528                 {
6529                   if (!signal_stop[oursig])
6530                     sprintf (argBuf, "%s %s", argv[0], "stop");
6531                   else
6532                     sprintf (argBuf, "%s %s", argv[0], "nostop");
6533                 }
6534               else if (strcmp (argv[1], "i") == 0)
6535                 {
6536                   if (!signal_program[oursig])
6537                     sprintf (argBuf, "%s %s", argv[0], "pass");
6538                   else
6539                     sprintf (argBuf, "%s %s", argv[0], "nopass");
6540                 }
6541               else if (strcmp (argv[1], "r") == 0)
6542                 {
6543                   if (!signal_print[oursig])
6544                     sprintf (argBuf, "%s %s", argv[0], "print");
6545                   else
6546                     sprintf (argBuf, "%s %s", argv[0], "noprint");
6547                 }
6548               else
6549                 validFlag = 0;
6550             }
6551           if (validFlag)
6552             handle_command (argBuf, from_tty);
6553           else
6554             printf_filtered (_("Invalid signal handling flag.\n"));
6555           if (argBuf)
6556             xfree (argBuf);
6557         }
6558     }
6559   do_cleanups (old_chain);
6560 }
6561
6562 enum gdb_signal
6563 gdb_signal_from_command (int num)
6564 {
6565   if (num >= 1 && num <= 15)
6566     return (enum gdb_signal) num;
6567   error (_("Only signals 1-15 are valid as numeric signals.\n\
6568 Use \"info signals\" for a list of symbolic signals."));
6569 }
6570
6571 /* Print current contents of the tables set by the handle command.
6572    It is possible we should just be printing signals actually used
6573    by the current target (but for things to work right when switching
6574    targets, all signals should be in the signal tables).  */
6575
6576 static void
6577 signals_info (char *signum_exp, int from_tty)
6578 {
6579   enum gdb_signal oursig;
6580
6581   sig_print_header ();
6582
6583   if (signum_exp)
6584     {
6585       /* First see if this is a symbol name.  */
6586       oursig = gdb_signal_from_name (signum_exp);
6587       if (oursig == GDB_SIGNAL_UNKNOWN)
6588         {
6589           /* No, try numeric.  */
6590           oursig =
6591             gdb_signal_from_command (parse_and_eval_long (signum_exp));
6592         }
6593       sig_print_info (oursig);
6594       return;
6595     }
6596
6597   printf_filtered ("\n");
6598   /* These ugly casts brought to you by the native VAX compiler.  */
6599   for (oursig = GDB_SIGNAL_FIRST;
6600        (int) oursig < (int) GDB_SIGNAL_LAST;
6601        oursig = (enum gdb_signal) ((int) oursig + 1))
6602     {
6603       QUIT;
6604
6605       if (oursig != GDB_SIGNAL_UNKNOWN
6606           && oursig != GDB_SIGNAL_DEFAULT && oursig != GDB_SIGNAL_0)
6607         sig_print_info (oursig);
6608     }
6609
6610   printf_filtered (_("\nUse the \"handle\" command "
6611                      "to change these tables.\n"));
6612 }
6613
6614 /* Check if it makes sense to read $_siginfo from the current thread
6615    at this point.  If not, throw an error.  */
6616
6617 static void
6618 validate_siginfo_access (void)
6619 {
6620   /* No current inferior, no siginfo.  */
6621   if (ptid_equal (inferior_ptid, null_ptid))
6622     error (_("No thread selected."));
6623
6624   /* Don't try to read from a dead thread.  */
6625   if (is_exited (inferior_ptid))
6626     error (_("The current thread has terminated"));
6627
6628   /* ... or from a spinning thread.  */
6629   if (is_running (inferior_ptid))
6630     error (_("Selected thread is running."));
6631 }
6632
6633 /* The $_siginfo convenience variable is a bit special.  We don't know
6634    for sure the type of the value until we actually have a chance to
6635    fetch the data.  The type can change depending on gdbarch, so it is
6636    also dependent on which thread you have selected.
6637
6638      1. making $_siginfo be an internalvar that creates a new value on
6639      access.
6640
6641      2. making the value of $_siginfo be an lval_computed value.  */
6642
6643 /* This function implements the lval_computed support for reading a
6644    $_siginfo value.  */
6645
6646 static void
6647 siginfo_value_read (struct value *v)
6648 {
6649   LONGEST transferred;
6650
6651   validate_siginfo_access ();
6652
6653   transferred =
6654     target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO,
6655                  NULL,
6656                  value_contents_all_raw (v),
6657                  value_offset (v),
6658                  TYPE_LENGTH (value_type (v)));
6659
6660   if (transferred != TYPE_LENGTH (value_type (v)))
6661     error (_("Unable to read siginfo"));
6662 }
6663
6664 /* This function implements the lval_computed support for writing a
6665    $_siginfo value.  */
6666
6667 static void
6668 siginfo_value_write (struct value *v, struct value *fromval)
6669 {
6670   LONGEST transferred;
6671
6672   validate_siginfo_access ();
6673
6674   transferred = target_write (&current_target,
6675                               TARGET_OBJECT_SIGNAL_INFO,
6676                               NULL,
6677                               value_contents_all_raw (fromval),
6678                               value_offset (v),
6679                               TYPE_LENGTH (value_type (fromval)));
6680
6681   if (transferred != TYPE_LENGTH (value_type (fromval)))
6682     error (_("Unable to write siginfo"));
6683 }
6684
6685 static const struct lval_funcs siginfo_value_funcs =
6686   {
6687     siginfo_value_read,
6688     siginfo_value_write
6689   };
6690
6691 /* Return a new value with the correct type for the siginfo object of
6692    the current thread using architecture GDBARCH.  Return a void value
6693    if there's no object available.  */
6694
6695 static struct value *
6696 siginfo_make_value (struct gdbarch *gdbarch, struct internalvar *var,
6697                     void *ignore)
6698 {
6699   if (target_has_stack
6700       && !ptid_equal (inferior_ptid, null_ptid)
6701       && gdbarch_get_siginfo_type_p (gdbarch))
6702     {
6703       struct type *type = gdbarch_get_siginfo_type (gdbarch);
6704
6705       return allocate_computed_value (type, &siginfo_value_funcs, NULL);
6706     }
6707
6708   return allocate_value (builtin_type (gdbarch)->builtin_void);
6709 }
6710
6711 \f
6712 /* infcall_suspend_state contains state about the program itself like its
6713    registers and any signal it received when it last stopped.
6714    This state must be restored regardless of how the inferior function call
6715    ends (either successfully, or after it hits a breakpoint or signal)
6716    if the program is to properly continue where it left off.  */
6717
6718 struct infcall_suspend_state
6719 {
6720   struct thread_suspend_state thread_suspend;
6721 #if 0 /* Currently unused and empty structures are not valid C.  */
6722   struct inferior_suspend_state inferior_suspend;
6723 #endif
6724
6725   /* Other fields:  */
6726   CORE_ADDR stop_pc;
6727   struct regcache *registers;
6728
6729   /* Format of SIGINFO_DATA or NULL if it is not present.  */
6730   struct gdbarch *siginfo_gdbarch;
6731
6732   /* The inferior format depends on SIGINFO_GDBARCH and it has a length of
6733      TYPE_LENGTH (gdbarch_get_siginfo_type ()).  For different gdbarch the
6734      content would be invalid.  */
6735   gdb_byte *siginfo_data;
6736 };
6737
6738 struct infcall_suspend_state *
6739 save_infcall_suspend_state (void)
6740 {
6741   struct infcall_suspend_state *inf_state;
6742   struct thread_info *tp = inferior_thread ();
6743 #if 0
6744   struct inferior *inf = current_inferior ();
6745 #endif
6746   struct regcache *regcache = get_current_regcache ();
6747   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6748   gdb_byte *siginfo_data = NULL;
6749
6750   if (gdbarch_get_siginfo_type_p (gdbarch))
6751     {
6752       struct type *type = gdbarch_get_siginfo_type (gdbarch);
6753       size_t len = TYPE_LENGTH (type);
6754       struct cleanup *back_to;
6755
6756       siginfo_data = xmalloc (len);
6757       back_to = make_cleanup (xfree, siginfo_data);
6758
6759       if (target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
6760                        siginfo_data, 0, len) == len)
6761         discard_cleanups (back_to);
6762       else
6763         {
6764           /* Errors ignored.  */
6765           do_cleanups (back_to);
6766           siginfo_data = NULL;
6767         }
6768     }
6769
6770   inf_state = XZALLOC (struct infcall_suspend_state);
6771
6772   if (siginfo_data)
6773     {
6774       inf_state->siginfo_gdbarch = gdbarch;
6775       inf_state->siginfo_data = siginfo_data;
6776     }
6777
6778   inf_state->thread_suspend = tp->suspend;
6779 #if 0 /* Currently unused and empty structures are not valid C.  */
6780   inf_state->inferior_suspend = inf->suspend;
6781 #endif
6782
6783   /* run_inferior_call will not use the signal due to its `proceed' call with
6784      GDB_SIGNAL_0 anyway.  */
6785   tp->suspend.stop_signal = GDB_SIGNAL_0;
6786
6787   inf_state->stop_pc = stop_pc;
6788
6789   inf_state->registers = regcache_dup (regcache);
6790
6791   return inf_state;
6792 }
6793
6794 /* Restore inferior session state to INF_STATE.  */
6795
6796 void
6797 restore_infcall_suspend_state (struct infcall_suspend_state *inf_state)
6798 {
6799   struct thread_info *tp = inferior_thread ();
6800 #if 0
6801   struct inferior *inf = current_inferior ();
6802 #endif
6803   struct regcache *regcache = get_current_regcache ();
6804   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6805
6806   tp->suspend = inf_state->thread_suspend;
6807 #if 0 /* Currently unused and empty structures are not valid C.  */
6808   inf->suspend = inf_state->inferior_suspend;
6809 #endif
6810
6811   stop_pc = inf_state->stop_pc;
6812
6813   if (inf_state->siginfo_gdbarch == gdbarch)
6814     {
6815       struct type *type = gdbarch_get_siginfo_type (gdbarch);
6816
6817       /* Errors ignored.  */
6818       target_write (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
6819                     inf_state->siginfo_data, 0, TYPE_LENGTH (type));
6820     }
6821
6822   /* The inferior can be gone if the user types "print exit(0)"
6823      (and perhaps other times).  */
6824   if (target_has_execution)
6825     /* NB: The register write goes through to the target.  */
6826     regcache_cpy (regcache, inf_state->registers);
6827
6828   discard_infcall_suspend_state (inf_state);
6829 }
6830
6831 static void
6832 do_restore_infcall_suspend_state_cleanup (void *state)
6833 {
6834   restore_infcall_suspend_state (state);
6835 }
6836
6837 struct cleanup *
6838 make_cleanup_restore_infcall_suspend_state
6839   (struct infcall_suspend_state *inf_state)
6840 {
6841   return make_cleanup (do_restore_infcall_suspend_state_cleanup, inf_state);
6842 }
6843
6844 void
6845 discard_infcall_suspend_state (struct infcall_suspend_state *inf_state)
6846 {
6847   regcache_xfree (inf_state->registers);
6848   xfree (inf_state->siginfo_data);
6849   xfree (inf_state);
6850 }
6851
6852 struct regcache *
6853 get_infcall_suspend_state_regcache (struct infcall_suspend_state *inf_state)
6854 {
6855   return inf_state->registers;
6856 }
6857
6858 /* infcall_control_state contains state regarding gdb's control of the
6859    inferior itself like stepping control.  It also contains session state like
6860    the user's currently selected frame.  */
6861
6862 struct infcall_control_state
6863 {
6864   struct thread_control_state thread_control;
6865   struct inferior_control_state inferior_control;
6866
6867   /* Other fields:  */
6868   enum stop_stack_kind stop_stack_dummy;
6869   int stopped_by_random_signal;
6870   int stop_after_trap;
6871
6872   /* ID if the selected frame when the inferior function call was made.  */
6873   struct frame_id selected_frame_id;
6874 };
6875
6876 /* Save all of the information associated with the inferior<==>gdb
6877    connection.  */
6878
6879 struct infcall_control_state *
6880 save_infcall_control_state (void)
6881 {
6882   struct infcall_control_state *inf_status = xmalloc (sizeof (*inf_status));
6883   struct thread_info *tp = inferior_thread ();
6884   struct inferior *inf = current_inferior ();
6885
6886   inf_status->thread_control = tp->control;
6887   inf_status->inferior_control = inf->control;
6888
6889   tp->control.step_resume_breakpoint = NULL;
6890   tp->control.exception_resume_breakpoint = NULL;
6891
6892   /* Save original bpstat chain to INF_STATUS; replace it in TP with copy of
6893      chain.  If caller's caller is walking the chain, they'll be happier if we
6894      hand them back the original chain when restore_infcall_control_state is
6895      called.  */
6896   tp->control.stop_bpstat = bpstat_copy (tp->control.stop_bpstat);
6897
6898   /* Other fields:  */
6899   inf_status->stop_stack_dummy = stop_stack_dummy;
6900   inf_status->stopped_by_random_signal = stopped_by_random_signal;
6901   inf_status->stop_after_trap = stop_after_trap;
6902
6903   inf_status->selected_frame_id = get_frame_id (get_selected_frame (NULL));
6904
6905   return inf_status;
6906 }
6907
6908 static int
6909 restore_selected_frame (void *args)
6910 {
6911   struct frame_id *fid = (struct frame_id *) args;
6912   struct frame_info *frame;
6913
6914   frame = frame_find_by_id (*fid);
6915
6916   /* If inf_status->selected_frame_id is NULL, there was no previously
6917      selected frame.  */
6918   if (frame == NULL)
6919     {
6920       warning (_("Unable to restore previously selected frame."));
6921       return 0;
6922     }
6923
6924   select_frame (frame);
6925
6926   return (1);
6927 }
6928
6929 /* Restore inferior session state to INF_STATUS.  */
6930
6931 void
6932 restore_infcall_control_state (struct infcall_control_state *inf_status)
6933 {
6934   struct thread_info *tp = inferior_thread ();
6935   struct inferior *inf = current_inferior ();
6936
6937   if (tp->control.step_resume_breakpoint)
6938     tp->control.step_resume_breakpoint->disposition = disp_del_at_next_stop;
6939
6940   if (tp->control.exception_resume_breakpoint)
6941     tp->control.exception_resume_breakpoint->disposition
6942       = disp_del_at_next_stop;
6943
6944   /* Handle the bpstat_copy of the chain.  */
6945   bpstat_clear (&tp->control.stop_bpstat);
6946
6947   tp->control = inf_status->thread_control;
6948   inf->control = inf_status->inferior_control;
6949
6950   /* Other fields:  */
6951   stop_stack_dummy = inf_status->stop_stack_dummy;
6952   stopped_by_random_signal = inf_status->stopped_by_random_signal;
6953   stop_after_trap = inf_status->stop_after_trap;
6954
6955   if (target_has_stack)
6956     {
6957       /* The point of catch_errors is that if the stack is clobbered,
6958          walking the stack might encounter a garbage pointer and
6959          error() trying to dereference it.  */
6960       if (catch_errors
6961           (restore_selected_frame, &inf_status->selected_frame_id,
6962            "Unable to restore previously selected frame:\n",
6963            RETURN_MASK_ERROR) == 0)
6964         /* Error in restoring the selected frame.  Select the innermost
6965            frame.  */
6966         select_frame (get_current_frame ());
6967     }
6968
6969   xfree (inf_status);
6970 }
6971
6972 static void
6973 do_restore_infcall_control_state_cleanup (void *sts)
6974 {
6975   restore_infcall_control_state (sts);
6976 }
6977
6978 struct cleanup *
6979 make_cleanup_restore_infcall_control_state
6980   (struct infcall_control_state *inf_status)
6981 {
6982   return make_cleanup (do_restore_infcall_control_state_cleanup, inf_status);
6983 }
6984
6985 void
6986 discard_infcall_control_state (struct infcall_control_state *inf_status)
6987 {
6988   if (inf_status->thread_control.step_resume_breakpoint)
6989     inf_status->thread_control.step_resume_breakpoint->disposition
6990       = disp_del_at_next_stop;
6991
6992   if (inf_status->thread_control.exception_resume_breakpoint)
6993     inf_status->thread_control.exception_resume_breakpoint->disposition
6994       = disp_del_at_next_stop;
6995
6996   /* See save_infcall_control_state for info on stop_bpstat.  */
6997   bpstat_clear (&inf_status->thread_control.stop_bpstat);
6998
6999   xfree (inf_status);
7000 }
7001 \f
7002 int
7003 ptid_match (ptid_t ptid, ptid_t filter)
7004 {
7005   if (ptid_equal (filter, minus_one_ptid))
7006     return 1;
7007   if (ptid_is_pid (filter)
7008       && ptid_get_pid (ptid) == ptid_get_pid (filter))
7009     return 1;
7010   else if (ptid_equal (ptid, filter))
7011     return 1;
7012
7013   return 0;
7014 }
7015
7016 /* restore_inferior_ptid() will be used by the cleanup machinery
7017    to restore the inferior_ptid value saved in a call to
7018    save_inferior_ptid().  */
7019
7020 static void
7021 restore_inferior_ptid (void *arg)
7022 {
7023   ptid_t *saved_ptid_ptr = arg;
7024
7025   inferior_ptid = *saved_ptid_ptr;
7026   xfree (arg);
7027 }
7028
7029 /* Save the value of inferior_ptid so that it may be restored by a
7030    later call to do_cleanups().  Returns the struct cleanup pointer
7031    needed for later doing the cleanup.  */
7032
7033 struct cleanup *
7034 save_inferior_ptid (void)
7035 {
7036   ptid_t *saved_ptid_ptr;
7037
7038   saved_ptid_ptr = xmalloc (sizeof (ptid_t));
7039   *saved_ptid_ptr = inferior_ptid;
7040   return make_cleanup (restore_inferior_ptid, saved_ptid_ptr);
7041 }
7042 \f
7043
7044 /* User interface for reverse debugging:
7045    Set exec-direction / show exec-direction commands
7046    (returns error unless target implements to_set_exec_direction method).  */
7047
7048 int execution_direction = EXEC_FORWARD;
7049 static const char exec_forward[] = "forward";
7050 static const char exec_reverse[] = "reverse";
7051 static const char *exec_direction = exec_forward;
7052 static const char *const exec_direction_names[] = {
7053   exec_forward,
7054   exec_reverse,
7055   NULL
7056 };
7057
7058 static void
7059 set_exec_direction_func (char *args, int from_tty,
7060                          struct cmd_list_element *cmd)
7061 {
7062   if (target_can_execute_reverse)
7063     {
7064       if (!strcmp (exec_direction, exec_forward))
7065         execution_direction = EXEC_FORWARD;
7066       else if (!strcmp (exec_direction, exec_reverse))
7067         execution_direction = EXEC_REVERSE;
7068     }
7069   else
7070     {
7071       exec_direction = exec_forward;
7072       error (_("Target does not support this operation."));
7073     }
7074 }
7075
7076 static void
7077 show_exec_direction_func (struct ui_file *out, int from_tty,
7078                           struct cmd_list_element *cmd, const char *value)
7079 {
7080   switch (execution_direction) {
7081   case EXEC_FORWARD:
7082     fprintf_filtered (out, _("Forward.\n"));
7083     break;
7084   case EXEC_REVERSE:
7085     fprintf_filtered (out, _("Reverse.\n"));
7086     break;
7087   default:
7088     internal_error (__FILE__, __LINE__,
7089                     _("bogus execution_direction value: %d"),
7090                     (int) execution_direction);
7091   }
7092 }
7093
7094 /* User interface for non-stop mode.  */
7095
7096 int non_stop = 0;
7097
7098 static void
7099 set_non_stop (char *args, int from_tty,
7100               struct cmd_list_element *c)
7101 {
7102   if (target_has_execution)
7103     {
7104       non_stop_1 = non_stop;
7105       error (_("Cannot change this setting while the inferior is running."));
7106     }
7107
7108   non_stop = non_stop_1;
7109 }
7110
7111 static void
7112 show_non_stop (struct ui_file *file, int from_tty,
7113                struct cmd_list_element *c, const char *value)
7114 {
7115   fprintf_filtered (file,
7116                     _("Controlling the inferior in non-stop mode is %s.\n"),
7117                     value);
7118 }
7119
7120 static void
7121 show_schedule_multiple (struct ui_file *file, int from_tty,
7122                         struct cmd_list_element *c, const char *value)
7123 {
7124   fprintf_filtered (file, _("Resuming the execution of threads "
7125                             "of all processes is %s.\n"), value);
7126 }
7127
7128 /* Implementation of `siginfo' variable.  */
7129
7130 static const struct internalvar_funcs siginfo_funcs =
7131 {
7132   siginfo_make_value,
7133   NULL,
7134   NULL
7135 };
7136
7137 void
7138 _initialize_infrun (void)
7139 {
7140   int i;
7141   int numsigs;
7142   struct cmd_list_element *c;
7143
7144   add_info ("signals", signals_info, _("\
7145 What debugger does when program gets various signals.\n\
7146 Specify a signal as argument to print info on that signal only."));
7147   add_info_alias ("handle", "signals", 0);
7148
7149   c = add_com ("handle", class_run, handle_command, _("\
7150 Specify how to handle signals.\n\
7151 Usage: handle SIGNAL [ACTIONS]\n\
7152 Args are signals and actions to apply to those signals.\n\
7153 If no actions are specified, the current settings for the specified signals\n\
7154 will be displayed instead.\n\
7155 \n\
7156 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
7157 from 1-15 are allowed for compatibility with old versions of GDB.\n\
7158 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
7159 The special arg \"all\" is recognized to mean all signals except those\n\
7160 used by the debugger, typically SIGTRAP and SIGINT.\n\
7161 \n\
7162 Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
7163 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
7164 Stop means reenter debugger if this signal happens (implies print).\n\
7165 Print means print a message if this signal happens.\n\
7166 Pass means let program see this signal; otherwise program doesn't know.\n\
7167 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
7168 Pass and Stop may be combined.\n\
7169 \n\
7170 Multiple signals may be specified.  Signal numbers and signal names\n\
7171 may be interspersed with actions, with the actions being performed for\n\
7172 all signals cumulatively specified."));
7173   set_cmd_completer (c, handle_completer);
7174
7175   if (xdb_commands)
7176     {
7177       add_com ("lz", class_info, signals_info, _("\
7178 What debugger does when program gets various signals.\n\
7179 Specify a signal as argument to print info on that signal only."));
7180       add_com ("z", class_run, xdb_handle_command, _("\
7181 Specify how to handle a signal.\n\
7182 Args are signals and actions to apply to those signals.\n\
7183 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
7184 from 1-15 are allowed for compatibility with old versions of GDB.\n\
7185 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
7186 The special arg \"all\" is recognized to mean all signals except those\n\
7187 used by the debugger, typically SIGTRAP and SIGINT.\n\
7188 Recognized actions include \"s\" (toggles between stop and nostop),\n\
7189 \"r\" (toggles between print and noprint), \"i\" (toggles between pass and \
7190 nopass), \"Q\" (noprint)\n\
7191 Stop means reenter debugger if this signal happens (implies print).\n\
7192 Print means print a message if this signal happens.\n\
7193 Pass means let program see this signal; otherwise program doesn't know.\n\
7194 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
7195 Pass and Stop may be combined."));
7196     }
7197
7198   if (!dbx_commands)
7199     stop_command = add_cmd ("stop", class_obscure,
7200                             not_just_help_class_command, _("\
7201 There is no `stop' command, but you can set a hook on `stop'.\n\
7202 This allows you to set a list of commands to be run each time execution\n\
7203 of the program stops."), &cmdlist);
7204
7205   add_setshow_zuinteger_cmd ("infrun", class_maintenance, &debug_infrun, _("\
7206 Set inferior debugging."), _("\
7207 Show inferior debugging."), _("\
7208 When non-zero, inferior specific debugging is enabled."),
7209                              NULL,
7210                              show_debug_infrun,
7211                              &setdebuglist, &showdebuglist);
7212
7213   add_setshow_boolean_cmd ("displaced", class_maintenance,
7214                            &debug_displaced, _("\
7215 Set displaced stepping debugging."), _("\
7216 Show displaced stepping debugging."), _("\
7217 When non-zero, displaced stepping specific debugging is enabled."),
7218                             NULL,
7219                             show_debug_displaced,
7220                             &setdebuglist, &showdebuglist);
7221
7222   add_setshow_boolean_cmd ("non-stop", no_class,
7223                            &non_stop_1, _("\
7224 Set whether gdb controls the inferior in non-stop mode."), _("\
7225 Show whether gdb controls the inferior in non-stop mode."), _("\
7226 When debugging a multi-threaded program and this setting is\n\
7227 off (the default, also called all-stop mode), when one thread stops\n\
7228 (for a breakpoint, watchpoint, exception, or similar events), GDB stops\n\
7229 all other threads in the program while you interact with the thread of\n\
7230 interest.  When you continue or step a thread, you can allow the other\n\
7231 threads to run, or have them remain stopped, but while you inspect any\n\
7232 thread's state, all threads stop.\n\
7233 \n\
7234 In non-stop mode, when one thread stops, other threads can continue\n\
7235 to run freely.  You'll be able to step each thread independently,\n\
7236 leave it stopped or free to run as needed."),
7237                            set_non_stop,
7238                            show_non_stop,
7239                            &setlist,
7240                            &showlist);
7241
7242   numsigs = (int) GDB_SIGNAL_LAST;
7243   signal_stop = (unsigned char *) xmalloc (sizeof (signal_stop[0]) * numsigs);
7244   signal_print = (unsigned char *)
7245     xmalloc (sizeof (signal_print[0]) * numsigs);
7246   signal_program = (unsigned char *)
7247     xmalloc (sizeof (signal_program[0]) * numsigs);
7248   signal_catch = (unsigned char *)
7249     xmalloc (sizeof (signal_catch[0]) * numsigs);
7250   signal_pass = (unsigned char *)
7251     xmalloc (sizeof (signal_program[0]) * numsigs);
7252   for (i = 0; i < numsigs; i++)
7253     {
7254       signal_stop[i] = 1;
7255       signal_print[i] = 1;
7256       signal_program[i] = 1;
7257       signal_catch[i] = 0;
7258     }
7259
7260   /* Signals caused by debugger's own actions
7261      should not be given to the program afterwards.  */
7262   signal_program[GDB_SIGNAL_TRAP] = 0;
7263   signal_program[GDB_SIGNAL_INT] = 0;
7264
7265   /* Signals that are not errors should not normally enter the debugger.  */
7266   signal_stop[GDB_SIGNAL_ALRM] = 0;
7267   signal_print[GDB_SIGNAL_ALRM] = 0;
7268   signal_stop[GDB_SIGNAL_VTALRM] = 0;
7269   signal_print[GDB_SIGNAL_VTALRM] = 0;
7270   signal_stop[GDB_SIGNAL_PROF] = 0;
7271   signal_print[GDB_SIGNAL_PROF] = 0;
7272   signal_stop[GDB_SIGNAL_CHLD] = 0;
7273   signal_print[GDB_SIGNAL_CHLD] = 0;
7274   signal_stop[GDB_SIGNAL_IO] = 0;
7275   signal_print[GDB_SIGNAL_IO] = 0;
7276   signal_stop[GDB_SIGNAL_POLL] = 0;
7277   signal_print[GDB_SIGNAL_POLL] = 0;
7278   signal_stop[GDB_SIGNAL_URG] = 0;
7279   signal_print[GDB_SIGNAL_URG] = 0;
7280   signal_stop[GDB_SIGNAL_WINCH] = 0;
7281   signal_print[GDB_SIGNAL_WINCH] = 0;
7282   signal_stop[GDB_SIGNAL_PRIO] = 0;
7283   signal_print[GDB_SIGNAL_PRIO] = 0;
7284
7285   /* These signals are used internally by user-level thread
7286      implementations.  (See signal(5) on Solaris.)  Like the above
7287      signals, a healthy program receives and handles them as part of
7288      its normal operation.  */
7289   signal_stop[GDB_SIGNAL_LWP] = 0;
7290   signal_print[GDB_SIGNAL_LWP] = 0;
7291   signal_stop[GDB_SIGNAL_WAITING] = 0;
7292   signal_print[GDB_SIGNAL_WAITING] = 0;
7293   signal_stop[GDB_SIGNAL_CANCEL] = 0;
7294   signal_print[GDB_SIGNAL_CANCEL] = 0;
7295
7296   /* Update cached state.  */
7297   signal_cache_update (-1);
7298
7299   add_setshow_zinteger_cmd ("stop-on-solib-events", class_support,
7300                             &stop_on_solib_events, _("\
7301 Set stopping for shared library events."), _("\
7302 Show stopping for shared library events."), _("\
7303 If nonzero, gdb will give control to the user when the dynamic linker\n\
7304 notifies gdb of shared library events.  The most common event of interest\n\
7305 to the user would be loading/unloading of a new library."),
7306                             NULL,
7307                             show_stop_on_solib_events,
7308                             &setlist, &showlist);
7309
7310   add_setshow_enum_cmd ("follow-fork-mode", class_run,
7311                         follow_fork_mode_kind_names,
7312                         &follow_fork_mode_string, _("\
7313 Set debugger response to a program call of fork or vfork."), _("\
7314 Show debugger response to a program call of fork or vfork."), _("\
7315 A fork or vfork creates a new process.  follow-fork-mode can be:\n\
7316   parent  - the original process is debugged after a fork\n\
7317   child   - the new process is debugged after a fork\n\
7318 The unfollowed process will continue to run.\n\
7319 By default, the debugger will follow the parent process."),
7320                         NULL,
7321                         show_follow_fork_mode_string,
7322                         &setlist, &showlist);
7323
7324   add_setshow_enum_cmd ("follow-exec-mode", class_run,
7325                         follow_exec_mode_names,
7326                         &follow_exec_mode_string, _("\
7327 Set debugger response to a program call of exec."), _("\
7328 Show debugger response to a program call of exec."), _("\
7329 An exec call replaces the program image of a process.\n\
7330 \n\
7331 follow-exec-mode can be:\n\
7332 \n\
7333   new - the debugger creates a new inferior and rebinds the process\n\
7334 to this new inferior.  The program the process was running before\n\
7335 the exec call can be restarted afterwards by restarting the original\n\
7336 inferior.\n\
7337 \n\
7338   same - the debugger keeps the process bound to the same inferior.\n\
7339 The new executable image replaces the previous executable loaded in\n\
7340 the inferior.  Restarting the inferior after the exec call restarts\n\
7341 the executable the process was running after the exec call.\n\
7342 \n\
7343 By default, the debugger will use the same inferior."),
7344                         NULL,
7345                         show_follow_exec_mode_string,
7346                         &setlist, &showlist);
7347
7348   add_setshow_enum_cmd ("scheduler-locking", class_run, 
7349                         scheduler_enums, &scheduler_mode, _("\
7350 Set mode for locking scheduler during execution."), _("\
7351 Show mode for locking scheduler during execution."), _("\
7352 off  == no locking (threads may preempt at any time)\n\
7353 on   == full locking (no thread except the current thread may run)\n\
7354 step == scheduler locked during every single-step operation.\n\
7355         In this mode, no other thread may run during a step command.\n\
7356         Other threads may run while stepping over a function call ('next')."), 
7357                         set_schedlock_func,     /* traps on target vector */
7358                         show_scheduler_mode,
7359                         &setlist, &showlist);
7360
7361   add_setshow_boolean_cmd ("schedule-multiple", class_run, &sched_multi, _("\
7362 Set mode for resuming threads of all processes."), _("\
7363 Show mode for resuming threads of all processes."), _("\
7364 When on, execution commands (such as 'continue' or 'next') resume all\n\
7365 threads of all processes.  When off (which is the default), execution\n\
7366 commands only resume the threads of the current process.  The set of\n\
7367 threads that are resumed is further refined by the scheduler-locking\n\
7368 mode (see help set scheduler-locking)."),
7369                            NULL,
7370                            show_schedule_multiple,
7371                            &setlist, &showlist);
7372
7373   add_setshow_boolean_cmd ("step-mode", class_run, &step_stop_if_no_debug, _("\
7374 Set mode of the step operation."), _("\
7375 Show mode of the step operation."), _("\
7376 When set, doing a step over a function without debug line information\n\
7377 will stop at the first instruction of that function. Otherwise, the\n\
7378 function is skipped and the step command stops at a different source line."),
7379                            NULL,
7380                            show_step_stop_if_no_debug,
7381                            &setlist, &showlist);
7382
7383   add_setshow_auto_boolean_cmd ("displaced-stepping", class_run,
7384                                 &can_use_displaced_stepping, _("\
7385 Set debugger's willingness to use displaced stepping."), _("\
7386 Show debugger's willingness to use displaced stepping."), _("\
7387 If on, gdb will use displaced stepping to step over breakpoints if it is\n\
7388 supported by the target architecture.  If off, gdb will not use displaced\n\
7389 stepping to step over breakpoints, even if such is supported by the target\n\
7390 architecture.  If auto (which is the default), gdb will use displaced stepping\n\
7391 if the target architecture supports it and non-stop mode is active, but will not\n\
7392 use it in all-stop mode (see help set non-stop)."),
7393                                 NULL,
7394                                 show_can_use_displaced_stepping,
7395                                 &setlist, &showlist);
7396
7397   add_setshow_enum_cmd ("exec-direction", class_run, exec_direction_names,
7398                         &exec_direction, _("Set direction of execution.\n\
7399 Options are 'forward' or 'reverse'."),
7400                         _("Show direction of execution (forward/reverse)."),
7401                         _("Tells gdb whether to execute forward or backward."),
7402                         set_exec_direction_func, show_exec_direction_func,
7403                         &setlist, &showlist);
7404
7405   /* Set/show detach-on-fork: user-settable mode.  */
7406
7407   add_setshow_boolean_cmd ("detach-on-fork", class_run, &detach_fork, _("\
7408 Set whether gdb will detach the child of a fork."), _("\
7409 Show whether gdb will detach the child of a fork."), _("\
7410 Tells gdb whether to detach the child of a fork."),
7411                            NULL, NULL, &setlist, &showlist);
7412
7413   /* Set/show disable address space randomization mode.  */
7414
7415   add_setshow_boolean_cmd ("disable-randomization", class_support,
7416                            &disable_randomization, _("\
7417 Set disabling of debuggee's virtual address space randomization."), _("\
7418 Show disabling of debuggee's virtual address space randomization."), _("\
7419 When this mode is on (which is the default), randomization of the virtual\n\
7420 address space is disabled.  Standalone programs run with the randomization\n\
7421 enabled by default on some platforms."),
7422                            &set_disable_randomization,
7423                            &show_disable_randomization,
7424                            &setlist, &showlist);
7425
7426   /* ptid initializations */
7427   inferior_ptid = null_ptid;
7428   target_last_wait_ptid = minus_one_ptid;
7429
7430   observer_attach_thread_ptid_changed (infrun_thread_ptid_changed);
7431   observer_attach_thread_stop_requested (infrun_thread_stop_requested);
7432   observer_attach_thread_exit (infrun_thread_thread_exit);
7433   observer_attach_inferior_exit (infrun_inferior_exit);
7434
7435   /* Explicitly create without lookup, since that tries to create a
7436      value with a void typed value, and when we get here, gdbarch
7437      isn't initialized yet.  At this point, we're quite sure there
7438      isn't another convenience variable of the same name.  */
7439   create_internalvar_type_lazy ("_siginfo", &siginfo_funcs, NULL);
7440
7441   add_setshow_boolean_cmd ("observer", no_class,
7442                            &observer_mode_1, _("\
7443 Set whether gdb controls the inferior in observer mode."), _("\
7444 Show whether gdb controls the inferior in observer mode."), _("\
7445 In observer mode, GDB can get data from the inferior, but not\n\
7446 affect its execution.  Registers and memory may not be changed,\n\
7447 breakpoints may not be set, and the program cannot be interrupted\n\
7448 or signalled."),
7449                            set_observer_mode,
7450                            show_observer_mode,
7451                            &setlist,
7452                            &showlist);
7453 }