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