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