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