Update copyright year range in header of all files managed by GDB
[binutils-gdb.git] / gdb / infrun.c
blobd5f97e3362583781055fe182c37a5046f5c0f2a1
1 /* Target-struct-independent code to start (run) and stop an inferior
2 process.
4 Copyright (C) 1986-2023 Free Software Foundation, Inc.
6 This file is part of GDB.
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.
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.
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/>. */
21 #include "defs.h"
22 #include "displaced-stepping.h"
23 #include "infrun.h"
24 #include <ctype.h>
25 #include "symtab.h"
26 #include "frame.h"
27 #include "inferior.h"
28 #include "breakpoint.h"
29 #include "gdbcore.h"
30 #include "gdbcmd.h"
31 #include "target.h"
32 #include "target-connection.h"
33 #include "gdbthread.h"
34 #include "annotate.h"
35 #include "symfile.h"
36 #include "top.h"
37 #include "inf-loop.h"
38 #include "regcache.h"
39 #include "value.h"
40 #include "observable.h"
41 #include "language.h"
42 #include "solib.h"
43 #include "main.h"
44 #include "block.h"
45 #include "mi/mi-common.h"
46 #include "event-top.h"
47 #include "record.h"
48 #include "record-full.h"
49 #include "inline-frame.h"
50 #include "jit.h"
51 #include "tracepoint.h"
52 #include "skip.h"
53 #include "probe.h"
54 #include "objfiles.h"
55 #include "completer.h"
56 #include "target-descriptions.h"
57 #include "target-dcache.h"
58 #include "terminal.h"
59 #include "solist.h"
60 #include "gdbsupport/event-loop.h"
61 #include "thread-fsm.h"
62 #include "gdbsupport/enum-flags.h"
63 #include "progspace-and-thread.h"
64 #include "gdbsupport/gdb_optional.h"
65 #include "arch-utils.h"
66 #include "gdbsupport/scope-exit.h"
67 #include "gdbsupport/forward-scope-exit.h"
68 #include "gdbsupport/gdb_select.h"
69 #include <unordered_map>
70 #include "async-event.h"
71 #include "gdbsupport/selftest.h"
72 #include "scoped-mock-context.h"
73 #include "test-target.h"
74 #include "gdbsupport/common-debug.h"
75 #include "gdbsupport/buildargv.h"
77 /* Prototypes for local functions */
79 static void sig_print_info (enum gdb_signal);
81 static void sig_print_header (void);
83 static void follow_inferior_reset_breakpoints (void);
85 static bool currently_stepping (struct thread_info *tp);
87 static void insert_hp_step_resume_breakpoint_at_frame (frame_info_ptr);
89 static void insert_step_resume_breakpoint_at_caller (frame_info_ptr);
91 static void insert_longjmp_resume_breakpoint (struct gdbarch *, CORE_ADDR);
93 static bool maybe_software_singlestep (struct gdbarch *gdbarch);
95 static void resume (gdb_signal sig);
97 static void wait_for_inferior (inferior *inf);
99 static void restart_threads (struct thread_info *event_thread,
100 inferior *inf = nullptr);
102 static bool start_step_over (void);
104 static bool step_over_info_valid_p (void);
106 /* Asynchronous signal handler registered as event loop source for
107 when we have pending events ready to be passed to the core. */
108 static struct async_event_handler *infrun_async_inferior_event_token;
110 /* Stores whether infrun_async was previously enabled or disabled.
111 Starts off as -1, indicating "never enabled/disabled". */
112 static int infrun_is_async = -1;
114 /* See infrun.h. */
116 void
117 infrun_async (int enable)
119 if (infrun_is_async != enable)
121 infrun_is_async = enable;
123 infrun_debug_printf ("enable=%d", enable);
125 if (enable)
126 mark_async_event_handler (infrun_async_inferior_event_token);
127 else
128 clear_async_event_handler (infrun_async_inferior_event_token);
132 /* See infrun.h. */
134 void
135 mark_infrun_async_event_handler (void)
137 mark_async_event_handler (infrun_async_inferior_event_token);
140 /* When set, stop the 'step' command if we enter a function which has
141 no line number information. The normal behavior is that we step
142 over such function. */
143 bool step_stop_if_no_debug = false;
144 static void
145 show_step_stop_if_no_debug (struct ui_file *file, int from_tty,
146 struct cmd_list_element *c, const char *value)
148 gdb_printf (file, _("Mode of the step operation is %s.\n"), value);
151 /* proceed and normal_stop use this to notify the user when the
152 inferior stopped in a different thread than it had been running
153 in. */
155 static ptid_t previous_inferior_ptid;
157 /* If set (default for legacy reasons), when following a fork, GDB
158 will detach from one of the fork branches, child or parent.
159 Exactly which branch is detached depends on 'set follow-fork-mode'
160 setting. */
162 static bool detach_fork = true;
164 bool debug_infrun = false;
165 static void
166 show_debug_infrun (struct ui_file *file, int from_tty,
167 struct cmd_list_element *c, const char *value)
169 gdb_printf (file, _("Inferior debugging is %s.\n"), value);
172 /* Support for disabling address space randomization. */
174 bool disable_randomization = true;
176 static void
177 show_disable_randomization (struct ui_file *file, int from_tty,
178 struct cmd_list_element *c, const char *value)
180 if (target_supports_disable_randomization ())
181 gdb_printf (file,
182 _("Disabling randomization of debuggee's "
183 "virtual address space is %s.\n"),
184 value);
185 else
186 gdb_puts (_("Disabling randomization of debuggee's "
187 "virtual address space is unsupported on\n"
188 "this platform.\n"), file);
191 static void
192 set_disable_randomization (const char *args, int from_tty,
193 struct cmd_list_element *c)
195 if (!target_supports_disable_randomization ())
196 error (_("Disabling randomization of debuggee's "
197 "virtual address space is unsupported on\n"
198 "this platform."));
201 /* User interface for non-stop mode. */
203 bool non_stop = false;
204 static bool non_stop_1 = false;
206 static void
207 set_non_stop (const char *args, int from_tty,
208 struct cmd_list_element *c)
210 if (target_has_execution ())
212 non_stop_1 = non_stop;
213 error (_("Cannot change this setting while the inferior is running."));
216 non_stop = non_stop_1;
219 static void
220 show_non_stop (struct ui_file *file, int from_tty,
221 struct cmd_list_element *c, const char *value)
223 gdb_printf (file,
224 _("Controlling the inferior in non-stop mode is %s.\n"),
225 value);
228 /* "Observer mode" is somewhat like a more extreme version of
229 non-stop, in which all GDB operations that might affect the
230 target's execution have been disabled. */
232 static bool observer_mode = false;
233 static bool observer_mode_1 = false;
235 static void
236 set_observer_mode (const char *args, int from_tty,
237 struct cmd_list_element *c)
239 if (target_has_execution ())
241 observer_mode_1 = observer_mode;
242 error (_("Cannot change this setting while the inferior is running."));
245 observer_mode = observer_mode_1;
247 may_write_registers = !observer_mode;
248 may_write_memory = !observer_mode;
249 may_insert_breakpoints = !observer_mode;
250 may_insert_tracepoints = !observer_mode;
251 /* We can insert fast tracepoints in or out of observer mode,
252 but enable them if we're going into this mode. */
253 if (observer_mode)
254 may_insert_fast_tracepoints = true;
255 may_stop = !observer_mode;
256 update_target_permissions ();
258 /* Going *into* observer mode we must force non-stop, then
259 going out we leave it that way. */
260 if (observer_mode)
262 pagination_enabled = false;
263 non_stop = non_stop_1 = true;
266 if (from_tty)
267 gdb_printf (_("Observer mode is now %s.\n"),
268 (observer_mode ? "on" : "off"));
271 static void
272 show_observer_mode (struct ui_file *file, int from_tty,
273 struct cmd_list_element *c, const char *value)
275 gdb_printf (file, _("Observer mode is %s.\n"), value);
278 /* This updates the value of observer mode based on changes in
279 permissions. Note that we are deliberately ignoring the values of
280 may-write-registers and may-write-memory, since the user may have
281 reason to enable these during a session, for instance to turn on a
282 debugging-related global. */
284 void
285 update_observer_mode (void)
287 bool newval = (!may_insert_breakpoints
288 && !may_insert_tracepoints
289 && may_insert_fast_tracepoints
290 && !may_stop
291 && non_stop);
293 /* Let the user know if things change. */
294 if (newval != observer_mode)
295 gdb_printf (_("Observer mode is now %s.\n"),
296 (newval ? "on" : "off"));
298 observer_mode = observer_mode_1 = newval;
301 /* Tables of how to react to signals; the user sets them. */
303 static unsigned char signal_stop[GDB_SIGNAL_LAST];
304 static unsigned char signal_print[GDB_SIGNAL_LAST];
305 static unsigned char signal_program[GDB_SIGNAL_LAST];
307 /* Table of signals that are registered with "catch signal". A
308 non-zero entry indicates that the signal is caught by some "catch
309 signal" command. */
310 static unsigned char signal_catch[GDB_SIGNAL_LAST];
312 /* Table of signals that the target may silently handle.
313 This is automatically determined from the flags above,
314 and simply cached here. */
315 static unsigned char signal_pass[GDB_SIGNAL_LAST];
317 #define SET_SIGS(nsigs,sigs,flags) \
318 do { \
319 int signum = (nsigs); \
320 while (signum-- > 0) \
321 if ((sigs)[signum]) \
322 (flags)[signum] = 1; \
323 } while (0)
325 #define UNSET_SIGS(nsigs,sigs,flags) \
326 do { \
327 int signum = (nsigs); \
328 while (signum-- > 0) \
329 if ((sigs)[signum]) \
330 (flags)[signum] = 0; \
331 } while (0)
333 /* Update the target's copy of SIGNAL_PROGRAM. The sole purpose of
334 this function is to avoid exporting `signal_program'. */
336 void
337 update_signals_program_target (void)
339 target_program_signals (signal_program);
342 /* Value to pass to target_resume() to cause all threads to resume. */
344 #define RESUME_ALL minus_one_ptid
346 /* Command list pointer for the "stop" placeholder. */
348 static struct cmd_list_element *stop_command;
350 /* Nonzero if we want to give control to the user when we're notified
351 of shared library events by the dynamic linker. */
352 int stop_on_solib_events;
354 /* Enable or disable optional shared library event breakpoints
355 as appropriate when the above flag is changed. */
357 static void
358 set_stop_on_solib_events (const char *args,
359 int from_tty, struct cmd_list_element *c)
361 update_solib_breakpoints ();
364 static void
365 show_stop_on_solib_events (struct ui_file *file, int from_tty,
366 struct cmd_list_element *c, const char *value)
368 gdb_printf (file, _("Stopping for shared library events is %s.\n"),
369 value);
372 /* True after stop if current stack frame should be printed. */
374 static bool stop_print_frame;
376 /* This is a cached copy of the target/ptid/waitstatus of the last
377 event returned by target_wait().
378 This information is returned by get_last_target_status(). */
379 static process_stratum_target *target_last_proc_target;
380 static ptid_t target_last_wait_ptid;
381 static struct target_waitstatus target_last_waitstatus;
383 void init_thread_stepping_state (struct thread_info *tss);
385 static const char follow_fork_mode_child[] = "child";
386 static const char follow_fork_mode_parent[] = "parent";
388 static const char *const follow_fork_mode_kind_names[] = {
389 follow_fork_mode_child,
390 follow_fork_mode_parent,
391 nullptr
394 static const char *follow_fork_mode_string = follow_fork_mode_parent;
395 static void
396 show_follow_fork_mode_string (struct ui_file *file, int from_tty,
397 struct cmd_list_element *c, const char *value)
399 gdb_printf (file,
400 _("Debugger response to a program "
401 "call of fork or vfork is \"%s\".\n"),
402 value);
406 /* Handle changes to the inferior list based on the type of fork,
407 which process is being followed, and whether the other process
408 should be detached. On entry inferior_ptid must be the ptid of
409 the fork parent. At return inferior_ptid is the ptid of the
410 followed inferior. */
412 static bool
413 follow_fork_inferior (bool follow_child, bool detach_fork)
415 target_waitkind fork_kind = inferior_thread ()->pending_follow.kind ();
416 gdb_assert (fork_kind == TARGET_WAITKIND_FORKED
417 || fork_kind == TARGET_WAITKIND_VFORKED);
418 bool has_vforked = fork_kind == TARGET_WAITKIND_VFORKED;
419 ptid_t parent_ptid = inferior_ptid;
420 ptid_t child_ptid = inferior_thread ()->pending_follow.child_ptid ();
422 if (has_vforked
423 && !non_stop /* Non-stop always resumes both branches. */
424 && current_ui->prompt_state == PROMPT_BLOCKED
425 && !(follow_child || detach_fork || sched_multi))
427 /* The parent stays blocked inside the vfork syscall until the
428 child execs or exits. If we don't let the child run, then
429 the parent stays blocked. If we're telling the parent to run
430 in the foreground, the user will not be able to ctrl-c to get
431 back the terminal, effectively hanging the debug session. */
432 gdb_printf (gdb_stderr, _("\
433 Can not resume the parent process over vfork in the foreground while\n\
434 holding the child stopped. Try \"set detach-on-fork\" or \
435 \"set schedule-multiple\".\n"));
436 return true;
439 inferior *parent_inf = current_inferior ();
440 inferior *child_inf = nullptr;
442 gdb_assert (parent_inf->thread_waiting_for_vfork_done == nullptr);
444 if (!follow_child)
446 /* Detach new forked process? */
447 if (detach_fork)
449 /* Before detaching from the child, remove all breakpoints
450 from it. If we forked, then this has already been taken
451 care of by infrun.c. If we vforked however, any
452 breakpoint inserted in the parent is visible in the
453 child, even those added while stopped in a vfork
454 catchpoint. This will remove the breakpoints from the
455 parent also, but they'll be reinserted below. */
456 if (has_vforked)
458 /* Keep breakpoints list in sync. */
459 remove_breakpoints_inf (current_inferior ());
462 if (print_inferior_events)
464 /* Ensure that we have a process ptid. */
465 ptid_t process_ptid = ptid_t (child_ptid.pid ());
467 target_terminal::ours_for_output ();
468 gdb_printf (_("[Detaching after %s from child %s]\n"),
469 has_vforked ? "vfork" : "fork",
470 target_pid_to_str (process_ptid).c_str ());
473 else
475 /* Add process to GDB's tables. */
476 child_inf = add_inferior (child_ptid.pid ());
478 child_inf->attach_flag = parent_inf->attach_flag;
479 copy_terminal_info (child_inf, parent_inf);
480 child_inf->gdbarch = parent_inf->gdbarch;
481 copy_inferior_target_desc_info (child_inf, parent_inf);
483 child_inf->symfile_flags = SYMFILE_NO_READ;
485 /* If this is a vfork child, then the address-space is
486 shared with the parent. */
487 if (has_vforked)
489 child_inf->pspace = parent_inf->pspace;
490 child_inf->aspace = parent_inf->aspace;
492 exec_on_vfork (child_inf);
494 /* The parent will be frozen until the child is done
495 with the shared region. Keep track of the
496 parent. */
497 child_inf->vfork_parent = parent_inf;
498 child_inf->pending_detach = false;
499 parent_inf->vfork_child = child_inf;
500 parent_inf->pending_detach = false;
502 else
504 child_inf->aspace = new address_space ();
505 child_inf->pspace = new program_space (child_inf->aspace);
506 child_inf->removable = true;
507 clone_program_space (child_inf->pspace, parent_inf->pspace);
511 if (has_vforked)
513 /* If we detached from the child, then we have to be careful
514 to not insert breakpoints in the parent until the child
515 is done with the shared memory region. However, if we're
516 staying attached to the child, then we can and should
517 insert breakpoints, so that we can debug it. A
518 subsequent child exec or exit is enough to know when does
519 the child stops using the parent's address space. */
520 parent_inf->thread_waiting_for_vfork_done
521 = detach_fork ? inferior_thread () : nullptr;
522 parent_inf->pspace->breakpoints_not_allowed = detach_fork;
525 else
527 /* Follow the child. */
529 if (print_inferior_events)
531 std::string parent_pid = target_pid_to_str (parent_ptid);
532 std::string child_pid = target_pid_to_str (child_ptid);
534 target_terminal::ours_for_output ();
535 gdb_printf (_("[Attaching after %s %s to child %s]\n"),
536 parent_pid.c_str (),
537 has_vforked ? "vfork" : "fork",
538 child_pid.c_str ());
541 /* Add the new inferior first, so that the target_detach below
542 doesn't unpush the target. */
544 child_inf = add_inferior (child_ptid.pid ());
546 child_inf->attach_flag = parent_inf->attach_flag;
547 copy_terminal_info (child_inf, parent_inf);
548 child_inf->gdbarch = parent_inf->gdbarch;
549 copy_inferior_target_desc_info (child_inf, parent_inf);
551 if (has_vforked)
553 /* If this is a vfork child, then the address-space is shared
554 with the parent. */
555 child_inf->aspace = parent_inf->aspace;
556 child_inf->pspace = parent_inf->pspace;
558 exec_on_vfork (child_inf);
560 else if (detach_fork)
562 /* We follow the child and detach from the parent: move the parent's
563 program space to the child. This simplifies some things, like
564 doing "next" over fork() and landing on the expected line in the
565 child (note, that is broken with "set detach-on-fork off").
567 Before assigning brand new spaces for the parent, remove
568 breakpoints from it: because the new pspace won't match
569 currently inserted locations, the normal detach procedure
570 wouldn't remove them, and we would leave them inserted when
571 detaching. */
572 remove_breakpoints_inf (parent_inf);
574 child_inf->aspace = parent_inf->aspace;
575 child_inf->pspace = parent_inf->pspace;
576 parent_inf->aspace = new address_space ();
577 parent_inf->pspace = new program_space (parent_inf->aspace);
578 clone_program_space (parent_inf->pspace, child_inf->pspace);
580 /* The parent inferior is still the current one, so keep things
581 in sync. */
582 set_current_program_space (parent_inf->pspace);
584 else
586 child_inf->aspace = new address_space ();
587 child_inf->pspace = new program_space (child_inf->aspace);
588 child_inf->removable = true;
589 child_inf->symfile_flags = SYMFILE_NO_READ;
590 clone_program_space (child_inf->pspace, parent_inf->pspace);
594 gdb_assert (current_inferior () == parent_inf);
596 /* If we are setting up an inferior for the child, target_follow_fork is
597 responsible for pushing the appropriate targets on the new inferior's
598 target stack and adding the initial thread (with ptid CHILD_PTID).
600 If we are not setting up an inferior for the child (because following
601 the parent and detach_fork is true), it is responsible for detaching
602 from CHILD_PTID. */
603 target_follow_fork (child_inf, child_ptid, fork_kind, follow_child,
604 detach_fork);
606 /* target_follow_fork must leave the parent as the current inferior. If we
607 want to follow the child, we make it the current one below. */
608 gdb_assert (current_inferior () == parent_inf);
610 /* If there is a child inferior, target_follow_fork must have created a thread
611 for it. */
612 if (child_inf != nullptr)
613 gdb_assert (!child_inf->thread_list.empty ());
615 /* Clear the parent thread's pending follow field. Do this before calling
616 target_detach, so that the target can differentiate the two following
617 cases:
619 - We continue past a fork with "follow-fork-mode == child" &&
620 "detach-on-fork on", and therefore detach the parent. In that
621 case the target should not detach the fork child.
622 - We run to a fork catchpoint and the user types "detach". In that
623 case, the target should detach the fork child in addition to the
624 parent.
626 The former case will have pending_follow cleared, the later will have
627 pending_follow set. */
628 thread_info *parent_thread = find_thread_ptid (parent_inf, parent_ptid);
629 gdb_assert (parent_thread != nullptr);
630 parent_thread->pending_follow.set_spurious ();
632 /* Detach the parent if needed. */
633 if (follow_child)
635 /* If we're vforking, we want to hold on to the parent until
636 the child exits or execs. At child exec or exit time we
637 can remove the old breakpoints from the parent and detach
638 or resume debugging it. Otherwise, detach the parent now;
639 we'll want to reuse it's program/address spaces, but we
640 can't set them to the child before removing breakpoints
641 from the parent, otherwise, the breakpoints module could
642 decide to remove breakpoints from the wrong process (since
643 they'd be assigned to the same address space). */
645 if (has_vforked)
647 gdb_assert (child_inf->vfork_parent == nullptr);
648 gdb_assert (parent_inf->vfork_child == nullptr);
649 child_inf->vfork_parent = parent_inf;
650 child_inf->pending_detach = false;
651 parent_inf->vfork_child = child_inf;
652 parent_inf->pending_detach = detach_fork;
654 else if (detach_fork)
656 if (print_inferior_events)
658 /* Ensure that we have a process ptid. */
659 ptid_t process_ptid = ptid_t (parent_ptid.pid ());
661 target_terminal::ours_for_output ();
662 gdb_printf (_("[Detaching after fork from "
663 "parent %s]\n"),
664 target_pid_to_str (process_ptid).c_str ());
667 target_detach (parent_inf, 0);
671 /* If we ended up creating a new inferior, call post_create_inferior to inform
672 the various subcomponents. */
673 if (child_inf != nullptr)
675 /* If FOLLOW_CHILD, we leave CHILD_INF as the current inferior
676 (do not restore the parent as the current inferior). */
677 gdb::optional<scoped_restore_current_thread> maybe_restore;
679 if (!follow_child)
680 maybe_restore.emplace ();
682 switch_to_thread (*child_inf->threads ().begin ());
683 post_create_inferior (0);
686 return false;
689 /* Tell the target to follow the fork we're stopped at. Returns true
690 if the inferior should be resumed; false, if the target for some
691 reason decided it's best not to resume. */
693 static bool
694 follow_fork ()
696 bool follow_child = (follow_fork_mode_string == follow_fork_mode_child);
697 bool should_resume = true;
699 /* Copy user stepping state to the new inferior thread. FIXME: the
700 followed fork child thread should have a copy of most of the
701 parent thread structure's run control related fields, not just these.
702 Initialized to avoid "may be used uninitialized" warnings from gcc. */
703 struct breakpoint *step_resume_breakpoint = nullptr;
704 struct breakpoint *exception_resume_breakpoint = nullptr;
705 CORE_ADDR step_range_start = 0;
706 CORE_ADDR step_range_end = 0;
707 int current_line = 0;
708 symtab *current_symtab = nullptr;
709 struct frame_id step_frame_id = { 0 };
711 if (!non_stop)
713 process_stratum_target *wait_target;
714 ptid_t wait_ptid;
715 struct target_waitstatus wait_status;
717 /* Get the last target status returned by target_wait(). */
718 get_last_target_status (&wait_target, &wait_ptid, &wait_status);
720 /* If not stopped at a fork event, then there's nothing else to
721 do. */
722 if (wait_status.kind () != TARGET_WAITKIND_FORKED
723 && wait_status.kind () != TARGET_WAITKIND_VFORKED)
724 return 1;
726 /* Check if we switched over from WAIT_PTID, since the event was
727 reported. */
728 if (wait_ptid != minus_one_ptid
729 && (current_inferior ()->process_target () != wait_target
730 || inferior_ptid != wait_ptid))
732 /* We did. Switch back to WAIT_PTID thread, to tell the
733 target to follow it (in either direction). We'll
734 afterwards refuse to resume, and inform the user what
735 happened. */
736 thread_info *wait_thread = find_thread_ptid (wait_target, wait_ptid);
737 switch_to_thread (wait_thread);
738 should_resume = false;
742 thread_info *tp = inferior_thread ();
744 /* If there were any forks/vforks that were caught and are now to be
745 followed, then do so now. */
746 switch (tp->pending_follow.kind ())
748 case TARGET_WAITKIND_FORKED:
749 case TARGET_WAITKIND_VFORKED:
751 ptid_t parent, child;
752 std::unique_ptr<struct thread_fsm> thread_fsm;
754 /* If the user did a next/step, etc, over a fork call,
755 preserve the stepping state in the fork child. */
756 if (follow_child && should_resume)
758 step_resume_breakpoint = clone_momentary_breakpoint
759 (tp->control.step_resume_breakpoint);
760 step_range_start = tp->control.step_range_start;
761 step_range_end = tp->control.step_range_end;
762 current_line = tp->current_line;
763 current_symtab = tp->current_symtab;
764 step_frame_id = tp->control.step_frame_id;
765 exception_resume_breakpoint
766 = clone_momentary_breakpoint (tp->control.exception_resume_breakpoint);
767 thread_fsm = tp->release_thread_fsm ();
769 /* For now, delete the parent's sr breakpoint, otherwise,
770 parent/child sr breakpoints are considered duplicates,
771 and the child version will not be installed. Remove
772 this when the breakpoints module becomes aware of
773 inferiors and address spaces. */
774 delete_step_resume_breakpoint (tp);
775 tp->control.step_range_start = 0;
776 tp->control.step_range_end = 0;
777 tp->control.step_frame_id = null_frame_id;
778 delete_exception_resume_breakpoint (tp);
781 parent = inferior_ptid;
782 child = tp->pending_follow.child_ptid ();
784 /* If handling a vfork, stop all the inferior's threads, they will be
785 restarted when the vfork shared region is complete. */
786 if (tp->pending_follow.kind () == TARGET_WAITKIND_VFORKED
787 && target_is_non_stop_p ())
788 stop_all_threads ("handling vfork", tp->inf);
790 process_stratum_target *parent_targ = tp->inf->process_target ();
791 /* Set up inferior(s) as specified by the caller, and tell the
792 target to do whatever is necessary to follow either parent
793 or child. */
794 if (follow_fork_inferior (follow_child, detach_fork))
796 /* Target refused to follow, or there's some other reason
797 we shouldn't resume. */
798 should_resume = 0;
800 else
802 /* This makes sure we don't try to apply the "Switched
803 over from WAIT_PID" logic above. */
804 nullify_last_target_wait_ptid ();
806 /* If we followed the child, switch to it... */
807 if (follow_child)
809 thread_info *child_thr = find_thread_ptid (parent_targ, child);
810 switch_to_thread (child_thr);
812 /* ... and preserve the stepping state, in case the
813 user was stepping over the fork call. */
814 if (should_resume)
816 tp = inferior_thread ();
817 tp->control.step_resume_breakpoint
818 = step_resume_breakpoint;
819 tp->control.step_range_start = step_range_start;
820 tp->control.step_range_end = step_range_end;
821 tp->current_line = current_line;
822 tp->current_symtab = current_symtab;
823 tp->control.step_frame_id = step_frame_id;
824 tp->control.exception_resume_breakpoint
825 = exception_resume_breakpoint;
826 tp->set_thread_fsm (std::move (thread_fsm));
828 else
830 /* If we get here, it was because we're trying to
831 resume from a fork catchpoint, but, the user
832 has switched threads away from the thread that
833 forked. In that case, the resume command
834 issued is most likely not applicable to the
835 child, so just warn, and refuse to resume. */
836 warning (_("Not resuming: switched threads "
837 "before following fork child."));
840 /* Reset breakpoints in the child as appropriate. */
841 follow_inferior_reset_breakpoints ();
845 break;
846 case TARGET_WAITKIND_SPURIOUS:
847 /* Nothing to follow. */
848 break;
849 default:
850 internal_error ("Unexpected pending_follow.kind %d\n",
851 tp->pending_follow.kind ());
852 break;
855 return should_resume;
858 static void
859 follow_inferior_reset_breakpoints (void)
861 struct thread_info *tp = inferior_thread ();
863 /* Was there a step_resume breakpoint? (There was if the user
864 did a "next" at the fork() call.) If so, explicitly reset its
865 thread number. Cloned step_resume breakpoints are disabled on
866 creation, so enable it here now that it is associated with the
867 correct thread.
869 step_resumes are a form of bp that are made to be per-thread.
870 Since we created the step_resume bp when the parent process
871 was being debugged, and now are switching to the child process,
872 from the breakpoint package's viewpoint, that's a switch of
873 "threads". We must update the bp's notion of which thread
874 it is for, or it'll be ignored when it triggers. */
876 if (tp->control.step_resume_breakpoint)
878 breakpoint_re_set_thread (tp->control.step_resume_breakpoint);
879 tp->control.step_resume_breakpoint->loc->enabled = 1;
882 /* Treat exception_resume breakpoints like step_resume breakpoints. */
883 if (tp->control.exception_resume_breakpoint)
885 breakpoint_re_set_thread (tp->control.exception_resume_breakpoint);
886 tp->control.exception_resume_breakpoint->loc->enabled = 1;
889 /* Reinsert all breakpoints in the child. The user may have set
890 breakpoints after catching the fork, in which case those
891 were never set in the child, but only in the parent. This makes
892 sure the inserted breakpoints match the breakpoint list. */
894 breakpoint_re_set ();
895 insert_breakpoints ();
898 /* The child has exited or execed: resume THREAD, a thread of the parent,
899 if it was meant to be executing. */
901 static void
902 proceed_after_vfork_done (thread_info *thread)
904 if (thread->state == THREAD_RUNNING
905 && !thread->executing ()
906 && !thread->stop_requested
907 && thread->stop_signal () == GDB_SIGNAL_0)
909 infrun_debug_printf ("resuming vfork parent thread %s",
910 thread->ptid.to_string ().c_str ());
912 switch_to_thread (thread);
913 clear_proceed_status (0);
914 proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
918 /* Called whenever we notice an exec or exit event, to handle
919 detaching or resuming a vfork parent. */
921 static void
922 handle_vfork_child_exec_or_exit (int exec)
924 struct inferior *inf = current_inferior ();
926 if (inf->vfork_parent)
928 inferior *resume_parent = nullptr;
930 /* This exec or exit marks the end of the shared memory region
931 between the parent and the child. Break the bonds. */
932 inferior *vfork_parent = inf->vfork_parent;
933 inf->vfork_parent->vfork_child = nullptr;
934 inf->vfork_parent = nullptr;
936 /* If the user wanted to detach from the parent, now is the
937 time. */
938 if (vfork_parent->pending_detach)
940 struct program_space *pspace;
941 struct address_space *aspace;
943 /* follow-fork child, detach-on-fork on. */
945 vfork_parent->pending_detach = false;
947 scoped_restore_current_pspace_and_thread restore_thread;
949 /* We're letting loose of the parent. */
950 thread_info *tp = any_live_thread_of_inferior (vfork_parent);
951 switch_to_thread (tp);
953 /* We're about to detach from the parent, which implicitly
954 removes breakpoints from its address space. There's a
955 catch here: we want to reuse the spaces for the child,
956 but, parent/child are still sharing the pspace at this
957 point, although the exec in reality makes the kernel give
958 the child a fresh set of new pages. The problem here is
959 that the breakpoints module being unaware of this, would
960 likely chose the child process to write to the parent
961 address space. Swapping the child temporarily away from
962 the spaces has the desired effect. Yes, this is "sort
963 of" a hack. */
965 pspace = inf->pspace;
966 aspace = inf->aspace;
967 inf->aspace = nullptr;
968 inf->pspace = nullptr;
970 if (print_inferior_events)
972 std::string pidstr
973 = target_pid_to_str (ptid_t (vfork_parent->pid));
975 target_terminal::ours_for_output ();
977 if (exec)
979 gdb_printf (_("[Detaching vfork parent %s "
980 "after child exec]\n"), pidstr.c_str ());
982 else
984 gdb_printf (_("[Detaching vfork parent %s "
985 "after child exit]\n"), pidstr.c_str ());
989 target_detach (vfork_parent, 0);
991 /* Put it back. */
992 inf->pspace = pspace;
993 inf->aspace = aspace;
995 else if (exec)
997 /* We're staying attached to the parent, so, really give the
998 child a new address space. */
999 inf->pspace = new program_space (maybe_new_address_space ());
1000 inf->aspace = inf->pspace->aspace;
1001 inf->removable = true;
1002 set_current_program_space (inf->pspace);
1004 resume_parent = vfork_parent;
1006 else
1008 /* If this is a vfork child exiting, then the pspace and
1009 aspaces were shared with the parent. Since we're
1010 reporting the process exit, we'll be mourning all that is
1011 found in the address space, and switching to null_ptid,
1012 preparing to start a new inferior. But, since we don't
1013 want to clobber the parent's address/program spaces, we
1014 go ahead and create a new one for this exiting
1015 inferior. */
1017 /* Switch to no-thread while running clone_program_space, so
1018 that clone_program_space doesn't want to read the
1019 selected frame of a dead process. */
1020 scoped_restore_current_thread restore_thread;
1021 switch_to_no_thread ();
1023 inf->pspace = new program_space (maybe_new_address_space ());
1024 inf->aspace = inf->pspace->aspace;
1025 set_current_program_space (inf->pspace);
1026 inf->removable = true;
1027 inf->symfile_flags = SYMFILE_NO_READ;
1028 clone_program_space (inf->pspace, vfork_parent->pspace);
1030 resume_parent = vfork_parent;
1033 gdb_assert (current_program_space == inf->pspace);
1035 if (non_stop && resume_parent != nullptr)
1037 /* If the user wanted the parent to be running, let it go
1038 free now. */
1039 scoped_restore_current_thread restore_thread;
1041 infrun_debug_printf ("resuming vfork parent process %d",
1042 resume_parent->pid);
1044 for (thread_info *thread : resume_parent->threads ())
1045 proceed_after_vfork_done (thread);
1050 /* Handle TARGET_WAITKIND_VFORK_DONE. */
1052 static void
1053 handle_vfork_done (thread_info *event_thread)
1055 /* We only care about this event if inferior::thread_waiting_for_vfork_done is
1056 set, that is if we are waiting for a vfork child not under our control
1057 (because we detached it) to exec or exit.
1059 If an inferior has vforked and we are debugging the child, we don't use
1060 the vfork-done event to get notified about the end of the shared address
1061 space window. We rely instead on the child's exec or exit event, and the
1062 inferior::vfork_{parent,child} fields are used instead. See
1063 handle_vfork_child_exec_or_exit for that. */
1064 if (event_thread->inf->thread_waiting_for_vfork_done == nullptr)
1066 infrun_debug_printf ("not waiting for a vfork-done event");
1067 return;
1070 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
1072 /* We stopped all threads (other than the vforking thread) of the inferior in
1073 follow_fork and kept them stopped until now. It should therefore not be
1074 possible for another thread to have reported a vfork during that window.
1075 If THREAD_WAITING_FOR_VFORK_DONE is set, it has to be the same thread whose
1076 vfork-done we are handling right now. */
1077 gdb_assert (event_thread->inf->thread_waiting_for_vfork_done == event_thread);
1079 event_thread->inf->thread_waiting_for_vfork_done = nullptr;
1080 event_thread->inf->pspace->breakpoints_not_allowed = 0;
1082 /* On non-stop targets, we stopped all the inferior's threads in follow_fork,
1083 resume them now. On all-stop targets, everything that needs to be resumed
1084 will be when we resume the event thread. */
1085 if (target_is_non_stop_p ())
1087 /* restart_threads and start_step_over may change the current thread, make
1088 sure we leave the event thread as the current thread. */
1089 scoped_restore_current_thread restore_thread;
1091 insert_breakpoints ();
1092 start_step_over ();
1094 if (!step_over_info_valid_p ())
1095 restart_threads (event_thread, event_thread->inf);
1099 /* Enum strings for "set|show follow-exec-mode". */
1101 static const char follow_exec_mode_new[] = "new";
1102 static const char follow_exec_mode_same[] = "same";
1103 static const char *const follow_exec_mode_names[] =
1105 follow_exec_mode_new,
1106 follow_exec_mode_same,
1107 nullptr,
1110 static const char *follow_exec_mode_string = follow_exec_mode_same;
1111 static void
1112 show_follow_exec_mode_string (struct ui_file *file, int from_tty,
1113 struct cmd_list_element *c, const char *value)
1115 gdb_printf (file, _("Follow exec mode is \"%s\".\n"), value);
1118 /* EXEC_FILE_TARGET is assumed to be non-NULL. */
1120 static void
1121 follow_exec (ptid_t ptid, const char *exec_file_target)
1123 int pid = ptid.pid ();
1124 ptid_t process_ptid;
1126 /* Switch terminal for any messages produced e.g. by
1127 breakpoint_re_set. */
1128 target_terminal::ours_for_output ();
1130 /* This is an exec event that we actually wish to pay attention to.
1131 Refresh our symbol table to the newly exec'd program, remove any
1132 momentary bp's, etc.
1134 If there are breakpoints, they aren't really inserted now,
1135 since the exec() transformed our inferior into a fresh set
1136 of instructions.
1138 We want to preserve symbolic breakpoints on the list, since
1139 we have hopes that they can be reset after the new a.out's
1140 symbol table is read.
1142 However, any "raw" breakpoints must be removed from the list
1143 (e.g., the solib bp's), since their address is probably invalid
1144 now.
1146 And, we DON'T want to call delete_breakpoints() here, since
1147 that may write the bp's "shadow contents" (the instruction
1148 value that was overwritten with a TRAP instruction). Since
1149 we now have a new a.out, those shadow contents aren't valid. */
1151 mark_breakpoints_out ();
1153 /* The target reports the exec event to the main thread, even if
1154 some other thread does the exec, and even if the main thread was
1155 stopped or already gone. We may still have non-leader threads of
1156 the process on our list. E.g., on targets that don't have thread
1157 exit events (like remote); or on native Linux in non-stop mode if
1158 there were only two threads in the inferior and the non-leader
1159 one is the one that execs (and nothing forces an update of the
1160 thread list up to here). When debugging remotely, it's best to
1161 avoid extra traffic, when possible, so avoid syncing the thread
1162 list with the target, and instead go ahead and delete all threads
1163 of the process but one that reported the event. Note this must
1164 be done before calling update_breakpoints_after_exec, as
1165 otherwise clearing the threads' resources would reference stale
1166 thread breakpoints -- it may have been one of these threads that
1167 stepped across the exec. We could just clear their stepping
1168 states, but as long as we're iterating, might as well delete
1169 them. Deleting them now rather than at the next user-visible
1170 stop provides a nicer sequence of events for user and MI
1171 notifications. */
1172 for (thread_info *th : all_threads_safe ())
1173 if (th->ptid.pid () == pid && th->ptid != ptid)
1174 delete_thread (th);
1176 /* We also need to clear any left over stale state for the
1177 leader/event thread. E.g., if there was any step-resume
1178 breakpoint or similar, it's gone now. We cannot truly
1179 step-to-next statement through an exec(). */
1180 thread_info *th = inferior_thread ();
1181 th->control.step_resume_breakpoint = nullptr;
1182 th->control.exception_resume_breakpoint = nullptr;
1183 th->control.single_step_breakpoints = nullptr;
1184 th->control.step_range_start = 0;
1185 th->control.step_range_end = 0;
1187 /* The user may have had the main thread held stopped in the
1188 previous image (e.g., schedlock on, or non-stop). Release
1189 it now. */
1190 th->stop_requested = 0;
1192 update_breakpoints_after_exec ();
1194 /* What is this a.out's name? */
1195 process_ptid = ptid_t (pid);
1196 gdb_printf (_("%s is executing new program: %s\n"),
1197 target_pid_to_str (process_ptid).c_str (),
1198 exec_file_target);
1200 /* We've followed the inferior through an exec. Therefore, the
1201 inferior has essentially been killed & reborn. */
1203 breakpoint_init_inferior (inf_execd);
1205 gdb::unique_xmalloc_ptr<char> exec_file_host
1206 = exec_file_find (exec_file_target, nullptr);
1208 /* If we were unable to map the executable target pathname onto a host
1209 pathname, tell the user that. Otherwise GDB's subsequent behavior
1210 is confusing. Maybe it would even be better to stop at this point
1211 so that the user can specify a file manually before continuing. */
1212 if (exec_file_host == nullptr)
1213 warning (_("Could not load symbols for executable %s.\n"
1214 "Do you need \"set sysroot\"?"),
1215 exec_file_target);
1217 /* Reset the shared library package. This ensures that we get a
1218 shlib event when the child reaches "_start", at which point the
1219 dld will have had a chance to initialize the child. */
1220 /* Also, loading a symbol file below may trigger symbol lookups, and
1221 we don't want those to be satisfied by the libraries of the
1222 previous incarnation of this process. */
1223 no_shared_libraries (nullptr, 0);
1225 struct inferior *inf = current_inferior ();
1227 if (follow_exec_mode_string == follow_exec_mode_new)
1229 /* The user wants to keep the old inferior and program spaces
1230 around. Create a new fresh one, and switch to it. */
1232 /* Do exit processing for the original inferior before setting the new
1233 inferior's pid. Having two inferiors with the same pid would confuse
1234 find_inferior_p(t)id. Transfer the terminal state and info from the
1235 old to the new inferior. */
1236 inferior *new_inferior = add_inferior_with_spaces ();
1238 swap_terminal_info (new_inferior, inf);
1239 exit_inferior_silent (inf);
1241 new_inferior->pid = pid;
1242 target_follow_exec (new_inferior, ptid, exec_file_target);
1244 /* We continue with the new inferior. */
1245 inf = new_inferior;
1247 else
1249 /* The old description may no longer be fit for the new image.
1250 E.g, a 64-bit process exec'ed a 32-bit process. Clear the
1251 old description; we'll read a new one below. No need to do
1252 this on "follow-exec-mode new", as the old inferior stays
1253 around (its description is later cleared/refetched on
1254 restart). */
1255 target_clear_description ();
1256 target_follow_exec (inf, ptid, exec_file_target);
1259 gdb_assert (current_inferior () == inf);
1260 gdb_assert (current_program_space == inf->pspace);
1262 /* Attempt to open the exec file. SYMFILE_DEFER_BP_RESET is used
1263 because the proper displacement for a PIE (Position Independent
1264 Executable) main symbol file will only be computed by
1265 solib_create_inferior_hook below. breakpoint_re_set would fail
1266 to insert the breakpoints with the zero displacement. */
1267 try_open_exec_file (exec_file_host.get (), inf, SYMFILE_DEFER_BP_RESET);
1269 /* If the target can specify a description, read it. Must do this
1270 after flipping to the new executable (because the target supplied
1271 description must be compatible with the executable's
1272 architecture, and the old executable may e.g., be 32-bit, while
1273 the new one 64-bit), and before anything involving memory or
1274 registers. */
1275 target_find_description ();
1277 gdb::observers::inferior_execd.notify (inf);
1279 breakpoint_re_set ();
1281 /* Reinsert all breakpoints. (Those which were symbolic have
1282 been reset to the proper address in the new a.out, thanks
1283 to symbol_file_command...). */
1284 insert_breakpoints ();
1286 /* The next resume of this inferior should bring it to the shlib
1287 startup breakpoints. (If the user had also set bp's on
1288 "main" from the old (parent) process, then they'll auto-
1289 matically get reset there in the new process.). */
1292 /* The chain of threads that need to do a step-over operation to get
1293 past e.g., a breakpoint. What technique is used to step over the
1294 breakpoint/watchpoint does not matter -- all threads end up in the
1295 same queue, to maintain rough temporal order of execution, in order
1296 to avoid starvation, otherwise, we could e.g., find ourselves
1297 constantly stepping the same couple threads past their breakpoints
1298 over and over, if the single-step finish fast enough. */
1299 thread_step_over_list global_thread_step_over_list;
1301 /* Bit flags indicating what the thread needs to step over. */
1303 enum step_over_what_flag
1305 /* Step over a breakpoint. */
1306 STEP_OVER_BREAKPOINT = 1,
1308 /* Step past a non-continuable watchpoint, in order to let the
1309 instruction execute so we can evaluate the watchpoint
1310 expression. */
1311 STEP_OVER_WATCHPOINT = 2
1313 DEF_ENUM_FLAGS_TYPE (enum step_over_what_flag, step_over_what);
1315 /* Info about an instruction that is being stepped over. */
1317 struct step_over_info
1319 /* If we're stepping past a breakpoint, this is the address space
1320 and address of the instruction the breakpoint is set at. We'll
1321 skip inserting all breakpoints here. Valid iff ASPACE is
1322 non-NULL. */
1323 const address_space *aspace = nullptr;
1324 CORE_ADDR address = 0;
1326 /* The instruction being stepped over triggers a nonsteppable
1327 watchpoint. If true, we'll skip inserting watchpoints. */
1328 int nonsteppable_watchpoint_p = 0;
1330 /* The thread's global number. */
1331 int thread = -1;
1334 /* The step-over info of the location that is being stepped over.
1336 Note that with async/breakpoint always-inserted mode, a user might
1337 set a new breakpoint/watchpoint/etc. exactly while a breakpoint is
1338 being stepped over. As setting a new breakpoint inserts all
1339 breakpoints, we need to make sure the breakpoint being stepped over
1340 isn't inserted then. We do that by only clearing the step-over
1341 info when the step-over is actually finished (or aborted).
1343 Presently GDB can only step over one breakpoint at any given time.
1344 Given threads that can't run code in the same address space as the
1345 breakpoint's can't really miss the breakpoint, GDB could be taught
1346 to step-over at most one breakpoint per address space (so this info
1347 could move to the address space object if/when GDB is extended).
1348 The set of breakpoints being stepped over will normally be much
1349 smaller than the set of all breakpoints, so a flag in the
1350 breakpoint location structure would be wasteful. A separate list
1351 also saves complexity and run-time, as otherwise we'd have to go
1352 through all breakpoint locations clearing their flag whenever we
1353 start a new sequence. Similar considerations weigh against storing
1354 this info in the thread object. Plus, not all step overs actually
1355 have breakpoint locations -- e.g., stepping past a single-step
1356 breakpoint, or stepping to complete a non-continuable
1357 watchpoint. */
1358 static struct step_over_info step_over_info;
1360 /* Record the address of the breakpoint/instruction we're currently
1361 stepping over.
1362 N.B. We record the aspace and address now, instead of say just the thread,
1363 because when we need the info later the thread may be running. */
1365 static void
1366 set_step_over_info (const address_space *aspace, CORE_ADDR address,
1367 int nonsteppable_watchpoint_p,
1368 int thread)
1370 step_over_info.aspace = aspace;
1371 step_over_info.address = address;
1372 step_over_info.nonsteppable_watchpoint_p = nonsteppable_watchpoint_p;
1373 step_over_info.thread = thread;
1376 /* Called when we're not longer stepping over a breakpoint / an
1377 instruction, so all breakpoints are free to be (re)inserted. */
1379 static void
1380 clear_step_over_info (void)
1382 infrun_debug_printf ("clearing step over info");
1383 step_over_info.aspace = nullptr;
1384 step_over_info.address = 0;
1385 step_over_info.nonsteppable_watchpoint_p = 0;
1386 step_over_info.thread = -1;
1389 /* See infrun.h. */
1392 stepping_past_instruction_at (struct address_space *aspace,
1393 CORE_ADDR address)
1395 return (step_over_info.aspace != nullptr
1396 && breakpoint_address_match (aspace, address,
1397 step_over_info.aspace,
1398 step_over_info.address));
1401 /* See infrun.h. */
1404 thread_is_stepping_over_breakpoint (int thread)
1406 return (step_over_info.thread != -1
1407 && thread == step_over_info.thread);
1410 /* See infrun.h. */
1413 stepping_past_nonsteppable_watchpoint (void)
1415 return step_over_info.nonsteppable_watchpoint_p;
1418 /* Returns true if step-over info is valid. */
1420 static bool
1421 step_over_info_valid_p (void)
1423 return (step_over_info.aspace != nullptr
1424 || stepping_past_nonsteppable_watchpoint ());
1428 /* Displaced stepping. */
1430 /* In non-stop debugging mode, we must take special care to manage
1431 breakpoints properly; in particular, the traditional strategy for
1432 stepping a thread past a breakpoint it has hit is unsuitable.
1433 'Displaced stepping' is a tactic for stepping one thread past a
1434 breakpoint it has hit while ensuring that other threads running
1435 concurrently will hit the breakpoint as they should.
1437 The traditional way to step a thread T off a breakpoint in a
1438 multi-threaded program in all-stop mode is as follows:
1440 a0) Initially, all threads are stopped, and breakpoints are not
1441 inserted.
1442 a1) We single-step T, leaving breakpoints uninserted.
1443 a2) We insert breakpoints, and resume all threads.
1445 In non-stop debugging, however, this strategy is unsuitable: we
1446 don't want to have to stop all threads in the system in order to
1447 continue or step T past a breakpoint. Instead, we use displaced
1448 stepping:
1450 n0) Initially, T is stopped, other threads are running, and
1451 breakpoints are inserted.
1452 n1) We copy the instruction "under" the breakpoint to a separate
1453 location, outside the main code stream, making any adjustments
1454 to the instruction, register, and memory state as directed by
1455 T's architecture.
1456 n2) We single-step T over the instruction at its new location.
1457 n3) We adjust the resulting register and memory state as directed
1458 by T's architecture. This includes resetting T's PC to point
1459 back into the main instruction stream.
1460 n4) We resume T.
1462 This approach depends on the following gdbarch methods:
1464 - gdbarch_max_insn_length and gdbarch_displaced_step_location
1465 indicate where to copy the instruction, and how much space must
1466 be reserved there. We use these in step n1.
1468 - gdbarch_displaced_step_copy_insn copies a instruction to a new
1469 address, and makes any necessary adjustments to the instruction,
1470 register contents, and memory. We use this in step n1.
1472 - gdbarch_displaced_step_fixup adjusts registers and memory after
1473 we have successfully single-stepped the instruction, to yield the
1474 same effect the instruction would have had if we had executed it
1475 at its original address. We use this in step n3.
1477 The gdbarch_displaced_step_copy_insn and
1478 gdbarch_displaced_step_fixup functions must be written so that
1479 copying an instruction with gdbarch_displaced_step_copy_insn,
1480 single-stepping across the copied instruction, and then applying
1481 gdbarch_displaced_insn_fixup should have the same effects on the
1482 thread's memory and registers as stepping the instruction in place
1483 would have. Exactly which responsibilities fall to the copy and
1484 which fall to the fixup is up to the author of those functions.
1486 See the comments in gdbarch.sh for details.
1488 Note that displaced stepping and software single-step cannot
1489 currently be used in combination, although with some care I think
1490 they could be made to. Software single-step works by placing
1491 breakpoints on all possible subsequent instructions; if the
1492 displaced instruction is a PC-relative jump, those breakpoints
1493 could fall in very strange places --- on pages that aren't
1494 executable, or at addresses that are not proper instruction
1495 boundaries. (We do generally let other threads run while we wait
1496 to hit the software single-step breakpoint, and they might
1497 encounter such a corrupted instruction.) One way to work around
1498 this would be to have gdbarch_displaced_step_copy_insn fully
1499 simulate the effect of PC-relative instructions (and return NULL)
1500 on architectures that use software single-stepping.
1502 In non-stop mode, we can have independent and simultaneous step
1503 requests, so more than one thread may need to simultaneously step
1504 over a breakpoint. The current implementation assumes there is
1505 only one scratch space per process. In this case, we have to
1506 serialize access to the scratch space. If thread A wants to step
1507 over a breakpoint, but we are currently waiting for some other
1508 thread to complete a displaced step, we leave thread A stopped and
1509 place it in the displaced_step_request_queue. Whenever a displaced
1510 step finishes, we pick the next thread in the queue and start a new
1511 displaced step operation on it. See displaced_step_prepare and
1512 displaced_step_finish for details. */
1514 /* Return true if THREAD is doing a displaced step. */
1516 static bool
1517 displaced_step_in_progress_thread (thread_info *thread)
1519 gdb_assert (thread != nullptr);
1521 return thread->displaced_step_state.in_progress ();
1524 /* Return true if INF has a thread doing a displaced step. */
1526 static bool
1527 displaced_step_in_progress (inferior *inf)
1529 return inf->displaced_step_state.in_progress_count > 0;
1532 /* Return true if any thread is doing a displaced step. */
1534 static bool
1535 displaced_step_in_progress_any_thread ()
1537 for (inferior *inf : all_non_exited_inferiors ())
1539 if (displaced_step_in_progress (inf))
1540 return true;
1543 return false;
1546 static void
1547 infrun_inferior_exit (struct inferior *inf)
1549 inf->displaced_step_state.reset ();
1550 inf->thread_waiting_for_vfork_done = nullptr;
1553 static void
1554 infrun_inferior_execd (inferior *inf)
1556 /* If some threads where was doing a displaced step in this inferior at the
1557 moment of the exec, they no longer exist. Even if the exec'ing thread
1558 doing a displaced step, we don't want to to any fixup nor restore displaced
1559 stepping buffer bytes. */
1560 inf->displaced_step_state.reset ();
1562 for (thread_info *thread : inf->threads ())
1563 thread->displaced_step_state.reset ();
1565 /* Since an in-line step is done with everything else stopped, if there was
1566 one in progress at the time of the exec, it must have been the exec'ing
1567 thread. */
1568 clear_step_over_info ();
1570 inf->thread_waiting_for_vfork_done = nullptr;
1573 /* If ON, and the architecture supports it, GDB will use displaced
1574 stepping to step over breakpoints. If OFF, or if the architecture
1575 doesn't support it, GDB will instead use the traditional
1576 hold-and-step approach. If AUTO (which is the default), GDB will
1577 decide which technique to use to step over breakpoints depending on
1578 whether the target works in a non-stop way (see use_displaced_stepping). */
1580 static enum auto_boolean can_use_displaced_stepping = AUTO_BOOLEAN_AUTO;
1582 static void
1583 show_can_use_displaced_stepping (struct ui_file *file, int from_tty,
1584 struct cmd_list_element *c,
1585 const char *value)
1587 if (can_use_displaced_stepping == AUTO_BOOLEAN_AUTO)
1588 gdb_printf (file,
1589 _("Debugger's willingness to use displaced stepping "
1590 "to step over breakpoints is %s (currently %s).\n"),
1591 value, target_is_non_stop_p () ? "on" : "off");
1592 else
1593 gdb_printf (file,
1594 _("Debugger's willingness to use displaced stepping "
1595 "to step over breakpoints is %s.\n"), value);
1598 /* Return true if the gdbarch implements the required methods to use
1599 displaced stepping. */
1601 static bool
1602 gdbarch_supports_displaced_stepping (gdbarch *arch)
1604 /* Only check for the presence of `prepare`. The gdbarch verification ensures
1605 that if `prepare` is provided, so is `finish`. */
1606 return gdbarch_displaced_step_prepare_p (arch);
1609 /* Return non-zero if displaced stepping can/should be used to step
1610 over breakpoints of thread TP. */
1612 static bool
1613 use_displaced_stepping (thread_info *tp)
1615 /* If the user disabled it explicitly, don't use displaced stepping. */
1616 if (can_use_displaced_stepping == AUTO_BOOLEAN_FALSE)
1617 return false;
1619 /* If "auto", only use displaced stepping if the target operates in a non-stop
1620 way. */
1621 if (can_use_displaced_stepping == AUTO_BOOLEAN_AUTO
1622 && !target_is_non_stop_p ())
1623 return false;
1625 gdbarch *gdbarch = get_thread_regcache (tp)->arch ();
1627 /* If the architecture doesn't implement displaced stepping, don't use
1628 it. */
1629 if (!gdbarch_supports_displaced_stepping (gdbarch))
1630 return false;
1632 /* If recording, don't use displaced stepping. */
1633 if (find_record_target () != nullptr)
1634 return false;
1636 /* If displaced stepping failed before for this inferior, don't bother trying
1637 again. */
1638 if (tp->inf->displaced_step_state.failed_before)
1639 return false;
1641 return true;
1644 /* Simple function wrapper around displaced_step_thread_state::reset. */
1646 static void
1647 displaced_step_reset (displaced_step_thread_state *displaced)
1649 displaced->reset ();
1652 /* A cleanup that wraps displaced_step_reset. We use this instead of, say,
1653 SCOPE_EXIT, because it needs to be discardable with "cleanup.release ()". */
1655 using displaced_step_reset_cleanup = FORWARD_SCOPE_EXIT (displaced_step_reset);
1657 /* See infrun.h. */
1659 std::string
1660 displaced_step_dump_bytes (const gdb_byte *buf, size_t len)
1662 std::string ret;
1664 for (size_t i = 0; i < len; i++)
1666 if (i == 0)
1667 ret += string_printf ("%02x", buf[i]);
1668 else
1669 ret += string_printf (" %02x", buf[i]);
1672 return ret;
1675 /* Prepare to single-step, using displaced stepping.
1677 Note that we cannot use displaced stepping when we have a signal to
1678 deliver. If we have a signal to deliver and an instruction to step
1679 over, then after the step, there will be no indication from the
1680 target whether the thread entered a signal handler or ignored the
1681 signal and stepped over the instruction successfully --- both cases
1682 result in a simple SIGTRAP. In the first case we mustn't do a
1683 fixup, and in the second case we must --- but we can't tell which.
1684 Comments in the code for 'random signals' in handle_inferior_event
1685 explain how we handle this case instead.
1687 Returns DISPLACED_STEP_PREPARE_STATUS_OK if preparing was successful -- this
1688 thread is going to be stepped now; DISPLACED_STEP_PREPARE_STATUS_UNAVAILABLE
1689 if displaced stepping this thread got queued; or
1690 DISPLACED_STEP_PREPARE_STATUS_CANT if this instruction can't be displaced
1691 stepped. */
1693 static displaced_step_prepare_status
1694 displaced_step_prepare_throw (thread_info *tp)
1696 regcache *regcache = get_thread_regcache (tp);
1697 struct gdbarch *gdbarch = regcache->arch ();
1698 displaced_step_thread_state &disp_step_thread_state
1699 = tp->displaced_step_state;
1701 /* We should never reach this function if the architecture does not
1702 support displaced stepping. */
1703 gdb_assert (gdbarch_supports_displaced_stepping (gdbarch));
1705 /* Nor if the thread isn't meant to step over a breakpoint. */
1706 gdb_assert (tp->control.trap_expected);
1708 /* Disable range stepping while executing in the scratch pad. We
1709 want a single-step even if executing the displaced instruction in
1710 the scratch buffer lands within the stepping range (e.g., a
1711 jump/branch). */
1712 tp->control.may_range_step = 0;
1714 /* We are about to start a displaced step for this thread. If one is already
1715 in progress, something's wrong. */
1716 gdb_assert (!disp_step_thread_state.in_progress ());
1718 if (tp->inf->displaced_step_state.unavailable)
1720 /* The gdbarch tells us it's not worth asking to try a prepare because
1721 it is likely that it will return unavailable, so don't bother asking. */
1723 displaced_debug_printf ("deferring step of %s",
1724 tp->ptid.to_string ().c_str ());
1726 global_thread_step_over_chain_enqueue (tp);
1727 return DISPLACED_STEP_PREPARE_STATUS_UNAVAILABLE;
1730 displaced_debug_printf ("displaced-stepping %s now",
1731 tp->ptid.to_string ().c_str ());
1733 scoped_restore_current_thread restore_thread;
1735 switch_to_thread (tp);
1737 CORE_ADDR original_pc = regcache_read_pc (regcache);
1738 CORE_ADDR displaced_pc;
1740 displaced_step_prepare_status status
1741 = gdbarch_displaced_step_prepare (gdbarch, tp, displaced_pc);
1743 if (status == DISPLACED_STEP_PREPARE_STATUS_CANT)
1745 displaced_debug_printf ("failed to prepare (%s)",
1746 tp->ptid.to_string ().c_str ());
1748 return DISPLACED_STEP_PREPARE_STATUS_CANT;
1750 else if (status == DISPLACED_STEP_PREPARE_STATUS_UNAVAILABLE)
1752 /* Not enough displaced stepping resources available, defer this
1753 request by placing it the queue. */
1755 displaced_debug_printf ("not enough resources available, "
1756 "deferring step of %s",
1757 tp->ptid.to_string ().c_str ());
1759 global_thread_step_over_chain_enqueue (tp);
1761 return DISPLACED_STEP_PREPARE_STATUS_UNAVAILABLE;
1764 gdb_assert (status == DISPLACED_STEP_PREPARE_STATUS_OK);
1766 /* Save the information we need to fix things up if the step
1767 succeeds. */
1768 disp_step_thread_state.set (gdbarch);
1770 tp->inf->displaced_step_state.in_progress_count++;
1772 displaced_debug_printf ("prepared successfully thread=%s, "
1773 "original_pc=%s, displaced_pc=%s",
1774 tp->ptid.to_string ().c_str (),
1775 paddress (gdbarch, original_pc),
1776 paddress (gdbarch, displaced_pc));
1778 return DISPLACED_STEP_PREPARE_STATUS_OK;
1781 /* Wrapper for displaced_step_prepare_throw that disabled further
1782 attempts at displaced stepping if we get a memory error. */
1784 static displaced_step_prepare_status
1785 displaced_step_prepare (thread_info *thread)
1787 displaced_step_prepare_status status
1788 = DISPLACED_STEP_PREPARE_STATUS_CANT;
1792 status = displaced_step_prepare_throw (thread);
1794 catch (const gdb_exception_error &ex)
1796 if (ex.error != MEMORY_ERROR
1797 && ex.error != NOT_SUPPORTED_ERROR)
1798 throw;
1800 infrun_debug_printf ("caught exception, disabling displaced stepping: %s",
1801 ex.what ());
1803 /* Be verbose if "set displaced-stepping" is "on", silent if
1804 "auto". */
1805 if (can_use_displaced_stepping == AUTO_BOOLEAN_TRUE)
1807 warning (_("disabling displaced stepping: %s"),
1808 ex.what ());
1811 /* Disable further displaced stepping attempts. */
1812 thread->inf->displaced_step_state.failed_before = 1;
1815 return status;
1818 /* If we displaced stepped an instruction successfully, adjust registers and
1819 memory to yield the same effect the instruction would have had if we had
1820 executed it at its original address, and return
1821 DISPLACED_STEP_FINISH_STATUS_OK. If the instruction didn't complete,
1822 relocate the PC and return DISPLACED_STEP_FINISH_STATUS_NOT_EXECUTED.
1824 If the thread wasn't displaced stepping, return
1825 DISPLACED_STEP_FINISH_STATUS_OK as well. */
1827 static displaced_step_finish_status
1828 displaced_step_finish (thread_info *event_thread, enum gdb_signal signal)
1830 displaced_step_thread_state *displaced = &event_thread->displaced_step_state;
1832 /* Was this thread performing a displaced step? */
1833 if (!displaced->in_progress ())
1834 return DISPLACED_STEP_FINISH_STATUS_OK;
1836 gdb_assert (event_thread->inf->displaced_step_state.in_progress_count > 0);
1837 event_thread->inf->displaced_step_state.in_progress_count--;
1839 /* Fixup may need to read memory/registers. Switch to the thread
1840 that we're fixing up. Also, target_stopped_by_watchpoint checks
1841 the current thread, and displaced_step_restore performs ptid-dependent
1842 memory accesses using current_inferior(). */
1843 switch_to_thread (event_thread);
1845 displaced_step_reset_cleanup cleanup (displaced);
1847 /* Do the fixup, and release the resources acquired to do the displaced
1848 step. */
1849 return gdbarch_displaced_step_finish (displaced->get_original_gdbarch (),
1850 event_thread, signal);
1853 /* Data to be passed around while handling an event. This data is
1854 discarded between events. */
1855 struct execution_control_state
1857 explicit execution_control_state (thread_info *thr = nullptr)
1858 : ptid (thr == nullptr ? null_ptid : thr->ptid),
1859 event_thread (thr)
1863 process_stratum_target *target = nullptr;
1864 ptid_t ptid;
1865 /* The thread that got the event, if this was a thread event; NULL
1866 otherwise. */
1867 struct thread_info *event_thread;
1869 struct target_waitstatus ws;
1870 int stop_func_filled_in = 0;
1871 CORE_ADDR stop_func_start = 0;
1872 CORE_ADDR stop_func_end = 0;
1873 const char *stop_func_name = nullptr;
1874 int wait_some_more = 0;
1876 /* True if the event thread hit the single-step breakpoint of
1877 another thread. Thus the event doesn't cause a stop, the thread
1878 needs to be single-stepped past the single-step breakpoint before
1879 we can switch back to the original stepping thread. */
1880 int hit_singlestep_breakpoint = 0;
1883 static void keep_going_pass_signal (struct execution_control_state *ecs);
1884 static void prepare_to_wait (struct execution_control_state *ecs);
1885 static bool keep_going_stepped_thread (struct thread_info *tp);
1886 static step_over_what thread_still_needs_step_over (struct thread_info *tp);
1888 /* Are there any pending step-over requests? If so, run all we can
1889 now and return true. Otherwise, return false. */
1891 static bool
1892 start_step_over (void)
1894 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
1896 /* Don't start a new step-over if we already have an in-line
1897 step-over operation ongoing. */
1898 if (step_over_info_valid_p ())
1899 return false;
1901 /* Steal the global thread step over chain. As we try to initiate displaced
1902 steps, threads will be enqueued in the global chain if no buffers are
1903 available. If we iterated on the global chain directly, we might iterate
1904 indefinitely. */
1905 thread_step_over_list threads_to_step
1906 = std::move (global_thread_step_over_list);
1908 infrun_debug_printf ("stealing global queue of threads to step, length = %d",
1909 thread_step_over_chain_length (threads_to_step));
1911 bool started = false;
1913 /* On scope exit (whatever the reason, return or exception), if there are
1914 threads left in the THREADS_TO_STEP chain, put back these threads in the
1915 global list. */
1916 SCOPE_EXIT
1918 if (threads_to_step.empty ())
1919 infrun_debug_printf ("step-over queue now empty");
1920 else
1922 infrun_debug_printf ("putting back %d threads to step in global queue",
1923 thread_step_over_chain_length (threads_to_step));
1925 global_thread_step_over_chain_enqueue_chain
1926 (std::move (threads_to_step));
1930 thread_step_over_list_safe_range range
1931 = make_thread_step_over_list_safe_range (threads_to_step);
1933 for (thread_info *tp : range)
1935 step_over_what step_what;
1936 int must_be_in_line;
1938 gdb_assert (!tp->stop_requested);
1940 if (tp->inf->displaced_step_state.unavailable)
1942 /* The arch told us to not even try preparing another displaced step
1943 for this inferior. Just leave the thread in THREADS_TO_STEP, it
1944 will get moved to the global chain on scope exit. */
1945 continue;
1948 if (tp->inf->thread_waiting_for_vfork_done != nullptr)
1950 /* When we stop all threads, handling a vfork, any thread in the step
1951 over chain remains there. A user could also try to continue a
1952 thread stopped at a breakpoint while another thread is waiting for
1953 a vfork-done event. In any case, we don't want to start a step
1954 over right now. */
1955 continue;
1958 /* Remove thread from the THREADS_TO_STEP chain. If anything goes wrong
1959 while we try to prepare the displaced step, we don't add it back to
1960 the global step over chain. This is to avoid a thread staying in the
1961 step over chain indefinitely if something goes wrong when resuming it
1962 If the error is intermittent and it still needs a step over, it will
1963 get enqueued again when we try to resume it normally. */
1964 threads_to_step.erase (threads_to_step.iterator_to (*tp));
1966 step_what = thread_still_needs_step_over (tp);
1967 must_be_in_line = ((step_what & STEP_OVER_WATCHPOINT)
1968 || ((step_what & STEP_OVER_BREAKPOINT)
1969 && !use_displaced_stepping (tp)));
1971 /* We currently stop all threads of all processes to step-over
1972 in-line. If we need to start a new in-line step-over, let
1973 any pending displaced steps finish first. */
1974 if (must_be_in_line && displaced_step_in_progress_any_thread ())
1976 global_thread_step_over_chain_enqueue (tp);
1977 continue;
1980 if (tp->control.trap_expected
1981 || tp->resumed ()
1982 || tp->executing ())
1984 internal_error ("[%s] has inconsistent state: "
1985 "trap_expected=%d, resumed=%d, executing=%d\n",
1986 tp->ptid.to_string ().c_str (),
1987 tp->control.trap_expected,
1988 tp->resumed (),
1989 tp->executing ());
1992 infrun_debug_printf ("resuming [%s] for step-over",
1993 tp->ptid.to_string ().c_str ());
1995 /* keep_going_pass_signal skips the step-over if the breakpoint
1996 is no longer inserted. In all-stop, we want to keep looking
1997 for a thread that needs a step-over instead of resuming TP,
1998 because we wouldn't be able to resume anything else until the
1999 target stops again. In non-stop, the resume always resumes
2000 only TP, so it's OK to let the thread resume freely. */
2001 if (!target_is_non_stop_p () && !step_what)
2002 continue;
2004 switch_to_thread (tp);
2005 execution_control_state ecs (tp);
2006 keep_going_pass_signal (&ecs);
2008 if (!ecs.wait_some_more)
2009 error (_("Command aborted."));
2011 /* If the thread's step over could not be initiated because no buffers
2012 were available, it was re-added to the global step over chain. */
2013 if (tp->resumed ())
2015 infrun_debug_printf ("[%s] was resumed.",
2016 tp->ptid.to_string ().c_str ());
2017 gdb_assert (!thread_is_in_step_over_chain (tp));
2019 else
2021 infrun_debug_printf ("[%s] was NOT resumed.",
2022 tp->ptid.to_string ().c_str ());
2023 gdb_assert (thread_is_in_step_over_chain (tp));
2026 /* If we started a new in-line step-over, we're done. */
2027 if (step_over_info_valid_p ())
2029 gdb_assert (tp->control.trap_expected);
2030 started = true;
2031 break;
2034 if (!target_is_non_stop_p ())
2036 /* On all-stop, shouldn't have resumed unless we needed a
2037 step over. */
2038 gdb_assert (tp->control.trap_expected
2039 || tp->step_after_step_resume_breakpoint);
2041 /* With remote targets (at least), in all-stop, we can't
2042 issue any further remote commands until the program stops
2043 again. */
2044 started = true;
2045 break;
2048 /* Either the thread no longer needed a step-over, or a new
2049 displaced stepping sequence started. Even in the latter
2050 case, continue looking. Maybe we can also start another
2051 displaced step on a thread of other process. */
2054 return started;
2057 /* Update global variables holding ptids to hold NEW_PTID if they were
2058 holding OLD_PTID. */
2059 static void
2060 infrun_thread_ptid_changed (process_stratum_target *target,
2061 ptid_t old_ptid, ptid_t new_ptid)
2063 if (inferior_ptid == old_ptid
2064 && current_inferior ()->process_target () == target)
2065 inferior_ptid = new_ptid;
2070 static const char schedlock_off[] = "off";
2071 static const char schedlock_on[] = "on";
2072 static const char schedlock_step[] = "step";
2073 static const char schedlock_replay[] = "replay";
2074 static const char *const scheduler_enums[] = {
2075 schedlock_off,
2076 schedlock_on,
2077 schedlock_step,
2078 schedlock_replay,
2079 nullptr
2081 static const char *scheduler_mode = schedlock_replay;
2082 static void
2083 show_scheduler_mode (struct ui_file *file, int from_tty,
2084 struct cmd_list_element *c, const char *value)
2086 gdb_printf (file,
2087 _("Mode for locking scheduler "
2088 "during execution is \"%s\".\n"),
2089 value);
2092 static void
2093 set_schedlock_func (const char *args, int from_tty, struct cmd_list_element *c)
2095 if (!target_can_lock_scheduler ())
2097 scheduler_mode = schedlock_off;
2098 error (_("Target '%s' cannot support this command."),
2099 target_shortname ());
2103 /* True if execution commands resume all threads of all processes by
2104 default; otherwise, resume only threads of the current inferior
2105 process. */
2106 bool sched_multi = false;
2108 /* Try to setup for software single stepping. Return true if target_resume()
2109 should use hardware single step.
2111 GDBARCH the current gdbarch. */
2113 static bool
2114 maybe_software_singlestep (struct gdbarch *gdbarch)
2116 bool hw_step = true;
2118 if (execution_direction == EXEC_FORWARD
2119 && gdbarch_software_single_step_p (gdbarch))
2120 hw_step = !insert_single_step_breakpoints (gdbarch);
2122 return hw_step;
2125 /* See infrun.h. */
2127 ptid_t
2128 user_visible_resume_ptid (int step)
2130 ptid_t resume_ptid;
2132 if (non_stop)
2134 /* With non-stop mode on, threads are always handled
2135 individually. */
2136 resume_ptid = inferior_ptid;
2138 else if ((scheduler_mode == schedlock_on)
2139 || (scheduler_mode == schedlock_step && step))
2141 /* User-settable 'scheduler' mode requires solo thread
2142 resume. */
2143 resume_ptid = inferior_ptid;
2145 else if ((scheduler_mode == schedlock_replay)
2146 && target_record_will_replay (minus_one_ptid, execution_direction))
2148 /* User-settable 'scheduler' mode requires solo thread resume in replay
2149 mode. */
2150 resume_ptid = inferior_ptid;
2152 else if (!sched_multi && target_supports_multi_process ())
2154 /* Resume all threads of the current process (and none of other
2155 processes). */
2156 resume_ptid = ptid_t (inferior_ptid.pid ());
2158 else
2160 /* Resume all threads of all processes. */
2161 resume_ptid = RESUME_ALL;
2164 return resume_ptid;
2167 /* See infrun.h. */
2169 process_stratum_target *
2170 user_visible_resume_target (ptid_t resume_ptid)
2172 return (resume_ptid == minus_one_ptid && sched_multi
2173 ? nullptr
2174 : current_inferior ()->process_target ());
2177 /* Return a ptid representing the set of threads that we will resume,
2178 in the perspective of the target, assuming run control handling
2179 does not require leaving some threads stopped (e.g., stepping past
2180 breakpoint). USER_STEP indicates whether we're about to start the
2181 target for a stepping command. */
2183 static ptid_t
2184 internal_resume_ptid (int user_step)
2186 /* In non-stop, we always control threads individually. Note that
2187 the target may always work in non-stop mode even with "set
2188 non-stop off", in which case user_visible_resume_ptid could
2189 return a wildcard ptid. */
2190 if (target_is_non_stop_p ())
2191 return inferior_ptid;
2193 /* The rest of the function assumes non-stop==off and
2194 target-non-stop==off.
2196 If a thread is waiting for a vfork-done event, it means breakpoints are out
2197 for this inferior (well, program space in fact). We don't want to resume
2198 any thread other than the one waiting for vfork done, otherwise these other
2199 threads could miss breakpoints. So if a thread in the resumption set is
2200 waiting for a vfork-done event, resume only that thread.
2202 The resumption set width depends on whether schedule-multiple is on or off.
2204 Note that if the target_resume interface was more flexible, we could be
2205 smarter here when schedule-multiple is on. For example, imagine 3
2206 inferiors with 2 threads each (1.1, 1.2, 2.1, 2.2, 3.1 and 3.2). Threads
2207 2.1 and 3.2 are both waiting for a vfork-done event. Then we could ask the
2208 target(s) to resume:
2210 - All threads of inferior 1
2211 - Thread 2.1
2212 - Thread 3.2
2214 Since we don't have that flexibility (we can only pass one ptid), just
2215 resume the first thread waiting for a vfork-done event we find (e.g. thread
2216 2.1). */
2217 if (sched_multi)
2219 for (inferior *inf : all_non_exited_inferiors ())
2220 if (inf->thread_waiting_for_vfork_done != nullptr)
2221 return inf->thread_waiting_for_vfork_done->ptid;
2223 else if (current_inferior ()->thread_waiting_for_vfork_done != nullptr)
2224 return current_inferior ()->thread_waiting_for_vfork_done->ptid;
2226 return user_visible_resume_ptid (user_step);
2229 /* Wrapper for target_resume, that handles infrun-specific
2230 bookkeeping. */
2232 static void
2233 do_target_resume (ptid_t resume_ptid, bool step, enum gdb_signal sig)
2235 struct thread_info *tp = inferior_thread ();
2237 gdb_assert (!tp->stop_requested);
2239 /* Install inferior's terminal modes. */
2240 target_terminal::inferior ();
2242 /* Avoid confusing the next resume, if the next stop/resume
2243 happens to apply to another thread. */
2244 tp->set_stop_signal (GDB_SIGNAL_0);
2246 /* Advise target which signals may be handled silently.
2248 If we have removed breakpoints because we are stepping over one
2249 in-line (in any thread), we need to receive all signals to avoid
2250 accidentally skipping a breakpoint during execution of a signal
2251 handler.
2253 Likewise if we're displaced stepping, otherwise a trap for a
2254 breakpoint in a signal handler might be confused with the
2255 displaced step finishing. We don't make the displaced_step_finish
2256 step distinguish the cases instead, because:
2258 - a backtrace while stopped in the signal handler would show the
2259 scratch pad as frame older than the signal handler, instead of
2260 the real mainline code.
2262 - when the thread is later resumed, the signal handler would
2263 return to the scratch pad area, which would no longer be
2264 valid. */
2265 if (step_over_info_valid_p ()
2266 || displaced_step_in_progress (tp->inf))
2267 target_pass_signals ({});
2268 else
2269 target_pass_signals (signal_pass);
2271 infrun_debug_printf ("resume_ptid=%s, step=%d, sig=%s",
2272 resume_ptid.to_string ().c_str (),
2273 step, gdb_signal_to_symbol_string (sig));
2275 target_resume (resume_ptid, step, sig);
2278 /* Resume the inferior. SIG is the signal to give the inferior
2279 (GDB_SIGNAL_0 for none). Note: don't call this directly; instead
2280 call 'resume', which handles exceptions. */
2282 static void
2283 resume_1 (enum gdb_signal sig)
2285 struct regcache *regcache = get_current_regcache ();
2286 struct gdbarch *gdbarch = regcache->arch ();
2287 struct thread_info *tp = inferior_thread ();
2288 const address_space *aspace = regcache->aspace ();
2289 ptid_t resume_ptid;
2290 /* This represents the user's step vs continue request. When
2291 deciding whether "set scheduler-locking step" applies, it's the
2292 user's intention that counts. */
2293 const int user_step = tp->control.stepping_command;
2294 /* This represents what we'll actually request the target to do.
2295 This can decay from a step to a continue, if e.g., we need to
2296 implement single-stepping with breakpoints (software
2297 single-step). */
2298 bool step;
2300 gdb_assert (!tp->stop_requested);
2301 gdb_assert (!thread_is_in_step_over_chain (tp));
2303 if (tp->has_pending_waitstatus ())
2305 infrun_debug_printf
2306 ("thread %s has pending wait "
2307 "status %s (currently_stepping=%d).",
2308 tp->ptid.to_string ().c_str (),
2309 tp->pending_waitstatus ().to_string ().c_str (),
2310 currently_stepping (tp));
2312 tp->inf->process_target ()->threads_executing = true;
2313 tp->set_resumed (true);
2315 /* FIXME: What should we do if we are supposed to resume this
2316 thread with a signal? Maybe we should maintain a queue of
2317 pending signals to deliver. */
2318 if (sig != GDB_SIGNAL_0)
2320 warning (_("Couldn't deliver signal %s to %s."),
2321 gdb_signal_to_name (sig),
2322 tp->ptid.to_string ().c_str ());
2325 tp->set_stop_signal (GDB_SIGNAL_0);
2327 if (target_can_async_p ())
2329 target_async (true);
2330 /* Tell the event loop we have an event to process. */
2331 mark_async_event_handler (infrun_async_inferior_event_token);
2333 return;
2336 tp->stepped_breakpoint = 0;
2338 /* Depends on stepped_breakpoint. */
2339 step = currently_stepping (tp);
2341 if (current_inferior ()->thread_waiting_for_vfork_done != nullptr)
2343 /* Don't try to single-step a vfork parent that is waiting for
2344 the child to get out of the shared memory region (by exec'ing
2345 or exiting). This is particularly important on software
2346 single-step archs, as the child process would trip on the
2347 software single step breakpoint inserted for the parent
2348 process. Since the parent will not actually execute any
2349 instruction until the child is out of the shared region (such
2350 are vfork's semantics), it is safe to simply continue it.
2351 Eventually, we'll see a TARGET_WAITKIND_VFORK_DONE event for
2352 the parent, and tell it to `keep_going', which automatically
2353 re-sets it stepping. */
2354 infrun_debug_printf ("resume : clear step");
2355 step = false;
2358 CORE_ADDR pc = regcache_read_pc (regcache);
2360 infrun_debug_printf ("step=%d, signal=%s, trap_expected=%d, "
2361 "current thread [%s] at %s",
2362 step, gdb_signal_to_symbol_string (sig),
2363 tp->control.trap_expected,
2364 inferior_ptid.to_string ().c_str (),
2365 paddress (gdbarch, pc));
2367 /* Normally, by the time we reach `resume', the breakpoints are either
2368 removed or inserted, as appropriate. The exception is if we're sitting
2369 at a permanent breakpoint; we need to step over it, but permanent
2370 breakpoints can't be removed. So we have to test for it here. */
2371 if (breakpoint_here_p (aspace, pc) == permanent_breakpoint_here)
2373 if (sig != GDB_SIGNAL_0)
2375 /* We have a signal to pass to the inferior. The resume
2376 may, or may not take us to the signal handler. If this
2377 is a step, we'll need to stop in the signal handler, if
2378 there's one, (if the target supports stepping into
2379 handlers), or in the next mainline instruction, if
2380 there's no handler. If this is a continue, we need to be
2381 sure to run the handler with all breakpoints inserted.
2382 In all cases, set a breakpoint at the current address
2383 (where the handler returns to), and once that breakpoint
2384 is hit, resume skipping the permanent breakpoint. If
2385 that breakpoint isn't hit, then we've stepped into the
2386 signal handler (or hit some other event). We'll delete
2387 the step-resume breakpoint then. */
2389 infrun_debug_printf ("resume: skipping permanent breakpoint, "
2390 "deliver signal first");
2392 clear_step_over_info ();
2393 tp->control.trap_expected = 0;
2395 if (tp->control.step_resume_breakpoint == nullptr)
2397 /* Set a "high-priority" step-resume, as we don't want
2398 user breakpoints at PC to trigger (again) when this
2399 hits. */
2400 insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
2401 gdb_assert (tp->control.step_resume_breakpoint->loc->permanent);
2403 tp->step_after_step_resume_breakpoint = step;
2406 insert_breakpoints ();
2408 else
2410 /* There's no signal to pass, we can go ahead and skip the
2411 permanent breakpoint manually. */
2412 infrun_debug_printf ("skipping permanent breakpoint");
2413 gdbarch_skip_permanent_breakpoint (gdbarch, regcache);
2414 /* Update pc to reflect the new address from which we will
2415 execute instructions. */
2416 pc = regcache_read_pc (regcache);
2418 if (step)
2420 /* We've already advanced the PC, so the stepping part
2421 is done. Now we need to arrange for a trap to be
2422 reported to handle_inferior_event. Set a breakpoint
2423 at the current PC, and run to it. Don't update
2424 prev_pc, because if we end in
2425 switch_back_to_stepped_thread, we want the "expected
2426 thread advanced also" branch to be taken. IOW, we
2427 don't want this thread to step further from PC
2428 (overstep). */
2429 gdb_assert (!step_over_info_valid_p ());
2430 insert_single_step_breakpoint (gdbarch, aspace, pc);
2431 insert_breakpoints ();
2433 resume_ptid = internal_resume_ptid (user_step);
2434 do_target_resume (resume_ptid, false, GDB_SIGNAL_0);
2435 tp->set_resumed (true);
2436 return;
2441 /* If we have a breakpoint to step over, make sure to do a single
2442 step only. Same if we have software watchpoints. */
2443 if (tp->control.trap_expected || bpstat_should_step ())
2444 tp->control.may_range_step = 0;
2446 /* If displaced stepping is enabled, step over breakpoints by executing a
2447 copy of the instruction at a different address.
2449 We can't use displaced stepping when we have a signal to deliver;
2450 the comments for displaced_step_prepare explain why. The
2451 comments in the handle_inferior event for dealing with 'random
2452 signals' explain what we do instead.
2454 We can't use displaced stepping when we are waiting for vfork_done
2455 event, displaced stepping breaks the vfork child similarly as single
2456 step software breakpoint. */
2457 if (tp->control.trap_expected
2458 && use_displaced_stepping (tp)
2459 && !step_over_info_valid_p ()
2460 && sig == GDB_SIGNAL_0
2461 && current_inferior ()->thread_waiting_for_vfork_done == nullptr)
2463 displaced_step_prepare_status prepare_status
2464 = displaced_step_prepare (tp);
2466 if (prepare_status == DISPLACED_STEP_PREPARE_STATUS_UNAVAILABLE)
2468 infrun_debug_printf ("Got placed in step-over queue");
2470 tp->control.trap_expected = 0;
2471 return;
2473 else if (prepare_status == DISPLACED_STEP_PREPARE_STATUS_CANT)
2475 /* Fallback to stepping over the breakpoint in-line. */
2477 if (target_is_non_stop_p ())
2478 stop_all_threads ("displaced stepping falling back on inline stepping");
2480 set_step_over_info (regcache->aspace (),
2481 regcache_read_pc (regcache), 0, tp->global_num);
2483 step = maybe_software_singlestep (gdbarch);
2485 insert_breakpoints ();
2487 else if (prepare_status == DISPLACED_STEP_PREPARE_STATUS_OK)
2489 /* Update pc to reflect the new address from which we will
2490 execute instructions due to displaced stepping. */
2491 pc = regcache_read_pc (get_thread_regcache (tp));
2493 step = gdbarch_displaced_step_hw_singlestep (gdbarch);
2495 else
2496 gdb_assert_not_reached ("Invalid displaced_step_prepare_status "
2497 "value.");
2500 /* Do we need to do it the hard way, w/temp breakpoints? */
2501 else if (step)
2502 step = maybe_software_singlestep (gdbarch);
2504 /* Currently, our software single-step implementation leads to different
2505 results than hardware single-stepping in one situation: when stepping
2506 into delivering a signal which has an associated signal handler,
2507 hardware single-step will stop at the first instruction of the handler,
2508 while software single-step will simply skip execution of the handler.
2510 For now, this difference in behavior is accepted since there is no
2511 easy way to actually implement single-stepping into a signal handler
2512 without kernel support.
2514 However, there is one scenario where this difference leads to follow-on
2515 problems: if we're stepping off a breakpoint by removing all breakpoints
2516 and then single-stepping. In this case, the software single-step
2517 behavior means that even if there is a *breakpoint* in the signal
2518 handler, GDB still would not stop.
2520 Fortunately, we can at least fix this particular issue. We detect
2521 here the case where we are about to deliver a signal while software
2522 single-stepping with breakpoints removed. In this situation, we
2523 revert the decisions to remove all breakpoints and insert single-
2524 step breakpoints, and instead we install a step-resume breakpoint
2525 at the current address, deliver the signal without stepping, and
2526 once we arrive back at the step-resume breakpoint, actually step
2527 over the breakpoint we originally wanted to step over. */
2528 if (thread_has_single_step_breakpoints_set (tp)
2529 && sig != GDB_SIGNAL_0
2530 && step_over_info_valid_p ())
2532 /* If we have nested signals or a pending signal is delivered
2533 immediately after a handler returns, might already have
2534 a step-resume breakpoint set on the earlier handler. We cannot
2535 set another step-resume breakpoint; just continue on until the
2536 original breakpoint is hit. */
2537 if (tp->control.step_resume_breakpoint == nullptr)
2539 insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
2540 tp->step_after_step_resume_breakpoint = 1;
2543 delete_single_step_breakpoints (tp);
2545 clear_step_over_info ();
2546 tp->control.trap_expected = 0;
2548 insert_breakpoints ();
2551 /* If STEP is set, it's a request to use hardware stepping
2552 facilities. But in that case, we should never
2553 use singlestep breakpoint. */
2554 gdb_assert (!(thread_has_single_step_breakpoints_set (tp) && step));
2556 /* Decide the set of threads to ask the target to resume. */
2557 if (tp->control.trap_expected)
2559 /* We're allowing a thread to run past a breakpoint it has
2560 hit, either by single-stepping the thread with the breakpoint
2561 removed, or by displaced stepping, with the breakpoint inserted.
2562 In the former case, we need to single-step only this thread,
2563 and keep others stopped, as they can miss this breakpoint if
2564 allowed to run. That's not really a problem for displaced
2565 stepping, but, we still keep other threads stopped, in case
2566 another thread is also stopped for a breakpoint waiting for
2567 its turn in the displaced stepping queue. */
2568 resume_ptid = inferior_ptid;
2570 else
2571 resume_ptid = internal_resume_ptid (user_step);
2573 if (execution_direction != EXEC_REVERSE
2574 && step && breakpoint_inserted_here_p (aspace, pc))
2576 /* There are two cases where we currently need to step a
2577 breakpoint instruction when we have a signal to deliver:
2579 - See handle_signal_stop where we handle random signals that
2580 could take out us out of the stepping range. Normally, in
2581 that case we end up continuing (instead of stepping) over the
2582 signal handler with a breakpoint at PC, but there are cases
2583 where we should _always_ single-step, even if we have a
2584 step-resume breakpoint, like when a software watchpoint is
2585 set. Assuming single-stepping and delivering a signal at the
2586 same time would takes us to the signal handler, then we could
2587 have removed the breakpoint at PC to step over it. However,
2588 some hardware step targets (like e.g., Mac OS) can't step
2589 into signal handlers, and for those, we need to leave the
2590 breakpoint at PC inserted, as otherwise if the handler
2591 recurses and executes PC again, it'll miss the breakpoint.
2592 So we leave the breakpoint inserted anyway, but we need to
2593 record that we tried to step a breakpoint instruction, so
2594 that adjust_pc_after_break doesn't end up confused.
2596 - In non-stop if we insert a breakpoint (e.g., a step-resume)
2597 in one thread after another thread that was stepping had been
2598 momentarily paused for a step-over. When we re-resume the
2599 stepping thread, it may be resumed from that address with a
2600 breakpoint that hasn't trapped yet. Seen with
2601 gdb.threads/non-stop-fair-events.exp, on targets that don't
2602 do displaced stepping. */
2604 infrun_debug_printf ("resume: [%s] stepped breakpoint",
2605 tp->ptid.to_string ().c_str ());
2607 tp->stepped_breakpoint = 1;
2609 /* Most targets can step a breakpoint instruction, thus
2610 executing it normally. But if this one cannot, just
2611 continue and we will hit it anyway. */
2612 if (gdbarch_cannot_step_breakpoint (gdbarch))
2613 step = false;
2616 if (debug_displaced
2617 && tp->control.trap_expected
2618 && use_displaced_stepping (tp)
2619 && !step_over_info_valid_p ())
2621 struct regcache *resume_regcache = get_thread_regcache (tp);
2622 struct gdbarch *resume_gdbarch = resume_regcache->arch ();
2623 CORE_ADDR actual_pc = regcache_read_pc (resume_regcache);
2624 gdb_byte buf[4];
2626 read_memory (actual_pc, buf, sizeof (buf));
2627 displaced_debug_printf ("run %s: %s",
2628 paddress (resume_gdbarch, actual_pc),
2629 displaced_step_dump_bytes
2630 (buf, sizeof (buf)).c_str ());
2633 if (tp->control.may_range_step)
2635 /* If we're resuming a thread with the PC out of the step
2636 range, then we're doing some nested/finer run control
2637 operation, like stepping the thread out of the dynamic
2638 linker or the displaced stepping scratch pad. We
2639 shouldn't have allowed a range step then. */
2640 gdb_assert (pc_in_thread_step_range (pc, tp));
2643 do_target_resume (resume_ptid, step, sig);
2644 tp->set_resumed (true);
2647 /* Resume the inferior. SIG is the signal to give the inferior
2648 (GDB_SIGNAL_0 for none). This is a wrapper around 'resume_1' that
2649 rolls back state on error. */
2651 static void
2652 resume (gdb_signal sig)
2656 resume_1 (sig);
2658 catch (const gdb_exception &ex)
2660 /* If resuming is being aborted for any reason, delete any
2661 single-step breakpoint resume_1 may have created, to avoid
2662 confusing the following resumption, and to avoid leaving
2663 single-step breakpoints perturbing other threads, in case
2664 we're running in non-stop mode. */
2665 if (inferior_ptid != null_ptid)
2666 delete_single_step_breakpoints (inferior_thread ());
2667 throw;
2672 /* Proceeding. */
2674 /* See infrun.h. */
2676 /* Counter that tracks number of user visible stops. This can be used
2677 to tell whether a command has proceeded the inferior past the
2678 current location. This allows e.g., inferior function calls in
2679 breakpoint commands to not interrupt the command list. When the
2680 call finishes successfully, the inferior is standing at the same
2681 breakpoint as if nothing happened (and so we don't call
2682 normal_stop). */
2683 static ULONGEST current_stop_id;
2685 /* See infrun.h. */
2687 ULONGEST
2688 get_stop_id (void)
2690 return current_stop_id;
2693 /* Called when we report a user visible stop. */
2695 static void
2696 new_stop_id (void)
2698 current_stop_id++;
2701 /* Clear out all variables saying what to do when inferior is continued.
2702 First do this, then set the ones you want, then call `proceed'. */
2704 static void
2705 clear_proceed_status_thread (struct thread_info *tp)
2707 infrun_debug_printf ("%s", tp->ptid.to_string ().c_str ());
2709 /* If we're starting a new sequence, then the previous finished
2710 single-step is no longer relevant. */
2711 if (tp->has_pending_waitstatus ())
2713 if (tp->stop_reason () == TARGET_STOPPED_BY_SINGLE_STEP)
2715 infrun_debug_printf ("pending event of %s was a finished step. "
2716 "Discarding.",
2717 tp->ptid.to_string ().c_str ());
2719 tp->clear_pending_waitstatus ();
2720 tp->set_stop_reason (TARGET_STOPPED_BY_NO_REASON);
2722 else
2724 infrun_debug_printf
2725 ("thread %s has pending wait status %s (currently_stepping=%d).",
2726 tp->ptid.to_string ().c_str (),
2727 tp->pending_waitstatus ().to_string ().c_str (),
2728 currently_stepping (tp));
2732 /* If this signal should not be seen by program, give it zero.
2733 Used for debugging signals. */
2734 if (!signal_pass_state (tp->stop_signal ()))
2735 tp->set_stop_signal (GDB_SIGNAL_0);
2737 tp->release_thread_fsm ();
2739 tp->control.trap_expected = 0;
2740 tp->control.step_range_start = 0;
2741 tp->control.step_range_end = 0;
2742 tp->control.may_range_step = 0;
2743 tp->control.step_frame_id = null_frame_id;
2744 tp->control.step_stack_frame_id = null_frame_id;
2745 tp->control.step_over_calls = STEP_OVER_UNDEBUGGABLE;
2746 tp->control.step_start_function = nullptr;
2747 tp->stop_requested = 0;
2749 tp->control.stop_step = 0;
2751 tp->control.proceed_to_finish = 0;
2753 tp->control.stepping_command = 0;
2755 /* Discard any remaining commands or status from previous stop. */
2756 bpstat_clear (&tp->control.stop_bpstat);
2759 void
2760 clear_proceed_status (int step)
2762 /* With scheduler-locking replay, stop replaying other threads if we're
2763 not replaying the user-visible resume ptid.
2765 This is a convenience feature to not require the user to explicitly
2766 stop replaying the other threads. We're assuming that the user's
2767 intent is to resume tracing the recorded process. */
2768 if (!non_stop && scheduler_mode == schedlock_replay
2769 && target_record_is_replaying (minus_one_ptid)
2770 && !target_record_will_replay (user_visible_resume_ptid (step),
2771 execution_direction))
2772 target_record_stop_replaying ();
2774 if (!non_stop && inferior_ptid != null_ptid)
2776 ptid_t resume_ptid = user_visible_resume_ptid (step);
2777 process_stratum_target *resume_target
2778 = user_visible_resume_target (resume_ptid);
2780 /* In all-stop mode, delete the per-thread status of all threads
2781 we're about to resume, implicitly and explicitly. */
2782 for (thread_info *tp : all_non_exited_threads (resume_target, resume_ptid))
2783 clear_proceed_status_thread (tp);
2786 if (inferior_ptid != null_ptid)
2788 struct inferior *inferior;
2790 if (non_stop)
2792 /* If in non-stop mode, only delete the per-thread status of
2793 the current thread. */
2794 clear_proceed_status_thread (inferior_thread ());
2797 inferior = current_inferior ();
2798 inferior->control.stop_soon = NO_STOP_QUIETLY;
2801 gdb::observers::about_to_proceed.notify ();
2804 /* Returns true if TP is still stopped at a breakpoint that needs
2805 stepping-over in order to make progress. If the breakpoint is gone
2806 meanwhile, we can skip the whole step-over dance. */
2808 static bool
2809 thread_still_needs_step_over_bp (struct thread_info *tp)
2811 if (tp->stepping_over_breakpoint)
2813 struct regcache *regcache = get_thread_regcache (tp);
2815 if (breakpoint_here_p (regcache->aspace (),
2816 regcache_read_pc (regcache))
2817 == ordinary_breakpoint_here)
2818 return true;
2820 tp->stepping_over_breakpoint = 0;
2823 return false;
2826 /* Check whether thread TP still needs to start a step-over in order
2827 to make progress when resumed. Returns an bitwise or of enum
2828 step_over_what bits, indicating what needs to be stepped over. */
2830 static step_over_what
2831 thread_still_needs_step_over (struct thread_info *tp)
2833 step_over_what what = 0;
2835 if (thread_still_needs_step_over_bp (tp))
2836 what |= STEP_OVER_BREAKPOINT;
2838 if (tp->stepping_over_watchpoint
2839 && !target_have_steppable_watchpoint ())
2840 what |= STEP_OVER_WATCHPOINT;
2842 return what;
2845 /* Returns true if scheduler locking applies. STEP indicates whether
2846 we're about to do a step/next-like command to a thread. */
2848 static bool
2849 schedlock_applies (struct thread_info *tp)
2851 return (scheduler_mode == schedlock_on
2852 || (scheduler_mode == schedlock_step
2853 && tp->control.stepping_command)
2854 || (scheduler_mode == schedlock_replay
2855 && target_record_will_replay (minus_one_ptid,
2856 execution_direction)));
2859 /* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
2860 stacks that have threads executing and don't have threads with
2861 pending events. */
2863 static void
2864 maybe_set_commit_resumed_all_targets ()
2866 scoped_restore_current_thread restore_thread;
2868 for (inferior *inf : all_non_exited_inferiors ())
2870 process_stratum_target *proc_target = inf->process_target ();
2872 if (proc_target->commit_resumed_state)
2874 /* We already set this in a previous iteration, via another
2875 inferior sharing the process_stratum target. */
2876 continue;
2879 /* If the target has no resumed threads, it would be useless to
2880 ask it to commit the resumed threads. */
2881 if (!proc_target->threads_executing)
2883 infrun_debug_printf ("not requesting commit-resumed for target "
2884 "%s, no resumed threads",
2885 proc_target->shortname ());
2886 continue;
2889 /* As an optimization, if a thread from this target has some
2890 status to report, handle it before requiring the target to
2891 commit its resumed threads: handling the status might lead to
2892 resuming more threads. */
2893 if (proc_target->has_resumed_with_pending_wait_status ())
2895 infrun_debug_printf ("not requesting commit-resumed for target %s, a"
2896 " thread has a pending waitstatus",
2897 proc_target->shortname ());
2898 continue;
2901 switch_to_inferior_no_thread (inf);
2903 if (target_has_pending_events ())
2905 infrun_debug_printf ("not requesting commit-resumed for target %s, "
2906 "target has pending events",
2907 proc_target->shortname ());
2908 continue;
2911 infrun_debug_printf ("enabling commit-resumed for target %s",
2912 proc_target->shortname ());
2914 proc_target->commit_resumed_state = true;
2918 /* See infrun.h. */
2920 void
2921 maybe_call_commit_resumed_all_targets ()
2923 scoped_restore_current_thread restore_thread;
2925 for (inferior *inf : all_non_exited_inferiors ())
2927 process_stratum_target *proc_target = inf->process_target ();
2929 if (!proc_target->commit_resumed_state)
2930 continue;
2932 switch_to_inferior_no_thread (inf);
2934 infrun_debug_printf ("calling commit_resumed for target %s",
2935 proc_target->shortname());
2937 target_commit_resumed ();
2941 /* To track nesting of scoped_disable_commit_resumed objects, ensuring
2942 that only the outermost one attempts to re-enable
2943 commit-resumed. */
2944 static bool enable_commit_resumed = true;
2946 /* See infrun.h. */
2948 scoped_disable_commit_resumed::scoped_disable_commit_resumed
2949 (const char *reason)
2950 : m_reason (reason),
2951 m_prev_enable_commit_resumed (enable_commit_resumed)
2953 infrun_debug_printf ("reason=%s", m_reason);
2955 enable_commit_resumed = false;
2957 for (inferior *inf : all_non_exited_inferiors ())
2959 process_stratum_target *proc_target = inf->process_target ();
2961 if (m_prev_enable_commit_resumed)
2963 /* This is the outermost instance: force all
2964 COMMIT_RESUMED_STATE to false. */
2965 proc_target->commit_resumed_state = false;
2967 else
2969 /* This is not the outermost instance, we expect
2970 COMMIT_RESUMED_STATE to have been cleared by the
2971 outermost instance. */
2972 gdb_assert (!proc_target->commit_resumed_state);
2977 /* See infrun.h. */
2979 void
2980 scoped_disable_commit_resumed::reset ()
2982 if (m_reset)
2983 return;
2984 m_reset = true;
2986 infrun_debug_printf ("reason=%s", m_reason);
2988 gdb_assert (!enable_commit_resumed);
2990 enable_commit_resumed = m_prev_enable_commit_resumed;
2992 if (m_prev_enable_commit_resumed)
2994 /* This is the outermost instance, re-enable
2995 COMMIT_RESUMED_STATE on the targets where it's possible. */
2996 maybe_set_commit_resumed_all_targets ();
2998 else
3000 /* This is not the outermost instance, we expect
3001 COMMIT_RESUMED_STATE to still be false. */
3002 for (inferior *inf : all_non_exited_inferiors ())
3004 process_stratum_target *proc_target = inf->process_target ();
3005 gdb_assert (!proc_target->commit_resumed_state);
3010 /* See infrun.h. */
3012 scoped_disable_commit_resumed::~scoped_disable_commit_resumed ()
3014 reset ();
3017 /* See infrun.h. */
3019 void
3020 scoped_disable_commit_resumed::reset_and_commit ()
3022 reset ();
3023 maybe_call_commit_resumed_all_targets ();
3026 /* See infrun.h. */
3028 scoped_enable_commit_resumed::scoped_enable_commit_resumed
3029 (const char *reason)
3030 : m_reason (reason),
3031 m_prev_enable_commit_resumed (enable_commit_resumed)
3033 infrun_debug_printf ("reason=%s", m_reason);
3035 if (!enable_commit_resumed)
3037 enable_commit_resumed = true;
3039 /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
3040 possible. */
3041 maybe_set_commit_resumed_all_targets ();
3043 maybe_call_commit_resumed_all_targets ();
3047 /* See infrun.h. */
3049 scoped_enable_commit_resumed::~scoped_enable_commit_resumed ()
3051 infrun_debug_printf ("reason=%s", m_reason);
3053 gdb_assert (enable_commit_resumed);
3055 enable_commit_resumed = m_prev_enable_commit_resumed;
3057 if (!enable_commit_resumed)
3059 /* Force all COMMIT_RESUMED_STATE back to false. */
3060 for (inferior *inf : all_non_exited_inferiors ())
3062 process_stratum_target *proc_target = inf->process_target ();
3063 proc_target->commit_resumed_state = false;
3068 /* Check that all the targets we're about to resume are in non-stop
3069 mode. Ideally, we'd only care whether all targets support
3070 target-async, but we're not there yet. E.g., stop_all_threads
3071 doesn't know how to handle all-stop targets. Also, the remote
3072 protocol in all-stop mode is synchronous, irrespective of
3073 target-async, which means that things like a breakpoint re-set
3074 triggered by one target would try to read memory from all targets
3075 and fail. */
3077 static void
3078 check_multi_target_resumption (process_stratum_target *resume_target)
3080 if (!non_stop && resume_target == nullptr)
3082 scoped_restore_current_thread restore_thread;
3084 /* This is used to track whether we're resuming more than one
3085 target. */
3086 process_stratum_target *first_connection = nullptr;
3088 /* The first inferior we see with a target that does not work in
3089 always-non-stop mode. */
3090 inferior *first_not_non_stop = nullptr;
3092 for (inferior *inf : all_non_exited_inferiors ())
3094 switch_to_inferior_no_thread (inf);
3096 if (!target_has_execution ())
3097 continue;
3099 process_stratum_target *proc_target
3100 = current_inferior ()->process_target();
3102 if (!target_is_non_stop_p ())
3103 first_not_non_stop = inf;
3105 if (first_connection == nullptr)
3106 first_connection = proc_target;
3107 else if (first_connection != proc_target
3108 && first_not_non_stop != nullptr)
3110 switch_to_inferior_no_thread (first_not_non_stop);
3112 proc_target = current_inferior ()->process_target();
3114 error (_("Connection %d (%s) does not support "
3115 "multi-target resumption."),
3116 proc_target->connection_number,
3117 make_target_connection_string (proc_target).c_str ());
3123 /* Basic routine for continuing the program in various fashions.
3125 ADDR is the address to resume at, or -1 for resume where stopped.
3126 SIGGNAL is the signal to give it, or GDB_SIGNAL_0 for none,
3127 or GDB_SIGNAL_DEFAULT for act according to how it stopped.
3129 You should call clear_proceed_status before calling proceed. */
3131 void
3132 proceed (CORE_ADDR addr, enum gdb_signal siggnal)
3134 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
3136 struct regcache *regcache;
3137 struct gdbarch *gdbarch;
3138 CORE_ADDR pc;
3140 /* If we're stopped at a fork/vfork, follow the branch set by the
3141 "set follow-fork-mode" command; otherwise, we'll just proceed
3142 resuming the current thread. */
3143 if (!follow_fork ())
3145 /* The target for some reason decided not to resume. */
3146 normal_stop ();
3147 if (target_can_async_p ())
3148 inferior_event_handler (INF_EXEC_COMPLETE);
3149 return;
3152 /* We'll update this if & when we switch to a new thread. */
3153 previous_inferior_ptid = inferior_ptid;
3155 regcache = get_current_regcache ();
3156 gdbarch = regcache->arch ();
3157 const address_space *aspace = regcache->aspace ();
3159 pc = regcache_read_pc_protected (regcache);
3161 thread_info *cur_thr = inferior_thread ();
3163 /* Fill in with reasonable starting values. */
3164 init_thread_stepping_state (cur_thr);
3166 gdb_assert (!thread_is_in_step_over_chain (cur_thr));
3168 ptid_t resume_ptid
3169 = user_visible_resume_ptid (cur_thr->control.stepping_command);
3170 process_stratum_target *resume_target
3171 = user_visible_resume_target (resume_ptid);
3173 check_multi_target_resumption (resume_target);
3175 if (addr == (CORE_ADDR) -1)
3177 if (cur_thr->stop_pc_p ()
3178 && pc == cur_thr->stop_pc ()
3179 && breakpoint_here_p (aspace, pc) == ordinary_breakpoint_here
3180 && execution_direction != EXEC_REVERSE)
3181 /* There is a breakpoint at the address we will resume at,
3182 step one instruction before inserting breakpoints so that
3183 we do not stop right away (and report a second hit at this
3184 breakpoint).
3186 Note, we don't do this in reverse, because we won't
3187 actually be executing the breakpoint insn anyway.
3188 We'll be (un-)executing the previous instruction. */
3189 cur_thr->stepping_over_breakpoint = 1;
3190 else if (gdbarch_single_step_through_delay_p (gdbarch)
3191 && gdbarch_single_step_through_delay (gdbarch,
3192 get_current_frame ()))
3193 /* We stepped onto an instruction that needs to be stepped
3194 again before re-inserting the breakpoint, do so. */
3195 cur_thr->stepping_over_breakpoint = 1;
3197 else
3199 regcache_write_pc (regcache, addr);
3202 if (siggnal != GDB_SIGNAL_DEFAULT)
3203 cur_thr->set_stop_signal (siggnal);
3205 /* If an exception is thrown from this point on, make sure to
3206 propagate GDB's knowledge of the executing state to the
3207 frontend/user running state. */
3208 scoped_finish_thread_state finish_state (resume_target, resume_ptid);
3210 /* Even if RESUME_PTID is a wildcard, and we end up resuming fewer
3211 threads (e.g., we might need to set threads stepping over
3212 breakpoints first), from the user/frontend's point of view, all
3213 threads in RESUME_PTID are now running. Unless we're calling an
3214 inferior function, as in that case we pretend the inferior
3215 doesn't run at all. */
3216 if (!cur_thr->control.in_infcall)
3217 set_running (resume_target, resume_ptid, true);
3219 infrun_debug_printf ("addr=%s, signal=%s", paddress (gdbarch, addr),
3220 gdb_signal_to_symbol_string (siggnal));
3222 annotate_starting ();
3224 /* Make sure that output from GDB appears before output from the
3225 inferior. */
3226 gdb_flush (gdb_stdout);
3228 /* Since we've marked the inferior running, give it the terminal. A
3229 QUIT/Ctrl-C from here on is forwarded to the target (which can
3230 still detect attempts to unblock a stuck connection with repeated
3231 Ctrl-C from within target_pass_ctrlc). */
3232 target_terminal::inferior ();
3234 /* In a multi-threaded task we may select another thread and
3235 then continue or step.
3237 But if a thread that we're resuming had stopped at a breakpoint,
3238 it will immediately cause another breakpoint stop without any
3239 execution (i.e. it will report a breakpoint hit incorrectly). So
3240 we must step over it first.
3242 Look for threads other than the current (TP) that reported a
3243 breakpoint hit and haven't been resumed yet since. */
3245 /* If scheduler locking applies, we can avoid iterating over all
3246 threads. */
3247 if (!non_stop && !schedlock_applies (cur_thr))
3249 for (thread_info *tp : all_non_exited_threads (resume_target,
3250 resume_ptid))
3252 switch_to_thread_no_regs (tp);
3254 /* Ignore the current thread here. It's handled
3255 afterwards. */
3256 if (tp == cur_thr)
3257 continue;
3259 if (!thread_still_needs_step_over (tp))
3260 continue;
3262 gdb_assert (!thread_is_in_step_over_chain (tp));
3264 infrun_debug_printf ("need to step-over [%s] first",
3265 tp->ptid.to_string ().c_str ());
3267 global_thread_step_over_chain_enqueue (tp);
3270 switch_to_thread (cur_thr);
3273 /* Enqueue the current thread last, so that we move all other
3274 threads over their breakpoints first. */
3275 if (cur_thr->stepping_over_breakpoint)
3276 global_thread_step_over_chain_enqueue (cur_thr);
3278 /* If the thread isn't started, we'll still need to set its prev_pc,
3279 so that switch_back_to_stepped_thread knows the thread hasn't
3280 advanced. Must do this before resuming any thread, as in
3281 all-stop/remote, once we resume we can't send any other packet
3282 until the target stops again. */
3283 cur_thr->prev_pc = regcache_read_pc_protected (regcache);
3286 scoped_disable_commit_resumed disable_commit_resumed ("proceeding");
3287 bool step_over_started = start_step_over ();
3289 if (step_over_info_valid_p ())
3291 /* Either this thread started a new in-line step over, or some
3292 other thread was already doing one. In either case, don't
3293 resume anything else until the step-over is finished. */
3295 else if (step_over_started && !target_is_non_stop_p ())
3297 /* A new displaced stepping sequence was started. In all-stop,
3298 we can't talk to the target anymore until it next stops. */
3300 else if (!non_stop && target_is_non_stop_p ())
3302 INFRUN_SCOPED_DEBUG_START_END
3303 ("resuming threads, all-stop-on-top-of-non-stop");
3305 /* In all-stop, but the target is always in non-stop mode.
3306 Start all other threads that are implicitly resumed too. */
3307 for (thread_info *tp : all_non_exited_threads (resume_target,
3308 resume_ptid))
3310 switch_to_thread_no_regs (tp);
3312 if (!tp->inf->has_execution ())
3314 infrun_debug_printf ("[%s] target has no execution",
3315 tp->ptid.to_string ().c_str ());
3316 continue;
3319 if (tp->resumed ())
3321 infrun_debug_printf ("[%s] resumed",
3322 tp->ptid.to_string ().c_str ());
3323 gdb_assert (tp->executing () || tp->has_pending_waitstatus ());
3324 continue;
3327 if (thread_is_in_step_over_chain (tp))
3329 infrun_debug_printf ("[%s] needs step-over",
3330 tp->ptid.to_string ().c_str ());
3331 continue;
3334 /* If a thread of that inferior is waiting for a vfork-done
3335 (for a detached vfork child to exec or exit), breakpoints are
3336 removed. We must not resume any thread of that inferior, other
3337 than the one waiting for the vfork-done. */
3338 if (tp->inf->thread_waiting_for_vfork_done != nullptr
3339 && tp != tp->inf->thread_waiting_for_vfork_done)
3341 infrun_debug_printf ("[%s] another thread of this inferior is "
3342 "waiting for vfork-done",
3343 tp->ptid.to_string ().c_str ());
3344 continue;
3347 infrun_debug_printf ("resuming %s",
3348 tp->ptid.to_string ().c_str ());
3350 execution_control_state ecs (tp);
3351 switch_to_thread (tp);
3352 keep_going_pass_signal (&ecs);
3353 if (!ecs.wait_some_more)
3354 error (_("Command aborted."));
3357 else if (!cur_thr->resumed ()
3358 && !thread_is_in_step_over_chain (cur_thr)
3359 /* In non-stop, forbid resuming a thread if some other thread of
3360 that inferior is waiting for a vfork-done event (this means
3361 breakpoints are out for this inferior). */
3362 && !(non_stop
3363 && cur_thr->inf->thread_waiting_for_vfork_done != nullptr))
3365 /* The thread wasn't started, and isn't queued, run it now. */
3366 execution_control_state ecs (cur_thr);
3367 switch_to_thread (cur_thr);
3368 keep_going_pass_signal (&ecs);
3369 if (!ecs.wait_some_more)
3370 error (_("Command aborted."));
3373 disable_commit_resumed.reset_and_commit ();
3376 finish_state.release ();
3378 /* If we've switched threads above, switch back to the previously
3379 current thread. We don't want the user to see a different
3380 selected thread. */
3381 switch_to_thread (cur_thr);
3383 /* Tell the event loop to wait for it to stop. If the target
3384 supports asynchronous execution, it'll do this from within
3385 target_resume. */
3386 if (!target_can_async_p ())
3387 mark_async_event_handler (infrun_async_inferior_event_token);
3391 /* Start remote-debugging of a machine over a serial link. */
3393 void
3394 start_remote (int from_tty)
3396 inferior *inf = current_inferior ();
3397 inf->control.stop_soon = STOP_QUIETLY_REMOTE;
3399 /* Always go on waiting for the target, regardless of the mode. */
3400 /* FIXME: cagney/1999-09-23: At present it isn't possible to
3401 indicate to wait_for_inferior that a target should timeout if
3402 nothing is returned (instead of just blocking). Because of this,
3403 targets expecting an immediate response need to, internally, set
3404 things up so that the target_wait() is forced to eventually
3405 timeout. */
3406 /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
3407 differentiate to its caller what the state of the target is after
3408 the initial open has been performed. Here we're assuming that
3409 the target has stopped. It should be possible to eventually have
3410 target_open() return to the caller an indication that the target
3411 is currently running and GDB state should be set to the same as
3412 for an async run. */
3413 wait_for_inferior (inf);
3415 /* Now that the inferior has stopped, do any bookkeeping like
3416 loading shared libraries. We want to do this before normal_stop,
3417 so that the displayed frame is up to date. */
3418 post_create_inferior (from_tty);
3420 normal_stop ();
3423 /* Initialize static vars when a new inferior begins. */
3425 void
3426 init_wait_for_inferior (void)
3428 /* These are meaningless until the first time through wait_for_inferior. */
3430 breakpoint_init_inferior (inf_starting);
3432 clear_proceed_status (0);
3434 nullify_last_target_wait_ptid ();
3436 previous_inferior_ptid = inferior_ptid;
3441 static void handle_inferior_event (struct execution_control_state *ecs);
3443 static void handle_step_into_function (struct gdbarch *gdbarch,
3444 struct execution_control_state *ecs);
3445 static void handle_step_into_function_backward (struct gdbarch *gdbarch,
3446 struct execution_control_state *ecs);
3447 static void handle_signal_stop (struct execution_control_state *ecs);
3448 static void check_exception_resume (struct execution_control_state *,
3449 frame_info_ptr);
3451 static void end_stepping_range (struct execution_control_state *ecs);
3452 static void stop_waiting (struct execution_control_state *ecs);
3453 static void keep_going (struct execution_control_state *ecs);
3454 static void process_event_stop_test (struct execution_control_state *ecs);
3455 static bool switch_back_to_stepped_thread (struct execution_control_state *ecs);
3457 /* This function is attached as a "thread_stop_requested" observer.
3458 Cleanup local state that assumed the PTID was to be resumed, and
3459 report the stop to the frontend. */
3461 static void
3462 infrun_thread_stop_requested (ptid_t ptid)
3464 process_stratum_target *curr_target = current_inferior ()->process_target ();
3466 /* PTID was requested to stop. If the thread was already stopped,
3467 but the user/frontend doesn't know about that yet (e.g., the
3468 thread had been temporarily paused for some step-over), set up
3469 for reporting the stop now. */
3470 for (thread_info *tp : all_threads (curr_target, ptid))
3472 if (tp->state != THREAD_RUNNING)
3473 continue;
3474 if (tp->executing ())
3475 continue;
3477 /* Remove matching threads from the step-over queue, so
3478 start_step_over doesn't try to resume them
3479 automatically. */
3480 if (thread_is_in_step_over_chain (tp))
3481 global_thread_step_over_chain_remove (tp);
3483 /* If the thread is stopped, but the user/frontend doesn't
3484 know about that yet, queue a pending event, as if the
3485 thread had just stopped now. Unless the thread already had
3486 a pending event. */
3487 if (!tp->has_pending_waitstatus ())
3489 target_waitstatus ws;
3490 ws.set_stopped (GDB_SIGNAL_0);
3491 tp->set_pending_waitstatus (ws);
3494 /* Clear the inline-frame state, since we're re-processing the
3495 stop. */
3496 clear_inline_frame_state (tp);
3498 /* If this thread was paused because some other thread was
3499 doing an inline-step over, let that finish first. Once
3500 that happens, we'll restart all threads and consume pending
3501 stop events then. */
3502 if (step_over_info_valid_p ())
3503 continue;
3505 /* Otherwise we can process the (new) pending event now. Set
3506 it so this pending event is considered by
3507 do_target_wait. */
3508 tp->set_resumed (true);
3512 static void
3513 infrun_thread_thread_exit (struct thread_info *tp, int silent)
3515 if (target_last_proc_target == tp->inf->process_target ()
3516 && target_last_wait_ptid == tp->ptid)
3517 nullify_last_target_wait_ptid ();
3520 /* Delete the step resume, single-step and longjmp/exception resume
3521 breakpoints of TP. */
3523 static void
3524 delete_thread_infrun_breakpoints (struct thread_info *tp)
3526 delete_step_resume_breakpoint (tp);
3527 delete_exception_resume_breakpoint (tp);
3528 delete_single_step_breakpoints (tp);
3531 /* If the target still has execution, call FUNC for each thread that
3532 just stopped. In all-stop, that's all the non-exited threads; in
3533 non-stop, that's the current thread, only. */
3535 typedef void (*for_each_just_stopped_thread_callback_func)
3536 (struct thread_info *tp);
3538 static void
3539 for_each_just_stopped_thread (for_each_just_stopped_thread_callback_func func)
3541 if (!target_has_execution () || inferior_ptid == null_ptid)
3542 return;
3544 if (target_is_non_stop_p ())
3546 /* If in non-stop mode, only the current thread stopped. */
3547 func (inferior_thread ());
3549 else
3551 /* In all-stop mode, all threads have stopped. */
3552 for (thread_info *tp : all_non_exited_threads ())
3553 func (tp);
3557 /* Delete the step resume and longjmp/exception resume breakpoints of
3558 the threads that just stopped. */
3560 static void
3561 delete_just_stopped_threads_infrun_breakpoints (void)
3563 for_each_just_stopped_thread (delete_thread_infrun_breakpoints);
3566 /* Delete the single-step breakpoints of the threads that just
3567 stopped. */
3569 static void
3570 delete_just_stopped_threads_single_step_breakpoints (void)
3572 for_each_just_stopped_thread (delete_single_step_breakpoints);
3575 /* See infrun.h. */
3577 void
3578 print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid,
3579 const struct target_waitstatus &ws)
3581 infrun_debug_printf ("target_wait (%s [%s], status) =",
3582 waiton_ptid.to_string ().c_str (),
3583 target_pid_to_str (waiton_ptid).c_str ());
3584 infrun_debug_printf (" %s [%s],",
3585 result_ptid.to_string ().c_str (),
3586 target_pid_to_str (result_ptid).c_str ());
3587 infrun_debug_printf (" %s", ws.to_string ().c_str ());
3590 /* Select a thread at random, out of those which are resumed and have
3591 had events. */
3593 static struct thread_info *
3594 random_pending_event_thread (inferior *inf, ptid_t waiton_ptid)
3596 process_stratum_target *proc_target = inf->process_target ();
3597 thread_info *thread
3598 = proc_target->random_resumed_with_pending_wait_status (inf, waiton_ptid);
3600 if (thread == nullptr)
3602 infrun_debug_printf ("None found.");
3603 return nullptr;
3606 infrun_debug_printf ("Found %s.", thread->ptid.to_string ().c_str ());
3607 gdb_assert (thread->resumed ());
3608 gdb_assert (thread->has_pending_waitstatus ());
3610 return thread;
3613 /* Wrapper for target_wait that first checks whether threads have
3614 pending statuses to report before actually asking the target for
3615 more events. INF is the inferior we're using to call target_wait
3616 on. */
3618 static ptid_t
3619 do_target_wait_1 (inferior *inf, ptid_t ptid,
3620 target_waitstatus *status, target_wait_flags options)
3622 struct thread_info *tp;
3624 /* We know that we are looking for an event in the target of inferior
3625 INF, but we don't know which thread the event might come from. As
3626 such we want to make sure that INFERIOR_PTID is reset so that none of
3627 the wait code relies on it - doing so is always a mistake. */
3628 switch_to_inferior_no_thread (inf);
3630 /* First check if there is a resumed thread with a wait status
3631 pending. */
3632 if (ptid == minus_one_ptid || ptid.is_pid ())
3634 tp = random_pending_event_thread (inf, ptid);
3636 else
3638 infrun_debug_printf ("Waiting for specific thread %s.",
3639 ptid.to_string ().c_str ());
3641 /* We have a specific thread to check. */
3642 tp = find_thread_ptid (inf, ptid);
3643 gdb_assert (tp != nullptr);
3644 if (!tp->has_pending_waitstatus ())
3645 tp = nullptr;
3648 if (tp != nullptr
3649 && (tp->stop_reason () == TARGET_STOPPED_BY_SW_BREAKPOINT
3650 || tp->stop_reason () == TARGET_STOPPED_BY_HW_BREAKPOINT))
3652 struct regcache *regcache = get_thread_regcache (tp);
3653 struct gdbarch *gdbarch = regcache->arch ();
3654 CORE_ADDR pc;
3655 int discard = 0;
3657 pc = regcache_read_pc (regcache);
3659 if (pc != tp->stop_pc ())
3661 infrun_debug_printf ("PC of %s changed. was=%s, now=%s",
3662 tp->ptid.to_string ().c_str (),
3663 paddress (gdbarch, tp->stop_pc ()),
3664 paddress (gdbarch, pc));
3665 discard = 1;
3667 else if (!breakpoint_inserted_here_p (regcache->aspace (), pc))
3669 infrun_debug_printf ("previous breakpoint of %s, at %s gone",
3670 tp->ptid.to_string ().c_str (),
3671 paddress (gdbarch, pc));
3673 discard = 1;
3676 if (discard)
3678 infrun_debug_printf ("pending event of %s cancelled.",
3679 tp->ptid.to_string ().c_str ());
3681 tp->clear_pending_waitstatus ();
3682 target_waitstatus ws;
3683 ws.set_spurious ();
3684 tp->set_pending_waitstatus (ws);
3685 tp->set_stop_reason (TARGET_STOPPED_BY_NO_REASON);
3689 if (tp != nullptr)
3691 infrun_debug_printf ("Using pending wait status %s for %s.",
3692 tp->pending_waitstatus ().to_string ().c_str (),
3693 tp->ptid.to_string ().c_str ());
3695 /* Now that we've selected our final event LWP, un-adjust its PC
3696 if it was a software breakpoint (and the target doesn't
3697 always adjust the PC itself). */
3698 if (tp->stop_reason () == TARGET_STOPPED_BY_SW_BREAKPOINT
3699 && !target_supports_stopped_by_sw_breakpoint ())
3701 struct regcache *regcache;
3702 struct gdbarch *gdbarch;
3703 int decr_pc;
3705 regcache = get_thread_regcache (tp);
3706 gdbarch = regcache->arch ();
3708 decr_pc = gdbarch_decr_pc_after_break (gdbarch);
3709 if (decr_pc != 0)
3711 CORE_ADDR pc;
3713 pc = regcache_read_pc (regcache);
3714 regcache_write_pc (regcache, pc + decr_pc);
3718 tp->set_stop_reason (TARGET_STOPPED_BY_NO_REASON);
3719 *status = tp->pending_waitstatus ();
3720 tp->clear_pending_waitstatus ();
3722 /* Wake up the event loop again, until all pending events are
3723 processed. */
3724 if (target_is_async_p ())
3725 mark_async_event_handler (infrun_async_inferior_event_token);
3726 return tp->ptid;
3729 /* But if we don't find one, we'll have to wait. */
3731 /* We can't ask a non-async target to do a non-blocking wait, so this will be
3732 a blocking wait. */
3733 if (!target_can_async_p ())
3734 options &= ~TARGET_WNOHANG;
3736 return target_wait (ptid, status, options);
3739 /* Wrapper for target_wait that first checks whether threads have
3740 pending statuses to report before actually asking the target for
3741 more events. Polls for events from all inferiors/targets. */
3743 static bool
3744 do_target_wait (execution_control_state *ecs, target_wait_flags options)
3746 int num_inferiors = 0;
3747 int random_selector;
3749 /* For fairness, we pick the first inferior/target to poll at random
3750 out of all inferiors that may report events, and then continue
3751 polling the rest of the inferior list starting from that one in a
3752 circular fashion until the whole list is polled once. */
3754 auto inferior_matches = [] (inferior *inf)
3756 return inf->process_target () != nullptr;
3759 /* First see how many matching inferiors we have. */
3760 for (inferior *inf : all_inferiors ())
3761 if (inferior_matches (inf))
3762 num_inferiors++;
3764 if (num_inferiors == 0)
3766 ecs->ws.set_ignore ();
3767 return false;
3770 /* Now randomly pick an inferior out of those that matched. */
3771 random_selector = (int)
3772 ((num_inferiors * (double) rand ()) / (RAND_MAX + 1.0));
3774 if (num_inferiors > 1)
3775 infrun_debug_printf ("Found %d inferiors, starting at #%d",
3776 num_inferiors, random_selector);
3778 /* Select the Nth inferior that matched. */
3780 inferior *selected = nullptr;
3782 for (inferior *inf : all_inferiors ())
3783 if (inferior_matches (inf))
3784 if (random_selector-- == 0)
3786 selected = inf;
3787 break;
3790 /* Now poll for events out of each of the matching inferior's
3791 targets, starting from the selected one. */
3793 auto do_wait = [&] (inferior *inf)
3795 ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
3796 ecs->target = inf->process_target ();
3797 return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
3800 /* Needed in 'all-stop + target-non-stop' mode, because we end up
3801 here spuriously after the target is all stopped and we've already
3802 reported the stop to the user, polling for events. */
3803 scoped_restore_current_thread restore_thread;
3805 intrusive_list_iterator<inferior> start
3806 = inferior_list.iterator_to (*selected);
3808 for (intrusive_list_iterator<inferior> it = start;
3809 it != inferior_list.end ();
3810 ++it)
3812 inferior *inf = &*it;
3814 if (inferior_matches (inf) && do_wait (inf))
3815 return true;
3818 for (intrusive_list_iterator<inferior> it = inferior_list.begin ();
3819 it != start;
3820 ++it)
3822 inferior *inf = &*it;
3824 if (inferior_matches (inf) && do_wait (inf))
3825 return true;
3828 ecs->ws.set_ignore ();
3829 return false;
3832 /* An event reported by wait_one. */
3834 struct wait_one_event
3836 /* The target the event came out of. */
3837 process_stratum_target *target;
3839 /* The PTID the event was for. */
3840 ptid_t ptid;
3842 /* The waitstatus. */
3843 target_waitstatus ws;
3846 static bool handle_one (const wait_one_event &event);
3848 /* Prepare and stabilize the inferior for detaching it. E.g.,
3849 detaching while a thread is displaced stepping is a recipe for
3850 crashing it, as nothing would readjust the PC out of the scratch
3851 pad. */
3853 void
3854 prepare_for_detach (void)
3856 struct inferior *inf = current_inferior ();
3857 ptid_t pid_ptid = ptid_t (inf->pid);
3858 scoped_restore_current_thread restore_thread;
3860 scoped_restore restore_detaching = make_scoped_restore (&inf->detaching, true);
3862 /* Remove all threads of INF from the global step-over chain. We
3863 want to stop any ongoing step-over, not start any new one. */
3864 thread_step_over_list_safe_range range
3865 = make_thread_step_over_list_safe_range (global_thread_step_over_list);
3867 for (thread_info *tp : range)
3868 if (tp->inf == inf)
3870 infrun_debug_printf ("removing thread %s from global step over chain",
3871 tp->ptid.to_string ().c_str ());
3872 global_thread_step_over_chain_remove (tp);
3875 /* If we were already in the middle of an inline step-over, and the
3876 thread stepping belongs to the inferior we're detaching, we need
3877 to restart the threads of other inferiors. */
3878 if (step_over_info.thread != -1)
3880 infrun_debug_printf ("inline step-over in-process while detaching");
3882 thread_info *thr = find_thread_global_id (step_over_info.thread);
3883 if (thr->inf == inf)
3885 /* Since we removed threads of INF from the step-over chain,
3886 we know this won't start a step-over for INF. */
3887 clear_step_over_info ();
3889 if (target_is_non_stop_p ())
3891 /* Start a new step-over in another thread if there's
3892 one that needs it. */
3893 start_step_over ();
3895 /* Restart all other threads (except the
3896 previously-stepping thread, since that one is still
3897 running). */
3898 if (!step_over_info_valid_p ())
3899 restart_threads (thr);
3904 if (displaced_step_in_progress (inf))
3906 infrun_debug_printf ("displaced-stepping in-process while detaching");
3908 /* Stop threads currently displaced stepping, aborting it. */
3910 for (thread_info *thr : inf->non_exited_threads ())
3912 if (thr->displaced_step_state.in_progress ())
3914 if (thr->executing ())
3916 if (!thr->stop_requested)
3918 target_stop (thr->ptid);
3919 thr->stop_requested = true;
3922 else
3923 thr->set_resumed (false);
3927 while (displaced_step_in_progress (inf))
3929 wait_one_event event;
3931 event.target = inf->process_target ();
3932 event.ptid = do_target_wait_1 (inf, pid_ptid, &event.ws, 0);
3934 if (debug_infrun)
3935 print_target_wait_results (pid_ptid, event.ptid, event.ws);
3937 handle_one (event);
3940 /* It's OK to leave some of the threads of INF stopped, since
3941 they'll be detached shortly. */
3945 /* If all-stop, but there exists a non-stop target, stop all threads
3946 now that we're presenting the stop to the user. */
3948 static void
3949 stop_all_threads_if_all_stop_mode ()
3951 if (!non_stop && exists_non_stop_target ())
3952 stop_all_threads ("presenting stop to user in all-stop");
3955 /* Wait for control to return from inferior to debugger.
3957 If inferior gets a signal, we may decide to start it up again
3958 instead of returning. That is why there is a loop in this function.
3959 When this function actually returns it means the inferior
3960 should be left stopped and GDB should read more commands. */
3962 static void
3963 wait_for_inferior (inferior *inf)
3965 infrun_debug_printf ("wait_for_inferior ()");
3967 SCOPE_EXIT { delete_just_stopped_threads_infrun_breakpoints (); };
3969 /* If an error happens while handling the event, propagate GDB's
3970 knowledge of the executing state to the frontend/user running
3971 state. */
3972 scoped_finish_thread_state finish_state
3973 (inf->process_target (), minus_one_ptid);
3975 while (1)
3977 execution_control_state ecs;
3979 overlay_cache_invalid = 1;
3981 /* Flush target cache before starting to handle each event.
3982 Target was running and cache could be stale. This is just a
3983 heuristic. Running threads may modify target memory, but we
3984 don't get any event. */
3985 target_dcache_invalidate ();
3987 ecs.ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs.ws, 0);
3988 ecs.target = inf->process_target ();
3990 if (debug_infrun)
3991 print_target_wait_results (minus_one_ptid, ecs.ptid, ecs.ws);
3993 /* Now figure out what to do with the result of the result. */
3994 handle_inferior_event (&ecs);
3996 if (!ecs.wait_some_more)
3997 break;
4000 stop_all_threads_if_all_stop_mode ();
4002 /* No error, don't finish the state yet. */
4003 finish_state.release ();
4006 /* Cleanup that reinstalls the readline callback handler, if the
4007 target is running in the background. If while handling the target
4008 event something triggered a secondary prompt, like e.g., a
4009 pagination prompt, we'll have removed the callback handler (see
4010 gdb_readline_wrapper_line). Need to do this as we go back to the
4011 event loop, ready to process further input. Note this has no
4012 effect if the handler hasn't actually been removed, because calling
4013 rl_callback_handler_install resets the line buffer, thus losing
4014 input. */
4016 static void
4017 reinstall_readline_callback_handler_cleanup ()
4019 struct ui *ui = current_ui;
4021 if (!ui->async)
4023 /* We're not going back to the top level event loop yet. Don't
4024 install the readline callback, as it'd prep the terminal,
4025 readline-style (raw, noecho) (e.g., --batch). We'll install
4026 it the next time the prompt is displayed, when we're ready
4027 for input. */
4028 return;
4031 if (ui->command_editing && ui->prompt_state != PROMPT_BLOCKED)
4032 gdb_rl_callback_handler_reinstall ();
4035 /* Clean up the FSMs of threads that are now stopped. In non-stop,
4036 that's just the event thread. In all-stop, that's all threads. */
4038 static void
4039 clean_up_just_stopped_threads_fsms (struct execution_control_state *ecs)
4041 /* The first clean_up call below assumes the event thread is the current
4042 one. */
4043 if (ecs->event_thread != nullptr)
4044 gdb_assert (ecs->event_thread == inferior_thread ());
4046 if (ecs->event_thread != nullptr
4047 && ecs->event_thread->thread_fsm () != nullptr)
4048 ecs->event_thread->thread_fsm ()->clean_up (ecs->event_thread);
4050 if (!non_stop)
4052 scoped_restore_current_thread restore_thread;
4054 for (thread_info *thr : all_non_exited_threads ())
4056 if (thr->thread_fsm () == nullptr)
4057 continue;
4058 if (thr == ecs->event_thread)
4059 continue;
4061 switch_to_thread (thr);
4062 thr->thread_fsm ()->clean_up (thr);
4067 /* Helper for all_uis_check_sync_execution_done that works on the
4068 current UI. */
4070 static void
4071 check_curr_ui_sync_execution_done (void)
4073 struct ui *ui = current_ui;
4075 if (ui->prompt_state == PROMPT_NEEDED
4076 && ui->async
4077 && !gdb_in_secondary_prompt_p (ui))
4079 target_terminal::ours ();
4080 gdb::observers::sync_execution_done.notify ();
4081 ui->register_file_handler ();
4085 /* See infrun.h. */
4087 void
4088 all_uis_check_sync_execution_done (void)
4090 SWITCH_THRU_ALL_UIS ()
4092 check_curr_ui_sync_execution_done ();
4096 /* See infrun.h. */
4098 void
4099 all_uis_on_sync_execution_starting (void)
4101 SWITCH_THRU_ALL_UIS ()
4103 if (current_ui->prompt_state == PROMPT_NEEDED)
4104 async_disable_stdin ();
4108 /* Asynchronous version of wait_for_inferior. It is called by the
4109 event loop whenever a change of state is detected on the file
4110 descriptor corresponding to the target. It can be called more than
4111 once to complete a single execution command. In such cases we need
4112 to keep the state in a global variable ECSS. If it is the last time
4113 that this function is called for a single execution command, then
4114 report to the user that the inferior has stopped, and do the
4115 necessary cleanups. */
4117 void
4118 fetch_inferior_event ()
4120 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
4122 execution_control_state ecs;
4123 int cmd_done = 0;
4125 /* Events are always processed with the main UI as current UI. This
4126 way, warnings, debug output, etc. are always consistently sent to
4127 the main console. */
4128 scoped_restore save_ui = make_scoped_restore (&current_ui, main_ui);
4130 /* Temporarily disable pagination. Otherwise, the user would be
4131 given an option to press 'q' to quit, which would cause an early
4132 exit and could leave GDB in a half-baked state. */
4133 scoped_restore save_pagination
4134 = make_scoped_restore (&pagination_enabled, false);
4136 /* End up with readline processing input, if necessary. */
4138 SCOPE_EXIT { reinstall_readline_callback_handler_cleanup (); };
4140 /* We're handling a live event, so make sure we're doing live
4141 debugging. If we're looking at traceframes while the target is
4142 running, we're going to need to get back to that mode after
4143 handling the event. */
4144 gdb::optional<scoped_restore_current_traceframe> maybe_restore_traceframe;
4145 if (non_stop)
4147 maybe_restore_traceframe.emplace ();
4148 set_current_traceframe (-1);
4151 /* The user/frontend should not notice a thread switch due to
4152 internal events. Make sure we revert to the user selected
4153 thread and frame after handling the event and running any
4154 breakpoint commands. */
4155 scoped_restore_current_thread restore_thread;
4157 overlay_cache_invalid = 1;
4158 /* Flush target cache before starting to handle each event. Target
4159 was running and cache could be stale. This is just a heuristic.
4160 Running threads may modify target memory, but we don't get any
4161 event. */
4162 target_dcache_invalidate ();
4164 scoped_restore save_exec_dir
4165 = make_scoped_restore (&execution_direction,
4166 target_execution_direction ());
4168 /* Allow targets to pause their resumed threads while we handle
4169 the event. */
4170 scoped_disable_commit_resumed disable_commit_resumed ("handling event");
4172 if (!do_target_wait (&ecs, TARGET_WNOHANG))
4174 infrun_debug_printf ("do_target_wait returned no event");
4175 disable_commit_resumed.reset_and_commit ();
4176 return;
4179 gdb_assert (ecs.ws.kind () != TARGET_WAITKIND_IGNORE);
4181 /* Switch to the target that generated the event, so we can do
4182 target calls. */
4183 switch_to_target_no_thread (ecs.target);
4185 if (debug_infrun)
4186 print_target_wait_results (minus_one_ptid, ecs.ptid, ecs.ws);
4188 /* If an error happens while handling the event, propagate GDB's
4189 knowledge of the executing state to the frontend/user running
4190 state. */
4191 ptid_t finish_ptid = !target_is_non_stop_p () ? minus_one_ptid : ecs.ptid;
4192 scoped_finish_thread_state finish_state (ecs.target, finish_ptid);
4194 /* Get executed before scoped_restore_current_thread above to apply
4195 still for the thread which has thrown the exception. */
4196 auto defer_bpstat_clear
4197 = make_scope_exit (bpstat_clear_actions);
4198 auto defer_delete_threads
4199 = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
4201 /* Now figure out what to do with the result of the result. */
4202 handle_inferior_event (&ecs);
4204 if (!ecs.wait_some_more)
4206 struct inferior *inf = find_inferior_ptid (ecs.target, ecs.ptid);
4207 bool should_stop = true;
4208 struct thread_info *thr = ecs.event_thread;
4210 delete_just_stopped_threads_infrun_breakpoints ();
4212 if (thr != nullptr && thr->thread_fsm () != nullptr)
4213 should_stop = thr->thread_fsm ()->should_stop (thr);
4215 if (!should_stop)
4217 keep_going (&ecs);
4219 else
4221 bool should_notify_stop = true;
4222 int proceeded = 0;
4224 stop_all_threads_if_all_stop_mode ();
4226 clean_up_just_stopped_threads_fsms (&ecs);
4228 if (thr != nullptr && thr->thread_fsm () != nullptr)
4229 should_notify_stop
4230 = thr->thread_fsm ()->should_notify_stop ();
4232 if (should_notify_stop)
4234 /* We may not find an inferior if this was a process exit. */
4235 if (inf == nullptr || inf->control.stop_soon == NO_STOP_QUIETLY)
4236 proceeded = normal_stop ();
4239 if (!proceeded)
4241 inferior_event_handler (INF_EXEC_COMPLETE);
4242 cmd_done = 1;
4245 /* If we got a TARGET_WAITKIND_NO_RESUMED event, then the
4246 previously selected thread is gone. We have two
4247 choices - switch to no thread selected, or restore the
4248 previously selected thread (now exited). We chose the
4249 later, just because that's what GDB used to do. After
4250 this, "info threads" says "The current thread <Thread
4251 ID 2> has terminated." instead of "No thread
4252 selected.". */
4253 if (!non_stop
4254 && cmd_done
4255 && ecs.ws.kind () != TARGET_WAITKIND_NO_RESUMED)
4256 restore_thread.dont_restore ();
4260 defer_delete_threads.release ();
4261 defer_bpstat_clear.release ();
4263 /* No error, don't finish the thread states yet. */
4264 finish_state.release ();
4266 disable_commit_resumed.reset_and_commit ();
4268 /* This scope is used to ensure that readline callbacks are
4269 reinstalled here. */
4272 /* Handling this event might have caused some inferiors to become prunable.
4273 For example, the exit of an inferior that was automatically added. Try
4274 to get rid of them. Keeping those around slows down things linearly.
4276 Note that this never removes the current inferior. Therefore, call this
4277 after RESTORE_THREAD went out of scope, in case the event inferior (which was
4278 temporarily made the current inferior) is meant to be deleted.
4280 Call this before all_uis_check_sync_execution_done, so that notifications about
4281 removed inferiors appear before the prompt. */
4282 prune_inferiors ();
4284 /* If a UI was in sync execution mode, and now isn't, restore its
4285 prompt (a synchronous execution command has finished, and we're
4286 ready for input). */
4287 all_uis_check_sync_execution_done ();
4289 if (cmd_done
4290 && exec_done_display_p
4291 && (inferior_ptid == null_ptid
4292 || inferior_thread ()->state != THREAD_RUNNING))
4293 gdb_printf (_("completed.\n"));
4296 /* See infrun.h. */
4298 void
4299 set_step_info (thread_info *tp, frame_info_ptr frame,
4300 struct symtab_and_line sal)
4302 /* This can be removed once this function no longer implicitly relies on the
4303 inferior_ptid value. */
4304 gdb_assert (inferior_ptid == tp->ptid);
4306 tp->control.step_frame_id = get_frame_id (frame);
4307 tp->control.step_stack_frame_id = get_stack_frame_id (frame);
4309 tp->current_symtab = sal.symtab;
4310 tp->current_line = sal.line;
4312 infrun_debug_printf
4313 ("symtab = %s, line = %d, step_frame_id = %s, step_stack_frame_id = %s",
4314 tp->current_symtab != nullptr ? tp->current_symtab->filename : "<null>",
4315 tp->current_line,
4316 tp->control.step_frame_id.to_string ().c_str (),
4317 tp->control.step_stack_frame_id.to_string ().c_str ());
4320 /* Clear context switchable stepping state. */
4322 void
4323 init_thread_stepping_state (struct thread_info *tss)
4325 tss->stepped_breakpoint = 0;
4326 tss->stepping_over_breakpoint = 0;
4327 tss->stepping_over_watchpoint = 0;
4328 tss->step_after_step_resume_breakpoint = 0;
4331 /* See infrun.h. */
4333 void
4334 set_last_target_status (process_stratum_target *target, ptid_t ptid,
4335 const target_waitstatus &status)
4337 target_last_proc_target = target;
4338 target_last_wait_ptid = ptid;
4339 target_last_waitstatus = status;
4342 /* See infrun.h. */
4344 void
4345 get_last_target_status (process_stratum_target **target, ptid_t *ptid,
4346 target_waitstatus *status)
4348 if (target != nullptr)
4349 *target = target_last_proc_target;
4350 if (ptid != nullptr)
4351 *ptid = target_last_wait_ptid;
4352 if (status != nullptr)
4353 *status = target_last_waitstatus;
4356 /* See infrun.h. */
4358 void
4359 nullify_last_target_wait_ptid (void)
4361 target_last_proc_target = nullptr;
4362 target_last_wait_ptid = minus_one_ptid;
4363 target_last_waitstatus = {};
4366 /* Switch thread contexts. */
4368 static void
4369 context_switch (execution_control_state *ecs)
4371 if (ecs->ptid != inferior_ptid
4372 && (inferior_ptid == null_ptid
4373 || ecs->event_thread != inferior_thread ()))
4375 infrun_debug_printf ("Switching context from %s to %s",
4376 inferior_ptid.to_string ().c_str (),
4377 ecs->ptid.to_string ().c_str ());
4380 switch_to_thread (ecs->event_thread);
4383 /* If the target can't tell whether we've hit breakpoints
4384 (target_supports_stopped_by_sw_breakpoint), and we got a SIGTRAP,
4385 check whether that could have been caused by a breakpoint. If so,
4386 adjust the PC, per gdbarch_decr_pc_after_break. */
4388 static void
4389 adjust_pc_after_break (struct thread_info *thread,
4390 const target_waitstatus &ws)
4392 struct regcache *regcache;
4393 struct gdbarch *gdbarch;
4394 CORE_ADDR breakpoint_pc, decr_pc;
4396 /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP. If
4397 we aren't, just return.
4399 We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
4400 affected by gdbarch_decr_pc_after_break. Other waitkinds which are
4401 implemented by software breakpoints should be handled through the normal
4402 breakpoint layer.
4404 NOTE drow/2004-01-31: On some targets, breakpoints may generate
4405 different signals (SIGILL or SIGEMT for instance), but it is less
4406 clear where the PC is pointing afterwards. It may not match
4407 gdbarch_decr_pc_after_break. I don't know any specific target that
4408 generates these signals at breakpoints (the code has been in GDB since at
4409 least 1992) so I can not guess how to handle them here.
4411 In earlier versions of GDB, a target with
4412 gdbarch_have_nonsteppable_watchpoint would have the PC after hitting a
4413 watchpoint affected by gdbarch_decr_pc_after_break. I haven't found any
4414 target with both of these set in GDB history, and it seems unlikely to be
4415 correct, so gdbarch_have_nonsteppable_watchpoint is not checked here. */
4417 if (ws.kind () != TARGET_WAITKIND_STOPPED)
4418 return;
4420 if (ws.sig () != GDB_SIGNAL_TRAP)
4421 return;
4423 /* In reverse execution, when a breakpoint is hit, the instruction
4424 under it has already been de-executed. The reported PC always
4425 points at the breakpoint address, so adjusting it further would
4426 be wrong. E.g., consider this case on a decr_pc_after_break == 1
4427 architecture:
4429 B1 0x08000000 : INSN1
4430 B2 0x08000001 : INSN2
4431 0x08000002 : INSN3
4432 PC -> 0x08000003 : INSN4
4434 Say you're stopped at 0x08000003 as above. Reverse continuing
4435 from that point should hit B2 as below. Reading the PC when the
4436 SIGTRAP is reported should read 0x08000001 and INSN2 should have
4437 been de-executed already.
4439 B1 0x08000000 : INSN1
4440 B2 PC -> 0x08000001 : INSN2
4441 0x08000002 : INSN3
4442 0x08000003 : INSN4
4444 We can't apply the same logic as for forward execution, because
4445 we would wrongly adjust the PC to 0x08000000, since there's a
4446 breakpoint at PC - 1. We'd then report a hit on B1, although
4447 INSN1 hadn't been de-executed yet. Doing nothing is the correct
4448 behaviour. */
4449 if (execution_direction == EXEC_REVERSE)
4450 return;
4452 /* If the target can tell whether the thread hit a SW breakpoint,
4453 trust it. Targets that can tell also adjust the PC
4454 themselves. */
4455 if (target_supports_stopped_by_sw_breakpoint ())
4456 return;
4458 /* Note that relying on whether a breakpoint is planted in memory to
4459 determine this can fail. E.g,. the breakpoint could have been
4460 removed since. Or the thread could have been told to step an
4461 instruction the size of a breakpoint instruction, and only
4462 _after_ was a breakpoint inserted at its address. */
4464 /* If this target does not decrement the PC after breakpoints, then
4465 we have nothing to do. */
4466 regcache = get_thread_regcache (thread);
4467 gdbarch = regcache->arch ();
4469 decr_pc = gdbarch_decr_pc_after_break (gdbarch);
4470 if (decr_pc == 0)
4471 return;
4473 const address_space *aspace = regcache->aspace ();
4475 /* Find the location where (if we've hit a breakpoint) the
4476 breakpoint would be. */
4477 breakpoint_pc = regcache_read_pc (regcache) - decr_pc;
4479 /* If the target can't tell whether a software breakpoint triggered,
4480 fallback to figuring it out based on breakpoints we think were
4481 inserted in the target, and on whether the thread was stepped or
4482 continued. */
4484 /* Check whether there actually is a software breakpoint inserted at
4485 that location.
4487 If in non-stop mode, a race condition is possible where we've
4488 removed a breakpoint, but stop events for that breakpoint were
4489 already queued and arrive later. To suppress those spurious
4490 SIGTRAPs, we keep a list of such breakpoint locations for a bit,
4491 and retire them after a number of stop events are reported. Note
4492 this is an heuristic and can thus get confused. The real fix is
4493 to get the "stopped by SW BP and needs adjustment" info out of
4494 the target/kernel (and thus never reach here; see above). */
4495 if (software_breakpoint_inserted_here_p (aspace, breakpoint_pc)
4496 || (target_is_non_stop_p ()
4497 && moribund_breakpoint_here_p (aspace, breakpoint_pc)))
4499 gdb::optional<scoped_restore_tmpl<int>> restore_operation_disable;
4501 if (record_full_is_used ())
4502 restore_operation_disable.emplace
4503 (record_full_gdb_operation_disable_set ());
4505 /* When using hardware single-step, a SIGTRAP is reported for both
4506 a completed single-step and a software breakpoint. Need to
4507 differentiate between the two, as the latter needs adjusting
4508 but the former does not.
4510 The SIGTRAP can be due to a completed hardware single-step only if
4511 - we didn't insert software single-step breakpoints
4512 - this thread is currently being stepped
4514 If any of these events did not occur, we must have stopped due
4515 to hitting a software breakpoint, and have to back up to the
4516 breakpoint address.
4518 As a special case, we could have hardware single-stepped a
4519 software breakpoint. In this case (prev_pc == breakpoint_pc),
4520 we also need to back up to the breakpoint address. */
4522 if (thread_has_single_step_breakpoints_set (thread)
4523 || !currently_stepping (thread)
4524 || (thread->stepped_breakpoint
4525 && thread->prev_pc == breakpoint_pc))
4526 regcache_write_pc (regcache, breakpoint_pc);
4530 static bool
4531 stepped_in_from (frame_info_ptr frame, struct frame_id step_frame_id)
4533 for (frame = get_prev_frame (frame);
4534 frame != nullptr;
4535 frame = get_prev_frame (frame))
4537 if (get_frame_id (frame) == step_frame_id)
4538 return true;
4540 if (get_frame_type (frame) != INLINE_FRAME)
4541 break;
4544 return false;
4547 /* Look for an inline frame that is marked for skip.
4548 If PREV_FRAME is TRUE start at the previous frame,
4549 otherwise start at the current frame. Stop at the
4550 first non-inline frame, or at the frame where the
4551 step started. */
4553 static bool
4554 inline_frame_is_marked_for_skip (bool prev_frame, struct thread_info *tp)
4556 frame_info_ptr frame = get_current_frame ();
4558 if (prev_frame)
4559 frame = get_prev_frame (frame);
4561 for (; frame != nullptr; frame = get_prev_frame (frame))
4563 const char *fn = nullptr;
4564 symtab_and_line sal;
4565 struct symbol *sym;
4567 if (get_frame_id (frame) == tp->control.step_frame_id)
4568 break;
4569 if (get_frame_type (frame) != INLINE_FRAME)
4570 break;
4572 sal = find_frame_sal (frame);
4573 sym = get_frame_function (frame);
4575 if (sym != nullptr)
4576 fn = sym->print_name ();
4578 if (sal.line != 0
4579 && function_name_is_marked_for_skip (fn, sal))
4580 return true;
4583 return false;
4586 /* If the event thread has the stop requested flag set, pretend it
4587 stopped for a GDB_SIGNAL_0 (i.e., as if it stopped due to
4588 target_stop). */
4590 static bool
4591 handle_stop_requested (struct execution_control_state *ecs)
4593 if (ecs->event_thread->stop_requested)
4595 ecs->ws.set_stopped (GDB_SIGNAL_0);
4596 handle_signal_stop (ecs);
4597 return true;
4599 return false;
4602 /* Auxiliary function that handles syscall entry/return events.
4603 It returns true if the inferior should keep going (and GDB
4604 should ignore the event), or false if the event deserves to be
4605 processed. */
4607 static bool
4608 handle_syscall_event (struct execution_control_state *ecs)
4610 struct regcache *regcache;
4611 int syscall_number;
4613 context_switch (ecs);
4615 regcache = get_thread_regcache (ecs->event_thread);
4616 syscall_number = ecs->ws.syscall_number ();
4617 ecs->event_thread->set_stop_pc (regcache_read_pc (regcache));
4619 if (catch_syscall_enabled () > 0
4620 && catching_syscall_number (syscall_number))
4622 infrun_debug_printf ("syscall number=%d", syscall_number);
4624 ecs->event_thread->control.stop_bpstat
4625 = bpstat_stop_status_nowatch (regcache->aspace (),
4626 ecs->event_thread->stop_pc (),
4627 ecs->event_thread, ecs->ws);
4629 if (handle_stop_requested (ecs))
4630 return false;
4632 if (bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
4634 /* Catchpoint hit. */
4635 return false;
4639 if (handle_stop_requested (ecs))
4640 return false;
4642 /* If no catchpoint triggered for this, then keep going. */
4643 keep_going (ecs);
4645 return true;
4648 /* Lazily fill in the execution_control_state's stop_func_* fields. */
4650 static void
4651 fill_in_stop_func (struct gdbarch *gdbarch,
4652 struct execution_control_state *ecs)
4654 if (!ecs->stop_func_filled_in)
4656 const block *block;
4657 const general_symbol_info *gsi;
4659 /* Don't care about return value; stop_func_start and stop_func_name
4660 will both be 0 if it doesn't work. */
4661 find_pc_partial_function_sym (ecs->event_thread->stop_pc (),
4662 &gsi,
4663 &ecs->stop_func_start,
4664 &ecs->stop_func_end,
4665 &block);
4666 ecs->stop_func_name = gsi == nullptr ? nullptr : gsi->print_name ();
4668 /* The call to find_pc_partial_function, above, will set
4669 stop_func_start and stop_func_end to the start and end
4670 of the range containing the stop pc. If this range
4671 contains the entry pc for the block (which is always the
4672 case for contiguous blocks), advance stop_func_start past
4673 the function's start offset and entrypoint. Note that
4674 stop_func_start is NOT advanced when in a range of a
4675 non-contiguous block that does not contain the entry pc. */
4676 if (block != nullptr
4677 && ecs->stop_func_start <= block->entry_pc ()
4678 && block->entry_pc () < ecs->stop_func_end)
4680 ecs->stop_func_start
4681 += gdbarch_deprecated_function_start_offset (gdbarch);
4683 if (gdbarch_skip_entrypoint_p (gdbarch))
4684 ecs->stop_func_start
4685 = gdbarch_skip_entrypoint (gdbarch, ecs->stop_func_start);
4688 ecs->stop_func_filled_in = 1;
4693 /* Return the STOP_SOON field of the inferior pointed at by ECS. */
4695 static enum stop_kind
4696 get_inferior_stop_soon (execution_control_state *ecs)
4698 struct inferior *inf = find_inferior_ptid (ecs->target, ecs->ptid);
4700 gdb_assert (inf != nullptr);
4701 return inf->control.stop_soon;
4704 /* Poll for one event out of the current target. Store the resulting
4705 waitstatus in WS, and return the event ptid. Does not block. */
4707 static ptid_t
4708 poll_one_curr_target (struct target_waitstatus *ws)
4710 ptid_t event_ptid;
4712 overlay_cache_invalid = 1;
4714 /* Flush target cache before starting to handle each event.
4715 Target was running and cache could be stale. This is just a
4716 heuristic. Running threads may modify target memory, but we
4717 don't get any event. */
4718 target_dcache_invalidate ();
4720 event_ptid = target_wait (minus_one_ptid, ws, TARGET_WNOHANG);
4722 if (debug_infrun)
4723 print_target_wait_results (minus_one_ptid, event_ptid, *ws);
4725 return event_ptid;
4728 /* Wait for one event out of any target. */
4730 static wait_one_event
4731 wait_one ()
4733 while (1)
4735 for (inferior *inf : all_inferiors ())
4737 process_stratum_target *target = inf->process_target ();
4738 if (target == nullptr
4739 || !target->is_async_p ()
4740 || !target->threads_executing)
4741 continue;
4743 switch_to_inferior_no_thread (inf);
4745 wait_one_event event;
4746 event.target = target;
4747 event.ptid = poll_one_curr_target (&event.ws);
4749 if (event.ws.kind () == TARGET_WAITKIND_NO_RESUMED)
4751 /* If nothing is resumed, remove the target from the
4752 event loop. */
4753 target_async (false);
4755 else if (event.ws.kind () != TARGET_WAITKIND_IGNORE)
4756 return event;
4759 /* Block waiting for some event. */
4761 fd_set readfds;
4762 int nfds = 0;
4764 FD_ZERO (&readfds);
4766 for (inferior *inf : all_inferiors ())
4768 process_stratum_target *target = inf->process_target ();
4769 if (target == nullptr
4770 || !target->is_async_p ()
4771 || !target->threads_executing)
4772 continue;
4774 int fd = target->async_wait_fd ();
4775 FD_SET (fd, &readfds);
4776 if (nfds <= fd)
4777 nfds = fd + 1;
4780 if (nfds == 0)
4782 /* No waitable targets left. All must be stopped. */
4783 target_waitstatus ws;
4784 ws.set_no_resumed ();
4785 return {nullptr, minus_one_ptid, std::move (ws)};
4788 QUIT;
4790 int numfds = interruptible_select (nfds, &readfds, 0, nullptr, 0);
4791 if (numfds < 0)
4793 if (errno == EINTR)
4794 continue;
4795 else
4796 perror_with_name ("interruptible_select");
4801 /* Save the thread's event and stop reason to process it later. */
4803 static void
4804 save_waitstatus (struct thread_info *tp, const target_waitstatus &ws)
4806 infrun_debug_printf ("saving status %s for %s",
4807 ws.to_string ().c_str (),
4808 tp->ptid.to_string ().c_str ());
4810 /* Record for later. */
4811 tp->set_pending_waitstatus (ws);
4813 if (ws.kind () == TARGET_WAITKIND_STOPPED
4814 && ws.sig () == GDB_SIGNAL_TRAP)
4816 struct regcache *regcache = get_thread_regcache (tp);
4817 const address_space *aspace = regcache->aspace ();
4818 CORE_ADDR pc = regcache_read_pc (regcache);
4820 adjust_pc_after_break (tp, tp->pending_waitstatus ());
4822 scoped_restore_current_thread restore_thread;
4823 switch_to_thread (tp);
4825 if (target_stopped_by_watchpoint ())
4826 tp->set_stop_reason (TARGET_STOPPED_BY_WATCHPOINT);
4827 else if (target_supports_stopped_by_sw_breakpoint ()
4828 && target_stopped_by_sw_breakpoint ())
4829 tp->set_stop_reason (TARGET_STOPPED_BY_SW_BREAKPOINT);
4830 else if (target_supports_stopped_by_hw_breakpoint ()
4831 && target_stopped_by_hw_breakpoint ())
4832 tp->set_stop_reason (TARGET_STOPPED_BY_HW_BREAKPOINT);
4833 else if (!target_supports_stopped_by_hw_breakpoint ()
4834 && hardware_breakpoint_inserted_here_p (aspace, pc))
4835 tp->set_stop_reason (TARGET_STOPPED_BY_HW_BREAKPOINT);
4836 else if (!target_supports_stopped_by_sw_breakpoint ()
4837 && software_breakpoint_inserted_here_p (aspace, pc))
4838 tp->set_stop_reason (TARGET_STOPPED_BY_SW_BREAKPOINT);
4839 else if (!thread_has_single_step_breakpoints_set (tp)
4840 && currently_stepping (tp))
4841 tp->set_stop_reason (TARGET_STOPPED_BY_SINGLE_STEP);
4845 /* Mark the non-executing threads accordingly. In all-stop, all
4846 threads of all processes are stopped when we get any event
4847 reported. In non-stop mode, only the event thread stops. */
4849 static void
4850 mark_non_executing_threads (process_stratum_target *target,
4851 ptid_t event_ptid,
4852 const target_waitstatus &ws)
4854 ptid_t mark_ptid;
4856 if (!target_is_non_stop_p ())
4857 mark_ptid = minus_one_ptid;
4858 else if (ws.kind () == TARGET_WAITKIND_SIGNALLED
4859 || ws.kind () == TARGET_WAITKIND_EXITED)
4861 /* If we're handling a process exit in non-stop mode, even
4862 though threads haven't been deleted yet, one would think
4863 that there is nothing to do, as threads of the dead process
4864 will be soon deleted, and threads of any other process were
4865 left running. However, on some targets, threads survive a
4866 process exit event. E.g., for the "checkpoint" command,
4867 when the current checkpoint/fork exits, linux-fork.c
4868 automatically switches to another fork from within
4869 target_mourn_inferior, by associating the same
4870 inferior/thread to another fork. We haven't mourned yet at
4871 this point, but we must mark any threads left in the
4872 process as not-executing so that finish_thread_state marks
4873 them stopped (in the user's perspective) if/when we present
4874 the stop to the user. */
4875 mark_ptid = ptid_t (event_ptid.pid ());
4877 else
4878 mark_ptid = event_ptid;
4880 set_executing (target, mark_ptid, false);
4882 /* Likewise the resumed flag. */
4883 set_resumed (target, mark_ptid, false);
4886 /* Handle one event after stopping threads. If the eventing thread
4887 reports back any interesting event, we leave it pending. If the
4888 eventing thread was in the middle of a displaced step, we
4889 cancel/finish it, and unless the thread's inferior is being
4890 detached, put the thread back in the step-over chain. Returns true
4891 if there are no resumed threads left in the target (thus there's no
4892 point in waiting further), false otherwise. */
4894 static bool
4895 handle_one (const wait_one_event &event)
4897 infrun_debug_printf
4898 ("%s %s", event.ws.to_string ().c_str (),
4899 event.ptid.to_string ().c_str ());
4901 if (event.ws.kind () == TARGET_WAITKIND_NO_RESUMED)
4903 /* All resumed threads exited. */
4904 return true;
4906 else if (event.ws.kind () == TARGET_WAITKIND_THREAD_EXITED
4907 || event.ws.kind () == TARGET_WAITKIND_EXITED
4908 || event.ws.kind () == TARGET_WAITKIND_SIGNALLED)
4910 /* One thread/process exited/signalled. */
4912 thread_info *t = nullptr;
4914 /* The target may have reported just a pid. If so, try
4915 the first non-exited thread. */
4916 if (event.ptid.is_pid ())
4918 int pid = event.ptid.pid ();
4919 inferior *inf = find_inferior_pid (event.target, pid);
4920 for (thread_info *tp : inf->non_exited_threads ())
4922 t = tp;
4923 break;
4926 /* If there is no available thread, the event would
4927 have to be appended to a per-inferior event list,
4928 which does not exist (and if it did, we'd have
4929 to adjust run control command to be able to
4930 resume such an inferior). We assert here instead
4931 of going into an infinite loop. */
4932 gdb_assert (t != nullptr);
4934 infrun_debug_printf
4935 ("using %s", t->ptid.to_string ().c_str ());
4937 else
4939 t = find_thread_ptid (event.target, event.ptid);
4940 /* Check if this is the first time we see this thread.
4941 Don't bother adding if it individually exited. */
4942 if (t == nullptr
4943 && event.ws.kind () != TARGET_WAITKIND_THREAD_EXITED)
4944 t = add_thread (event.target, event.ptid);
4947 if (t != nullptr)
4949 /* Set the threads as non-executing to avoid
4950 another stop attempt on them. */
4951 switch_to_thread_no_regs (t);
4952 mark_non_executing_threads (event.target, event.ptid,
4953 event.ws);
4954 save_waitstatus (t, event.ws);
4955 t->stop_requested = false;
4958 else
4960 thread_info *t = find_thread_ptid (event.target, event.ptid);
4961 if (t == nullptr)
4962 t = add_thread (event.target, event.ptid);
4964 t->stop_requested = 0;
4965 t->set_executing (false);
4966 t->set_resumed (false);
4967 t->control.may_range_step = 0;
4969 /* This may be the first time we see the inferior report
4970 a stop. */
4971 if (t->inf->needs_setup)
4973 switch_to_thread_no_regs (t);
4974 setup_inferior (0);
4977 if (event.ws.kind () == TARGET_WAITKIND_STOPPED
4978 && event.ws.sig () == GDB_SIGNAL_0)
4980 /* We caught the event that we intended to catch, so
4981 there's no event to save as pending. */
4983 if (displaced_step_finish (t, GDB_SIGNAL_0)
4984 == DISPLACED_STEP_FINISH_STATUS_NOT_EXECUTED)
4986 /* Add it back to the step-over queue. */
4987 infrun_debug_printf
4988 ("displaced-step of %s canceled",
4989 t->ptid.to_string ().c_str ());
4991 t->control.trap_expected = 0;
4992 if (!t->inf->detaching)
4993 global_thread_step_over_chain_enqueue (t);
4996 else
4998 enum gdb_signal sig;
4999 struct regcache *regcache;
5001 infrun_debug_printf
5002 ("target_wait %s, saving status for %s",
5003 event.ws.to_string ().c_str (),
5004 t->ptid.to_string ().c_str ());
5006 /* Record for later. */
5007 save_waitstatus (t, event.ws);
5009 sig = (event.ws.kind () == TARGET_WAITKIND_STOPPED
5010 ? event.ws.sig () : GDB_SIGNAL_0);
5012 if (displaced_step_finish (t, sig)
5013 == DISPLACED_STEP_FINISH_STATUS_NOT_EXECUTED)
5015 /* Add it back to the step-over queue. */
5016 t->control.trap_expected = 0;
5017 if (!t->inf->detaching)
5018 global_thread_step_over_chain_enqueue (t);
5021 regcache = get_thread_regcache (t);
5022 t->set_stop_pc (regcache_read_pc (regcache));
5024 infrun_debug_printf ("saved stop_pc=%s for %s "
5025 "(currently_stepping=%d)",
5026 paddress (target_gdbarch (), t->stop_pc ()),
5027 t->ptid.to_string ().c_str (),
5028 currently_stepping (t));
5032 return false;
5035 /* See infrun.h. */
5037 void
5038 stop_all_threads (const char *reason, inferior *inf)
5040 /* We may need multiple passes to discover all threads. */
5041 int pass;
5042 int iterations = 0;
5044 gdb_assert (exists_non_stop_target ());
5046 INFRUN_SCOPED_DEBUG_START_END ("reason=%s, inf=%d", reason,
5047 inf != nullptr ? inf->num : -1);
5049 infrun_debug_show_threads ("non-exited threads",
5050 all_non_exited_threads ());
5052 scoped_restore_current_thread restore_thread;
5054 /* Enable thread events on relevant targets. */
5055 for (auto *target : all_non_exited_process_targets ())
5057 if (inf != nullptr && inf->process_target () != target)
5058 continue;
5060 switch_to_target_no_thread (target);
5061 target_thread_events (true);
5064 SCOPE_EXIT
5066 /* Disable thread events on relevant targets. */
5067 for (auto *target : all_non_exited_process_targets ())
5069 if (inf != nullptr && inf->process_target () != target)
5070 continue;
5072 switch_to_target_no_thread (target);
5073 target_thread_events (false);
5076 /* Use debug_prefixed_printf directly to get a meaningful function
5077 name. */
5078 if (debug_infrun)
5079 debug_prefixed_printf ("infrun", "stop_all_threads", "done");
5082 /* Request threads to stop, and then wait for the stops. Because
5083 threads we already know about can spawn more threads while we're
5084 trying to stop them, and we only learn about new threads when we
5085 update the thread list, do this in a loop, and keep iterating
5086 until two passes find no threads that need to be stopped. */
5087 for (pass = 0; pass < 2; pass++, iterations++)
5089 infrun_debug_printf ("pass=%d, iterations=%d", pass, iterations);
5090 while (1)
5092 int waits_needed = 0;
5094 for (auto *target : all_non_exited_process_targets ())
5096 if (inf != nullptr && inf->process_target () != target)
5097 continue;
5099 switch_to_target_no_thread (target);
5100 update_thread_list ();
5103 /* Go through all threads looking for threads that we need
5104 to tell the target to stop. */
5105 for (thread_info *t : all_non_exited_threads ())
5107 if (inf != nullptr && t->inf != inf)
5108 continue;
5110 /* For a single-target setting with an all-stop target,
5111 we would not even arrive here. For a multi-target
5112 setting, until GDB is able to handle a mixture of
5113 all-stop and non-stop targets, simply skip all-stop
5114 targets' threads. This should be fine due to the
5115 protection of 'check_multi_target_resumption'. */
5117 switch_to_thread_no_regs (t);
5118 if (!target_is_non_stop_p ())
5119 continue;
5121 if (t->executing ())
5123 /* If already stopping, don't request a stop again.
5124 We just haven't seen the notification yet. */
5125 if (!t->stop_requested)
5127 infrun_debug_printf (" %s executing, need stop",
5128 t->ptid.to_string ().c_str ());
5129 target_stop (t->ptid);
5130 t->stop_requested = 1;
5132 else
5134 infrun_debug_printf (" %s executing, already stopping",
5135 t->ptid.to_string ().c_str ());
5138 if (t->stop_requested)
5139 waits_needed++;
5141 else
5143 infrun_debug_printf (" %s not executing",
5144 t->ptid.to_string ().c_str ());
5146 /* The thread may be not executing, but still be
5147 resumed with a pending status to process. */
5148 t->set_resumed (false);
5152 if (waits_needed == 0)
5153 break;
5155 /* If we find new threads on the second iteration, restart
5156 over. We want to see two iterations in a row with all
5157 threads stopped. */
5158 if (pass > 0)
5159 pass = -1;
5161 for (int i = 0; i < waits_needed; i++)
5163 wait_one_event event = wait_one ();
5164 if (handle_one (event))
5165 break;
5171 /* Handle a TARGET_WAITKIND_NO_RESUMED event. */
5173 static bool
5174 handle_no_resumed (struct execution_control_state *ecs)
5176 if (target_can_async_p ())
5178 bool any_sync = false;
5180 for (ui *ui : all_uis ())
5182 if (ui->prompt_state == PROMPT_BLOCKED)
5184 any_sync = true;
5185 break;
5188 if (!any_sync)
5190 /* There were no unwaited-for children left in the target, but,
5191 we're not synchronously waiting for events either. Just
5192 ignore. */
5194 infrun_debug_printf ("TARGET_WAITKIND_NO_RESUMED (ignoring: bg)");
5195 prepare_to_wait (ecs);
5196 return true;
5200 /* Otherwise, if we were running a synchronous execution command, we
5201 may need to cancel it and give the user back the terminal.
5203 In non-stop mode, the target can't tell whether we've already
5204 consumed previous stop events, so it can end up sending us a
5205 no-resumed event like so:
5207 #0 - thread 1 is left stopped
5209 #1 - thread 2 is resumed and hits breakpoint
5210 -> TARGET_WAITKIND_STOPPED
5212 #2 - thread 3 is resumed and exits
5213 this is the last resumed thread, so
5214 -> TARGET_WAITKIND_NO_RESUMED
5216 #3 - gdb processes stop for thread 2 and decides to re-resume
5219 #4 - gdb processes the TARGET_WAITKIND_NO_RESUMED event.
5220 thread 2 is now resumed, so the event should be ignored.
5222 IOW, if the stop for thread 2 doesn't end a foreground command,
5223 then we need to ignore the following TARGET_WAITKIND_NO_RESUMED
5224 event. But it could be that the event meant that thread 2 itself
5225 (or whatever other thread was the last resumed thread) exited.
5227 To address this we refresh the thread list and check whether we
5228 have resumed threads _now_. In the example above, this removes
5229 thread 3 from the thread list. If thread 2 was re-resumed, we
5230 ignore this event. If we find no thread resumed, then we cancel
5231 the synchronous command and show "no unwaited-for " to the
5232 user. */
5234 inferior *curr_inf = current_inferior ();
5236 scoped_restore_current_thread restore_thread;
5237 update_thread_list ();
5239 /* If:
5241 - the current target has no thread executing, and
5242 - the current inferior is native, and
5243 - the current inferior is the one which has the terminal, and
5244 - we did nothing,
5246 then a Ctrl-C from this point on would remain stuck in the
5247 kernel, until a thread resumes and dequeues it. That would
5248 result in the GDB CLI not reacting to Ctrl-C, not able to
5249 interrupt the program. To address this, if the current inferior
5250 no longer has any thread executing, we give the terminal to some
5251 other inferior that has at least one thread executing. */
5252 bool swap_terminal = true;
5254 /* Whether to ignore this TARGET_WAITKIND_NO_RESUMED event, or
5255 whether to report it to the user. */
5256 bool ignore_event = false;
5258 for (thread_info *thread : all_non_exited_threads ())
5260 if (swap_terminal && thread->executing ())
5262 if (thread->inf != curr_inf)
5264 target_terminal::ours ();
5266 switch_to_thread (thread);
5267 target_terminal::inferior ();
5269 swap_terminal = false;
5272 if (!ignore_event && thread->resumed ())
5274 /* Either there were no unwaited-for children left in the
5275 target at some point, but there are now, or some target
5276 other than the eventing one has unwaited-for children
5277 left. Just ignore. */
5278 infrun_debug_printf ("TARGET_WAITKIND_NO_RESUMED "
5279 "(ignoring: found resumed)");
5281 ignore_event = true;
5284 if (ignore_event && !swap_terminal)
5285 break;
5288 if (ignore_event)
5290 switch_to_inferior_no_thread (curr_inf);
5291 prepare_to_wait (ecs);
5292 return true;
5295 /* Go ahead and report the event. */
5296 return false;
5299 /* Given an execution control state that has been freshly filled in by
5300 an event from the inferior, figure out what it means and take
5301 appropriate action.
5303 The alternatives are:
5305 1) stop_waiting and return; to really stop and return to the
5306 debugger.
5308 2) keep_going and return; to wait for the next event (set
5309 ecs->event_thread->stepping_over_breakpoint to 1 to single step
5310 once). */
5312 static void
5313 handle_inferior_event (struct execution_control_state *ecs)
5315 /* Make sure that all temporary struct value objects that were
5316 created during the handling of the event get deleted at the
5317 end. */
5318 scoped_value_mark free_values;
5320 infrun_debug_printf ("%s", ecs->ws.to_string ().c_str ());
5322 if (ecs->ws.kind () == TARGET_WAITKIND_IGNORE)
5324 /* We had an event in the inferior, but we are not interested in
5325 handling it at this level. The lower layers have already
5326 done what needs to be done, if anything.
5328 One of the possible circumstances for this is when the
5329 inferior produces output for the console. The inferior has
5330 not stopped, and we are ignoring the event. Another possible
5331 circumstance is any event which the lower level knows will be
5332 reported multiple times without an intervening resume. */
5333 prepare_to_wait (ecs);
5334 return;
5337 if (ecs->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
5339 prepare_to_wait (ecs);
5340 return;
5343 if (ecs->ws.kind () == TARGET_WAITKIND_NO_RESUMED
5344 && handle_no_resumed (ecs))
5345 return;
5347 /* Cache the last target/ptid/waitstatus. */
5348 set_last_target_status (ecs->target, ecs->ptid, ecs->ws);
5350 /* Always clear state belonging to the previous time we stopped. */
5351 stop_stack_dummy = STOP_NONE;
5353 if (ecs->ws.kind () == TARGET_WAITKIND_NO_RESUMED)
5355 /* No unwaited-for children left. IOW, all resumed children
5356 have exited. */
5357 stop_print_frame = false;
5358 stop_waiting (ecs);
5359 return;
5362 if (ecs->ws.kind () != TARGET_WAITKIND_EXITED
5363 && ecs->ws.kind () != TARGET_WAITKIND_SIGNALLED)
5365 ecs->event_thread = find_thread_ptid (ecs->target, ecs->ptid);
5366 /* If it's a new thread, add it to the thread database. */
5367 if (ecs->event_thread == nullptr)
5368 ecs->event_thread = add_thread (ecs->target, ecs->ptid);
5370 /* Disable range stepping. If the next step request could use a
5371 range, this will be end up re-enabled then. */
5372 ecs->event_thread->control.may_range_step = 0;
5375 /* Dependent on valid ECS->EVENT_THREAD. */
5376 adjust_pc_after_break (ecs->event_thread, ecs->ws);
5378 /* Dependent on the current PC value modified by adjust_pc_after_break. */
5379 reinit_frame_cache ();
5381 breakpoint_retire_moribund ();
5383 /* First, distinguish signals caused by the debugger from signals
5384 that have to do with the program's own actions. Note that
5385 breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
5386 on the operating system version. Here we detect when a SIGILL or
5387 SIGEMT is really a breakpoint and change it to SIGTRAP. We do
5388 something similar for SIGSEGV, since a SIGSEGV will be generated
5389 when we're trying to execute a breakpoint instruction on a
5390 non-executable stack. This happens for call dummy breakpoints
5391 for architectures like SPARC that place call dummies on the
5392 stack. */
5393 if (ecs->ws.kind () == TARGET_WAITKIND_STOPPED
5394 && (ecs->ws.sig () == GDB_SIGNAL_ILL
5395 || ecs->ws.sig () == GDB_SIGNAL_SEGV
5396 || ecs->ws.sig () == GDB_SIGNAL_EMT))
5398 struct regcache *regcache = get_thread_regcache (ecs->event_thread);
5400 if (breakpoint_inserted_here_p (regcache->aspace (),
5401 regcache_read_pc (regcache)))
5403 infrun_debug_printf ("Treating signal as SIGTRAP");
5404 ecs->ws.set_stopped (GDB_SIGNAL_TRAP);
5408 mark_non_executing_threads (ecs->target, ecs->ptid, ecs->ws);
5410 switch (ecs->ws.kind ())
5412 case TARGET_WAITKIND_LOADED:
5414 context_switch (ecs);
5415 /* Ignore gracefully during startup of the inferior, as it might
5416 be the shell which has just loaded some objects, otherwise
5417 add the symbols for the newly loaded objects. Also ignore at
5418 the beginning of an attach or remote session; we will query
5419 the full list of libraries once the connection is
5420 established. */
5422 stop_kind stop_soon = get_inferior_stop_soon (ecs);
5423 if (stop_soon == NO_STOP_QUIETLY)
5425 struct regcache *regcache;
5427 regcache = get_thread_regcache (ecs->event_thread);
5429 handle_solib_event ();
5431 ecs->event_thread->set_stop_pc (regcache_read_pc (regcache));
5432 ecs->event_thread->control.stop_bpstat
5433 = bpstat_stop_status_nowatch (regcache->aspace (),
5434 ecs->event_thread->stop_pc (),
5435 ecs->event_thread, ecs->ws);
5437 if (handle_stop_requested (ecs))
5438 return;
5440 if (bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5442 /* A catchpoint triggered. */
5443 process_event_stop_test (ecs);
5444 return;
5447 /* If requested, stop when the dynamic linker notifies
5448 gdb of events. This allows the user to get control
5449 and place breakpoints in initializer routines for
5450 dynamically loaded objects (among other things). */
5451 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
5452 if (stop_on_solib_events)
5454 /* Make sure we print "Stopped due to solib-event" in
5455 normal_stop. */
5456 stop_print_frame = true;
5458 stop_waiting (ecs);
5459 return;
5463 /* If we are skipping through a shell, or through shared library
5464 loading that we aren't interested in, resume the program. If
5465 we're running the program normally, also resume. */
5466 if (stop_soon == STOP_QUIETLY || stop_soon == NO_STOP_QUIETLY)
5468 /* Loading of shared libraries might have changed breakpoint
5469 addresses. Make sure new breakpoints are inserted. */
5470 if (stop_soon == NO_STOP_QUIETLY)
5471 insert_breakpoints ();
5472 resume (GDB_SIGNAL_0);
5473 prepare_to_wait (ecs);
5474 return;
5477 /* But stop if we're attaching or setting up a remote
5478 connection. */
5479 if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
5480 || stop_soon == STOP_QUIETLY_REMOTE)
5482 infrun_debug_printf ("quietly stopped");
5483 stop_waiting (ecs);
5484 return;
5487 internal_error (_("unhandled stop_soon: %d"), (int) stop_soon);
5490 case TARGET_WAITKIND_SPURIOUS:
5491 if (handle_stop_requested (ecs))
5492 return;
5493 context_switch (ecs);
5494 resume (GDB_SIGNAL_0);
5495 prepare_to_wait (ecs);
5496 return;
5498 case TARGET_WAITKIND_THREAD_CREATED:
5499 if (handle_stop_requested (ecs))
5500 return;
5501 context_switch (ecs);
5502 if (!switch_back_to_stepped_thread (ecs))
5503 keep_going (ecs);
5504 return;
5506 case TARGET_WAITKIND_EXITED:
5507 case TARGET_WAITKIND_SIGNALLED:
5509 /* Depending on the system, ecs->ptid may point to a thread or
5510 to a process. On some targets, target_mourn_inferior may
5511 need to have access to the just-exited thread. That is the
5512 case of GNU/Linux's "checkpoint" support, for example.
5513 Call the switch_to_xxx routine as appropriate. */
5514 thread_info *thr = find_thread_ptid (ecs->target, ecs->ptid);
5515 if (thr != nullptr)
5516 switch_to_thread (thr);
5517 else
5519 inferior *inf = find_inferior_ptid (ecs->target, ecs->ptid);
5520 switch_to_inferior_no_thread (inf);
5523 handle_vfork_child_exec_or_exit (0);
5524 target_terminal::ours (); /* Must do this before mourn anyway. */
5526 /* Clearing any previous state of convenience variables. */
5527 clear_exit_convenience_vars ();
5529 if (ecs->ws.kind () == TARGET_WAITKIND_EXITED)
5531 /* Record the exit code in the convenience variable $_exitcode, so
5532 that the user can inspect this again later. */
5533 set_internalvar_integer (lookup_internalvar ("_exitcode"),
5534 (LONGEST) ecs->ws.exit_status ());
5536 /* Also record this in the inferior itself. */
5537 current_inferior ()->has_exit_code = true;
5538 current_inferior ()->exit_code = (LONGEST) ecs->ws.exit_status ();
5540 /* Support the --return-child-result option. */
5541 return_child_result_value = ecs->ws.exit_status ();
5543 gdb::observers::exited.notify (ecs->ws.exit_status ());
5545 else
5547 struct gdbarch *gdbarch = current_inferior ()->gdbarch;
5549 if (gdbarch_gdb_signal_to_target_p (gdbarch))
5551 /* Set the value of the internal variable $_exitsignal,
5552 which holds the signal uncaught by the inferior. */
5553 set_internalvar_integer (lookup_internalvar ("_exitsignal"),
5554 gdbarch_gdb_signal_to_target (gdbarch,
5555 ecs->ws.sig ()));
5557 else
5559 /* We don't have access to the target's method used for
5560 converting between signal numbers (GDB's internal
5561 representation <-> target's representation).
5562 Therefore, we cannot do a good job at displaying this
5563 information to the user. It's better to just warn
5564 her about it (if infrun debugging is enabled), and
5565 give up. */
5566 infrun_debug_printf ("Cannot fill $_exitsignal with the correct "
5567 "signal number.");
5570 gdb::observers::signal_exited.notify (ecs->ws.sig ());
5573 gdb_flush (gdb_stdout);
5574 target_mourn_inferior (inferior_ptid);
5575 stop_print_frame = false;
5576 stop_waiting (ecs);
5577 return;
5579 case TARGET_WAITKIND_FORKED:
5580 case TARGET_WAITKIND_VFORKED:
5581 /* Check whether the inferior is displaced stepping. */
5583 struct regcache *regcache = get_thread_regcache (ecs->event_thread);
5584 struct gdbarch *gdbarch = regcache->arch ();
5585 inferior *parent_inf = find_inferior_ptid (ecs->target, ecs->ptid);
5587 /* If this is a fork (child gets its own address space copy)
5588 and some displaced step buffers were in use at the time of
5589 the fork, restore the displaced step buffer bytes in the
5590 child process.
5592 Architectures which support displaced stepping and fork
5593 events must supply an implementation of
5594 gdbarch_displaced_step_restore_all_in_ptid. This is not
5595 enforced during gdbarch validation to support architectures
5596 which support displaced stepping but not forks. */
5597 if (ecs->ws.kind () == TARGET_WAITKIND_FORKED
5598 && gdbarch_supports_displaced_stepping (gdbarch))
5599 gdbarch_displaced_step_restore_all_in_ptid
5600 (gdbarch, parent_inf, ecs->ws.child_ptid ());
5602 /* If displaced stepping is supported, and thread ecs->ptid is
5603 displaced stepping. */
5604 if (displaced_step_in_progress_thread (ecs->event_thread))
5606 struct regcache *child_regcache;
5607 CORE_ADDR parent_pc;
5609 /* GDB has got TARGET_WAITKIND_FORKED or TARGET_WAITKIND_VFORKED,
5610 indicating that the displaced stepping of syscall instruction
5611 has been done. Perform cleanup for parent process here. Note
5612 that this operation also cleans up the child process for vfork,
5613 because their pages are shared. */
5614 displaced_step_finish (ecs->event_thread, GDB_SIGNAL_TRAP);
5615 /* Start a new step-over in another thread if there's one
5616 that needs it. */
5617 start_step_over ();
5619 /* Since the vfork/fork syscall instruction was executed in the scratchpad,
5620 the child's PC is also within the scratchpad. Set the child's PC
5621 to the parent's PC value, which has already been fixed up.
5622 FIXME: we use the parent's aspace here, although we're touching
5623 the child, because the child hasn't been added to the inferior
5624 list yet at this point. */
5626 child_regcache
5627 = get_thread_arch_aspace_regcache (parent_inf->process_target (),
5628 ecs->ws.child_ptid (),
5629 gdbarch,
5630 parent_inf->aspace);
5631 /* Read PC value of parent process. */
5632 parent_pc = regcache_read_pc (regcache);
5634 displaced_debug_printf ("write child pc from %s to %s",
5635 paddress (gdbarch,
5636 regcache_read_pc (child_regcache)),
5637 paddress (gdbarch, parent_pc));
5639 regcache_write_pc (child_regcache, parent_pc);
5643 context_switch (ecs);
5645 /* Immediately detach breakpoints from the child before there's
5646 any chance of letting the user delete breakpoints from the
5647 breakpoint lists. If we don't do this early, it's easy to
5648 leave left over traps in the child, vis: "break foo; catch
5649 fork; c; <fork>; del; c; <child calls foo>". We only follow
5650 the fork on the last `continue', and by that time the
5651 breakpoint at "foo" is long gone from the breakpoint table.
5652 If we vforked, then we don't need to unpatch here, since both
5653 parent and child are sharing the same memory pages; we'll
5654 need to unpatch at follow/detach time instead to be certain
5655 that new breakpoints added between catchpoint hit time and
5656 vfork follow are detached. */
5657 if (ecs->ws.kind () != TARGET_WAITKIND_VFORKED)
5659 /* This won't actually modify the breakpoint list, but will
5660 physically remove the breakpoints from the child. */
5661 detach_breakpoints (ecs->ws.child_ptid ());
5664 delete_just_stopped_threads_single_step_breakpoints ();
5666 /* In case the event is caught by a catchpoint, remember that
5667 the event is to be followed at the next resume of the thread,
5668 and not immediately. */
5669 ecs->event_thread->pending_follow = ecs->ws;
5671 ecs->event_thread->set_stop_pc
5672 (regcache_read_pc (get_thread_regcache (ecs->event_thread)));
5674 ecs->event_thread->control.stop_bpstat
5675 = bpstat_stop_status_nowatch (get_current_regcache ()->aspace (),
5676 ecs->event_thread->stop_pc (),
5677 ecs->event_thread, ecs->ws);
5679 if (handle_stop_requested (ecs))
5680 return;
5682 /* If no catchpoint triggered for this, then keep going. Note
5683 that we're interested in knowing the bpstat actually causes a
5684 stop, not just if it may explain the signal. Software
5685 watchpoints, for example, always appear in the bpstat. */
5686 if (!bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5688 bool follow_child
5689 = (follow_fork_mode_string == follow_fork_mode_child);
5691 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
5693 process_stratum_target *targ
5694 = ecs->event_thread->inf->process_target ();
5696 bool should_resume = follow_fork ();
5698 /* Note that one of these may be an invalid pointer,
5699 depending on detach_fork. */
5700 thread_info *parent = ecs->event_thread;
5701 thread_info *child = find_thread_ptid (targ, ecs->ws.child_ptid ());
5703 /* At this point, the parent is marked running, and the
5704 child is marked stopped. */
5706 /* If not resuming the parent, mark it stopped. */
5707 if (follow_child && !detach_fork && !non_stop && !sched_multi)
5708 parent->set_running (false);
5710 /* If resuming the child, mark it running. */
5711 if (follow_child || (!detach_fork && (non_stop || sched_multi)))
5712 child->set_running (true);
5714 /* In non-stop mode, also resume the other branch. */
5715 if (!detach_fork && (non_stop
5716 || (sched_multi && target_is_non_stop_p ())))
5718 if (follow_child)
5719 switch_to_thread (parent);
5720 else
5721 switch_to_thread (child);
5723 ecs->event_thread = inferior_thread ();
5724 ecs->ptid = inferior_ptid;
5725 keep_going (ecs);
5728 if (follow_child)
5729 switch_to_thread (child);
5730 else
5731 switch_to_thread (parent);
5733 ecs->event_thread = inferior_thread ();
5734 ecs->ptid = inferior_ptid;
5736 if (should_resume)
5738 /* Never call switch_back_to_stepped_thread if we are waiting for
5739 vfork-done (waiting for an external vfork child to exec or
5740 exit). We will resume only the vforking thread for the purpose
5741 of collecting the vfork-done event, and we will restart any
5742 step once the critical shared address space window is done. */
5743 if ((!follow_child
5744 && detach_fork
5745 && parent->inf->thread_waiting_for_vfork_done != nullptr)
5746 || !switch_back_to_stepped_thread (ecs))
5747 keep_going (ecs);
5749 else
5750 stop_waiting (ecs);
5751 return;
5753 process_event_stop_test (ecs);
5754 return;
5756 case TARGET_WAITKIND_VFORK_DONE:
5757 /* Done with the shared memory region. Re-insert breakpoints in
5758 the parent, and keep going. */
5760 context_switch (ecs);
5762 handle_vfork_done (ecs->event_thread);
5763 gdb_assert (inferior_thread () == ecs->event_thread);
5765 if (handle_stop_requested (ecs))
5766 return;
5768 if (!switch_back_to_stepped_thread (ecs))
5770 gdb_assert (inferior_thread () == ecs->event_thread);
5771 /* This also takes care of reinserting breakpoints in the
5772 previously locked inferior. */
5773 keep_going (ecs);
5775 return;
5777 case TARGET_WAITKIND_EXECD:
5779 /* Note we can't read registers yet (the stop_pc), because we
5780 don't yet know the inferior's post-exec architecture.
5781 'stop_pc' is explicitly read below instead. */
5782 switch_to_thread_no_regs (ecs->event_thread);
5784 /* Do whatever is necessary to the parent branch of the vfork. */
5785 handle_vfork_child_exec_or_exit (1);
5787 /* This causes the eventpoints and symbol table to be reset.
5788 Must do this now, before trying to determine whether to
5789 stop. */
5790 follow_exec (inferior_ptid, ecs->ws.execd_pathname ());
5792 /* In follow_exec we may have deleted the original thread and
5793 created a new one. Make sure that the event thread is the
5794 execd thread for that case (this is a nop otherwise). */
5795 ecs->event_thread = inferior_thread ();
5797 ecs->event_thread->set_stop_pc
5798 (regcache_read_pc (get_thread_regcache (ecs->event_thread)));
5800 ecs->event_thread->control.stop_bpstat
5801 = bpstat_stop_status_nowatch (get_current_regcache ()->aspace (),
5802 ecs->event_thread->stop_pc (),
5803 ecs->event_thread, ecs->ws);
5805 if (handle_stop_requested (ecs))
5806 return;
5808 /* If no catchpoint triggered for this, then keep going. */
5809 if (!bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5811 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
5812 keep_going (ecs);
5813 return;
5815 process_event_stop_test (ecs);
5816 return;
5818 /* Be careful not to try to gather much state about a thread
5819 that's in a syscall. It's frequently a losing proposition. */
5820 case TARGET_WAITKIND_SYSCALL_ENTRY:
5821 /* Getting the current syscall number. */
5822 if (handle_syscall_event (ecs) == 0)
5823 process_event_stop_test (ecs);
5824 return;
5826 /* Before examining the threads further, step this thread to
5827 get it entirely out of the syscall. (We get notice of the
5828 event when the thread is just on the verge of exiting a
5829 syscall. Stepping one instruction seems to get it back
5830 into user code.) */
5831 case TARGET_WAITKIND_SYSCALL_RETURN:
5832 if (handle_syscall_event (ecs) == 0)
5833 process_event_stop_test (ecs);
5834 return;
5836 case TARGET_WAITKIND_STOPPED:
5837 handle_signal_stop (ecs);
5838 return;
5840 case TARGET_WAITKIND_NO_HISTORY:
5841 /* Reverse execution: target ran out of history info. */
5843 /* Switch to the stopped thread. */
5844 context_switch (ecs);
5845 infrun_debug_printf ("stopped");
5847 delete_just_stopped_threads_single_step_breakpoints ();
5848 ecs->event_thread->set_stop_pc
5849 (regcache_read_pc (get_thread_regcache (inferior_thread ())));
5851 if (handle_stop_requested (ecs))
5852 return;
5854 gdb::observers::no_history.notify ();
5855 stop_waiting (ecs);
5856 return;
5860 /* Restart threads back to what they were trying to do back when we
5861 paused them (because of an in-line step-over or vfork, for example).
5862 The EVENT_THREAD thread is ignored (not restarted).
5864 If INF is non-nullptr, only resume threads from INF. */
5866 static void
5867 restart_threads (struct thread_info *event_thread, inferior *inf)
5869 INFRUN_SCOPED_DEBUG_START_END ("event_thread=%s, inf=%d",
5870 event_thread->ptid.to_string ().c_str (),
5871 inf != nullptr ? inf->num : -1);
5873 gdb_assert (!step_over_info_valid_p ());
5875 /* In case the instruction just stepped spawned a new thread. */
5876 update_thread_list ();
5878 for (thread_info *tp : all_non_exited_threads ())
5880 if (inf != nullptr && tp->inf != inf)
5881 continue;
5883 if (tp->inf->detaching)
5885 infrun_debug_printf ("restart threads: [%s] inferior detaching",
5886 tp->ptid.to_string ().c_str ());
5887 continue;
5890 switch_to_thread_no_regs (tp);
5892 if (tp == event_thread)
5894 infrun_debug_printf ("restart threads: [%s] is event thread",
5895 tp->ptid.to_string ().c_str ());
5896 continue;
5899 if (!(tp->state == THREAD_RUNNING || tp->control.in_infcall))
5901 infrun_debug_printf ("restart threads: [%s] not meant to be running",
5902 tp->ptid.to_string ().c_str ());
5903 continue;
5906 if (tp->resumed ())
5908 infrun_debug_printf ("restart threads: [%s] resumed",
5909 tp->ptid.to_string ().c_str ());
5910 gdb_assert (tp->executing () || tp->has_pending_waitstatus ());
5911 continue;
5914 if (thread_is_in_step_over_chain (tp))
5916 infrun_debug_printf ("restart threads: [%s] needs step-over",
5917 tp->ptid.to_string ().c_str ());
5918 gdb_assert (!tp->resumed ());
5919 continue;
5923 if (tp->has_pending_waitstatus ())
5925 infrun_debug_printf ("restart threads: [%s] has pending status",
5926 tp->ptid.to_string ().c_str ());
5927 tp->set_resumed (true);
5928 continue;
5931 gdb_assert (!tp->stop_requested);
5933 /* If some thread needs to start a step-over at this point, it
5934 should still be in the step-over queue, and thus skipped
5935 above. */
5936 if (thread_still_needs_step_over (tp))
5938 internal_error ("thread [%s] needs a step-over, but not in "
5939 "step-over queue\n",
5940 tp->ptid.to_string ().c_str ());
5943 if (currently_stepping (tp))
5945 infrun_debug_printf ("restart threads: [%s] was stepping",
5946 tp->ptid.to_string ().c_str ());
5947 keep_going_stepped_thread (tp);
5949 else
5951 infrun_debug_printf ("restart threads: [%s] continuing",
5952 tp->ptid.to_string ().c_str ());
5953 execution_control_state ecs (tp);
5954 switch_to_thread (tp);
5955 keep_going_pass_signal (&ecs);
5960 /* Callback for iterate_over_threads. Find a resumed thread that has
5961 a pending waitstatus. */
5963 static int
5964 resumed_thread_with_pending_status (struct thread_info *tp,
5965 void *arg)
5967 return tp->resumed () && tp->has_pending_waitstatus ();
5970 /* Called when we get an event that may finish an in-line or
5971 out-of-line (displaced stepping) step-over started previously.
5972 Return true if the event is processed and we should go back to the
5973 event loop; false if the caller should continue processing the
5974 event. */
5976 static int
5977 finish_step_over (struct execution_control_state *ecs)
5979 displaced_step_finish (ecs->event_thread, ecs->event_thread->stop_signal ());
5981 bool had_step_over_info = step_over_info_valid_p ();
5983 if (had_step_over_info)
5985 /* If we're stepping over a breakpoint with all threads locked,
5986 then only the thread that was stepped should be reporting
5987 back an event. */
5988 gdb_assert (ecs->event_thread->control.trap_expected);
5990 clear_step_over_info ();
5993 if (!target_is_non_stop_p ())
5994 return 0;
5996 /* Start a new step-over in another thread if there's one that
5997 needs it. */
5998 start_step_over ();
6000 /* If we were stepping over a breakpoint before, and haven't started
6001 a new in-line step-over sequence, then restart all other threads
6002 (except the event thread). We can't do this in all-stop, as then
6003 e.g., we wouldn't be able to issue any other remote packet until
6004 these other threads stop. */
6005 if (had_step_over_info && !step_over_info_valid_p ())
6007 struct thread_info *pending;
6009 /* If we only have threads with pending statuses, the restart
6010 below won't restart any thread and so nothing re-inserts the
6011 breakpoint we just stepped over. But we need it inserted
6012 when we later process the pending events, otherwise if
6013 another thread has a pending event for this breakpoint too,
6014 we'd discard its event (because the breakpoint that
6015 originally caused the event was no longer inserted). */
6016 context_switch (ecs);
6017 insert_breakpoints ();
6019 restart_threads (ecs->event_thread);
6021 /* If we have events pending, go through handle_inferior_event
6022 again, picking up a pending event at random. This avoids
6023 thread starvation. */
6025 /* But not if we just stepped over a watchpoint in order to let
6026 the instruction execute so we can evaluate its expression.
6027 The set of watchpoints that triggered is recorded in the
6028 breakpoint objects themselves (see bp->watchpoint_triggered).
6029 If we processed another event first, that other event could
6030 clobber this info. */
6031 if (ecs->event_thread->stepping_over_watchpoint)
6032 return 0;
6034 pending = iterate_over_threads (resumed_thread_with_pending_status,
6035 nullptr);
6036 if (pending != nullptr)
6038 struct thread_info *tp = ecs->event_thread;
6039 struct regcache *regcache;
6041 infrun_debug_printf ("found resumed threads with "
6042 "pending events, saving status");
6044 gdb_assert (pending != tp);
6046 /* Record the event thread's event for later. */
6047 save_waitstatus (tp, ecs->ws);
6048 /* This was cleared early, by handle_inferior_event. Set it
6049 so this pending event is considered by
6050 do_target_wait. */
6051 tp->set_resumed (true);
6053 gdb_assert (!tp->executing ());
6055 regcache = get_thread_regcache (tp);
6056 tp->set_stop_pc (regcache_read_pc (regcache));
6058 infrun_debug_printf ("saved stop_pc=%s for %s "
6059 "(currently_stepping=%d)",
6060 paddress (target_gdbarch (), tp->stop_pc ()),
6061 tp->ptid.to_string ().c_str (),
6062 currently_stepping (tp));
6064 /* This in-line step-over finished; clear this so we won't
6065 start a new one. This is what handle_signal_stop would
6066 do, if we returned false. */
6067 tp->stepping_over_breakpoint = 0;
6069 /* Wake up the event loop again. */
6070 mark_async_event_handler (infrun_async_inferior_event_token);
6072 prepare_to_wait (ecs);
6073 return 1;
6077 return 0;
6080 /* Come here when the program has stopped with a signal. */
6082 static void
6083 handle_signal_stop (struct execution_control_state *ecs)
6085 frame_info_ptr frame;
6086 struct gdbarch *gdbarch;
6087 int stopped_by_watchpoint;
6088 enum stop_kind stop_soon;
6089 int random_signal;
6091 gdb_assert (ecs->ws.kind () == TARGET_WAITKIND_STOPPED);
6093 ecs->event_thread->set_stop_signal (ecs->ws.sig ());
6095 /* Do we need to clean up the state of a thread that has
6096 completed a displaced single-step? (Doing so usually affects
6097 the PC, so do it here, before we set stop_pc.) */
6098 if (finish_step_over (ecs))
6099 return;
6101 /* If we either finished a single-step or hit a breakpoint, but
6102 the user wanted this thread to be stopped, pretend we got a
6103 SIG0 (generic unsignaled stop). */
6104 if (ecs->event_thread->stop_requested
6105 && ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP)
6106 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
6108 ecs->event_thread->set_stop_pc
6109 (regcache_read_pc (get_thread_regcache (ecs->event_thread)));
6111 context_switch (ecs);
6113 if (deprecated_context_hook)
6114 deprecated_context_hook (ecs->event_thread->global_num);
6116 if (debug_infrun)
6118 struct regcache *regcache = get_thread_regcache (ecs->event_thread);
6119 struct gdbarch *reg_gdbarch = regcache->arch ();
6121 infrun_debug_printf
6122 ("stop_pc=%s", paddress (reg_gdbarch, ecs->event_thread->stop_pc ()));
6123 if (target_stopped_by_watchpoint ())
6125 CORE_ADDR addr;
6127 infrun_debug_printf ("stopped by watchpoint");
6129 if (target_stopped_data_address (current_inferior ()->top_target (),
6130 &addr))
6131 infrun_debug_printf ("stopped data address=%s",
6132 paddress (reg_gdbarch, addr));
6133 else
6134 infrun_debug_printf ("(no data address available)");
6138 /* This is originated from start_remote(), start_inferior() and
6139 shared libraries hook functions. */
6140 stop_soon = get_inferior_stop_soon (ecs);
6141 if (stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_REMOTE)
6143 infrun_debug_printf ("quietly stopped");
6144 stop_print_frame = true;
6145 stop_waiting (ecs);
6146 return;
6149 /* This originates from attach_command(). We need to overwrite
6150 the stop_signal here, because some kernels don't ignore a
6151 SIGSTOP in a subsequent ptrace(PTRACE_CONT,SIGSTOP) call.
6152 See more comments in inferior.h. On the other hand, if we
6153 get a non-SIGSTOP, report it to the user - assume the backend
6154 will handle the SIGSTOP if it should show up later.
6156 Also consider that the attach is complete when we see a
6157 SIGTRAP. Some systems (e.g. Windows), and stubs supporting
6158 target extended-remote report it instead of a SIGSTOP
6159 (e.g. gdbserver). We already rely on SIGTRAP being our
6160 signal, so this is no exception.
6162 Also consider that the attach is complete when we see a
6163 GDB_SIGNAL_0. In non-stop mode, GDB will explicitly tell
6164 the target to stop all threads of the inferior, in case the
6165 low level attach operation doesn't stop them implicitly. If
6166 they weren't stopped implicitly, then the stub will report a
6167 GDB_SIGNAL_0, meaning: stopped for no particular reason
6168 other than GDB's request. */
6169 if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
6170 && (ecs->event_thread->stop_signal () == GDB_SIGNAL_STOP
6171 || ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP
6172 || ecs->event_thread->stop_signal () == GDB_SIGNAL_0))
6174 stop_print_frame = true;
6175 stop_waiting (ecs);
6176 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
6177 return;
6180 /* At this point, get hold of the now-current thread's frame. */
6181 frame = get_current_frame ();
6182 gdbarch = get_frame_arch (frame);
6184 /* Pull the single step breakpoints out of the target. */
6185 if (ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP)
6187 struct regcache *regcache;
6188 CORE_ADDR pc;
6190 regcache = get_thread_regcache (ecs->event_thread);
6191 const address_space *aspace = regcache->aspace ();
6193 pc = regcache_read_pc (regcache);
6195 /* However, before doing so, if this single-step breakpoint was
6196 actually for another thread, set this thread up for moving
6197 past it. */
6198 if (!thread_has_single_step_breakpoint_here (ecs->event_thread,
6199 aspace, pc))
6201 if (single_step_breakpoint_inserted_here_p (aspace, pc))
6203 infrun_debug_printf ("[%s] hit another thread's single-step "
6204 "breakpoint",
6205 ecs->ptid.to_string ().c_str ());
6206 ecs->hit_singlestep_breakpoint = 1;
6209 else
6211 infrun_debug_printf ("[%s] hit its single-step breakpoint",
6212 ecs->ptid.to_string ().c_str ());
6215 delete_just_stopped_threads_single_step_breakpoints ();
6217 if (ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP
6218 && ecs->event_thread->control.trap_expected
6219 && ecs->event_thread->stepping_over_watchpoint)
6220 stopped_by_watchpoint = 0;
6221 else
6222 stopped_by_watchpoint = watchpoints_triggered (ecs->ws);
6224 /* If necessary, step over this watchpoint. We'll be back to display
6225 it in a moment. */
6226 if (stopped_by_watchpoint
6227 && (target_have_steppable_watchpoint ()
6228 || gdbarch_have_nonsteppable_watchpoint (gdbarch)))
6230 /* At this point, we are stopped at an instruction which has
6231 attempted to write to a piece of memory under control of
6232 a watchpoint. The instruction hasn't actually executed
6233 yet. If we were to evaluate the watchpoint expression
6234 now, we would get the old value, and therefore no change
6235 would seem to have occurred.
6237 In order to make watchpoints work `right', we really need
6238 to complete the memory write, and then evaluate the
6239 watchpoint expression. We do this by single-stepping the
6240 target.
6242 It may not be necessary to disable the watchpoint to step over
6243 it. For example, the PA can (with some kernel cooperation)
6244 single step over a watchpoint without disabling the watchpoint.
6246 It is far more common to need to disable a watchpoint to step
6247 the inferior over it. If we have non-steppable watchpoints,
6248 we must disable the current watchpoint; it's simplest to
6249 disable all watchpoints.
6251 Any breakpoint at PC must also be stepped over -- if there's
6252 one, it will have already triggered before the watchpoint
6253 triggered, and we either already reported it to the user, or
6254 it didn't cause a stop and we called keep_going. In either
6255 case, if there was a breakpoint at PC, we must be trying to
6256 step past it. */
6257 ecs->event_thread->stepping_over_watchpoint = 1;
6258 keep_going (ecs);
6259 return;
6262 ecs->event_thread->stepping_over_breakpoint = 0;
6263 ecs->event_thread->stepping_over_watchpoint = 0;
6264 bpstat_clear (&ecs->event_thread->control.stop_bpstat);
6265 ecs->event_thread->control.stop_step = 0;
6266 stop_print_frame = true;
6267 stopped_by_random_signal = 0;
6268 bpstat *stop_chain = nullptr;
6270 /* Hide inlined functions starting here, unless we just performed stepi or
6271 nexti. After stepi and nexti, always show the innermost frame (not any
6272 inline function call sites). */
6273 if (ecs->event_thread->control.step_range_end != 1)
6275 const address_space *aspace
6276 = get_thread_regcache (ecs->event_thread)->aspace ();
6278 /* skip_inline_frames is expensive, so we avoid it if we can
6279 determine that the address is one where functions cannot have
6280 been inlined. This improves performance with inferiors that
6281 load a lot of shared libraries, because the solib event
6282 breakpoint is defined as the address of a function (i.e. not
6283 inline). Note that we have to check the previous PC as well
6284 as the current one to catch cases when we have just
6285 single-stepped off a breakpoint prior to reinstating it.
6286 Note that we're assuming that the code we single-step to is
6287 not inline, but that's not definitive: there's nothing
6288 preventing the event breakpoint function from containing
6289 inlined code, and the single-step ending up there. If the
6290 user had set a breakpoint on that inlined code, the missing
6291 skip_inline_frames call would break things. Fortunately
6292 that's an extremely unlikely scenario. */
6293 if (!pc_at_non_inline_function (aspace,
6294 ecs->event_thread->stop_pc (),
6295 ecs->ws)
6296 && !(ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP
6297 && ecs->event_thread->control.trap_expected
6298 && pc_at_non_inline_function (aspace,
6299 ecs->event_thread->prev_pc,
6300 ecs->ws)))
6302 stop_chain = build_bpstat_chain (aspace,
6303 ecs->event_thread->stop_pc (),
6304 ecs->ws);
6305 skip_inline_frames (ecs->event_thread, stop_chain);
6307 /* Re-fetch current thread's frame in case that invalidated
6308 the frame cache. */
6309 frame = get_current_frame ();
6310 gdbarch = get_frame_arch (frame);
6314 if (ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP
6315 && ecs->event_thread->control.trap_expected
6316 && gdbarch_single_step_through_delay_p (gdbarch)
6317 && currently_stepping (ecs->event_thread))
6319 /* We're trying to step off a breakpoint. Turns out that we're
6320 also on an instruction that needs to be stepped multiple
6321 times before it's been fully executing. E.g., architectures
6322 with a delay slot. It needs to be stepped twice, once for
6323 the instruction and once for the delay slot. */
6324 int step_through_delay
6325 = gdbarch_single_step_through_delay (gdbarch, frame);
6327 if (step_through_delay)
6328 infrun_debug_printf ("step through delay");
6330 if (ecs->event_thread->control.step_range_end == 0
6331 && step_through_delay)
6333 /* The user issued a continue when stopped at a breakpoint.
6334 Set up for another trap and get out of here. */
6335 ecs->event_thread->stepping_over_breakpoint = 1;
6336 keep_going (ecs);
6337 return;
6339 else if (step_through_delay)
6341 /* The user issued a step when stopped at a breakpoint.
6342 Maybe we should stop, maybe we should not - the delay
6343 slot *might* correspond to a line of source. In any
6344 case, don't decide that here, just set
6345 ecs->stepping_over_breakpoint, making sure we
6346 single-step again before breakpoints are re-inserted. */
6347 ecs->event_thread->stepping_over_breakpoint = 1;
6351 /* See if there is a breakpoint/watchpoint/catchpoint/etc. that
6352 handles this event. */
6353 ecs->event_thread->control.stop_bpstat
6354 = bpstat_stop_status (get_current_regcache ()->aspace (),
6355 ecs->event_thread->stop_pc (),
6356 ecs->event_thread, ecs->ws, stop_chain);
6358 /* Following in case break condition called a
6359 function. */
6360 stop_print_frame = true;
6362 /* This is where we handle "moribund" watchpoints. Unlike
6363 software breakpoints traps, hardware watchpoint traps are
6364 always distinguishable from random traps. If no high-level
6365 watchpoint is associated with the reported stop data address
6366 anymore, then the bpstat does not explain the signal ---
6367 simply make sure to ignore it if `stopped_by_watchpoint' is
6368 set. */
6370 if (ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP
6371 && !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat,
6372 GDB_SIGNAL_TRAP)
6373 && stopped_by_watchpoint)
6375 infrun_debug_printf ("no user watchpoint explains watchpoint SIGTRAP, "
6376 "ignoring");
6379 /* NOTE: cagney/2003-03-29: These checks for a random signal
6380 at one stage in the past included checks for an inferior
6381 function call's call dummy's return breakpoint. The original
6382 comment, that went with the test, read:
6384 ``End of a stack dummy. Some systems (e.g. Sony news) give
6385 another signal besides SIGTRAP, so check here as well as
6386 above.''
6388 If someone ever tries to get call dummys on a
6389 non-executable stack to work (where the target would stop
6390 with something like a SIGSEGV), then those tests might need
6391 to be re-instated. Given, however, that the tests were only
6392 enabled when momentary breakpoints were not being used, I
6393 suspect that it won't be the case.
6395 NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
6396 be necessary for call dummies on a non-executable stack on
6397 SPARC. */
6399 /* See if the breakpoints module can explain the signal. */
6400 random_signal
6401 = !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat,
6402 ecs->event_thread->stop_signal ());
6404 /* Maybe this was a trap for a software breakpoint that has since
6405 been removed. */
6406 if (random_signal && target_stopped_by_sw_breakpoint ())
6408 if (gdbarch_program_breakpoint_here_p (gdbarch,
6409 ecs->event_thread->stop_pc ()))
6411 struct regcache *regcache;
6412 int decr_pc;
6414 /* Re-adjust PC to what the program would see if GDB was not
6415 debugging it. */
6416 regcache = get_thread_regcache (ecs->event_thread);
6417 decr_pc = gdbarch_decr_pc_after_break (gdbarch);
6418 if (decr_pc != 0)
6420 gdb::optional<scoped_restore_tmpl<int>>
6421 restore_operation_disable;
6423 if (record_full_is_used ())
6424 restore_operation_disable.emplace
6425 (record_full_gdb_operation_disable_set ());
6427 regcache_write_pc (regcache,
6428 ecs->event_thread->stop_pc () + decr_pc);
6431 else
6433 /* A delayed software breakpoint event. Ignore the trap. */
6434 infrun_debug_printf ("delayed software breakpoint trap, ignoring");
6435 random_signal = 0;
6439 /* Maybe this was a trap for a hardware breakpoint/watchpoint that
6440 has since been removed. */
6441 if (random_signal && target_stopped_by_hw_breakpoint ())
6443 /* A delayed hardware breakpoint event. Ignore the trap. */
6444 infrun_debug_printf ("delayed hardware breakpoint/watchpoint "
6445 "trap, ignoring");
6446 random_signal = 0;
6449 /* If not, perhaps stepping/nexting can. */
6450 if (random_signal)
6451 random_signal = !(ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP
6452 && currently_stepping (ecs->event_thread));
6454 /* Perhaps the thread hit a single-step breakpoint of _another_
6455 thread. Single-step breakpoints are transparent to the
6456 breakpoints module. */
6457 if (random_signal)
6458 random_signal = !ecs->hit_singlestep_breakpoint;
6460 /* No? Perhaps we got a moribund watchpoint. */
6461 if (random_signal)
6462 random_signal = !stopped_by_watchpoint;
6464 /* Always stop if the user explicitly requested this thread to
6465 remain stopped. */
6466 if (ecs->event_thread->stop_requested)
6468 random_signal = 1;
6469 infrun_debug_printf ("user-requested stop");
6472 /* For the program's own signals, act according to
6473 the signal handling tables. */
6475 if (random_signal)
6477 /* Signal not for debugging purposes. */
6478 enum gdb_signal stop_signal = ecs->event_thread->stop_signal ();
6480 infrun_debug_printf ("random signal (%s)",
6481 gdb_signal_to_symbol_string (stop_signal));
6483 stopped_by_random_signal = 1;
6485 /* Always stop on signals if we're either just gaining control
6486 of the program, or the user explicitly requested this thread
6487 to remain stopped. */
6488 if (stop_soon != NO_STOP_QUIETLY
6489 || ecs->event_thread->stop_requested
6490 || signal_stop_state (ecs->event_thread->stop_signal ()))
6492 stop_waiting (ecs);
6493 return;
6496 /* Notify observers the signal has "handle print" set. Note we
6497 returned early above if stopping; normal_stop handles the
6498 printing in that case. */
6499 if (signal_print[ecs->event_thread->stop_signal ()])
6501 /* The signal table tells us to print about this signal. */
6502 target_terminal::ours_for_output ();
6503 gdb::observers::signal_received.notify (ecs->event_thread->stop_signal ());
6504 target_terminal::inferior ();
6507 /* Clear the signal if it should not be passed. */
6508 if (signal_program[ecs->event_thread->stop_signal ()] == 0)
6509 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
6511 if (ecs->event_thread->prev_pc == ecs->event_thread->stop_pc ()
6512 && ecs->event_thread->control.trap_expected
6513 && ecs->event_thread->control.step_resume_breakpoint == nullptr)
6515 /* We were just starting a new sequence, attempting to
6516 single-step off of a breakpoint and expecting a SIGTRAP.
6517 Instead this signal arrives. This signal will take us out
6518 of the stepping range so GDB needs to remember to, when
6519 the signal handler returns, resume stepping off that
6520 breakpoint. */
6521 /* To simplify things, "continue" is forced to use the same
6522 code paths as single-step - set a breakpoint at the
6523 signal return address and then, once hit, step off that
6524 breakpoint. */
6525 infrun_debug_printf ("signal arrived while stepping over breakpoint");
6527 insert_hp_step_resume_breakpoint_at_frame (frame);
6528 ecs->event_thread->step_after_step_resume_breakpoint = 1;
6529 /* Reset trap_expected to ensure breakpoints are re-inserted. */
6530 ecs->event_thread->control.trap_expected = 0;
6532 /* If we were nexting/stepping some other thread, switch to
6533 it, so that we don't continue it, losing control. */
6534 if (!switch_back_to_stepped_thread (ecs))
6535 keep_going (ecs);
6536 return;
6539 if (ecs->event_thread->stop_signal () != GDB_SIGNAL_0
6540 && (pc_in_thread_step_range (ecs->event_thread->stop_pc (),
6541 ecs->event_thread)
6542 || ecs->event_thread->control.step_range_end == 1)
6543 && (get_stack_frame_id (frame)
6544 == ecs->event_thread->control.step_stack_frame_id)
6545 && ecs->event_thread->control.step_resume_breakpoint == nullptr)
6547 /* The inferior is about to take a signal that will take it
6548 out of the single step range. Set a breakpoint at the
6549 current PC (which is presumably where the signal handler
6550 will eventually return) and then allow the inferior to
6551 run free.
6553 Note that this is only needed for a signal delivered
6554 while in the single-step range. Nested signals aren't a
6555 problem as they eventually all return. */
6556 infrun_debug_printf ("signal may take us out of single-step range");
6558 clear_step_over_info ();
6559 insert_hp_step_resume_breakpoint_at_frame (frame);
6560 ecs->event_thread->step_after_step_resume_breakpoint = 1;
6561 /* Reset trap_expected to ensure breakpoints are re-inserted. */
6562 ecs->event_thread->control.trap_expected = 0;
6563 keep_going (ecs);
6564 return;
6567 /* Note: step_resume_breakpoint may be non-NULL. This occurs
6568 when either there's a nested signal, or when there's a
6569 pending signal enabled just as the signal handler returns
6570 (leaving the inferior at the step-resume-breakpoint without
6571 actually executing it). Either way continue until the
6572 breakpoint is really hit. */
6574 if (!switch_back_to_stepped_thread (ecs))
6576 infrun_debug_printf ("random signal, keep going");
6578 keep_going (ecs);
6580 return;
6583 process_event_stop_test (ecs);
6586 /* Come here when we've got some debug event / signal we can explain
6587 (IOW, not a random signal), and test whether it should cause a
6588 stop, or whether we should resume the inferior (transparently).
6589 E.g., could be a breakpoint whose condition evaluates false; we
6590 could be still stepping within the line; etc. */
6592 static void
6593 process_event_stop_test (struct execution_control_state *ecs)
6595 struct symtab_and_line stop_pc_sal;
6596 frame_info_ptr frame;
6597 struct gdbarch *gdbarch;
6598 CORE_ADDR jmp_buf_pc;
6599 struct bpstat_what what;
6601 /* Handle cases caused by hitting a breakpoint. */
6603 frame = get_current_frame ();
6604 gdbarch = get_frame_arch (frame);
6606 what = bpstat_what (ecs->event_thread->control.stop_bpstat);
6608 if (what.call_dummy)
6610 stop_stack_dummy = what.call_dummy;
6613 /* A few breakpoint types have callbacks associated (e.g.,
6614 bp_jit_event). Run them now. */
6615 bpstat_run_callbacks (ecs->event_thread->control.stop_bpstat);
6617 /* If we hit an internal event that triggers symbol changes, the
6618 current frame will be invalidated within bpstat_what (e.g., if we
6619 hit an internal solib event). Re-fetch it. */
6620 frame = get_current_frame ();
6621 gdbarch = get_frame_arch (frame);
6623 switch (what.main_action)
6625 case BPSTAT_WHAT_SET_LONGJMP_RESUME:
6626 /* If we hit the breakpoint at longjmp while stepping, we
6627 install a momentary breakpoint at the target of the
6628 jmp_buf. */
6630 infrun_debug_printf ("BPSTAT_WHAT_SET_LONGJMP_RESUME");
6632 ecs->event_thread->stepping_over_breakpoint = 1;
6634 if (what.is_longjmp)
6636 struct value *arg_value;
6638 /* If we set the longjmp breakpoint via a SystemTap probe,
6639 then use it to extract the arguments. The destination PC
6640 is the third argument to the probe. */
6641 arg_value = probe_safe_evaluate_at_pc (frame, 2);
6642 if (arg_value)
6644 jmp_buf_pc = value_as_address (arg_value);
6645 jmp_buf_pc = gdbarch_addr_bits_remove (gdbarch, jmp_buf_pc);
6647 else if (!gdbarch_get_longjmp_target_p (gdbarch)
6648 || !gdbarch_get_longjmp_target (gdbarch,
6649 frame, &jmp_buf_pc))
6651 infrun_debug_printf ("BPSTAT_WHAT_SET_LONGJMP_RESUME "
6652 "(!gdbarch_get_longjmp_target)");
6653 keep_going (ecs);
6654 return;
6657 /* Insert a breakpoint at resume address. */
6658 insert_longjmp_resume_breakpoint (gdbarch, jmp_buf_pc);
6660 else
6661 check_exception_resume (ecs, frame);
6662 keep_going (ecs);
6663 return;
6665 case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
6667 frame_info_ptr init_frame;
6669 /* There are several cases to consider.
6671 1. The initiating frame no longer exists. In this case we
6672 must stop, because the exception or longjmp has gone too
6673 far.
6675 2. The initiating frame exists, and is the same as the
6676 current frame. We stop, because the exception or longjmp
6677 has been caught.
6679 3. The initiating frame exists and is different from the
6680 current frame. This means the exception or longjmp has
6681 been caught beneath the initiating frame, so keep going.
6683 4. longjmp breakpoint has been placed just to protect
6684 against stale dummy frames and user is not interested in
6685 stopping around longjmps. */
6687 infrun_debug_printf ("BPSTAT_WHAT_CLEAR_LONGJMP_RESUME");
6689 gdb_assert (ecs->event_thread->control.exception_resume_breakpoint
6690 != nullptr);
6691 delete_exception_resume_breakpoint (ecs->event_thread);
6693 if (what.is_longjmp)
6695 check_longjmp_breakpoint_for_call_dummy (ecs->event_thread);
6697 if (!frame_id_p (ecs->event_thread->initiating_frame))
6699 /* Case 4. */
6700 keep_going (ecs);
6701 return;
6705 init_frame = frame_find_by_id (ecs->event_thread->initiating_frame);
6707 if (init_frame)
6709 struct frame_id current_id
6710 = get_frame_id (get_current_frame ());
6711 if (current_id == ecs->event_thread->initiating_frame)
6713 /* Case 2. Fall through. */
6715 else
6717 /* Case 3. */
6718 keep_going (ecs);
6719 return;
6723 /* For Cases 1 and 2, remove the step-resume breakpoint, if it
6724 exists. */
6725 delete_step_resume_breakpoint (ecs->event_thread);
6727 end_stepping_range (ecs);
6729 return;
6731 case BPSTAT_WHAT_SINGLE:
6732 infrun_debug_printf ("BPSTAT_WHAT_SINGLE");
6733 ecs->event_thread->stepping_over_breakpoint = 1;
6734 /* Still need to check other stuff, at least the case where we
6735 are stepping and step out of the right range. */
6736 break;
6738 case BPSTAT_WHAT_STEP_RESUME:
6739 infrun_debug_printf ("BPSTAT_WHAT_STEP_RESUME");
6741 delete_step_resume_breakpoint (ecs->event_thread);
6742 if (ecs->event_thread->control.proceed_to_finish
6743 && execution_direction == EXEC_REVERSE)
6745 struct thread_info *tp = ecs->event_thread;
6747 /* We are finishing a function in reverse, and just hit the
6748 step-resume breakpoint at the start address of the
6749 function, and we're almost there -- just need to back up
6750 by one more single-step, which should take us back to the
6751 function call. */
6752 tp->control.step_range_start = tp->control.step_range_end = 1;
6753 keep_going (ecs);
6754 return;
6756 fill_in_stop_func (gdbarch, ecs);
6757 if (ecs->event_thread->stop_pc () == ecs->stop_func_start
6758 && execution_direction == EXEC_REVERSE)
6760 /* We are stepping over a function call in reverse, and just
6761 hit the step-resume breakpoint at the start address of
6762 the function. Go back to single-stepping, which should
6763 take us back to the function call. */
6764 ecs->event_thread->stepping_over_breakpoint = 1;
6765 keep_going (ecs);
6766 return;
6768 break;
6770 case BPSTAT_WHAT_STOP_NOISY:
6771 infrun_debug_printf ("BPSTAT_WHAT_STOP_NOISY");
6772 stop_print_frame = true;
6774 /* Assume the thread stopped for a breakpoint. We'll still check
6775 whether a/the breakpoint is there when the thread is next
6776 resumed. */
6777 ecs->event_thread->stepping_over_breakpoint = 1;
6779 stop_waiting (ecs);
6780 return;
6782 case BPSTAT_WHAT_STOP_SILENT:
6783 infrun_debug_printf ("BPSTAT_WHAT_STOP_SILENT");
6784 stop_print_frame = false;
6786 /* Assume the thread stopped for a breakpoint. We'll still check
6787 whether a/the breakpoint is there when the thread is next
6788 resumed. */
6789 ecs->event_thread->stepping_over_breakpoint = 1;
6790 stop_waiting (ecs);
6791 return;
6793 case BPSTAT_WHAT_HP_STEP_RESUME:
6794 infrun_debug_printf ("BPSTAT_WHAT_HP_STEP_RESUME");
6796 delete_step_resume_breakpoint (ecs->event_thread);
6797 if (ecs->event_thread->step_after_step_resume_breakpoint)
6799 /* Back when the step-resume breakpoint was inserted, we
6800 were trying to single-step off a breakpoint. Go back to
6801 doing that. */
6802 ecs->event_thread->step_after_step_resume_breakpoint = 0;
6803 ecs->event_thread->stepping_over_breakpoint = 1;
6804 keep_going (ecs);
6805 return;
6807 break;
6809 case BPSTAT_WHAT_KEEP_CHECKING:
6810 break;
6813 /* If we stepped a permanent breakpoint and we had a high priority
6814 step-resume breakpoint for the address we stepped, but we didn't
6815 hit it, then we must have stepped into the signal handler. The
6816 step-resume was only necessary to catch the case of _not_
6817 stepping into the handler, so delete it, and fall through to
6818 checking whether the step finished. */
6819 if (ecs->event_thread->stepped_breakpoint)
6821 struct breakpoint *sr_bp
6822 = ecs->event_thread->control.step_resume_breakpoint;
6824 if (sr_bp != nullptr
6825 && sr_bp->loc->permanent
6826 && sr_bp->type == bp_hp_step_resume
6827 && sr_bp->loc->address == ecs->event_thread->prev_pc)
6829 infrun_debug_printf ("stepped permanent breakpoint, stopped in handler");
6830 delete_step_resume_breakpoint (ecs->event_thread);
6831 ecs->event_thread->step_after_step_resume_breakpoint = 0;
6835 /* We come here if we hit a breakpoint but should not stop for it.
6836 Possibly we also were stepping and should stop for that. So fall
6837 through and test for stepping. But, if not stepping, do not
6838 stop. */
6840 /* In all-stop mode, if we're currently stepping but have stopped in
6841 some other thread, we need to switch back to the stepped thread. */
6842 if (switch_back_to_stepped_thread (ecs))
6843 return;
6845 if (ecs->event_thread->control.step_resume_breakpoint)
6847 infrun_debug_printf ("step-resume breakpoint is inserted");
6849 /* Having a step-resume breakpoint overrides anything
6850 else having to do with stepping commands until
6851 that breakpoint is reached. */
6852 keep_going (ecs);
6853 return;
6856 if (ecs->event_thread->control.step_range_end == 0)
6858 infrun_debug_printf ("no stepping, continue");
6859 /* Likewise if we aren't even stepping. */
6860 keep_going (ecs);
6861 return;
6864 /* Re-fetch current thread's frame in case the code above caused
6865 the frame cache to be re-initialized, making our FRAME variable
6866 a dangling pointer. */
6867 frame = get_current_frame ();
6868 gdbarch = get_frame_arch (frame);
6869 fill_in_stop_func (gdbarch, ecs);
6871 /* If stepping through a line, keep going if still within it.
6873 Note that step_range_end is the address of the first instruction
6874 beyond the step range, and NOT the address of the last instruction
6875 within it!
6877 Note also that during reverse execution, we may be stepping
6878 through a function epilogue and therefore must detect when
6879 the current-frame changes in the middle of a line. */
6881 if (pc_in_thread_step_range (ecs->event_thread->stop_pc (),
6882 ecs->event_thread)
6883 && (execution_direction != EXEC_REVERSE
6884 || get_frame_id (frame) == ecs->event_thread->control.step_frame_id))
6886 infrun_debug_printf
6887 ("stepping inside range [%s-%s]",
6888 paddress (gdbarch, ecs->event_thread->control.step_range_start),
6889 paddress (gdbarch, ecs->event_thread->control.step_range_end));
6891 /* Tentatively re-enable range stepping; `resume' disables it if
6892 necessary (e.g., if we're stepping over a breakpoint or we
6893 have software watchpoints). */
6894 ecs->event_thread->control.may_range_step = 1;
6896 /* When stepping backward, stop at beginning of line range
6897 (unless it's the function entry point, in which case
6898 keep going back to the call point). */
6899 CORE_ADDR stop_pc = ecs->event_thread->stop_pc ();
6900 if (stop_pc == ecs->event_thread->control.step_range_start
6901 && stop_pc != ecs->stop_func_start
6902 && execution_direction == EXEC_REVERSE)
6903 end_stepping_range (ecs);
6904 else
6905 keep_going (ecs);
6907 return;
6910 /* We stepped out of the stepping range. */
6912 /* If we are stepping at the source level and entered the runtime
6913 loader dynamic symbol resolution code...
6915 EXEC_FORWARD: we keep on single stepping until we exit the run
6916 time loader code and reach the callee's address.
6918 EXEC_REVERSE: we've already executed the callee (backward), and
6919 the runtime loader code is handled just like any other
6920 undebuggable function call. Now we need only keep stepping
6921 backward through the trampoline code, and that's handled further
6922 down, so there is nothing for us to do here. */
6924 if (execution_direction != EXEC_REVERSE
6925 && ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6926 && in_solib_dynsym_resolve_code (ecs->event_thread->stop_pc ())
6927 && (ecs->event_thread->control.step_start_function == nullptr
6928 || !in_solib_dynsym_resolve_code (
6929 ecs->event_thread->control.step_start_function->value_block ()
6930 ->entry_pc ())))
6932 CORE_ADDR pc_after_resolver =
6933 gdbarch_skip_solib_resolver (gdbarch, ecs->event_thread->stop_pc ());
6935 infrun_debug_printf ("stepped into dynsym resolve code");
6937 if (pc_after_resolver)
6939 /* Set up a step-resume breakpoint at the address
6940 indicated by SKIP_SOLIB_RESOLVER. */
6941 symtab_and_line sr_sal;
6942 sr_sal.pc = pc_after_resolver;
6943 sr_sal.pspace = get_frame_program_space (frame);
6945 insert_step_resume_breakpoint_at_sal (gdbarch,
6946 sr_sal, null_frame_id);
6949 keep_going (ecs);
6950 return;
6953 /* Step through an indirect branch thunk. */
6954 if (ecs->event_thread->control.step_over_calls != STEP_OVER_NONE
6955 && gdbarch_in_indirect_branch_thunk (gdbarch,
6956 ecs->event_thread->stop_pc ()))
6958 infrun_debug_printf ("stepped into indirect branch thunk");
6959 keep_going (ecs);
6960 return;
6963 if (ecs->event_thread->control.step_range_end != 1
6964 && (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6965 || ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6966 && get_frame_type (frame) == SIGTRAMP_FRAME)
6968 infrun_debug_printf ("stepped into signal trampoline");
6969 /* The inferior, while doing a "step" or "next", has ended up in
6970 a signal trampoline (either by a signal being delivered or by
6971 the signal handler returning). Just single-step until the
6972 inferior leaves the trampoline (either by calling the handler
6973 or returning). */
6974 keep_going (ecs);
6975 return;
6978 /* If we're in the return path from a shared library trampoline,
6979 we want to proceed through the trampoline when stepping. */
6980 /* macro/2012-04-25: This needs to come before the subroutine
6981 call check below as on some targets return trampolines look
6982 like subroutine calls (MIPS16 return thunks). */
6983 if (gdbarch_in_solib_return_trampoline (gdbarch,
6984 ecs->event_thread->stop_pc (),
6985 ecs->stop_func_name)
6986 && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
6988 /* Determine where this trampoline returns. */
6989 CORE_ADDR stop_pc = ecs->event_thread->stop_pc ();
6990 CORE_ADDR real_stop_pc
6991 = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
6993 infrun_debug_printf ("stepped into solib return tramp");
6995 /* Only proceed through if we know where it's going. */
6996 if (real_stop_pc)
6998 /* And put the step-breakpoint there and go until there. */
6999 symtab_and_line sr_sal;
7000 sr_sal.pc = real_stop_pc;
7001 sr_sal.section = find_pc_overlay (sr_sal.pc);
7002 sr_sal.pspace = get_frame_program_space (frame);
7004 /* Do not specify what the fp should be when we stop since
7005 on some machines the prologue is where the new fp value
7006 is established. */
7007 insert_step_resume_breakpoint_at_sal (gdbarch,
7008 sr_sal, null_frame_id);
7010 /* Restart without fiddling with the step ranges or
7011 other state. */
7012 keep_going (ecs);
7013 return;
7017 /* Check for subroutine calls. The check for the current frame
7018 equalling the step ID is not necessary - the check of the
7019 previous frame's ID is sufficient - but it is a common case and
7020 cheaper than checking the previous frame's ID.
7022 NOTE: frame_id::operator== will never report two invalid frame IDs as
7023 being equal, so to get into this block, both the current and
7024 previous frame must have valid frame IDs. */
7025 /* The outer_frame_id check is a heuristic to detect stepping
7026 through startup code. If we step over an instruction which
7027 sets the stack pointer from an invalid value to a valid value,
7028 we may detect that as a subroutine call from the mythical
7029 "outermost" function. This could be fixed by marking
7030 outermost frames as !stack_p,code_p,special_p. Then the
7031 initial outermost frame, before sp was valid, would
7032 have code_addr == &_start. See the comment in frame_id::operator==
7033 for more. */
7034 if ((get_stack_frame_id (frame)
7035 != ecs->event_thread->control.step_stack_frame_id)
7036 && ((frame_unwind_caller_id (get_current_frame ())
7037 == ecs->event_thread->control.step_stack_frame_id)
7038 && ((ecs->event_thread->control.step_stack_frame_id
7039 != outer_frame_id)
7040 || (ecs->event_thread->control.step_start_function
7041 != find_pc_function (ecs->event_thread->stop_pc ())))))
7043 CORE_ADDR stop_pc = ecs->event_thread->stop_pc ();
7044 CORE_ADDR real_stop_pc;
7046 infrun_debug_printf ("stepped into subroutine");
7048 if (ecs->event_thread->control.step_over_calls == STEP_OVER_NONE)
7050 /* I presume that step_over_calls is only 0 when we're
7051 supposed to be stepping at the assembly language level
7052 ("stepi"). Just stop. */
7053 /* And this works the same backward as frontward. MVS */
7054 end_stepping_range (ecs);
7055 return;
7058 /* Reverse stepping through solib trampolines. */
7060 if (execution_direction == EXEC_REVERSE
7061 && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE
7062 && (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
7063 || (ecs->stop_func_start == 0
7064 && in_solib_dynsym_resolve_code (stop_pc))))
7066 /* Any solib trampoline code can be handled in reverse
7067 by simply continuing to single-step. We have already
7068 executed the solib function (backwards), and a few
7069 steps will take us back through the trampoline to the
7070 caller. */
7071 keep_going (ecs);
7072 return;
7075 if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
7077 /* We're doing a "next".
7079 Normal (forward) execution: set a breakpoint at the
7080 callee's return address (the address at which the caller
7081 will resume).
7083 Reverse (backward) execution. set the step-resume
7084 breakpoint at the start of the function that we just
7085 stepped into (backwards), and continue to there. When we
7086 get there, we'll need to single-step back to the caller. */
7088 if (execution_direction == EXEC_REVERSE)
7090 /* If we're already at the start of the function, we've either
7091 just stepped backward into a single instruction function,
7092 or stepped back out of a signal handler to the first instruction
7093 of the function. Just keep going, which will single-step back
7094 to the caller. */
7095 if (ecs->stop_func_start != stop_pc && ecs->stop_func_start != 0)
7097 /* Normal function call return (static or dynamic). */
7098 symtab_and_line sr_sal;
7099 sr_sal.pc = ecs->stop_func_start;
7100 sr_sal.pspace = get_frame_program_space (frame);
7101 insert_step_resume_breakpoint_at_sal (gdbarch,
7102 sr_sal, get_stack_frame_id (frame));
7105 else
7106 insert_step_resume_breakpoint_at_caller (frame);
7108 keep_going (ecs);
7109 return;
7112 /* If we are in a function call trampoline (a stub between the
7113 calling routine and the real function), locate the real
7114 function. That's what tells us (a) whether we want to step
7115 into it at all, and (b) what prologue we want to run to the
7116 end of, if we do step into it. */
7117 real_stop_pc = skip_language_trampoline (frame, stop_pc);
7118 if (real_stop_pc == 0)
7119 real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
7120 if (real_stop_pc != 0)
7121 ecs->stop_func_start = real_stop_pc;
7123 if (real_stop_pc != 0 && in_solib_dynsym_resolve_code (real_stop_pc))
7125 symtab_and_line sr_sal;
7126 sr_sal.pc = ecs->stop_func_start;
7127 sr_sal.pspace = get_frame_program_space (frame);
7129 insert_step_resume_breakpoint_at_sal (gdbarch,
7130 sr_sal, null_frame_id);
7131 keep_going (ecs);
7132 return;
7135 /* If we have line number information for the function we are
7136 thinking of stepping into and the function isn't on the skip
7137 list, step into it.
7139 If there are several symtabs at that PC (e.g. with include
7140 files), just want to know whether *any* of them have line
7141 numbers. find_pc_line handles this. */
7143 struct symtab_and_line tmp_sal;
7145 tmp_sal = find_pc_line (ecs->stop_func_start, 0);
7146 if (tmp_sal.line != 0
7147 && !function_name_is_marked_for_skip (ecs->stop_func_name,
7148 tmp_sal)
7149 && !inline_frame_is_marked_for_skip (true, ecs->event_thread))
7151 if (execution_direction == EXEC_REVERSE)
7152 handle_step_into_function_backward (gdbarch, ecs);
7153 else
7154 handle_step_into_function (gdbarch, ecs);
7155 return;
7159 /* If we have no line number and the step-stop-if-no-debug is
7160 set, we stop the step so that the user has a chance to switch
7161 in assembly mode. */
7162 if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
7163 && step_stop_if_no_debug)
7165 end_stepping_range (ecs);
7166 return;
7169 if (execution_direction == EXEC_REVERSE)
7171 /* If we're already at the start of the function, we've either just
7172 stepped backward into a single instruction function without line
7173 number info, or stepped back out of a signal handler to the first
7174 instruction of the function without line number info. Just keep
7175 going, which will single-step back to the caller. */
7176 if (ecs->stop_func_start != stop_pc)
7178 /* Set a breakpoint at callee's start address.
7179 From there we can step once and be back in the caller. */
7180 symtab_and_line sr_sal;
7181 sr_sal.pc = ecs->stop_func_start;
7182 sr_sal.pspace = get_frame_program_space (frame);
7183 insert_step_resume_breakpoint_at_sal (gdbarch,
7184 sr_sal, null_frame_id);
7187 else
7188 /* Set a breakpoint at callee's return address (the address
7189 at which the caller will resume). */
7190 insert_step_resume_breakpoint_at_caller (frame);
7192 keep_going (ecs);
7193 return;
7196 /* Reverse stepping through solib trampolines. */
7198 if (execution_direction == EXEC_REVERSE
7199 && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
7201 CORE_ADDR stop_pc = ecs->event_thread->stop_pc ();
7203 if (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
7204 || (ecs->stop_func_start == 0
7205 && in_solib_dynsym_resolve_code (stop_pc)))
7207 /* Any solib trampoline code can be handled in reverse
7208 by simply continuing to single-step. We have already
7209 executed the solib function (backwards), and a few
7210 steps will take us back through the trampoline to the
7211 caller. */
7212 keep_going (ecs);
7213 return;
7215 else if (in_solib_dynsym_resolve_code (stop_pc))
7217 /* Stepped backward into the solib dynsym resolver.
7218 Set a breakpoint at its start and continue, then
7219 one more step will take us out. */
7220 symtab_and_line sr_sal;
7221 sr_sal.pc = ecs->stop_func_start;
7222 sr_sal.pspace = get_frame_program_space (frame);
7223 insert_step_resume_breakpoint_at_sal (gdbarch,
7224 sr_sal, null_frame_id);
7225 keep_going (ecs);
7226 return;
7230 /* This always returns the sal for the inner-most frame when we are in a
7231 stack of inlined frames, even if GDB actually believes that it is in a
7232 more outer frame. This is checked for below by calls to
7233 inline_skipped_frames. */
7234 stop_pc_sal = find_pc_line (ecs->event_thread->stop_pc (), 0);
7236 /* NOTE: tausq/2004-05-24: This if block used to be done before all
7237 the trampoline processing logic, however, there are some trampolines
7238 that have no names, so we should do trampoline handling first. */
7239 if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
7240 && ecs->stop_func_name == nullptr
7241 && stop_pc_sal.line == 0)
7243 infrun_debug_printf ("stepped into undebuggable function");
7245 /* The inferior just stepped into, or returned to, an
7246 undebuggable function (where there is no debugging information
7247 and no line number corresponding to the address where the
7248 inferior stopped). Since we want to skip this kind of code,
7249 we keep going until the inferior returns from this
7250 function - unless the user has asked us not to (via
7251 set step-mode) or we no longer know how to get back
7252 to the call site. */
7253 if (step_stop_if_no_debug
7254 || !frame_id_p (frame_unwind_caller_id (frame)))
7256 /* If we have no line number and the step-stop-if-no-debug
7257 is set, we stop the step so that the user has a chance to
7258 switch in assembly mode. */
7259 end_stepping_range (ecs);
7260 return;
7262 else
7264 /* Set a breakpoint at callee's return address (the address
7265 at which the caller will resume). */
7266 insert_step_resume_breakpoint_at_caller (frame);
7267 keep_going (ecs);
7268 return;
7272 if (ecs->event_thread->control.step_range_end == 1)
7274 /* It is stepi or nexti. We always want to stop stepping after
7275 one instruction. */
7276 infrun_debug_printf ("stepi/nexti");
7277 end_stepping_range (ecs);
7278 return;
7281 if (stop_pc_sal.line == 0)
7283 /* We have no line number information. That means to stop
7284 stepping (does this always happen right after one instruction,
7285 when we do "s" in a function with no line numbers,
7286 or can this happen as a result of a return or longjmp?). */
7287 infrun_debug_printf ("line number info");
7288 end_stepping_range (ecs);
7289 return;
7292 /* Look for "calls" to inlined functions, part one. If the inline
7293 frame machinery detected some skipped call sites, we have entered
7294 a new inline function. */
7296 if ((get_frame_id (get_current_frame ())
7297 == ecs->event_thread->control.step_frame_id)
7298 && inline_skipped_frames (ecs->event_thread))
7300 infrun_debug_printf ("stepped into inlined function");
7302 symtab_and_line call_sal = find_frame_sal (get_current_frame ());
7304 if (ecs->event_thread->control.step_over_calls != STEP_OVER_ALL)
7306 /* For "step", we're going to stop. But if the call site
7307 for this inlined function is on the same source line as
7308 we were previously stepping, go down into the function
7309 first. Otherwise stop at the call site. */
7311 if (call_sal.line == ecs->event_thread->current_line
7312 && call_sal.symtab == ecs->event_thread->current_symtab)
7314 step_into_inline_frame (ecs->event_thread);
7315 if (inline_frame_is_marked_for_skip (false, ecs->event_thread))
7317 keep_going (ecs);
7318 return;
7322 end_stepping_range (ecs);
7323 return;
7325 else
7327 /* For "next", we should stop at the call site if it is on a
7328 different source line. Otherwise continue through the
7329 inlined function. */
7330 if (call_sal.line == ecs->event_thread->current_line
7331 && call_sal.symtab == ecs->event_thread->current_symtab)
7332 keep_going (ecs);
7333 else
7334 end_stepping_range (ecs);
7335 return;
7339 /* Look for "calls" to inlined functions, part two. If we are still
7340 in the same real function we were stepping through, but we have
7341 to go further up to find the exact frame ID, we are stepping
7342 through a more inlined call beyond its call site. */
7344 if (get_frame_type (get_current_frame ()) == INLINE_FRAME
7345 && (get_frame_id (get_current_frame ())
7346 != ecs->event_thread->control.step_frame_id)
7347 && stepped_in_from (get_current_frame (),
7348 ecs->event_thread->control.step_frame_id))
7350 infrun_debug_printf ("stepping through inlined function");
7352 if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL
7353 || inline_frame_is_marked_for_skip (false, ecs->event_thread))
7354 keep_going (ecs);
7355 else
7356 end_stepping_range (ecs);
7357 return;
7360 bool refresh_step_info = true;
7361 if ((ecs->event_thread->stop_pc () == stop_pc_sal.pc)
7362 && (ecs->event_thread->current_line != stop_pc_sal.line
7363 || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
7365 /* We are at a different line. */
7367 if (stop_pc_sal.is_stmt)
7369 /* We are at the start of a statement.
7371 So stop. Note that we don't stop if we step into the middle of a
7372 statement. That is said to make things like for (;;) statements
7373 work better. */
7374 infrun_debug_printf ("stepped to a different line");
7375 end_stepping_range (ecs);
7376 return;
7378 else if (get_frame_id (get_current_frame ())
7379 == ecs->event_thread->control.step_frame_id)
7381 /* We are not at the start of a statement, and we have not changed
7382 frame.
7384 We ignore this line table entry, and continue stepping forward,
7385 looking for a better place to stop. */
7386 refresh_step_info = false;
7387 infrun_debug_printf ("stepped to a different line, but "
7388 "it's not the start of a statement");
7390 else
7392 /* We are not the start of a statement, and we have changed frame.
7394 We ignore this line table entry, and continue stepping forward,
7395 looking for a better place to stop. Keep refresh_step_info at
7396 true to note that the frame has changed, but ignore the line
7397 number to make sure we don't ignore a subsequent entry with the
7398 same line number. */
7399 stop_pc_sal.line = 0;
7400 infrun_debug_printf ("stepped to a different frame, but "
7401 "it's not the start of a statement");
7405 /* We aren't done stepping.
7407 Optimize by setting the stepping range to the line.
7408 (We might not be in the original line, but if we entered a
7409 new line in mid-statement, we continue stepping. This makes
7410 things like for(;;) statements work better.)
7412 If we entered a SAL that indicates a non-statement line table entry,
7413 then we update the stepping range, but we don't update the step info,
7414 which includes things like the line number we are stepping away from.
7415 This means we will stop when we find a line table entry that is marked
7416 as is-statement, even if it matches the non-statement one we just
7417 stepped into. */
7419 ecs->event_thread->control.step_range_start = stop_pc_sal.pc;
7420 ecs->event_thread->control.step_range_end = stop_pc_sal.end;
7421 ecs->event_thread->control.may_range_step = 1;
7422 infrun_debug_printf
7423 ("updated step range, start = %s, end = %s, may_range_step = %d",
7424 paddress (gdbarch, ecs->event_thread->control.step_range_start),
7425 paddress (gdbarch, ecs->event_thread->control.step_range_end),
7426 ecs->event_thread->control.may_range_step);
7427 if (refresh_step_info)
7428 set_step_info (ecs->event_thread, frame, stop_pc_sal);
7430 infrun_debug_printf ("keep going");
7431 keep_going (ecs);
7434 static bool restart_stepped_thread (process_stratum_target *resume_target,
7435 ptid_t resume_ptid);
7437 /* In all-stop mode, if we're currently stepping but have stopped in
7438 some other thread, we may need to switch back to the stepped
7439 thread. Returns true we set the inferior running, false if we left
7440 it stopped (and the event needs further processing). */
7442 static bool
7443 switch_back_to_stepped_thread (struct execution_control_state *ecs)
7445 if (!target_is_non_stop_p ())
7447 /* If any thread is blocked on some internal breakpoint, and we
7448 simply need to step over that breakpoint to get it going
7449 again, do that first. */
7451 /* However, if we see an event for the stepping thread, then we
7452 know all other threads have been moved past their breakpoints
7453 already. Let the caller check whether the step is finished,
7454 etc., before deciding to move it past a breakpoint. */
7455 if (ecs->event_thread->control.step_range_end != 0)
7456 return false;
7458 /* Check if the current thread is blocked on an incomplete
7459 step-over, interrupted by a random signal. */
7460 if (ecs->event_thread->control.trap_expected
7461 && ecs->event_thread->stop_signal () != GDB_SIGNAL_TRAP)
7463 infrun_debug_printf
7464 ("need to finish step-over of [%s]",
7465 ecs->event_thread->ptid.to_string ().c_str ());
7466 keep_going (ecs);
7467 return true;
7470 /* Check if the current thread is blocked by a single-step
7471 breakpoint of another thread. */
7472 if (ecs->hit_singlestep_breakpoint)
7474 infrun_debug_printf ("need to step [%s] over single-step breakpoint",
7475 ecs->ptid.to_string ().c_str ());
7476 keep_going (ecs);
7477 return true;
7480 /* If this thread needs yet another step-over (e.g., stepping
7481 through a delay slot), do it first before moving on to
7482 another thread. */
7483 if (thread_still_needs_step_over (ecs->event_thread))
7485 infrun_debug_printf
7486 ("thread [%s] still needs step-over",
7487 ecs->event_thread->ptid.to_string ().c_str ());
7488 keep_going (ecs);
7489 return true;
7492 /* If scheduler locking applies even if not stepping, there's no
7493 need to walk over threads. Above we've checked whether the
7494 current thread is stepping. If some other thread not the
7495 event thread is stepping, then it must be that scheduler
7496 locking is not in effect. */
7497 if (schedlock_applies (ecs->event_thread))
7498 return false;
7500 /* Otherwise, we no longer expect a trap in the current thread.
7501 Clear the trap_expected flag before switching back -- this is
7502 what keep_going does as well, if we call it. */
7503 ecs->event_thread->control.trap_expected = 0;
7505 /* Likewise, clear the signal if it should not be passed. */
7506 if (!signal_program[ecs->event_thread->stop_signal ()])
7507 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
7509 if (restart_stepped_thread (ecs->target, ecs->ptid))
7511 prepare_to_wait (ecs);
7512 return true;
7515 switch_to_thread (ecs->event_thread);
7518 return false;
7521 /* Look for the thread that was stepping, and resume it.
7522 RESUME_TARGET / RESUME_PTID indicate the set of threads the caller
7523 is resuming. Return true if a thread was started, false
7524 otherwise. */
7526 static bool
7527 restart_stepped_thread (process_stratum_target *resume_target,
7528 ptid_t resume_ptid)
7530 /* Do all pending step-overs before actually proceeding with
7531 step/next/etc. */
7532 if (start_step_over ())
7533 return true;
7535 for (thread_info *tp : all_threads_safe ())
7537 if (tp->state == THREAD_EXITED)
7538 continue;
7540 if (tp->has_pending_waitstatus ())
7541 continue;
7543 /* Ignore threads of processes the caller is not
7544 resuming. */
7545 if (!sched_multi
7546 && (tp->inf->process_target () != resume_target
7547 || tp->inf->pid != resume_ptid.pid ()))
7548 continue;
7550 if (tp->control.trap_expected)
7552 infrun_debug_printf ("switching back to stepped thread (step-over)");
7554 if (keep_going_stepped_thread (tp))
7555 return true;
7559 for (thread_info *tp : all_threads_safe ())
7561 if (tp->state == THREAD_EXITED)
7562 continue;
7564 if (tp->has_pending_waitstatus ())
7565 continue;
7567 /* Ignore threads of processes the caller is not
7568 resuming. */
7569 if (!sched_multi
7570 && (tp->inf->process_target () != resume_target
7571 || tp->inf->pid != resume_ptid.pid ()))
7572 continue;
7574 /* Did we find the stepping thread? */
7575 if (tp->control.step_range_end)
7577 infrun_debug_printf ("switching back to stepped thread (stepping)");
7579 if (keep_going_stepped_thread (tp))
7580 return true;
7584 return false;
7587 /* See infrun.h. */
7589 void
7590 restart_after_all_stop_detach (process_stratum_target *proc_target)
7592 /* Note we don't check target_is_non_stop_p() here, because the
7593 current inferior may no longer have a process_stratum target
7594 pushed, as we just detached. */
7596 /* See if we have a THREAD_RUNNING thread that need to be
7597 re-resumed. If we have any thread that is already executing,
7598 then we don't need to resume the target -- it is already been
7599 resumed. With the remote target (in all-stop), it's even
7600 impossible to issue another resumption if the target is already
7601 resumed, until the target reports a stop. */
7602 for (thread_info *thr : all_threads (proc_target))
7604 if (thr->state != THREAD_RUNNING)
7605 continue;
7607 /* If we have any thread that is already executing, then we
7608 don't need to resume the target -- it is already been
7609 resumed. */
7610 if (thr->executing ())
7611 return;
7613 /* If we have a pending event to process, skip resuming the
7614 target and go straight to processing it. */
7615 if (thr->resumed () && thr->has_pending_waitstatus ())
7616 return;
7619 /* Alright, we need to re-resume the target. If a thread was
7620 stepping, we need to restart it stepping. */
7621 if (restart_stepped_thread (proc_target, minus_one_ptid))
7622 return;
7624 /* Otherwise, find the first THREAD_RUNNING thread and resume
7625 it. */
7626 for (thread_info *thr : all_threads (proc_target))
7628 if (thr->state != THREAD_RUNNING)
7629 continue;
7631 execution_control_state ecs (thr);
7632 switch_to_thread (thr);
7633 keep_going (&ecs);
7634 return;
7638 /* Set a previously stepped thread back to stepping. Returns true on
7639 success, false if the resume is not possible (e.g., the thread
7640 vanished). */
7642 static bool
7643 keep_going_stepped_thread (struct thread_info *tp)
7645 frame_info_ptr frame;
7647 /* If the stepping thread exited, then don't try to switch back and
7648 resume it, which could fail in several different ways depending
7649 on the target. Instead, just keep going.
7651 We can find a stepping dead thread in the thread list in two
7652 cases:
7654 - The target supports thread exit events, and when the target
7655 tries to delete the thread from the thread list, inferior_ptid
7656 pointed at the exiting thread. In such case, calling
7657 delete_thread does not really remove the thread from the list;
7658 instead, the thread is left listed, with 'exited' state.
7660 - The target's debug interface does not support thread exit
7661 events, and so we have no idea whatsoever if the previously
7662 stepping thread is still alive. For that reason, we need to
7663 synchronously query the target now. */
7665 if (tp->state == THREAD_EXITED || !target_thread_alive (tp->ptid))
7667 infrun_debug_printf ("not resuming previously stepped thread, it has "
7668 "vanished");
7670 delete_thread (tp);
7671 return false;
7674 infrun_debug_printf ("resuming previously stepped thread");
7676 execution_control_state ecs (tp);
7677 switch_to_thread (tp);
7679 tp->set_stop_pc (regcache_read_pc (get_thread_regcache (tp)));
7680 frame = get_current_frame ();
7682 /* If the PC of the thread we were trying to single-step has
7683 changed, then that thread has trapped or been signaled, but the
7684 event has not been reported to GDB yet. Re-poll the target
7685 looking for this particular thread's event (i.e. temporarily
7686 enable schedlock) by:
7688 - setting a break at the current PC
7689 - resuming that particular thread, only (by setting trap
7690 expected)
7692 This prevents us continuously moving the single-step breakpoint
7693 forward, one instruction at a time, overstepping. */
7695 if (tp->stop_pc () != tp->prev_pc)
7697 ptid_t resume_ptid;
7699 infrun_debug_printf ("expected thread advanced also (%s -> %s)",
7700 paddress (target_gdbarch (), tp->prev_pc),
7701 paddress (target_gdbarch (), tp->stop_pc ()));
7703 /* Clear the info of the previous step-over, as it's no longer
7704 valid (if the thread was trying to step over a breakpoint, it
7705 has already succeeded). It's what keep_going would do too,
7706 if we called it. Do this before trying to insert the sss
7707 breakpoint, otherwise if we were previously trying to step
7708 over this exact address in another thread, the breakpoint is
7709 skipped. */
7710 clear_step_over_info ();
7711 tp->control.trap_expected = 0;
7713 insert_single_step_breakpoint (get_frame_arch (frame),
7714 get_frame_address_space (frame),
7715 tp->stop_pc ());
7717 tp->set_resumed (true);
7718 resume_ptid = internal_resume_ptid (tp->control.stepping_command);
7719 do_target_resume (resume_ptid, false, GDB_SIGNAL_0);
7721 else
7723 infrun_debug_printf ("expected thread still hasn't advanced");
7725 keep_going_pass_signal (&ecs);
7728 return true;
7731 /* Is thread TP in the middle of (software or hardware)
7732 single-stepping? (Note the result of this function must never be
7733 passed directly as target_resume's STEP parameter.) */
7735 static bool
7736 currently_stepping (struct thread_info *tp)
7738 return ((tp->control.step_range_end
7739 && tp->control.step_resume_breakpoint == nullptr)
7740 || tp->control.trap_expected
7741 || tp->stepped_breakpoint
7742 || bpstat_should_step ());
7745 /* Inferior has stepped into a subroutine call with source code that
7746 we should not step over. Do step to the first line of code in
7747 it. */
7749 static void
7750 handle_step_into_function (struct gdbarch *gdbarch,
7751 struct execution_control_state *ecs)
7753 fill_in_stop_func (gdbarch, ecs);
7755 compunit_symtab *cust
7756 = find_pc_compunit_symtab (ecs->event_thread->stop_pc ());
7757 if (cust != nullptr && cust->language () != language_asm)
7758 ecs->stop_func_start
7759 = gdbarch_skip_prologue_noexcept (gdbarch, ecs->stop_func_start);
7761 symtab_and_line stop_func_sal = find_pc_line (ecs->stop_func_start, 0);
7762 /* Use the step_resume_break to step until the end of the prologue,
7763 even if that involves jumps (as it seems to on the vax under
7764 4.2). */
7765 /* If the prologue ends in the middle of a source line, continue to
7766 the end of that source line (if it is still within the function).
7767 Otherwise, just go to end of prologue. */
7768 if (stop_func_sal.end
7769 && stop_func_sal.pc != ecs->stop_func_start
7770 && stop_func_sal.end < ecs->stop_func_end)
7771 ecs->stop_func_start = stop_func_sal.end;
7773 /* Architectures which require breakpoint adjustment might not be able
7774 to place a breakpoint at the computed address. If so, the test
7775 ``ecs->stop_func_start == stop_pc'' will never succeed. Adjust
7776 ecs->stop_func_start to an address at which a breakpoint may be
7777 legitimately placed.
7779 Note: kevinb/2004-01-19: On FR-V, if this adjustment is not
7780 made, GDB will enter an infinite loop when stepping through
7781 optimized code consisting of VLIW instructions which contain
7782 subinstructions corresponding to different source lines. On
7783 FR-V, it's not permitted to place a breakpoint on any but the
7784 first subinstruction of a VLIW instruction. When a breakpoint is
7785 set, GDB will adjust the breakpoint address to the beginning of
7786 the VLIW instruction. Thus, we need to make the corresponding
7787 adjustment here when computing the stop address. */
7789 if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7791 ecs->stop_func_start
7792 = gdbarch_adjust_breakpoint_address (gdbarch,
7793 ecs->stop_func_start);
7796 if (ecs->stop_func_start == ecs->event_thread->stop_pc ())
7798 /* We are already there: stop now. */
7799 end_stepping_range (ecs);
7800 return;
7802 else
7804 /* Put the step-breakpoint there and go until there. */
7805 symtab_and_line sr_sal;
7806 sr_sal.pc = ecs->stop_func_start;
7807 sr_sal.section = find_pc_overlay (ecs->stop_func_start);
7808 sr_sal.pspace = get_frame_program_space (get_current_frame ());
7810 /* Do not specify what the fp should be when we stop since on
7811 some machines the prologue is where the new fp value is
7812 established. */
7813 insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal, null_frame_id);
7815 /* And make sure stepping stops right away then. */
7816 ecs->event_thread->control.step_range_end
7817 = ecs->event_thread->control.step_range_start;
7819 keep_going (ecs);
7822 /* Inferior has stepped backward into a subroutine call with source
7823 code that we should not step over. Do step to the beginning of the
7824 last line of code in it. */
7826 static void
7827 handle_step_into_function_backward (struct gdbarch *gdbarch,
7828 struct execution_control_state *ecs)
7830 struct compunit_symtab *cust;
7831 struct symtab_and_line stop_func_sal;
7833 fill_in_stop_func (gdbarch, ecs);
7835 cust = find_pc_compunit_symtab (ecs->event_thread->stop_pc ());
7836 if (cust != nullptr && cust->language () != language_asm)
7837 ecs->stop_func_start
7838 = gdbarch_skip_prologue_noexcept (gdbarch, ecs->stop_func_start);
7840 stop_func_sal = find_pc_line (ecs->event_thread->stop_pc (), 0);
7842 /* OK, we're just going to keep stepping here. */
7843 if (stop_func_sal.pc == ecs->event_thread->stop_pc ())
7845 /* We're there already. Just stop stepping now. */
7846 end_stepping_range (ecs);
7848 else
7850 /* Else just reset the step range and keep going.
7851 No step-resume breakpoint, they don't work for
7852 epilogues, which can have multiple entry paths. */
7853 ecs->event_thread->control.step_range_start = stop_func_sal.pc;
7854 ecs->event_thread->control.step_range_end = stop_func_sal.end;
7855 keep_going (ecs);
7857 return;
7860 /* Insert a "step-resume breakpoint" at SR_SAL with frame ID SR_ID.
7861 This is used to both functions and to skip over code. */
7863 static void
7864 insert_step_resume_breakpoint_at_sal_1 (struct gdbarch *gdbarch,
7865 struct symtab_and_line sr_sal,
7866 struct frame_id sr_id,
7867 enum bptype sr_type)
7869 /* There should never be more than one step-resume or longjmp-resume
7870 breakpoint per thread, so we should never be setting a new
7871 step_resume_breakpoint when one is already active. */
7872 gdb_assert (inferior_thread ()->control.step_resume_breakpoint == nullptr);
7873 gdb_assert (sr_type == bp_step_resume || sr_type == bp_hp_step_resume);
7875 infrun_debug_printf ("inserting step-resume breakpoint at %s",
7876 paddress (gdbarch, sr_sal.pc));
7878 inferior_thread ()->control.step_resume_breakpoint
7879 = set_momentary_breakpoint (gdbarch, sr_sal, sr_id, sr_type).release ();
7882 void
7883 insert_step_resume_breakpoint_at_sal (struct gdbarch *gdbarch,
7884 struct symtab_and_line sr_sal,
7885 struct frame_id sr_id)
7887 insert_step_resume_breakpoint_at_sal_1 (gdbarch,
7888 sr_sal, sr_id,
7889 bp_step_resume);
7892 /* Insert a "high-priority step-resume breakpoint" at RETURN_FRAME.pc.
7893 This is used to skip a potential signal handler.
7895 This is called with the interrupted function's frame. The signal
7896 handler, when it returns, will resume the interrupted function at
7897 RETURN_FRAME.pc. */
7899 static void
7900 insert_hp_step_resume_breakpoint_at_frame (frame_info_ptr return_frame)
7902 gdb_assert (return_frame != nullptr);
7904 struct gdbarch *gdbarch = get_frame_arch (return_frame);
7906 symtab_and_line sr_sal;
7907 sr_sal.pc = gdbarch_addr_bits_remove (gdbarch, get_frame_pc (return_frame));
7908 sr_sal.section = find_pc_overlay (sr_sal.pc);
7909 sr_sal.pspace = get_frame_program_space (return_frame);
7911 insert_step_resume_breakpoint_at_sal_1 (gdbarch, sr_sal,
7912 get_stack_frame_id (return_frame),
7913 bp_hp_step_resume);
7916 /* Insert a "step-resume breakpoint" at the previous frame's PC. This
7917 is used to skip a function after stepping into it (for "next" or if
7918 the called function has no debugging information).
7920 The current function has almost always been reached by single
7921 stepping a call or return instruction. NEXT_FRAME belongs to the
7922 current function, and the breakpoint will be set at the caller's
7923 resume address.
7925 This is a separate function rather than reusing
7926 insert_hp_step_resume_breakpoint_at_frame in order to avoid
7927 get_prev_frame, which may stop prematurely (see the implementation
7928 of frame_unwind_caller_id for an example). */
7930 static void
7931 insert_step_resume_breakpoint_at_caller (frame_info_ptr next_frame)
7933 /* We shouldn't have gotten here if we don't know where the call site
7934 is. */
7935 gdb_assert (frame_id_p (frame_unwind_caller_id (next_frame)));
7937 struct gdbarch *gdbarch = frame_unwind_caller_arch (next_frame);
7939 symtab_and_line sr_sal;
7940 sr_sal.pc = gdbarch_addr_bits_remove (gdbarch,
7941 frame_unwind_caller_pc (next_frame));
7942 sr_sal.section = find_pc_overlay (sr_sal.pc);
7943 sr_sal.pspace = frame_unwind_program_space (next_frame);
7945 insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal,
7946 frame_unwind_caller_id (next_frame));
7949 /* Insert a "longjmp-resume" breakpoint at PC. This is used to set a
7950 new breakpoint at the target of a jmp_buf. The handling of
7951 longjmp-resume uses the same mechanisms used for handling
7952 "step-resume" breakpoints. */
7954 static void
7955 insert_longjmp_resume_breakpoint (struct gdbarch *gdbarch, CORE_ADDR pc)
7957 /* There should never be more than one longjmp-resume breakpoint per
7958 thread, so we should never be setting a new
7959 longjmp_resume_breakpoint when one is already active. */
7960 gdb_assert (inferior_thread ()->control.exception_resume_breakpoint == nullptr);
7962 infrun_debug_printf ("inserting longjmp-resume breakpoint at %s",
7963 paddress (gdbarch, pc));
7965 inferior_thread ()->control.exception_resume_breakpoint =
7966 set_momentary_breakpoint_at_pc (gdbarch, pc, bp_longjmp_resume).release ();
7969 /* Insert an exception resume breakpoint. TP is the thread throwing
7970 the exception. The block B is the block of the unwinder debug hook
7971 function. FRAME is the frame corresponding to the call to this
7972 function. SYM is the symbol of the function argument holding the
7973 target PC of the exception. */
7975 static void
7976 insert_exception_resume_breakpoint (struct thread_info *tp,
7977 const struct block *b,
7978 frame_info_ptr frame,
7979 struct symbol *sym)
7983 struct block_symbol vsym;
7984 struct value *value;
7985 CORE_ADDR handler;
7986 struct breakpoint *bp;
7988 vsym = lookup_symbol_search_name (sym->search_name (),
7989 b, VAR_DOMAIN);
7990 value = read_var_value (vsym.symbol, vsym.block, frame);
7991 /* If the value was optimized out, revert to the old behavior. */
7992 if (! value_optimized_out (value))
7994 handler = value_as_address (value);
7996 infrun_debug_printf ("exception resume at %lx",
7997 (unsigned long) handler);
7999 bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
8000 handler,
8001 bp_exception_resume).release ();
8003 /* set_momentary_breakpoint_at_pc invalidates FRAME. */
8004 frame = nullptr;
8006 bp->thread = tp->global_num;
8007 inferior_thread ()->control.exception_resume_breakpoint = bp;
8010 catch (const gdb_exception_error &e)
8012 /* We want to ignore errors here. */
8016 /* A helper for check_exception_resume that sets an
8017 exception-breakpoint based on a SystemTap probe. */
8019 static void
8020 insert_exception_resume_from_probe (struct thread_info *tp,
8021 const struct bound_probe *probe,
8022 frame_info_ptr frame)
8024 struct value *arg_value;
8025 CORE_ADDR handler;
8026 struct breakpoint *bp;
8028 arg_value = probe_safe_evaluate_at_pc (frame, 1);
8029 if (!arg_value)
8030 return;
8032 handler = value_as_address (arg_value);
8034 infrun_debug_printf ("exception resume at %s",
8035 paddress (probe->objfile->arch (), handler));
8037 bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
8038 handler, bp_exception_resume).release ();
8039 bp->thread = tp->global_num;
8040 inferior_thread ()->control.exception_resume_breakpoint = bp;
8043 /* This is called when an exception has been intercepted. Check to
8044 see whether the exception's destination is of interest, and if so,
8045 set an exception resume breakpoint there. */
8047 static void
8048 check_exception_resume (struct execution_control_state *ecs,
8049 frame_info_ptr frame)
8051 struct bound_probe probe;
8052 struct symbol *func;
8054 /* First see if this exception unwinding breakpoint was set via a
8055 SystemTap probe point. If so, the probe has two arguments: the
8056 CFA and the HANDLER. We ignore the CFA, extract the handler, and
8057 set a breakpoint there. */
8058 probe = find_probe_by_pc (get_frame_pc (frame));
8059 if (probe.prob)
8061 insert_exception_resume_from_probe (ecs->event_thread, &probe, frame);
8062 return;
8065 func = get_frame_function (frame);
8066 if (!func)
8067 return;
8071 const struct block *b;
8072 struct block_iterator iter;
8073 struct symbol *sym;
8074 int argno = 0;
8076 /* The exception breakpoint is a thread-specific breakpoint on
8077 the unwinder's debug hook, declared as:
8079 void _Unwind_DebugHook (void *cfa, void *handler);
8081 The CFA argument indicates the frame to which control is
8082 about to be transferred. HANDLER is the destination PC.
8084 We ignore the CFA and set a temporary breakpoint at HANDLER.
8085 This is not extremely efficient but it avoids issues in gdb
8086 with computing the DWARF CFA, and it also works even in weird
8087 cases such as throwing an exception from inside a signal
8088 handler. */
8090 b = func->value_block ();
8091 ALL_BLOCK_SYMBOLS (b, iter, sym)
8093 if (!sym->is_argument ())
8094 continue;
8096 if (argno == 0)
8097 ++argno;
8098 else
8100 insert_exception_resume_breakpoint (ecs->event_thread,
8101 b, frame, sym);
8102 break;
8106 catch (const gdb_exception_error &e)
8111 static void
8112 stop_waiting (struct execution_control_state *ecs)
8114 infrun_debug_printf ("stop_waiting");
8116 /* Let callers know we don't want to wait for the inferior anymore. */
8117 ecs->wait_some_more = 0;
8120 /* Like keep_going, but passes the signal to the inferior, even if the
8121 signal is set to nopass. */
8123 static void
8124 keep_going_pass_signal (struct execution_control_state *ecs)
8126 gdb_assert (ecs->event_thread->ptid == inferior_ptid);
8127 gdb_assert (!ecs->event_thread->resumed ());
8129 /* Save the pc before execution, to compare with pc after stop. */
8130 ecs->event_thread->prev_pc
8131 = regcache_read_pc_protected (get_thread_regcache (ecs->event_thread));
8133 if (ecs->event_thread->control.trap_expected)
8135 struct thread_info *tp = ecs->event_thread;
8137 infrun_debug_printf ("%s has trap_expected set, "
8138 "resuming to collect trap",
8139 tp->ptid.to_string ().c_str ());
8141 /* We haven't yet gotten our trap, and either: intercepted a
8142 non-signal event (e.g., a fork); or took a signal which we
8143 are supposed to pass through to the inferior. Simply
8144 continue. */
8145 resume (ecs->event_thread->stop_signal ());
8147 else if (step_over_info_valid_p ())
8149 /* Another thread is stepping over a breakpoint in-line. If
8150 this thread needs a step-over too, queue the request. In
8151 either case, this resume must be deferred for later. */
8152 struct thread_info *tp = ecs->event_thread;
8154 if (ecs->hit_singlestep_breakpoint
8155 || thread_still_needs_step_over (tp))
8157 infrun_debug_printf ("step-over already in progress: "
8158 "step-over for %s deferred",
8159 tp->ptid.to_string ().c_str ());
8160 global_thread_step_over_chain_enqueue (tp);
8162 else
8163 infrun_debug_printf ("step-over in progress: resume of %s deferred",
8164 tp->ptid.to_string ().c_str ());
8166 else
8168 struct regcache *regcache = get_current_regcache ();
8169 int remove_bp;
8170 int remove_wps;
8171 step_over_what step_what;
8173 /* Either the trap was not expected, but we are continuing
8174 anyway (if we got a signal, the user asked it be passed to
8175 the child)
8176 -- or --
8177 We got our expected trap, but decided we should resume from
8180 We're going to run this baby now!
8182 Note that insert_breakpoints won't try to re-insert
8183 already inserted breakpoints. Therefore, we don't
8184 care if breakpoints were already inserted, or not. */
8186 /* If we need to step over a breakpoint, and we're not using
8187 displaced stepping to do so, insert all breakpoints
8188 (watchpoints, etc.) but the one we're stepping over, step one
8189 instruction, and then re-insert the breakpoint when that step
8190 is finished. */
8192 step_what = thread_still_needs_step_over (ecs->event_thread);
8194 remove_bp = (ecs->hit_singlestep_breakpoint
8195 || (step_what & STEP_OVER_BREAKPOINT));
8196 remove_wps = (step_what & STEP_OVER_WATCHPOINT);
8198 /* We can't use displaced stepping if we need to step past a
8199 watchpoint. The instruction copied to the scratch pad would
8200 still trigger the watchpoint. */
8201 if (remove_bp
8202 && (remove_wps || !use_displaced_stepping (ecs->event_thread)))
8204 set_step_over_info (regcache->aspace (),
8205 regcache_read_pc (regcache), remove_wps,
8206 ecs->event_thread->global_num);
8208 else if (remove_wps)
8209 set_step_over_info (nullptr, 0, remove_wps, -1);
8211 /* If we now need to do an in-line step-over, we need to stop
8212 all other threads. Note this must be done before
8213 insert_breakpoints below, because that removes the breakpoint
8214 we're about to step over, otherwise other threads could miss
8215 it. */
8216 if (step_over_info_valid_p () && target_is_non_stop_p ())
8217 stop_all_threads ("starting in-line step-over");
8219 /* Stop stepping if inserting breakpoints fails. */
8222 insert_breakpoints ();
8224 catch (const gdb_exception_error &e)
8226 exception_print (gdb_stderr, e);
8227 stop_waiting (ecs);
8228 clear_step_over_info ();
8229 return;
8232 ecs->event_thread->control.trap_expected = (remove_bp || remove_wps);
8234 resume (ecs->event_thread->stop_signal ());
8237 prepare_to_wait (ecs);
8240 /* Called when we should continue running the inferior, because the
8241 current event doesn't cause a user visible stop. This does the
8242 resuming part; waiting for the next event is done elsewhere. */
8244 static void
8245 keep_going (struct execution_control_state *ecs)
8247 if (ecs->event_thread->control.trap_expected
8248 && ecs->event_thread->stop_signal () == GDB_SIGNAL_TRAP)
8249 ecs->event_thread->control.trap_expected = 0;
8251 if (!signal_program[ecs->event_thread->stop_signal ()])
8252 ecs->event_thread->set_stop_signal (GDB_SIGNAL_0);
8253 keep_going_pass_signal (ecs);
8256 /* This function normally comes after a resume, before
8257 handle_inferior_event exits. It takes care of any last bits of
8258 housekeeping, and sets the all-important wait_some_more flag. */
8260 static void
8261 prepare_to_wait (struct execution_control_state *ecs)
8263 infrun_debug_printf ("prepare_to_wait");
8265 ecs->wait_some_more = 1;
8267 /* If the target can't async, emulate it by marking the infrun event
8268 handler such that as soon as we get back to the event-loop, we
8269 immediately end up in fetch_inferior_event again calling
8270 target_wait. */
8271 if (!target_can_async_p ())
8272 mark_infrun_async_event_handler ();
8275 /* We are done with the step range of a step/next/si/ni command.
8276 Called once for each n of a "step n" operation. */
8278 static void
8279 end_stepping_range (struct execution_control_state *ecs)
8281 ecs->event_thread->control.stop_step = 1;
8282 stop_waiting (ecs);
8285 /* Several print_*_reason functions to print why the inferior has stopped.
8286 We always print something when the inferior exits, or receives a signal.
8287 The rest of the cases are dealt with later on in normal_stop and
8288 print_it_typical. Ideally there should be a call to one of these
8289 print_*_reason functions functions from handle_inferior_event each time
8290 stop_waiting is called.
8292 Note that we don't call these directly, instead we delegate that to
8293 the interpreters, through observers. Interpreters then call these
8294 with whatever uiout is right. */
8296 void
8297 print_end_stepping_range_reason (struct ui_out *uiout)
8299 /* For CLI-like interpreters, print nothing. */
8301 if (uiout->is_mi_like_p ())
8303 uiout->field_string ("reason",
8304 async_reason_lookup (EXEC_ASYNC_END_STEPPING_RANGE));
8308 void
8309 print_signal_exited_reason (struct ui_out *uiout, enum gdb_signal siggnal)
8311 annotate_signalled ();
8312 if (uiout->is_mi_like_p ())
8313 uiout->field_string
8314 ("reason", async_reason_lookup (EXEC_ASYNC_EXITED_SIGNALLED));
8315 uiout->text ("\nProgram terminated with signal ");
8316 annotate_signal_name ();
8317 uiout->field_string ("signal-name",
8318 gdb_signal_to_name (siggnal));
8319 annotate_signal_name_end ();
8320 uiout->text (", ");
8321 annotate_signal_string ();
8322 uiout->field_string ("signal-meaning",
8323 gdb_signal_to_string (siggnal));
8324 annotate_signal_string_end ();
8325 uiout->text (".\n");
8326 uiout->text ("The program no longer exists.\n");
8329 void
8330 print_exited_reason (struct ui_out *uiout, int exitstatus)
8332 struct inferior *inf = current_inferior ();
8333 std::string pidstr = target_pid_to_str (ptid_t (inf->pid));
8335 annotate_exited (exitstatus);
8336 if (exitstatus)
8338 if (uiout->is_mi_like_p ())
8339 uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXITED));
8340 std::string exit_code_str
8341 = string_printf ("0%o", (unsigned int) exitstatus);
8342 uiout->message ("[Inferior %s (%s) exited with code %pF]\n",
8343 plongest (inf->num), pidstr.c_str (),
8344 string_field ("exit-code", exit_code_str.c_str ()));
8346 else
8348 if (uiout->is_mi_like_p ())
8349 uiout->field_string
8350 ("reason", async_reason_lookup (EXEC_ASYNC_EXITED_NORMALLY));
8351 uiout->message ("[Inferior %s (%s) exited normally]\n",
8352 plongest (inf->num), pidstr.c_str ());
8356 void
8357 print_signal_received_reason (struct ui_out *uiout, enum gdb_signal siggnal)
8359 struct thread_info *thr = inferior_thread ();
8361 annotate_signal ();
8363 if (uiout->is_mi_like_p ())
8365 else if (show_thread_that_caused_stop ())
8367 uiout->text ("\nThread ");
8368 uiout->field_string ("thread-id", print_thread_id (thr));
8370 const char *name = thread_name (thr);
8371 if (name != nullptr)
8373 uiout->text (" \"");
8374 uiout->field_string ("name", name);
8375 uiout->text ("\"");
8378 else
8379 uiout->text ("\nProgram");
8381 if (siggnal == GDB_SIGNAL_0 && !uiout->is_mi_like_p ())
8382 uiout->text (" stopped");
8383 else
8385 uiout->text (" received signal ");
8386 annotate_signal_name ();
8387 if (uiout->is_mi_like_p ())
8388 uiout->field_string
8389 ("reason", async_reason_lookup (EXEC_ASYNC_SIGNAL_RECEIVED));
8390 uiout->field_string ("signal-name", gdb_signal_to_name (siggnal));
8391 annotate_signal_name_end ();
8392 uiout->text (", ");
8393 annotate_signal_string ();
8394 uiout->field_string ("signal-meaning", gdb_signal_to_string (siggnal));
8396 struct regcache *regcache = get_current_regcache ();
8397 struct gdbarch *gdbarch = regcache->arch ();
8398 if (gdbarch_report_signal_info_p (gdbarch))
8399 gdbarch_report_signal_info (gdbarch, uiout, siggnal);
8401 annotate_signal_string_end ();
8403 uiout->text (".\n");
8406 void
8407 print_no_history_reason (struct ui_out *uiout)
8409 uiout->text ("\nNo more reverse-execution history.\n");
8412 /* Print current location without a level number, if we have changed
8413 functions or hit a breakpoint. Print source line if we have one.
8414 bpstat_print contains the logic deciding in detail what to print,
8415 based on the event(s) that just occurred. */
8417 static void
8418 print_stop_location (const target_waitstatus &ws)
8420 int bpstat_ret;
8421 enum print_what source_flag;
8422 int do_frame_printing = 1;
8423 struct thread_info *tp = inferior_thread ();
8425 bpstat_ret = bpstat_print (tp->control.stop_bpstat, ws.kind ());
8426 switch (bpstat_ret)
8428 case PRINT_UNKNOWN:
8429 /* FIXME: cagney/2002-12-01: Given that a frame ID does (or
8430 should) carry around the function and does (or should) use
8431 that when doing a frame comparison. */
8432 if (tp->control.stop_step
8433 && (tp->control.step_frame_id
8434 == get_frame_id (get_current_frame ()))
8435 && (tp->control.step_start_function
8436 == find_pc_function (tp->stop_pc ())))
8438 /* Finished step, just print source line. */
8439 source_flag = SRC_LINE;
8441 else
8443 /* Print location and source line. */
8444 source_flag = SRC_AND_LOC;
8446 break;
8447 case PRINT_SRC_AND_LOC:
8448 /* Print location and source line. */
8449 source_flag = SRC_AND_LOC;
8450 break;
8451 case PRINT_SRC_ONLY:
8452 source_flag = SRC_LINE;
8453 break;
8454 case PRINT_NOTHING:
8455 /* Something bogus. */
8456 source_flag = SRC_LINE;
8457 do_frame_printing = 0;
8458 break;
8459 default:
8460 internal_error (_("Unknown value."));
8463 /* The behavior of this routine with respect to the source
8464 flag is:
8465 SRC_LINE: Print only source line
8466 LOCATION: Print only location
8467 SRC_AND_LOC: Print location and source line. */
8468 if (do_frame_printing)
8469 print_stack_frame (get_selected_frame (nullptr), 0, source_flag, 1);
8472 /* See infrun.h. */
8474 void
8475 print_stop_event (struct ui_out *uiout, bool displays)
8477 struct target_waitstatus last;
8478 struct thread_info *tp;
8480 get_last_target_status (nullptr, nullptr, &last);
8483 scoped_restore save_uiout = make_scoped_restore (&current_uiout, uiout);
8485 print_stop_location (last);
8487 /* Display the auto-display expressions. */
8488 if (displays)
8489 do_displays ();
8492 tp = inferior_thread ();
8493 if (tp->thread_fsm () != nullptr
8494 && tp->thread_fsm ()->finished_p ())
8496 struct return_value_info *rv;
8498 rv = tp->thread_fsm ()->return_value ();
8499 if (rv != nullptr)
8500 print_return_value (uiout, rv);
8504 /* See infrun.h. */
8506 void
8507 maybe_remove_breakpoints (void)
8509 if (!breakpoints_should_be_inserted_now () && target_has_execution ())
8511 if (remove_breakpoints ())
8513 target_terminal::ours_for_output ();
8514 gdb_printf (_("Cannot remove breakpoints because "
8515 "program is no longer writable.\nFurther "
8516 "execution is probably impossible.\n"));
8521 /* The execution context that just caused a normal stop. */
8523 struct stop_context
8525 stop_context ();
8527 DISABLE_COPY_AND_ASSIGN (stop_context);
8529 bool changed () const;
8531 /* The stop ID. */
8532 ULONGEST stop_id;
8534 /* The event PTID. */
8536 ptid_t ptid;
8538 /* If stopp for a thread event, this is the thread that caused the
8539 stop. */
8540 thread_info_ref thread;
8542 /* The inferior that caused the stop. */
8543 int inf_num;
8546 /* Initializes a new stop context. If stopped for a thread event, this
8547 takes a strong reference to the thread. */
8549 stop_context::stop_context ()
8551 stop_id = get_stop_id ();
8552 ptid = inferior_ptid;
8553 inf_num = current_inferior ()->num;
8555 if (inferior_ptid != null_ptid)
8557 /* Take a strong reference so that the thread can't be deleted
8558 yet. */
8559 thread = thread_info_ref::new_reference (inferior_thread ());
8563 /* Return true if the current context no longer matches the saved stop
8564 context. */
8566 bool
8567 stop_context::changed () const
8569 if (ptid != inferior_ptid)
8570 return true;
8571 if (inf_num != current_inferior ()->num)
8572 return true;
8573 if (thread != nullptr && thread->state != THREAD_STOPPED)
8574 return true;
8575 if (get_stop_id () != stop_id)
8576 return true;
8577 return false;
8580 /* See infrun.h. */
8583 normal_stop (void)
8585 struct target_waitstatus last;
8587 get_last_target_status (nullptr, nullptr, &last);
8589 new_stop_id ();
8591 /* If an exception is thrown from this point on, make sure to
8592 propagate GDB's knowledge of the executing state to the
8593 frontend/user running state. A QUIT is an easy exception to see
8594 here, so do this before any filtered output. */
8596 ptid_t finish_ptid = null_ptid;
8598 if (!non_stop)
8599 finish_ptid = minus_one_ptid;
8600 else if (last.kind () == TARGET_WAITKIND_SIGNALLED
8601 || last.kind () == TARGET_WAITKIND_EXITED)
8603 /* On some targets, we may still have live threads in the
8604 inferior when we get a process exit event. E.g., for
8605 "checkpoint", when the current checkpoint/fork exits,
8606 linux-fork.c automatically switches to another fork from
8607 within target_mourn_inferior. */
8608 if (inferior_ptid != null_ptid)
8609 finish_ptid = ptid_t (inferior_ptid.pid ());
8611 else if (last.kind () != TARGET_WAITKIND_NO_RESUMED)
8612 finish_ptid = inferior_ptid;
8614 gdb::optional<scoped_finish_thread_state> maybe_finish_thread_state;
8615 if (finish_ptid != null_ptid)
8617 maybe_finish_thread_state.emplace
8618 (user_visible_resume_target (finish_ptid), finish_ptid);
8621 /* As we're presenting a stop, and potentially removing breakpoints,
8622 update the thread list so we can tell whether there are threads
8623 running on the target. With target remote, for example, we can
8624 only learn about new threads when we explicitly update the thread
8625 list. Do this before notifying the interpreters about signal
8626 stops, end of stepping ranges, etc., so that the "new thread"
8627 output is emitted before e.g., "Program received signal FOO",
8628 instead of after. */
8629 update_thread_list ();
8631 if (last.kind () == TARGET_WAITKIND_STOPPED && stopped_by_random_signal)
8632 gdb::observers::signal_received.notify (inferior_thread ()->stop_signal ());
8634 /* As with the notification of thread events, we want to delay
8635 notifying the user that we've switched thread context until
8636 the inferior actually stops.
8638 There's no point in saying anything if the inferior has exited.
8639 Note that SIGNALLED here means "exited with a signal", not
8640 "received a signal".
8642 Also skip saying anything in non-stop mode. In that mode, as we
8643 don't want GDB to switch threads behind the user's back, to avoid
8644 races where the user is typing a command to apply to thread x,
8645 but GDB switches to thread y before the user finishes entering
8646 the command, fetch_inferior_event installs a cleanup to restore
8647 the current thread back to the thread the user had selected right
8648 after this event is handled, so we're not really switching, only
8649 informing of a stop. */
8650 if (!non_stop
8651 && previous_inferior_ptid != inferior_ptid
8652 && target_has_execution ()
8653 && last.kind () != TARGET_WAITKIND_SIGNALLED
8654 && last.kind () != TARGET_WAITKIND_EXITED
8655 && last.kind () != TARGET_WAITKIND_NO_RESUMED)
8657 SWITCH_THRU_ALL_UIS ()
8659 target_terminal::ours_for_output ();
8660 gdb_printf (_("[Switching to %s]\n"),
8661 target_pid_to_str (inferior_ptid).c_str ());
8662 annotate_thread_changed ();
8664 previous_inferior_ptid = inferior_ptid;
8667 if (last.kind () == TARGET_WAITKIND_NO_RESUMED)
8669 SWITCH_THRU_ALL_UIS ()
8670 if (current_ui->prompt_state == PROMPT_BLOCKED)
8672 target_terminal::ours_for_output ();
8673 gdb_printf (_("No unwaited-for children left.\n"));
8677 /* Note: this depends on the update_thread_list call above. */
8678 maybe_remove_breakpoints ();
8680 /* If an auto-display called a function and that got a signal,
8681 delete that auto-display to avoid an infinite recursion. */
8683 if (stopped_by_random_signal)
8684 disable_current_display ();
8686 SWITCH_THRU_ALL_UIS ()
8688 async_enable_stdin ();
8691 /* Let the user/frontend see the threads as stopped. */
8692 maybe_finish_thread_state.reset ();
8694 /* Select innermost stack frame - i.e., current frame is frame 0,
8695 and current location is based on that. Handle the case where the
8696 dummy call is returning after being stopped. E.g. the dummy call
8697 previously hit a breakpoint. (If the dummy call returns
8698 normally, we won't reach here.) Do this before the stop hook is
8699 run, so that it doesn't get to see the temporary dummy frame,
8700 which is not where we'll present the stop. */
8701 if (has_stack_frames ())
8703 if (stop_stack_dummy == STOP_STACK_DUMMY)
8705 /* Pop the empty frame that contains the stack dummy. This
8706 also restores inferior state prior to the call (struct
8707 infcall_suspend_state). */
8708 frame_info_ptr frame = get_current_frame ();
8710 gdb_assert (get_frame_type (frame) == DUMMY_FRAME);
8711 frame_pop (frame);
8712 /* frame_pop calls reinit_frame_cache as the last thing it
8713 does which means there's now no selected frame. */
8716 select_frame (get_current_frame ());
8718 /* Set the current source location. */
8719 set_current_sal_from_frame (get_current_frame ());
8722 /* Look up the hook_stop and run it (CLI internally handles problem
8723 of stop_command's pre-hook not existing). */
8724 stop_context saved_context;
8728 execute_cmd_pre_hook (stop_command);
8730 catch (const gdb_exception &ex)
8732 exception_fprintf (gdb_stderr, ex,
8733 "Error while running hook_stop:\n");
8736 /* If the stop hook resumes the target, then there's no point in
8737 trying to notify about the previous stop; its context is
8738 gone. Likewise if the command switches thread or inferior --
8739 the observers would print a stop for the wrong
8740 thread/inferior. */
8741 if (saved_context.changed ())
8742 return 1;
8744 /* Notify observers about the stop. This is where the interpreters
8745 print the stop event. */
8746 if (inferior_ptid != null_ptid)
8747 gdb::observers::normal_stop.notify (inferior_thread ()->control.stop_bpstat,
8748 stop_print_frame);
8749 else
8750 gdb::observers::normal_stop.notify (nullptr, stop_print_frame);
8752 annotate_stopped ();
8754 if (target_has_execution ())
8756 if (last.kind () != TARGET_WAITKIND_SIGNALLED
8757 && last.kind () != TARGET_WAITKIND_EXITED
8758 && last.kind () != TARGET_WAITKIND_NO_RESUMED)
8759 /* Delete the breakpoint we stopped at, if it wants to be deleted.
8760 Delete any breakpoint that is to be deleted at the next stop. */
8761 breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
8764 return 0;
8768 signal_stop_state (int signo)
8770 return signal_stop[signo];
8774 signal_print_state (int signo)
8776 return signal_print[signo];
8780 signal_pass_state (int signo)
8782 return signal_program[signo];
8785 static void
8786 signal_cache_update (int signo)
8788 if (signo == -1)
8790 for (signo = 0; signo < (int) GDB_SIGNAL_LAST; signo++)
8791 signal_cache_update (signo);
8793 return;
8796 signal_pass[signo] = (signal_stop[signo] == 0
8797 && signal_print[signo] == 0
8798 && signal_program[signo] == 1
8799 && signal_catch[signo] == 0);
8803 signal_stop_update (int signo, int state)
8805 int ret = signal_stop[signo];
8807 signal_stop[signo] = state;
8808 signal_cache_update (signo);
8809 return ret;
8813 signal_print_update (int signo, int state)
8815 int ret = signal_print[signo];
8817 signal_print[signo] = state;
8818 signal_cache_update (signo);
8819 return ret;
8823 signal_pass_update (int signo, int state)
8825 int ret = signal_program[signo];
8827 signal_program[signo] = state;
8828 signal_cache_update (signo);
8829 return ret;
8832 /* Update the global 'signal_catch' from INFO and notify the
8833 target. */
8835 void
8836 signal_catch_update (const unsigned int *info)
8838 int i;
8840 for (i = 0; i < GDB_SIGNAL_LAST; ++i)
8841 signal_catch[i] = info[i] > 0;
8842 signal_cache_update (-1);
8843 target_pass_signals (signal_pass);
8846 static void
8847 sig_print_header (void)
8849 gdb_printf (_("Signal Stop\tPrint\tPass "
8850 "to program\tDescription\n"));
8853 static void
8854 sig_print_info (enum gdb_signal oursig)
8856 const char *name = gdb_signal_to_name (oursig);
8857 int name_padding = 13 - strlen (name);
8859 if (name_padding <= 0)
8860 name_padding = 0;
8862 gdb_printf ("%s", name);
8863 gdb_printf ("%*.*s ", name_padding, name_padding, " ");
8864 gdb_printf ("%s\t", signal_stop[oursig] ? "Yes" : "No");
8865 gdb_printf ("%s\t", signal_print[oursig] ? "Yes" : "No");
8866 gdb_printf ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
8867 gdb_printf ("%s\n", gdb_signal_to_string (oursig));
8870 /* Specify how various signals in the inferior should be handled. */
8872 static void
8873 handle_command (const char *args, int from_tty)
8875 int digits, wordlen;
8876 int sigfirst, siglast;
8877 enum gdb_signal oursig;
8878 int allsigs;
8880 if (args == nullptr)
8882 error_no_arg (_("signal to handle"));
8885 /* Allocate and zero an array of flags for which signals to handle. */
8887 const size_t nsigs = GDB_SIGNAL_LAST;
8888 unsigned char sigs[nsigs] {};
8890 /* Break the command line up into args. */
8892 gdb_argv built_argv (args);
8894 /* Walk through the args, looking for signal oursigs, signal names, and
8895 actions. Signal numbers and signal names may be interspersed with
8896 actions, with the actions being performed for all signals cumulatively
8897 specified. Signal ranges can be specified as <LOW>-<HIGH>. */
8899 for (char *arg : built_argv)
8901 wordlen = strlen (arg);
8902 for (digits = 0; isdigit (arg[digits]); digits++)
8905 allsigs = 0;
8906 sigfirst = siglast = -1;
8908 if (wordlen >= 1 && !strncmp (arg, "all", wordlen))
8910 /* Apply action to all signals except those used by the
8911 debugger. Silently skip those. */
8912 allsigs = 1;
8913 sigfirst = 0;
8914 siglast = nsigs - 1;
8916 else if (wordlen >= 1 && !strncmp (arg, "stop", wordlen))
8918 SET_SIGS (nsigs, sigs, signal_stop);
8919 SET_SIGS (nsigs, sigs, signal_print);
8921 else if (wordlen >= 1 && !strncmp (arg, "ignore", wordlen))
8923 UNSET_SIGS (nsigs, sigs, signal_program);
8925 else if (wordlen >= 2 && !strncmp (arg, "print", wordlen))
8927 SET_SIGS (nsigs, sigs, signal_print);
8929 else if (wordlen >= 2 && !strncmp (arg, "pass", wordlen))
8931 SET_SIGS (nsigs, sigs, signal_program);
8933 else if (wordlen >= 3 && !strncmp (arg, "nostop", wordlen))
8935 UNSET_SIGS (nsigs, sigs, signal_stop);
8937 else if (wordlen >= 3 && !strncmp (arg, "noignore", wordlen))
8939 SET_SIGS (nsigs, sigs, signal_program);
8941 else if (wordlen >= 4 && !strncmp (arg, "noprint", wordlen))
8943 UNSET_SIGS (nsigs, sigs, signal_print);
8944 UNSET_SIGS (nsigs, sigs, signal_stop);
8946 else if (wordlen >= 4 && !strncmp (arg, "nopass", wordlen))
8948 UNSET_SIGS (nsigs, sigs, signal_program);
8950 else if (digits > 0)
8952 /* It is numeric. The numeric signal refers to our own
8953 internal signal numbering from target.h, not to host/target
8954 signal number. This is a feature; users really should be
8955 using symbolic names anyway, and the common ones like
8956 SIGHUP, SIGINT, SIGALRM, etc. will work right anyway. */
8958 sigfirst = siglast = (int)
8959 gdb_signal_from_command (atoi (arg));
8960 if (arg[digits] == '-')
8962 siglast = (int)
8963 gdb_signal_from_command (atoi (arg + digits + 1));
8965 if (sigfirst > siglast)
8967 /* Bet he didn't figure we'd think of this case... */
8968 std::swap (sigfirst, siglast);
8971 else
8973 oursig = gdb_signal_from_name (arg);
8974 if (oursig != GDB_SIGNAL_UNKNOWN)
8976 sigfirst = siglast = (int) oursig;
8978 else
8980 /* Not a number and not a recognized flag word => complain. */
8981 error (_("Unrecognized or ambiguous flag word: \"%s\"."), arg);
8985 /* If any signal numbers or symbol names were found, set flags for
8986 which signals to apply actions to. */
8988 for (int signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
8990 switch ((enum gdb_signal) signum)
8992 case GDB_SIGNAL_TRAP:
8993 case GDB_SIGNAL_INT:
8994 if (!allsigs && !sigs[signum])
8996 if (query (_("%s is used by the debugger.\n\
8997 Are you sure you want to change it? "),
8998 gdb_signal_to_name ((enum gdb_signal) signum)))
9000 sigs[signum] = 1;
9002 else
9003 gdb_printf (_("Not confirmed, unchanged.\n"));
9005 break;
9006 case GDB_SIGNAL_0:
9007 case GDB_SIGNAL_DEFAULT:
9008 case GDB_SIGNAL_UNKNOWN:
9009 /* Make sure that "all" doesn't print these. */
9010 break;
9011 default:
9012 sigs[signum] = 1;
9013 break;
9018 for (int signum = 0; signum < nsigs; signum++)
9019 if (sigs[signum])
9021 signal_cache_update (-1);
9022 target_pass_signals (signal_pass);
9023 target_program_signals (signal_program);
9025 if (from_tty)
9027 /* Show the results. */
9028 sig_print_header ();
9029 for (; signum < nsigs; signum++)
9030 if (sigs[signum])
9031 sig_print_info ((enum gdb_signal) signum);
9034 break;
9038 /* Complete the "handle" command. */
9040 static void
9041 handle_completer (struct cmd_list_element *ignore,
9042 completion_tracker &tracker,
9043 const char *text, const char *word)
9045 static const char * const keywords[] =
9047 "all",
9048 "stop",
9049 "ignore",
9050 "print",
9051 "pass",
9052 "nostop",
9053 "noignore",
9054 "noprint",
9055 "nopass",
9056 nullptr,
9059 signal_completer (ignore, tracker, text, word);
9060 complete_on_enum (tracker, keywords, word, word);
9063 enum gdb_signal
9064 gdb_signal_from_command (int num)
9066 if (num >= 1 && num <= 15)
9067 return (enum gdb_signal) num;
9068 error (_("Only signals 1-15 are valid as numeric signals.\n\
9069 Use \"info signals\" for a list of symbolic signals."));
9072 /* Print current contents of the tables set by the handle command.
9073 It is possible we should just be printing signals actually used
9074 by the current target (but for things to work right when switching
9075 targets, all signals should be in the signal tables). */
9077 static void
9078 info_signals_command (const char *signum_exp, int from_tty)
9080 enum gdb_signal oursig;
9082 sig_print_header ();
9084 if (signum_exp)
9086 /* First see if this is a symbol name. */
9087 oursig = gdb_signal_from_name (signum_exp);
9088 if (oursig == GDB_SIGNAL_UNKNOWN)
9090 /* No, try numeric. */
9091 oursig =
9092 gdb_signal_from_command (parse_and_eval_long (signum_exp));
9094 sig_print_info (oursig);
9095 return;
9098 gdb_printf ("\n");
9099 /* These ugly casts brought to you by the native VAX compiler. */
9100 for (oursig = GDB_SIGNAL_FIRST;
9101 (int) oursig < (int) GDB_SIGNAL_LAST;
9102 oursig = (enum gdb_signal) ((int) oursig + 1))
9104 QUIT;
9106 if (oursig != GDB_SIGNAL_UNKNOWN
9107 && oursig != GDB_SIGNAL_DEFAULT && oursig != GDB_SIGNAL_0)
9108 sig_print_info (oursig);
9111 gdb_printf (_("\nUse the \"handle\" command "
9112 "to change these tables.\n"));
9115 /* The $_siginfo convenience variable is a bit special. We don't know
9116 for sure the type of the value until we actually have a chance to
9117 fetch the data. The type can change depending on gdbarch, so it is
9118 also dependent on which thread you have selected.
9120 1. making $_siginfo be an internalvar that creates a new value on
9121 access.
9123 2. making the value of $_siginfo be an lval_computed value. */
9125 /* This function implements the lval_computed support for reading a
9126 $_siginfo value. */
9128 static void
9129 siginfo_value_read (struct value *v)
9131 LONGEST transferred;
9133 /* If we can access registers, so can we access $_siginfo. Likewise
9134 vice versa. */
9135 validate_registers_access ();
9137 transferred =
9138 target_read (current_inferior ()->top_target (),
9139 TARGET_OBJECT_SIGNAL_INFO,
9140 nullptr,
9141 value_contents_all_raw (v).data (),
9142 value_offset (v),
9143 value_type (v)->length ());
9145 if (transferred != value_type (v)->length ())
9146 error (_("Unable to read siginfo"));
9149 /* This function implements the lval_computed support for writing a
9150 $_siginfo value. */
9152 static void
9153 siginfo_value_write (struct value *v, struct value *fromval)
9155 LONGEST transferred;
9157 /* If we can access registers, so can we access $_siginfo. Likewise
9158 vice versa. */
9159 validate_registers_access ();
9161 transferred = target_write (current_inferior ()->top_target (),
9162 TARGET_OBJECT_SIGNAL_INFO,
9163 nullptr,
9164 value_contents_all_raw (fromval).data (),
9165 value_offset (v),
9166 value_type (fromval)->length ());
9168 if (transferred != value_type (fromval)->length ())
9169 error (_("Unable to write siginfo"));
9172 static const struct lval_funcs siginfo_value_funcs =
9174 siginfo_value_read,
9175 siginfo_value_write
9178 /* Return a new value with the correct type for the siginfo object of
9179 the current thread using architecture GDBARCH. Return a void value
9180 if there's no object available. */
9182 static struct value *
9183 siginfo_make_value (struct gdbarch *gdbarch, struct internalvar *var,
9184 void *ignore)
9186 if (target_has_stack ()
9187 && inferior_ptid != null_ptid
9188 && gdbarch_get_siginfo_type_p (gdbarch))
9190 struct type *type = gdbarch_get_siginfo_type (gdbarch);
9192 return allocate_computed_value (type, &siginfo_value_funcs, nullptr);
9195 return allocate_value (builtin_type (gdbarch)->builtin_void);
9199 /* infcall_suspend_state contains state about the program itself like its
9200 registers and any signal it received when it last stopped.
9201 This state must be restored regardless of how the inferior function call
9202 ends (either successfully, or after it hits a breakpoint or signal)
9203 if the program is to properly continue where it left off. */
9205 class infcall_suspend_state
9207 public:
9208 /* Capture state from GDBARCH, TP, and REGCACHE that must be restored
9209 once the inferior function call has finished. */
9210 infcall_suspend_state (struct gdbarch *gdbarch,
9211 const struct thread_info *tp,
9212 struct regcache *regcache)
9213 : m_registers (new readonly_detached_regcache (*regcache))
9215 tp->save_suspend_to (m_thread_suspend);
9217 gdb::unique_xmalloc_ptr<gdb_byte> siginfo_data;
9219 if (gdbarch_get_siginfo_type_p (gdbarch))
9221 struct type *type = gdbarch_get_siginfo_type (gdbarch);
9222 size_t len = type->length ();
9224 siginfo_data.reset ((gdb_byte *) xmalloc (len));
9226 if (target_read (current_inferior ()->top_target (),
9227 TARGET_OBJECT_SIGNAL_INFO, nullptr,
9228 siginfo_data.get (), 0, len) != len)
9230 /* Errors ignored. */
9231 siginfo_data.reset (nullptr);
9235 if (siginfo_data)
9237 m_siginfo_gdbarch = gdbarch;
9238 m_siginfo_data = std::move (siginfo_data);
9242 /* Return a pointer to the stored register state. */
9244 readonly_detached_regcache *registers () const
9246 return m_registers.get ();
9249 /* Restores the stored state into GDBARCH, TP, and REGCACHE. */
9251 void restore (struct gdbarch *gdbarch,
9252 struct thread_info *tp,
9253 struct regcache *regcache) const
9255 tp->restore_suspend_from (m_thread_suspend);
9257 if (m_siginfo_gdbarch == gdbarch)
9259 struct type *type = gdbarch_get_siginfo_type (gdbarch);
9261 /* Errors ignored. */
9262 target_write (current_inferior ()->top_target (),
9263 TARGET_OBJECT_SIGNAL_INFO, nullptr,
9264 m_siginfo_data.get (), 0, type->length ());
9267 /* The inferior can be gone if the user types "print exit(0)"
9268 (and perhaps other times). */
9269 if (target_has_execution ())
9270 /* NB: The register write goes through to the target. */
9271 regcache->restore (registers ());
9274 private:
9275 /* How the current thread stopped before the inferior function call was
9276 executed. */
9277 struct thread_suspend_state m_thread_suspend;
9279 /* The registers before the inferior function call was executed. */
9280 std::unique_ptr<readonly_detached_regcache> m_registers;
9282 /* Format of SIGINFO_DATA or NULL if it is not present. */
9283 struct gdbarch *m_siginfo_gdbarch = nullptr;
9285 /* The inferior format depends on SIGINFO_GDBARCH and it has a length of
9286 gdbarch_get_siginfo_type ()->length (). For different gdbarch the
9287 content would be invalid. */
9288 gdb::unique_xmalloc_ptr<gdb_byte> m_siginfo_data;
9291 infcall_suspend_state_up
9292 save_infcall_suspend_state ()
9294 struct thread_info *tp = inferior_thread ();
9295 struct regcache *regcache = get_current_regcache ();
9296 struct gdbarch *gdbarch = regcache->arch ();
9298 infcall_suspend_state_up inf_state
9299 (new struct infcall_suspend_state (gdbarch, tp, regcache));
9301 /* Having saved the current state, adjust the thread state, discarding
9302 any stop signal information. The stop signal is not useful when
9303 starting an inferior function call, and run_inferior_call will not use
9304 the signal due to its `proceed' call with GDB_SIGNAL_0. */
9305 tp->set_stop_signal (GDB_SIGNAL_0);
9307 return inf_state;
9310 /* Restore inferior session state to INF_STATE. */
9312 void
9313 restore_infcall_suspend_state (struct infcall_suspend_state *inf_state)
9315 struct thread_info *tp = inferior_thread ();
9316 struct regcache *regcache = get_current_regcache ();
9317 struct gdbarch *gdbarch = regcache->arch ();
9319 inf_state->restore (gdbarch, tp, regcache);
9320 discard_infcall_suspend_state (inf_state);
9323 void
9324 discard_infcall_suspend_state (struct infcall_suspend_state *inf_state)
9326 delete inf_state;
9329 readonly_detached_regcache *
9330 get_infcall_suspend_state_regcache (struct infcall_suspend_state *inf_state)
9332 return inf_state->registers ();
9335 /* infcall_control_state contains state regarding gdb's control of the
9336 inferior itself like stepping control. It also contains session state like
9337 the user's currently selected frame. */
9339 struct infcall_control_state
9341 struct thread_control_state thread_control;
9342 struct inferior_control_state inferior_control;
9344 /* Other fields: */
9345 enum stop_stack_kind stop_stack_dummy = STOP_NONE;
9346 int stopped_by_random_signal = 0;
9348 /* ID and level of the selected frame when the inferior function
9349 call was made. */
9350 struct frame_id selected_frame_id {};
9351 int selected_frame_level = -1;
9354 /* Save all of the information associated with the inferior<==>gdb
9355 connection. */
9357 infcall_control_state_up
9358 save_infcall_control_state ()
9360 infcall_control_state_up inf_status (new struct infcall_control_state);
9361 struct thread_info *tp = inferior_thread ();
9362 struct inferior *inf = current_inferior ();
9364 inf_status->thread_control = tp->control;
9365 inf_status->inferior_control = inf->control;
9367 tp->control.step_resume_breakpoint = nullptr;
9368 tp->control.exception_resume_breakpoint = nullptr;
9370 /* Save original bpstat chain to INF_STATUS; replace it in TP with copy of
9371 chain. If caller's caller is walking the chain, they'll be happier if we
9372 hand them back the original chain when restore_infcall_control_state is
9373 called. */
9374 tp->control.stop_bpstat = bpstat_copy (tp->control.stop_bpstat);
9376 /* Other fields: */
9377 inf_status->stop_stack_dummy = stop_stack_dummy;
9378 inf_status->stopped_by_random_signal = stopped_by_random_signal;
9380 save_selected_frame (&inf_status->selected_frame_id,
9381 &inf_status->selected_frame_level);
9383 return inf_status;
9386 /* Restore inferior session state to INF_STATUS. */
9388 void
9389 restore_infcall_control_state (struct infcall_control_state *inf_status)
9391 struct thread_info *tp = inferior_thread ();
9392 struct inferior *inf = current_inferior ();
9394 if (tp->control.step_resume_breakpoint)
9395 tp->control.step_resume_breakpoint->disposition = disp_del_at_next_stop;
9397 if (tp->control.exception_resume_breakpoint)
9398 tp->control.exception_resume_breakpoint->disposition
9399 = disp_del_at_next_stop;
9401 /* Handle the bpstat_copy of the chain. */
9402 bpstat_clear (&tp->control.stop_bpstat);
9404 tp->control = inf_status->thread_control;
9405 inf->control = inf_status->inferior_control;
9407 /* Other fields: */
9408 stop_stack_dummy = inf_status->stop_stack_dummy;
9409 stopped_by_random_signal = inf_status->stopped_by_random_signal;
9411 if (target_has_stack ())
9413 restore_selected_frame (inf_status->selected_frame_id,
9414 inf_status->selected_frame_level);
9417 delete inf_status;
9420 void
9421 discard_infcall_control_state (struct infcall_control_state *inf_status)
9423 if (inf_status->thread_control.step_resume_breakpoint)
9424 inf_status->thread_control.step_resume_breakpoint->disposition
9425 = disp_del_at_next_stop;
9427 if (inf_status->thread_control.exception_resume_breakpoint)
9428 inf_status->thread_control.exception_resume_breakpoint->disposition
9429 = disp_del_at_next_stop;
9431 /* See save_infcall_control_state for info on stop_bpstat. */
9432 bpstat_clear (&inf_status->thread_control.stop_bpstat);
9434 delete inf_status;
9437 /* See infrun.h. */
9439 void
9440 clear_exit_convenience_vars (void)
9442 clear_internalvar (lookup_internalvar ("_exitsignal"));
9443 clear_internalvar (lookup_internalvar ("_exitcode"));
9447 /* User interface for reverse debugging:
9448 Set exec-direction / show exec-direction commands
9449 (returns error unless target implements to_set_exec_direction method). */
9451 enum exec_direction_kind execution_direction = EXEC_FORWARD;
9452 static const char exec_forward[] = "forward";
9453 static const char exec_reverse[] = "reverse";
9454 static const char *exec_direction = exec_forward;
9455 static const char *const exec_direction_names[] = {
9456 exec_forward,
9457 exec_reverse,
9458 nullptr
9461 static void
9462 set_exec_direction_func (const char *args, int from_tty,
9463 struct cmd_list_element *cmd)
9465 if (target_can_execute_reverse ())
9467 if (!strcmp (exec_direction, exec_forward))
9468 execution_direction = EXEC_FORWARD;
9469 else if (!strcmp (exec_direction, exec_reverse))
9470 execution_direction = EXEC_REVERSE;
9472 else
9474 exec_direction = exec_forward;
9475 error (_("Target does not support this operation."));
9479 static void
9480 show_exec_direction_func (struct ui_file *out, int from_tty,
9481 struct cmd_list_element *cmd, const char *value)
9483 switch (execution_direction) {
9484 case EXEC_FORWARD:
9485 gdb_printf (out, _("Forward.\n"));
9486 break;
9487 case EXEC_REVERSE:
9488 gdb_printf (out, _("Reverse.\n"));
9489 break;
9490 default:
9491 internal_error (_("bogus execution_direction value: %d"),
9492 (int) execution_direction);
9496 static void
9497 show_schedule_multiple (struct ui_file *file, int from_tty,
9498 struct cmd_list_element *c, const char *value)
9500 gdb_printf (file, _("Resuming the execution of threads "
9501 "of all processes is %s.\n"), value);
9504 /* Implementation of `siginfo' variable. */
9506 static const struct internalvar_funcs siginfo_funcs =
9508 siginfo_make_value,
9509 nullptr,
9512 /* Callback for infrun's target events source. This is marked when a
9513 thread has a pending status to process. */
9515 static void
9516 infrun_async_inferior_event_handler (gdb_client_data data)
9518 clear_async_event_handler (infrun_async_inferior_event_token);
9519 inferior_event_handler (INF_REG_EVENT);
9522 #if GDB_SELF_TEST
9523 namespace selftests
9526 /* Verify that when two threads with the same ptid exist (from two different
9527 targets) and one of them changes ptid, we only update inferior_ptid if
9528 it is appropriate. */
9530 static void
9531 infrun_thread_ptid_changed ()
9533 gdbarch *arch = current_inferior ()->gdbarch;
9535 /* The thread which inferior_ptid represents changes ptid. */
9537 scoped_restore_current_pspace_and_thread restore;
9539 scoped_mock_context<test_target_ops> target1 (arch);
9540 scoped_mock_context<test_target_ops> target2 (arch);
9542 ptid_t old_ptid (111, 222);
9543 ptid_t new_ptid (111, 333);
9545 target1.mock_inferior.pid = old_ptid.pid ();
9546 target1.mock_thread.ptid = old_ptid;
9547 target1.mock_inferior.ptid_thread_map.clear ();
9548 target1.mock_inferior.ptid_thread_map[old_ptid] = &target1.mock_thread;
9550 target2.mock_inferior.pid = old_ptid.pid ();
9551 target2.mock_thread.ptid = old_ptid;
9552 target2.mock_inferior.ptid_thread_map.clear ();
9553 target2.mock_inferior.ptid_thread_map[old_ptid] = &target2.mock_thread;
9555 auto restore_inferior_ptid = make_scoped_restore (&inferior_ptid, old_ptid);
9556 set_current_inferior (&target1.mock_inferior);
9558 thread_change_ptid (&target1.mock_target, old_ptid, new_ptid);
9560 gdb_assert (inferior_ptid == new_ptid);
9563 /* A thread with the same ptid as inferior_ptid, but from another target,
9564 changes ptid. */
9566 scoped_restore_current_pspace_and_thread restore;
9568 scoped_mock_context<test_target_ops> target1 (arch);
9569 scoped_mock_context<test_target_ops> target2 (arch);
9571 ptid_t old_ptid (111, 222);
9572 ptid_t new_ptid (111, 333);
9574 target1.mock_inferior.pid = old_ptid.pid ();
9575 target1.mock_thread.ptid = old_ptid;
9576 target1.mock_inferior.ptid_thread_map.clear ();
9577 target1.mock_inferior.ptid_thread_map[old_ptid] = &target1.mock_thread;
9579 target2.mock_inferior.pid = old_ptid.pid ();
9580 target2.mock_thread.ptid = old_ptid;
9581 target2.mock_inferior.ptid_thread_map.clear ();
9582 target2.mock_inferior.ptid_thread_map[old_ptid] = &target2.mock_thread;
9584 auto restore_inferior_ptid = make_scoped_restore (&inferior_ptid, old_ptid);
9585 set_current_inferior (&target2.mock_inferior);
9587 thread_change_ptid (&target1.mock_target, old_ptid, new_ptid);
9589 gdb_assert (inferior_ptid == old_ptid);
9593 } /* namespace selftests */
9595 #endif /* GDB_SELF_TEST */
9597 void _initialize_infrun ();
9598 void
9599 _initialize_infrun ()
9601 struct cmd_list_element *c;
9603 /* Register extra event sources in the event loop. */
9604 infrun_async_inferior_event_token
9605 = create_async_event_handler (infrun_async_inferior_event_handler, nullptr,
9606 "infrun");
9608 cmd_list_element *info_signals_cmd
9609 = add_info ("signals", info_signals_command, _("\
9610 What debugger does when program gets various signals.\n\
9611 Specify a signal as argument to print info on that signal only."));
9612 add_info_alias ("handle", info_signals_cmd, 0);
9614 c = add_com ("handle", class_run, handle_command, _("\
9615 Specify how to handle signals.\n\
9616 Usage: handle SIGNAL [ACTIONS]\n\
9617 Args are signals and actions to apply to those signals.\n\
9618 If no actions are specified, the current settings for the specified signals\n\
9619 will be displayed instead.\n\
9621 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
9622 from 1-15 are allowed for compatibility with old versions of GDB.\n\
9623 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
9624 The special arg \"all\" is recognized to mean all signals except those\n\
9625 used by the debugger, typically SIGTRAP and SIGINT.\n\
9627 Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
9628 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
9629 Stop means reenter debugger if this signal happens (implies print).\n\
9630 Print means print a message if this signal happens.\n\
9631 Pass means let program see this signal; otherwise program doesn't know.\n\
9632 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
9633 Pass and Stop may be combined.\n\
9635 Multiple signals may be specified. Signal numbers and signal names\n\
9636 may be interspersed with actions, with the actions being performed for\n\
9637 all signals cumulatively specified."));
9638 set_cmd_completer (c, handle_completer);
9640 stop_command = add_cmd ("stop", class_obscure,
9641 not_just_help_class_command, _("\
9642 There is no `stop' command, but you can set a hook on `stop'.\n\
9643 This allows you to set a list of commands to be run each time execution\n\
9644 of the program stops."), &cmdlist);
9646 add_setshow_boolean_cmd
9647 ("infrun", class_maintenance, &debug_infrun,
9648 _("Set inferior debugging."),
9649 _("Show inferior debugging."),
9650 _("When non-zero, inferior specific debugging is enabled."),
9651 nullptr, show_debug_infrun, &setdebuglist, &showdebuglist);
9653 add_setshow_boolean_cmd ("non-stop", no_class,
9654 &non_stop_1, _("\
9655 Set whether gdb controls the inferior in non-stop mode."), _("\
9656 Show whether gdb controls the inferior in non-stop mode."), _("\
9657 When debugging a multi-threaded program and this setting is\n\
9658 off (the default, also called all-stop mode), when one thread stops\n\
9659 (for a breakpoint, watchpoint, exception, or similar events), GDB stops\n\
9660 all other threads in the program while you interact with the thread of\n\
9661 interest. When you continue or step a thread, you can allow the other\n\
9662 threads to run, or have them remain stopped, but while you inspect any\n\
9663 thread's state, all threads stop.\n\
9665 In non-stop mode, when one thread stops, other threads can continue\n\
9666 to run freely. You'll be able to step each thread independently,\n\
9667 leave it stopped or free to run as needed."),
9668 set_non_stop,
9669 show_non_stop,
9670 &setlist,
9671 &showlist);
9673 for (size_t i = 0; i < GDB_SIGNAL_LAST; i++)
9675 signal_stop[i] = 1;
9676 signal_print[i] = 1;
9677 signal_program[i] = 1;
9678 signal_catch[i] = 0;
9681 /* Signals caused by debugger's own actions should not be given to
9682 the program afterwards.
9684 Do not deliver GDB_SIGNAL_TRAP by default, except when the user
9685 explicitly specifies that it should be delivered to the target
9686 program. Typically, that would occur when a user is debugging a
9687 target monitor on a simulator: the target monitor sets a
9688 breakpoint; the simulator encounters this breakpoint and halts
9689 the simulation handing control to GDB; GDB, noting that the stop
9690 address doesn't map to any known breakpoint, returns control back
9691 to the simulator; the simulator then delivers the hardware
9692 equivalent of a GDB_SIGNAL_TRAP to the program being
9693 debugged. */
9694 signal_program[GDB_SIGNAL_TRAP] = 0;
9695 signal_program[GDB_SIGNAL_INT] = 0;
9697 /* Signals that are not errors should not normally enter the debugger. */
9698 signal_stop[GDB_SIGNAL_ALRM] = 0;
9699 signal_print[GDB_SIGNAL_ALRM] = 0;
9700 signal_stop[GDB_SIGNAL_VTALRM] = 0;
9701 signal_print[GDB_SIGNAL_VTALRM] = 0;
9702 signal_stop[GDB_SIGNAL_PROF] = 0;
9703 signal_print[GDB_SIGNAL_PROF] = 0;
9704 signal_stop[GDB_SIGNAL_CHLD] = 0;
9705 signal_print[GDB_SIGNAL_CHLD] = 0;
9706 signal_stop[GDB_SIGNAL_IO] = 0;
9707 signal_print[GDB_SIGNAL_IO] = 0;
9708 signal_stop[GDB_SIGNAL_POLL] = 0;
9709 signal_print[GDB_SIGNAL_POLL] = 0;
9710 signal_stop[GDB_SIGNAL_URG] = 0;
9711 signal_print[GDB_SIGNAL_URG] = 0;
9712 signal_stop[GDB_SIGNAL_WINCH] = 0;
9713 signal_print[GDB_SIGNAL_WINCH] = 0;
9714 signal_stop[GDB_SIGNAL_PRIO] = 0;
9715 signal_print[GDB_SIGNAL_PRIO] = 0;
9717 /* These signals are used internally by user-level thread
9718 implementations. (See signal(5) on Solaris.) Like the above
9719 signals, a healthy program receives and handles them as part of
9720 its normal operation. */
9721 signal_stop[GDB_SIGNAL_LWP] = 0;
9722 signal_print[GDB_SIGNAL_LWP] = 0;
9723 signal_stop[GDB_SIGNAL_WAITING] = 0;
9724 signal_print[GDB_SIGNAL_WAITING] = 0;
9725 signal_stop[GDB_SIGNAL_CANCEL] = 0;
9726 signal_print[GDB_SIGNAL_CANCEL] = 0;
9727 signal_stop[GDB_SIGNAL_LIBRT] = 0;
9728 signal_print[GDB_SIGNAL_LIBRT] = 0;
9730 /* Update cached state. */
9731 signal_cache_update (-1);
9733 add_setshow_zinteger_cmd ("stop-on-solib-events", class_support,
9734 &stop_on_solib_events, _("\
9735 Set stopping for shared library events."), _("\
9736 Show stopping for shared library events."), _("\
9737 If nonzero, gdb will give control to the user when the dynamic linker\n\
9738 notifies gdb of shared library events. The most common event of interest\n\
9739 to the user would be loading/unloading of a new library."),
9740 set_stop_on_solib_events,
9741 show_stop_on_solib_events,
9742 &setlist, &showlist);
9744 add_setshow_enum_cmd ("follow-fork-mode", class_run,
9745 follow_fork_mode_kind_names,
9746 &follow_fork_mode_string, _("\
9747 Set debugger response to a program call of fork or vfork."), _("\
9748 Show debugger response to a program call of fork or vfork."), _("\
9749 A fork or vfork creates a new process. follow-fork-mode can be:\n\
9750 parent - the original process is debugged after a fork\n\
9751 child - the new process is debugged after a fork\n\
9752 The unfollowed process will continue to run.\n\
9753 By default, the debugger will follow the parent process."),
9754 nullptr,
9755 show_follow_fork_mode_string,
9756 &setlist, &showlist);
9758 add_setshow_enum_cmd ("follow-exec-mode", class_run,
9759 follow_exec_mode_names,
9760 &follow_exec_mode_string, _("\
9761 Set debugger response to a program call of exec."), _("\
9762 Show debugger response to a program call of exec."), _("\
9763 An exec call replaces the program image of a process.\n\
9765 follow-exec-mode can be:\n\
9767 new - the debugger creates a new inferior and rebinds the process\n\
9768 to this new inferior. The program the process was running before\n\
9769 the exec call can be restarted afterwards by restarting the original\n\
9770 inferior.\n\
9772 same - the debugger keeps the process bound to the same inferior.\n\
9773 The new executable image replaces the previous executable loaded in\n\
9774 the inferior. Restarting the inferior after the exec call restarts\n\
9775 the executable the process was running after the exec call.\n\
9777 By default, the debugger will use the same inferior."),
9778 nullptr,
9779 show_follow_exec_mode_string,
9780 &setlist, &showlist);
9782 add_setshow_enum_cmd ("scheduler-locking", class_run,
9783 scheduler_enums, &scheduler_mode, _("\
9784 Set mode for locking scheduler during execution."), _("\
9785 Show mode for locking scheduler during execution."), _("\
9786 off == no locking (threads may preempt at any time)\n\
9787 on == full locking (no thread except the current thread may run)\n\
9788 This applies to both normal execution and replay mode.\n\
9789 step == scheduler locked during stepping commands (step, next, stepi, nexti).\n\
9790 In this mode, other threads may run during other commands.\n\
9791 This applies to both normal execution and replay mode.\n\
9792 replay == scheduler locked in replay mode and unlocked during normal execution."),
9793 set_schedlock_func, /* traps on target vector */
9794 show_scheduler_mode,
9795 &setlist, &showlist);
9797 add_setshow_boolean_cmd ("schedule-multiple", class_run, &sched_multi, _("\
9798 Set mode for resuming threads of all processes."), _("\
9799 Show mode for resuming threads of all processes."), _("\
9800 When on, execution commands (such as 'continue' or 'next') resume all\n\
9801 threads of all processes. When off (which is the default), execution\n\
9802 commands only resume the threads of the current process. The set of\n\
9803 threads that are resumed is further refined by the scheduler-locking\n\
9804 mode (see help set scheduler-locking)."),
9805 nullptr,
9806 show_schedule_multiple,
9807 &setlist, &showlist);
9809 add_setshow_boolean_cmd ("step-mode", class_run, &step_stop_if_no_debug, _("\
9810 Set mode of the step operation."), _("\
9811 Show mode of the step operation."), _("\
9812 When set, doing a step over a function without debug line information\n\
9813 will stop at the first instruction of that function. Otherwise, the\n\
9814 function is skipped and the step command stops at a different source line."),
9815 nullptr,
9816 show_step_stop_if_no_debug,
9817 &setlist, &showlist);
9819 add_setshow_auto_boolean_cmd ("displaced-stepping", class_run,
9820 &can_use_displaced_stepping, _("\
9821 Set debugger's willingness to use displaced stepping."), _("\
9822 Show debugger's willingness to use displaced stepping."), _("\
9823 If on, gdb will use displaced stepping to step over breakpoints if it is\n\
9824 supported by the target architecture. If off, gdb will not use displaced\n\
9825 stepping to step over breakpoints, even if such is supported by the target\n\
9826 architecture. If auto (which is the default), gdb will use displaced stepping\n\
9827 if the target architecture supports it and non-stop mode is active, but will not\n\
9828 use it in all-stop mode (see help set non-stop)."),
9829 nullptr,
9830 show_can_use_displaced_stepping,
9831 &setlist, &showlist);
9833 add_setshow_enum_cmd ("exec-direction", class_run, exec_direction_names,
9834 &exec_direction, _("Set direction of execution.\n\
9835 Options are 'forward' or 'reverse'."),
9836 _("Show direction of execution (forward/reverse)."),
9837 _("Tells gdb whether to execute forward or backward."),
9838 set_exec_direction_func, show_exec_direction_func,
9839 &setlist, &showlist);
9841 /* Set/show detach-on-fork: user-settable mode. */
9843 add_setshow_boolean_cmd ("detach-on-fork", class_run, &detach_fork, _("\
9844 Set whether gdb will detach the child of a fork."), _("\
9845 Show whether gdb will detach the child of a fork."), _("\
9846 Tells gdb whether to detach the child of a fork."),
9847 nullptr, nullptr, &setlist, &showlist);
9849 /* Set/show disable address space randomization mode. */
9851 add_setshow_boolean_cmd ("disable-randomization", class_support,
9852 &disable_randomization, _("\
9853 Set disabling of debuggee's virtual address space randomization."), _("\
9854 Show disabling of debuggee's virtual address space randomization."), _("\
9855 When this mode is on (which is the default), randomization of the virtual\n\
9856 address space is disabled. Standalone programs run with the randomization\n\
9857 enabled by default on some platforms."),
9858 &set_disable_randomization,
9859 &show_disable_randomization,
9860 &setlist, &showlist);
9862 /* ptid initializations */
9863 inferior_ptid = null_ptid;
9864 target_last_wait_ptid = minus_one_ptid;
9866 gdb::observers::thread_ptid_changed.attach (infrun_thread_ptid_changed,
9867 "infrun");
9868 gdb::observers::thread_stop_requested.attach (infrun_thread_stop_requested,
9869 "infrun");
9870 gdb::observers::thread_exit.attach (infrun_thread_thread_exit, "infrun");
9871 gdb::observers::inferior_exit.attach (infrun_inferior_exit, "infrun");
9872 gdb::observers::inferior_execd.attach (infrun_inferior_execd, "infrun");
9874 /* Explicitly create without lookup, since that tries to create a
9875 value with a void typed value, and when we get here, gdbarch
9876 isn't initialized yet. At this point, we're quite sure there
9877 isn't another convenience variable of the same name. */
9878 create_internalvar_type_lazy ("_siginfo", &siginfo_funcs, nullptr);
9880 add_setshow_boolean_cmd ("observer", no_class,
9881 &observer_mode_1, _("\
9882 Set whether gdb controls the inferior in observer mode."), _("\
9883 Show whether gdb controls the inferior in observer mode."), _("\
9884 In observer mode, GDB can get data from the inferior, but not\n\
9885 affect its execution. Registers and memory may not be changed,\n\
9886 breakpoints may not be set, and the program cannot be interrupted\n\
9887 or signalled."),
9888 set_observer_mode,
9889 show_observer_mode,
9890 &setlist,
9891 &showlist);
9893 #if GDB_SELF_TEST
9894 selftests::register_test ("infrun_thread_ptid_changed",
9895 selftests::infrun_thread_ptid_changed);
9896 #endif