d425664957aca36952f9d02397593ab9901ace6f
[external/binutils.git] / gdb / infrun.c
1 /* Target-struct-independent code to start (run) and stop an inferior
2    process.
3
4    Copyright (C) 1986-2017 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 <ctype.h>
24 #include "symtab.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "breakpoint.h"
28 #include "gdb_wait.h"
29 #include "gdbcore.h"
30 #include "gdbcmd.h"
31 #include "cli/cli-script.h"
32 #include "target.h"
33 #include "gdbthread.h"
34 #include "annotate.h"
35 #include "symfile.h"
36 #include "top.h"
37 #include <signal.h>
38 #include "inf-loop.h"
39 #include "regcache.h"
40 #include "value.h"
41 #include "observer.h"
42 #include "language.h"
43 #include "solib.h"
44 #include "main.h"
45 #include "dictionary.h"
46 #include "block.h"
47 #include "mi/mi-common.h"
48 #include "event-top.h"
49 #include "record.h"
50 #include "record-full.h"
51 #include "inline-frame.h"
52 #include "jit.h"
53 #include "tracepoint.h"
54 #include "continuations.h"
55 #include "interps.h"
56 #include "skip.h"
57 #include "probe.h"
58 #include "objfiles.h"
59 #include "completer.h"
60 #include "target-descriptions.h"
61 #include "target-dcache.h"
62 #include "terminal.h"
63 #include "solist.h"
64 #include "event-loop.h"
65 #include "thread-fsm.h"
66 #include "common/enum-flags.h"
67 #include "progspace-and-thread.h"
68 #include "common/gdb_optional.h"
69 #include "arch-utils.h"
70
71 /* Prototypes for local functions */
72
73 static void info_signals_command (char *, int);
74
75 static void handle_command (char *, int);
76
77 static void sig_print_info (enum gdb_signal);
78
79 static void sig_print_header (void);
80
81 static void resume_cleanups (void *);
82
83 static int follow_fork (void);
84
85 static int follow_fork_inferior (int follow_child, int detach_fork);
86
87 static void follow_inferior_reset_breakpoints (void);
88
89 static void set_schedlock_func (char *args, int from_tty,
90                                 struct cmd_list_element *c);
91
92 static int currently_stepping (struct thread_info *tp);
93
94 void nullify_last_target_wait_ptid (void);
95
96 static void insert_hp_step_resume_breakpoint_at_frame (struct frame_info *);
97
98 static void insert_step_resume_breakpoint_at_caller (struct frame_info *);
99
100 static void insert_longjmp_resume_breakpoint (struct gdbarch *, CORE_ADDR);
101
102 static int maybe_software_singlestep (struct gdbarch *gdbarch, CORE_ADDR pc);
103
104 /* Asynchronous signal handler registered as event loop source for
105    when we have pending events ready to be passed to the core.  */
106 static struct async_event_handler *infrun_async_inferior_event_token;
107
108 /* Stores whether infrun_async was previously enabled or disabled.
109    Starts off as -1, indicating "never enabled/disabled".  */
110 static int infrun_is_async = -1;
111
112 /* See infrun.h.  */
113
114 void
115 infrun_async (int enable)
116 {
117   if (infrun_is_async != enable)
118     {
119       infrun_is_async = enable;
120
121       if (debug_infrun)
122         fprintf_unfiltered (gdb_stdlog,
123                             "infrun: infrun_async(%d)\n",
124                             enable);
125
126       if (enable)
127         mark_async_event_handler (infrun_async_inferior_event_token);
128       else
129         clear_async_event_handler (infrun_async_inferior_event_token);
130     }
131 }
132
133 /* See infrun.h.  */
134
135 void
136 mark_infrun_async_event_handler (void)
137 {
138   mark_async_event_handler (infrun_async_inferior_event_token);
139 }
140
141 /* When set, stop the 'step' command if we enter a function which has
142    no line number information.  The normal behavior is that we step
143    over such function.  */
144 int step_stop_if_no_debug = 0;
145 static void
146 show_step_stop_if_no_debug (struct ui_file *file, int from_tty,
147                             struct cmd_list_element *c, const char *value)
148 {
149   fprintf_filtered (file, _("Mode of the step operation is %s.\n"), value);
150 }
151
152 /* proceed and normal_stop use this to notify the user when the
153    inferior stopped in a different thread than it had been running
154    in.  */
155
156 static ptid_t previous_inferior_ptid;
157
158 /* If set (default for legacy reasons), when following a fork, GDB
159    will detach from one of the fork branches, child or parent.
160    Exactly which branch is detached depends on 'set follow-fork-mode'
161    setting.  */
162
163 static int detach_fork = 1;
164
165 int debug_displaced = 0;
166 static void
167 show_debug_displaced (struct ui_file *file, int from_tty,
168                       struct cmd_list_element *c, const char *value)
169 {
170   fprintf_filtered (file, _("Displace stepping debugging is %s.\n"), value);
171 }
172
173 unsigned int debug_infrun = 0;
174 static void
175 show_debug_infrun (struct ui_file *file, int from_tty,
176                    struct cmd_list_element *c, const char *value)
177 {
178   fprintf_filtered (file, _("Inferior debugging is %s.\n"), value);
179 }
180
181
182 /* Support for disabling address space randomization.  */
183
184 int disable_randomization = 1;
185
186 static void
187 show_disable_randomization (struct ui_file *file, int from_tty,
188                             struct cmd_list_element *c, const char *value)
189 {
190   if (target_supports_disable_randomization ())
191     fprintf_filtered (file,
192                       _("Disabling randomization of debuggee's "
193                         "virtual address space is %s.\n"),
194                       value);
195   else
196     fputs_filtered (_("Disabling randomization of debuggee's "
197                       "virtual address space is unsupported on\n"
198                       "this platform.\n"), file);
199 }
200
201 static void
202 set_disable_randomization (char *args, int from_tty,
203                            struct cmd_list_element *c)
204 {
205   if (!target_supports_disable_randomization ())
206     error (_("Disabling randomization of debuggee's "
207              "virtual address space is unsupported on\n"
208              "this platform."));
209 }
210
211 /* User interface for non-stop mode.  */
212
213 int non_stop = 0;
214 static int non_stop_1 = 0;
215
216 static void
217 set_non_stop (char *args, int from_tty,
218               struct cmd_list_element *c)
219 {
220   if (target_has_execution)
221     {
222       non_stop_1 = non_stop;
223       error (_("Cannot change this setting while the inferior is running."));
224     }
225
226   non_stop = non_stop_1;
227 }
228
229 static void
230 show_non_stop (struct ui_file *file, int from_tty,
231                struct cmd_list_element *c, const char *value)
232 {
233   fprintf_filtered (file,
234                     _("Controlling the inferior in non-stop mode is %s.\n"),
235                     value);
236 }
237
238 /* "Observer mode" is somewhat like a more extreme version of
239    non-stop, in which all GDB operations that might affect the
240    target's execution have been disabled.  */
241
242 int observer_mode = 0;
243 static int observer_mode_1 = 0;
244
245 static void
246 set_observer_mode (char *args, int from_tty,
247                    struct cmd_list_element *c)
248 {
249   if (target_has_execution)
250     {
251       observer_mode_1 = observer_mode;
252       error (_("Cannot change this setting while the inferior is running."));
253     }
254
255   observer_mode = observer_mode_1;
256
257   may_write_registers = !observer_mode;
258   may_write_memory = !observer_mode;
259   may_insert_breakpoints = !observer_mode;
260   may_insert_tracepoints = !observer_mode;
261   /* We can insert fast tracepoints in or out of observer mode,
262      but enable them if we're going into this mode.  */
263   if (observer_mode)
264     may_insert_fast_tracepoints = 1;
265   may_stop = !observer_mode;
266   update_target_permissions ();
267
268   /* Going *into* observer mode we must force non-stop, then
269      going out we leave it that way.  */
270   if (observer_mode)
271     {
272       pagination_enabled = 0;
273       non_stop = non_stop_1 = 1;
274     }
275
276   if (from_tty)
277     printf_filtered (_("Observer mode is now %s.\n"),
278                      (observer_mode ? "on" : "off"));
279 }
280
281 static void
282 show_observer_mode (struct ui_file *file, int from_tty,
283                     struct cmd_list_element *c, const char *value)
284 {
285   fprintf_filtered (file, _("Observer mode is %s.\n"), value);
286 }
287
288 /* This updates the value of observer mode based on changes in
289    permissions.  Note that we are deliberately ignoring the values of
290    may-write-registers and may-write-memory, since the user may have
291    reason to enable these during a session, for instance to turn on a
292    debugging-related global.  */
293
294 void
295 update_observer_mode (void)
296 {
297   int newval;
298
299   newval = (!may_insert_breakpoints
300             && !may_insert_tracepoints
301             && may_insert_fast_tracepoints
302             && !may_stop
303             && non_stop);
304
305   /* Let the user know if things change.  */
306   if (newval != observer_mode)
307     printf_filtered (_("Observer mode is now %s.\n"),
308                      (newval ? "on" : "off"));
309
310   observer_mode = observer_mode_1 = newval;
311 }
312
313 /* Tables of how to react to signals; the user sets them.  */
314
315 static unsigned char *signal_stop;
316 static unsigned char *signal_print;
317 static unsigned char *signal_program;
318
319 /* Table of signals that are registered with "catch signal".  A
320    non-zero entry indicates that the signal is caught by some "catch
321    signal" command.  This has size GDB_SIGNAL_LAST, to accommodate all
322    signals.  */
323 static unsigned char *signal_catch;
324
325 /* Table of signals that the target may silently handle.
326    This is automatically determined from the flags above,
327    and simply cached here.  */
328 static unsigned char *signal_pass;
329
330 #define SET_SIGS(nsigs,sigs,flags) \
331   do { \
332     int signum = (nsigs); \
333     while (signum-- > 0) \
334       if ((sigs)[signum]) \
335         (flags)[signum] = 1; \
336   } while (0)
337
338 #define UNSET_SIGS(nsigs,sigs,flags) \
339   do { \
340     int signum = (nsigs); \
341     while (signum-- > 0) \
342       if ((sigs)[signum]) \
343         (flags)[signum] = 0; \
344   } while (0)
345
346 /* Update the target's copy of SIGNAL_PROGRAM.  The sole purpose of
347    this function is to avoid exporting `signal_program'.  */
348
349 void
350 update_signals_program_target (void)
351 {
352   target_program_signals ((int) GDB_SIGNAL_LAST, signal_program);
353 }
354
355 /* Value to pass to target_resume() to cause all threads to resume.  */
356
357 #define RESUME_ALL minus_one_ptid
358
359 /* Command list pointer for the "stop" placeholder.  */
360
361 static struct cmd_list_element *stop_command;
362
363 /* Nonzero if we want to give control to the user when we're notified
364    of shared library events by the dynamic linker.  */
365 int stop_on_solib_events;
366
367 /* Enable or disable optional shared library event breakpoints
368    as appropriate when the above flag is changed.  */
369
370 static void
371 set_stop_on_solib_events (char *args, int from_tty, struct cmd_list_element *c)
372 {
373   update_solib_breakpoints ();
374 }
375
376 static void
377 show_stop_on_solib_events (struct ui_file *file, int from_tty,
378                            struct cmd_list_element *c, const char *value)
379 {
380   fprintf_filtered (file, _("Stopping for shared library events is %s.\n"),
381                     value);
382 }
383
384 /* Nonzero after stop if current stack frame should be printed.  */
385
386 static int stop_print_frame;
387
388 /* This is a cached copy of the pid/waitstatus of the last event
389    returned by target_wait()/deprecated_target_wait_hook().  This
390    information is returned by get_last_target_status().  */
391 static ptid_t target_last_wait_ptid;
392 static struct target_waitstatus target_last_waitstatus;
393
394 static void context_switch (ptid_t ptid);
395
396 void init_thread_stepping_state (struct thread_info *tss);
397
398 static const char follow_fork_mode_child[] = "child";
399 static const char follow_fork_mode_parent[] = "parent";
400
401 static const char *const follow_fork_mode_kind_names[] = {
402   follow_fork_mode_child,
403   follow_fork_mode_parent,
404   NULL
405 };
406
407 static const char *follow_fork_mode_string = follow_fork_mode_parent;
408 static void
409 show_follow_fork_mode_string (struct ui_file *file, int from_tty,
410                               struct cmd_list_element *c, const char *value)
411 {
412   fprintf_filtered (file,
413                     _("Debugger response to a program "
414                       "call of fork or vfork is \"%s\".\n"),
415                     value);
416 }
417 \f
418
419 /* Handle changes to the inferior list based on the type of fork,
420    which process is being followed, and whether the other process
421    should be detached.  On entry inferior_ptid must be the ptid of
422    the fork parent.  At return inferior_ptid is the ptid of the
423    followed inferior.  */
424
425 static int
426 follow_fork_inferior (int follow_child, int detach_fork)
427 {
428   int has_vforked;
429   ptid_t parent_ptid, child_ptid;
430
431   has_vforked = (inferior_thread ()->pending_follow.kind
432                  == TARGET_WAITKIND_VFORKED);
433   parent_ptid = inferior_ptid;
434   child_ptid = inferior_thread ()->pending_follow.value.related_pid;
435
436   if (has_vforked
437       && !non_stop /* Non-stop always resumes both branches.  */
438       && current_ui->prompt_state == PROMPT_BLOCKED
439       && !(follow_child || detach_fork || sched_multi))
440     {
441       /* The parent stays blocked inside the vfork syscall until the
442          child execs or exits.  If we don't let the child run, then
443          the parent stays blocked.  If we're telling the parent to run
444          in the foreground, the user will not be able to ctrl-c to get
445          back the terminal, effectively hanging the debug session.  */
446       fprintf_filtered (gdb_stderr, _("\
447 Can not resume the parent process over vfork in the foreground while\n\
448 holding the child stopped.  Try \"set detach-on-fork\" or \
449 \"set schedule-multiple\".\n"));
450       /* FIXME output string > 80 columns.  */
451       return 1;
452     }
453
454   if (!follow_child)
455     {
456       /* Detach new forked process?  */
457       if (detach_fork)
458         {
459           /* Before detaching from the child, remove all breakpoints
460              from it.  If we forked, then this has already been taken
461              care of by infrun.c.  If we vforked however, any
462              breakpoint inserted in the parent is visible in the
463              child, even those added while stopped in a vfork
464              catchpoint.  This will remove the breakpoints from the
465              parent also, but they'll be reinserted below.  */
466           if (has_vforked)
467             {
468               /* Keep breakpoints list in sync.  */
469               remove_breakpoints_pid (ptid_get_pid (inferior_ptid));
470             }
471
472           if (info_verbose || debug_infrun)
473             {
474               /* Ensure that we have a process ptid.  */
475               ptid_t process_ptid = pid_to_ptid (ptid_get_pid (child_ptid));
476
477               target_terminal::ours_for_output ();
478               fprintf_filtered (gdb_stdlog,
479                                 _("Detaching after %s from child %s.\n"),
480                                 has_vforked ? "vfork" : "fork",
481                                 target_pid_to_str (process_ptid));
482             }
483         }
484       else
485         {
486           struct inferior *parent_inf, *child_inf;
487
488           /* Add process to GDB's tables.  */
489           child_inf = add_inferior (ptid_get_pid (child_ptid));
490
491           parent_inf = current_inferior ();
492           child_inf->attach_flag = parent_inf->attach_flag;
493           copy_terminal_info (child_inf, parent_inf);
494           child_inf->gdbarch = parent_inf->gdbarch;
495           copy_inferior_target_desc_info (child_inf, parent_inf);
496
497           scoped_restore_current_pspace_and_thread restore_pspace_thread;
498
499           inferior_ptid = child_ptid;
500           add_thread (inferior_ptid);
501           set_current_inferior (child_inf);
502           child_inf->symfile_flags = SYMFILE_NO_READ;
503
504           /* If this is a vfork child, then the address-space is
505              shared with the parent.  */
506           if (has_vforked)
507             {
508               child_inf->pspace = parent_inf->pspace;
509               child_inf->aspace = parent_inf->aspace;
510
511               /* The parent will be frozen until the child is done
512                  with the shared region.  Keep track of the
513                  parent.  */
514               child_inf->vfork_parent = parent_inf;
515               child_inf->pending_detach = 0;
516               parent_inf->vfork_child = child_inf;
517               parent_inf->pending_detach = 0;
518             }
519           else
520             {
521               child_inf->aspace = new_address_space ();
522               child_inf->pspace = add_program_space (child_inf->aspace);
523               child_inf->removable = 1;
524               set_current_program_space (child_inf->pspace);
525               clone_program_space (child_inf->pspace, parent_inf->pspace);
526
527               /* Let the shared library layer (e.g., solib-svr4) learn
528                  about this new process, relocate the cloned exec, pull
529                  in shared libraries, and install the solib event
530                  breakpoint.  If a "cloned-VM" event was propagated
531                  better throughout the core, this wouldn't be
532                  required.  */
533               solib_create_inferior_hook (0);
534             }
535         }
536
537       if (has_vforked)
538         {
539           struct inferior *parent_inf;
540
541           parent_inf = current_inferior ();
542
543           /* If we detached from the child, then we have to be careful
544              to not insert breakpoints in the parent until the child
545              is done with the shared memory region.  However, if we're
546              staying attached to the child, then we can and should
547              insert breakpoints, so that we can debug it.  A
548              subsequent child exec or exit is enough to know when does
549              the child stops using the parent's address space.  */
550           parent_inf->waiting_for_vfork_done = detach_fork;
551           parent_inf->pspace->breakpoints_not_allowed = detach_fork;
552         }
553     }
554   else
555     {
556       /* Follow the child.  */
557       struct inferior *parent_inf, *child_inf;
558       struct program_space *parent_pspace;
559
560       if (info_verbose || debug_infrun)
561         {
562           target_terminal::ours_for_output ();
563           fprintf_filtered (gdb_stdlog,
564                             _("Attaching after %s %s to child %s.\n"),
565                             target_pid_to_str (parent_ptid),
566                             has_vforked ? "vfork" : "fork",
567                             target_pid_to_str (child_ptid));
568         }
569
570       /* Add the new inferior first, so that the target_detach below
571          doesn't unpush the target.  */
572
573       child_inf = add_inferior (ptid_get_pid (child_ptid));
574
575       parent_inf = current_inferior ();
576       child_inf->attach_flag = parent_inf->attach_flag;
577       copy_terminal_info (child_inf, parent_inf);
578       child_inf->gdbarch = parent_inf->gdbarch;
579       copy_inferior_target_desc_info (child_inf, parent_inf);
580
581       parent_pspace = parent_inf->pspace;
582
583       /* If we're vforking, we want to hold on to the parent until the
584          child exits or execs.  At child exec or exit time we can
585          remove the old breakpoints from the parent and detach or
586          resume debugging it.  Otherwise, detach the parent now; we'll
587          want to reuse it's program/address spaces, but we can't set
588          them to the child before removing breakpoints from the
589          parent, otherwise, the breakpoints module could decide to
590          remove breakpoints from the wrong process (since they'd be
591          assigned to the same address space).  */
592
593       if (has_vforked)
594         {
595           gdb_assert (child_inf->vfork_parent == NULL);
596           gdb_assert (parent_inf->vfork_child == NULL);
597           child_inf->vfork_parent = parent_inf;
598           child_inf->pending_detach = 0;
599           parent_inf->vfork_child = child_inf;
600           parent_inf->pending_detach = detach_fork;
601           parent_inf->waiting_for_vfork_done = 0;
602         }
603       else if (detach_fork)
604         {
605           if (info_verbose || debug_infrun)
606             {
607               /* Ensure that we have a process ptid.  */
608               ptid_t process_ptid = pid_to_ptid (ptid_get_pid (child_ptid));
609
610               target_terminal::ours_for_output ();
611               fprintf_filtered (gdb_stdlog,
612                                 _("Detaching after fork from "
613                                   "child %s.\n"),
614                                 target_pid_to_str (process_ptid));
615             }
616
617           target_detach (NULL, 0);
618         }
619
620       /* Note that the detach above makes PARENT_INF dangling.  */
621
622       /* Add the child thread to the appropriate lists, and switch to
623          this new thread, before cloning the program space, and
624          informing the solib layer about this new process.  */
625
626       inferior_ptid = child_ptid;
627       add_thread (inferior_ptid);
628       set_current_inferior (child_inf);
629
630       /* If this is a vfork child, then the address-space is shared
631          with the parent.  If we detached from the parent, then we can
632          reuse the parent's program/address spaces.  */
633       if (has_vforked || detach_fork)
634         {
635           child_inf->pspace = parent_pspace;
636           child_inf->aspace = child_inf->pspace->aspace;
637         }
638       else
639         {
640           child_inf->aspace = new_address_space ();
641           child_inf->pspace = add_program_space (child_inf->aspace);
642           child_inf->removable = 1;
643           child_inf->symfile_flags = SYMFILE_NO_READ;
644           set_current_program_space (child_inf->pspace);
645           clone_program_space (child_inf->pspace, parent_pspace);
646
647           /* Let the shared library layer (e.g., solib-svr4) learn
648              about this new process, relocate the cloned exec, pull in
649              shared libraries, and install the solib event breakpoint.
650              If a "cloned-VM" event was propagated better throughout
651              the core, this wouldn't be required.  */
652           solib_create_inferior_hook (0);
653         }
654     }
655
656   return target_follow_fork (follow_child, detach_fork);
657 }
658
659 /* Tell the target to follow the fork we're stopped at.  Returns true
660    if the inferior should be resumed; false, if the target for some
661    reason decided it's best not to resume.  */
662
663 static int
664 follow_fork (void)
665 {
666   int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
667   int should_resume = 1;
668   struct thread_info *tp;
669
670   /* Copy user stepping state to the new inferior thread.  FIXME: the
671      followed fork child thread should have a copy of most of the
672      parent thread structure's run control related fields, not just these.
673      Initialized to avoid "may be used uninitialized" warnings from gcc.  */
674   struct breakpoint *step_resume_breakpoint = NULL;
675   struct breakpoint *exception_resume_breakpoint = NULL;
676   CORE_ADDR step_range_start = 0;
677   CORE_ADDR step_range_end = 0;
678   struct frame_id step_frame_id = { 0 };
679   struct thread_fsm *thread_fsm = NULL;
680
681   if (!non_stop)
682     {
683       ptid_t wait_ptid;
684       struct target_waitstatus wait_status;
685
686       /* Get the last target status returned by target_wait().  */
687       get_last_target_status (&wait_ptid, &wait_status);
688
689       /* If not stopped at a fork event, then there's nothing else to
690          do.  */
691       if (wait_status.kind != TARGET_WAITKIND_FORKED
692           && wait_status.kind != TARGET_WAITKIND_VFORKED)
693         return 1;
694
695       /* Check if we switched over from WAIT_PTID, since the event was
696          reported.  */
697       if (!ptid_equal (wait_ptid, minus_one_ptid)
698           && !ptid_equal (inferior_ptid, wait_ptid))
699         {
700           /* We did.  Switch back to WAIT_PTID thread, to tell the
701              target to follow it (in either direction).  We'll
702              afterwards refuse to resume, and inform the user what
703              happened.  */
704           switch_to_thread (wait_ptid);
705           should_resume = 0;
706         }
707     }
708
709   tp = inferior_thread ();
710
711   /* If there were any forks/vforks that were caught and are now to be
712      followed, then do so now.  */
713   switch (tp->pending_follow.kind)
714     {
715     case TARGET_WAITKIND_FORKED:
716     case TARGET_WAITKIND_VFORKED:
717       {
718         ptid_t parent, child;
719
720         /* If the user did a next/step, etc, over a fork call,
721            preserve the stepping state in the fork child.  */
722         if (follow_child && should_resume)
723           {
724             step_resume_breakpoint = clone_momentary_breakpoint
725                                          (tp->control.step_resume_breakpoint);
726             step_range_start = tp->control.step_range_start;
727             step_range_end = tp->control.step_range_end;
728             step_frame_id = tp->control.step_frame_id;
729             exception_resume_breakpoint
730               = clone_momentary_breakpoint (tp->control.exception_resume_breakpoint);
731             thread_fsm = tp->thread_fsm;
732
733             /* For now, delete the parent's sr breakpoint, otherwise,
734                parent/child sr breakpoints are considered duplicates,
735                and the child version will not be installed.  Remove
736                this when the breakpoints module becomes aware of
737                inferiors and address spaces.  */
738             delete_step_resume_breakpoint (tp);
739             tp->control.step_range_start = 0;
740             tp->control.step_range_end = 0;
741             tp->control.step_frame_id = null_frame_id;
742             delete_exception_resume_breakpoint (tp);
743             tp->thread_fsm = NULL;
744           }
745
746         parent = inferior_ptid;
747         child = tp->pending_follow.value.related_pid;
748
749         /* Set up inferior(s) as specified by the caller, and tell the
750            target to do whatever is necessary to follow either parent
751            or child.  */
752         if (follow_fork_inferior (follow_child, detach_fork))
753           {
754             /* Target refused to follow, or there's some other reason
755                we shouldn't resume.  */
756             should_resume = 0;
757           }
758         else
759           {
760             /* This pending follow fork event is now handled, one way
761                or another.  The previous selected thread may be gone
762                from the lists by now, but if it is still around, need
763                to clear the pending follow request.  */
764             tp = find_thread_ptid (parent);
765             if (tp)
766               tp->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
767
768             /* This makes sure we don't try to apply the "Switched
769                over from WAIT_PID" logic above.  */
770             nullify_last_target_wait_ptid ();
771
772             /* If we followed the child, switch to it...  */
773             if (follow_child)
774               {
775                 switch_to_thread (child);
776
777                 /* ... and preserve the stepping state, in case the
778                    user was stepping over the fork call.  */
779                 if (should_resume)
780                   {
781                     tp = inferior_thread ();
782                     tp->control.step_resume_breakpoint
783                       = step_resume_breakpoint;
784                     tp->control.step_range_start = step_range_start;
785                     tp->control.step_range_end = step_range_end;
786                     tp->control.step_frame_id = step_frame_id;
787                     tp->control.exception_resume_breakpoint
788                       = exception_resume_breakpoint;
789                     tp->thread_fsm = thread_fsm;
790                   }
791                 else
792                   {
793                     /* If we get here, it was because we're trying to
794                        resume from a fork catchpoint, but, the user
795                        has switched threads away from the thread that
796                        forked.  In that case, the resume command
797                        issued is most likely not applicable to the
798                        child, so just warn, and refuse to resume.  */
799                     warning (_("Not resuming: switched threads "
800                                "before following fork child."));
801                   }
802
803                 /* Reset breakpoints in the child as appropriate.  */
804                 follow_inferior_reset_breakpoints ();
805               }
806             else
807               switch_to_thread (parent);
808           }
809       }
810       break;
811     case TARGET_WAITKIND_SPURIOUS:
812       /* Nothing to follow.  */
813       break;
814     default:
815       internal_error (__FILE__, __LINE__,
816                       "Unexpected pending_follow.kind %d\n",
817                       tp->pending_follow.kind);
818       break;
819     }
820
821   return should_resume;
822 }
823
824 static void
825 follow_inferior_reset_breakpoints (void)
826 {
827   struct thread_info *tp = inferior_thread ();
828
829   /* Was there a step_resume breakpoint?  (There was if the user
830      did a "next" at the fork() call.)  If so, explicitly reset its
831      thread number.  Cloned step_resume breakpoints are disabled on
832      creation, so enable it here now that it is associated with the
833      correct thread.
834
835      step_resumes are a form of bp that are made to be per-thread.
836      Since we created the step_resume bp when the parent process
837      was being debugged, and now are switching to the child process,
838      from the breakpoint package's viewpoint, that's a switch of
839      "threads".  We must update the bp's notion of which thread
840      it is for, or it'll be ignored when it triggers.  */
841
842   if (tp->control.step_resume_breakpoint)
843     {
844       breakpoint_re_set_thread (tp->control.step_resume_breakpoint);
845       tp->control.step_resume_breakpoint->loc->enabled = 1;
846     }
847
848   /* Treat exception_resume breakpoints like step_resume breakpoints.  */
849   if (tp->control.exception_resume_breakpoint)
850     {
851       breakpoint_re_set_thread (tp->control.exception_resume_breakpoint);
852       tp->control.exception_resume_breakpoint->loc->enabled = 1;
853     }
854
855   /* Reinsert all breakpoints in the child.  The user may have set
856      breakpoints after catching the fork, in which case those
857      were never set in the child, but only in the parent.  This makes
858      sure the inserted breakpoints match the breakpoint list.  */
859
860   breakpoint_re_set ();
861   insert_breakpoints ();
862 }
863
864 /* The child has exited or execed: resume threads of the parent the
865    user wanted to be executing.  */
866
867 static int
868 proceed_after_vfork_done (struct thread_info *thread,
869                           void *arg)
870 {
871   int pid = * (int *) arg;
872
873   if (ptid_get_pid (thread->ptid) == pid
874       && is_running (thread->ptid)
875       && !is_executing (thread->ptid)
876       && !thread->stop_requested
877       && thread->suspend.stop_signal == GDB_SIGNAL_0)
878     {
879       if (debug_infrun)
880         fprintf_unfiltered (gdb_stdlog,
881                             "infrun: resuming vfork parent thread %s\n",
882                             target_pid_to_str (thread->ptid));
883
884       switch_to_thread (thread->ptid);
885       clear_proceed_status (0);
886       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
887     }
888
889   return 0;
890 }
891
892 /* Save/restore inferior_ptid, current program space and current
893    inferior.  Only use this if the current context points at an exited
894    inferior (and therefore there's no current thread to save).  */
895 class scoped_restore_exited_inferior
896 {
897 public:
898   scoped_restore_exited_inferior ()
899     : m_saved_ptid (&inferior_ptid)
900   {}
901
902 private:
903   scoped_restore_tmpl<ptid_t> m_saved_ptid;
904   scoped_restore_current_program_space m_pspace;
905   scoped_restore_current_inferior m_inferior;
906 };
907
908 /* Called whenever we notice an exec or exit event, to handle
909    detaching or resuming a vfork parent.  */
910
911 static void
912 handle_vfork_child_exec_or_exit (int exec)
913 {
914   struct inferior *inf = current_inferior ();
915
916   if (inf->vfork_parent)
917     {
918       int resume_parent = -1;
919
920       /* This exec or exit marks the end of the shared memory region
921          between the parent and the child.  If the user wanted to
922          detach from the parent, now is the time.  */
923
924       if (inf->vfork_parent->pending_detach)
925         {
926           struct thread_info *tp;
927           struct program_space *pspace;
928           struct address_space *aspace;
929
930           /* follow-fork child, detach-on-fork on.  */
931
932           inf->vfork_parent->pending_detach = 0;
933
934           gdb::optional<scoped_restore_exited_inferior>
935             maybe_restore_inferior;
936           gdb::optional<scoped_restore_current_pspace_and_thread>
937             maybe_restore_thread;
938
939           /* If we're handling a child exit, then inferior_ptid points
940              at the inferior's pid, not to a thread.  */
941           if (!exec)
942             maybe_restore_inferior.emplace ();
943           else
944             maybe_restore_thread.emplace ();
945
946           /* We're letting loose of the parent.  */
947           tp = any_live_thread_of_process (inf->vfork_parent->pid);
948           switch_to_thread (tp->ptid);
949
950           /* We're about to detach from the parent, which implicitly
951              removes breakpoints from its address space.  There's a
952              catch here: we want to reuse the spaces for the child,
953              but, parent/child are still sharing the pspace at this
954              point, although the exec in reality makes the kernel give
955              the child a fresh set of new pages.  The problem here is
956              that the breakpoints module being unaware of this, would
957              likely chose the child process to write to the parent
958              address space.  Swapping the child temporarily away from
959              the spaces has the desired effect.  Yes, this is "sort
960              of" a hack.  */
961
962           pspace = inf->pspace;
963           aspace = inf->aspace;
964           inf->aspace = NULL;
965           inf->pspace = NULL;
966
967           if (debug_infrun || info_verbose)
968             {
969               target_terminal::ours_for_output ();
970
971               if (exec)
972                 {
973                   fprintf_filtered (gdb_stdlog,
974                                     _("Detaching vfork parent process "
975                                       "%d after child exec.\n"),
976                                     inf->vfork_parent->pid);
977                 }
978               else
979                 {
980                   fprintf_filtered (gdb_stdlog,
981                                     _("Detaching vfork parent process "
982                                       "%d after child exit.\n"),
983                                     inf->vfork_parent->pid);
984                 }
985             }
986
987           target_detach (NULL, 0);
988
989           /* Put it back.  */
990           inf->pspace = pspace;
991           inf->aspace = aspace;
992         }
993       else if (exec)
994         {
995           /* We're staying attached to the parent, so, really give the
996              child a new address space.  */
997           inf->pspace = add_program_space (maybe_new_address_space ());
998           inf->aspace = inf->pspace->aspace;
999           inf->removable = 1;
1000           set_current_program_space (inf->pspace);
1001
1002           resume_parent = inf->vfork_parent->pid;
1003
1004           /* Break the bonds.  */
1005           inf->vfork_parent->vfork_child = NULL;
1006         }
1007       else
1008         {
1009           struct program_space *pspace;
1010
1011           /* If this is a vfork child exiting, then the pspace and
1012              aspaces were shared with the parent.  Since we're
1013              reporting the process exit, we'll be mourning all that is
1014              found in the address space, and switching to null_ptid,
1015              preparing to start a new inferior.  But, since we don't
1016              want to clobber the parent's address/program spaces, we
1017              go ahead and create a new one for this exiting
1018              inferior.  */
1019
1020           /* Switch to null_ptid while running clone_program_space, so
1021              that clone_program_space doesn't want to read the
1022              selected frame of a dead process.  */
1023           scoped_restore restore_ptid
1024             = make_scoped_restore (&inferior_ptid, null_ptid);
1025
1026           /* This inferior is dead, so avoid giving the breakpoints
1027              module the option to write through to it (cloning a
1028              program space resets breakpoints).  */
1029           inf->aspace = NULL;
1030           inf->pspace = NULL;
1031           pspace = add_program_space (maybe_new_address_space ());
1032           set_current_program_space (pspace);
1033           inf->removable = 1;
1034           inf->symfile_flags = SYMFILE_NO_READ;
1035           clone_program_space (pspace, inf->vfork_parent->pspace);
1036           inf->pspace = pspace;
1037           inf->aspace = pspace->aspace;
1038
1039           resume_parent = inf->vfork_parent->pid;
1040           /* Break the bonds.  */
1041           inf->vfork_parent->vfork_child = NULL;
1042         }
1043
1044       inf->vfork_parent = NULL;
1045
1046       gdb_assert (current_program_space == inf->pspace);
1047
1048       if (non_stop && resume_parent != -1)
1049         {
1050           /* If the user wanted the parent to be running, let it go
1051              free now.  */
1052           scoped_restore_current_thread restore_thread;
1053
1054           if (debug_infrun)
1055             fprintf_unfiltered (gdb_stdlog,
1056                                 "infrun: resuming vfork parent process %d\n",
1057                                 resume_parent);
1058
1059           iterate_over_threads (proceed_after_vfork_done, &resume_parent);
1060         }
1061     }
1062 }
1063
1064 /* Enum strings for "set|show follow-exec-mode".  */
1065
1066 static const char follow_exec_mode_new[] = "new";
1067 static const char follow_exec_mode_same[] = "same";
1068 static const char *const follow_exec_mode_names[] =
1069 {
1070   follow_exec_mode_new,
1071   follow_exec_mode_same,
1072   NULL,
1073 };
1074
1075 static const char *follow_exec_mode_string = follow_exec_mode_same;
1076 static void
1077 show_follow_exec_mode_string (struct ui_file *file, int from_tty,
1078                               struct cmd_list_element *c, const char *value)
1079 {
1080   fprintf_filtered (file, _("Follow exec mode is \"%s\".\n"),  value);
1081 }
1082
1083 /* EXEC_FILE_TARGET is assumed to be non-NULL.  */
1084
1085 static void
1086 follow_exec (ptid_t ptid, char *exec_file_target)
1087 {
1088   struct thread_info *th, *tmp;
1089   struct inferior *inf = current_inferior ();
1090   int pid = ptid_get_pid (ptid);
1091   ptid_t process_ptid;
1092   char *exec_file_host;
1093   struct cleanup *old_chain;
1094
1095   /* This is an exec event that we actually wish to pay attention to.
1096      Refresh our symbol table to the newly exec'd program, remove any
1097      momentary bp's, etc.
1098
1099      If there are breakpoints, they aren't really inserted now,
1100      since the exec() transformed our inferior into a fresh set
1101      of instructions.
1102
1103      We want to preserve symbolic breakpoints on the list, since
1104      we have hopes that they can be reset after the new a.out's
1105      symbol table is read.
1106
1107      However, any "raw" breakpoints must be removed from the list
1108      (e.g., the solib bp's), since their address is probably invalid
1109      now.
1110
1111      And, we DON'T want to call delete_breakpoints() here, since
1112      that may write the bp's "shadow contents" (the instruction
1113      value that was overwritten witha TRAP instruction).  Since
1114      we now have a new a.out, those shadow contents aren't valid.  */
1115
1116   mark_breakpoints_out ();
1117
1118   /* The target reports the exec event to the main thread, even if
1119      some other thread does the exec, and even if the main thread was
1120      stopped or already gone.  We may still have non-leader threads of
1121      the process on our list.  E.g., on targets that don't have thread
1122      exit events (like remote); or on native Linux in non-stop mode if
1123      there were only two threads in the inferior and the non-leader
1124      one is the one that execs (and nothing forces an update of the
1125      thread list up to here).  When debugging remotely, it's best to
1126      avoid extra traffic, when possible, so avoid syncing the thread
1127      list with the target, and instead go ahead and delete all threads
1128      of the process but one that reported the event.  Note this must
1129      be done before calling update_breakpoints_after_exec, as
1130      otherwise clearing the threads' resources would reference stale
1131      thread breakpoints -- it may have been one of these threads that
1132      stepped across the exec.  We could just clear their stepping
1133      states, but as long as we're iterating, might as well delete
1134      them.  Deleting them now rather than at the next user-visible
1135      stop provides a nicer sequence of events for user and MI
1136      notifications.  */
1137   ALL_THREADS_SAFE (th, tmp)
1138     if (ptid_get_pid (th->ptid) == pid && !ptid_equal (th->ptid, ptid))
1139       delete_thread (th->ptid);
1140
1141   /* We also need to clear any left over stale state for the
1142      leader/event thread.  E.g., if there was any step-resume
1143      breakpoint or similar, it's gone now.  We cannot truly
1144      step-to-next statement through an exec().  */
1145   th = inferior_thread ();
1146   th->control.step_resume_breakpoint = NULL;
1147   th->control.exception_resume_breakpoint = NULL;
1148   th->control.single_step_breakpoints = NULL;
1149   th->control.step_range_start = 0;
1150   th->control.step_range_end = 0;
1151
1152   /* The user may have had the main thread held stopped in the
1153      previous image (e.g., schedlock on, or non-stop).  Release
1154      it now.  */
1155   th->stop_requested = 0;
1156
1157   update_breakpoints_after_exec ();
1158
1159   /* What is this a.out's name?  */
1160   process_ptid = pid_to_ptid (pid);
1161   printf_unfiltered (_("%s is executing new program: %s\n"),
1162                      target_pid_to_str (process_ptid),
1163                      exec_file_target);
1164
1165   /* We've followed the inferior through an exec.  Therefore, the
1166      inferior has essentially been killed & reborn.  */
1167
1168   gdb_flush (gdb_stdout);
1169
1170   breakpoint_init_inferior (inf_execd);
1171
1172   exec_file_host = exec_file_find (exec_file_target, NULL);
1173   old_chain = make_cleanup (xfree, exec_file_host);
1174
1175   /* If we were unable to map the executable target pathname onto a host
1176      pathname, tell the user that.  Otherwise GDB's subsequent behavior
1177      is confusing.  Maybe it would even be better to stop at this point
1178      so that the user can specify a file manually before continuing.  */
1179   if (exec_file_host == NULL)
1180     warning (_("Could not load symbols for executable %s.\n"
1181                "Do you need \"set sysroot\"?"),
1182              exec_file_target);
1183
1184   /* Reset the shared library package.  This ensures that we get a
1185      shlib event when the child reaches "_start", at which point the
1186      dld will have had a chance to initialize the child.  */
1187   /* Also, loading a symbol file below may trigger symbol lookups, and
1188      we don't want those to be satisfied by the libraries of the
1189      previous incarnation of this process.  */
1190   no_shared_libraries (NULL, 0);
1191
1192   if (follow_exec_mode_string == follow_exec_mode_new)
1193     {
1194       /* The user wants to keep the old inferior and program spaces
1195          around.  Create a new fresh one, and switch to it.  */
1196
1197       /* Do exit processing for the original inferior before adding
1198          the new inferior so we don't have two active inferiors with
1199          the same ptid, which can confuse find_inferior_ptid.  */
1200       exit_inferior_num_silent (current_inferior ()->num);
1201
1202       inf = add_inferior_with_spaces ();
1203       inf->pid = pid;
1204       target_follow_exec (inf, exec_file_target);
1205
1206       set_current_inferior (inf);
1207       set_current_program_space (inf->pspace);
1208     }
1209   else
1210     {
1211       /* The old description may no longer be fit for the new image.
1212          E.g, a 64-bit process exec'ed a 32-bit process.  Clear the
1213          old description; we'll read a new one below.  No need to do
1214          this on "follow-exec-mode new", as the old inferior stays
1215          around (its description is later cleared/refetched on
1216          restart).  */
1217       target_clear_description ();
1218     }
1219
1220   gdb_assert (current_program_space == inf->pspace);
1221
1222   /* Attempt to open the exec file.  SYMFILE_DEFER_BP_RESET is used
1223      because the proper displacement for a PIE (Position Independent
1224      Executable) main symbol file will only be computed by
1225      solib_create_inferior_hook below.  breakpoint_re_set would fail
1226      to insert the breakpoints with the zero displacement.  */
1227   try_open_exec_file (exec_file_host, inf, SYMFILE_DEFER_BP_RESET);
1228
1229   do_cleanups (old_chain);
1230
1231   /* If the target can specify a description, read it.  Must do this
1232      after flipping to the new executable (because the target supplied
1233      description must be compatible with the executable's
1234      architecture, and the old executable may e.g., be 32-bit, while
1235      the new one 64-bit), and before anything involving memory or
1236      registers.  */
1237   target_find_description ();
1238
1239   /* The add_thread call ends up reading registers, so do it after updating the
1240      target description.  */
1241   if (follow_exec_mode_string == follow_exec_mode_new)
1242     add_thread (ptid);
1243
1244   solib_create_inferior_hook (0);
1245
1246   jit_inferior_created_hook ();
1247
1248   breakpoint_re_set ();
1249
1250   /* Reinsert all breakpoints.  (Those which were symbolic have
1251      been reset to the proper address in the new a.out, thanks
1252      to symbol_file_command...).  */
1253   insert_breakpoints ();
1254
1255   /* The next resume of this inferior should bring it to the shlib
1256      startup breakpoints.  (If the user had also set bp's on
1257      "main" from the old (parent) process, then they'll auto-
1258      matically get reset there in the new process.).  */
1259 }
1260
1261 /* The queue of threads that need to do a step-over operation to get
1262    past e.g., a breakpoint.  What technique is used to step over the
1263    breakpoint/watchpoint does not matter -- all threads end up in the
1264    same queue, to maintain rough temporal order of execution, in order
1265    to avoid starvation, otherwise, we could e.g., find ourselves
1266    constantly stepping the same couple threads past their breakpoints
1267    over and over, if the single-step finish fast enough.  */
1268 struct thread_info *step_over_queue_head;
1269
1270 /* Bit flags indicating what the thread needs to step over.  */
1271
1272 enum step_over_what_flag
1273   {
1274     /* Step over a breakpoint.  */
1275     STEP_OVER_BREAKPOINT = 1,
1276
1277     /* Step past a non-continuable watchpoint, in order to let the
1278        instruction execute so we can evaluate the watchpoint
1279        expression.  */
1280     STEP_OVER_WATCHPOINT = 2
1281   };
1282 DEF_ENUM_FLAGS_TYPE (enum step_over_what_flag, step_over_what);
1283
1284 /* Info about an instruction that is being stepped over.  */
1285
1286 struct step_over_info
1287 {
1288   /* If we're stepping past a breakpoint, this is the address space
1289      and address of the instruction the breakpoint is set at.  We'll
1290      skip inserting all breakpoints here.  Valid iff ASPACE is
1291      non-NULL.  */
1292   const address_space *aspace;
1293   CORE_ADDR address;
1294
1295   /* The instruction being stepped over triggers a nonsteppable
1296      watchpoint.  If true, we'll skip inserting watchpoints.  */
1297   int nonsteppable_watchpoint_p;
1298
1299   /* The thread's global number.  */
1300   int thread;
1301 };
1302
1303 /* The step-over info of the location that is being stepped over.
1304
1305    Note that with async/breakpoint always-inserted mode, a user might
1306    set a new breakpoint/watchpoint/etc. exactly while a breakpoint is
1307    being stepped over.  As setting a new breakpoint inserts all
1308    breakpoints, we need to make sure the breakpoint being stepped over
1309    isn't inserted then.  We do that by only clearing the step-over
1310    info when the step-over is actually finished (or aborted).
1311
1312    Presently GDB can only step over one breakpoint at any given time.
1313    Given threads that can't run code in the same address space as the
1314    breakpoint's can't really miss the breakpoint, GDB could be taught
1315    to step-over at most one breakpoint per address space (so this info
1316    could move to the address space object if/when GDB is extended).
1317    The set of breakpoints being stepped over will normally be much
1318    smaller than the set of all breakpoints, so a flag in the
1319    breakpoint location structure would be wasteful.  A separate list
1320    also saves complexity and run-time, as otherwise we'd have to go
1321    through all breakpoint locations clearing their flag whenever we
1322    start a new sequence.  Similar considerations weigh against storing
1323    this info in the thread object.  Plus, not all step overs actually
1324    have breakpoint locations -- e.g., stepping past a single-step
1325    breakpoint, or stepping to complete a non-continuable
1326    watchpoint.  */
1327 static struct step_over_info step_over_info;
1328
1329 /* Record the address of the breakpoint/instruction we're currently
1330    stepping over.
1331    N.B. We record the aspace and address now, instead of say just the thread,
1332    because when we need the info later the thread may be running.  */
1333
1334 static void
1335 set_step_over_info (const address_space *aspace, CORE_ADDR address,
1336                     int nonsteppable_watchpoint_p,
1337                     int thread)
1338 {
1339   step_over_info.aspace = aspace;
1340   step_over_info.address = address;
1341   step_over_info.nonsteppable_watchpoint_p = nonsteppable_watchpoint_p;
1342   step_over_info.thread = thread;
1343 }
1344
1345 /* Called when we're not longer stepping over a breakpoint / an
1346    instruction, so all breakpoints are free to be (re)inserted.  */
1347
1348 static void
1349 clear_step_over_info (void)
1350 {
1351   if (debug_infrun)
1352     fprintf_unfiltered (gdb_stdlog,
1353                         "infrun: clear_step_over_info\n");
1354   step_over_info.aspace = NULL;
1355   step_over_info.address = 0;
1356   step_over_info.nonsteppable_watchpoint_p = 0;
1357   step_over_info.thread = -1;
1358 }
1359
1360 /* See infrun.h.  */
1361
1362 int
1363 stepping_past_instruction_at (struct address_space *aspace,
1364                               CORE_ADDR address)
1365 {
1366   return (step_over_info.aspace != NULL
1367           && breakpoint_address_match (aspace, address,
1368                                        step_over_info.aspace,
1369                                        step_over_info.address));
1370 }
1371
1372 /* See infrun.h.  */
1373
1374 int
1375 thread_is_stepping_over_breakpoint (int thread)
1376 {
1377   return (step_over_info.thread != -1
1378           && thread == step_over_info.thread);
1379 }
1380
1381 /* See infrun.h.  */
1382
1383 int
1384 stepping_past_nonsteppable_watchpoint (void)
1385 {
1386   return step_over_info.nonsteppable_watchpoint_p;
1387 }
1388
1389 /* Returns true if step-over info is valid.  */
1390
1391 static int
1392 step_over_info_valid_p (void)
1393 {
1394   return (step_over_info.aspace != NULL
1395           || stepping_past_nonsteppable_watchpoint ());
1396 }
1397
1398 \f
1399 /* Displaced stepping.  */
1400
1401 /* In non-stop debugging mode, we must take special care to manage
1402    breakpoints properly; in particular, the traditional strategy for
1403    stepping a thread past a breakpoint it has hit is unsuitable.
1404    'Displaced stepping' is a tactic for stepping one thread past a
1405    breakpoint it has hit while ensuring that other threads running
1406    concurrently will hit the breakpoint as they should.
1407
1408    The traditional way to step a thread T off a breakpoint in a
1409    multi-threaded program in all-stop mode is as follows:
1410
1411    a0) Initially, all threads are stopped, and breakpoints are not
1412        inserted.
1413    a1) We single-step T, leaving breakpoints uninserted.
1414    a2) We insert breakpoints, and resume all threads.
1415
1416    In non-stop debugging, however, this strategy is unsuitable: we
1417    don't want to have to stop all threads in the system in order to
1418    continue or step T past a breakpoint.  Instead, we use displaced
1419    stepping:
1420
1421    n0) Initially, T is stopped, other threads are running, and
1422        breakpoints are inserted.
1423    n1) We copy the instruction "under" the breakpoint to a separate
1424        location, outside the main code stream, making any adjustments
1425        to the instruction, register, and memory state as directed by
1426        T's architecture.
1427    n2) We single-step T over the instruction at its new location.
1428    n3) We adjust the resulting register and memory state as directed
1429        by T's architecture.  This includes resetting T's PC to point
1430        back into the main instruction stream.
1431    n4) We resume T.
1432
1433    This approach depends on the following gdbarch methods:
1434
1435    - gdbarch_max_insn_length and gdbarch_displaced_step_location
1436      indicate where to copy the instruction, and how much space must
1437      be reserved there.  We use these in step n1.
1438
1439    - gdbarch_displaced_step_copy_insn copies a instruction to a new
1440      address, and makes any necessary adjustments to the instruction,
1441      register contents, and memory.  We use this in step n1.
1442
1443    - gdbarch_displaced_step_fixup adjusts registers and memory after
1444      we have successfuly single-stepped the instruction, to yield the
1445      same effect the instruction would have had if we had executed it
1446      at its original address.  We use this in step n3.
1447
1448    The gdbarch_displaced_step_copy_insn and
1449    gdbarch_displaced_step_fixup functions must be written so that
1450    copying an instruction with gdbarch_displaced_step_copy_insn,
1451    single-stepping across the copied instruction, and then applying
1452    gdbarch_displaced_insn_fixup should have the same effects on the
1453    thread's memory and registers as stepping the instruction in place
1454    would have.  Exactly which responsibilities fall to the copy and
1455    which fall to the fixup is up to the author of those functions.
1456
1457    See the comments in gdbarch.sh for details.
1458
1459    Note that displaced stepping and software single-step cannot
1460    currently be used in combination, although with some care I think
1461    they could be made to.  Software single-step works by placing
1462    breakpoints on all possible subsequent instructions; if the
1463    displaced instruction is a PC-relative jump, those breakpoints
1464    could fall in very strange places --- on pages that aren't
1465    executable, or at addresses that are not proper instruction
1466    boundaries.  (We do generally let other threads run while we wait
1467    to hit the software single-step breakpoint, and they might
1468    encounter such a corrupted instruction.)  One way to work around
1469    this would be to have gdbarch_displaced_step_copy_insn fully
1470    simulate the effect of PC-relative instructions (and return NULL)
1471    on architectures that use software single-stepping.
1472
1473    In non-stop mode, we can have independent and simultaneous step
1474    requests, so more than one thread may need to simultaneously step
1475    over a breakpoint.  The current implementation assumes there is
1476    only one scratch space per process.  In this case, we have to
1477    serialize access to the scratch space.  If thread A wants to step
1478    over a breakpoint, but we are currently waiting for some other
1479    thread to complete a displaced step, we leave thread A stopped and
1480    place it in the displaced_step_request_queue.  Whenever a displaced
1481    step finishes, we pick the next thread in the queue and start a new
1482    displaced step operation on it.  See displaced_step_prepare and
1483    displaced_step_fixup for details.  */
1484
1485 /* Default destructor for displaced_step_closure.  */
1486
1487 displaced_step_closure::~displaced_step_closure () = default;
1488
1489 /* Per-inferior displaced stepping state.  */
1490 struct displaced_step_inferior_state
1491 {
1492   /* Pointer to next in linked list.  */
1493   struct displaced_step_inferior_state *next;
1494
1495   /* The process this displaced step state refers to.  */
1496   int pid;
1497
1498   /* True if preparing a displaced step ever failed.  If so, we won't
1499      try displaced stepping for this inferior again.  */
1500   int failed_before;
1501
1502   /* If this is not null_ptid, this is the thread carrying out a
1503      displaced single-step in process PID.  This thread's state will
1504      require fixing up once it has completed its step.  */
1505   ptid_t step_ptid;
1506
1507   /* The architecture the thread had when we stepped it.  */
1508   struct gdbarch *step_gdbarch;
1509
1510   /* The closure provided gdbarch_displaced_step_copy_insn, to be used
1511      for post-step cleanup.  */
1512   struct displaced_step_closure *step_closure;
1513
1514   /* The address of the original instruction, and the copy we
1515      made.  */
1516   CORE_ADDR step_original, step_copy;
1517
1518   /* Saved contents of copy area.  */
1519   gdb_byte *step_saved_copy;
1520 };
1521
1522 /* The list of states of processes involved in displaced stepping
1523    presently.  */
1524 static struct displaced_step_inferior_state *displaced_step_inferior_states;
1525
1526 /* Get the displaced stepping state of process PID.  */
1527
1528 static struct displaced_step_inferior_state *
1529 get_displaced_stepping_state (int pid)
1530 {
1531   struct displaced_step_inferior_state *state;
1532
1533   for (state = displaced_step_inferior_states;
1534        state != NULL;
1535        state = state->next)
1536     if (state->pid == pid)
1537       return state;
1538
1539   return NULL;
1540 }
1541
1542 /* Returns true if any inferior has a thread doing a displaced
1543    step.  */
1544
1545 static int
1546 displaced_step_in_progress_any_inferior (void)
1547 {
1548   struct displaced_step_inferior_state *state;
1549
1550   for (state = displaced_step_inferior_states;
1551        state != NULL;
1552        state = state->next)
1553     if (!ptid_equal (state->step_ptid, null_ptid))
1554       return 1;
1555
1556   return 0;
1557 }
1558
1559 /* Return true if thread represented by PTID is doing a displaced
1560    step.  */
1561
1562 static int
1563 displaced_step_in_progress_thread (ptid_t ptid)
1564 {
1565   struct displaced_step_inferior_state *displaced;
1566
1567   gdb_assert (!ptid_equal (ptid, null_ptid));
1568
1569   displaced = get_displaced_stepping_state (ptid_get_pid (ptid));
1570
1571   return (displaced != NULL && ptid_equal (displaced->step_ptid, ptid));
1572 }
1573
1574 /* Return true if process PID has a thread doing a displaced step.  */
1575
1576 static int
1577 displaced_step_in_progress (int pid)
1578 {
1579   struct displaced_step_inferior_state *displaced;
1580
1581   displaced = get_displaced_stepping_state (pid);
1582   if (displaced != NULL && !ptid_equal (displaced->step_ptid, null_ptid))
1583     return 1;
1584
1585   return 0;
1586 }
1587
1588 /* Add a new displaced stepping state for process PID to the displaced
1589    stepping state list, or return a pointer to an already existing
1590    entry, if it already exists.  Never returns NULL.  */
1591
1592 static struct displaced_step_inferior_state *
1593 add_displaced_stepping_state (int pid)
1594 {
1595   struct displaced_step_inferior_state *state;
1596
1597   for (state = displaced_step_inferior_states;
1598        state != NULL;
1599        state = state->next)
1600     if (state->pid == pid)
1601       return state;
1602
1603   state = XCNEW (struct displaced_step_inferior_state);
1604   state->pid = pid;
1605   state->next = displaced_step_inferior_states;
1606   displaced_step_inferior_states = state;
1607
1608   return state;
1609 }
1610
1611 /* If inferior is in displaced stepping, and ADDR equals to starting address
1612    of copy area, return corresponding displaced_step_closure.  Otherwise,
1613    return NULL.  */
1614
1615 struct displaced_step_closure*
1616 get_displaced_step_closure_by_addr (CORE_ADDR addr)
1617 {
1618   struct displaced_step_inferior_state *displaced
1619     = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
1620
1621   /* If checking the mode of displaced instruction in copy area.  */
1622   if (displaced && !ptid_equal (displaced->step_ptid, null_ptid)
1623      && (displaced->step_copy == addr))
1624     return displaced->step_closure;
1625
1626   return NULL;
1627 }
1628
1629 /* Remove the displaced stepping state of process PID.  */
1630
1631 static void
1632 remove_displaced_stepping_state (int pid)
1633 {
1634   struct displaced_step_inferior_state *it, **prev_next_p;
1635
1636   gdb_assert (pid != 0);
1637
1638   it = displaced_step_inferior_states;
1639   prev_next_p = &displaced_step_inferior_states;
1640   while (it)
1641     {
1642       if (it->pid == pid)
1643         {
1644           *prev_next_p = it->next;
1645           xfree (it);
1646           return;
1647         }
1648
1649       prev_next_p = &it->next;
1650       it = *prev_next_p;
1651     }
1652 }
1653
1654 static void
1655 infrun_inferior_exit (struct inferior *inf)
1656 {
1657   remove_displaced_stepping_state (inf->pid);
1658 }
1659
1660 /* If ON, and the architecture supports it, GDB will use displaced
1661    stepping to step over breakpoints.  If OFF, or if the architecture
1662    doesn't support it, GDB will instead use the traditional
1663    hold-and-step approach.  If AUTO (which is the default), GDB will
1664    decide which technique to use to step over breakpoints depending on
1665    which of all-stop or non-stop mode is active --- displaced stepping
1666    in non-stop mode; hold-and-step in all-stop mode.  */
1667
1668 static enum auto_boolean can_use_displaced_stepping = AUTO_BOOLEAN_AUTO;
1669
1670 static void
1671 show_can_use_displaced_stepping (struct ui_file *file, int from_tty,
1672                                  struct cmd_list_element *c,
1673                                  const char *value)
1674 {
1675   if (can_use_displaced_stepping == AUTO_BOOLEAN_AUTO)
1676     fprintf_filtered (file,
1677                       _("Debugger's willingness to use displaced stepping "
1678                         "to step over breakpoints is %s (currently %s).\n"),
1679                       value, target_is_non_stop_p () ? "on" : "off");
1680   else
1681     fprintf_filtered (file,
1682                       _("Debugger's willingness to use displaced stepping "
1683                         "to step over breakpoints is %s.\n"), value);
1684 }
1685
1686 /* Return non-zero if displaced stepping can/should be used to step
1687    over breakpoints of thread TP.  */
1688
1689 static int
1690 use_displaced_stepping (struct thread_info *tp)
1691 {
1692   struct regcache *regcache = get_thread_regcache (tp->ptid);
1693   struct gdbarch *gdbarch = regcache->arch ();
1694   struct displaced_step_inferior_state *displaced_state;
1695
1696   displaced_state = get_displaced_stepping_state (ptid_get_pid (tp->ptid));
1697
1698   return (((can_use_displaced_stepping == AUTO_BOOLEAN_AUTO
1699             && target_is_non_stop_p ())
1700            || can_use_displaced_stepping == AUTO_BOOLEAN_TRUE)
1701           && gdbarch_displaced_step_copy_insn_p (gdbarch)
1702           && find_record_target () == NULL
1703           && (displaced_state == NULL
1704               || !displaced_state->failed_before));
1705 }
1706
1707 /* Clean out any stray displaced stepping state.  */
1708 static void
1709 displaced_step_clear (struct displaced_step_inferior_state *displaced)
1710 {
1711   /* Indicate that there is no cleanup pending.  */
1712   displaced->step_ptid = null_ptid;
1713
1714   delete displaced->step_closure;
1715   displaced->step_closure = NULL;
1716 }
1717
1718 static void
1719 displaced_step_clear_cleanup (void *arg)
1720 {
1721   struct displaced_step_inferior_state *state
1722     = (struct displaced_step_inferior_state *) arg;
1723
1724   displaced_step_clear (state);
1725 }
1726
1727 /* Dump LEN bytes at BUF in hex to FILE, followed by a newline.  */
1728 void
1729 displaced_step_dump_bytes (struct ui_file *file,
1730                            const gdb_byte *buf,
1731                            size_t len)
1732 {
1733   int i;
1734
1735   for (i = 0; i < len; i++)
1736     fprintf_unfiltered (file, "%02x ", buf[i]);
1737   fputs_unfiltered ("\n", file);
1738 }
1739
1740 /* Prepare to single-step, using displaced stepping.
1741
1742    Note that we cannot use displaced stepping when we have a signal to
1743    deliver.  If we have a signal to deliver and an instruction to step
1744    over, then after the step, there will be no indication from the
1745    target whether the thread entered a signal handler or ignored the
1746    signal and stepped over the instruction successfully --- both cases
1747    result in a simple SIGTRAP.  In the first case we mustn't do a
1748    fixup, and in the second case we must --- but we can't tell which.
1749    Comments in the code for 'random signals' in handle_inferior_event
1750    explain how we handle this case instead.
1751
1752    Returns 1 if preparing was successful -- this thread is going to be
1753    stepped now; 0 if displaced stepping this thread got queued; or -1
1754    if this instruction can't be displaced stepped.  */
1755
1756 static int
1757 displaced_step_prepare_throw (ptid_t ptid)
1758 {
1759   struct cleanup *ignore_cleanups;
1760   struct thread_info *tp = find_thread_ptid (ptid);
1761   struct regcache *regcache = get_thread_regcache (ptid);
1762   struct gdbarch *gdbarch = regcache->arch ();
1763   const address_space *aspace = regcache->aspace ();
1764   CORE_ADDR original, copy;
1765   ULONGEST len;
1766   struct displaced_step_closure *closure;
1767   struct displaced_step_inferior_state *displaced;
1768   int status;
1769
1770   /* We should never reach this function if the architecture does not
1771      support displaced stepping.  */
1772   gdb_assert (gdbarch_displaced_step_copy_insn_p (gdbarch));
1773
1774   /* Nor if the thread isn't meant to step over a breakpoint.  */
1775   gdb_assert (tp->control.trap_expected);
1776
1777   /* Disable range stepping while executing in the scratch pad.  We
1778      want a single-step even if executing the displaced instruction in
1779      the scratch buffer lands within the stepping range (e.g., a
1780      jump/branch).  */
1781   tp->control.may_range_step = 0;
1782
1783   /* We have to displaced step one thread at a time, as we only have
1784      access to a single scratch space per inferior.  */
1785
1786   displaced = add_displaced_stepping_state (ptid_get_pid (ptid));
1787
1788   if (!ptid_equal (displaced->step_ptid, null_ptid))
1789     {
1790       /* Already waiting for a displaced step to finish.  Defer this
1791          request and place in queue.  */
1792
1793       if (debug_displaced)
1794         fprintf_unfiltered (gdb_stdlog,
1795                             "displaced: deferring step of %s\n",
1796                             target_pid_to_str (ptid));
1797
1798       thread_step_over_chain_enqueue (tp);
1799       return 0;
1800     }
1801   else
1802     {
1803       if (debug_displaced)
1804         fprintf_unfiltered (gdb_stdlog,
1805                             "displaced: stepping %s now\n",
1806                             target_pid_to_str (ptid));
1807     }
1808
1809   displaced_step_clear (displaced);
1810
1811   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
1812   inferior_ptid = ptid;
1813
1814   original = regcache_read_pc (regcache);
1815
1816   copy = gdbarch_displaced_step_location (gdbarch);
1817   len = gdbarch_max_insn_length (gdbarch);
1818
1819   if (breakpoint_in_range_p (aspace, copy, len))
1820     {
1821       /* There's a breakpoint set in the scratch pad location range
1822          (which is usually around the entry point).  We'd either
1823          install it before resuming, which would overwrite/corrupt the
1824          scratch pad, or if it was already inserted, this displaced
1825          step would overwrite it.  The latter is OK in the sense that
1826          we already assume that no thread is going to execute the code
1827          in the scratch pad range (after initial startup) anyway, but
1828          the former is unacceptable.  Simply punt and fallback to
1829          stepping over this breakpoint in-line.  */
1830       if (debug_displaced)
1831         {
1832           fprintf_unfiltered (gdb_stdlog,
1833                               "displaced: breakpoint set in scratch pad.  "
1834                               "Stepping over breakpoint in-line instead.\n");
1835         }
1836
1837       return -1;
1838     }
1839
1840   /* Save the original contents of the copy area.  */
1841   displaced->step_saved_copy = (gdb_byte *) xmalloc (len);
1842   ignore_cleanups = make_cleanup (free_current_contents,
1843                                   &displaced->step_saved_copy);
1844   status = target_read_memory (copy, displaced->step_saved_copy, len);
1845   if (status != 0)
1846     throw_error (MEMORY_ERROR,
1847                  _("Error accessing memory address %s (%s) for "
1848                    "displaced-stepping scratch space."),
1849                  paddress (gdbarch, copy), safe_strerror (status));
1850   if (debug_displaced)
1851     {
1852       fprintf_unfiltered (gdb_stdlog, "displaced: saved %s: ",
1853                           paddress (gdbarch, copy));
1854       displaced_step_dump_bytes (gdb_stdlog,
1855                                  displaced->step_saved_copy,
1856                                  len);
1857     };
1858
1859   closure = gdbarch_displaced_step_copy_insn (gdbarch,
1860                                               original, copy, regcache);
1861   if (closure == NULL)
1862     {
1863       /* The architecture doesn't know how or want to displaced step
1864          this instruction or instruction sequence.  Fallback to
1865          stepping over the breakpoint in-line.  */
1866       do_cleanups (ignore_cleanups);
1867       return -1;
1868     }
1869
1870   /* Save the information we need to fix things up if the step
1871      succeeds.  */
1872   displaced->step_ptid = ptid;
1873   displaced->step_gdbarch = gdbarch;
1874   displaced->step_closure = closure;
1875   displaced->step_original = original;
1876   displaced->step_copy = copy;
1877
1878   make_cleanup (displaced_step_clear_cleanup, displaced);
1879
1880   /* Resume execution at the copy.  */
1881   regcache_write_pc (regcache, copy);
1882
1883   discard_cleanups (ignore_cleanups);
1884
1885   if (debug_displaced)
1886     fprintf_unfiltered (gdb_stdlog, "displaced: displaced pc to %s\n",
1887                         paddress (gdbarch, copy));
1888
1889   return 1;
1890 }
1891
1892 /* Wrapper for displaced_step_prepare_throw that disabled further
1893    attempts at displaced stepping if we get a memory error.  */
1894
1895 static int
1896 displaced_step_prepare (ptid_t ptid)
1897 {
1898   int prepared = -1;
1899
1900   TRY
1901     {
1902       prepared = displaced_step_prepare_throw (ptid);
1903     }
1904   CATCH (ex, RETURN_MASK_ERROR)
1905     {
1906       struct displaced_step_inferior_state *displaced_state;
1907
1908       if (ex.error != MEMORY_ERROR
1909           && ex.error != NOT_SUPPORTED_ERROR)
1910         throw_exception (ex);
1911
1912       if (debug_infrun)
1913         {
1914           fprintf_unfiltered (gdb_stdlog,
1915                               "infrun: disabling displaced stepping: %s\n",
1916                               ex.message);
1917         }
1918
1919       /* Be verbose if "set displaced-stepping" is "on", silent if
1920          "auto".  */
1921       if (can_use_displaced_stepping == AUTO_BOOLEAN_TRUE)
1922         {
1923           warning (_("disabling displaced stepping: %s"),
1924                    ex.message);
1925         }
1926
1927       /* Disable further displaced stepping attempts.  */
1928       displaced_state
1929         = get_displaced_stepping_state (ptid_get_pid (ptid));
1930       displaced_state->failed_before = 1;
1931     }
1932   END_CATCH
1933
1934   return prepared;
1935 }
1936
1937 static void
1938 write_memory_ptid (ptid_t ptid, CORE_ADDR memaddr,
1939                    const gdb_byte *myaddr, int len)
1940 {
1941   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
1942
1943   inferior_ptid = ptid;
1944   write_memory (memaddr, myaddr, len);
1945 }
1946
1947 /* Restore the contents of the copy area for thread PTID.  */
1948
1949 static void
1950 displaced_step_restore (struct displaced_step_inferior_state *displaced,
1951                         ptid_t ptid)
1952 {
1953   ULONGEST len = gdbarch_max_insn_length (displaced->step_gdbarch);
1954
1955   write_memory_ptid (ptid, displaced->step_copy,
1956                      displaced->step_saved_copy, len);
1957   if (debug_displaced)
1958     fprintf_unfiltered (gdb_stdlog, "displaced: restored %s %s\n",
1959                         target_pid_to_str (ptid),
1960                         paddress (displaced->step_gdbarch,
1961                                   displaced->step_copy));
1962 }
1963
1964 /* If we displaced stepped an instruction successfully, adjust
1965    registers and memory to yield the same effect the instruction would
1966    have had if we had executed it at its original address, and return
1967    1.  If the instruction didn't complete, relocate the PC and return
1968    -1.  If the thread wasn't displaced stepping, return 0.  */
1969
1970 static int
1971 displaced_step_fixup (ptid_t event_ptid, enum gdb_signal signal)
1972 {
1973   struct cleanup *old_cleanups;
1974   struct displaced_step_inferior_state *displaced
1975     = get_displaced_stepping_state (ptid_get_pid (event_ptid));
1976   int ret;
1977
1978   /* Was any thread of this process doing a displaced step?  */
1979   if (displaced == NULL)
1980     return 0;
1981
1982   /* Was this event for the pid we displaced?  */
1983   if (ptid_equal (displaced->step_ptid, null_ptid)
1984       || ! ptid_equal (displaced->step_ptid, event_ptid))
1985     return 0;
1986
1987   old_cleanups = make_cleanup (displaced_step_clear_cleanup, displaced);
1988
1989   displaced_step_restore (displaced, displaced->step_ptid);
1990
1991   /* Fixup may need to read memory/registers.  Switch to the thread
1992      that we're fixing up.  Also, target_stopped_by_watchpoint checks
1993      the current thread.  */
1994   switch_to_thread (event_ptid);
1995
1996   /* Did the instruction complete successfully?  */
1997   if (signal == GDB_SIGNAL_TRAP
1998       && !(target_stopped_by_watchpoint ()
1999            && (gdbarch_have_nonsteppable_watchpoint (displaced->step_gdbarch)
2000                || target_have_steppable_watchpoint)))
2001     {
2002       /* Fix up the resulting state.  */
2003       gdbarch_displaced_step_fixup (displaced->step_gdbarch,
2004                                     displaced->step_closure,
2005                                     displaced->step_original,
2006                                     displaced->step_copy,
2007                                     get_thread_regcache (displaced->step_ptid));
2008       ret = 1;
2009     }
2010   else
2011     {
2012       /* Since the instruction didn't complete, all we can do is
2013          relocate the PC.  */
2014       struct regcache *regcache = get_thread_regcache (event_ptid);
2015       CORE_ADDR pc = regcache_read_pc (regcache);
2016
2017       pc = displaced->step_original + (pc - displaced->step_copy);
2018       regcache_write_pc (regcache, pc);
2019       ret = -1;
2020     }
2021
2022   do_cleanups (old_cleanups);
2023
2024   displaced->step_ptid = null_ptid;
2025
2026   return ret;
2027 }
2028
2029 /* Data to be passed around while handling an event.  This data is
2030    discarded between events.  */
2031 struct execution_control_state
2032 {
2033   ptid_t ptid;
2034   /* The thread that got the event, if this was a thread event; NULL
2035      otherwise.  */
2036   struct thread_info *event_thread;
2037
2038   struct target_waitstatus ws;
2039   int stop_func_filled_in;
2040   CORE_ADDR stop_func_start;
2041   CORE_ADDR stop_func_end;
2042   const char *stop_func_name;
2043   int wait_some_more;
2044
2045   /* True if the event thread hit the single-step breakpoint of
2046      another thread.  Thus the event doesn't cause a stop, the thread
2047      needs to be single-stepped past the single-step breakpoint before
2048      we can switch back to the original stepping thread.  */
2049   int hit_singlestep_breakpoint;
2050 };
2051
2052 /* Clear ECS and set it to point at TP.  */
2053
2054 static void
2055 reset_ecs (struct execution_control_state *ecs, struct thread_info *tp)
2056 {
2057   memset (ecs, 0, sizeof (*ecs));
2058   ecs->event_thread = tp;
2059   ecs->ptid = tp->ptid;
2060 }
2061
2062 static void keep_going_pass_signal (struct execution_control_state *ecs);
2063 static void prepare_to_wait (struct execution_control_state *ecs);
2064 static int keep_going_stepped_thread (struct thread_info *tp);
2065 static step_over_what thread_still_needs_step_over (struct thread_info *tp);
2066
2067 /* Are there any pending step-over requests?  If so, run all we can
2068    now and return true.  Otherwise, return false.  */
2069
2070 static int
2071 start_step_over (void)
2072 {
2073   struct thread_info *tp, *next;
2074
2075   /* Don't start a new step-over if we already have an in-line
2076      step-over operation ongoing.  */
2077   if (step_over_info_valid_p ())
2078     return 0;
2079
2080   for (tp = step_over_queue_head; tp != NULL; tp = next)
2081     {
2082       struct execution_control_state ecss;
2083       struct execution_control_state *ecs = &ecss;
2084       step_over_what step_what;
2085       int must_be_in_line;
2086
2087       gdb_assert (!tp->stop_requested);
2088
2089       next = thread_step_over_chain_next (tp);
2090
2091       /* If this inferior already has a displaced step in process,
2092          don't start a new one.  */
2093       if (displaced_step_in_progress (ptid_get_pid (tp->ptid)))
2094         continue;
2095
2096       step_what = thread_still_needs_step_over (tp);
2097       must_be_in_line = ((step_what & STEP_OVER_WATCHPOINT)
2098                          || ((step_what & STEP_OVER_BREAKPOINT)
2099                              && !use_displaced_stepping (tp)));
2100
2101       /* We currently stop all threads of all processes to step-over
2102          in-line.  If we need to start a new in-line step-over, let
2103          any pending displaced steps finish first.  */
2104       if (must_be_in_line && displaced_step_in_progress_any_inferior ())
2105         return 0;
2106
2107       thread_step_over_chain_remove (tp);
2108
2109       if (step_over_queue_head == NULL)
2110         {
2111           if (debug_infrun)
2112             fprintf_unfiltered (gdb_stdlog,
2113                                 "infrun: step-over queue now empty\n");
2114         }
2115
2116       if (tp->control.trap_expected
2117           || tp->resumed
2118           || tp->executing)
2119         {
2120           internal_error (__FILE__, __LINE__,
2121                           "[%s] has inconsistent state: "
2122                           "trap_expected=%d, resumed=%d, executing=%d\n",
2123                           target_pid_to_str (tp->ptid),
2124                           tp->control.trap_expected,
2125                           tp->resumed,
2126                           tp->executing);
2127         }
2128
2129       if (debug_infrun)
2130         fprintf_unfiltered (gdb_stdlog,
2131                             "infrun: resuming [%s] for step-over\n",
2132                             target_pid_to_str (tp->ptid));
2133
2134       /* keep_going_pass_signal skips the step-over if the breakpoint
2135          is no longer inserted.  In all-stop, we want to keep looking
2136          for a thread that needs a step-over instead of resuming TP,
2137          because we wouldn't be able to resume anything else until the
2138          target stops again.  In non-stop, the resume always resumes
2139          only TP, so it's OK to let the thread resume freely.  */
2140       if (!target_is_non_stop_p () && !step_what)
2141         continue;
2142
2143       switch_to_thread (tp->ptid);
2144       reset_ecs (ecs, tp);
2145       keep_going_pass_signal (ecs);
2146
2147       if (!ecs->wait_some_more)
2148         error (_("Command aborted."));
2149
2150       gdb_assert (tp->resumed);
2151
2152       /* If we started a new in-line step-over, we're done.  */
2153       if (step_over_info_valid_p ())
2154         {
2155           gdb_assert (tp->control.trap_expected);
2156           return 1;
2157         }
2158
2159       if (!target_is_non_stop_p ())
2160         {
2161           /* On all-stop, shouldn't have resumed unless we needed a
2162              step over.  */
2163           gdb_assert (tp->control.trap_expected
2164                       || tp->step_after_step_resume_breakpoint);
2165
2166           /* With remote targets (at least), in all-stop, we can't
2167              issue any further remote commands until the program stops
2168              again.  */
2169           return 1;
2170         }
2171
2172       /* Either the thread no longer needed a step-over, or a new
2173          displaced stepping sequence started.  Even in the latter
2174          case, continue looking.  Maybe we can also start another
2175          displaced step on a thread of other process. */
2176     }
2177
2178   return 0;
2179 }
2180
2181 /* Update global variables holding ptids to hold NEW_PTID if they were
2182    holding OLD_PTID.  */
2183 static void
2184 infrun_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
2185 {
2186   struct displaced_step_inferior_state *displaced;
2187
2188   if (ptid_equal (inferior_ptid, old_ptid))
2189     inferior_ptid = new_ptid;
2190
2191   for (displaced = displaced_step_inferior_states;
2192        displaced;
2193        displaced = displaced->next)
2194     {
2195       if (ptid_equal (displaced->step_ptid, old_ptid))
2196         displaced->step_ptid = new_ptid;
2197     }
2198 }
2199
2200 \f
2201 /* Resuming.  */
2202
2203 /* Things to clean up if we QUIT out of resume ().  */
2204 static void
2205 resume_cleanups (void *ignore)
2206 {
2207   if (!ptid_equal (inferior_ptid, null_ptid))
2208     delete_single_step_breakpoints (inferior_thread ());
2209
2210   normal_stop ();
2211 }
2212
2213 static const char schedlock_off[] = "off";
2214 static const char schedlock_on[] = "on";
2215 static const char schedlock_step[] = "step";
2216 static const char schedlock_replay[] = "replay";
2217 static const char *const scheduler_enums[] = {
2218   schedlock_off,
2219   schedlock_on,
2220   schedlock_step,
2221   schedlock_replay,
2222   NULL
2223 };
2224 static const char *scheduler_mode = schedlock_replay;
2225 static void
2226 show_scheduler_mode (struct ui_file *file, int from_tty,
2227                      struct cmd_list_element *c, const char *value)
2228 {
2229   fprintf_filtered (file,
2230                     _("Mode for locking scheduler "
2231                       "during execution is \"%s\".\n"),
2232                     value);
2233 }
2234
2235 static void
2236 set_schedlock_func (char *args, int from_tty, struct cmd_list_element *c)
2237 {
2238   if (!target_can_lock_scheduler)
2239     {
2240       scheduler_mode = schedlock_off;
2241       error (_("Target '%s' cannot support this command."), target_shortname);
2242     }
2243 }
2244
2245 /* True if execution commands resume all threads of all processes by
2246    default; otherwise, resume only threads of the current inferior
2247    process.  */
2248 int sched_multi = 0;
2249
2250 /* Try to setup for software single stepping over the specified location.
2251    Return 1 if target_resume() should use hardware single step.
2252
2253    GDBARCH the current gdbarch.
2254    PC the location to step over.  */
2255
2256 static int
2257 maybe_software_singlestep (struct gdbarch *gdbarch, CORE_ADDR pc)
2258 {
2259   int hw_step = 1;
2260
2261   if (execution_direction == EXEC_FORWARD
2262       && gdbarch_software_single_step_p (gdbarch))
2263     hw_step = !insert_single_step_breakpoints (gdbarch);
2264
2265   return hw_step;
2266 }
2267
2268 /* See infrun.h.  */
2269
2270 ptid_t
2271 user_visible_resume_ptid (int step)
2272 {
2273   ptid_t resume_ptid;
2274
2275   if (non_stop)
2276     {
2277       /* With non-stop mode on, threads are always handled
2278          individually.  */
2279       resume_ptid = inferior_ptid;
2280     }
2281   else if ((scheduler_mode == schedlock_on)
2282            || (scheduler_mode == schedlock_step && step))
2283     {
2284       /* User-settable 'scheduler' mode requires solo thread
2285          resume.  */
2286       resume_ptid = inferior_ptid;
2287     }
2288   else if ((scheduler_mode == schedlock_replay)
2289            && target_record_will_replay (minus_one_ptid, execution_direction))
2290     {
2291       /* User-settable 'scheduler' mode requires solo thread resume in replay
2292          mode.  */
2293       resume_ptid = inferior_ptid;
2294     }
2295   else if (!sched_multi && target_supports_multi_process ())
2296     {
2297       /* Resume all threads of the current process (and none of other
2298          processes).  */
2299       resume_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
2300     }
2301   else
2302     {
2303       /* Resume all threads of all processes.  */
2304       resume_ptid = RESUME_ALL;
2305     }
2306
2307   return resume_ptid;
2308 }
2309
2310 /* Return a ptid representing the set of threads that we will resume,
2311    in the perspective of the target, assuming run control handling
2312    does not require leaving some threads stopped (e.g., stepping past
2313    breakpoint).  USER_STEP indicates whether we're about to start the
2314    target for a stepping command.  */
2315
2316 static ptid_t
2317 internal_resume_ptid (int user_step)
2318 {
2319   /* In non-stop, we always control threads individually.  Note that
2320      the target may always work in non-stop mode even with "set
2321      non-stop off", in which case user_visible_resume_ptid could
2322      return a wildcard ptid.  */
2323   if (target_is_non_stop_p ())
2324     return inferior_ptid;
2325   else
2326     return user_visible_resume_ptid (user_step);
2327 }
2328
2329 /* Wrapper for target_resume, that handles infrun-specific
2330    bookkeeping.  */
2331
2332 static void
2333 do_target_resume (ptid_t resume_ptid, int step, enum gdb_signal sig)
2334 {
2335   struct thread_info *tp = inferior_thread ();
2336
2337   gdb_assert (!tp->stop_requested);
2338
2339   /* Install inferior's terminal modes.  */
2340   target_terminal::inferior ();
2341
2342   /* Avoid confusing the next resume, if the next stop/resume
2343      happens to apply to another thread.  */
2344   tp->suspend.stop_signal = GDB_SIGNAL_0;
2345
2346   /* Advise target which signals may be handled silently.
2347
2348      If we have removed breakpoints because we are stepping over one
2349      in-line (in any thread), we need to receive all signals to avoid
2350      accidentally skipping a breakpoint during execution of a signal
2351      handler.
2352
2353      Likewise if we're displaced stepping, otherwise a trap for a
2354      breakpoint in a signal handler might be confused with the
2355      displaced step finishing.  We don't make the displaced_step_fixup
2356      step distinguish the cases instead, because:
2357
2358      - a backtrace while stopped in the signal handler would show the
2359        scratch pad as frame older than the signal handler, instead of
2360        the real mainline code.
2361
2362      - when the thread is later resumed, the signal handler would
2363        return to the scratch pad area, which would no longer be
2364        valid.  */
2365   if (step_over_info_valid_p ()
2366       || displaced_step_in_progress (ptid_get_pid (tp->ptid)))
2367     target_pass_signals (0, NULL);
2368   else
2369     target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
2370
2371   target_resume (resume_ptid, step, sig);
2372
2373   target_commit_resume ();
2374 }
2375
2376 /* Resume the inferior, but allow a QUIT.  This is useful if the user
2377    wants to interrupt some lengthy single-stepping operation
2378    (for child processes, the SIGINT goes to the inferior, and so
2379    we get a SIGINT random_signal, but for remote debugging and perhaps
2380    other targets, that's not true).
2381
2382    SIG is the signal to give the inferior (zero for none).  */
2383 void
2384 resume (enum gdb_signal sig)
2385 {
2386   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
2387   struct regcache *regcache = get_current_regcache ();
2388   struct gdbarch *gdbarch = regcache->arch ();
2389   struct thread_info *tp = inferior_thread ();
2390   CORE_ADDR pc = regcache_read_pc (regcache);
2391   const address_space *aspace = regcache->aspace ();
2392   ptid_t resume_ptid;
2393   /* This represents the user's step vs continue request.  When
2394      deciding whether "set scheduler-locking step" applies, it's the
2395      user's intention that counts.  */
2396   const int user_step = tp->control.stepping_command;
2397   /* This represents what we'll actually request the target to do.
2398      This can decay from a step to a continue, if e.g., we need to
2399      implement single-stepping with breakpoints (software
2400      single-step).  */
2401   int step;
2402
2403   gdb_assert (!tp->stop_requested);
2404   gdb_assert (!thread_is_in_step_over_chain (tp));
2405
2406   QUIT;
2407
2408   if (tp->suspend.waitstatus_pending_p)
2409     {
2410       if (debug_infrun)
2411         {
2412           std::string statstr
2413             = target_waitstatus_to_string (&tp->suspend.waitstatus);
2414
2415           fprintf_unfiltered (gdb_stdlog,
2416                               "infrun: resume: thread %s has pending wait "
2417                               "status %s (currently_stepping=%d).\n",
2418                               target_pid_to_str (tp->ptid), statstr.c_str (),
2419                               currently_stepping (tp));
2420         }
2421
2422       tp->resumed = 1;
2423
2424       /* FIXME: What should we do if we are supposed to resume this
2425          thread with a signal?  Maybe we should maintain a queue of
2426          pending signals to deliver.  */
2427       if (sig != GDB_SIGNAL_0)
2428         {
2429           warning (_("Couldn't deliver signal %s to %s."),
2430                    gdb_signal_to_name (sig), target_pid_to_str (tp->ptid));
2431         }
2432
2433       tp->suspend.stop_signal = GDB_SIGNAL_0;
2434       discard_cleanups (old_cleanups);
2435
2436       if (target_can_async_p ())
2437         target_async (1);
2438       return;
2439     }
2440
2441   tp->stepped_breakpoint = 0;
2442
2443   /* Depends on stepped_breakpoint.  */
2444   step = currently_stepping (tp);
2445
2446   if (current_inferior ()->waiting_for_vfork_done)
2447     {
2448       /* Don't try to single-step a vfork parent that is waiting for
2449          the child to get out of the shared memory region (by exec'ing
2450          or exiting).  This is particularly important on software
2451          single-step archs, as the child process would trip on the
2452          software single step breakpoint inserted for the parent
2453          process.  Since the parent will not actually execute any
2454          instruction until the child is out of the shared region (such
2455          are vfork's semantics), it is safe to simply continue it.
2456          Eventually, we'll see a TARGET_WAITKIND_VFORK_DONE event for
2457          the parent, and tell it to `keep_going', which automatically
2458          re-sets it stepping.  */
2459       if (debug_infrun)
2460         fprintf_unfiltered (gdb_stdlog,
2461                             "infrun: resume : clear step\n");
2462       step = 0;
2463     }
2464
2465   if (debug_infrun)
2466     fprintf_unfiltered (gdb_stdlog,
2467                         "infrun: resume (step=%d, signal=%s), "
2468                         "trap_expected=%d, current thread [%s] at %s\n",
2469                         step, gdb_signal_to_symbol_string (sig),
2470                         tp->control.trap_expected,
2471                         target_pid_to_str (inferior_ptid),
2472                         paddress (gdbarch, pc));
2473
2474   /* Normally, by the time we reach `resume', the breakpoints are either
2475      removed or inserted, as appropriate.  The exception is if we're sitting
2476      at a permanent breakpoint; we need to step over it, but permanent
2477      breakpoints can't be removed.  So we have to test for it here.  */
2478   if (breakpoint_here_p (aspace, pc) == permanent_breakpoint_here)
2479     {
2480       if (sig != GDB_SIGNAL_0)
2481         {
2482           /* We have a signal to pass to the inferior.  The resume
2483              may, or may not take us to the signal handler.  If this
2484              is a step, we'll need to stop in the signal handler, if
2485              there's one, (if the target supports stepping into
2486              handlers), or in the next mainline instruction, if
2487              there's no handler.  If this is a continue, we need to be
2488              sure to run the handler with all breakpoints inserted.
2489              In all cases, set a breakpoint at the current address
2490              (where the handler returns to), and once that breakpoint
2491              is hit, resume skipping the permanent breakpoint.  If
2492              that breakpoint isn't hit, then we've stepped into the
2493              signal handler (or hit some other event).  We'll delete
2494              the step-resume breakpoint then.  */
2495
2496           if (debug_infrun)
2497             fprintf_unfiltered (gdb_stdlog,
2498                                 "infrun: resume: skipping permanent breakpoint, "
2499                                 "deliver signal first\n");
2500
2501           clear_step_over_info ();
2502           tp->control.trap_expected = 0;
2503
2504           if (tp->control.step_resume_breakpoint == NULL)
2505             {
2506               /* Set a "high-priority" step-resume, as we don't want
2507                  user breakpoints at PC to trigger (again) when this
2508                  hits.  */
2509               insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
2510               gdb_assert (tp->control.step_resume_breakpoint->loc->permanent);
2511
2512               tp->step_after_step_resume_breakpoint = step;
2513             }
2514
2515           insert_breakpoints ();
2516         }
2517       else
2518         {
2519           /* There's no signal to pass, we can go ahead and skip the
2520              permanent breakpoint manually.  */
2521           if (debug_infrun)
2522             fprintf_unfiltered (gdb_stdlog,
2523                                 "infrun: resume: skipping permanent breakpoint\n");
2524           gdbarch_skip_permanent_breakpoint (gdbarch, regcache);
2525           /* Update pc to reflect the new address from which we will
2526              execute instructions.  */
2527           pc = regcache_read_pc (regcache);
2528
2529           if (step)
2530             {
2531               /* We've already advanced the PC, so the stepping part
2532                  is done.  Now we need to arrange for a trap to be
2533                  reported to handle_inferior_event.  Set a breakpoint
2534                  at the current PC, and run to it.  Don't update
2535                  prev_pc, because if we end in
2536                  switch_back_to_stepped_thread, we want the "expected
2537                  thread advanced also" branch to be taken.  IOW, we
2538                  don't want this thread to step further from PC
2539                  (overstep).  */
2540               gdb_assert (!step_over_info_valid_p ());
2541               insert_single_step_breakpoint (gdbarch, aspace, pc);
2542               insert_breakpoints ();
2543
2544               resume_ptid = internal_resume_ptid (user_step);
2545               do_target_resume (resume_ptid, 0, GDB_SIGNAL_0);
2546               discard_cleanups (old_cleanups);
2547               tp->resumed = 1;
2548               return;
2549             }
2550         }
2551     }
2552
2553   /* If we have a breakpoint to step over, make sure to do a single
2554      step only.  Same if we have software watchpoints.  */
2555   if (tp->control.trap_expected || bpstat_should_step ())
2556     tp->control.may_range_step = 0;
2557
2558   /* If enabled, step over breakpoints by executing a copy of the
2559      instruction at a different address.
2560
2561      We can't use displaced stepping when we have a signal to deliver;
2562      the comments for displaced_step_prepare explain why.  The
2563      comments in the handle_inferior event for dealing with 'random
2564      signals' explain what we do instead.
2565
2566      We can't use displaced stepping when we are waiting for vfork_done
2567      event, displaced stepping breaks the vfork child similarly as single
2568      step software breakpoint.  */
2569   if (tp->control.trap_expected
2570       && use_displaced_stepping (tp)
2571       && !step_over_info_valid_p ()
2572       && sig == GDB_SIGNAL_0
2573       && !current_inferior ()->waiting_for_vfork_done)
2574     {
2575       int prepared = displaced_step_prepare (inferior_ptid);
2576
2577       if (prepared == 0)
2578         {
2579           if (debug_infrun)
2580             fprintf_unfiltered (gdb_stdlog,
2581                                 "Got placed in step-over queue\n");
2582
2583           tp->control.trap_expected = 0;
2584           discard_cleanups (old_cleanups);
2585           return;
2586         }
2587       else if (prepared < 0)
2588         {
2589           /* Fallback to stepping over the breakpoint in-line.  */
2590
2591           if (target_is_non_stop_p ())
2592             stop_all_threads ();
2593
2594           set_step_over_info (regcache->aspace (),
2595                               regcache_read_pc (regcache), 0, tp->global_num);
2596
2597           step = maybe_software_singlestep (gdbarch, pc);
2598
2599           insert_breakpoints ();
2600         }
2601       else if (prepared > 0)
2602         {
2603           struct displaced_step_inferior_state *displaced;
2604
2605           /* Update pc to reflect the new address from which we will
2606              execute instructions due to displaced stepping.  */
2607           pc = regcache_read_pc (get_thread_regcache (inferior_ptid));
2608
2609           displaced = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
2610           step = gdbarch_displaced_step_hw_singlestep (gdbarch,
2611                                                        displaced->step_closure);
2612         }
2613     }
2614
2615   /* Do we need to do it the hard way, w/temp breakpoints?  */
2616   else if (step)
2617     step = maybe_software_singlestep (gdbarch, pc);
2618
2619   /* Currently, our software single-step implementation leads to different
2620      results than hardware single-stepping in one situation: when stepping
2621      into delivering a signal which has an associated signal handler,
2622      hardware single-step will stop at the first instruction of the handler,
2623      while software single-step will simply skip execution of the handler.
2624
2625      For now, this difference in behavior is accepted since there is no
2626      easy way to actually implement single-stepping into a signal handler
2627      without kernel support.
2628
2629      However, there is one scenario where this difference leads to follow-on
2630      problems: if we're stepping off a breakpoint by removing all breakpoints
2631      and then single-stepping.  In this case, the software single-step
2632      behavior means that even if there is a *breakpoint* in the signal
2633      handler, GDB still would not stop.
2634
2635      Fortunately, we can at least fix this particular issue.  We detect
2636      here the case where we are about to deliver a signal while software
2637      single-stepping with breakpoints removed.  In this situation, we
2638      revert the decisions to remove all breakpoints and insert single-
2639      step breakpoints, and instead we install a step-resume breakpoint
2640      at the current address, deliver the signal without stepping, and
2641      once we arrive back at the step-resume breakpoint, actually step
2642      over the breakpoint we originally wanted to step over.  */
2643   if (thread_has_single_step_breakpoints_set (tp)
2644       && sig != GDB_SIGNAL_0
2645       && step_over_info_valid_p ())
2646     {
2647       /* If we have nested signals or a pending signal is delivered
2648          immediately after a handler returns, might might already have
2649          a step-resume breakpoint set on the earlier handler.  We cannot
2650          set another step-resume breakpoint; just continue on until the
2651          original breakpoint is hit.  */
2652       if (tp->control.step_resume_breakpoint == NULL)
2653         {
2654           insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
2655           tp->step_after_step_resume_breakpoint = 1;
2656         }
2657
2658       delete_single_step_breakpoints (tp);
2659
2660       clear_step_over_info ();
2661       tp->control.trap_expected = 0;
2662
2663       insert_breakpoints ();
2664     }
2665
2666   /* If STEP is set, it's a request to use hardware stepping
2667      facilities.  But in that case, we should never
2668      use singlestep breakpoint.  */
2669   gdb_assert (!(thread_has_single_step_breakpoints_set (tp) && step));
2670
2671   /* Decide the set of threads to ask the target to resume.  */
2672   if (tp->control.trap_expected)
2673     {
2674       /* We're allowing a thread to run past a breakpoint it has
2675          hit, either by single-stepping the thread with the breakpoint
2676          removed, or by displaced stepping, with the breakpoint inserted.
2677          In the former case, we need to single-step only this thread,
2678          and keep others stopped, as they can miss this breakpoint if
2679          allowed to run.  That's not really a problem for displaced
2680          stepping, but, we still keep other threads stopped, in case
2681          another thread is also stopped for a breakpoint waiting for
2682          its turn in the displaced stepping queue.  */
2683       resume_ptid = inferior_ptid;
2684     }
2685   else
2686     resume_ptid = internal_resume_ptid (user_step);
2687
2688   if (execution_direction != EXEC_REVERSE
2689       && step && breakpoint_inserted_here_p (aspace, pc))
2690     {
2691       /* There are two cases where we currently need to step a
2692          breakpoint instruction when we have a signal to deliver:
2693
2694          - See handle_signal_stop where we handle random signals that
2695          could take out us out of the stepping range.  Normally, in
2696          that case we end up continuing (instead of stepping) over the
2697          signal handler with a breakpoint at PC, but there are cases
2698          where we should _always_ single-step, even if we have a
2699          step-resume breakpoint, like when a software watchpoint is
2700          set.  Assuming single-stepping and delivering a signal at the
2701          same time would takes us to the signal handler, then we could
2702          have removed the breakpoint at PC to step over it.  However,
2703          some hardware step targets (like e.g., Mac OS) can't step
2704          into signal handlers, and for those, we need to leave the
2705          breakpoint at PC inserted, as otherwise if the handler
2706          recurses and executes PC again, it'll miss the breakpoint.
2707          So we leave the breakpoint inserted anyway, but we need to
2708          record that we tried to step a breakpoint instruction, so
2709          that adjust_pc_after_break doesn't end up confused.
2710
2711          - In non-stop if we insert a breakpoint (e.g., a step-resume)
2712          in one thread after another thread that was stepping had been
2713          momentarily paused for a step-over.  When we re-resume the
2714          stepping thread, it may be resumed from that address with a
2715          breakpoint that hasn't trapped yet.  Seen with
2716          gdb.threads/non-stop-fair-events.exp, on targets that don't
2717          do displaced stepping.  */
2718
2719       if (debug_infrun)
2720         fprintf_unfiltered (gdb_stdlog,
2721                             "infrun: resume: [%s] stepped breakpoint\n",
2722                             target_pid_to_str (tp->ptid));
2723
2724       tp->stepped_breakpoint = 1;
2725
2726       /* Most targets can step a breakpoint instruction, thus
2727          executing it normally.  But if this one cannot, just
2728          continue and we will hit it anyway.  */
2729       if (gdbarch_cannot_step_breakpoint (gdbarch))
2730         step = 0;
2731     }
2732
2733   if (debug_displaced
2734       && tp->control.trap_expected
2735       && use_displaced_stepping (tp)
2736       && !step_over_info_valid_p ())
2737     {
2738       struct regcache *resume_regcache = get_thread_regcache (tp->ptid);
2739       struct gdbarch *resume_gdbarch = resume_regcache->arch ();
2740       CORE_ADDR actual_pc = regcache_read_pc (resume_regcache);
2741       gdb_byte buf[4];
2742
2743       fprintf_unfiltered (gdb_stdlog, "displaced: run %s: ",
2744                           paddress (resume_gdbarch, actual_pc));
2745       read_memory (actual_pc, buf, sizeof (buf));
2746       displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
2747     }
2748
2749   if (tp->control.may_range_step)
2750     {
2751       /* If we're resuming a thread with the PC out of the step
2752          range, then we're doing some nested/finer run control
2753          operation, like stepping the thread out of the dynamic
2754          linker or the displaced stepping scratch pad.  We
2755          shouldn't have allowed a range step then.  */
2756       gdb_assert (pc_in_thread_step_range (pc, tp));
2757     }
2758
2759   do_target_resume (resume_ptid, step, sig);
2760   tp->resumed = 1;
2761   discard_cleanups (old_cleanups);
2762 }
2763 \f
2764 /* Proceeding.  */
2765
2766 /* See infrun.h.  */
2767
2768 /* Counter that tracks number of user visible stops.  This can be used
2769    to tell whether a command has proceeded the inferior past the
2770    current location.  This allows e.g., inferior function calls in
2771    breakpoint commands to not interrupt the command list.  When the
2772    call finishes successfully, the inferior is standing at the same
2773    breakpoint as if nothing happened (and so we don't call
2774    normal_stop).  */
2775 static ULONGEST current_stop_id;
2776
2777 /* See infrun.h.  */
2778
2779 ULONGEST
2780 get_stop_id (void)
2781 {
2782   return current_stop_id;
2783 }
2784
2785 /* Called when we report a user visible stop.  */
2786
2787 static void
2788 new_stop_id (void)
2789 {
2790   current_stop_id++;
2791 }
2792
2793 /* Clear out all variables saying what to do when inferior is continued.
2794    First do this, then set the ones you want, then call `proceed'.  */
2795
2796 static void
2797 clear_proceed_status_thread (struct thread_info *tp)
2798 {
2799   if (debug_infrun)
2800     fprintf_unfiltered (gdb_stdlog,
2801                         "infrun: clear_proceed_status_thread (%s)\n",
2802                         target_pid_to_str (tp->ptid));
2803
2804   /* If we're starting a new sequence, then the previous finished
2805      single-step is no longer relevant.  */
2806   if (tp->suspend.waitstatus_pending_p)
2807     {
2808       if (tp->suspend.stop_reason == TARGET_STOPPED_BY_SINGLE_STEP)
2809         {
2810           if (debug_infrun)
2811             fprintf_unfiltered (gdb_stdlog,
2812                                 "infrun: clear_proceed_status: pending "
2813                                 "event of %s was a finished step. "
2814                                 "Discarding.\n",
2815                                 target_pid_to_str (tp->ptid));
2816
2817           tp->suspend.waitstatus_pending_p = 0;
2818           tp->suspend.stop_reason = TARGET_STOPPED_BY_NO_REASON;
2819         }
2820       else if (debug_infrun)
2821         {
2822           std::string statstr
2823             = target_waitstatus_to_string (&tp->suspend.waitstatus);
2824
2825           fprintf_unfiltered (gdb_stdlog,
2826                               "infrun: clear_proceed_status_thread: thread %s "
2827                               "has pending wait status %s "
2828                               "(currently_stepping=%d).\n",
2829                               target_pid_to_str (tp->ptid), statstr.c_str (),
2830                               currently_stepping (tp));
2831         }
2832     }
2833
2834   /* If this signal should not be seen by program, give it zero.
2835      Used for debugging signals.  */
2836   if (!signal_pass_state (tp->suspend.stop_signal))
2837     tp->suspend.stop_signal = GDB_SIGNAL_0;
2838
2839   thread_fsm_delete (tp->thread_fsm);
2840   tp->thread_fsm = NULL;
2841
2842   tp->control.trap_expected = 0;
2843   tp->control.step_range_start = 0;
2844   tp->control.step_range_end = 0;
2845   tp->control.may_range_step = 0;
2846   tp->control.step_frame_id = null_frame_id;
2847   tp->control.step_stack_frame_id = null_frame_id;
2848   tp->control.step_over_calls = STEP_OVER_UNDEBUGGABLE;
2849   tp->control.step_start_function = NULL;
2850   tp->stop_requested = 0;
2851
2852   tp->control.stop_step = 0;
2853
2854   tp->control.proceed_to_finish = 0;
2855
2856   tp->control.stepping_command = 0;
2857
2858   /* Discard any remaining commands or status from previous stop.  */
2859   bpstat_clear (&tp->control.stop_bpstat);
2860 }
2861
2862 void
2863 clear_proceed_status (int step)
2864 {
2865   /* With scheduler-locking replay, stop replaying other threads if we're
2866      not replaying the user-visible resume ptid.
2867
2868      This is a convenience feature to not require the user to explicitly
2869      stop replaying the other threads.  We're assuming that the user's
2870      intent is to resume tracing the recorded process.  */
2871   if (!non_stop && scheduler_mode == schedlock_replay
2872       && target_record_is_replaying (minus_one_ptid)
2873       && !target_record_will_replay (user_visible_resume_ptid (step),
2874                                      execution_direction))
2875     target_record_stop_replaying ();
2876
2877   if (!non_stop)
2878     {
2879       struct thread_info *tp;
2880       ptid_t resume_ptid;
2881
2882       resume_ptid = user_visible_resume_ptid (step);
2883
2884       /* In all-stop mode, delete the per-thread status of all threads
2885          we're about to resume, implicitly and explicitly.  */
2886       ALL_NON_EXITED_THREADS (tp)
2887         {
2888           if (!ptid_match (tp->ptid, resume_ptid))
2889             continue;
2890           clear_proceed_status_thread (tp);
2891         }
2892     }
2893
2894   if (!ptid_equal (inferior_ptid, null_ptid))
2895     {
2896       struct inferior *inferior;
2897
2898       if (non_stop)
2899         {
2900           /* If in non-stop mode, only delete the per-thread status of
2901              the current thread.  */
2902           clear_proceed_status_thread (inferior_thread ());
2903         }
2904
2905       inferior = current_inferior ();
2906       inferior->control.stop_soon = NO_STOP_QUIETLY;
2907     }
2908
2909   observer_notify_about_to_proceed ();
2910 }
2911
2912 /* Returns true if TP is still stopped at a breakpoint that needs
2913    stepping-over in order to make progress.  If the breakpoint is gone
2914    meanwhile, we can skip the whole step-over dance.  */
2915
2916 static int
2917 thread_still_needs_step_over_bp (struct thread_info *tp)
2918 {
2919   if (tp->stepping_over_breakpoint)
2920     {
2921       struct regcache *regcache = get_thread_regcache (tp->ptid);
2922
2923       if (breakpoint_here_p (regcache->aspace (),
2924                              regcache_read_pc (regcache))
2925           == ordinary_breakpoint_here)
2926         return 1;
2927
2928       tp->stepping_over_breakpoint = 0;
2929     }
2930
2931   return 0;
2932 }
2933
2934 /* Check whether thread TP still needs to start a step-over in order
2935    to make progress when resumed.  Returns an bitwise or of enum
2936    step_over_what bits, indicating what needs to be stepped over.  */
2937
2938 static step_over_what
2939 thread_still_needs_step_over (struct thread_info *tp)
2940 {
2941   step_over_what what = 0;
2942
2943   if (thread_still_needs_step_over_bp (tp))
2944     what |= STEP_OVER_BREAKPOINT;
2945
2946   if (tp->stepping_over_watchpoint
2947       && !target_have_steppable_watchpoint)
2948     what |= STEP_OVER_WATCHPOINT;
2949
2950   return what;
2951 }
2952
2953 /* Returns true if scheduler locking applies.  STEP indicates whether
2954    we're about to do a step/next-like command to a thread.  */
2955
2956 static int
2957 schedlock_applies (struct thread_info *tp)
2958 {
2959   return (scheduler_mode == schedlock_on
2960           || (scheduler_mode == schedlock_step
2961               && tp->control.stepping_command)
2962           || (scheduler_mode == schedlock_replay
2963               && target_record_will_replay (minus_one_ptid,
2964                                             execution_direction)));
2965 }
2966
2967 /* Basic routine for continuing the program in various fashions.
2968
2969    ADDR is the address to resume at, or -1 for resume where stopped.
2970    SIGGNAL is the signal to give it, or 0 for none,
2971    or -1 for act according to how it stopped.
2972    STEP is nonzero if should trap after one instruction.
2973    -1 means return after that and print nothing.
2974    You should probably set various step_... variables
2975    before calling here, if you are stepping.
2976
2977    You should call clear_proceed_status before calling proceed.  */
2978
2979 void
2980 proceed (CORE_ADDR addr, enum gdb_signal siggnal)
2981 {
2982   struct regcache *regcache;
2983   struct gdbarch *gdbarch;
2984   struct thread_info *tp;
2985   CORE_ADDR pc;
2986   ptid_t resume_ptid;
2987   struct execution_control_state ecss;
2988   struct execution_control_state *ecs = &ecss;
2989   struct cleanup *old_chain;
2990   int started;
2991
2992   /* If we're stopped at a fork/vfork, follow the branch set by the
2993      "set follow-fork-mode" command; otherwise, we'll just proceed
2994      resuming the current thread.  */
2995   if (!follow_fork ())
2996     {
2997       /* The target for some reason decided not to resume.  */
2998       normal_stop ();
2999       if (target_can_async_p ())
3000         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
3001       return;
3002     }
3003
3004   /* We'll update this if & when we switch to a new thread.  */
3005   previous_inferior_ptid = inferior_ptid;
3006
3007   regcache = get_current_regcache ();
3008   gdbarch = regcache->arch ();
3009   const address_space *aspace = regcache->aspace ();
3010
3011   pc = regcache_read_pc (regcache);
3012   tp = inferior_thread ();
3013
3014   /* Fill in with reasonable starting values.  */
3015   init_thread_stepping_state (tp);
3016
3017   gdb_assert (!thread_is_in_step_over_chain (tp));
3018
3019   if (addr == (CORE_ADDR) -1)
3020     {
3021       if (pc == stop_pc
3022           && breakpoint_here_p (aspace, pc) == ordinary_breakpoint_here
3023           && execution_direction != EXEC_REVERSE)
3024         /* There is a breakpoint at the address we will resume at,
3025            step one instruction before inserting breakpoints so that
3026            we do not stop right away (and report a second hit at this
3027            breakpoint).
3028
3029            Note, we don't do this in reverse, because we won't
3030            actually be executing the breakpoint insn anyway.
3031            We'll be (un-)executing the previous instruction.  */
3032         tp->stepping_over_breakpoint = 1;
3033       else if (gdbarch_single_step_through_delay_p (gdbarch)
3034                && gdbarch_single_step_through_delay (gdbarch,
3035                                                      get_current_frame ()))
3036         /* We stepped onto an instruction that needs to be stepped
3037            again before re-inserting the breakpoint, do so.  */
3038         tp->stepping_over_breakpoint = 1;
3039     }
3040   else
3041     {
3042       regcache_write_pc (regcache, addr);
3043     }
3044
3045   if (siggnal != GDB_SIGNAL_DEFAULT)
3046     tp->suspend.stop_signal = siggnal;
3047
3048   resume_ptid = user_visible_resume_ptid (tp->control.stepping_command);
3049
3050   /* If an exception is thrown from this point on, make sure to
3051      propagate GDB's knowledge of the executing state to the
3052      frontend/user running state.  */
3053   old_chain = make_cleanup (finish_thread_state_cleanup, &resume_ptid);
3054
3055   /* Even if RESUME_PTID is a wildcard, and we end up resuming fewer
3056      threads (e.g., we might need to set threads stepping over
3057      breakpoints first), from the user/frontend's point of view, all
3058      threads in RESUME_PTID are now running.  Unless we're calling an
3059      inferior function, as in that case we pretend the inferior
3060      doesn't run at all.  */
3061   if (!tp->control.in_infcall)
3062    set_running (resume_ptid, 1);
3063
3064   if (debug_infrun)
3065     fprintf_unfiltered (gdb_stdlog,
3066                         "infrun: proceed (addr=%s, signal=%s)\n",
3067                         paddress (gdbarch, addr),
3068                         gdb_signal_to_symbol_string (siggnal));
3069
3070   annotate_starting ();
3071
3072   /* Make sure that output from GDB appears before output from the
3073      inferior.  */
3074   gdb_flush (gdb_stdout);
3075
3076   /* In a multi-threaded task we may select another thread and
3077      then continue or step.
3078
3079      But if a thread that we're resuming had stopped at a breakpoint,
3080      it will immediately cause another breakpoint stop without any
3081      execution (i.e. it will report a breakpoint hit incorrectly).  So
3082      we must step over it first.
3083
3084      Look for threads other than the current (TP) that reported a
3085      breakpoint hit and haven't been resumed yet since.  */
3086
3087   /* If scheduler locking applies, we can avoid iterating over all
3088      threads.  */
3089   if (!non_stop && !schedlock_applies (tp))
3090     {
3091       struct thread_info *current = tp;
3092
3093       ALL_NON_EXITED_THREADS (tp)
3094         {
3095           /* Ignore the current thread here.  It's handled
3096              afterwards.  */
3097           if (tp == current)
3098             continue;
3099
3100           /* Ignore threads of processes we're not resuming.  */
3101           if (!ptid_match (tp->ptid, resume_ptid))
3102             continue;
3103
3104           if (!thread_still_needs_step_over (tp))
3105             continue;
3106
3107           gdb_assert (!thread_is_in_step_over_chain (tp));
3108
3109           if (debug_infrun)
3110             fprintf_unfiltered (gdb_stdlog,
3111                                 "infrun: need to step-over [%s] first\n",
3112                                 target_pid_to_str (tp->ptid));
3113
3114           thread_step_over_chain_enqueue (tp);
3115         }
3116
3117       tp = current;
3118     }
3119
3120   /* Enqueue the current thread last, so that we move all other
3121      threads over their breakpoints first.  */
3122   if (tp->stepping_over_breakpoint)
3123     thread_step_over_chain_enqueue (tp);
3124
3125   /* If the thread isn't started, we'll still need to set its prev_pc,
3126      so that switch_back_to_stepped_thread knows the thread hasn't
3127      advanced.  Must do this before resuming any thread, as in
3128      all-stop/remote, once we resume we can't send any other packet
3129      until the target stops again.  */
3130   tp->prev_pc = regcache_read_pc (regcache);
3131
3132   {
3133     scoped_restore save_defer_tc = make_scoped_defer_target_commit_resume ();
3134
3135     started = start_step_over ();
3136
3137     if (step_over_info_valid_p ())
3138       {
3139         /* Either this thread started a new in-line step over, or some
3140            other thread was already doing one.  In either case, don't
3141            resume anything else until the step-over is finished.  */
3142       }
3143     else if (started && !target_is_non_stop_p ())
3144       {
3145         /* A new displaced stepping sequence was started.  In all-stop,
3146            we can't talk to the target anymore until it next stops.  */
3147       }
3148     else if (!non_stop && target_is_non_stop_p ())
3149       {
3150         /* In all-stop, but the target is always in non-stop mode.
3151            Start all other threads that are implicitly resumed too.  */
3152         ALL_NON_EXITED_THREADS (tp)
3153         {
3154           /* Ignore threads of processes we're not resuming.  */
3155           if (!ptid_match (tp->ptid, resume_ptid))
3156             continue;
3157
3158           if (tp->resumed)
3159             {
3160               if (debug_infrun)
3161                 fprintf_unfiltered (gdb_stdlog,
3162                                     "infrun: proceed: [%s] resumed\n",
3163                                     target_pid_to_str (tp->ptid));
3164               gdb_assert (tp->executing || tp->suspend.waitstatus_pending_p);
3165               continue;
3166             }
3167
3168           if (thread_is_in_step_over_chain (tp))
3169             {
3170               if (debug_infrun)
3171                 fprintf_unfiltered (gdb_stdlog,
3172                                     "infrun: proceed: [%s] needs step-over\n",
3173                                     target_pid_to_str (tp->ptid));
3174               continue;
3175             }
3176
3177           if (debug_infrun)
3178             fprintf_unfiltered (gdb_stdlog,
3179                                 "infrun: proceed: resuming %s\n",
3180                                 target_pid_to_str (tp->ptid));
3181
3182           reset_ecs (ecs, tp);
3183           switch_to_thread (tp->ptid);
3184           keep_going_pass_signal (ecs);
3185           if (!ecs->wait_some_more)
3186             error (_("Command aborted."));
3187         }
3188       }
3189     else if (!tp->resumed && !thread_is_in_step_over_chain (tp))
3190       {
3191         /* The thread wasn't started, and isn't queued, run it now.  */
3192         reset_ecs (ecs, tp);
3193         switch_to_thread (tp->ptid);
3194         keep_going_pass_signal (ecs);
3195         if (!ecs->wait_some_more)
3196           error (_("Command aborted."));
3197       }
3198   }
3199
3200   target_commit_resume ();
3201
3202   discard_cleanups (old_chain);
3203
3204   /* Tell the event loop to wait for it to stop.  If the target
3205      supports asynchronous execution, it'll do this from within
3206      target_resume.  */
3207   if (!target_can_async_p ())
3208     mark_async_event_handler (infrun_async_inferior_event_token);
3209 }
3210 \f
3211
3212 /* Start remote-debugging of a machine over a serial link.  */
3213
3214 void
3215 start_remote (int from_tty)
3216 {
3217   struct inferior *inferior;
3218
3219   inferior = current_inferior ();
3220   inferior->control.stop_soon = STOP_QUIETLY_REMOTE;
3221
3222   /* Always go on waiting for the target, regardless of the mode.  */
3223   /* FIXME: cagney/1999-09-23: At present it isn't possible to
3224      indicate to wait_for_inferior that a target should timeout if
3225      nothing is returned (instead of just blocking).  Because of this,
3226      targets expecting an immediate response need to, internally, set
3227      things up so that the target_wait() is forced to eventually
3228      timeout.  */
3229   /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
3230      differentiate to its caller what the state of the target is after
3231      the initial open has been performed.  Here we're assuming that
3232      the target has stopped.  It should be possible to eventually have
3233      target_open() return to the caller an indication that the target
3234      is currently running and GDB state should be set to the same as
3235      for an async run.  */
3236   wait_for_inferior ();
3237
3238   /* Now that the inferior has stopped, do any bookkeeping like
3239      loading shared libraries.  We want to do this before normal_stop,
3240      so that the displayed frame is up to date.  */
3241   post_create_inferior (&current_target, from_tty);
3242
3243   normal_stop ();
3244 }
3245
3246 /* Initialize static vars when a new inferior begins.  */
3247
3248 void
3249 init_wait_for_inferior (void)
3250 {
3251   /* These are meaningless until the first time through wait_for_inferior.  */
3252
3253   breakpoint_init_inferior (inf_starting);
3254
3255   clear_proceed_status (0);
3256
3257   target_last_wait_ptid = minus_one_ptid;
3258
3259   previous_inferior_ptid = inferior_ptid;
3260
3261   /* Discard any skipped inlined frames.  */
3262   clear_inline_frame_state (minus_one_ptid);
3263 }
3264
3265 \f
3266
3267 static void handle_inferior_event (struct execution_control_state *ecs);
3268
3269 static void handle_step_into_function (struct gdbarch *gdbarch,
3270                                        struct execution_control_state *ecs);
3271 static void handle_step_into_function_backward (struct gdbarch *gdbarch,
3272                                                 struct execution_control_state *ecs);
3273 static void handle_signal_stop (struct execution_control_state *ecs);
3274 static void check_exception_resume (struct execution_control_state *,
3275                                     struct frame_info *);
3276
3277 static void end_stepping_range (struct execution_control_state *ecs);
3278 static void stop_waiting (struct execution_control_state *ecs);
3279 static void keep_going (struct execution_control_state *ecs);
3280 static void process_event_stop_test (struct execution_control_state *ecs);
3281 static int switch_back_to_stepped_thread (struct execution_control_state *ecs);
3282
3283 /* This function is attached as a "thread_stop_requested" observer.
3284    Cleanup local state that assumed the PTID was to be resumed, and
3285    report the stop to the frontend.  */
3286
3287 static void
3288 infrun_thread_stop_requested (ptid_t ptid)
3289 {
3290   struct thread_info *tp;
3291
3292   /* PTID was requested to stop.  If the thread was already stopped,
3293      but the user/frontend doesn't know about that yet (e.g., the
3294      thread had been temporarily paused for some step-over), set up
3295      for reporting the stop now.  */
3296   ALL_NON_EXITED_THREADS (tp)
3297     if (ptid_match (tp->ptid, ptid))
3298       {
3299         if (tp->state != THREAD_RUNNING)
3300           continue;
3301         if (tp->executing)
3302           continue;
3303
3304         /* Remove matching threads from the step-over queue, so
3305            start_step_over doesn't try to resume them
3306            automatically.  */
3307         if (thread_is_in_step_over_chain (tp))
3308           thread_step_over_chain_remove (tp);
3309
3310         /* If the thread is stopped, but the user/frontend doesn't
3311            know about that yet, queue a pending event, as if the
3312            thread had just stopped now.  Unless the thread already had
3313            a pending event.  */
3314         if (!tp->suspend.waitstatus_pending_p)
3315           {
3316             tp->suspend.waitstatus_pending_p = 1;
3317             tp->suspend.waitstatus.kind = TARGET_WAITKIND_STOPPED;
3318             tp->suspend.waitstatus.value.sig = GDB_SIGNAL_0;
3319           }
3320
3321         /* Clear the inline-frame state, since we're re-processing the
3322            stop.  */
3323         clear_inline_frame_state (tp->ptid);
3324
3325         /* If this thread was paused because some other thread was
3326            doing an inline-step over, let that finish first.  Once
3327            that happens, we'll restart all threads and consume pending
3328            stop events then.  */
3329         if (step_over_info_valid_p ())
3330           continue;
3331
3332         /* Otherwise we can process the (new) pending event now.  Set
3333            it so this pending event is considered by
3334            do_target_wait.  */
3335         tp->resumed = 1;
3336       }
3337 }
3338
3339 static void
3340 infrun_thread_thread_exit (struct thread_info *tp, int silent)
3341 {
3342   if (ptid_equal (target_last_wait_ptid, tp->ptid))
3343     nullify_last_target_wait_ptid ();
3344 }
3345
3346 /* Delete the step resume, single-step and longjmp/exception resume
3347    breakpoints of TP.  */
3348
3349 static void
3350 delete_thread_infrun_breakpoints (struct thread_info *tp)
3351 {
3352   delete_step_resume_breakpoint (tp);
3353   delete_exception_resume_breakpoint (tp);
3354   delete_single_step_breakpoints (tp);
3355 }
3356
3357 /* If the target still has execution, call FUNC for each thread that
3358    just stopped.  In all-stop, that's all the non-exited threads; in
3359    non-stop, that's the current thread, only.  */
3360
3361 typedef void (*for_each_just_stopped_thread_callback_func)
3362   (struct thread_info *tp);
3363
3364 static void
3365 for_each_just_stopped_thread (for_each_just_stopped_thread_callback_func func)
3366 {
3367   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
3368     return;
3369
3370   if (target_is_non_stop_p ())
3371     {
3372       /* If in non-stop mode, only the current thread stopped.  */
3373       func (inferior_thread ());
3374     }
3375   else
3376     {
3377       struct thread_info *tp;
3378
3379       /* In all-stop mode, all threads have stopped.  */
3380       ALL_NON_EXITED_THREADS (tp)
3381         {
3382           func (tp);
3383         }
3384     }
3385 }
3386
3387 /* Delete the step resume and longjmp/exception resume breakpoints of
3388    the threads that just stopped.  */
3389
3390 static void
3391 delete_just_stopped_threads_infrun_breakpoints (void)
3392 {
3393   for_each_just_stopped_thread (delete_thread_infrun_breakpoints);
3394 }
3395
3396 /* Delete the single-step breakpoints of the threads that just
3397    stopped.  */
3398
3399 static void
3400 delete_just_stopped_threads_single_step_breakpoints (void)
3401 {
3402   for_each_just_stopped_thread (delete_single_step_breakpoints);
3403 }
3404
3405 /* A cleanup wrapper.  */
3406
3407 static void
3408 delete_just_stopped_threads_infrun_breakpoints_cleanup (void *arg)
3409 {
3410   delete_just_stopped_threads_infrun_breakpoints ();
3411 }
3412
3413 /* See infrun.h.  */
3414
3415 void
3416 print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid,
3417                            const struct target_waitstatus *ws)
3418 {
3419   std::string status_string = target_waitstatus_to_string (ws);
3420   string_file stb;
3421
3422   /* The text is split over several lines because it was getting too long.
3423      Call fprintf_unfiltered (gdb_stdlog) once so that the text is still
3424      output as a unit; we want only one timestamp printed if debug_timestamp
3425      is set.  */
3426
3427   stb.printf ("infrun: target_wait (%d.%ld.%ld",
3428               ptid_get_pid (waiton_ptid),
3429               ptid_get_lwp (waiton_ptid),
3430               ptid_get_tid (waiton_ptid));
3431   if (ptid_get_pid (waiton_ptid) != -1)
3432     stb.printf (" [%s]", target_pid_to_str (waiton_ptid));
3433   stb.printf (", status) =\n");
3434   stb.printf ("infrun:   %d.%ld.%ld [%s],\n",
3435               ptid_get_pid (result_ptid),
3436               ptid_get_lwp (result_ptid),
3437               ptid_get_tid (result_ptid),
3438               target_pid_to_str (result_ptid));
3439   stb.printf ("infrun:   %s\n", status_string.c_str ());
3440
3441   /* This uses %s in part to handle %'s in the text, but also to avoid
3442      a gcc error: the format attribute requires a string literal.  */
3443   fprintf_unfiltered (gdb_stdlog, "%s", stb.c_str ());
3444 }
3445
3446 /* Select a thread at random, out of those which are resumed and have
3447    had events.  */
3448
3449 static struct thread_info *
3450 random_pending_event_thread (ptid_t waiton_ptid)
3451 {
3452   struct thread_info *event_tp;
3453   int num_events = 0;
3454   int random_selector;
3455
3456   /* First see how many events we have.  Count only resumed threads
3457      that have an event pending.  */
3458   ALL_NON_EXITED_THREADS (event_tp)
3459     if (ptid_match (event_tp->ptid, waiton_ptid)
3460         && event_tp->resumed
3461         && event_tp->suspend.waitstatus_pending_p)
3462       num_events++;
3463
3464   if (num_events == 0)
3465     return NULL;
3466
3467   /* Now randomly pick a thread out of those that have had events.  */
3468   random_selector = (int)
3469     ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
3470
3471   if (debug_infrun && num_events > 1)
3472     fprintf_unfiltered (gdb_stdlog,
3473                         "infrun: Found %d events, selecting #%d\n",
3474                         num_events, random_selector);
3475
3476   /* Select the Nth thread that has had an event.  */
3477   ALL_NON_EXITED_THREADS (event_tp)
3478     if (ptid_match (event_tp->ptid, waiton_ptid)
3479         && event_tp->resumed
3480         && event_tp->suspend.waitstatus_pending_p)
3481       if (random_selector-- == 0)
3482         break;
3483
3484   return event_tp;
3485 }
3486
3487 /* Wrapper for target_wait that first checks whether threads have
3488    pending statuses to report before actually asking the target for
3489    more events.  */
3490
3491 static ptid_t
3492 do_target_wait (ptid_t ptid, struct target_waitstatus *status, int options)
3493 {
3494   ptid_t event_ptid;
3495   struct thread_info *tp;
3496
3497   /* First check if there is a resumed thread with a wait status
3498      pending.  */
3499   if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
3500     {
3501       tp = random_pending_event_thread (ptid);
3502     }
3503   else
3504     {
3505       if (debug_infrun)
3506         fprintf_unfiltered (gdb_stdlog,
3507                             "infrun: Waiting for specific thread %s.\n",
3508                             target_pid_to_str (ptid));
3509
3510       /* We have a specific thread to check.  */
3511       tp = find_thread_ptid (ptid);
3512       gdb_assert (tp != NULL);
3513       if (!tp->suspend.waitstatus_pending_p)
3514         tp = NULL;
3515     }
3516
3517   if (tp != NULL
3518       && (tp->suspend.stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3519           || tp->suspend.stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT))
3520     {
3521       struct regcache *regcache = get_thread_regcache (tp->ptid);
3522       struct gdbarch *gdbarch = regcache->arch ();
3523       CORE_ADDR pc;
3524       int discard = 0;
3525
3526       pc = regcache_read_pc (regcache);
3527
3528       if (pc != tp->suspend.stop_pc)
3529         {
3530           if (debug_infrun)
3531             fprintf_unfiltered (gdb_stdlog,
3532                                 "infrun: PC of %s changed.  was=%s, now=%s\n",
3533                                 target_pid_to_str (tp->ptid),
3534                                 paddress (gdbarch, tp->prev_pc),
3535                                 paddress (gdbarch, pc));
3536           discard = 1;
3537         }
3538       else if (!breakpoint_inserted_here_p (regcache->aspace (), pc))
3539         {
3540           if (debug_infrun)
3541             fprintf_unfiltered (gdb_stdlog,
3542                                 "infrun: previous breakpoint of %s, at %s gone\n",
3543                                 target_pid_to_str (tp->ptid),
3544                                 paddress (gdbarch, pc));
3545
3546           discard = 1;
3547         }
3548
3549       if (discard)
3550         {
3551           if (debug_infrun)
3552             fprintf_unfiltered (gdb_stdlog,
3553                                 "infrun: pending event of %s cancelled.\n",
3554                                 target_pid_to_str (tp->ptid));
3555
3556           tp->suspend.waitstatus.kind = TARGET_WAITKIND_SPURIOUS;
3557           tp->suspend.stop_reason = TARGET_STOPPED_BY_NO_REASON;
3558         }
3559     }
3560
3561   if (tp != NULL)
3562     {
3563       if (debug_infrun)
3564         {
3565           std::string statstr
3566             = target_waitstatus_to_string (&tp->suspend.waitstatus);
3567
3568           fprintf_unfiltered (gdb_stdlog,
3569                               "infrun: Using pending wait status %s for %s.\n",
3570                               statstr.c_str (),
3571                               target_pid_to_str (tp->ptid));
3572         }
3573
3574       /* Now that we've selected our final event LWP, un-adjust its PC
3575          if it was a software breakpoint (and the target doesn't
3576          always adjust the PC itself).  */
3577       if (tp->suspend.stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3578           && !target_supports_stopped_by_sw_breakpoint ())
3579         {
3580           struct regcache *regcache;
3581           struct gdbarch *gdbarch;
3582           int decr_pc;
3583
3584           regcache = get_thread_regcache (tp->ptid);
3585           gdbarch = regcache->arch ();
3586
3587           decr_pc = gdbarch_decr_pc_after_break (gdbarch);
3588           if (decr_pc != 0)
3589             {
3590               CORE_ADDR pc;
3591
3592               pc = regcache_read_pc (regcache);
3593               regcache_write_pc (regcache, pc + decr_pc);
3594             }
3595         }
3596
3597       tp->suspend.stop_reason = TARGET_STOPPED_BY_NO_REASON;
3598       *status = tp->suspend.waitstatus;
3599       tp->suspend.waitstatus_pending_p = 0;
3600
3601       /* Wake up the event loop again, until all pending events are
3602          processed.  */
3603       if (target_is_async_p ())
3604         mark_async_event_handler (infrun_async_inferior_event_token);
3605       return tp->ptid;
3606     }
3607
3608   /* But if we don't find one, we'll have to wait.  */
3609
3610   if (deprecated_target_wait_hook)
3611     event_ptid = deprecated_target_wait_hook (ptid, status, options);
3612   else
3613     event_ptid = target_wait (ptid, status, options);
3614
3615   return event_ptid;
3616 }
3617
3618 /* Prepare and stabilize the inferior for detaching it.  E.g.,
3619    detaching while a thread is displaced stepping is a recipe for
3620    crashing it, as nothing would readjust the PC out of the scratch
3621    pad.  */
3622
3623 void
3624 prepare_for_detach (void)
3625 {
3626   struct inferior *inf = current_inferior ();
3627   ptid_t pid_ptid = pid_to_ptid (inf->pid);
3628   struct displaced_step_inferior_state *displaced;
3629
3630   displaced = get_displaced_stepping_state (inf->pid);
3631
3632   /* Is any thread of this process displaced stepping?  If not,
3633      there's nothing else to do.  */
3634   if (displaced == NULL || ptid_equal (displaced->step_ptid, null_ptid))
3635     return;
3636
3637   if (debug_infrun)
3638     fprintf_unfiltered (gdb_stdlog,
3639                         "displaced-stepping in-process while detaching");
3640
3641   scoped_restore restore_detaching = make_scoped_restore (&inf->detaching, true);
3642
3643   while (!ptid_equal (displaced->step_ptid, null_ptid))
3644     {
3645       struct cleanup *old_chain_2;
3646       struct execution_control_state ecss;
3647       struct execution_control_state *ecs;
3648
3649       ecs = &ecss;
3650       memset (ecs, 0, sizeof (*ecs));
3651
3652       overlay_cache_invalid = 1;
3653       /* Flush target cache before starting to handle each event.
3654          Target was running and cache could be stale.  This is just a
3655          heuristic.  Running threads may modify target memory, but we
3656          don't get any event.  */
3657       target_dcache_invalidate ();
3658
3659       ecs->ptid = do_target_wait (pid_ptid, &ecs->ws, 0);
3660
3661       if (debug_infrun)
3662         print_target_wait_results (pid_ptid, ecs->ptid, &ecs->ws);
3663
3664       /* If an error happens while handling the event, propagate GDB's
3665          knowledge of the executing state to the frontend/user running
3666          state.  */
3667       old_chain_2 = make_cleanup (finish_thread_state_cleanup,
3668                                   &minus_one_ptid);
3669
3670       /* Now figure out what to do with the result of the result.  */
3671       handle_inferior_event (ecs);
3672
3673       /* No error, don't finish the state yet.  */
3674       discard_cleanups (old_chain_2);
3675
3676       /* Breakpoints and watchpoints are not installed on the target
3677          at this point, and signals are passed directly to the
3678          inferior, so this must mean the process is gone.  */
3679       if (!ecs->wait_some_more)
3680         {
3681           restore_detaching.release ();
3682           error (_("Program exited while detaching"));
3683         }
3684     }
3685
3686   restore_detaching.release ();
3687 }
3688
3689 /* Wait for control to return from inferior to debugger.
3690
3691    If inferior gets a signal, we may decide to start it up again
3692    instead of returning.  That is why there is a loop in this function.
3693    When this function actually returns it means the inferior
3694    should be left stopped and GDB should read more commands.  */
3695
3696 void
3697 wait_for_inferior (void)
3698 {
3699   struct cleanup *old_cleanups;
3700   struct cleanup *thread_state_chain;
3701
3702   if (debug_infrun)
3703     fprintf_unfiltered
3704       (gdb_stdlog, "infrun: wait_for_inferior ()\n");
3705
3706   old_cleanups
3707     = make_cleanup (delete_just_stopped_threads_infrun_breakpoints_cleanup,
3708                     NULL);
3709
3710   /* If an error happens while handling the event, propagate GDB's
3711      knowledge of the executing state to the frontend/user running
3712      state.  */
3713   thread_state_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
3714
3715   while (1)
3716     {
3717       struct execution_control_state ecss;
3718       struct execution_control_state *ecs = &ecss;
3719       ptid_t waiton_ptid = minus_one_ptid;
3720
3721       memset (ecs, 0, sizeof (*ecs));
3722
3723       overlay_cache_invalid = 1;
3724
3725       /* Flush target cache before starting to handle each event.
3726          Target was running and cache could be stale.  This is just a
3727          heuristic.  Running threads may modify target memory, but we
3728          don't get any event.  */
3729       target_dcache_invalidate ();
3730
3731       ecs->ptid = do_target_wait (waiton_ptid, &ecs->ws, 0);
3732
3733       if (debug_infrun)
3734         print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
3735
3736       /* Now figure out what to do with the result of the result.  */
3737       handle_inferior_event (ecs);
3738
3739       if (!ecs->wait_some_more)
3740         break;
3741     }
3742
3743   /* No error, don't finish the state yet.  */
3744   discard_cleanups (thread_state_chain);
3745
3746   do_cleanups (old_cleanups);
3747 }
3748
3749 /* Cleanup that reinstalls the readline callback handler, if the
3750    target is running in the background.  If while handling the target
3751    event something triggered a secondary prompt, like e.g., a
3752    pagination prompt, we'll have removed the callback handler (see
3753    gdb_readline_wrapper_line).  Need to do this as we go back to the
3754    event loop, ready to process further input.  Note this has no
3755    effect if the handler hasn't actually been removed, because calling
3756    rl_callback_handler_install resets the line buffer, thus losing
3757    input.  */
3758
3759 static void
3760 reinstall_readline_callback_handler_cleanup (void *arg)
3761 {
3762   struct ui *ui = current_ui;
3763
3764   if (!ui->async)
3765     {
3766       /* We're not going back to the top level event loop yet.  Don't
3767          install the readline callback, as it'd prep the terminal,
3768          readline-style (raw, noecho) (e.g., --batch).  We'll install
3769          it the next time the prompt is displayed, when we're ready
3770          for input.  */
3771       return;
3772     }
3773
3774   if (ui->command_editing && ui->prompt_state != PROMPT_BLOCKED)
3775     gdb_rl_callback_handler_reinstall ();
3776 }
3777
3778 /* Clean up the FSMs of threads that are now stopped.  In non-stop,
3779    that's just the event thread.  In all-stop, that's all threads.  */
3780
3781 static void
3782 clean_up_just_stopped_threads_fsms (struct execution_control_state *ecs)
3783 {
3784   struct thread_info *thr = ecs->event_thread;
3785
3786   if (thr != NULL && thr->thread_fsm != NULL)
3787     thread_fsm_clean_up (thr->thread_fsm, thr);
3788
3789   if (!non_stop)
3790     {
3791       ALL_NON_EXITED_THREADS (thr)
3792         {
3793           if (thr->thread_fsm == NULL)
3794             continue;
3795           if (thr == ecs->event_thread)
3796             continue;
3797
3798           switch_to_thread (thr->ptid);
3799           thread_fsm_clean_up (thr->thread_fsm, thr);
3800         }
3801
3802       if (ecs->event_thread != NULL)
3803         switch_to_thread (ecs->event_thread->ptid);
3804     }
3805 }
3806
3807 /* Helper for all_uis_check_sync_execution_done that works on the
3808    current UI.  */
3809
3810 static void
3811 check_curr_ui_sync_execution_done (void)
3812 {
3813   struct ui *ui = current_ui;
3814
3815   if (ui->prompt_state == PROMPT_NEEDED
3816       && ui->async
3817       && !gdb_in_secondary_prompt_p (ui))
3818     {
3819       target_terminal::ours ();
3820       observer_notify_sync_execution_done ();
3821       ui_register_input_event_handler (ui);
3822     }
3823 }
3824
3825 /* See infrun.h.  */
3826
3827 void
3828 all_uis_check_sync_execution_done (void)
3829 {
3830   SWITCH_THRU_ALL_UIS ()
3831     {
3832       check_curr_ui_sync_execution_done ();
3833     }
3834 }
3835
3836 /* See infrun.h.  */
3837
3838 void
3839 all_uis_on_sync_execution_starting (void)
3840 {
3841   SWITCH_THRU_ALL_UIS ()
3842     {
3843       if (current_ui->prompt_state == PROMPT_NEEDED)
3844         async_disable_stdin ();
3845     }
3846 }
3847
3848 /* Asynchronous version of wait_for_inferior.  It is called by the
3849    event loop whenever a change of state is detected on the file
3850    descriptor corresponding to the target.  It can be called more than
3851    once to complete a single execution command.  In such cases we need
3852    to keep the state in a global variable ECSS.  If it is the last time
3853    that this function is called for a single execution command, then
3854    report to the user that the inferior has stopped, and do the
3855    necessary cleanups.  */
3856
3857 void
3858 fetch_inferior_event (void *client_data)
3859 {
3860   struct execution_control_state ecss;
3861   struct execution_control_state *ecs = &ecss;
3862   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
3863   struct cleanup *ts_old_chain;
3864   int cmd_done = 0;
3865   ptid_t waiton_ptid = minus_one_ptid;
3866
3867   memset (ecs, 0, sizeof (*ecs));
3868
3869   /* Events are always processed with the main UI as current UI.  This
3870      way, warnings, debug output, etc. are always consistently sent to
3871      the main console.  */
3872   scoped_restore save_ui = make_scoped_restore (&current_ui, main_ui);
3873
3874   /* End up with readline processing input, if necessary.  */
3875   make_cleanup (reinstall_readline_callback_handler_cleanup, NULL);
3876
3877   /* We're handling a live event, so make sure we're doing live
3878      debugging.  If we're looking at traceframes while the target is
3879      running, we're going to need to get back to that mode after
3880      handling the event.  */
3881   if (non_stop)
3882     {
3883       make_cleanup_restore_current_traceframe ();
3884       set_current_traceframe (-1);
3885     }
3886
3887   gdb::optional<scoped_restore_current_thread> maybe_restore_thread;
3888
3889   if (non_stop)
3890     /* In non-stop mode, the user/frontend should not notice a thread
3891        switch due to internal events.  Make sure we reverse to the
3892        user selected thread and frame after handling the event and
3893        running any breakpoint commands.  */
3894     maybe_restore_thread.emplace ();
3895
3896   overlay_cache_invalid = 1;
3897   /* Flush target cache before starting to handle each event.  Target
3898      was running and cache could be stale.  This is just a heuristic.
3899      Running threads may modify target memory, but we don't get any
3900      event.  */
3901   target_dcache_invalidate ();
3902
3903   scoped_restore save_exec_dir
3904     = make_scoped_restore (&execution_direction, target_execution_direction ());
3905
3906   ecs->ptid = do_target_wait (waiton_ptid, &ecs->ws,
3907                               target_can_async_p () ? TARGET_WNOHANG : 0);
3908
3909   if (debug_infrun)
3910     print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
3911
3912   /* If an error happens while handling the event, propagate GDB's
3913      knowledge of the executing state to the frontend/user running
3914      state.  */
3915   if (!target_is_non_stop_p ())
3916     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
3917   else
3918     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &ecs->ptid);
3919
3920   /* Get executed before make_cleanup_restore_current_thread above to apply
3921      still for the thread which has thrown the exception.  */
3922   make_bpstat_clear_actions_cleanup ();
3923
3924   make_cleanup (delete_just_stopped_threads_infrun_breakpoints_cleanup, NULL);
3925
3926   /* Now figure out what to do with the result of the result.  */
3927   handle_inferior_event (ecs);
3928
3929   if (!ecs->wait_some_more)
3930     {
3931       struct inferior *inf = find_inferior_ptid (ecs->ptid);
3932       int should_stop = 1;
3933       struct thread_info *thr = ecs->event_thread;
3934       int should_notify_stop = 1;
3935
3936       delete_just_stopped_threads_infrun_breakpoints ();
3937
3938       if (thr != NULL)
3939         {
3940           struct thread_fsm *thread_fsm = thr->thread_fsm;
3941
3942           if (thread_fsm != NULL)
3943             should_stop = thread_fsm_should_stop (thread_fsm, thr);
3944         }
3945
3946       if (!should_stop)
3947         {
3948           keep_going (ecs);
3949         }
3950       else
3951         {
3952           clean_up_just_stopped_threads_fsms (ecs);
3953
3954           if (thr != NULL && thr->thread_fsm != NULL)
3955             {
3956               should_notify_stop
3957                 = thread_fsm_should_notify_stop (thr->thread_fsm);
3958             }
3959
3960           if (should_notify_stop)
3961             {
3962               int proceeded = 0;
3963
3964               /* We may not find an inferior if this was a process exit.  */
3965               if (inf == NULL || inf->control.stop_soon == NO_STOP_QUIETLY)
3966                 proceeded = normal_stop ();
3967
3968               if (!proceeded)
3969                 {
3970                   inferior_event_handler (INF_EXEC_COMPLETE, NULL);
3971                   cmd_done = 1;
3972                 }
3973             }
3974         }
3975     }
3976
3977   /* No error, don't finish the thread states yet.  */
3978   discard_cleanups (ts_old_chain);
3979
3980   /* Revert thread and frame.  */
3981   do_cleanups (old_chain);
3982
3983   /* If a UI was in sync execution mode, and now isn't, restore its
3984      prompt (a synchronous execution command has finished, and we're
3985      ready for input).  */
3986   all_uis_check_sync_execution_done ();
3987
3988   if (cmd_done
3989       && exec_done_display_p
3990       && (ptid_equal (inferior_ptid, null_ptid)
3991           || !is_running (inferior_ptid)))
3992     printf_unfiltered (_("completed.\n"));
3993 }
3994
3995 /* Record the frame and location we're currently stepping through.  */
3996 void
3997 set_step_info (struct frame_info *frame, struct symtab_and_line sal)
3998 {
3999   struct thread_info *tp = inferior_thread ();
4000
4001   tp->control.step_frame_id = get_frame_id (frame);
4002   tp->control.step_stack_frame_id = get_stack_frame_id (frame);
4003
4004   tp->current_symtab = sal.symtab;
4005   tp->current_line = sal.line;
4006 }
4007
4008 /* Clear context switchable stepping state.  */
4009
4010 void
4011 init_thread_stepping_state (struct thread_info *tss)
4012 {
4013   tss->stepped_breakpoint = 0;
4014   tss->stepping_over_breakpoint = 0;
4015   tss->stepping_over_watchpoint = 0;
4016   tss->step_after_step_resume_breakpoint = 0;
4017 }
4018
4019 /* Set the cached copy of the last ptid/waitstatus.  */
4020
4021 void
4022 set_last_target_status (ptid_t ptid, struct target_waitstatus status)
4023 {
4024   target_last_wait_ptid = ptid;
4025   target_last_waitstatus = status;
4026 }
4027
4028 /* Return the cached copy of the last pid/waitstatus returned by
4029    target_wait()/deprecated_target_wait_hook().  The data is actually
4030    cached by handle_inferior_event(), which gets called immediately
4031    after target_wait()/deprecated_target_wait_hook().  */
4032
4033 void
4034 get_last_target_status (ptid_t *ptidp, struct target_waitstatus *status)
4035 {
4036   *ptidp = target_last_wait_ptid;
4037   *status = target_last_waitstatus;
4038 }
4039
4040 void
4041 nullify_last_target_wait_ptid (void)
4042 {
4043   target_last_wait_ptid = minus_one_ptid;
4044 }
4045
4046 /* Switch thread contexts.  */
4047
4048 static void
4049 context_switch (ptid_t ptid)
4050 {
4051   if (debug_infrun && !ptid_equal (ptid, inferior_ptid))
4052     {
4053       fprintf_unfiltered (gdb_stdlog, "infrun: Switching context from %s ",
4054                           target_pid_to_str (inferior_ptid));
4055       fprintf_unfiltered (gdb_stdlog, "to %s\n",
4056                           target_pid_to_str (ptid));
4057     }
4058
4059   switch_to_thread (ptid);
4060 }
4061
4062 /* If the target can't tell whether we've hit breakpoints
4063    (target_supports_stopped_by_sw_breakpoint), and we got a SIGTRAP,
4064    check whether that could have been caused by a breakpoint.  If so,
4065    adjust the PC, per gdbarch_decr_pc_after_break.  */
4066
4067 static void
4068 adjust_pc_after_break (struct thread_info *thread,
4069                        struct target_waitstatus *ws)
4070 {
4071   struct regcache *regcache;
4072   struct gdbarch *gdbarch;
4073   CORE_ADDR breakpoint_pc, decr_pc;
4074
4075   /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP.  If
4076      we aren't, just return.
4077
4078      We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
4079      affected by gdbarch_decr_pc_after_break.  Other waitkinds which are
4080      implemented by software breakpoints should be handled through the normal
4081      breakpoint layer.
4082
4083      NOTE drow/2004-01-31: On some targets, breakpoints may generate
4084      different signals (SIGILL or SIGEMT for instance), but it is less
4085      clear where the PC is pointing afterwards.  It may not match
4086      gdbarch_decr_pc_after_break.  I don't know any specific target that
4087      generates these signals at breakpoints (the code has been in GDB since at
4088      least 1992) so I can not guess how to handle them here.
4089
4090      In earlier versions of GDB, a target with 
4091      gdbarch_have_nonsteppable_watchpoint would have the PC after hitting a
4092      watchpoint affected by gdbarch_decr_pc_after_break.  I haven't found any
4093      target with both of these set in GDB history, and it seems unlikely to be
4094      correct, so gdbarch_have_nonsteppable_watchpoint is not checked here.  */
4095
4096   if (ws->kind != TARGET_WAITKIND_STOPPED)
4097     return;
4098
4099   if (ws->value.sig != GDB_SIGNAL_TRAP)
4100     return;
4101
4102   /* In reverse execution, when a breakpoint is hit, the instruction
4103      under it has already been de-executed.  The reported PC always
4104      points at the breakpoint address, so adjusting it further would
4105      be wrong.  E.g., consider this case on a decr_pc_after_break == 1
4106      architecture:
4107
4108        B1         0x08000000 :   INSN1
4109        B2         0x08000001 :   INSN2
4110                   0x08000002 :   INSN3
4111             PC -> 0x08000003 :   INSN4
4112
4113      Say you're stopped at 0x08000003 as above.  Reverse continuing
4114      from that point should hit B2 as below.  Reading the PC when the
4115      SIGTRAP is reported should read 0x08000001 and INSN2 should have
4116      been de-executed already.
4117
4118        B1         0x08000000 :   INSN1
4119        B2   PC -> 0x08000001 :   INSN2
4120                   0x08000002 :   INSN3
4121                   0x08000003 :   INSN4
4122
4123      We can't apply the same logic as for forward execution, because
4124      we would wrongly adjust the PC to 0x08000000, since there's a
4125      breakpoint at PC - 1.  We'd then report a hit on B1, although
4126      INSN1 hadn't been de-executed yet.  Doing nothing is the correct
4127      behaviour.  */
4128   if (execution_direction == EXEC_REVERSE)
4129     return;
4130
4131   /* If the target can tell whether the thread hit a SW breakpoint,
4132      trust it.  Targets that can tell also adjust the PC
4133      themselves.  */
4134   if (target_supports_stopped_by_sw_breakpoint ())
4135     return;
4136
4137   /* Note that relying on whether a breakpoint is planted in memory to
4138      determine this can fail.  E.g,. the breakpoint could have been
4139      removed since.  Or the thread could have been told to step an
4140      instruction the size of a breakpoint instruction, and only
4141      _after_ was a breakpoint inserted at its address.  */
4142
4143   /* If this target does not decrement the PC after breakpoints, then
4144      we have nothing to do.  */
4145   regcache = get_thread_regcache (thread->ptid);
4146   gdbarch = regcache->arch ();
4147
4148   decr_pc = gdbarch_decr_pc_after_break (gdbarch);
4149   if (decr_pc == 0)
4150     return;
4151
4152   const address_space *aspace = regcache->aspace ();
4153
4154   /* Find the location where (if we've hit a breakpoint) the
4155      breakpoint would be.  */
4156   breakpoint_pc = regcache_read_pc (regcache) - decr_pc;
4157
4158   /* If the target can't tell whether a software breakpoint triggered,
4159      fallback to figuring it out based on breakpoints we think were
4160      inserted in the target, and on whether the thread was stepped or
4161      continued.  */
4162
4163   /* Check whether there actually is a software breakpoint inserted at
4164      that location.
4165
4166      If in non-stop mode, a race condition is possible where we've
4167      removed a breakpoint, but stop events for that breakpoint were
4168      already queued and arrive later.  To suppress those spurious
4169      SIGTRAPs, we keep a list of such breakpoint locations for a bit,
4170      and retire them after a number of stop events are reported.  Note
4171      this is an heuristic and can thus get confused.  The real fix is
4172      to get the "stopped by SW BP and needs adjustment" info out of
4173      the target/kernel (and thus never reach here; see above).  */
4174   if (software_breakpoint_inserted_here_p (aspace, breakpoint_pc)
4175       || (target_is_non_stop_p ()
4176           && moribund_breakpoint_here_p (aspace, breakpoint_pc)))
4177     {
4178       gdb::optional<scoped_restore_tmpl<int>> restore_operation_disable;
4179
4180       if (record_full_is_used ())
4181         restore_operation_disable.emplace
4182           (record_full_gdb_operation_disable_set ());
4183
4184       /* When using hardware single-step, a SIGTRAP is reported for both
4185          a completed single-step and a software breakpoint.  Need to
4186          differentiate between the two, as the latter needs adjusting
4187          but the former does not.
4188
4189          The SIGTRAP can be due to a completed hardware single-step only if 
4190           - we didn't insert software single-step breakpoints
4191           - this thread is currently being stepped
4192
4193          If any of these events did not occur, we must have stopped due
4194          to hitting a software breakpoint, and have to back up to the
4195          breakpoint address.
4196
4197          As a special case, we could have hardware single-stepped a
4198          software breakpoint.  In this case (prev_pc == breakpoint_pc),
4199          we also need to back up to the breakpoint address.  */
4200
4201       if (thread_has_single_step_breakpoints_set (thread)
4202           || !currently_stepping (thread)
4203           || (thread->stepped_breakpoint
4204               && thread->prev_pc == breakpoint_pc))
4205         regcache_write_pc (regcache, breakpoint_pc);
4206     }
4207 }
4208
4209 static int
4210 stepped_in_from (struct frame_info *frame, struct frame_id step_frame_id)
4211 {
4212   for (frame = get_prev_frame (frame);
4213        frame != NULL;
4214        frame = get_prev_frame (frame))
4215     {
4216       if (frame_id_eq (get_frame_id (frame), step_frame_id))
4217         return 1;
4218       if (get_frame_type (frame) != INLINE_FRAME)
4219         break;
4220     }
4221
4222   return 0;
4223 }
4224
4225 /* If the event thread has the stop requested flag set, pretend it
4226    stopped for a GDB_SIGNAL_0 (i.e., as if it stopped due to
4227    target_stop).  */
4228
4229 static bool
4230 handle_stop_requested (struct execution_control_state *ecs)
4231 {
4232   if (ecs->event_thread->stop_requested)
4233     {
4234       ecs->ws.kind = TARGET_WAITKIND_STOPPED;
4235       ecs->ws.value.sig = GDB_SIGNAL_0;
4236       handle_signal_stop (ecs);
4237       return true;
4238     }
4239   return false;
4240 }
4241
4242 /* Auxiliary function that handles syscall entry/return events.
4243    It returns 1 if the inferior should keep going (and GDB
4244    should ignore the event), or 0 if the event deserves to be
4245    processed.  */
4246
4247 static int
4248 handle_syscall_event (struct execution_control_state *ecs)
4249 {
4250   struct regcache *regcache;
4251   int syscall_number;
4252
4253   if (!ptid_equal (ecs->ptid, inferior_ptid))
4254     context_switch (ecs->ptid);
4255
4256   regcache = get_thread_regcache (ecs->ptid);
4257   syscall_number = ecs->ws.value.syscall_number;
4258   stop_pc = regcache_read_pc (regcache);
4259
4260   if (catch_syscall_enabled () > 0
4261       && catching_syscall_number (syscall_number) > 0)
4262     {
4263       if (debug_infrun)
4264         fprintf_unfiltered (gdb_stdlog, "infrun: syscall number = '%d'\n",
4265                             syscall_number);
4266
4267       ecs->event_thread->control.stop_bpstat
4268         = bpstat_stop_status (regcache->aspace (),
4269                               stop_pc, ecs->ptid, &ecs->ws);
4270
4271       if (handle_stop_requested (ecs))
4272         return 0;
4273
4274       if (bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
4275         {
4276           /* Catchpoint hit.  */
4277           return 0;
4278         }
4279     }
4280
4281   if (handle_stop_requested (ecs))
4282     return 0;
4283
4284   /* If no catchpoint triggered for this, then keep going.  */
4285   keep_going (ecs);
4286   return 1;
4287 }
4288
4289 /* Lazily fill in the execution_control_state's stop_func_* fields.  */
4290
4291 static void
4292 fill_in_stop_func (struct gdbarch *gdbarch,
4293                    struct execution_control_state *ecs)
4294 {
4295   if (!ecs->stop_func_filled_in)
4296     {
4297       /* Don't care about return value; stop_func_start and stop_func_name
4298          will both be 0 if it doesn't work.  */
4299       find_pc_partial_function (stop_pc, &ecs->stop_func_name,
4300                                 &ecs->stop_func_start, &ecs->stop_func_end);
4301       ecs->stop_func_start
4302         += gdbarch_deprecated_function_start_offset (gdbarch);
4303
4304       if (gdbarch_skip_entrypoint_p (gdbarch))
4305         ecs->stop_func_start = gdbarch_skip_entrypoint (gdbarch,
4306                                                         ecs->stop_func_start);
4307
4308       ecs->stop_func_filled_in = 1;
4309     }
4310 }
4311
4312
4313 /* Return the STOP_SOON field of the inferior pointed at by PTID.  */
4314
4315 static enum stop_kind
4316 get_inferior_stop_soon (ptid_t ptid)
4317 {
4318   struct inferior *inf = find_inferior_ptid (ptid);
4319
4320   gdb_assert (inf != NULL);
4321   return inf->control.stop_soon;
4322 }
4323
4324 /* Wait for one event.  Store the resulting waitstatus in WS, and
4325    return the event ptid.  */
4326
4327 static ptid_t
4328 wait_one (struct target_waitstatus *ws)
4329 {
4330   ptid_t event_ptid;
4331   ptid_t wait_ptid = minus_one_ptid;
4332
4333   overlay_cache_invalid = 1;
4334
4335   /* Flush target cache before starting to handle each event.
4336      Target was running and cache could be stale.  This is just a
4337      heuristic.  Running threads may modify target memory, but we
4338      don't get any event.  */
4339   target_dcache_invalidate ();
4340
4341   if (deprecated_target_wait_hook)
4342     event_ptid = deprecated_target_wait_hook (wait_ptid, ws, 0);
4343   else
4344     event_ptid = target_wait (wait_ptid, ws, 0);
4345
4346   if (debug_infrun)
4347     print_target_wait_results (wait_ptid, event_ptid, ws);
4348
4349   return event_ptid;
4350 }
4351
4352 /* Generate a wrapper for target_stopped_by_REASON that works on PTID
4353    instead of the current thread.  */
4354 #define THREAD_STOPPED_BY(REASON)               \
4355 static int                                      \
4356 thread_stopped_by_ ## REASON (ptid_t ptid)      \
4357 {                                               \
4358   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid); \
4359   inferior_ptid = ptid;                         \
4360                                                 \
4361   return target_stopped_by_ ## REASON ();       \
4362 }
4363
4364 /* Generate thread_stopped_by_watchpoint.  */
4365 THREAD_STOPPED_BY (watchpoint)
4366 /* Generate thread_stopped_by_sw_breakpoint.  */
4367 THREAD_STOPPED_BY (sw_breakpoint)
4368 /* Generate thread_stopped_by_hw_breakpoint.  */
4369 THREAD_STOPPED_BY (hw_breakpoint)
4370
4371 /* Cleanups that switches to the PTID pointed at by PTID_P.  */
4372
4373 static void
4374 switch_to_thread_cleanup (void *ptid_p)
4375 {
4376   ptid_t ptid = *(ptid_t *) ptid_p;
4377
4378   switch_to_thread (ptid);
4379 }
4380
4381 /* Save the thread's event and stop reason to process it later.  */
4382
4383 static void
4384 save_waitstatus (struct thread_info *tp, struct target_waitstatus *ws)
4385 {
4386   struct regcache *regcache;
4387
4388   if (debug_infrun)
4389     {
4390       std::string statstr = target_waitstatus_to_string (ws);
4391
4392       fprintf_unfiltered (gdb_stdlog,
4393                           "infrun: saving status %s for %d.%ld.%ld\n",
4394                           statstr.c_str (),
4395                           ptid_get_pid (tp->ptid),
4396                           ptid_get_lwp (tp->ptid),
4397                           ptid_get_tid (tp->ptid));
4398     }
4399
4400   /* Record for later.  */
4401   tp->suspend.waitstatus = *ws;
4402   tp->suspend.waitstatus_pending_p = 1;
4403
4404   regcache = get_thread_regcache (tp->ptid);
4405   const address_space *aspace = regcache->aspace ();
4406
4407   if (ws->kind == TARGET_WAITKIND_STOPPED
4408       && ws->value.sig == GDB_SIGNAL_TRAP)
4409     {
4410       CORE_ADDR pc = regcache_read_pc (regcache);
4411
4412       adjust_pc_after_break (tp, &tp->suspend.waitstatus);
4413
4414       if (thread_stopped_by_watchpoint (tp->ptid))
4415         {
4416           tp->suspend.stop_reason
4417             = TARGET_STOPPED_BY_WATCHPOINT;
4418         }
4419       else if (target_supports_stopped_by_sw_breakpoint ()
4420                && thread_stopped_by_sw_breakpoint (tp->ptid))
4421         {
4422           tp->suspend.stop_reason
4423             = TARGET_STOPPED_BY_SW_BREAKPOINT;
4424         }
4425       else if (target_supports_stopped_by_hw_breakpoint ()
4426                && thread_stopped_by_hw_breakpoint (tp->ptid))
4427         {
4428           tp->suspend.stop_reason
4429             = TARGET_STOPPED_BY_HW_BREAKPOINT;
4430         }
4431       else if (!target_supports_stopped_by_hw_breakpoint ()
4432                && hardware_breakpoint_inserted_here_p (aspace,
4433                                                        pc))
4434         {
4435           tp->suspend.stop_reason
4436             = TARGET_STOPPED_BY_HW_BREAKPOINT;
4437         }
4438       else if (!target_supports_stopped_by_sw_breakpoint ()
4439                && software_breakpoint_inserted_here_p (aspace,
4440                                                        pc))
4441         {
4442           tp->suspend.stop_reason
4443             = TARGET_STOPPED_BY_SW_BREAKPOINT;
4444         }
4445       else if (!thread_has_single_step_breakpoints_set (tp)
4446                && currently_stepping (tp))
4447         {
4448           tp->suspend.stop_reason
4449             = TARGET_STOPPED_BY_SINGLE_STEP;
4450         }
4451     }
4452 }
4453
4454 /* A cleanup that disables thread create/exit events.  */
4455
4456 static void
4457 disable_thread_events (void *arg)
4458 {
4459   target_thread_events (0);
4460 }
4461
4462 /* See infrun.h.  */
4463
4464 void
4465 stop_all_threads (void)
4466 {
4467   /* We may need multiple passes to discover all threads.  */
4468   int pass;
4469   int iterations = 0;
4470   ptid_t entry_ptid;
4471   struct cleanup *old_chain;
4472
4473   gdb_assert (target_is_non_stop_p ());
4474
4475   if (debug_infrun)
4476     fprintf_unfiltered (gdb_stdlog, "infrun: stop_all_threads\n");
4477
4478   entry_ptid = inferior_ptid;
4479   old_chain = make_cleanup (switch_to_thread_cleanup, &entry_ptid);
4480
4481   target_thread_events (1);
4482   make_cleanup (disable_thread_events, NULL);
4483
4484   /* Request threads to stop, and then wait for the stops.  Because
4485      threads we already know about can spawn more threads while we're
4486      trying to stop them, and we only learn about new threads when we
4487      update the thread list, do this in a loop, and keep iterating
4488      until two passes find no threads that need to be stopped.  */
4489   for (pass = 0; pass < 2; pass++, iterations++)
4490     {
4491       if (debug_infrun)
4492         fprintf_unfiltered (gdb_stdlog,
4493                             "infrun: stop_all_threads, pass=%d, "
4494                             "iterations=%d\n", pass, iterations);
4495       while (1)
4496         {
4497           ptid_t event_ptid;
4498           struct target_waitstatus ws;
4499           int need_wait = 0;
4500           struct thread_info *t;
4501
4502           update_thread_list ();
4503
4504           /* Go through all threads looking for threads that we need
4505              to tell the target to stop.  */
4506           ALL_NON_EXITED_THREADS (t)
4507             {
4508               if (t->executing)
4509                 {
4510                   /* If already stopping, don't request a stop again.
4511                      We just haven't seen the notification yet.  */
4512                   if (!t->stop_requested)
4513                     {
4514                       if (debug_infrun)
4515                         fprintf_unfiltered (gdb_stdlog,
4516                                             "infrun:   %s executing, "
4517                                             "need stop\n",
4518                                             target_pid_to_str (t->ptid));
4519                       target_stop (t->ptid);
4520                       t->stop_requested = 1;
4521                     }
4522                   else
4523                     {
4524                       if (debug_infrun)
4525                         fprintf_unfiltered (gdb_stdlog,
4526                                             "infrun:   %s executing, "
4527                                             "already stopping\n",
4528                                             target_pid_to_str (t->ptid));
4529                     }
4530
4531                   if (t->stop_requested)
4532                     need_wait = 1;
4533                 }
4534               else
4535                 {
4536                   if (debug_infrun)
4537                     fprintf_unfiltered (gdb_stdlog,
4538                                         "infrun:   %s not executing\n",
4539                                         target_pid_to_str (t->ptid));
4540
4541                   /* The thread may be not executing, but still be
4542                      resumed with a pending status to process.  */
4543                   t->resumed = 0;
4544                 }
4545             }
4546
4547           if (!need_wait)
4548             break;
4549
4550           /* If we find new threads on the second iteration, restart
4551              over.  We want to see two iterations in a row with all
4552              threads stopped.  */
4553           if (pass > 0)
4554             pass = -1;
4555
4556           event_ptid = wait_one (&ws);
4557           if (ws.kind == TARGET_WAITKIND_NO_RESUMED)
4558             {
4559               /* All resumed threads exited.  */
4560             }
4561           else if (ws.kind == TARGET_WAITKIND_THREAD_EXITED
4562                    || ws.kind == TARGET_WAITKIND_EXITED
4563                    || ws.kind == TARGET_WAITKIND_SIGNALLED)
4564             {
4565               if (debug_infrun)
4566                 {
4567                   ptid_t ptid = pid_to_ptid (ws.value.integer);
4568
4569                   fprintf_unfiltered (gdb_stdlog,
4570                                       "infrun: %s exited while "
4571                                       "stopping threads\n",
4572                                       target_pid_to_str (ptid));
4573                 }
4574             }
4575           else
4576             {
4577               struct inferior *inf;
4578
4579               t = find_thread_ptid (event_ptid);
4580               if (t == NULL)
4581                 t = add_thread (event_ptid);
4582
4583               t->stop_requested = 0;
4584               t->executing = 0;
4585               t->resumed = 0;
4586               t->control.may_range_step = 0;
4587
4588               /* This may be the first time we see the inferior report
4589                  a stop.  */
4590               inf = find_inferior_ptid (event_ptid);
4591               if (inf->needs_setup)
4592                 {
4593                   switch_to_thread_no_regs (t);
4594                   setup_inferior (0);
4595                 }
4596
4597               if (ws.kind == TARGET_WAITKIND_STOPPED
4598                   && ws.value.sig == GDB_SIGNAL_0)
4599                 {
4600                   /* We caught the event that we intended to catch, so
4601                      there's no event pending.  */
4602                   t->suspend.waitstatus.kind = TARGET_WAITKIND_IGNORE;
4603                   t->suspend.waitstatus_pending_p = 0;
4604
4605                   if (displaced_step_fixup (t->ptid, GDB_SIGNAL_0) < 0)
4606                     {
4607                       /* Add it back to the step-over queue.  */
4608                       if (debug_infrun)
4609                         {
4610                           fprintf_unfiltered (gdb_stdlog,
4611                                               "infrun: displaced-step of %s "
4612                                               "canceled: adding back to the "
4613                                               "step-over queue\n",
4614                                               target_pid_to_str (t->ptid));
4615                         }
4616                       t->control.trap_expected = 0;
4617                       thread_step_over_chain_enqueue (t);
4618                     }
4619                 }
4620               else
4621                 {
4622                   enum gdb_signal sig;
4623                   struct regcache *regcache;
4624
4625                   if (debug_infrun)
4626                     {
4627                       std::string statstr = target_waitstatus_to_string (&ws);
4628
4629                       fprintf_unfiltered (gdb_stdlog,
4630                                           "infrun: target_wait %s, saving "
4631                                           "status for %d.%ld.%ld\n",
4632                                           statstr.c_str (),
4633                                           ptid_get_pid (t->ptid),
4634                                           ptid_get_lwp (t->ptid),
4635                                           ptid_get_tid (t->ptid));
4636                     }
4637
4638                   /* Record for later.  */
4639                   save_waitstatus (t, &ws);
4640
4641                   sig = (ws.kind == TARGET_WAITKIND_STOPPED
4642                          ? ws.value.sig : GDB_SIGNAL_0);
4643
4644                   if (displaced_step_fixup (t->ptid, sig) < 0)
4645                     {
4646                       /* Add it back to the step-over queue.  */
4647                       t->control.trap_expected = 0;
4648                       thread_step_over_chain_enqueue (t);
4649                     }
4650
4651                   regcache = get_thread_regcache (t->ptid);
4652                   t->suspend.stop_pc = regcache_read_pc (regcache);
4653
4654                   if (debug_infrun)
4655                     {
4656                       fprintf_unfiltered (gdb_stdlog,
4657                                           "infrun: saved stop_pc=%s for %s "
4658                                           "(currently_stepping=%d)\n",
4659                                           paddress (target_gdbarch (),
4660                                                     t->suspend.stop_pc),
4661                                           target_pid_to_str (t->ptid),
4662                                           currently_stepping (t));
4663                     }
4664                 }
4665             }
4666         }
4667     }
4668
4669   do_cleanups (old_chain);
4670
4671   if (debug_infrun)
4672     fprintf_unfiltered (gdb_stdlog, "infrun: stop_all_threads done\n");
4673 }
4674
4675 /* Handle a TARGET_WAITKIND_NO_RESUMED event.  */
4676
4677 static int
4678 handle_no_resumed (struct execution_control_state *ecs)
4679 {
4680   struct inferior *inf;
4681   struct thread_info *thread;
4682
4683   if (target_can_async_p ())
4684     {
4685       struct ui *ui;
4686       int any_sync = 0;
4687
4688       ALL_UIS (ui)
4689         {
4690           if (ui->prompt_state == PROMPT_BLOCKED)
4691             {
4692               any_sync = 1;
4693               break;
4694             }
4695         }
4696       if (!any_sync)
4697         {
4698           /* There were no unwaited-for children left in the target, but,
4699              we're not synchronously waiting for events either.  Just
4700              ignore.  */
4701
4702           if (debug_infrun)
4703             fprintf_unfiltered (gdb_stdlog,
4704                                 "infrun: TARGET_WAITKIND_NO_RESUMED "
4705                                 "(ignoring: bg)\n");
4706           prepare_to_wait (ecs);
4707           return 1;
4708         }
4709     }
4710
4711   /* Otherwise, if we were running a synchronous execution command, we
4712      may need to cancel it and give the user back the terminal.
4713
4714      In non-stop mode, the target can't tell whether we've already
4715      consumed previous stop events, so it can end up sending us a
4716      no-resumed event like so:
4717
4718        #0 - thread 1 is left stopped
4719
4720        #1 - thread 2 is resumed and hits breakpoint
4721                -> TARGET_WAITKIND_STOPPED
4722
4723        #2 - thread 3 is resumed and exits
4724             this is the last resumed thread, so
4725                -> TARGET_WAITKIND_NO_RESUMED
4726
4727        #3 - gdb processes stop for thread 2 and decides to re-resume
4728             it.
4729
4730        #4 - gdb processes the TARGET_WAITKIND_NO_RESUMED event.
4731             thread 2 is now resumed, so the event should be ignored.
4732
4733      IOW, if the stop for thread 2 doesn't end a foreground command,
4734      then we need to ignore the following TARGET_WAITKIND_NO_RESUMED
4735      event.  But it could be that the event meant that thread 2 itself
4736      (or whatever other thread was the last resumed thread) exited.
4737
4738      To address this we refresh the thread list and check whether we
4739      have resumed threads _now_.  In the example above, this removes
4740      thread 3 from the thread list.  If thread 2 was re-resumed, we
4741      ignore this event.  If we find no thread resumed, then we cancel
4742      the synchronous command show "no unwaited-for " to the user.  */
4743   update_thread_list ();
4744
4745   ALL_NON_EXITED_THREADS (thread)
4746     {
4747       if (thread->executing
4748           || thread->suspend.waitstatus_pending_p)
4749         {
4750           /* There were no unwaited-for children left in the target at
4751              some point, but there are now.  Just ignore.  */
4752           if (debug_infrun)
4753             fprintf_unfiltered (gdb_stdlog,
4754                                 "infrun: TARGET_WAITKIND_NO_RESUMED "
4755                                 "(ignoring: found resumed)\n");
4756           prepare_to_wait (ecs);
4757           return 1;
4758         }
4759     }
4760
4761   /* Note however that we may find no resumed thread because the whole
4762      process exited meanwhile (thus updating the thread list results
4763      in an empty thread list).  In this case we know we'll be getting
4764      a process exit event shortly.  */
4765   ALL_INFERIORS (inf)
4766     {
4767       if (inf->pid == 0)
4768         continue;
4769
4770       thread = any_live_thread_of_process (inf->pid);
4771       if (thread == NULL)
4772         {
4773           if (debug_infrun)
4774             fprintf_unfiltered (gdb_stdlog,
4775                                 "infrun: TARGET_WAITKIND_NO_RESUMED "
4776                                 "(expect process exit)\n");
4777           prepare_to_wait (ecs);
4778           return 1;
4779         }
4780     }
4781
4782   /* Go ahead and report the event.  */
4783   return 0;
4784 }
4785
4786 /* Given an execution control state that has been freshly filled in by
4787    an event from the inferior, figure out what it means and take
4788    appropriate action.
4789
4790    The alternatives are:
4791
4792    1) stop_waiting and return; to really stop and return to the
4793    debugger.
4794
4795    2) keep_going and return; to wait for the next event (set
4796    ecs->event_thread->stepping_over_breakpoint to 1 to single step
4797    once).  */
4798
4799 static void
4800 handle_inferior_event_1 (struct execution_control_state *ecs)
4801 {
4802   enum stop_kind stop_soon;
4803
4804   if (ecs->ws.kind == TARGET_WAITKIND_IGNORE)
4805     {
4806       /* We had an event in the inferior, but we are not interested in
4807          handling it at this level.  The lower layers have already
4808          done what needs to be done, if anything.
4809
4810          One of the possible circumstances for this is when the
4811          inferior produces output for the console.  The inferior has
4812          not stopped, and we are ignoring the event.  Another possible
4813          circumstance is any event which the lower level knows will be
4814          reported multiple times without an intervening resume.  */
4815       if (debug_infrun)
4816         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_IGNORE\n");
4817       prepare_to_wait (ecs);
4818       return;
4819     }
4820
4821   if (ecs->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
4822     {
4823       if (debug_infrun)
4824         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_THREAD_EXITED\n");
4825       prepare_to_wait (ecs);
4826       return;
4827     }
4828
4829   if (ecs->ws.kind == TARGET_WAITKIND_NO_RESUMED
4830       && handle_no_resumed (ecs))
4831     return;
4832
4833   /* Cache the last pid/waitstatus.  */
4834   set_last_target_status (ecs->ptid, ecs->ws);
4835
4836   /* Always clear state belonging to the previous time we stopped.  */
4837   stop_stack_dummy = STOP_NONE;
4838
4839   if (ecs->ws.kind == TARGET_WAITKIND_NO_RESUMED)
4840     {
4841       /* No unwaited-for children left.  IOW, all resumed children
4842          have exited.  */
4843       if (debug_infrun)
4844         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_NO_RESUMED\n");
4845
4846       stop_print_frame = 0;
4847       stop_waiting (ecs);
4848       return;
4849     }
4850
4851   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
4852       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
4853     {
4854       ecs->event_thread = find_thread_ptid (ecs->ptid);
4855       /* If it's a new thread, add it to the thread database.  */
4856       if (ecs->event_thread == NULL)
4857         ecs->event_thread = add_thread (ecs->ptid);
4858
4859       /* Disable range stepping.  If the next step request could use a
4860          range, this will be end up re-enabled then.  */
4861       ecs->event_thread->control.may_range_step = 0;
4862     }
4863
4864   /* Dependent on valid ECS->EVENT_THREAD.  */
4865   adjust_pc_after_break (ecs->event_thread, &ecs->ws);
4866
4867   /* Dependent on the current PC value modified by adjust_pc_after_break.  */
4868   reinit_frame_cache ();
4869
4870   breakpoint_retire_moribund ();
4871
4872   /* First, distinguish signals caused by the debugger from signals
4873      that have to do with the program's own actions.  Note that
4874      breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
4875      on the operating system version.  Here we detect when a SIGILL or
4876      SIGEMT is really a breakpoint and change it to SIGTRAP.  We do
4877      something similar for SIGSEGV, since a SIGSEGV will be generated
4878      when we're trying to execute a breakpoint instruction on a
4879      non-executable stack.  This happens for call dummy breakpoints
4880      for architectures like SPARC that place call dummies on the
4881      stack.  */
4882   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED
4883       && (ecs->ws.value.sig == GDB_SIGNAL_ILL
4884           || ecs->ws.value.sig == GDB_SIGNAL_SEGV
4885           || ecs->ws.value.sig == GDB_SIGNAL_EMT))
4886     {
4887       struct regcache *regcache = get_thread_regcache (ecs->ptid);
4888
4889       if (breakpoint_inserted_here_p (regcache->aspace (),
4890                                       regcache_read_pc (regcache)))
4891         {
4892           if (debug_infrun)
4893             fprintf_unfiltered (gdb_stdlog,
4894                                 "infrun: Treating signal as SIGTRAP\n");
4895           ecs->ws.value.sig = GDB_SIGNAL_TRAP;
4896         }
4897     }
4898
4899   /* Mark the non-executing threads accordingly.  In all-stop, all
4900      threads of all processes are stopped when we get any event
4901      reported.  In non-stop mode, only the event thread stops.  */
4902   {
4903     ptid_t mark_ptid;
4904
4905     if (!target_is_non_stop_p ())
4906       mark_ptid = minus_one_ptid;
4907     else if (ecs->ws.kind == TARGET_WAITKIND_SIGNALLED
4908              || ecs->ws.kind == TARGET_WAITKIND_EXITED)
4909       {
4910         /* If we're handling a process exit in non-stop mode, even
4911            though threads haven't been deleted yet, one would think
4912            that there is nothing to do, as threads of the dead process
4913            will be soon deleted, and threads of any other process were
4914            left running.  However, on some targets, threads survive a
4915            process exit event.  E.g., for the "checkpoint" command,
4916            when the current checkpoint/fork exits, linux-fork.c
4917            automatically switches to another fork from within
4918            target_mourn_inferior, by associating the same
4919            inferior/thread to another fork.  We haven't mourned yet at
4920            this point, but we must mark any threads left in the
4921            process as not-executing so that finish_thread_state marks
4922            them stopped (in the user's perspective) if/when we present
4923            the stop to the user.  */
4924         mark_ptid = pid_to_ptid (ptid_get_pid (ecs->ptid));
4925       }
4926     else
4927       mark_ptid = ecs->ptid;
4928
4929     set_executing (mark_ptid, 0);
4930
4931     /* Likewise the resumed flag.  */
4932     set_resumed (mark_ptid, 0);
4933   }
4934
4935   switch (ecs->ws.kind)
4936     {
4937     case TARGET_WAITKIND_LOADED:
4938       if (debug_infrun)
4939         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_LOADED\n");
4940       if (!ptid_equal (ecs->ptid, inferior_ptid))
4941         context_switch (ecs->ptid);
4942       /* Ignore gracefully during startup of the inferior, as it might
4943          be the shell which has just loaded some objects, otherwise
4944          add the symbols for the newly loaded objects.  Also ignore at
4945          the beginning of an attach or remote session; we will query
4946          the full list of libraries once the connection is
4947          established.  */
4948
4949       stop_soon = get_inferior_stop_soon (ecs->ptid);
4950       if (stop_soon == NO_STOP_QUIETLY)
4951         {
4952           struct regcache *regcache;
4953
4954           regcache = get_thread_regcache (ecs->ptid);
4955
4956           handle_solib_event ();
4957
4958           ecs->event_thread->control.stop_bpstat
4959             = bpstat_stop_status (regcache->aspace (),
4960                                   stop_pc, ecs->ptid, &ecs->ws);
4961
4962           if (handle_stop_requested (ecs))
4963             return;
4964
4965           if (bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
4966             {
4967               /* A catchpoint triggered.  */
4968               process_event_stop_test (ecs);
4969               return;
4970             }
4971
4972           /* If requested, stop when the dynamic linker notifies
4973              gdb of events.  This allows the user to get control
4974              and place breakpoints in initializer routines for
4975              dynamically loaded objects (among other things).  */
4976           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
4977           if (stop_on_solib_events)
4978             {
4979               /* Make sure we print "Stopped due to solib-event" in
4980                  normal_stop.  */
4981               stop_print_frame = 1;
4982
4983               stop_waiting (ecs);
4984               return;
4985             }
4986         }
4987
4988       /* If we are skipping through a shell, or through shared library
4989          loading that we aren't interested in, resume the program.  If
4990          we're running the program normally, also resume.  */
4991       if (stop_soon == STOP_QUIETLY || stop_soon == NO_STOP_QUIETLY)
4992         {
4993           /* Loading of shared libraries might have changed breakpoint
4994              addresses.  Make sure new breakpoints are inserted.  */
4995           if (stop_soon == NO_STOP_QUIETLY)
4996             insert_breakpoints ();
4997           resume (GDB_SIGNAL_0);
4998           prepare_to_wait (ecs);
4999           return;
5000         }
5001
5002       /* But stop if we're attaching or setting up a remote
5003          connection.  */
5004       if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
5005           || stop_soon == STOP_QUIETLY_REMOTE)
5006         {
5007           if (debug_infrun)
5008             fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
5009           stop_waiting (ecs);
5010           return;
5011         }
5012
5013       internal_error (__FILE__, __LINE__,
5014                       _("unhandled stop_soon: %d"), (int) stop_soon);
5015
5016     case TARGET_WAITKIND_SPURIOUS:
5017       if (debug_infrun)
5018         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SPURIOUS\n");
5019       if (handle_stop_requested (ecs))
5020         return;
5021       if (!ptid_equal (ecs->ptid, inferior_ptid))
5022         context_switch (ecs->ptid);
5023       resume (GDB_SIGNAL_0);
5024       prepare_to_wait (ecs);
5025       return;
5026
5027     case TARGET_WAITKIND_THREAD_CREATED:
5028       if (debug_infrun)
5029         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_THREAD_CREATED\n");
5030       if (handle_stop_requested (ecs))
5031         return;
5032       if (!ptid_equal (ecs->ptid, inferior_ptid))
5033         context_switch (ecs->ptid);
5034       if (!switch_back_to_stepped_thread (ecs))
5035         keep_going (ecs);
5036       return;
5037
5038     case TARGET_WAITKIND_EXITED:
5039     case TARGET_WAITKIND_SIGNALLED:
5040       if (debug_infrun)
5041         {
5042           if (ecs->ws.kind == TARGET_WAITKIND_EXITED)
5043             fprintf_unfiltered (gdb_stdlog,
5044                                 "infrun: TARGET_WAITKIND_EXITED\n");
5045           else
5046             fprintf_unfiltered (gdb_stdlog,
5047                                 "infrun: TARGET_WAITKIND_SIGNALLED\n");
5048         }
5049
5050       inferior_ptid = ecs->ptid;
5051       set_current_inferior (find_inferior_ptid (ecs->ptid));
5052       set_current_program_space (current_inferior ()->pspace);
5053       handle_vfork_child_exec_or_exit (0);
5054       target_terminal::ours (); /* Must do this before mourn anyway.  */
5055
5056       /* Clearing any previous state of convenience variables.  */
5057       clear_exit_convenience_vars ();
5058
5059       if (ecs->ws.kind == TARGET_WAITKIND_EXITED)
5060         {
5061           /* Record the exit code in the convenience variable $_exitcode, so
5062              that the user can inspect this again later.  */
5063           set_internalvar_integer (lookup_internalvar ("_exitcode"),
5064                                    (LONGEST) ecs->ws.value.integer);
5065
5066           /* Also record this in the inferior itself.  */
5067           current_inferior ()->has_exit_code = 1;
5068           current_inferior ()->exit_code = (LONGEST) ecs->ws.value.integer;
5069
5070           /* Support the --return-child-result option.  */
5071           return_child_result_value = ecs->ws.value.integer;
5072
5073           observer_notify_exited (ecs->ws.value.integer);
5074         }
5075       else
5076         {
5077           struct regcache *regcache = get_thread_regcache (ecs->ptid);
5078           struct gdbarch *gdbarch = regcache->arch ();
5079
5080           if (gdbarch_gdb_signal_to_target_p (gdbarch))
5081             {
5082               /* Set the value of the internal variable $_exitsignal,
5083                  which holds the signal uncaught by the inferior.  */
5084               set_internalvar_integer (lookup_internalvar ("_exitsignal"),
5085                                        gdbarch_gdb_signal_to_target (gdbarch,
5086                                                           ecs->ws.value.sig));
5087             }
5088           else
5089             {
5090               /* We don't have access to the target's method used for
5091                  converting between signal numbers (GDB's internal
5092                  representation <-> target's representation).
5093                  Therefore, we cannot do a good job at displaying this
5094                  information to the user.  It's better to just warn
5095                  her about it (if infrun debugging is enabled), and
5096                  give up.  */
5097               if (debug_infrun)
5098                 fprintf_filtered (gdb_stdlog, _("\
5099 Cannot fill $_exitsignal with the correct signal number.\n"));
5100             }
5101
5102           observer_notify_signal_exited (ecs->ws.value.sig);
5103         }
5104
5105       gdb_flush (gdb_stdout);
5106       target_mourn_inferior (inferior_ptid);
5107       stop_print_frame = 0;
5108       stop_waiting (ecs);
5109       return;
5110
5111       /* The following are the only cases in which we keep going;
5112          the above cases end in a continue or goto.  */
5113     case TARGET_WAITKIND_FORKED:
5114     case TARGET_WAITKIND_VFORKED:
5115       if (debug_infrun)
5116         {
5117           if (ecs->ws.kind == TARGET_WAITKIND_FORKED)
5118             fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_FORKED\n");
5119           else
5120             fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_VFORKED\n");
5121         }
5122
5123       /* Check whether the inferior is displaced stepping.  */
5124       {
5125         struct regcache *regcache = get_thread_regcache (ecs->ptid);
5126         struct gdbarch *gdbarch = regcache->arch ();
5127
5128         /* If checking displaced stepping is supported, and thread
5129            ecs->ptid is displaced stepping.  */
5130         if (displaced_step_in_progress_thread (ecs->ptid))
5131           {
5132             struct inferior *parent_inf
5133               = find_inferior_ptid (ecs->ptid);
5134             struct regcache *child_regcache;
5135             CORE_ADDR parent_pc;
5136
5137             /* GDB has got TARGET_WAITKIND_FORKED or TARGET_WAITKIND_VFORKED,
5138                indicating that the displaced stepping of syscall instruction
5139                has been done.  Perform cleanup for parent process here.  Note
5140                that this operation also cleans up the child process for vfork,
5141                because their pages are shared.  */
5142             displaced_step_fixup (ecs->ptid, GDB_SIGNAL_TRAP);
5143             /* Start a new step-over in another thread if there's one
5144                that needs it.  */
5145             start_step_over ();
5146
5147             if (ecs->ws.kind == TARGET_WAITKIND_FORKED)
5148               {
5149                 struct displaced_step_inferior_state *displaced
5150                   = get_displaced_stepping_state (ptid_get_pid (ecs->ptid));
5151
5152                 /* Restore scratch pad for child process.  */
5153                 displaced_step_restore (displaced, ecs->ws.value.related_pid);
5154               }
5155
5156             /* Since the vfork/fork syscall instruction was executed in the scratchpad,
5157                the child's PC is also within the scratchpad.  Set the child's PC
5158                to the parent's PC value, which has already been fixed up.
5159                FIXME: we use the parent's aspace here, although we're touching
5160                the child, because the child hasn't been added to the inferior
5161                list yet at this point.  */
5162
5163             child_regcache
5164               = get_thread_arch_aspace_regcache (ecs->ws.value.related_pid,
5165                                                  gdbarch,
5166                                                  parent_inf->aspace);
5167             /* Read PC value of parent process.  */
5168             parent_pc = regcache_read_pc (regcache);
5169
5170             if (debug_displaced)
5171               fprintf_unfiltered (gdb_stdlog,
5172                                   "displaced: write child pc from %s to %s\n",
5173                                   paddress (gdbarch,
5174                                             regcache_read_pc (child_regcache)),
5175                                   paddress (gdbarch, parent_pc));
5176
5177             regcache_write_pc (child_regcache, parent_pc);
5178           }
5179       }
5180
5181       if (!ptid_equal (ecs->ptid, inferior_ptid))
5182         context_switch (ecs->ptid);
5183
5184       /* Immediately detach breakpoints from the child before there's
5185          any chance of letting the user delete breakpoints from the
5186          breakpoint lists.  If we don't do this early, it's easy to
5187          leave left over traps in the child, vis: "break foo; catch
5188          fork; c; <fork>; del; c; <child calls foo>".  We only follow
5189          the fork on the last `continue', and by that time the
5190          breakpoint at "foo" is long gone from the breakpoint table.
5191          If we vforked, then we don't need to unpatch here, since both
5192          parent and child are sharing the same memory pages; we'll
5193          need to unpatch at follow/detach time instead to be certain
5194          that new breakpoints added between catchpoint hit time and
5195          vfork follow are detached.  */
5196       if (ecs->ws.kind != TARGET_WAITKIND_VFORKED)
5197         {
5198           /* This won't actually modify the breakpoint list, but will
5199              physically remove the breakpoints from the child.  */
5200           detach_breakpoints (ecs->ws.value.related_pid);
5201         }
5202
5203       delete_just_stopped_threads_single_step_breakpoints ();
5204
5205       /* In case the event is caught by a catchpoint, remember that
5206          the event is to be followed at the next resume of the thread,
5207          and not immediately.  */
5208       ecs->event_thread->pending_follow = ecs->ws;
5209
5210       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
5211
5212       ecs->event_thread->control.stop_bpstat
5213         = bpstat_stop_status (get_current_regcache ()->aspace (),
5214                               stop_pc, ecs->ptid, &ecs->ws);
5215
5216       if (handle_stop_requested (ecs))
5217         return;
5218
5219       /* If no catchpoint triggered for this, then keep going.  Note
5220          that we're interested in knowing the bpstat actually causes a
5221          stop, not just if it may explain the signal.  Software
5222          watchpoints, for example, always appear in the bpstat.  */
5223       if (!bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5224         {
5225           ptid_t parent;
5226           ptid_t child;
5227           int should_resume;
5228           int follow_child
5229             = (follow_fork_mode_string == follow_fork_mode_child);
5230
5231           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5232
5233           should_resume = follow_fork ();
5234
5235           parent = ecs->ptid;
5236           child = ecs->ws.value.related_pid;
5237
5238           /* At this point, the parent is marked running, and the
5239              child is marked stopped.  */
5240
5241           /* If not resuming the parent, mark it stopped.  */
5242           if (follow_child && !detach_fork && !non_stop && !sched_multi)
5243             set_running (parent, 0);
5244
5245           /* If resuming the child, mark it running.  */
5246           if (follow_child || (!detach_fork && (non_stop || sched_multi)))
5247             set_running (child, 1);
5248
5249           /* In non-stop mode, also resume the other branch.  */
5250           if (!detach_fork && (non_stop
5251                                || (sched_multi && target_is_non_stop_p ())))
5252             {
5253               if (follow_child)
5254                 switch_to_thread (parent);
5255               else
5256                 switch_to_thread (child);
5257
5258               ecs->event_thread = inferior_thread ();
5259               ecs->ptid = inferior_ptid;
5260               keep_going (ecs);
5261             }
5262
5263           if (follow_child)
5264             switch_to_thread (child);
5265           else
5266             switch_to_thread (parent);
5267
5268           ecs->event_thread = inferior_thread ();
5269           ecs->ptid = inferior_ptid;
5270
5271           if (should_resume)
5272             keep_going (ecs);
5273           else
5274             stop_waiting (ecs);
5275           return;
5276         }
5277       process_event_stop_test (ecs);
5278       return;
5279
5280     case TARGET_WAITKIND_VFORK_DONE:
5281       /* Done with the shared memory region.  Re-insert breakpoints in
5282          the parent, and keep going.  */
5283
5284       if (debug_infrun)
5285         fprintf_unfiltered (gdb_stdlog,
5286                             "infrun: TARGET_WAITKIND_VFORK_DONE\n");
5287
5288       if (!ptid_equal (ecs->ptid, inferior_ptid))
5289         context_switch (ecs->ptid);
5290
5291       current_inferior ()->waiting_for_vfork_done = 0;
5292       current_inferior ()->pspace->breakpoints_not_allowed = 0;
5293
5294       if (handle_stop_requested (ecs))
5295         return;
5296
5297       /* This also takes care of reinserting breakpoints in the
5298          previously locked inferior.  */
5299       keep_going (ecs);
5300       return;
5301
5302     case TARGET_WAITKIND_EXECD:
5303       if (debug_infrun)
5304         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXECD\n");
5305
5306       /* Note we can't read registers yet (the stop_pc), because we
5307          don't yet know the inferior's post-exec architecture.
5308          'stop_pc' is explicitly read below instead.  */
5309       if (!ptid_equal (ecs->ptid, inferior_ptid))
5310         switch_to_thread_no_regs (ecs->event_thread);
5311
5312       /* Do whatever is necessary to the parent branch of the vfork.  */
5313       handle_vfork_child_exec_or_exit (1);
5314
5315       /* This causes the eventpoints and symbol table to be reset.
5316          Must do this now, before trying to determine whether to
5317          stop.  */
5318       follow_exec (inferior_ptid, ecs->ws.value.execd_pathname);
5319
5320       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
5321
5322       /* In follow_exec we may have deleted the original thread and
5323          created a new one.  Make sure that the event thread is the
5324          execd thread for that case (this is a nop otherwise).  */
5325       ecs->event_thread = inferior_thread ();
5326
5327       ecs->event_thread->control.stop_bpstat
5328         = bpstat_stop_status (get_current_regcache ()->aspace (),
5329                               stop_pc, ecs->ptid, &ecs->ws);
5330
5331       /* Note that this may be referenced from inside
5332          bpstat_stop_status above, through inferior_has_execd.  */
5333       xfree (ecs->ws.value.execd_pathname);
5334       ecs->ws.value.execd_pathname = NULL;
5335
5336       if (handle_stop_requested (ecs))
5337         return;
5338
5339       /* If no catchpoint triggered for this, then keep going.  */
5340       if (!bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5341         {
5342           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5343           keep_going (ecs);
5344           return;
5345         }
5346       process_event_stop_test (ecs);
5347       return;
5348
5349       /* Be careful not to try to gather much state about a thread
5350          that's in a syscall.  It's frequently a losing proposition.  */
5351     case TARGET_WAITKIND_SYSCALL_ENTRY:
5352       if (debug_infrun)
5353         fprintf_unfiltered (gdb_stdlog,
5354                             "infrun: TARGET_WAITKIND_SYSCALL_ENTRY\n");
5355       /* Getting the current syscall number.  */
5356       if (handle_syscall_event (ecs) == 0)
5357         process_event_stop_test (ecs);
5358       return;
5359
5360       /* Before examining the threads further, step this thread to
5361          get it entirely out of the syscall.  (We get notice of the
5362          event when the thread is just on the verge of exiting a
5363          syscall.  Stepping one instruction seems to get it back
5364          into user code.)  */
5365     case TARGET_WAITKIND_SYSCALL_RETURN:
5366       if (debug_infrun)
5367         fprintf_unfiltered (gdb_stdlog,
5368                             "infrun: TARGET_WAITKIND_SYSCALL_RETURN\n");
5369       if (handle_syscall_event (ecs) == 0)
5370         process_event_stop_test (ecs);
5371       return;
5372
5373     case TARGET_WAITKIND_STOPPED:
5374       if (debug_infrun)
5375         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_STOPPED\n");
5376       handle_signal_stop (ecs);
5377       return;
5378
5379     case TARGET_WAITKIND_NO_HISTORY:
5380       if (debug_infrun)
5381         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_NO_HISTORY\n");
5382       /* Reverse execution: target ran out of history info.  */
5383
5384       /* Switch to the stopped thread.  */
5385       if (!ptid_equal (ecs->ptid, inferior_ptid))
5386         context_switch (ecs->ptid);
5387       if (debug_infrun)
5388         fprintf_unfiltered (gdb_stdlog, "infrun: stopped\n");
5389
5390       delete_just_stopped_threads_single_step_breakpoints ();
5391       stop_pc = regcache_read_pc (get_thread_regcache (inferior_ptid));
5392
5393       if (handle_stop_requested (ecs))
5394         return;
5395
5396       observer_notify_no_history ();
5397       stop_waiting (ecs);
5398       return;
5399     }
5400 }
5401
5402 /* A wrapper around handle_inferior_event_1, which also makes sure
5403    that all temporary struct value objects that were created during
5404    the handling of the event get deleted at the end.  */
5405
5406 static void
5407 handle_inferior_event (struct execution_control_state *ecs)
5408 {
5409   struct value *mark = value_mark ();
5410
5411   handle_inferior_event_1 (ecs);
5412   /* Purge all temporary values created during the event handling,
5413      as it could be a long time before we return to the command level
5414      where such values would otherwise be purged.  */
5415   value_free_to_mark (mark);
5416 }
5417
5418 /* Restart threads back to what they were trying to do back when we
5419    paused them for an in-line step-over.  The EVENT_THREAD thread is
5420    ignored.  */
5421
5422 static void
5423 restart_threads (struct thread_info *event_thread)
5424 {
5425   struct thread_info *tp;
5426
5427   /* In case the instruction just stepped spawned a new thread.  */
5428   update_thread_list ();
5429
5430   ALL_NON_EXITED_THREADS (tp)
5431     {
5432       if (tp == event_thread)
5433         {
5434           if (debug_infrun)
5435             fprintf_unfiltered (gdb_stdlog,
5436                                 "infrun: restart threads: "
5437                                 "[%s] is event thread\n",
5438                                 target_pid_to_str (tp->ptid));
5439           continue;
5440         }
5441
5442       if (!(tp->state == THREAD_RUNNING || tp->control.in_infcall))
5443         {
5444           if (debug_infrun)
5445             fprintf_unfiltered (gdb_stdlog,
5446                                 "infrun: restart threads: "
5447                                 "[%s] not meant to be running\n",
5448                                 target_pid_to_str (tp->ptid));
5449           continue;
5450         }
5451
5452       if (tp->resumed)
5453         {
5454           if (debug_infrun)
5455             fprintf_unfiltered (gdb_stdlog,
5456                                 "infrun: restart threads: [%s] resumed\n",
5457                                 target_pid_to_str (tp->ptid));
5458           gdb_assert (tp->executing || tp->suspend.waitstatus_pending_p);
5459           continue;
5460         }
5461
5462       if (thread_is_in_step_over_chain (tp))
5463         {
5464           if (debug_infrun)
5465             fprintf_unfiltered (gdb_stdlog,
5466                                 "infrun: restart threads: "
5467                                 "[%s] needs step-over\n",
5468                                 target_pid_to_str (tp->ptid));
5469           gdb_assert (!tp->resumed);
5470           continue;
5471         }
5472
5473
5474       if (tp->suspend.waitstatus_pending_p)
5475         {
5476           if (debug_infrun)
5477             fprintf_unfiltered (gdb_stdlog,
5478                                 "infrun: restart threads: "
5479                                 "[%s] has pending status\n",
5480                                 target_pid_to_str (tp->ptid));
5481           tp->resumed = 1;
5482           continue;
5483         }
5484
5485       gdb_assert (!tp->stop_requested);
5486
5487       /* If some thread needs to start a step-over at this point, it
5488          should still be in the step-over queue, and thus skipped
5489          above.  */
5490       if (thread_still_needs_step_over (tp))
5491         {
5492           internal_error (__FILE__, __LINE__,
5493                           "thread [%s] needs a step-over, but not in "
5494                           "step-over queue\n",
5495                           target_pid_to_str (tp->ptid));
5496         }
5497
5498       if (currently_stepping (tp))
5499         {
5500           if (debug_infrun)
5501             fprintf_unfiltered (gdb_stdlog,
5502                                 "infrun: restart threads: [%s] was stepping\n",
5503                                 target_pid_to_str (tp->ptid));
5504           keep_going_stepped_thread (tp);
5505         }
5506       else
5507         {
5508           struct execution_control_state ecss;
5509           struct execution_control_state *ecs = &ecss;
5510
5511           if (debug_infrun)
5512             fprintf_unfiltered (gdb_stdlog,
5513                                 "infrun: restart threads: [%s] continuing\n",
5514                                 target_pid_to_str (tp->ptid));
5515           reset_ecs (ecs, tp);
5516           switch_to_thread (tp->ptid);
5517           keep_going_pass_signal (ecs);
5518         }
5519     }
5520 }
5521
5522 /* Callback for iterate_over_threads.  Find a resumed thread that has
5523    a pending waitstatus.  */
5524
5525 static int
5526 resumed_thread_with_pending_status (struct thread_info *tp,
5527                                     void *arg)
5528 {
5529   return (tp->resumed
5530           && tp->suspend.waitstatus_pending_p);
5531 }
5532
5533 /* Called when we get an event that may finish an in-line or
5534    out-of-line (displaced stepping) step-over started previously.
5535    Return true if the event is processed and we should go back to the
5536    event loop; false if the caller should continue processing the
5537    event.  */
5538
5539 static int
5540 finish_step_over (struct execution_control_state *ecs)
5541 {
5542   int had_step_over_info;
5543
5544   displaced_step_fixup (ecs->ptid,
5545                         ecs->event_thread->suspend.stop_signal);
5546
5547   had_step_over_info = step_over_info_valid_p ();
5548
5549   if (had_step_over_info)
5550     {
5551       /* If we're stepping over a breakpoint with all threads locked,
5552          then only the thread that was stepped should be reporting
5553          back an event.  */
5554       gdb_assert (ecs->event_thread->control.trap_expected);
5555
5556       clear_step_over_info ();
5557     }
5558
5559   if (!target_is_non_stop_p ())
5560     return 0;
5561
5562   /* Start a new step-over in another thread if there's one that
5563      needs it.  */
5564   start_step_over ();
5565
5566   /* If we were stepping over a breakpoint before, and haven't started
5567      a new in-line step-over sequence, then restart all other threads
5568      (except the event thread).  We can't do this in all-stop, as then
5569      e.g., we wouldn't be able to issue any other remote packet until
5570      these other threads stop.  */
5571   if (had_step_over_info && !step_over_info_valid_p ())
5572     {
5573       struct thread_info *pending;
5574
5575       /* If we only have threads with pending statuses, the restart
5576          below won't restart any thread and so nothing re-inserts the
5577          breakpoint we just stepped over.  But we need it inserted
5578          when we later process the pending events, otherwise if
5579          another thread has a pending event for this breakpoint too,
5580          we'd discard its event (because the breakpoint that
5581          originally caused the event was no longer inserted).  */
5582       context_switch (ecs->ptid);
5583       insert_breakpoints ();
5584
5585       restart_threads (ecs->event_thread);
5586
5587       /* If we have events pending, go through handle_inferior_event
5588          again, picking up a pending event at random.  This avoids
5589          thread starvation.  */
5590
5591       /* But not if we just stepped over a watchpoint in order to let
5592          the instruction execute so we can evaluate its expression.
5593          The set of watchpoints that triggered is recorded in the
5594          breakpoint objects themselves (see bp->watchpoint_triggered).
5595          If we processed another event first, that other event could
5596          clobber this info.  */
5597       if (ecs->event_thread->stepping_over_watchpoint)
5598         return 0;
5599
5600       pending = iterate_over_threads (resumed_thread_with_pending_status,
5601                                       NULL);
5602       if (pending != NULL)
5603         {
5604           struct thread_info *tp = ecs->event_thread;
5605           struct regcache *regcache;
5606
5607           if (debug_infrun)
5608             {
5609               fprintf_unfiltered (gdb_stdlog,
5610                                   "infrun: found resumed threads with "
5611                                   "pending events, saving status\n");
5612             }
5613
5614           gdb_assert (pending != tp);
5615
5616           /* Record the event thread's event for later.  */
5617           save_waitstatus (tp, &ecs->ws);
5618           /* This was cleared early, by handle_inferior_event.  Set it
5619              so this pending event is considered by
5620              do_target_wait.  */
5621           tp->resumed = 1;
5622
5623           gdb_assert (!tp->executing);
5624
5625           regcache = get_thread_regcache (tp->ptid);
5626           tp->suspend.stop_pc = regcache_read_pc (regcache);
5627
5628           if (debug_infrun)
5629             {
5630               fprintf_unfiltered (gdb_stdlog,
5631                                   "infrun: saved stop_pc=%s for %s "
5632                                   "(currently_stepping=%d)\n",
5633                                   paddress (target_gdbarch (),
5634                                             tp->suspend.stop_pc),
5635                                   target_pid_to_str (tp->ptid),
5636                                   currently_stepping (tp));
5637             }
5638
5639           /* This in-line step-over finished; clear this so we won't
5640              start a new one.  This is what handle_signal_stop would
5641              do, if we returned false.  */
5642           tp->stepping_over_breakpoint = 0;
5643
5644           /* Wake up the event loop again.  */
5645           mark_async_event_handler (infrun_async_inferior_event_token);
5646
5647           prepare_to_wait (ecs);
5648           return 1;
5649         }
5650     }
5651
5652   return 0;
5653 }
5654
5655 /* Come here when the program has stopped with a signal.  */
5656
5657 static void
5658 handle_signal_stop (struct execution_control_state *ecs)
5659 {
5660   struct frame_info *frame;
5661   struct gdbarch *gdbarch;
5662   int stopped_by_watchpoint;
5663   enum stop_kind stop_soon;
5664   int random_signal;
5665
5666   gdb_assert (ecs->ws.kind == TARGET_WAITKIND_STOPPED);
5667
5668   ecs->event_thread->suspend.stop_signal = ecs->ws.value.sig;
5669
5670   /* Do we need to clean up the state of a thread that has
5671      completed a displaced single-step?  (Doing so usually affects
5672      the PC, so do it here, before we set stop_pc.)  */
5673   if (finish_step_over (ecs))
5674     return;
5675
5676   /* If we either finished a single-step or hit a breakpoint, but
5677      the user wanted this thread to be stopped, pretend we got a
5678      SIG0 (generic unsignaled stop).  */
5679   if (ecs->event_thread->stop_requested
5680       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
5681     ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5682
5683   stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
5684
5685   if (debug_infrun)
5686     {
5687       struct regcache *regcache = get_thread_regcache (ecs->ptid);
5688       struct gdbarch *gdbarch = regcache->arch ();
5689       scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
5690
5691       inferior_ptid = ecs->ptid;
5692
5693       fprintf_unfiltered (gdb_stdlog, "infrun: stop_pc = %s\n",
5694                           paddress (gdbarch, stop_pc));
5695       if (target_stopped_by_watchpoint ())
5696         {
5697           CORE_ADDR addr;
5698
5699           fprintf_unfiltered (gdb_stdlog, "infrun: stopped by watchpoint\n");
5700
5701           if (target_stopped_data_address (&current_target, &addr))
5702             fprintf_unfiltered (gdb_stdlog,
5703                                 "infrun: stopped data address = %s\n",
5704                                 paddress (gdbarch, addr));
5705           else
5706             fprintf_unfiltered (gdb_stdlog,
5707                                 "infrun: (no data address available)\n");
5708         }
5709     }
5710
5711   /* This is originated from start_remote(), start_inferior() and
5712      shared libraries hook functions.  */
5713   stop_soon = get_inferior_stop_soon (ecs->ptid);
5714   if (stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_REMOTE)
5715     {
5716       if (!ptid_equal (ecs->ptid, inferior_ptid))
5717         context_switch (ecs->ptid);
5718       if (debug_infrun)
5719         fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
5720       stop_print_frame = 1;
5721       stop_waiting (ecs);
5722       return;
5723     }
5724
5725   /* This originates from attach_command().  We need to overwrite
5726      the stop_signal here, because some kernels don't ignore a
5727      SIGSTOP in a subsequent ptrace(PTRACE_CONT,SIGSTOP) call.
5728      See more comments in inferior.h.  On the other hand, if we
5729      get a non-SIGSTOP, report it to the user - assume the backend
5730      will handle the SIGSTOP if it should show up later.
5731
5732      Also consider that the attach is complete when we see a
5733      SIGTRAP.  Some systems (e.g. Windows), and stubs supporting
5734      target extended-remote report it instead of a SIGSTOP
5735      (e.g. gdbserver).  We already rely on SIGTRAP being our
5736      signal, so this is no exception.
5737
5738      Also consider that the attach is complete when we see a
5739      GDB_SIGNAL_0.  In non-stop mode, GDB will explicitly tell
5740      the target to stop all threads of the inferior, in case the
5741      low level attach operation doesn't stop them implicitly.  If
5742      they weren't stopped implicitly, then the stub will report a
5743      GDB_SIGNAL_0, meaning: stopped for no particular reason
5744      other than GDB's request.  */
5745   if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
5746       && (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_STOP
5747           || ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5748           || ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_0))
5749     {
5750       stop_print_frame = 1;
5751       stop_waiting (ecs);
5752       ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5753       return;
5754     }
5755
5756   /* See if something interesting happened to the non-current thread.  If
5757      so, then switch to that thread.  */
5758   if (!ptid_equal (ecs->ptid, inferior_ptid))
5759     {
5760       if (debug_infrun)
5761         fprintf_unfiltered (gdb_stdlog, "infrun: context switch\n");
5762
5763       context_switch (ecs->ptid);
5764
5765       if (deprecated_context_hook)
5766         deprecated_context_hook (ptid_to_global_thread_id (ecs->ptid));
5767     }
5768
5769   /* At this point, get hold of the now-current thread's frame.  */
5770   frame = get_current_frame ();
5771   gdbarch = get_frame_arch (frame);
5772
5773   /* Pull the single step breakpoints out of the target.  */
5774   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
5775     {
5776       struct regcache *regcache;
5777       CORE_ADDR pc;
5778
5779       regcache = get_thread_regcache (ecs->ptid);
5780       const address_space *aspace = regcache->aspace ();
5781
5782       pc = regcache_read_pc (regcache);
5783
5784       /* However, before doing so, if this single-step breakpoint was
5785          actually for another thread, set this thread up for moving
5786          past it.  */
5787       if (!thread_has_single_step_breakpoint_here (ecs->event_thread,
5788                                                    aspace, pc))
5789         {
5790           if (single_step_breakpoint_inserted_here_p (aspace, pc))
5791             {
5792               if (debug_infrun)
5793                 {
5794                   fprintf_unfiltered (gdb_stdlog,
5795                                       "infrun: [%s] hit another thread's "
5796                                       "single-step breakpoint\n",
5797                                       target_pid_to_str (ecs->ptid));
5798                 }
5799               ecs->hit_singlestep_breakpoint = 1;
5800             }
5801         }
5802       else
5803         {
5804           if (debug_infrun)
5805             {
5806               fprintf_unfiltered (gdb_stdlog,
5807                                   "infrun: [%s] hit its "
5808                                   "single-step breakpoint\n",
5809                                   target_pid_to_str (ecs->ptid));
5810             }
5811         }
5812     }
5813   delete_just_stopped_threads_single_step_breakpoints ();
5814
5815   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5816       && ecs->event_thread->control.trap_expected
5817       && ecs->event_thread->stepping_over_watchpoint)
5818     stopped_by_watchpoint = 0;
5819   else
5820     stopped_by_watchpoint = watchpoints_triggered (&ecs->ws);
5821
5822   /* If necessary, step over this watchpoint.  We'll be back to display
5823      it in a moment.  */
5824   if (stopped_by_watchpoint
5825       && (target_have_steppable_watchpoint
5826           || gdbarch_have_nonsteppable_watchpoint (gdbarch)))
5827     {
5828       /* At this point, we are stopped at an instruction which has
5829          attempted to write to a piece of memory under control of
5830          a watchpoint.  The instruction hasn't actually executed
5831          yet.  If we were to evaluate the watchpoint expression
5832          now, we would get the old value, and therefore no change
5833          would seem to have occurred.
5834
5835          In order to make watchpoints work `right', we really need
5836          to complete the memory write, and then evaluate the
5837          watchpoint expression.  We do this by single-stepping the
5838          target.
5839
5840          It may not be necessary to disable the watchpoint to step over
5841          it.  For example, the PA can (with some kernel cooperation)
5842          single step over a watchpoint without disabling the watchpoint.
5843
5844          It is far more common to need to disable a watchpoint to step
5845          the inferior over it.  If we have non-steppable watchpoints,
5846          we must disable the current watchpoint; it's simplest to
5847          disable all watchpoints.
5848
5849          Any breakpoint at PC must also be stepped over -- if there's
5850          one, it will have already triggered before the watchpoint
5851          triggered, and we either already reported it to the user, or
5852          it didn't cause a stop and we called keep_going.  In either
5853          case, if there was a breakpoint at PC, we must be trying to
5854          step past it.  */
5855       ecs->event_thread->stepping_over_watchpoint = 1;
5856       keep_going (ecs);
5857       return;
5858     }
5859
5860   ecs->event_thread->stepping_over_breakpoint = 0;
5861   ecs->event_thread->stepping_over_watchpoint = 0;
5862   bpstat_clear (&ecs->event_thread->control.stop_bpstat);
5863   ecs->event_thread->control.stop_step = 0;
5864   stop_print_frame = 1;
5865   stopped_by_random_signal = 0;
5866
5867   /* Hide inlined functions starting here, unless we just performed stepi or
5868      nexti.  After stepi and nexti, always show the innermost frame (not any
5869      inline function call sites).  */
5870   if (ecs->event_thread->control.step_range_end != 1)
5871     {
5872       const address_space *aspace =
5873         get_thread_regcache (ecs->ptid)->aspace ();
5874
5875       /* skip_inline_frames is expensive, so we avoid it if we can
5876          determine that the address is one where functions cannot have
5877          been inlined.  This improves performance with inferiors that
5878          load a lot of shared libraries, because the solib event
5879          breakpoint is defined as the address of a function (i.e. not
5880          inline).  Note that we have to check the previous PC as well
5881          as the current one to catch cases when we have just
5882          single-stepped off a breakpoint prior to reinstating it.
5883          Note that we're assuming that the code we single-step to is
5884          not inline, but that's not definitive: there's nothing
5885          preventing the event breakpoint function from containing
5886          inlined code, and the single-step ending up there.  If the
5887          user had set a breakpoint on that inlined code, the missing
5888          skip_inline_frames call would break things.  Fortunately
5889          that's an extremely unlikely scenario.  */
5890       if (!pc_at_non_inline_function (aspace, stop_pc, &ecs->ws)
5891           && !(ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5892                && ecs->event_thread->control.trap_expected
5893                && pc_at_non_inline_function (aspace,
5894                                              ecs->event_thread->prev_pc,
5895                                              &ecs->ws)))
5896         {
5897           skip_inline_frames (ecs->ptid);
5898
5899           /* Re-fetch current thread's frame in case that invalidated
5900              the frame cache.  */
5901           frame = get_current_frame ();
5902           gdbarch = get_frame_arch (frame);
5903         }
5904     }
5905
5906   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5907       && ecs->event_thread->control.trap_expected
5908       && gdbarch_single_step_through_delay_p (gdbarch)
5909       && currently_stepping (ecs->event_thread))
5910     {
5911       /* We're trying to step off a breakpoint.  Turns out that we're
5912          also on an instruction that needs to be stepped multiple
5913          times before it's been fully executing.  E.g., architectures
5914          with a delay slot.  It needs to be stepped twice, once for
5915          the instruction and once for the delay slot.  */
5916       int step_through_delay
5917         = gdbarch_single_step_through_delay (gdbarch, frame);
5918
5919       if (debug_infrun && step_through_delay)
5920         fprintf_unfiltered (gdb_stdlog, "infrun: step through delay\n");
5921       if (ecs->event_thread->control.step_range_end == 0
5922           && step_through_delay)
5923         {
5924           /* The user issued a continue when stopped at a breakpoint.
5925              Set up for another trap and get out of here.  */
5926          ecs->event_thread->stepping_over_breakpoint = 1;
5927          keep_going (ecs);
5928          return;
5929         }
5930       else if (step_through_delay)
5931         {
5932           /* The user issued a step when stopped at a breakpoint.
5933              Maybe we should stop, maybe we should not - the delay
5934              slot *might* correspond to a line of source.  In any
5935              case, don't decide that here, just set 
5936              ecs->stepping_over_breakpoint, making sure we 
5937              single-step again before breakpoints are re-inserted.  */
5938           ecs->event_thread->stepping_over_breakpoint = 1;
5939         }
5940     }
5941
5942   /* See if there is a breakpoint/watchpoint/catchpoint/etc. that
5943      handles this event.  */
5944   ecs->event_thread->control.stop_bpstat
5945     = bpstat_stop_status (get_current_regcache ()->aspace (),
5946                           stop_pc, ecs->ptid, &ecs->ws);
5947
5948   /* Following in case break condition called a
5949      function.  */
5950   stop_print_frame = 1;
5951
5952   /* This is where we handle "moribund" watchpoints.  Unlike
5953      software breakpoints traps, hardware watchpoint traps are
5954      always distinguishable from random traps.  If no high-level
5955      watchpoint is associated with the reported stop data address
5956      anymore, then the bpstat does not explain the signal ---
5957      simply make sure to ignore it if `stopped_by_watchpoint' is
5958      set.  */
5959
5960   if (debug_infrun
5961       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5962       && !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat,
5963                                   GDB_SIGNAL_TRAP)
5964       && stopped_by_watchpoint)
5965     fprintf_unfiltered (gdb_stdlog,
5966                         "infrun: no user watchpoint explains "
5967                         "watchpoint SIGTRAP, ignoring\n");
5968
5969   /* NOTE: cagney/2003-03-29: These checks for a random signal
5970      at one stage in the past included checks for an inferior
5971      function call's call dummy's return breakpoint.  The original
5972      comment, that went with the test, read:
5973
5974      ``End of a stack dummy.  Some systems (e.g. Sony news) give
5975      another signal besides SIGTRAP, so check here as well as
5976      above.''
5977
5978      If someone ever tries to get call dummys on a
5979      non-executable stack to work (where the target would stop
5980      with something like a SIGSEGV), then those tests might need
5981      to be re-instated.  Given, however, that the tests were only
5982      enabled when momentary breakpoints were not being used, I
5983      suspect that it won't be the case.
5984
5985      NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
5986      be necessary for call dummies on a non-executable stack on
5987      SPARC.  */
5988
5989   /* See if the breakpoints module can explain the signal.  */
5990   random_signal
5991     = !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat,
5992                                ecs->event_thread->suspend.stop_signal);
5993
5994   /* Maybe this was a trap for a software breakpoint that has since
5995      been removed.  */
5996   if (random_signal && target_stopped_by_sw_breakpoint ())
5997     {
5998       if (program_breakpoint_here_p (gdbarch, stop_pc))
5999         {
6000           struct regcache *regcache;
6001           int decr_pc;
6002
6003           /* Re-adjust PC to what the program would see if GDB was not
6004              debugging it.  */
6005           regcache = get_thread_regcache (ecs->event_thread->ptid);
6006           decr_pc = gdbarch_decr_pc_after_break (gdbarch);
6007           if (decr_pc != 0)
6008             {
6009               gdb::optional<scoped_restore_tmpl<int>>
6010                 restore_operation_disable;
6011
6012               if (record_full_is_used ())
6013                 restore_operation_disable.emplace
6014                   (record_full_gdb_operation_disable_set ());
6015
6016               regcache_write_pc (regcache, stop_pc + decr_pc);
6017             }
6018         }
6019       else
6020         {
6021           /* A delayed software breakpoint event.  Ignore the trap.  */
6022           if (debug_infrun)
6023             fprintf_unfiltered (gdb_stdlog,
6024                                 "infrun: delayed software breakpoint "
6025                                 "trap, ignoring\n");
6026           random_signal = 0;
6027         }
6028     }
6029
6030   /* Maybe this was a trap for a hardware breakpoint/watchpoint that
6031      has since been removed.  */
6032   if (random_signal && target_stopped_by_hw_breakpoint ())
6033     {
6034       /* A delayed hardware breakpoint event.  Ignore the trap.  */
6035       if (debug_infrun)
6036         fprintf_unfiltered (gdb_stdlog,
6037                             "infrun: delayed hardware breakpoint/watchpoint "
6038                             "trap, ignoring\n");
6039       random_signal = 0;
6040     }
6041
6042   /* If not, perhaps stepping/nexting can.  */
6043   if (random_signal)
6044     random_signal = !(ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
6045                       && currently_stepping (ecs->event_thread));
6046
6047   /* Perhaps the thread hit a single-step breakpoint of _another_
6048      thread.  Single-step breakpoints are transparent to the
6049      breakpoints module.  */
6050   if (random_signal)
6051     random_signal = !ecs->hit_singlestep_breakpoint;
6052
6053   /* No?  Perhaps we got a moribund watchpoint.  */
6054   if (random_signal)
6055     random_signal = !stopped_by_watchpoint;
6056
6057   /* Always stop if the user explicitly requested this thread to
6058      remain stopped.  */
6059   if (ecs->event_thread->stop_requested)
6060     {
6061       random_signal = 1;
6062       if (debug_infrun)
6063         fprintf_unfiltered (gdb_stdlog, "infrun: user-requested stop\n");
6064     }
6065
6066   /* For the program's own signals, act according to
6067      the signal handling tables.  */
6068
6069   if (random_signal)
6070     {
6071       /* Signal not for debugging purposes.  */
6072       struct inferior *inf = find_inferior_ptid (ecs->ptid);
6073       enum gdb_signal stop_signal = ecs->event_thread->suspend.stop_signal;
6074
6075       if (debug_infrun)
6076          fprintf_unfiltered (gdb_stdlog, "infrun: random signal (%s)\n",
6077                              gdb_signal_to_symbol_string (stop_signal));
6078
6079       stopped_by_random_signal = 1;
6080
6081       /* Always stop on signals if we're either just gaining control
6082          of the program, or the user explicitly requested this thread
6083          to remain stopped.  */
6084       if (stop_soon != NO_STOP_QUIETLY
6085           || ecs->event_thread->stop_requested
6086           || (!inf->detaching
6087               && signal_stop_state (ecs->event_thread->suspend.stop_signal)))
6088         {
6089           stop_waiting (ecs);
6090           return;
6091         }
6092
6093       /* Notify observers the signal has "handle print" set.  Note we
6094          returned early above if stopping; normal_stop handles the
6095          printing in that case.  */
6096       if (signal_print[ecs->event_thread->suspend.stop_signal])
6097         {
6098           /* The signal table tells us to print about this signal.  */
6099           target_terminal::ours_for_output ();
6100           observer_notify_signal_received (ecs->event_thread->suspend.stop_signal);
6101           target_terminal::inferior ();
6102         }
6103
6104       /* Clear the signal if it should not be passed.  */
6105       if (signal_program[ecs->event_thread->suspend.stop_signal] == 0)
6106         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
6107
6108       if (ecs->event_thread->prev_pc == stop_pc
6109           && ecs->event_thread->control.trap_expected
6110           && ecs->event_thread->control.step_resume_breakpoint == NULL)
6111         {
6112           /* We were just starting a new sequence, attempting to
6113              single-step off of a breakpoint and expecting a SIGTRAP.
6114              Instead this signal arrives.  This signal will take us out
6115              of the stepping range so GDB needs to remember to, when
6116              the signal handler returns, resume stepping off that
6117              breakpoint.  */
6118           /* To simplify things, "continue" is forced to use the same
6119              code paths as single-step - set a breakpoint at the
6120              signal return address and then, once hit, step off that
6121              breakpoint.  */
6122           if (debug_infrun)
6123             fprintf_unfiltered (gdb_stdlog,
6124                                 "infrun: signal arrived while stepping over "
6125                                 "breakpoint\n");
6126
6127           insert_hp_step_resume_breakpoint_at_frame (frame);
6128           ecs->event_thread->step_after_step_resume_breakpoint = 1;
6129           /* Reset trap_expected to ensure breakpoints are re-inserted.  */
6130           ecs->event_thread->control.trap_expected = 0;
6131
6132           /* If we were nexting/stepping some other thread, switch to
6133              it, so that we don't continue it, losing control.  */
6134           if (!switch_back_to_stepped_thread (ecs))
6135             keep_going (ecs);
6136           return;
6137         }
6138
6139       if (ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_0
6140           && (pc_in_thread_step_range (stop_pc, ecs->event_thread)
6141               || ecs->event_thread->control.step_range_end == 1)
6142           && frame_id_eq (get_stack_frame_id (frame),
6143                           ecs->event_thread->control.step_stack_frame_id)
6144           && ecs->event_thread->control.step_resume_breakpoint == NULL)
6145         {
6146           /* The inferior is about to take a signal that will take it
6147              out of the single step range.  Set a breakpoint at the
6148              current PC (which is presumably where the signal handler
6149              will eventually return) and then allow the inferior to
6150              run free.
6151
6152              Note that this is only needed for a signal delivered
6153              while in the single-step range.  Nested signals aren't a
6154              problem as they eventually all return.  */
6155           if (debug_infrun)
6156             fprintf_unfiltered (gdb_stdlog,
6157                                 "infrun: signal may take us out of "
6158                                 "single-step range\n");
6159
6160           clear_step_over_info ();
6161           insert_hp_step_resume_breakpoint_at_frame (frame);
6162           ecs->event_thread->step_after_step_resume_breakpoint = 1;
6163           /* Reset trap_expected to ensure breakpoints are re-inserted.  */
6164           ecs->event_thread->control.trap_expected = 0;
6165           keep_going (ecs);
6166           return;
6167         }
6168
6169       /* Note: step_resume_breakpoint may be non-NULL.  This occures
6170          when either there's a nested signal, or when there's a
6171          pending signal enabled just as the signal handler returns
6172          (leaving the inferior at the step-resume-breakpoint without
6173          actually executing it).  Either way continue until the
6174          breakpoint is really hit.  */
6175
6176       if (!switch_back_to_stepped_thread (ecs))
6177         {
6178           if (debug_infrun)
6179             fprintf_unfiltered (gdb_stdlog,
6180                                 "infrun: random signal, keep going\n");
6181
6182           keep_going (ecs);
6183         }
6184       return;
6185     }
6186
6187   process_event_stop_test (ecs);
6188 }
6189
6190 /* Come here when we've got some debug event / signal we can explain
6191    (IOW, not a random signal), and test whether it should cause a
6192    stop, or whether we should resume the inferior (transparently).
6193    E.g., could be a breakpoint whose condition evaluates false; we
6194    could be still stepping within the line; etc.  */
6195
6196 static void
6197 process_event_stop_test (struct execution_control_state *ecs)
6198 {
6199   struct symtab_and_line stop_pc_sal;
6200   struct frame_info *frame;
6201   struct gdbarch *gdbarch;
6202   CORE_ADDR jmp_buf_pc;
6203   struct bpstat_what what;
6204
6205   /* Handle cases caused by hitting a breakpoint.  */
6206
6207   frame = get_current_frame ();
6208   gdbarch = get_frame_arch (frame);
6209
6210   what = bpstat_what (ecs->event_thread->control.stop_bpstat);
6211
6212   if (what.call_dummy)
6213     {
6214       stop_stack_dummy = what.call_dummy;
6215     }
6216
6217   /* A few breakpoint types have callbacks associated (e.g.,
6218      bp_jit_event).  Run them now.  */
6219   bpstat_run_callbacks (ecs->event_thread->control.stop_bpstat);
6220
6221   /* If we hit an internal event that triggers symbol changes, the
6222      current frame will be invalidated within bpstat_what (e.g., if we
6223      hit an internal solib event).  Re-fetch it.  */
6224   frame = get_current_frame ();
6225   gdbarch = get_frame_arch (frame);
6226
6227   switch (what.main_action)
6228     {
6229     case BPSTAT_WHAT_SET_LONGJMP_RESUME:
6230       /* If we hit the breakpoint at longjmp while stepping, we
6231          install a momentary breakpoint at the target of the
6232          jmp_buf.  */
6233
6234       if (debug_infrun)
6235         fprintf_unfiltered (gdb_stdlog,
6236                             "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME\n");
6237
6238       ecs->event_thread->stepping_over_breakpoint = 1;
6239
6240       if (what.is_longjmp)
6241         {
6242           struct value *arg_value;
6243
6244           /* If we set the longjmp breakpoint via a SystemTap probe,
6245              then use it to extract the arguments.  The destination PC
6246              is the third argument to the probe.  */
6247           arg_value = probe_safe_evaluate_at_pc (frame, 2);
6248           if (arg_value)
6249             {
6250               jmp_buf_pc = value_as_address (arg_value);
6251               jmp_buf_pc = gdbarch_addr_bits_remove (gdbarch, jmp_buf_pc);
6252             }
6253           else if (!gdbarch_get_longjmp_target_p (gdbarch)
6254                    || !gdbarch_get_longjmp_target (gdbarch,
6255                                                    frame, &jmp_buf_pc))
6256             {
6257               if (debug_infrun)
6258                 fprintf_unfiltered (gdb_stdlog,
6259                                     "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME "
6260                                     "(!gdbarch_get_longjmp_target)\n");
6261               keep_going (ecs);
6262               return;
6263             }
6264
6265           /* Insert a breakpoint at resume address.  */
6266           insert_longjmp_resume_breakpoint (gdbarch, jmp_buf_pc);
6267         }
6268       else
6269         check_exception_resume (ecs, frame);
6270       keep_going (ecs);
6271       return;
6272
6273     case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
6274       {
6275         struct frame_info *init_frame;
6276
6277         /* There are several cases to consider.
6278
6279            1. The initiating frame no longer exists.  In this case we
6280            must stop, because the exception or longjmp has gone too
6281            far.
6282
6283            2. The initiating frame exists, and is the same as the
6284            current frame.  We stop, because the exception or longjmp
6285            has been caught.
6286
6287            3. The initiating frame exists and is different from the
6288            current frame.  This means the exception or longjmp has
6289            been caught beneath the initiating frame, so keep going.
6290
6291            4. longjmp breakpoint has been placed just to protect
6292            against stale dummy frames and user is not interested in
6293            stopping around longjmps.  */
6294
6295         if (debug_infrun)
6296           fprintf_unfiltered (gdb_stdlog,
6297                               "infrun: BPSTAT_WHAT_CLEAR_LONGJMP_RESUME\n");
6298
6299         gdb_assert (ecs->event_thread->control.exception_resume_breakpoint
6300                     != NULL);
6301         delete_exception_resume_breakpoint (ecs->event_thread);
6302
6303         if (what.is_longjmp)
6304           {
6305             check_longjmp_breakpoint_for_call_dummy (ecs->event_thread);
6306
6307             if (!frame_id_p (ecs->event_thread->initiating_frame))
6308               {
6309                 /* Case 4.  */
6310                 keep_going (ecs);
6311                 return;
6312               }
6313           }
6314
6315         init_frame = frame_find_by_id (ecs->event_thread->initiating_frame);
6316
6317         if (init_frame)
6318           {
6319             struct frame_id current_id
6320               = get_frame_id (get_current_frame ());
6321             if (frame_id_eq (current_id,
6322                              ecs->event_thread->initiating_frame))
6323               {
6324                 /* Case 2.  Fall through.  */
6325               }
6326             else
6327               {
6328                 /* Case 3.  */
6329                 keep_going (ecs);
6330                 return;
6331               }
6332           }
6333
6334         /* For Cases 1 and 2, remove the step-resume breakpoint, if it
6335            exists.  */
6336         delete_step_resume_breakpoint (ecs->event_thread);
6337
6338         end_stepping_range (ecs);
6339       }
6340       return;
6341
6342     case BPSTAT_WHAT_SINGLE:
6343       if (debug_infrun)
6344         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_SINGLE\n");
6345       ecs->event_thread->stepping_over_breakpoint = 1;
6346       /* Still need to check other stuff, at least the case where we
6347          are stepping and step out of the right range.  */
6348       break;
6349
6350     case BPSTAT_WHAT_STEP_RESUME:
6351       if (debug_infrun)
6352         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STEP_RESUME\n");
6353
6354       delete_step_resume_breakpoint (ecs->event_thread);
6355       if (ecs->event_thread->control.proceed_to_finish
6356           && execution_direction == EXEC_REVERSE)
6357         {
6358           struct thread_info *tp = ecs->event_thread;
6359
6360           /* We are finishing a function in reverse, and just hit the
6361              step-resume breakpoint at the start address of the
6362              function, and we're almost there -- just need to back up
6363              by one more single-step, which should take us back to the
6364              function call.  */
6365           tp->control.step_range_start = tp->control.step_range_end = 1;
6366           keep_going (ecs);
6367           return;
6368         }
6369       fill_in_stop_func (gdbarch, ecs);
6370       if (stop_pc == ecs->stop_func_start
6371           && execution_direction == EXEC_REVERSE)
6372         {
6373           /* We are stepping over a function call in reverse, and just
6374              hit the step-resume breakpoint at the start address of
6375              the function.  Go back to single-stepping, which should
6376              take us back to the function call.  */
6377           ecs->event_thread->stepping_over_breakpoint = 1;
6378           keep_going (ecs);
6379           return;
6380         }
6381       break;
6382
6383     case BPSTAT_WHAT_STOP_NOISY:
6384       if (debug_infrun)
6385         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_NOISY\n");
6386       stop_print_frame = 1;
6387
6388       /* Assume the thread stopped for a breapoint.  We'll still check
6389          whether a/the breakpoint is there when the thread is next
6390          resumed.  */
6391       ecs->event_thread->stepping_over_breakpoint = 1;
6392
6393       stop_waiting (ecs);
6394       return;
6395
6396     case BPSTAT_WHAT_STOP_SILENT:
6397       if (debug_infrun)
6398         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_SILENT\n");
6399       stop_print_frame = 0;
6400
6401       /* Assume the thread stopped for a breapoint.  We'll still check
6402          whether a/the breakpoint is there when the thread is next
6403          resumed.  */
6404       ecs->event_thread->stepping_over_breakpoint = 1;
6405       stop_waiting (ecs);
6406       return;
6407
6408     case BPSTAT_WHAT_HP_STEP_RESUME:
6409       if (debug_infrun)
6410         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_HP_STEP_RESUME\n");
6411
6412       delete_step_resume_breakpoint (ecs->event_thread);
6413       if (ecs->event_thread->step_after_step_resume_breakpoint)
6414         {
6415           /* Back when the step-resume breakpoint was inserted, we
6416              were trying to single-step off a breakpoint.  Go back to
6417              doing that.  */
6418           ecs->event_thread->step_after_step_resume_breakpoint = 0;
6419           ecs->event_thread->stepping_over_breakpoint = 1;
6420           keep_going (ecs);
6421           return;
6422         }
6423       break;
6424
6425     case BPSTAT_WHAT_KEEP_CHECKING:
6426       break;
6427     }
6428
6429   /* If we stepped a permanent breakpoint and we had a high priority
6430      step-resume breakpoint for the address we stepped, but we didn't
6431      hit it, then we must have stepped into the signal handler.  The
6432      step-resume was only necessary to catch the case of _not_
6433      stepping into the handler, so delete it, and fall through to
6434      checking whether the step finished.  */
6435   if (ecs->event_thread->stepped_breakpoint)
6436     {
6437       struct breakpoint *sr_bp
6438         = ecs->event_thread->control.step_resume_breakpoint;
6439
6440       if (sr_bp != NULL
6441           && sr_bp->loc->permanent
6442           && sr_bp->type == bp_hp_step_resume
6443           && sr_bp->loc->address == ecs->event_thread->prev_pc)
6444         {
6445           if (debug_infrun)
6446             fprintf_unfiltered (gdb_stdlog,
6447                                 "infrun: stepped permanent breakpoint, stopped in "
6448                                 "handler\n");
6449           delete_step_resume_breakpoint (ecs->event_thread);
6450           ecs->event_thread->step_after_step_resume_breakpoint = 0;
6451         }
6452     }
6453
6454   /* We come here if we hit a breakpoint but should not stop for it.
6455      Possibly we also were stepping and should stop for that.  So fall
6456      through and test for stepping.  But, if not stepping, do not
6457      stop.  */
6458
6459   /* In all-stop mode, if we're currently stepping but have stopped in
6460      some other thread, we need to switch back to the stepped thread.  */
6461   if (switch_back_to_stepped_thread (ecs))
6462     return;
6463
6464   if (ecs->event_thread->control.step_resume_breakpoint)
6465     {
6466       if (debug_infrun)
6467          fprintf_unfiltered (gdb_stdlog,
6468                              "infrun: step-resume breakpoint is inserted\n");
6469
6470       /* Having a step-resume breakpoint overrides anything
6471          else having to do with stepping commands until
6472          that breakpoint is reached.  */
6473       keep_going (ecs);
6474       return;
6475     }
6476
6477   if (ecs->event_thread->control.step_range_end == 0)
6478     {
6479       if (debug_infrun)
6480          fprintf_unfiltered (gdb_stdlog, "infrun: no stepping, continue\n");
6481       /* Likewise if we aren't even stepping.  */
6482       keep_going (ecs);
6483       return;
6484     }
6485
6486   /* Re-fetch current thread's frame in case the code above caused
6487      the frame cache to be re-initialized, making our FRAME variable
6488      a dangling pointer.  */
6489   frame = get_current_frame ();
6490   gdbarch = get_frame_arch (frame);
6491   fill_in_stop_func (gdbarch, ecs);
6492
6493   /* If stepping through a line, keep going if still within it.
6494
6495      Note that step_range_end is the address of the first instruction
6496      beyond the step range, and NOT the address of the last instruction
6497      within it!
6498
6499      Note also that during reverse execution, we may be stepping
6500      through a function epilogue and therefore must detect when
6501      the current-frame changes in the middle of a line.  */
6502
6503   if (pc_in_thread_step_range (stop_pc, ecs->event_thread)
6504       && (execution_direction != EXEC_REVERSE
6505           || frame_id_eq (get_frame_id (frame),
6506                           ecs->event_thread->control.step_frame_id)))
6507     {
6508       if (debug_infrun)
6509         fprintf_unfiltered
6510           (gdb_stdlog, "infrun: stepping inside range [%s-%s]\n",
6511            paddress (gdbarch, ecs->event_thread->control.step_range_start),
6512            paddress (gdbarch, ecs->event_thread->control.step_range_end));
6513
6514       /* Tentatively re-enable range stepping; `resume' disables it if
6515          necessary (e.g., if we're stepping over a breakpoint or we
6516          have software watchpoints).  */
6517       ecs->event_thread->control.may_range_step = 1;
6518
6519       /* When stepping backward, stop at beginning of line range
6520          (unless it's the function entry point, in which case
6521          keep going back to the call point).  */
6522       if (stop_pc == ecs->event_thread->control.step_range_start
6523           && stop_pc != ecs->stop_func_start
6524           && execution_direction == EXEC_REVERSE)
6525         end_stepping_range (ecs);
6526       else
6527         keep_going (ecs);
6528
6529       return;
6530     }
6531
6532   /* We stepped out of the stepping range.  */
6533
6534   /* If we are stepping at the source level and entered the runtime
6535      loader dynamic symbol resolution code...
6536
6537      EXEC_FORWARD: we keep on single stepping until we exit the run
6538      time loader code and reach the callee's address.
6539
6540      EXEC_REVERSE: we've already executed the callee (backward), and
6541      the runtime loader code is handled just like any other
6542      undebuggable function call.  Now we need only keep stepping
6543      backward through the trampoline code, and that's handled further
6544      down, so there is nothing for us to do here.  */
6545
6546   if (execution_direction != EXEC_REVERSE
6547       && ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6548       && in_solib_dynsym_resolve_code (stop_pc))
6549     {
6550       CORE_ADDR pc_after_resolver =
6551         gdbarch_skip_solib_resolver (gdbarch, stop_pc);
6552
6553       if (debug_infrun)
6554          fprintf_unfiltered (gdb_stdlog,
6555                              "infrun: stepped into dynsym resolve code\n");
6556
6557       if (pc_after_resolver)
6558         {
6559           /* Set up a step-resume breakpoint at the address
6560              indicated by SKIP_SOLIB_RESOLVER.  */
6561           symtab_and_line sr_sal;
6562           sr_sal.pc = pc_after_resolver;
6563           sr_sal.pspace = get_frame_program_space (frame);
6564
6565           insert_step_resume_breakpoint_at_sal (gdbarch,
6566                                                 sr_sal, null_frame_id);
6567         }
6568
6569       keep_going (ecs);
6570       return;
6571     }
6572
6573   if (ecs->event_thread->control.step_range_end != 1
6574       && (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6575           || ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6576       && get_frame_type (frame) == SIGTRAMP_FRAME)
6577     {
6578       if (debug_infrun)
6579          fprintf_unfiltered (gdb_stdlog,
6580                              "infrun: stepped into signal trampoline\n");
6581       /* The inferior, while doing a "step" or "next", has ended up in
6582          a signal trampoline (either by a signal being delivered or by
6583          the signal handler returning).  Just single-step until the
6584          inferior leaves the trampoline (either by calling the handler
6585          or returning).  */
6586       keep_going (ecs);
6587       return;
6588     }
6589
6590   /* If we're in the return path from a shared library trampoline,
6591      we want to proceed through the trampoline when stepping.  */
6592   /* macro/2012-04-25: This needs to come before the subroutine
6593      call check below as on some targets return trampolines look
6594      like subroutine calls (MIPS16 return thunks).  */
6595   if (gdbarch_in_solib_return_trampoline (gdbarch,
6596                                           stop_pc, ecs->stop_func_name)
6597       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
6598     {
6599       /* Determine where this trampoline returns.  */
6600       CORE_ADDR real_stop_pc;
6601
6602       real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
6603
6604       if (debug_infrun)
6605          fprintf_unfiltered (gdb_stdlog,
6606                              "infrun: stepped into solib return tramp\n");
6607
6608       /* Only proceed through if we know where it's going.  */
6609       if (real_stop_pc)
6610         {
6611           /* And put the step-breakpoint there and go until there.  */
6612           symtab_and_line sr_sal;
6613           sr_sal.pc = real_stop_pc;
6614           sr_sal.section = find_pc_overlay (sr_sal.pc);
6615           sr_sal.pspace = get_frame_program_space (frame);
6616
6617           /* Do not specify what the fp should be when we stop since
6618              on some machines the prologue is where the new fp value
6619              is established.  */
6620           insert_step_resume_breakpoint_at_sal (gdbarch,
6621                                                 sr_sal, null_frame_id);
6622
6623           /* Restart without fiddling with the step ranges or
6624              other state.  */
6625           keep_going (ecs);
6626           return;
6627         }
6628     }
6629
6630   /* Check for subroutine calls.  The check for the current frame
6631      equalling the step ID is not necessary - the check of the
6632      previous frame's ID is sufficient - but it is a common case and
6633      cheaper than checking the previous frame's ID.
6634
6635      NOTE: frame_id_eq will never report two invalid frame IDs as
6636      being equal, so to get into this block, both the current and
6637      previous frame must have valid frame IDs.  */
6638   /* The outer_frame_id check is a heuristic to detect stepping
6639      through startup code.  If we step over an instruction which
6640      sets the stack pointer from an invalid value to a valid value,
6641      we may detect that as a subroutine call from the mythical
6642      "outermost" function.  This could be fixed by marking
6643      outermost frames as !stack_p,code_p,special_p.  Then the
6644      initial outermost frame, before sp was valid, would
6645      have code_addr == &_start.  See the comment in frame_id_eq
6646      for more.  */
6647   if (!frame_id_eq (get_stack_frame_id (frame),
6648                     ecs->event_thread->control.step_stack_frame_id)
6649       && (frame_id_eq (frame_unwind_caller_id (get_current_frame ()),
6650                        ecs->event_thread->control.step_stack_frame_id)
6651           && (!frame_id_eq (ecs->event_thread->control.step_stack_frame_id,
6652                             outer_frame_id)
6653               || (ecs->event_thread->control.step_start_function
6654                   != find_pc_function (stop_pc)))))
6655     {
6656       CORE_ADDR real_stop_pc;
6657
6658       if (debug_infrun)
6659          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into subroutine\n");
6660
6661       if (ecs->event_thread->control.step_over_calls == STEP_OVER_NONE)
6662         {
6663           /* I presume that step_over_calls is only 0 when we're
6664              supposed to be stepping at the assembly language level
6665              ("stepi").  Just stop.  */
6666           /* And this works the same backward as frontward.  MVS */
6667           end_stepping_range (ecs);
6668           return;
6669         }
6670
6671       /* Reverse stepping through solib trampolines.  */
6672
6673       if (execution_direction == EXEC_REVERSE
6674           && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE
6675           && (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
6676               || (ecs->stop_func_start == 0
6677                   && in_solib_dynsym_resolve_code (stop_pc))))
6678         {
6679           /* Any solib trampoline code can be handled in reverse
6680              by simply continuing to single-step.  We have already
6681              executed the solib function (backwards), and a few 
6682              steps will take us back through the trampoline to the
6683              caller.  */
6684           keep_going (ecs);
6685           return;
6686         }
6687
6688       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6689         {
6690           /* We're doing a "next".
6691
6692              Normal (forward) execution: set a breakpoint at the
6693              callee's return address (the address at which the caller
6694              will resume).
6695
6696              Reverse (backward) execution.  set the step-resume
6697              breakpoint at the start of the function that we just
6698              stepped into (backwards), and continue to there.  When we
6699              get there, we'll need to single-step back to the caller.  */
6700
6701           if (execution_direction == EXEC_REVERSE)
6702             {
6703               /* If we're already at the start of the function, we've either
6704                  just stepped backward into a single instruction function,
6705                  or stepped back out of a signal handler to the first instruction
6706                  of the function.  Just keep going, which will single-step back
6707                  to the caller.  */
6708               if (ecs->stop_func_start != stop_pc && ecs->stop_func_start != 0)
6709                 {
6710                   /* Normal function call return (static or dynamic).  */
6711                   symtab_and_line sr_sal;
6712                   sr_sal.pc = ecs->stop_func_start;
6713                   sr_sal.pspace = get_frame_program_space (frame);
6714                   insert_step_resume_breakpoint_at_sal (gdbarch,
6715                                                         sr_sal, null_frame_id);
6716                 }
6717             }
6718           else
6719             insert_step_resume_breakpoint_at_caller (frame);
6720
6721           keep_going (ecs);
6722           return;
6723         }
6724
6725       /* If we are in a function call trampoline (a stub between the
6726          calling routine and the real function), locate the real
6727          function.  That's what tells us (a) whether we want to step
6728          into it at all, and (b) what prologue we want to run to the
6729          end of, if we do step into it.  */
6730       real_stop_pc = skip_language_trampoline (frame, stop_pc);
6731       if (real_stop_pc == 0)
6732         real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
6733       if (real_stop_pc != 0)
6734         ecs->stop_func_start = real_stop_pc;
6735
6736       if (real_stop_pc != 0 && in_solib_dynsym_resolve_code (real_stop_pc))
6737         {
6738           symtab_and_line sr_sal;
6739           sr_sal.pc = ecs->stop_func_start;
6740           sr_sal.pspace = get_frame_program_space (frame);
6741
6742           insert_step_resume_breakpoint_at_sal (gdbarch,
6743                                                 sr_sal, null_frame_id);
6744           keep_going (ecs);
6745           return;
6746         }
6747
6748       /* If we have line number information for the function we are
6749          thinking of stepping into and the function isn't on the skip
6750          list, step into it.
6751
6752          If there are several symtabs at that PC (e.g. with include
6753          files), just want to know whether *any* of them have line
6754          numbers.  find_pc_line handles this.  */
6755       {
6756         struct symtab_and_line tmp_sal;
6757
6758         tmp_sal = find_pc_line (ecs->stop_func_start, 0);
6759         if (tmp_sal.line != 0
6760             && !function_name_is_marked_for_skip (ecs->stop_func_name,
6761                                                   tmp_sal))
6762           {
6763             if (execution_direction == EXEC_REVERSE)
6764               handle_step_into_function_backward (gdbarch, ecs);
6765             else
6766               handle_step_into_function (gdbarch, ecs);
6767             return;
6768           }
6769       }
6770
6771       /* If we have no line number and the step-stop-if-no-debug is
6772          set, we stop the step so that the user has a chance to switch
6773          in assembly mode.  */
6774       if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6775           && step_stop_if_no_debug)
6776         {
6777           end_stepping_range (ecs);
6778           return;
6779         }
6780
6781       if (execution_direction == EXEC_REVERSE)
6782         {
6783           /* If we're already at the start of the function, we've either just
6784              stepped backward into a single instruction function without line
6785              number info, or stepped back out of a signal handler to the first
6786              instruction of the function without line number info.  Just keep
6787              going, which will single-step back to the caller.  */
6788           if (ecs->stop_func_start != stop_pc)
6789             {
6790               /* Set a breakpoint at callee's start address.
6791                  From there we can step once and be back in the caller.  */
6792               symtab_and_line sr_sal;
6793               sr_sal.pc = ecs->stop_func_start;
6794               sr_sal.pspace = get_frame_program_space (frame);
6795               insert_step_resume_breakpoint_at_sal (gdbarch,
6796                                                     sr_sal, null_frame_id);
6797             }
6798         }
6799       else
6800         /* Set a breakpoint at callee's return address (the address
6801            at which the caller will resume).  */
6802         insert_step_resume_breakpoint_at_caller (frame);
6803
6804       keep_going (ecs);
6805       return;
6806     }
6807
6808   /* Reverse stepping through solib trampolines.  */
6809
6810   if (execution_direction == EXEC_REVERSE
6811       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
6812     {
6813       if (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
6814           || (ecs->stop_func_start == 0
6815               && in_solib_dynsym_resolve_code (stop_pc)))
6816         {
6817           /* Any solib trampoline code can be handled in reverse
6818              by simply continuing to single-step.  We have already
6819              executed the solib function (backwards), and a few 
6820              steps will take us back through the trampoline to the
6821              caller.  */
6822           keep_going (ecs);
6823           return;
6824         }
6825       else if (in_solib_dynsym_resolve_code (stop_pc))
6826         {
6827           /* Stepped backward into the solib dynsym resolver.
6828              Set a breakpoint at its start and continue, then
6829              one more step will take us out.  */
6830           symtab_and_line sr_sal;
6831           sr_sal.pc = ecs->stop_func_start;
6832           sr_sal.pspace = get_frame_program_space (frame);
6833           insert_step_resume_breakpoint_at_sal (gdbarch, 
6834                                                 sr_sal, null_frame_id);
6835           keep_going (ecs);
6836           return;
6837         }
6838     }
6839
6840   stop_pc_sal = find_pc_line (stop_pc, 0);
6841
6842   /* NOTE: tausq/2004-05-24: This if block used to be done before all
6843      the trampoline processing logic, however, there are some trampolines 
6844      that have no names, so we should do trampoline handling first.  */
6845   if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6846       && ecs->stop_func_name == NULL
6847       && stop_pc_sal.line == 0)
6848     {
6849       if (debug_infrun)
6850          fprintf_unfiltered (gdb_stdlog,
6851                              "infrun: stepped into undebuggable function\n");
6852
6853       /* The inferior just stepped into, or returned to, an
6854          undebuggable function (where there is no debugging information
6855          and no line number corresponding to the address where the
6856          inferior stopped).  Since we want to skip this kind of code,
6857          we keep going until the inferior returns from this
6858          function - unless the user has asked us not to (via
6859          set step-mode) or we no longer know how to get back
6860          to the call site.  */
6861       if (step_stop_if_no_debug
6862           || !frame_id_p (frame_unwind_caller_id (frame)))
6863         {
6864           /* If we have no line number and the step-stop-if-no-debug
6865              is set, we stop the step so that the user has a chance to
6866              switch in assembly mode.  */
6867           end_stepping_range (ecs);
6868           return;
6869         }
6870       else
6871         {
6872           /* Set a breakpoint at callee's return address (the address
6873              at which the caller will resume).  */
6874           insert_step_resume_breakpoint_at_caller (frame);
6875           keep_going (ecs);
6876           return;
6877         }
6878     }
6879
6880   if (ecs->event_thread->control.step_range_end == 1)
6881     {
6882       /* It is stepi or nexti.  We always want to stop stepping after
6883          one instruction.  */
6884       if (debug_infrun)
6885          fprintf_unfiltered (gdb_stdlog, "infrun: stepi/nexti\n");
6886       end_stepping_range (ecs);
6887       return;
6888     }
6889
6890   if (stop_pc_sal.line == 0)
6891     {
6892       /* We have no line number information.  That means to stop
6893          stepping (does this always happen right after one instruction,
6894          when we do "s" in a function with no line numbers,
6895          or can this happen as a result of a return or longjmp?).  */
6896       if (debug_infrun)
6897          fprintf_unfiltered (gdb_stdlog, "infrun: no line number info\n");
6898       end_stepping_range (ecs);
6899       return;
6900     }
6901
6902   /* Look for "calls" to inlined functions, part one.  If the inline
6903      frame machinery detected some skipped call sites, we have entered
6904      a new inline function.  */
6905
6906   if (frame_id_eq (get_frame_id (get_current_frame ()),
6907                    ecs->event_thread->control.step_frame_id)
6908       && inline_skipped_frames (ecs->ptid))
6909     {
6910       if (debug_infrun)
6911         fprintf_unfiltered (gdb_stdlog,
6912                             "infrun: stepped into inlined function\n");
6913
6914       symtab_and_line call_sal = find_frame_sal (get_current_frame ());
6915
6916       if (ecs->event_thread->control.step_over_calls != STEP_OVER_ALL)
6917         {
6918           /* For "step", we're going to stop.  But if the call site
6919              for this inlined function is on the same source line as
6920              we were previously stepping, go down into the function
6921              first.  Otherwise stop at the call site.  */
6922
6923           if (call_sal.line == ecs->event_thread->current_line
6924               && call_sal.symtab == ecs->event_thread->current_symtab)
6925             step_into_inline_frame (ecs->ptid);
6926
6927           end_stepping_range (ecs);
6928           return;
6929         }
6930       else
6931         {
6932           /* For "next", we should stop at the call site if it is on a
6933              different source line.  Otherwise continue through the
6934              inlined function.  */
6935           if (call_sal.line == ecs->event_thread->current_line
6936               && call_sal.symtab == ecs->event_thread->current_symtab)
6937             keep_going (ecs);
6938           else
6939             end_stepping_range (ecs);
6940           return;
6941         }
6942     }
6943
6944   /* Look for "calls" to inlined functions, part two.  If we are still
6945      in the same real function we were stepping through, but we have
6946      to go further up to find the exact frame ID, we are stepping
6947      through a more inlined call beyond its call site.  */
6948
6949   if (get_frame_type (get_current_frame ()) == INLINE_FRAME
6950       && !frame_id_eq (get_frame_id (get_current_frame ()),
6951                        ecs->event_thread->control.step_frame_id)
6952       && stepped_in_from (get_current_frame (),
6953                           ecs->event_thread->control.step_frame_id))
6954     {
6955       if (debug_infrun)
6956         fprintf_unfiltered (gdb_stdlog,
6957                             "infrun: stepping through inlined function\n");
6958
6959       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6960         keep_going (ecs);
6961       else
6962         end_stepping_range (ecs);
6963       return;
6964     }
6965
6966   if ((stop_pc == stop_pc_sal.pc)
6967       && (ecs->event_thread->current_line != stop_pc_sal.line
6968           || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
6969     {
6970       /* We are at the start of a different line.  So stop.  Note that
6971          we don't stop if we step into the middle of a different line.
6972          That is said to make things like for (;;) statements work
6973          better.  */
6974       if (debug_infrun)
6975          fprintf_unfiltered (gdb_stdlog,
6976                              "infrun: stepped to a different line\n");
6977       end_stepping_range (ecs);
6978       return;
6979     }
6980
6981   /* We aren't done stepping.
6982
6983      Optimize by setting the stepping range to the line.
6984      (We might not be in the original line, but if we entered a
6985      new line in mid-statement, we continue stepping.  This makes
6986      things like for(;;) statements work better.)  */
6987
6988   ecs->event_thread->control.step_range_start = stop_pc_sal.pc;
6989   ecs->event_thread->control.step_range_end = stop_pc_sal.end;
6990   ecs->event_thread->control.may_range_step = 1;
6991   set_step_info (frame, stop_pc_sal);
6992
6993   if (debug_infrun)
6994      fprintf_unfiltered (gdb_stdlog, "infrun: keep going\n");
6995   keep_going (ecs);
6996 }
6997
6998 /* In all-stop mode, if we're currently stepping but have stopped in
6999    some other thread, we may need to switch back to the stepped
7000    thread.  Returns true we set the inferior running, false if we left
7001    it stopped (and the event needs further processing).  */
7002
7003 static int
7004 switch_back_to_stepped_thread (struct execution_control_state *ecs)
7005 {
7006   if (!target_is_non_stop_p ())
7007     {
7008       struct thread_info *tp;
7009       struct thread_info *stepping_thread;
7010
7011       /* If any thread is blocked on some internal breakpoint, and we
7012          simply need to step over that breakpoint to get it going
7013          again, do that first.  */
7014
7015       /* However, if we see an event for the stepping thread, then we
7016          know all other threads have been moved past their breakpoints
7017          already.  Let the caller check whether the step is finished,
7018          etc., before deciding to move it past a breakpoint.  */
7019       if (ecs->event_thread->control.step_range_end != 0)
7020         return 0;
7021
7022       /* Check if the current thread is blocked on an incomplete
7023          step-over, interrupted by a random signal.  */
7024       if (ecs->event_thread->control.trap_expected
7025           && ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_TRAP)
7026         {
7027           if (debug_infrun)
7028             {
7029               fprintf_unfiltered (gdb_stdlog,
7030                                   "infrun: need to finish step-over of [%s]\n",
7031                                   target_pid_to_str (ecs->event_thread->ptid));
7032             }
7033           keep_going (ecs);
7034           return 1;
7035         }
7036
7037       /* Check if the current thread is blocked by a single-step
7038          breakpoint of another thread.  */
7039       if (ecs->hit_singlestep_breakpoint)
7040        {
7041          if (debug_infrun)
7042            {
7043              fprintf_unfiltered (gdb_stdlog,
7044                                  "infrun: need to step [%s] over single-step "
7045                                  "breakpoint\n",
7046                                  target_pid_to_str (ecs->ptid));
7047            }
7048          keep_going (ecs);
7049          return 1;
7050        }
7051
7052       /* If this thread needs yet another step-over (e.g., stepping
7053          through a delay slot), do it first before moving on to
7054          another thread.  */
7055       if (thread_still_needs_step_over (ecs->event_thread))
7056         {
7057           if (debug_infrun)
7058             {
7059               fprintf_unfiltered (gdb_stdlog,
7060                                   "infrun: thread [%s] still needs step-over\n",
7061                                   target_pid_to_str (ecs->event_thread->ptid));
7062             }
7063           keep_going (ecs);
7064           return 1;
7065         }
7066
7067       /* If scheduler locking applies even if not stepping, there's no
7068          need to walk over threads.  Above we've checked whether the
7069          current thread is stepping.  If some other thread not the
7070          event thread is stepping, then it must be that scheduler
7071          locking is not in effect.  */
7072       if (schedlock_applies (ecs->event_thread))
7073         return 0;
7074
7075       /* Otherwise, we no longer expect a trap in the current thread.
7076          Clear the trap_expected flag before switching back -- this is
7077          what keep_going does as well, if we call it.  */
7078       ecs->event_thread->control.trap_expected = 0;
7079
7080       /* Likewise, clear the signal if it should not be passed.  */
7081       if (!signal_program[ecs->event_thread->suspend.stop_signal])
7082         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
7083
7084       /* Do all pending step-overs before actually proceeding with
7085          step/next/etc.  */
7086       if (start_step_over ())
7087         {
7088           prepare_to_wait (ecs);
7089           return 1;
7090         }
7091
7092       /* Look for the stepping/nexting thread.  */
7093       stepping_thread = NULL;
7094
7095       ALL_NON_EXITED_THREADS (tp)
7096         {
7097           /* Ignore threads of processes the caller is not
7098              resuming.  */
7099           if (!sched_multi
7100               && ptid_get_pid (tp->ptid) != ptid_get_pid (ecs->ptid))
7101             continue;
7102
7103           /* When stepping over a breakpoint, we lock all threads
7104              except the one that needs to move past the breakpoint.
7105              If a non-event thread has this set, the "incomplete
7106              step-over" check above should have caught it earlier.  */
7107           if (tp->control.trap_expected)
7108             {
7109               internal_error (__FILE__, __LINE__,
7110                               "[%s] has inconsistent state: "
7111                               "trap_expected=%d\n",
7112                               target_pid_to_str (tp->ptid),
7113                               tp->control.trap_expected);
7114             }
7115
7116           /* Did we find the stepping thread?  */
7117           if (tp->control.step_range_end)
7118             {
7119               /* Yep.  There should only one though.  */
7120               gdb_assert (stepping_thread == NULL);
7121
7122               /* The event thread is handled at the top, before we
7123                  enter this loop.  */
7124               gdb_assert (tp != ecs->event_thread);
7125
7126               /* If some thread other than the event thread is
7127                  stepping, then scheduler locking can't be in effect,
7128                  otherwise we wouldn't have resumed the current event
7129                  thread in the first place.  */
7130               gdb_assert (!schedlock_applies (tp));
7131
7132               stepping_thread = tp;
7133             }
7134         }
7135
7136       if (stepping_thread != NULL)
7137         {
7138           if (debug_infrun)
7139             fprintf_unfiltered (gdb_stdlog,
7140                                 "infrun: switching back to stepped thread\n");
7141
7142           if (keep_going_stepped_thread (stepping_thread))
7143             {
7144               prepare_to_wait (ecs);
7145               return 1;
7146             }
7147         }
7148     }
7149
7150   return 0;
7151 }
7152
7153 /* Set a previously stepped thread back to stepping.  Returns true on
7154    success, false if the resume is not possible (e.g., the thread
7155    vanished).  */
7156
7157 static int
7158 keep_going_stepped_thread (struct thread_info *tp)
7159 {
7160   struct frame_info *frame;
7161   struct execution_control_state ecss;
7162   struct execution_control_state *ecs = &ecss;
7163
7164   /* If the stepping thread exited, then don't try to switch back and
7165      resume it, which could fail in several different ways depending
7166      on the target.  Instead, just keep going.
7167
7168      We can find a stepping dead thread in the thread list in two
7169      cases:
7170
7171      - The target supports thread exit events, and when the target
7172        tries to delete the thread from the thread list, inferior_ptid
7173        pointed at the exiting thread.  In such case, calling
7174        delete_thread does not really remove the thread from the list;
7175        instead, the thread is left listed, with 'exited' state.
7176
7177      - The target's debug interface does not support thread exit
7178        events, and so we have no idea whatsoever if the previously
7179        stepping thread is still alive.  For that reason, we need to
7180        synchronously query the target now.  */
7181
7182   if (is_exited (tp->ptid)
7183       || !target_thread_alive (tp->ptid))
7184     {
7185       if (debug_infrun)
7186         fprintf_unfiltered (gdb_stdlog,
7187                             "infrun: not resuming previously  "
7188                             "stepped thread, it has vanished\n");
7189
7190       delete_thread (tp->ptid);
7191       return 0;
7192     }
7193
7194   if (debug_infrun)
7195     fprintf_unfiltered (gdb_stdlog,
7196                         "infrun: resuming previously stepped thread\n");
7197
7198   reset_ecs (ecs, tp);
7199   switch_to_thread (tp->ptid);
7200
7201   stop_pc = regcache_read_pc (get_thread_regcache (tp->ptid));
7202   frame = get_current_frame ();
7203
7204   /* If the PC of the thread we were trying to single-step has
7205      changed, then that thread has trapped or been signaled, but the
7206      event has not been reported to GDB yet.  Re-poll the target
7207      looking for this particular thread's event (i.e. temporarily
7208      enable schedlock) by:
7209
7210      - setting a break at the current PC
7211      - resuming that particular thread, only (by setting trap
7212      expected)
7213
7214      This prevents us continuously moving the single-step breakpoint
7215      forward, one instruction at a time, overstepping.  */
7216
7217   if (stop_pc != tp->prev_pc)
7218     {
7219       ptid_t resume_ptid;
7220
7221       if (debug_infrun)
7222         fprintf_unfiltered (gdb_stdlog,
7223                             "infrun: expected thread advanced also (%s -> %s)\n",
7224                             paddress (target_gdbarch (), tp->prev_pc),
7225                             paddress (target_gdbarch (), stop_pc));
7226
7227       /* Clear the info of the previous step-over, as it's no longer
7228          valid (if the thread was trying to step over a breakpoint, it
7229          has already succeeded).  It's what keep_going would do too,
7230          if we called it.  Do this before trying to insert the sss
7231          breakpoint, otherwise if we were previously trying to step
7232          over this exact address in another thread, the breakpoint is
7233          skipped.  */
7234       clear_step_over_info ();
7235       tp->control.trap_expected = 0;
7236
7237       insert_single_step_breakpoint (get_frame_arch (frame),
7238                                      get_frame_address_space (frame),
7239                                      stop_pc);
7240
7241       tp->resumed = 1;
7242       resume_ptid = internal_resume_ptid (tp->control.stepping_command);
7243       do_target_resume (resume_ptid, 0, GDB_SIGNAL_0);
7244     }
7245   else
7246     {
7247       if (debug_infrun)
7248         fprintf_unfiltered (gdb_stdlog,
7249                             "infrun: expected thread still hasn't advanced\n");
7250
7251       keep_going_pass_signal (ecs);
7252     }
7253   return 1;
7254 }
7255
7256 /* Is thread TP in the middle of (software or hardware)
7257    single-stepping?  (Note the result of this function must never be
7258    passed directly as target_resume's STEP parameter.)  */
7259
7260 static int
7261 currently_stepping (struct thread_info *tp)
7262 {
7263   return ((tp->control.step_range_end
7264            && tp->control.step_resume_breakpoint == NULL)
7265           || tp->control.trap_expected
7266           || tp->stepped_breakpoint
7267           || bpstat_should_step ());
7268 }
7269
7270 /* Inferior has stepped into a subroutine call with source code that
7271    we should not step over.  Do step to the first line of code in
7272    it.  */
7273
7274 static void
7275 handle_step_into_function (struct gdbarch *gdbarch,
7276                            struct execution_control_state *ecs)
7277 {
7278   fill_in_stop_func (gdbarch, ecs);
7279
7280   compunit_symtab *cust = find_pc_compunit_symtab (stop_pc);
7281   if (cust != NULL && compunit_language (cust) != language_asm)
7282     ecs->stop_func_start
7283       = gdbarch_skip_prologue_noexcept (gdbarch, ecs->stop_func_start);
7284
7285   symtab_and_line stop_func_sal = find_pc_line (ecs->stop_func_start, 0);
7286   /* Use the step_resume_break to step until the end of the prologue,
7287      even if that involves jumps (as it seems to on the vax under
7288      4.2).  */
7289   /* If the prologue ends in the middle of a source line, continue to
7290      the end of that source line (if it is still within the function).
7291      Otherwise, just go to end of prologue.  */
7292   if (stop_func_sal.end
7293       && stop_func_sal.pc != ecs->stop_func_start
7294       && stop_func_sal.end < ecs->stop_func_end)
7295     ecs->stop_func_start = stop_func_sal.end;
7296
7297   /* Architectures which require breakpoint adjustment might not be able
7298      to place a breakpoint at the computed address.  If so, the test
7299      ``ecs->stop_func_start == stop_pc'' will never succeed.  Adjust
7300      ecs->stop_func_start to an address at which a breakpoint may be
7301      legitimately placed.
7302
7303      Note:  kevinb/2004-01-19:  On FR-V, if this adjustment is not
7304      made, GDB will enter an infinite loop when stepping through
7305      optimized code consisting of VLIW instructions which contain
7306      subinstructions corresponding to different source lines.  On
7307      FR-V, it's not permitted to place a breakpoint on any but the
7308      first subinstruction of a VLIW instruction.  When a breakpoint is
7309      set, GDB will adjust the breakpoint address to the beginning of
7310      the VLIW instruction.  Thus, we need to make the corresponding
7311      adjustment here when computing the stop address.  */
7312
7313   if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7314     {
7315       ecs->stop_func_start
7316         = gdbarch_adjust_breakpoint_address (gdbarch,
7317                                              ecs->stop_func_start);
7318     }
7319
7320   if (ecs->stop_func_start == stop_pc)
7321     {
7322       /* We are already there: stop now.  */
7323       end_stepping_range (ecs);
7324       return;
7325     }
7326   else
7327     {
7328       /* Put the step-breakpoint there and go until there.  */
7329       symtab_and_line sr_sal;
7330       sr_sal.pc = ecs->stop_func_start;
7331       sr_sal.section = find_pc_overlay (ecs->stop_func_start);
7332       sr_sal.pspace = get_frame_program_space (get_current_frame ());
7333
7334       /* Do not specify what the fp should be when we stop since on
7335          some machines the prologue is where the new fp value is
7336          established.  */
7337       insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal, null_frame_id);
7338
7339       /* And make sure stepping stops right away then.  */
7340       ecs->event_thread->control.step_range_end
7341         = ecs->event_thread->control.step_range_start;
7342     }
7343   keep_going (ecs);
7344 }
7345
7346 /* Inferior has stepped backward into a subroutine call with source
7347    code that we should not step over.  Do step to the beginning of the
7348    last line of code in it.  */
7349
7350 static void
7351 handle_step_into_function_backward (struct gdbarch *gdbarch,
7352                                     struct execution_control_state *ecs)
7353 {
7354   struct compunit_symtab *cust;
7355   struct symtab_and_line stop_func_sal;
7356
7357   fill_in_stop_func (gdbarch, ecs);
7358
7359   cust = find_pc_compunit_symtab (stop_pc);
7360   if (cust != NULL && compunit_language (cust) != language_asm)
7361     ecs->stop_func_start
7362       = gdbarch_skip_prologue_noexcept (gdbarch, ecs->stop_func_start);
7363
7364   stop_func_sal = find_pc_line (stop_pc, 0);
7365
7366   /* OK, we're just going to keep stepping here.  */
7367   if (stop_func_sal.pc == stop_pc)
7368     {
7369       /* We're there already.  Just stop stepping now.  */
7370       end_stepping_range (ecs);
7371     }
7372   else
7373     {
7374       /* Else just reset the step range and keep going.
7375          No step-resume breakpoint, they don't work for
7376          epilogues, which can have multiple entry paths.  */
7377       ecs->event_thread->control.step_range_start = stop_func_sal.pc;
7378       ecs->event_thread->control.step_range_end = stop_func_sal.end;
7379       keep_going (ecs);
7380     }
7381   return;
7382 }
7383
7384 /* Insert a "step-resume breakpoint" at SR_SAL with frame ID SR_ID.
7385    This is used to both functions and to skip over code.  */
7386
7387 static void
7388 insert_step_resume_breakpoint_at_sal_1 (struct gdbarch *gdbarch,
7389                                         struct symtab_and_line sr_sal,
7390                                         struct frame_id sr_id,
7391                                         enum bptype sr_type)
7392 {
7393   /* There should never be more than one step-resume or longjmp-resume
7394      breakpoint per thread, so we should never be setting a new
7395      step_resume_breakpoint when one is already active.  */
7396   gdb_assert (inferior_thread ()->control.step_resume_breakpoint == NULL);
7397   gdb_assert (sr_type == bp_step_resume || sr_type == bp_hp_step_resume);
7398
7399   if (debug_infrun)
7400     fprintf_unfiltered (gdb_stdlog,
7401                         "infrun: inserting step-resume breakpoint at %s\n",
7402                         paddress (gdbarch, sr_sal.pc));
7403
7404   inferior_thread ()->control.step_resume_breakpoint
7405     = set_momentary_breakpoint (gdbarch, sr_sal, sr_id, sr_type).release ();
7406 }
7407
7408 void
7409 insert_step_resume_breakpoint_at_sal (struct gdbarch *gdbarch,
7410                                       struct symtab_and_line sr_sal,
7411                                       struct frame_id sr_id)
7412 {
7413   insert_step_resume_breakpoint_at_sal_1 (gdbarch,
7414                                           sr_sal, sr_id,
7415                                           bp_step_resume);
7416 }
7417
7418 /* Insert a "high-priority step-resume breakpoint" at RETURN_FRAME.pc.
7419    This is used to skip a potential signal handler.
7420
7421    This is called with the interrupted function's frame.  The signal
7422    handler, when it returns, will resume the interrupted function at
7423    RETURN_FRAME.pc.  */
7424
7425 static void
7426 insert_hp_step_resume_breakpoint_at_frame (struct frame_info *return_frame)
7427 {
7428   gdb_assert (return_frame != NULL);
7429
7430   struct gdbarch *gdbarch = get_frame_arch (return_frame);
7431
7432   symtab_and_line sr_sal;
7433   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch, get_frame_pc (return_frame));
7434   sr_sal.section = find_pc_overlay (sr_sal.pc);
7435   sr_sal.pspace = get_frame_program_space (return_frame);
7436
7437   insert_step_resume_breakpoint_at_sal_1 (gdbarch, sr_sal,
7438                                           get_stack_frame_id (return_frame),
7439                                           bp_hp_step_resume);
7440 }
7441
7442 /* Insert a "step-resume breakpoint" at the previous frame's PC.  This
7443    is used to skip a function after stepping into it (for "next" or if
7444    the called function has no debugging information).
7445
7446    The current function has almost always been reached by single
7447    stepping a call or return instruction.  NEXT_FRAME belongs to the
7448    current function, and the breakpoint will be set at the caller's
7449    resume address.
7450
7451    This is a separate function rather than reusing
7452    insert_hp_step_resume_breakpoint_at_frame in order to avoid
7453    get_prev_frame, which may stop prematurely (see the implementation
7454    of frame_unwind_caller_id for an example).  */
7455
7456 static void
7457 insert_step_resume_breakpoint_at_caller (struct frame_info *next_frame)
7458 {
7459   /* We shouldn't have gotten here if we don't know where the call site
7460      is.  */
7461   gdb_assert (frame_id_p (frame_unwind_caller_id (next_frame)));
7462
7463   struct gdbarch *gdbarch = frame_unwind_caller_arch (next_frame);
7464
7465   symtab_and_line sr_sal;
7466   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch,
7467                                         frame_unwind_caller_pc (next_frame));
7468   sr_sal.section = find_pc_overlay (sr_sal.pc);
7469   sr_sal.pspace = frame_unwind_program_space (next_frame);
7470
7471   insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal,
7472                                         frame_unwind_caller_id (next_frame));
7473 }
7474
7475 /* Insert a "longjmp-resume" breakpoint at PC.  This is used to set a
7476    new breakpoint at the target of a jmp_buf.  The handling of
7477    longjmp-resume uses the same mechanisms used for handling
7478    "step-resume" breakpoints.  */
7479
7480 static void
7481 insert_longjmp_resume_breakpoint (struct gdbarch *gdbarch, CORE_ADDR pc)
7482 {
7483   /* There should never be more than one longjmp-resume breakpoint per
7484      thread, so we should never be setting a new
7485      longjmp_resume_breakpoint when one is already active.  */
7486   gdb_assert (inferior_thread ()->control.exception_resume_breakpoint == NULL);
7487
7488   if (debug_infrun)
7489     fprintf_unfiltered (gdb_stdlog,
7490                         "infrun: inserting longjmp-resume breakpoint at %s\n",
7491                         paddress (gdbarch, pc));
7492
7493   inferior_thread ()->control.exception_resume_breakpoint =
7494     set_momentary_breakpoint_at_pc (gdbarch, pc, bp_longjmp_resume).release ();
7495 }
7496
7497 /* Insert an exception resume breakpoint.  TP is the thread throwing
7498    the exception.  The block B is the block of the unwinder debug hook
7499    function.  FRAME is the frame corresponding to the call to this
7500    function.  SYM is the symbol of the function argument holding the
7501    target PC of the exception.  */
7502
7503 static void
7504 insert_exception_resume_breakpoint (struct thread_info *tp,
7505                                     const struct block *b,
7506                                     struct frame_info *frame,
7507                                     struct symbol *sym)
7508 {
7509   TRY
7510     {
7511       struct block_symbol vsym;
7512       struct value *value;
7513       CORE_ADDR handler;
7514       struct breakpoint *bp;
7515
7516       vsym = lookup_symbol (SYMBOL_LINKAGE_NAME (sym), b, VAR_DOMAIN, NULL);
7517       value = read_var_value (vsym.symbol, vsym.block, frame);
7518       /* If the value was optimized out, revert to the old behavior.  */
7519       if (! value_optimized_out (value))
7520         {
7521           handler = value_as_address (value);
7522
7523           if (debug_infrun)
7524             fprintf_unfiltered (gdb_stdlog,
7525                                 "infrun: exception resume at %lx\n",
7526                                 (unsigned long) handler);
7527
7528           bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
7529                                                handler,
7530                                                bp_exception_resume).release ();
7531
7532           /* set_momentary_breakpoint_at_pc invalidates FRAME.  */
7533           frame = NULL;
7534
7535           bp->thread = tp->global_num;
7536           inferior_thread ()->control.exception_resume_breakpoint = bp;
7537         }
7538     }
7539   CATCH (e, RETURN_MASK_ERROR)
7540     {
7541       /* We want to ignore errors here.  */
7542     }
7543   END_CATCH
7544 }
7545
7546 /* A helper for check_exception_resume that sets an
7547    exception-breakpoint based on a SystemTap probe.  */
7548
7549 static void
7550 insert_exception_resume_from_probe (struct thread_info *tp,
7551                                     const struct bound_probe *probe,
7552                                     struct frame_info *frame)
7553 {
7554   struct value *arg_value;
7555   CORE_ADDR handler;
7556   struct breakpoint *bp;
7557
7558   arg_value = probe_safe_evaluate_at_pc (frame, 1);
7559   if (!arg_value)
7560     return;
7561
7562   handler = value_as_address (arg_value);
7563
7564   if (debug_infrun)
7565     fprintf_unfiltered (gdb_stdlog,
7566                         "infrun: exception resume at %s\n",
7567                         paddress (get_objfile_arch (probe->objfile),
7568                                   handler));
7569
7570   bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
7571                                        handler, bp_exception_resume).release ();
7572   bp->thread = tp->global_num;
7573   inferior_thread ()->control.exception_resume_breakpoint = bp;
7574 }
7575
7576 /* This is called when an exception has been intercepted.  Check to
7577    see whether the exception's destination is of interest, and if so,
7578    set an exception resume breakpoint there.  */
7579
7580 static void
7581 check_exception_resume (struct execution_control_state *ecs,
7582                         struct frame_info *frame)
7583 {
7584   struct bound_probe probe;
7585   struct symbol *func;
7586
7587   /* First see if this exception unwinding breakpoint was set via a
7588      SystemTap probe point.  If so, the probe has two arguments: the
7589      CFA and the HANDLER.  We ignore the CFA, extract the handler, and
7590      set a breakpoint there.  */
7591   probe = find_probe_by_pc (get_frame_pc (frame));
7592   if (probe.probe)
7593     {
7594       insert_exception_resume_from_probe (ecs->event_thread, &probe, frame);
7595       return;
7596     }
7597
7598   func = get_frame_function (frame);
7599   if (!func)
7600     return;
7601
7602   TRY
7603     {
7604       const struct block *b;
7605       struct block_iterator iter;
7606       struct symbol *sym;
7607       int argno = 0;
7608
7609       /* The exception breakpoint is a thread-specific breakpoint on
7610          the unwinder's debug hook, declared as:
7611          
7612          void _Unwind_DebugHook (void *cfa, void *handler);
7613          
7614          The CFA argument indicates the frame to which control is
7615          about to be transferred.  HANDLER is the destination PC.
7616          
7617          We ignore the CFA and set a temporary breakpoint at HANDLER.
7618          This is not extremely efficient but it avoids issues in gdb
7619          with computing the DWARF CFA, and it also works even in weird
7620          cases such as throwing an exception from inside a signal
7621          handler.  */
7622
7623       b = SYMBOL_BLOCK_VALUE (func);
7624       ALL_BLOCK_SYMBOLS (b, iter, sym)
7625         {
7626           if (!SYMBOL_IS_ARGUMENT (sym))
7627             continue;
7628
7629           if (argno == 0)
7630             ++argno;
7631           else
7632             {
7633               insert_exception_resume_breakpoint (ecs->event_thread,
7634                                                   b, frame, sym);
7635               break;
7636             }
7637         }
7638     }
7639   CATCH (e, RETURN_MASK_ERROR)
7640     {
7641     }
7642   END_CATCH
7643 }
7644
7645 static void
7646 stop_waiting (struct execution_control_state *ecs)
7647 {
7648   if (debug_infrun)
7649     fprintf_unfiltered (gdb_stdlog, "infrun: stop_waiting\n");
7650
7651   /* Let callers know we don't want to wait for the inferior anymore.  */
7652   ecs->wait_some_more = 0;
7653
7654   /* If all-stop, but the target is always in non-stop mode, stop all
7655      threads now that we're presenting the stop to the user.  */
7656   if (!non_stop && target_is_non_stop_p ())
7657     stop_all_threads ();
7658 }
7659
7660 /* Like keep_going, but passes the signal to the inferior, even if the
7661    signal is set to nopass.  */
7662
7663 static void
7664 keep_going_pass_signal (struct execution_control_state *ecs)
7665 {
7666   /* Make sure normal_stop is called if we get a QUIT handled before
7667      reaching resume.  */
7668   struct cleanup *old_cleanups = make_cleanup (resume_cleanups, 0);
7669
7670   gdb_assert (ptid_equal (ecs->event_thread->ptid, inferior_ptid));
7671   gdb_assert (!ecs->event_thread->resumed);
7672
7673   /* Save the pc before execution, to compare with pc after stop.  */
7674   ecs->event_thread->prev_pc
7675     = regcache_read_pc (get_thread_regcache (ecs->ptid));
7676
7677   if (ecs->event_thread->control.trap_expected)
7678     {
7679       struct thread_info *tp = ecs->event_thread;
7680
7681       if (debug_infrun)
7682         fprintf_unfiltered (gdb_stdlog,
7683                             "infrun: %s has trap_expected set, "
7684                             "resuming to collect trap\n",
7685                             target_pid_to_str (tp->ptid));
7686
7687       /* We haven't yet gotten our trap, and either: intercepted a
7688          non-signal event (e.g., a fork); or took a signal which we
7689          are supposed to pass through to the inferior.  Simply
7690          continue.  */
7691       discard_cleanups (old_cleanups);
7692       resume (ecs->event_thread->suspend.stop_signal);
7693     }
7694   else if (step_over_info_valid_p ())
7695     {
7696       /* Another thread is stepping over a breakpoint in-line.  If
7697          this thread needs a step-over too, queue the request.  In
7698          either case, this resume must be deferred for later.  */
7699       struct thread_info *tp = ecs->event_thread;
7700
7701       if (ecs->hit_singlestep_breakpoint
7702           || thread_still_needs_step_over (tp))
7703         {
7704           if (debug_infrun)
7705             fprintf_unfiltered (gdb_stdlog,
7706                                 "infrun: step-over already in progress: "
7707                                 "step-over for %s deferred\n",
7708                                 target_pid_to_str (tp->ptid));
7709           thread_step_over_chain_enqueue (tp);
7710         }
7711       else
7712         {
7713           if (debug_infrun)
7714             fprintf_unfiltered (gdb_stdlog,
7715                                 "infrun: step-over in progress: "
7716                                 "resume of %s deferred\n",
7717                                 target_pid_to_str (tp->ptid));
7718         }
7719
7720       discard_cleanups (old_cleanups);
7721     }
7722   else
7723     {
7724       struct regcache *regcache = get_current_regcache ();
7725       int remove_bp;
7726       int remove_wps;
7727       step_over_what step_what;
7728
7729       /* Either the trap was not expected, but we are continuing
7730          anyway (if we got a signal, the user asked it be passed to
7731          the child)
7732          -- or --
7733          We got our expected trap, but decided we should resume from
7734          it.
7735
7736          We're going to run this baby now!
7737
7738          Note that insert_breakpoints won't try to re-insert
7739          already inserted breakpoints.  Therefore, we don't
7740          care if breakpoints were already inserted, or not.  */
7741
7742       /* If we need to step over a breakpoint, and we're not using
7743          displaced stepping to do so, insert all breakpoints
7744          (watchpoints, etc.) but the one we're stepping over, step one
7745          instruction, and then re-insert the breakpoint when that step
7746          is finished.  */
7747
7748       step_what = thread_still_needs_step_over (ecs->event_thread);
7749
7750       remove_bp = (ecs->hit_singlestep_breakpoint
7751                    || (step_what & STEP_OVER_BREAKPOINT));
7752       remove_wps = (step_what & STEP_OVER_WATCHPOINT);
7753
7754       /* We can't use displaced stepping if we need to step past a
7755          watchpoint.  The instruction copied to the scratch pad would
7756          still trigger the watchpoint.  */
7757       if (remove_bp
7758           && (remove_wps || !use_displaced_stepping (ecs->event_thread)))
7759         {
7760           set_step_over_info (regcache->aspace (),
7761                               regcache_read_pc (regcache), remove_wps,
7762                               ecs->event_thread->global_num);
7763         }
7764       else if (remove_wps)
7765         set_step_over_info (NULL, 0, remove_wps, -1);
7766
7767       /* If we now need to do an in-line step-over, we need to stop
7768          all other threads.  Note this must be done before
7769          insert_breakpoints below, because that removes the breakpoint
7770          we're about to step over, otherwise other threads could miss
7771          it.  */
7772       if (step_over_info_valid_p () && target_is_non_stop_p ())
7773         stop_all_threads ();
7774
7775       /* Stop stepping if inserting breakpoints fails.  */
7776       TRY
7777         {
7778           insert_breakpoints ();
7779         }
7780       CATCH (e, RETURN_MASK_ERROR)
7781         {
7782           exception_print (gdb_stderr, e);
7783           stop_waiting (ecs);
7784           discard_cleanups (old_cleanups);
7785           return;
7786         }
7787       END_CATCH
7788
7789       ecs->event_thread->control.trap_expected = (remove_bp || remove_wps);
7790
7791       discard_cleanups (old_cleanups);
7792       resume (ecs->event_thread->suspend.stop_signal);
7793     }
7794
7795   prepare_to_wait (ecs);
7796 }
7797
7798 /* Called when we should continue running the inferior, because the
7799    current event doesn't cause a user visible stop.  This does the
7800    resuming part; waiting for the next event is done elsewhere.  */
7801
7802 static void
7803 keep_going (struct execution_control_state *ecs)
7804 {
7805   if (ecs->event_thread->control.trap_expected
7806       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
7807     ecs->event_thread->control.trap_expected = 0;
7808
7809   if (!signal_program[ecs->event_thread->suspend.stop_signal])
7810     ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
7811   keep_going_pass_signal (ecs);
7812 }
7813
7814 /* This function normally comes after a resume, before
7815    handle_inferior_event exits.  It takes care of any last bits of
7816    housekeeping, and sets the all-important wait_some_more flag.  */
7817
7818 static void
7819 prepare_to_wait (struct execution_control_state *ecs)
7820 {
7821   if (debug_infrun)
7822     fprintf_unfiltered (gdb_stdlog, "infrun: prepare_to_wait\n");
7823
7824   ecs->wait_some_more = 1;
7825
7826   if (!target_is_async_p ())
7827     mark_infrun_async_event_handler ();
7828 }
7829
7830 /* We are done with the step range of a step/next/si/ni command.
7831    Called once for each n of a "step n" operation.  */
7832
7833 static void
7834 end_stepping_range (struct execution_control_state *ecs)
7835 {
7836   ecs->event_thread->control.stop_step = 1;
7837   stop_waiting (ecs);
7838 }
7839
7840 /* Several print_*_reason functions to print why the inferior has stopped.
7841    We always print something when the inferior exits, or receives a signal.
7842    The rest of the cases are dealt with later on in normal_stop and
7843    print_it_typical.  Ideally there should be a call to one of these
7844    print_*_reason functions functions from handle_inferior_event each time
7845    stop_waiting is called.
7846
7847    Note that we don't call these directly, instead we delegate that to
7848    the interpreters, through observers.  Interpreters then call these
7849    with whatever uiout is right.  */
7850
7851 void
7852 print_end_stepping_range_reason (struct ui_out *uiout)
7853 {
7854   /* For CLI-like interpreters, print nothing.  */
7855
7856   if (uiout->is_mi_like_p ())
7857     {
7858       uiout->field_string ("reason",
7859                            async_reason_lookup (EXEC_ASYNC_END_STEPPING_RANGE));
7860     }
7861 }
7862
7863 void
7864 print_signal_exited_reason (struct ui_out *uiout, enum gdb_signal siggnal)
7865 {
7866   annotate_signalled ();
7867   if (uiout->is_mi_like_p ())
7868     uiout->field_string
7869       ("reason", async_reason_lookup (EXEC_ASYNC_EXITED_SIGNALLED));
7870   uiout->text ("\nProgram terminated with signal ");
7871   annotate_signal_name ();
7872   uiout->field_string ("signal-name",
7873                        gdb_signal_to_name (siggnal));
7874   annotate_signal_name_end ();
7875   uiout->text (", ");
7876   annotate_signal_string ();
7877   uiout->field_string ("signal-meaning",
7878                        gdb_signal_to_string (siggnal));
7879   annotate_signal_string_end ();
7880   uiout->text (".\n");
7881   uiout->text ("The program no longer exists.\n");
7882 }
7883
7884 void
7885 print_exited_reason (struct ui_out *uiout, int exitstatus)
7886 {
7887   struct inferior *inf = current_inferior ();
7888   const char *pidstr = target_pid_to_str (pid_to_ptid (inf->pid));
7889
7890   annotate_exited (exitstatus);
7891   if (exitstatus)
7892     {
7893       if (uiout->is_mi_like_p ())
7894         uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXITED));
7895       uiout->text ("[Inferior ");
7896       uiout->text (plongest (inf->num));
7897       uiout->text (" (");
7898       uiout->text (pidstr);
7899       uiout->text (") exited with code ");
7900       uiout->field_fmt ("exit-code", "0%o", (unsigned int) exitstatus);
7901       uiout->text ("]\n");
7902     }
7903   else
7904     {
7905       if (uiout->is_mi_like_p ())
7906         uiout->field_string
7907           ("reason", async_reason_lookup (EXEC_ASYNC_EXITED_NORMALLY));
7908       uiout->text ("[Inferior ");
7909       uiout->text (plongest (inf->num));
7910       uiout->text (" (");
7911       uiout->text (pidstr);
7912       uiout->text (") exited normally]\n");
7913     }
7914 }
7915
7916 /* Some targets/architectures can do extra processing/display of
7917    segmentation faults.  E.g., Intel MPX boundary faults.
7918    Call the architecture dependent function to handle the fault.  */
7919
7920 static void
7921 handle_segmentation_fault (struct ui_out *uiout)
7922 {
7923   struct regcache *regcache = get_current_regcache ();
7924   struct gdbarch *gdbarch = regcache->arch ();
7925
7926   if (gdbarch_handle_segmentation_fault_p (gdbarch))
7927     gdbarch_handle_segmentation_fault (gdbarch, uiout);
7928 }
7929
7930 void
7931 print_signal_received_reason (struct ui_out *uiout, enum gdb_signal siggnal)
7932 {
7933   struct thread_info *thr = inferior_thread ();
7934
7935   annotate_signal ();
7936
7937   if (uiout->is_mi_like_p ())
7938     ;
7939   else if (show_thread_that_caused_stop ())
7940     {
7941       const char *name;
7942
7943       uiout->text ("\nThread ");
7944       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
7945
7946       name = thr->name != NULL ? thr->name : target_thread_name (thr);
7947       if (name != NULL)
7948         {
7949           uiout->text (" \"");
7950           uiout->field_fmt ("name", "%s", name);
7951           uiout->text ("\"");
7952         }
7953     }
7954   else
7955     uiout->text ("\nProgram");
7956
7957   if (siggnal == GDB_SIGNAL_0 && !uiout->is_mi_like_p ())
7958     uiout->text (" stopped");
7959   else
7960     {
7961       uiout->text (" received signal ");
7962       annotate_signal_name ();
7963       if (uiout->is_mi_like_p ())
7964         uiout->field_string
7965           ("reason", async_reason_lookup (EXEC_ASYNC_SIGNAL_RECEIVED));
7966       uiout->field_string ("signal-name", gdb_signal_to_name (siggnal));
7967       annotate_signal_name_end ();
7968       uiout->text (", ");
7969       annotate_signal_string ();
7970       uiout->field_string ("signal-meaning", gdb_signal_to_string (siggnal));
7971
7972       if (siggnal == GDB_SIGNAL_SEGV)
7973         handle_segmentation_fault (uiout);
7974
7975       annotate_signal_string_end ();
7976     }
7977   uiout->text (".\n");
7978 }
7979
7980 void
7981 print_no_history_reason (struct ui_out *uiout)
7982 {
7983   uiout->text ("\nNo more reverse-execution history.\n");
7984 }
7985
7986 /* Print current location without a level number, if we have changed
7987    functions or hit a breakpoint.  Print source line if we have one.
7988    bpstat_print contains the logic deciding in detail what to print,
7989    based on the event(s) that just occurred.  */
7990
7991 static void
7992 print_stop_location (struct target_waitstatus *ws)
7993 {
7994   int bpstat_ret;
7995   enum print_what source_flag;
7996   int do_frame_printing = 1;
7997   struct thread_info *tp = inferior_thread ();
7998
7999   bpstat_ret = bpstat_print (tp->control.stop_bpstat, ws->kind);
8000   switch (bpstat_ret)
8001     {
8002     case PRINT_UNKNOWN:
8003       /* FIXME: cagney/2002-12-01: Given that a frame ID does (or
8004          should) carry around the function and does (or should) use
8005          that when doing a frame comparison.  */
8006       if (tp->control.stop_step
8007           && frame_id_eq (tp->control.step_frame_id,
8008                           get_frame_id (get_current_frame ()))
8009           && tp->control.step_start_function == find_pc_function (stop_pc))
8010         {
8011           /* Finished step, just print source line.  */
8012           source_flag = SRC_LINE;
8013         }
8014       else
8015         {
8016           /* Print location and source line.  */
8017           source_flag = SRC_AND_LOC;
8018         }
8019       break;
8020     case PRINT_SRC_AND_LOC:
8021       /* Print location and source line.  */
8022       source_flag = SRC_AND_LOC;
8023       break;
8024     case PRINT_SRC_ONLY:
8025       source_flag = SRC_LINE;
8026       break;
8027     case PRINT_NOTHING:
8028       /* Something bogus.  */
8029       source_flag = SRC_LINE;
8030       do_frame_printing = 0;
8031       break;
8032     default:
8033       internal_error (__FILE__, __LINE__, _("Unknown value."));
8034     }
8035
8036   /* The behavior of this routine with respect to the source
8037      flag is:
8038      SRC_LINE: Print only source line
8039      LOCATION: Print only location
8040      SRC_AND_LOC: Print location and source line.  */
8041   if (do_frame_printing)
8042     print_stack_frame (get_selected_frame (NULL), 0, source_flag, 1);
8043 }
8044
8045 /* See infrun.h.  */
8046
8047 void
8048 print_stop_event (struct ui_out *uiout)
8049 {
8050   struct target_waitstatus last;
8051   ptid_t last_ptid;
8052   struct thread_info *tp;
8053
8054   get_last_target_status (&last_ptid, &last);
8055
8056   {
8057     scoped_restore save_uiout = make_scoped_restore (&current_uiout, uiout);
8058
8059     print_stop_location (&last);
8060
8061     /* Display the auto-display expressions.  */
8062     do_displays ();
8063   }
8064
8065   tp = inferior_thread ();
8066   if (tp->thread_fsm != NULL
8067       && thread_fsm_finished_p (tp->thread_fsm))
8068     {
8069       struct return_value_info *rv;
8070
8071       rv = thread_fsm_return_value (tp->thread_fsm);
8072       if (rv != NULL)
8073         print_return_value (uiout, rv);
8074     }
8075 }
8076
8077 /* See infrun.h.  */
8078
8079 void
8080 maybe_remove_breakpoints (void)
8081 {
8082   if (!breakpoints_should_be_inserted_now () && target_has_execution)
8083     {
8084       if (remove_breakpoints ())
8085         {
8086           target_terminal::ours_for_output ();
8087           printf_filtered (_("Cannot remove breakpoints because "
8088                              "program is no longer writable.\nFurther "
8089                              "execution is probably impossible.\n"));
8090         }
8091     }
8092 }
8093
8094 /* The execution context that just caused a normal stop.  */
8095
8096 struct stop_context
8097 {
8098   /* The stop ID.  */
8099   ULONGEST stop_id;
8100
8101   /* The event PTID.  */
8102
8103   ptid_t ptid;
8104
8105   /* If stopp for a thread event, this is the thread that caused the
8106      stop.  */
8107   struct thread_info *thread;
8108
8109   /* The inferior that caused the stop.  */
8110   int inf_num;
8111 };
8112
8113 /* Returns a new stop context.  If stopped for a thread event, this
8114    takes a strong reference to the thread.  */
8115
8116 static struct stop_context *
8117 save_stop_context (void)
8118 {
8119   struct stop_context *sc = XNEW (struct stop_context);
8120
8121   sc->stop_id = get_stop_id ();
8122   sc->ptid = inferior_ptid;
8123   sc->inf_num = current_inferior ()->num;
8124
8125   if (!ptid_equal (inferior_ptid, null_ptid))
8126     {
8127       /* Take a strong reference so that the thread can't be deleted
8128          yet.  */
8129       sc->thread = inferior_thread ();
8130       sc->thread->incref ();
8131     }
8132   else
8133     sc->thread = NULL;
8134
8135   return sc;
8136 }
8137
8138 /* Release a stop context previously created with save_stop_context.
8139    Releases the strong reference to the thread as well. */
8140
8141 static void
8142 release_stop_context_cleanup (void *arg)
8143 {
8144   struct stop_context *sc = (struct stop_context *) arg;
8145
8146   if (sc->thread != NULL)
8147     sc->thread->decref ();
8148   xfree (sc);
8149 }
8150
8151 /* Return true if the current context no longer matches the saved stop
8152    context.  */
8153
8154 static int
8155 stop_context_changed (struct stop_context *prev)
8156 {
8157   if (!ptid_equal (prev->ptid, inferior_ptid))
8158     return 1;
8159   if (prev->inf_num != current_inferior ()->num)
8160     return 1;
8161   if (prev->thread != NULL && prev->thread->state != THREAD_STOPPED)
8162     return 1;
8163   if (get_stop_id () != prev->stop_id)
8164     return 1;
8165   return 0;
8166 }
8167
8168 /* See infrun.h.  */
8169
8170 int
8171 normal_stop (void)
8172 {
8173   struct target_waitstatus last;
8174   ptid_t last_ptid;
8175   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
8176   ptid_t pid_ptid;
8177
8178   get_last_target_status (&last_ptid, &last);
8179
8180   new_stop_id ();
8181
8182   /* If an exception is thrown from this point on, make sure to
8183      propagate GDB's knowledge of the executing state to the
8184      frontend/user running state.  A QUIT is an easy exception to see
8185      here, so do this before any filtered output.  */
8186   if (!non_stop)
8187     make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
8188   else if (last.kind == TARGET_WAITKIND_SIGNALLED
8189            || last.kind == TARGET_WAITKIND_EXITED)
8190     {
8191       /* On some targets, we may still have live threads in the
8192          inferior when we get a process exit event.  E.g., for
8193          "checkpoint", when the current checkpoint/fork exits,
8194          linux-fork.c automatically switches to another fork from
8195          within target_mourn_inferior.  */
8196       if (!ptid_equal (inferior_ptid, null_ptid))
8197         {
8198           pid_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
8199           make_cleanup (finish_thread_state_cleanup, &pid_ptid);
8200         }
8201     }
8202   else if (last.kind != TARGET_WAITKIND_NO_RESUMED)
8203     make_cleanup (finish_thread_state_cleanup, &inferior_ptid);
8204
8205   /* As we're presenting a stop, and potentially removing breakpoints,
8206      update the thread list so we can tell whether there are threads
8207      running on the target.  With target remote, for example, we can
8208      only learn about new threads when we explicitly update the thread
8209      list.  Do this before notifying the interpreters about signal
8210      stops, end of stepping ranges, etc., so that the "new thread"
8211      output is emitted before e.g., "Program received signal FOO",
8212      instead of after.  */
8213   update_thread_list ();
8214
8215   if (last.kind == TARGET_WAITKIND_STOPPED && stopped_by_random_signal)
8216     observer_notify_signal_received (inferior_thread ()->suspend.stop_signal);
8217
8218   /* As with the notification of thread events, we want to delay
8219      notifying the user that we've switched thread context until
8220      the inferior actually stops.
8221
8222      There's no point in saying anything if the inferior has exited.
8223      Note that SIGNALLED here means "exited with a signal", not
8224      "received a signal".
8225
8226      Also skip saying anything in non-stop mode.  In that mode, as we
8227      don't want GDB to switch threads behind the user's back, to avoid
8228      races where the user is typing a command to apply to thread x,
8229      but GDB switches to thread y before the user finishes entering
8230      the command, fetch_inferior_event installs a cleanup to restore
8231      the current thread back to the thread the user had selected right
8232      after this event is handled, so we're not really switching, only
8233      informing of a stop.  */
8234   if (!non_stop
8235       && !ptid_equal (previous_inferior_ptid, inferior_ptid)
8236       && target_has_execution
8237       && last.kind != TARGET_WAITKIND_SIGNALLED
8238       && last.kind != TARGET_WAITKIND_EXITED
8239       && last.kind != TARGET_WAITKIND_NO_RESUMED)
8240     {
8241       SWITCH_THRU_ALL_UIS ()
8242         {
8243           target_terminal::ours_for_output ();
8244           printf_filtered (_("[Switching to %s]\n"),
8245                            target_pid_to_str (inferior_ptid));
8246           annotate_thread_changed ();
8247         }
8248       previous_inferior_ptid = inferior_ptid;
8249     }
8250
8251   if (last.kind == TARGET_WAITKIND_NO_RESUMED)
8252     {
8253       SWITCH_THRU_ALL_UIS ()
8254         if (current_ui->prompt_state == PROMPT_BLOCKED)
8255           {
8256             target_terminal::ours_for_output ();
8257             printf_filtered (_("No unwaited-for children left.\n"));
8258           }
8259     }
8260
8261   /* Note: this depends on the update_thread_list call above.  */
8262   maybe_remove_breakpoints ();
8263
8264   /* If an auto-display called a function and that got a signal,
8265      delete that auto-display to avoid an infinite recursion.  */
8266
8267   if (stopped_by_random_signal)
8268     disable_current_display ();
8269
8270   SWITCH_THRU_ALL_UIS ()
8271     {
8272       async_enable_stdin ();
8273     }
8274
8275   /* Let the user/frontend see the threads as stopped.  */
8276   do_cleanups (old_chain);
8277
8278   /* Select innermost stack frame - i.e., current frame is frame 0,
8279      and current location is based on that.  Handle the case where the
8280      dummy call is returning after being stopped.  E.g. the dummy call
8281      previously hit a breakpoint.  (If the dummy call returns
8282      normally, we won't reach here.)  Do this before the stop hook is
8283      run, so that it doesn't get to see the temporary dummy frame,
8284      which is not where we'll present the stop.  */
8285   if (has_stack_frames ())
8286     {
8287       if (stop_stack_dummy == STOP_STACK_DUMMY)
8288         {
8289           /* Pop the empty frame that contains the stack dummy.  This
8290              also restores inferior state prior to the call (struct
8291              infcall_suspend_state).  */
8292           struct frame_info *frame = get_current_frame ();
8293
8294           gdb_assert (get_frame_type (frame) == DUMMY_FRAME);
8295           frame_pop (frame);
8296           /* frame_pop calls reinit_frame_cache as the last thing it
8297              does which means there's now no selected frame.  */
8298         }
8299
8300       select_frame (get_current_frame ());
8301
8302       /* Set the current source location.  */
8303       set_current_sal_from_frame (get_current_frame ());
8304     }
8305
8306   /* Look up the hook_stop and run it (CLI internally handles problem
8307      of stop_command's pre-hook not existing).  */
8308   if (stop_command != NULL)
8309     {
8310       struct stop_context *saved_context = save_stop_context ();
8311       struct cleanup *old_chain
8312         = make_cleanup (release_stop_context_cleanup, saved_context);
8313
8314       TRY
8315         {
8316           execute_cmd_pre_hook (stop_command);
8317         }
8318       CATCH (ex, RETURN_MASK_ALL)
8319         {
8320           exception_fprintf (gdb_stderr, ex,
8321                              "Error while running hook_stop:\n");
8322         }
8323       END_CATCH
8324
8325       /* If the stop hook resumes the target, then there's no point in
8326          trying to notify about the previous stop; its context is
8327          gone.  Likewise if the command switches thread or inferior --
8328          the observers would print a stop for the wrong
8329          thread/inferior.  */
8330       if (stop_context_changed (saved_context))
8331         {
8332           do_cleanups (old_chain);
8333           return 1;
8334         }
8335       do_cleanups (old_chain);
8336     }
8337
8338   /* Notify observers about the stop.  This is where the interpreters
8339      print the stop event.  */
8340   if (!ptid_equal (inferior_ptid, null_ptid))
8341     observer_notify_normal_stop (inferior_thread ()->control.stop_bpstat,
8342                                  stop_print_frame);
8343   else
8344     observer_notify_normal_stop (NULL, stop_print_frame);
8345
8346   annotate_stopped ();
8347
8348   if (target_has_execution)
8349     {
8350       if (last.kind != TARGET_WAITKIND_SIGNALLED
8351           && last.kind != TARGET_WAITKIND_EXITED)
8352         /* Delete the breakpoint we stopped at, if it wants to be deleted.
8353            Delete any breakpoint that is to be deleted at the next stop.  */
8354         breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
8355     }
8356
8357   /* Try to get rid of automatically added inferiors that are no
8358      longer needed.  Keeping those around slows down things linearly.
8359      Note that this never removes the current inferior.  */
8360   prune_inferiors ();
8361
8362   return 0;
8363 }
8364 \f
8365 int
8366 signal_stop_state (int signo)
8367 {
8368   return signal_stop[signo];
8369 }
8370
8371 int
8372 signal_print_state (int signo)
8373 {
8374   return signal_print[signo];
8375 }
8376
8377 int
8378 signal_pass_state (int signo)
8379 {
8380   return signal_program[signo];
8381 }
8382
8383 static void
8384 signal_cache_update (int signo)
8385 {
8386   if (signo == -1)
8387     {
8388       for (signo = 0; signo < (int) GDB_SIGNAL_LAST; signo++)
8389         signal_cache_update (signo);
8390
8391       return;
8392     }
8393
8394   signal_pass[signo] = (signal_stop[signo] == 0
8395                         && signal_print[signo] == 0
8396                         && signal_program[signo] == 1
8397                         && signal_catch[signo] == 0);
8398 }
8399
8400 int
8401 signal_stop_update (int signo, int state)
8402 {
8403   int ret = signal_stop[signo];
8404
8405   signal_stop[signo] = state;
8406   signal_cache_update (signo);
8407   return ret;
8408 }
8409
8410 int
8411 signal_print_update (int signo, int state)
8412 {
8413   int ret = signal_print[signo];
8414
8415   signal_print[signo] = state;
8416   signal_cache_update (signo);
8417   return ret;
8418 }
8419
8420 int
8421 signal_pass_update (int signo, int state)
8422 {
8423   int ret = signal_program[signo];
8424
8425   signal_program[signo] = state;
8426   signal_cache_update (signo);
8427   return ret;
8428 }
8429
8430 /* Update the global 'signal_catch' from INFO and notify the
8431    target.  */
8432
8433 void
8434 signal_catch_update (const unsigned int *info)
8435 {
8436   int i;
8437
8438   for (i = 0; i < GDB_SIGNAL_LAST; ++i)
8439     signal_catch[i] = info[i] > 0;
8440   signal_cache_update (-1);
8441   target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
8442 }
8443
8444 static void
8445 sig_print_header (void)
8446 {
8447   printf_filtered (_("Signal        Stop\tPrint\tPass "
8448                      "to program\tDescription\n"));
8449 }
8450
8451 static void
8452 sig_print_info (enum gdb_signal oursig)
8453 {
8454   const char *name = gdb_signal_to_name (oursig);
8455   int name_padding = 13 - strlen (name);
8456
8457   if (name_padding <= 0)
8458     name_padding = 0;
8459
8460   printf_filtered ("%s", name);
8461   printf_filtered ("%*.*s ", name_padding, name_padding, "                 ");
8462   printf_filtered ("%s\t", signal_stop[oursig] ? "Yes" : "No");
8463   printf_filtered ("%s\t", signal_print[oursig] ? "Yes" : "No");
8464   printf_filtered ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
8465   printf_filtered ("%s\n", gdb_signal_to_string (oursig));
8466 }
8467
8468 /* Specify how various signals in the inferior should be handled.  */
8469
8470 static void
8471 handle_command (char *args, int from_tty)
8472 {
8473   int digits, wordlen;
8474   int sigfirst, signum, siglast;
8475   enum gdb_signal oursig;
8476   int allsigs;
8477   int nsigs;
8478   unsigned char *sigs;
8479
8480   if (args == NULL)
8481     {
8482       error_no_arg (_("signal to handle"));
8483     }
8484
8485   /* Allocate and zero an array of flags for which signals to handle.  */
8486
8487   nsigs = (int) GDB_SIGNAL_LAST;
8488   sigs = (unsigned char *) alloca (nsigs);
8489   memset (sigs, 0, nsigs);
8490
8491   /* Break the command line up into args.  */
8492
8493   gdb_argv built_argv (args);
8494
8495   /* Walk through the args, looking for signal oursigs, signal names, and
8496      actions.  Signal numbers and signal names may be interspersed with
8497      actions, with the actions being performed for all signals cumulatively
8498      specified.  Signal ranges can be specified as <LOW>-<HIGH>.  */
8499
8500   for (char *arg : built_argv)
8501     {
8502       wordlen = strlen (arg);
8503       for (digits = 0; isdigit (arg[digits]); digits++)
8504         {;
8505         }
8506       allsigs = 0;
8507       sigfirst = siglast = -1;
8508
8509       if (wordlen >= 1 && !strncmp (arg, "all", wordlen))
8510         {
8511           /* Apply action to all signals except those used by the
8512              debugger.  Silently skip those.  */
8513           allsigs = 1;
8514           sigfirst = 0;
8515           siglast = nsigs - 1;
8516         }
8517       else if (wordlen >= 1 && !strncmp (arg, "stop", wordlen))
8518         {
8519           SET_SIGS (nsigs, sigs, signal_stop);
8520           SET_SIGS (nsigs, sigs, signal_print);
8521         }
8522       else if (wordlen >= 1 && !strncmp (arg, "ignore", wordlen))
8523         {
8524           UNSET_SIGS (nsigs, sigs, signal_program);
8525         }
8526       else if (wordlen >= 2 && !strncmp (arg, "print", wordlen))
8527         {
8528           SET_SIGS (nsigs, sigs, signal_print);
8529         }
8530       else if (wordlen >= 2 && !strncmp (arg, "pass", wordlen))
8531         {
8532           SET_SIGS (nsigs, sigs, signal_program);
8533         }
8534       else if (wordlen >= 3 && !strncmp (arg, "nostop", wordlen))
8535         {
8536           UNSET_SIGS (nsigs, sigs, signal_stop);
8537         }
8538       else if (wordlen >= 3 && !strncmp (arg, "noignore", wordlen))
8539         {
8540           SET_SIGS (nsigs, sigs, signal_program);
8541         }
8542       else if (wordlen >= 4 && !strncmp (arg, "noprint", wordlen))
8543         {
8544           UNSET_SIGS (nsigs, sigs, signal_print);
8545           UNSET_SIGS (nsigs, sigs, signal_stop);
8546         }
8547       else if (wordlen >= 4 && !strncmp (arg, "nopass", wordlen))
8548         {
8549           UNSET_SIGS (nsigs, sigs, signal_program);
8550         }
8551       else if (digits > 0)
8552         {
8553           /* It is numeric.  The numeric signal refers to our own
8554              internal signal numbering from target.h, not to host/target
8555              signal  number.  This is a feature; users really should be
8556              using symbolic names anyway, and the common ones like
8557              SIGHUP, SIGINT, SIGALRM, etc. will work right anyway.  */
8558
8559           sigfirst = siglast = (int)
8560             gdb_signal_from_command (atoi (arg));
8561           if (arg[digits] == '-')
8562             {
8563               siglast = (int)
8564                 gdb_signal_from_command (atoi (arg + digits + 1));
8565             }
8566           if (sigfirst > siglast)
8567             {
8568               /* Bet he didn't figure we'd think of this case...  */
8569               signum = sigfirst;
8570               sigfirst = siglast;
8571               siglast = signum;
8572             }
8573         }
8574       else
8575         {
8576           oursig = gdb_signal_from_name (arg);
8577           if (oursig != GDB_SIGNAL_UNKNOWN)
8578             {
8579               sigfirst = siglast = (int) oursig;
8580             }
8581           else
8582             {
8583               /* Not a number and not a recognized flag word => complain.  */
8584               error (_("Unrecognized or ambiguous flag word: \"%s\"."), arg);
8585             }
8586         }
8587
8588       /* If any signal numbers or symbol names were found, set flags for
8589          which signals to apply actions to.  */
8590
8591       for (signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
8592         {
8593           switch ((enum gdb_signal) signum)
8594             {
8595             case GDB_SIGNAL_TRAP:
8596             case GDB_SIGNAL_INT:
8597               if (!allsigs && !sigs[signum])
8598                 {
8599                   if (query (_("%s is used by the debugger.\n\
8600 Are you sure you want to change it? "),
8601                              gdb_signal_to_name ((enum gdb_signal) signum)))
8602                     {
8603                       sigs[signum] = 1;
8604                     }
8605                   else
8606                     {
8607                       printf_unfiltered (_("Not confirmed, unchanged.\n"));
8608                       gdb_flush (gdb_stdout);
8609                     }
8610                 }
8611               break;
8612             case GDB_SIGNAL_0:
8613             case GDB_SIGNAL_DEFAULT:
8614             case GDB_SIGNAL_UNKNOWN:
8615               /* Make sure that "all" doesn't print these.  */
8616               break;
8617             default:
8618               sigs[signum] = 1;
8619               break;
8620             }
8621         }
8622     }
8623
8624   for (signum = 0; signum < nsigs; signum++)
8625     if (sigs[signum])
8626       {
8627         signal_cache_update (-1);
8628         target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
8629         target_program_signals ((int) GDB_SIGNAL_LAST, signal_program);
8630
8631         if (from_tty)
8632           {
8633             /* Show the results.  */
8634             sig_print_header ();
8635             for (; signum < nsigs; signum++)
8636               if (sigs[signum])
8637                 sig_print_info ((enum gdb_signal) signum);
8638           }
8639
8640         break;
8641       }
8642 }
8643
8644 /* Complete the "handle" command.  */
8645
8646 static void
8647 handle_completer (struct cmd_list_element *ignore,
8648                   completion_tracker &tracker,
8649                   const char *text, const char *word)
8650 {
8651   static const char * const keywords[] =
8652     {
8653       "all",
8654       "stop",
8655       "ignore",
8656       "print",
8657       "pass",
8658       "nostop",
8659       "noignore",
8660       "noprint",
8661       "nopass",
8662       NULL,
8663     };
8664
8665   signal_completer (ignore, tracker, text, word);
8666   complete_on_enum (tracker, keywords, word, word);
8667 }
8668
8669 enum gdb_signal
8670 gdb_signal_from_command (int num)
8671 {
8672   if (num >= 1 && num <= 15)
8673     return (enum gdb_signal) num;
8674   error (_("Only signals 1-15 are valid as numeric signals.\n\
8675 Use \"info signals\" for a list of symbolic signals."));
8676 }
8677
8678 /* Print current contents of the tables set by the handle command.
8679    It is possible we should just be printing signals actually used
8680    by the current target (but for things to work right when switching
8681    targets, all signals should be in the signal tables).  */
8682
8683 static void
8684 info_signals_command (char *signum_exp, int from_tty)
8685 {
8686   enum gdb_signal oursig;
8687
8688   sig_print_header ();
8689
8690   if (signum_exp)
8691     {
8692       /* First see if this is a symbol name.  */
8693       oursig = gdb_signal_from_name (signum_exp);
8694       if (oursig == GDB_SIGNAL_UNKNOWN)
8695         {
8696           /* No, try numeric.  */
8697           oursig =
8698             gdb_signal_from_command (parse_and_eval_long (signum_exp));
8699         }
8700       sig_print_info (oursig);
8701       return;
8702     }
8703
8704   printf_filtered ("\n");
8705   /* These ugly casts brought to you by the native VAX compiler.  */
8706   for (oursig = GDB_SIGNAL_FIRST;
8707        (int) oursig < (int) GDB_SIGNAL_LAST;
8708        oursig = (enum gdb_signal) ((int) oursig + 1))
8709     {
8710       QUIT;
8711
8712       if (oursig != GDB_SIGNAL_UNKNOWN
8713           && oursig != GDB_SIGNAL_DEFAULT && oursig != GDB_SIGNAL_0)
8714         sig_print_info (oursig);
8715     }
8716
8717   printf_filtered (_("\nUse the \"handle\" command "
8718                      "to change these tables.\n"));
8719 }
8720
8721 /* The $_siginfo convenience variable is a bit special.  We don't know
8722    for sure the type of the value until we actually have a chance to
8723    fetch the data.  The type can change depending on gdbarch, so it is
8724    also dependent on which thread you have selected.
8725
8726      1. making $_siginfo be an internalvar that creates a new value on
8727      access.
8728
8729      2. making the value of $_siginfo be an lval_computed value.  */
8730
8731 /* This function implements the lval_computed support for reading a
8732    $_siginfo value.  */
8733
8734 static void
8735 siginfo_value_read (struct value *v)
8736 {
8737   LONGEST transferred;
8738
8739   /* If we can access registers, so can we access $_siginfo.  Likewise
8740      vice versa.  */
8741   validate_registers_access ();
8742
8743   transferred =
8744     target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO,
8745                  NULL,
8746                  value_contents_all_raw (v),
8747                  value_offset (v),
8748                  TYPE_LENGTH (value_type (v)));
8749
8750   if (transferred != TYPE_LENGTH (value_type (v)))
8751     error (_("Unable to read siginfo"));
8752 }
8753
8754 /* This function implements the lval_computed support for writing a
8755    $_siginfo value.  */
8756
8757 static void
8758 siginfo_value_write (struct value *v, struct value *fromval)
8759 {
8760   LONGEST transferred;
8761
8762   /* If we can access registers, so can we access $_siginfo.  Likewise
8763      vice versa.  */
8764   validate_registers_access ();
8765
8766   transferred = target_write (&current_target,
8767                               TARGET_OBJECT_SIGNAL_INFO,
8768                               NULL,
8769                               value_contents_all_raw (fromval),
8770                               value_offset (v),
8771                               TYPE_LENGTH (value_type (fromval)));
8772
8773   if (transferred != TYPE_LENGTH (value_type (fromval)))
8774     error (_("Unable to write siginfo"));
8775 }
8776
8777 static const struct lval_funcs siginfo_value_funcs =
8778   {
8779     siginfo_value_read,
8780     siginfo_value_write
8781   };
8782
8783 /* Return a new value with the correct type for the siginfo object of
8784    the current thread using architecture GDBARCH.  Return a void value
8785    if there's no object available.  */
8786
8787 static struct value *
8788 siginfo_make_value (struct gdbarch *gdbarch, struct internalvar *var,
8789                     void *ignore)
8790 {
8791   if (target_has_stack
8792       && !ptid_equal (inferior_ptid, null_ptid)
8793       && gdbarch_get_siginfo_type_p (gdbarch))
8794     {
8795       struct type *type = gdbarch_get_siginfo_type (gdbarch);
8796
8797       return allocate_computed_value (type, &siginfo_value_funcs, NULL);
8798     }
8799
8800   return allocate_value (builtin_type (gdbarch)->builtin_void);
8801 }
8802
8803 \f
8804 /* infcall_suspend_state contains state about the program itself like its
8805    registers and any signal it received when it last stopped.
8806    This state must be restored regardless of how the inferior function call
8807    ends (either successfully, or after it hits a breakpoint or signal)
8808    if the program is to properly continue where it left off.  */
8809
8810 struct infcall_suspend_state
8811 {
8812   struct thread_suspend_state thread_suspend;
8813
8814   /* Other fields:  */
8815   CORE_ADDR stop_pc;
8816   struct regcache *registers;
8817
8818   /* Format of SIGINFO_DATA or NULL if it is not present.  */
8819   struct gdbarch *siginfo_gdbarch;
8820
8821   /* The inferior format depends on SIGINFO_GDBARCH and it has a length of
8822      TYPE_LENGTH (gdbarch_get_siginfo_type ()).  For different gdbarch the
8823      content would be invalid.  */
8824   gdb_byte *siginfo_data;
8825 };
8826
8827 struct infcall_suspend_state *
8828 save_infcall_suspend_state (void)
8829 {
8830   struct infcall_suspend_state *inf_state;
8831   struct thread_info *tp = inferior_thread ();
8832   struct regcache *regcache = get_current_regcache ();
8833   struct gdbarch *gdbarch = regcache->arch ();
8834   gdb_byte *siginfo_data = NULL;
8835
8836   if (gdbarch_get_siginfo_type_p (gdbarch))
8837     {
8838       struct type *type = gdbarch_get_siginfo_type (gdbarch);
8839       size_t len = TYPE_LENGTH (type);
8840       struct cleanup *back_to;
8841
8842       siginfo_data = (gdb_byte *) xmalloc (len);
8843       back_to = make_cleanup (xfree, siginfo_data);
8844
8845       if (target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
8846                        siginfo_data, 0, len) == len)
8847         discard_cleanups (back_to);
8848       else
8849         {
8850           /* Errors ignored.  */
8851           do_cleanups (back_to);
8852           siginfo_data = NULL;
8853         }
8854     }
8855
8856   inf_state = XCNEW (struct infcall_suspend_state);
8857
8858   if (siginfo_data)
8859     {
8860       inf_state->siginfo_gdbarch = gdbarch;
8861       inf_state->siginfo_data = siginfo_data;
8862     }
8863
8864   inf_state->thread_suspend = tp->suspend;
8865
8866   /* run_inferior_call will not use the signal due to its `proceed' call with
8867      GDB_SIGNAL_0 anyway.  */
8868   tp->suspend.stop_signal = GDB_SIGNAL_0;
8869
8870   inf_state->stop_pc = stop_pc;
8871
8872   inf_state->registers = regcache_dup (regcache);
8873
8874   return inf_state;
8875 }
8876
8877 /* Restore inferior session state to INF_STATE.  */
8878
8879 void
8880 restore_infcall_suspend_state (struct infcall_suspend_state *inf_state)
8881 {
8882   struct thread_info *tp = inferior_thread ();
8883   struct regcache *regcache = get_current_regcache ();
8884   struct gdbarch *gdbarch = regcache->arch ();
8885
8886   tp->suspend = inf_state->thread_suspend;
8887
8888   stop_pc = inf_state->stop_pc;
8889
8890   if (inf_state->siginfo_gdbarch == gdbarch)
8891     {
8892       struct type *type = gdbarch_get_siginfo_type (gdbarch);
8893
8894       /* Errors ignored.  */
8895       target_write (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
8896                     inf_state->siginfo_data, 0, TYPE_LENGTH (type));
8897     }
8898
8899   /* The inferior can be gone if the user types "print exit(0)"
8900      (and perhaps other times).  */
8901   if (target_has_execution)
8902     /* NB: The register write goes through to the target.  */
8903     regcache_cpy (regcache, inf_state->registers);
8904
8905   discard_infcall_suspend_state (inf_state);
8906 }
8907
8908 static void
8909 do_restore_infcall_suspend_state_cleanup (void *state)
8910 {
8911   restore_infcall_suspend_state ((struct infcall_suspend_state *) state);
8912 }
8913
8914 struct cleanup *
8915 make_cleanup_restore_infcall_suspend_state
8916   (struct infcall_suspend_state *inf_state)
8917 {
8918   return make_cleanup (do_restore_infcall_suspend_state_cleanup, inf_state);
8919 }
8920
8921 void
8922 discard_infcall_suspend_state (struct infcall_suspend_state *inf_state)
8923 {
8924   delete inf_state->registers;
8925   xfree (inf_state->siginfo_data);
8926   xfree (inf_state);
8927 }
8928
8929 struct regcache *
8930 get_infcall_suspend_state_regcache (struct infcall_suspend_state *inf_state)
8931 {
8932   return inf_state->registers;
8933 }
8934
8935 /* infcall_control_state contains state regarding gdb's control of the
8936    inferior itself like stepping control.  It also contains session state like
8937    the user's currently selected frame.  */
8938
8939 struct infcall_control_state
8940 {
8941   struct thread_control_state thread_control;
8942   struct inferior_control_state inferior_control;
8943
8944   /* Other fields:  */
8945   enum stop_stack_kind stop_stack_dummy;
8946   int stopped_by_random_signal;
8947
8948   /* ID if the selected frame when the inferior function call was made.  */
8949   struct frame_id selected_frame_id;
8950 };
8951
8952 /* Save all of the information associated with the inferior<==>gdb
8953    connection.  */
8954
8955 struct infcall_control_state *
8956 save_infcall_control_state (void)
8957 {
8958   struct infcall_control_state *inf_status =
8959     XNEW (struct infcall_control_state);
8960   struct thread_info *tp = inferior_thread ();
8961   struct inferior *inf = current_inferior ();
8962
8963   inf_status->thread_control = tp->control;
8964   inf_status->inferior_control = inf->control;
8965
8966   tp->control.step_resume_breakpoint = NULL;
8967   tp->control.exception_resume_breakpoint = NULL;
8968
8969   /* Save original bpstat chain to INF_STATUS; replace it in TP with copy of
8970      chain.  If caller's caller is walking the chain, they'll be happier if we
8971      hand them back the original chain when restore_infcall_control_state is
8972      called.  */
8973   tp->control.stop_bpstat = bpstat_copy (tp->control.stop_bpstat);
8974
8975   /* Other fields:  */
8976   inf_status->stop_stack_dummy = stop_stack_dummy;
8977   inf_status->stopped_by_random_signal = stopped_by_random_signal;
8978
8979   inf_status->selected_frame_id = get_frame_id (get_selected_frame (NULL));
8980
8981   return inf_status;
8982 }
8983
8984 static void
8985 restore_selected_frame (const frame_id &fid)
8986 {
8987   frame_info *frame = frame_find_by_id (fid);
8988
8989   /* If inf_status->selected_frame_id is NULL, there was no previously
8990      selected frame.  */
8991   if (frame == NULL)
8992     {
8993       warning (_("Unable to restore previously selected frame."));
8994       return;
8995     }
8996
8997   select_frame (frame);
8998 }
8999
9000 /* Restore inferior session state to INF_STATUS.  */
9001
9002 void
9003 restore_infcall_control_state (struct infcall_control_state *inf_status)
9004 {
9005   struct thread_info *tp = inferior_thread ();
9006   struct inferior *inf = current_inferior ();
9007
9008   if (tp->control.step_resume_breakpoint)
9009     tp->control.step_resume_breakpoint->disposition = disp_del_at_next_stop;
9010
9011   if (tp->control.exception_resume_breakpoint)
9012     tp->control.exception_resume_breakpoint->disposition
9013       = disp_del_at_next_stop;
9014
9015   /* Handle the bpstat_copy of the chain.  */
9016   bpstat_clear (&tp->control.stop_bpstat);
9017
9018   tp->control = inf_status->thread_control;
9019   inf->control = inf_status->inferior_control;
9020
9021   /* Other fields:  */
9022   stop_stack_dummy = inf_status->stop_stack_dummy;
9023   stopped_by_random_signal = inf_status->stopped_by_random_signal;
9024
9025   if (target_has_stack)
9026     {
9027       /* The point of the try/catch is that if the stack is clobbered,
9028          walking the stack might encounter a garbage pointer and
9029          error() trying to dereference it.  */
9030       TRY
9031         {
9032           restore_selected_frame (inf_status->selected_frame_id);
9033         }
9034       CATCH (ex, RETURN_MASK_ERROR)
9035         {
9036           exception_fprintf (gdb_stderr, ex,
9037                              "Unable to restore previously selected frame:\n");
9038           /* Error in restoring the selected frame.  Select the
9039              innermost frame.  */
9040           select_frame (get_current_frame ());
9041         }
9042       END_CATCH
9043     }
9044
9045   xfree (inf_status);
9046 }
9047
9048 static void
9049 do_restore_infcall_control_state_cleanup (void *sts)
9050 {
9051   restore_infcall_control_state ((struct infcall_control_state *) sts);
9052 }
9053
9054 struct cleanup *
9055 make_cleanup_restore_infcall_control_state
9056   (struct infcall_control_state *inf_status)
9057 {
9058   return make_cleanup (do_restore_infcall_control_state_cleanup, inf_status);
9059 }
9060
9061 void
9062 discard_infcall_control_state (struct infcall_control_state *inf_status)
9063 {
9064   if (inf_status->thread_control.step_resume_breakpoint)
9065     inf_status->thread_control.step_resume_breakpoint->disposition
9066       = disp_del_at_next_stop;
9067
9068   if (inf_status->thread_control.exception_resume_breakpoint)
9069     inf_status->thread_control.exception_resume_breakpoint->disposition
9070       = disp_del_at_next_stop;
9071
9072   /* See save_infcall_control_state for info on stop_bpstat.  */
9073   bpstat_clear (&inf_status->thread_control.stop_bpstat);
9074
9075   xfree (inf_status);
9076 }
9077 \f
9078 /* See infrun.h.  */
9079
9080 void
9081 clear_exit_convenience_vars (void)
9082 {
9083   clear_internalvar (lookup_internalvar ("_exitsignal"));
9084   clear_internalvar (lookup_internalvar ("_exitcode"));
9085 }
9086 \f
9087
9088 /* User interface for reverse debugging:
9089    Set exec-direction / show exec-direction commands
9090    (returns error unless target implements to_set_exec_direction method).  */
9091
9092 enum exec_direction_kind execution_direction = EXEC_FORWARD;
9093 static const char exec_forward[] = "forward";
9094 static const char exec_reverse[] = "reverse";
9095 static const char *exec_direction = exec_forward;
9096 static const char *const exec_direction_names[] = {
9097   exec_forward,
9098   exec_reverse,
9099   NULL
9100 };
9101
9102 static void
9103 set_exec_direction_func (char *args, int from_tty,
9104                          struct cmd_list_element *cmd)
9105 {
9106   if (target_can_execute_reverse)
9107     {
9108       if (!strcmp (exec_direction, exec_forward))
9109         execution_direction = EXEC_FORWARD;
9110       else if (!strcmp (exec_direction, exec_reverse))
9111         execution_direction = EXEC_REVERSE;
9112     }
9113   else
9114     {
9115       exec_direction = exec_forward;
9116       error (_("Target does not support this operation."));
9117     }
9118 }
9119
9120 static void
9121 show_exec_direction_func (struct ui_file *out, int from_tty,
9122                           struct cmd_list_element *cmd, const char *value)
9123 {
9124   switch (execution_direction) {
9125   case EXEC_FORWARD:
9126     fprintf_filtered (out, _("Forward.\n"));
9127     break;
9128   case EXEC_REVERSE:
9129     fprintf_filtered (out, _("Reverse.\n"));
9130     break;
9131   default:
9132     internal_error (__FILE__, __LINE__,
9133                     _("bogus execution_direction value: %d"),
9134                     (int) execution_direction);
9135   }
9136 }
9137
9138 static void
9139 show_schedule_multiple (struct ui_file *file, int from_tty,
9140                         struct cmd_list_element *c, const char *value)
9141 {
9142   fprintf_filtered (file, _("Resuming the execution of threads "
9143                             "of all processes is %s.\n"), value);
9144 }
9145
9146 /* Implementation of `siginfo' variable.  */
9147
9148 static const struct internalvar_funcs siginfo_funcs =
9149 {
9150   siginfo_make_value,
9151   NULL,
9152   NULL
9153 };
9154
9155 /* Callback for infrun's target events source.  This is marked when a
9156    thread has a pending status to process.  */
9157
9158 static void
9159 infrun_async_inferior_event_handler (gdb_client_data data)
9160 {
9161   inferior_event_handler (INF_REG_EVENT, NULL);
9162 }
9163
9164 void
9165 _initialize_infrun (void)
9166 {
9167   int i;
9168   int numsigs;
9169   struct cmd_list_element *c;
9170
9171   /* Register extra event sources in the event loop.  */
9172   infrun_async_inferior_event_token
9173     = create_async_event_handler (infrun_async_inferior_event_handler, NULL);
9174
9175   add_info ("signals", info_signals_command, _("\
9176 What debugger does when program gets various signals.\n\
9177 Specify a signal as argument to print info on that signal only."));
9178   add_info_alias ("handle", "signals", 0);
9179
9180   c = add_com ("handle", class_run, handle_command, _("\
9181 Specify how to handle signals.\n\
9182 Usage: handle SIGNAL [ACTIONS]\n\
9183 Args are signals and actions to apply to those signals.\n\
9184 If no actions are specified, the current settings for the specified signals\n\
9185 will be displayed instead.\n\
9186 \n\
9187 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
9188 from 1-15 are allowed for compatibility with old versions of GDB.\n\
9189 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
9190 The special arg \"all\" is recognized to mean all signals except those\n\
9191 used by the debugger, typically SIGTRAP and SIGINT.\n\
9192 \n\
9193 Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
9194 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
9195 Stop means reenter debugger if this signal happens (implies print).\n\
9196 Print means print a message if this signal happens.\n\
9197 Pass means let program see this signal; otherwise program doesn't know.\n\
9198 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
9199 Pass and Stop may be combined.\n\
9200 \n\
9201 Multiple signals may be specified.  Signal numbers and signal names\n\
9202 may be interspersed with actions, with the actions being performed for\n\
9203 all signals cumulatively specified."));
9204   set_cmd_completer (c, handle_completer);
9205
9206   if (!dbx_commands)
9207     stop_command = add_cmd ("stop", class_obscure,
9208                             not_just_help_class_command, _("\
9209 There is no `stop' command, but you can set a hook on `stop'.\n\
9210 This allows you to set a list of commands to be run each time execution\n\
9211 of the program stops."), &cmdlist);
9212
9213   add_setshow_zuinteger_cmd ("infrun", class_maintenance, &debug_infrun, _("\
9214 Set inferior debugging."), _("\
9215 Show inferior debugging."), _("\
9216 When non-zero, inferior specific debugging is enabled."),
9217                              NULL,
9218                              show_debug_infrun,
9219                              &setdebuglist, &showdebuglist);
9220
9221   add_setshow_boolean_cmd ("displaced", class_maintenance,
9222                            &debug_displaced, _("\
9223 Set displaced stepping debugging."), _("\
9224 Show displaced stepping debugging."), _("\
9225 When non-zero, displaced stepping specific debugging is enabled."),
9226                             NULL,
9227                             show_debug_displaced,
9228                             &setdebuglist, &showdebuglist);
9229
9230   add_setshow_boolean_cmd ("non-stop", no_class,
9231                            &non_stop_1, _("\
9232 Set whether gdb controls the inferior in non-stop mode."), _("\
9233 Show whether gdb controls the inferior in non-stop mode."), _("\
9234 When debugging a multi-threaded program and this setting is\n\
9235 off (the default, also called all-stop mode), when one thread stops\n\
9236 (for a breakpoint, watchpoint, exception, or similar events), GDB stops\n\
9237 all other threads in the program while you interact with the thread of\n\
9238 interest.  When you continue or step a thread, you can allow the other\n\
9239 threads to run, or have them remain stopped, but while you inspect any\n\
9240 thread's state, all threads stop.\n\
9241 \n\
9242 In non-stop mode, when one thread stops, other threads can continue\n\
9243 to run freely.  You'll be able to step each thread independently,\n\
9244 leave it stopped or free to run as needed."),
9245                            set_non_stop,
9246                            show_non_stop,
9247                            &setlist,
9248                            &showlist);
9249
9250   numsigs = (int) GDB_SIGNAL_LAST;
9251   signal_stop = XNEWVEC (unsigned char, numsigs);
9252   signal_print = XNEWVEC (unsigned char, numsigs);
9253   signal_program = XNEWVEC (unsigned char, numsigs);
9254   signal_catch = XNEWVEC (unsigned char, numsigs);
9255   signal_pass = XNEWVEC (unsigned char, numsigs);
9256   for (i = 0; i < numsigs; i++)
9257     {
9258       signal_stop[i] = 1;
9259       signal_print[i] = 1;
9260       signal_program[i] = 1;
9261       signal_catch[i] = 0;
9262     }
9263
9264   /* Signals caused by debugger's own actions should not be given to
9265      the program afterwards.
9266
9267      Do not deliver GDB_SIGNAL_TRAP by default, except when the user
9268      explicitly specifies that it should be delivered to the target
9269      program.  Typically, that would occur when a user is debugging a
9270      target monitor on a simulator: the target monitor sets a
9271      breakpoint; the simulator encounters this breakpoint and halts
9272      the simulation handing control to GDB; GDB, noting that the stop
9273      address doesn't map to any known breakpoint, returns control back
9274      to the simulator; the simulator then delivers the hardware
9275      equivalent of a GDB_SIGNAL_TRAP to the program being
9276      debugged.  */
9277   signal_program[GDB_SIGNAL_TRAP] = 0;
9278   signal_program[GDB_SIGNAL_INT] = 0;
9279
9280   /* Signals that are not errors should not normally enter the debugger.  */
9281   signal_stop[GDB_SIGNAL_ALRM] = 0;
9282   signal_print[GDB_SIGNAL_ALRM] = 0;
9283   signal_stop[GDB_SIGNAL_VTALRM] = 0;
9284   signal_print[GDB_SIGNAL_VTALRM] = 0;
9285   signal_stop[GDB_SIGNAL_PROF] = 0;
9286   signal_print[GDB_SIGNAL_PROF] = 0;
9287   signal_stop[GDB_SIGNAL_CHLD] = 0;
9288   signal_print[GDB_SIGNAL_CHLD] = 0;
9289   signal_stop[GDB_SIGNAL_IO] = 0;
9290   signal_print[GDB_SIGNAL_IO] = 0;
9291   signal_stop[GDB_SIGNAL_POLL] = 0;
9292   signal_print[GDB_SIGNAL_POLL] = 0;
9293   signal_stop[GDB_SIGNAL_URG] = 0;
9294   signal_print[GDB_SIGNAL_URG] = 0;
9295   signal_stop[GDB_SIGNAL_WINCH] = 0;
9296   signal_print[GDB_SIGNAL_WINCH] = 0;
9297   signal_stop[GDB_SIGNAL_PRIO] = 0;
9298   signal_print[GDB_SIGNAL_PRIO] = 0;
9299
9300   /* These signals are used internally by user-level thread
9301      implementations.  (See signal(5) on Solaris.)  Like the above
9302      signals, a healthy program receives and handles them as part of
9303      its normal operation.  */
9304   signal_stop[GDB_SIGNAL_LWP] = 0;
9305   signal_print[GDB_SIGNAL_LWP] = 0;
9306   signal_stop[GDB_SIGNAL_WAITING] = 0;
9307   signal_print[GDB_SIGNAL_WAITING] = 0;
9308   signal_stop[GDB_SIGNAL_CANCEL] = 0;
9309   signal_print[GDB_SIGNAL_CANCEL] = 0;
9310   signal_stop[GDB_SIGNAL_LIBRT] = 0;
9311   signal_print[GDB_SIGNAL_LIBRT] = 0;
9312
9313   /* Update cached state.  */
9314   signal_cache_update (-1);
9315
9316   add_setshow_zinteger_cmd ("stop-on-solib-events", class_support,
9317                             &stop_on_solib_events, _("\
9318 Set stopping for shared library events."), _("\
9319 Show stopping for shared library events."), _("\
9320 If nonzero, gdb will give control to the user when the dynamic linker\n\
9321 notifies gdb of shared library events.  The most common event of interest\n\
9322 to the user would be loading/unloading of a new library."),
9323                             set_stop_on_solib_events,
9324                             show_stop_on_solib_events,
9325                             &setlist, &showlist);
9326
9327   add_setshow_enum_cmd ("follow-fork-mode", class_run,
9328                         follow_fork_mode_kind_names,
9329                         &follow_fork_mode_string, _("\
9330 Set debugger response to a program call of fork or vfork."), _("\
9331 Show debugger response to a program call of fork or vfork."), _("\
9332 A fork or vfork creates a new process.  follow-fork-mode can be:\n\
9333   parent  - the original process is debugged after a fork\n\
9334   child   - the new process is debugged after a fork\n\
9335 The unfollowed process will continue to run.\n\
9336 By default, the debugger will follow the parent process."),
9337                         NULL,
9338                         show_follow_fork_mode_string,
9339                         &setlist, &showlist);
9340
9341   add_setshow_enum_cmd ("follow-exec-mode", class_run,
9342                         follow_exec_mode_names,
9343                         &follow_exec_mode_string, _("\
9344 Set debugger response to a program call of exec."), _("\
9345 Show debugger response to a program call of exec."), _("\
9346 An exec call replaces the program image of a process.\n\
9347 \n\
9348 follow-exec-mode can be:\n\
9349 \n\
9350   new - the debugger creates a new inferior and rebinds the process\n\
9351 to this new inferior.  The program the process was running before\n\
9352 the exec call can be restarted afterwards by restarting the original\n\
9353 inferior.\n\
9354 \n\
9355   same - the debugger keeps the process bound to the same inferior.\n\
9356 The new executable image replaces the previous executable loaded in\n\
9357 the inferior.  Restarting the inferior after the exec call restarts\n\
9358 the executable the process was running after the exec call.\n\
9359 \n\
9360 By default, the debugger will use the same inferior."),
9361                         NULL,
9362                         show_follow_exec_mode_string,
9363                         &setlist, &showlist);
9364
9365   add_setshow_enum_cmd ("scheduler-locking", class_run, 
9366                         scheduler_enums, &scheduler_mode, _("\
9367 Set mode for locking scheduler during execution."), _("\
9368 Show mode for locking scheduler during execution."), _("\
9369 off    == no locking (threads may preempt at any time)\n\
9370 on     == full locking (no thread except the current thread may run)\n\
9371           This applies to both normal execution and replay mode.\n\
9372 step   == scheduler locked during stepping commands (step, next, stepi, nexti).\n\
9373           In this mode, other threads may run during other commands.\n\
9374           This applies to both normal execution and replay mode.\n\
9375 replay == scheduler locked in replay mode and unlocked during normal execution."),
9376                         set_schedlock_func,     /* traps on target vector */
9377                         show_scheduler_mode,
9378                         &setlist, &showlist);
9379
9380   add_setshow_boolean_cmd ("schedule-multiple", class_run, &sched_multi, _("\
9381 Set mode for resuming threads of all processes."), _("\
9382 Show mode for resuming threads of all processes."), _("\
9383 When on, execution commands (such as 'continue' or 'next') resume all\n\
9384 threads of all processes.  When off (which is the default), execution\n\
9385 commands only resume the threads of the current process.  The set of\n\
9386 threads that are resumed is further refined by the scheduler-locking\n\
9387 mode (see help set scheduler-locking)."),
9388                            NULL,
9389                            show_schedule_multiple,
9390                            &setlist, &showlist);
9391
9392   add_setshow_boolean_cmd ("step-mode", class_run, &step_stop_if_no_debug, _("\
9393 Set mode of the step operation."), _("\
9394 Show mode of the step operation."), _("\
9395 When set, doing a step over a function without debug line information\n\
9396 will stop at the first instruction of that function. Otherwise, the\n\
9397 function is skipped and the step command stops at a different source line."),
9398                            NULL,
9399                            show_step_stop_if_no_debug,
9400                            &setlist, &showlist);
9401
9402   add_setshow_auto_boolean_cmd ("displaced-stepping", class_run,
9403                                 &can_use_displaced_stepping, _("\
9404 Set debugger's willingness to use displaced stepping."), _("\
9405 Show debugger's willingness to use displaced stepping."), _("\
9406 If on, gdb will use displaced stepping to step over breakpoints if it is\n\
9407 supported by the target architecture.  If off, gdb will not use displaced\n\
9408 stepping to step over breakpoints, even if such is supported by the target\n\
9409 architecture.  If auto (which is the default), gdb will use displaced stepping\n\
9410 if the target architecture supports it and non-stop mode is active, but will not\n\
9411 use it in all-stop mode (see help set non-stop)."),
9412                                 NULL,
9413                                 show_can_use_displaced_stepping,
9414                                 &setlist, &showlist);
9415
9416   add_setshow_enum_cmd ("exec-direction", class_run, exec_direction_names,
9417                         &exec_direction, _("Set direction of execution.\n\
9418 Options are 'forward' or 'reverse'."),
9419                         _("Show direction of execution (forward/reverse)."),
9420                         _("Tells gdb whether to execute forward or backward."),
9421                         set_exec_direction_func, show_exec_direction_func,
9422                         &setlist, &showlist);
9423
9424   /* Set/show detach-on-fork: user-settable mode.  */
9425
9426   add_setshow_boolean_cmd ("detach-on-fork", class_run, &detach_fork, _("\
9427 Set whether gdb will detach the child of a fork."), _("\
9428 Show whether gdb will detach the child of a fork."), _("\
9429 Tells gdb whether to detach the child of a fork."),
9430                            NULL, NULL, &setlist, &showlist);
9431
9432   /* Set/show disable address space randomization mode.  */
9433
9434   add_setshow_boolean_cmd ("disable-randomization", class_support,
9435                            &disable_randomization, _("\
9436 Set disabling of debuggee's virtual address space randomization."), _("\
9437 Show disabling of debuggee's virtual address space randomization."), _("\
9438 When this mode is on (which is the default), randomization of the virtual\n\
9439 address space is disabled.  Standalone programs run with the randomization\n\
9440 enabled by default on some platforms."),
9441                            &set_disable_randomization,
9442                            &show_disable_randomization,
9443                            &setlist, &showlist);
9444
9445   /* ptid initializations */
9446   inferior_ptid = null_ptid;
9447   target_last_wait_ptid = minus_one_ptid;
9448
9449   observer_attach_thread_ptid_changed (infrun_thread_ptid_changed);
9450   observer_attach_thread_stop_requested (infrun_thread_stop_requested);
9451   observer_attach_thread_exit (infrun_thread_thread_exit);
9452   observer_attach_inferior_exit (infrun_inferior_exit);
9453
9454   /* Explicitly create without lookup, since that tries to create a
9455      value with a void typed value, and when we get here, gdbarch
9456      isn't initialized yet.  At this point, we're quite sure there
9457      isn't another convenience variable of the same name.  */
9458   create_internalvar_type_lazy ("_siginfo", &siginfo_funcs, NULL);
9459
9460   add_setshow_boolean_cmd ("observer", no_class,
9461                            &observer_mode_1, _("\
9462 Set whether gdb controls the inferior in observer mode."), _("\
9463 Show whether gdb controls the inferior in observer mode."), _("\
9464 In observer mode, GDB can get data from the inferior, but not\n\
9465 affect its execution.  Registers and memory may not be changed,\n\
9466 breakpoints may not be set, and the program cannot be interrupted\n\
9467 or signalled."),
9468                            set_observer_mode,
9469                            show_observer_mode,
9470                            &setlist,
9471                            &showlist);
9472 }