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