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