1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2025 Free Software Foundation, Inc.
5 Contributed by Lynx Real-Time Systems, Inc. Los Gatos, CA.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
26 #include "gdbsupport/environ.h"
30 #include "gdbthread.h"
32 #include "cli/cli-cmds.h"
37 #include <sys/types.h>
40 #include "observable.h"
42 #include "cli/cli-decode.h"
43 #include "cli/cli-option.h"
44 #include "gdbsupport/gdb_regex.h"
45 #include "cli/cli-utils.h"
46 #include "thread-fsm.h"
47 #include "tid-parse.h"
50 #include "inline-frame.h"
53 #include "record-full.h"
55 /* See gdbthread.h. */
57 bool debug_threads
= false;
59 /* Implement 'show debug threads'. */
62 show_debug_threads (struct ui_file
*file
, int from_tty
,
63 struct cmd_list_element
*c
, const char *value
)
65 gdb_printf (file
, _("Thread debugging is \"%s\".\n"), value
);
68 /* Definition of struct thread_info exported to gdbthread.h. */
70 /* Prototypes for local functions. */
72 static int highest_thread_num
;
74 /* The current/selected thread. */
75 static thread_info
*current_thread_
;
77 /* Returns true if THR is the current thread. */
80 is_current_thread (const thread_info
*thr
)
82 return thr
== current_thread_
;
86 inferior_thread (void)
88 gdb_assert (current_thread_
!= nullptr);
89 return current_thread_
;
92 /* Delete the breakpoint pointed at by BP_P, if there's one. */
95 delete_thread_breakpoint (struct breakpoint
**bp_p
)
99 delete_breakpoint (*bp_p
);
105 delete_step_resume_breakpoint (struct thread_info
*tp
)
108 delete_thread_breakpoint (&tp
->control
.step_resume_breakpoint
);
112 delete_exception_resume_breakpoint (struct thread_info
*tp
)
115 delete_thread_breakpoint (&tp
->control
.exception_resume_breakpoint
);
118 /* See gdbthread.h. */
121 delete_single_step_breakpoints (struct thread_info
*tp
)
124 delete_thread_breakpoint (&tp
->control
.single_step_breakpoints
);
127 /* Delete the breakpoint pointed at by BP_P at the next stop, if
131 delete_at_next_stop (struct breakpoint
**bp
)
135 (*bp
)->disposition
= disp_del_at_next_stop
;
140 /* See gdbthread.h. */
143 thread_has_single_step_breakpoints_set (struct thread_info
*tp
)
145 return tp
->control
.single_step_breakpoints
!= NULL
;
148 /* See gdbthread.h. */
151 thread_has_single_step_breakpoint_here (struct thread_info
*tp
,
152 const address_space
*aspace
,
155 struct breakpoint
*ss_bps
= tp
->control
.single_step_breakpoints
;
157 return (ss_bps
!= NULL
158 && breakpoint_has_location_inserted_here (ss_bps
, aspace
, addr
));
161 /* See gdbthread.h. */
164 thread_cancel_execution_command (struct thread_info
*thr
)
166 if (thr
->thread_fsm () != nullptr)
168 std::unique_ptr
<thread_fsm
> fsm
= thr
->release_thread_fsm ();
174 clear_thread_inferior_resources (struct thread_info
*tp
)
176 /* NOTE: this will take care of any left-over step_resume breakpoints,
177 but not any user-specified thread-specific breakpoints. We can not
178 delete the breakpoint straight-off, because the inferior might not
179 be stopped at the moment. */
180 delete_at_next_stop (&tp
->control
.step_resume_breakpoint
);
181 delete_at_next_stop (&tp
->control
.exception_resume_breakpoint
);
182 delete_at_next_stop (&tp
->control
.single_step_breakpoints
);
184 delete_longjmp_breakpoint_at_next_stop (tp
->global_num
);
186 bpstat_clear (&tp
->control
.stop_bpstat
);
188 btrace_teardown (tp
);
190 thread_cancel_execution_command (tp
);
192 clear_inline_frame_state (tp
);
195 /* Notify interpreters and observers that thread T has exited. */
198 notify_thread_exited (thread_info
*t
, std::optional
<ULONGEST
> exit_code
,
201 if (!silent
&& print_thread_events
)
203 if (exit_code
.has_value ())
204 gdb_printf (_("[%s exited with code %s]\n"),
205 target_pid_to_str (t
->ptid
).c_str (),
206 pulongest (*exit_code
));
208 gdb_printf (_("[%s exited]\n"),
209 target_pid_to_str (t
->ptid
).c_str ());
212 interps_notify_thread_exited (t
, exit_code
, silent
);
213 gdb::observers::thread_exit
.notify (t
, exit_code
, silent
);
216 /* See gdbthread.h. */
219 set_thread_exited (thread_info
*tp
, std::optional
<ULONGEST
> exit_code
,
222 /* Dead threads don't need to step-over. Remove from chain. */
223 if (thread_is_in_step_over_chain (tp
))
224 global_thread_step_over_chain_remove (tp
);
226 if (tp
->state
!= THREAD_EXITED
)
228 process_stratum_target
*proc_target
= tp
->inf
->process_target ();
230 /* Some targets unpush themselves from the inferior's target stack before
231 clearing the inferior's thread list (which marks all threads as exited,
232 and therefore leads to this function). In this case, the inferior's
233 process target will be nullptr when we arrive here.
235 See also the comment in inferior::unpush_target. */
236 if (proc_target
!= nullptr)
237 proc_target
->maybe_remove_resumed_with_pending_wait_status (tp
);
239 notify_thread_exited (tp
, exit_code
, silent
);
241 /* Tag it as exited. */
242 tp
->state
= THREAD_EXITED
;
244 /* Clear breakpoints, etc. associated with this thread. */
245 clear_thread_inferior_resources (tp
);
247 /* Remove from the ptid_t map. We don't want for
248 inferior::find_thread to find exited threads. Also, the target
249 may reuse the ptid for a new thread, and there can only be
250 one value per key; adding a new thread with the same ptid_t
251 would overwrite the exited thread's ptid entry. */
252 size_t nr_deleted
= tp
->inf
->ptid_thread_map
.erase (tp
->ptid
);
253 gdb_assert (nr_deleted
== 1);
258 init_thread_list (void)
260 highest_thread_num
= 0;
262 for (inferior
*inf
: all_inferiors ())
263 inf
->clear_thread_list ();
266 /* Allocate a new thread of inferior INF with target id PTID and add
267 it to the thread list. */
269 static struct thread_info
*
270 new_thread (struct inferior
*inf
, ptid_t ptid
)
272 thread_info
*tp
= new thread_info (inf
, ptid
);
274 threads_debug_printf ("creating a new thread object, inferior %d, ptid %s",
275 inf
->num
, ptid
.to_string ().c_str ());
277 inf
->thread_list
.push_back (*tp
);
279 /* A thread with this ptid should not exist in the map yet. */
280 gdb_assert (inf
->ptid_thread_map
.find (ptid
) == inf
->ptid_thread_map
.end ());
282 inf
->ptid_thread_map
[ptid
] = tp
;
287 /* Notify interpreters and observers that thread T has been created. */
290 notify_new_thread (thread_info
*t
)
292 interps_notify_new_thread (t
);
293 gdb::observers::new_thread
.notify (t
);
297 add_thread_silent (process_stratum_target
*targ
, ptid_t ptid
)
299 gdb_assert (targ
!= nullptr);
301 inferior
*inf
= find_inferior_ptid (targ
, ptid
);
303 threads_debug_printf ("add thread to inferior %d, ptid %s, target %s",
304 inf
->num
, ptid
.to_string ().c_str (),
307 /* We may have an old thread with the same id in the thread list.
308 If we do, it must be dead, otherwise we wouldn't be adding a new
309 thread with the same id. The OS is reusing this id --- delete
310 the old thread, and create a new one. */
311 thread_info
*tp
= inf
->find_thread (ptid
);
315 tp
= new_thread (inf
, ptid
);
316 notify_new_thread (tp
);
322 add_thread_with_info (process_stratum_target
*targ
, ptid_t ptid
,
323 private_thread_info_up priv
)
325 thread_info
*result
= add_thread_silent (targ
, ptid
);
327 result
->priv
= std::move (priv
);
329 if (print_thread_events
)
330 gdb_printf (_("[New %s]\n"), target_pid_to_str (ptid
).c_str ());
332 annotate_new_thread ();
337 add_thread (process_stratum_target
*targ
, ptid_t ptid
)
339 return add_thread_with_info (targ
, ptid
, NULL
);
342 private_thread_info::~private_thread_info () = default;
344 thread_info::thread_info (struct inferior
*inf_
, ptid_t ptid_
)
345 : ptid (ptid_
), inf (inf_
)
347 gdb_assert (inf_
!= NULL
);
349 this->global_num
= ++highest_thread_num
;
350 this->per_inf_num
= ++inf_
->highest_thread_num
;
352 /* Nothing to follow yet. */
353 this->pending_follow
.set_spurious ();
356 /* See gdbthread.h. */
358 thread_info::~thread_info ()
360 threads_debug_printf ("thread %s", this->ptid
.to_string ().c_str ());
363 /* See gdbthread.h. */
366 thread_info::deletable () const
368 /* If this is the current thread, or there's code out there that
369 relies on it existing (refcount > 0) we can't delete yet. */
370 return refcount () == 0 && !is_current_thread (this);
373 /* See gdbthread.h. */
376 thread_info::set_executing (bool executing
)
378 m_executing
= executing
;
380 this->clear_stop_pc ();
383 /* See gdbthread.h. */
386 thread_info::set_resumed (bool resumed
)
388 if (resumed
== m_resumed
)
391 process_stratum_target
*proc_target
= this->inf
->process_target ();
393 /* If we transition from resumed to not resumed, we might need to remove
394 the thread from the resumed threads with pending statuses list. */
396 proc_target
->maybe_remove_resumed_with_pending_wait_status (this);
400 /* If we transition from not resumed to resumed, we might need to add
401 the thread to the resumed threads with pending statuses list. */
403 proc_target
->maybe_add_resumed_with_pending_wait_status (this);
406 /* See gdbthread.h. */
409 thread_info::set_pending_waitstatus (const target_waitstatus
&ws
)
411 gdb_assert (!this->has_pending_waitstatus ());
413 m_suspend
.waitstatus
= ws
;
414 m_suspend
.waitstatus_pending_p
= 1;
416 process_stratum_target
*proc_target
= this->inf
->process_target ();
417 proc_target
->maybe_add_resumed_with_pending_wait_status (this);
420 /* See gdbthread.h. */
423 thread_info::clear_pending_waitstatus ()
425 gdb_assert (this->has_pending_waitstatus ());
427 process_stratum_target
*proc_target
= this->inf
->process_target ();
428 proc_target
->maybe_remove_resumed_with_pending_wait_status (this);
430 m_suspend
.waitstatus_pending_p
= 0;
433 /* See gdbthread.h. */
436 thread_info::set_thread_options (gdb_thread_options thread_options
)
438 gdb_assert (this->state
!= THREAD_EXITED
);
439 gdb_assert (!this->executing ());
441 if (m_thread_options
== thread_options
)
444 m_thread_options
= thread_options
;
446 infrun_debug_printf ("[options for %s are now %s]",
447 this->ptid
.to_string ().c_str (),
448 to_string (thread_options
).c_str ());
451 /* See gdbthread.h. */
454 thread_is_in_step_over_chain (struct thread_info
*tp
)
456 return tp
->step_over_list_node
.is_linked ();
459 /* See gdbthread.h. */
462 thread_step_over_chain_length (const thread_step_over_list
&l
)
466 for (const thread_info
&thread ATTRIBUTE_UNUSED
: l
)
472 /* See gdbthread.h. */
475 global_thread_step_over_chain_enqueue (struct thread_info
*tp
)
477 infrun_debug_printf ("enqueueing thread %s in global step over chain",
478 tp
->ptid
.to_string ().c_str ());
480 gdb_assert (!thread_is_in_step_over_chain (tp
));
481 global_thread_step_over_list
.push_back (*tp
);
484 /* See gdbthread.h. */
487 global_thread_step_over_chain_enqueue_chain (thread_step_over_list
&&list
)
489 global_thread_step_over_list
.splice (std::move (list
));
492 /* See gdbthread.h. */
495 global_thread_step_over_chain_remove (struct thread_info
*tp
)
497 infrun_debug_printf ("removing thread %s from global step over chain",
498 tp
->ptid
.to_string ().c_str ());
500 gdb_assert (thread_is_in_step_over_chain (tp
));
501 auto it
= global_thread_step_over_list
.iterator_to (*tp
);
502 global_thread_step_over_list
.erase (it
);
505 /* Helper for the different delete_thread variants. */
508 delete_thread_1 (thread_info
*thr
, std::optional
<ULONGEST
> exit_code
,
511 gdb_assert (thr
!= nullptr);
513 threads_debug_printf ("deleting thread %s, exit_code = %s, silent = %d",
514 thr
->ptid
.to_string ().c_str (),
515 (exit_code
.has_value ()
516 ? pulongest (*exit_code
)
520 set_thread_exited (thr
, exit_code
, silent
);
522 if (!thr
->deletable ())
524 /* Will be really deleted some other time. */
528 auto it
= thr
->inf
->thread_list
.iterator_to (*thr
);
529 thr
->inf
->thread_list
.erase (it
);
531 gdb::observers::thread_deleted
.notify (thr
);
536 /* See gdbthread.h. */
539 delete_thread_with_exit_code (thread_info
*thread
, ULONGEST exit_code
,
542 delete_thread_1 (thread
, exit_code
, silent
);
545 /* See gdbthread.h. */
548 delete_thread (thread_info
*thread
)
550 delete_thread_1 (thread
, {}, false /* not silent */);
554 delete_thread_silent (thread_info
*thread
)
556 delete_thread_1 (thread
, {}, true /* not silent */);
560 find_thread_global_id (int global_id
)
562 for (thread_info
*tp
: all_threads ())
563 if (tp
->global_num
== global_id
)
569 static struct thread_info
*
570 find_thread_id (struct inferior
*inf
, int thr_num
)
572 for (thread_info
*tp
: inf
->threads ())
573 if (tp
->per_inf_num
== thr_num
)
579 /* See gdbthread.h. */
582 find_thread_by_handle (gdb::array_view
<const gdb_byte
> handle
,
583 struct inferior
*inf
)
585 return target_thread_handle_to_thread_info (handle
.data (),
591 * Thread iterator function.
593 * Calls a callback function once for each thread, so long as
594 * the callback function returns false. If the callback function
595 * returns true, the iteration will end and the current thread
596 * will be returned. This can be useful for implementing a
597 * search for a thread with arbitrary attributes, or for applying
598 * some operation to every thread.
600 * FIXME: some of the existing functionality, such as
601 * "Thread apply all", might be rewritten using this functionality.
605 iterate_over_threads (gdb::function_view
<bool (struct thread_info
*)> callback
)
607 for (thread_info
*tp
: all_threads_safe ())
614 /* See gdbthread.h. */
619 for (thread_info
*tp ATTRIBUTE_UNUSED
: all_threads ())
625 thread_count (process_stratum_target
*proc_target
)
627 auto rng
= all_threads (proc_target
);
628 return std::distance (rng
.begin (), rng
.end ());
631 /* Return the number of non-exited threads in the thread list. */
634 live_threads_count (void)
636 auto rng
= all_non_exited_threads ();
637 return std::distance (rng
.begin (), rng
.end ());
641 valid_global_thread_id (int global_id
)
643 for (thread_info
*tp
: all_threads ())
644 if (tp
->global_num
== global_id
)
651 in_thread_list (process_stratum_target
*targ
, ptid_t ptid
)
653 return targ
->find_thread (ptid
) != nullptr;
656 /* Finds the first thread of the inferior. */
659 first_thread_of_inferior (inferior
*inf
)
661 if (inf
->thread_list
.empty ())
664 return &inf
->thread_list
.front ();
668 any_thread_of_inferior (inferior
*inf
)
670 gdb_assert (inf
->pid
!= 0);
672 /* Prefer the current thread, if there's one. */
673 if (inf
== current_inferior () && inferior_ptid
!= null_ptid
)
674 return inferior_thread ();
676 for (thread_info
*tp
: inf
->non_exited_threads ())
683 any_live_thread_of_inferior (inferior
*inf
)
685 struct thread_info
*curr_tp
= NULL
;
686 struct thread_info
*tp_executing
= NULL
;
688 gdb_assert (inf
!= NULL
&& inf
->pid
!= 0);
690 /* Prefer the current thread if it's not executing. */
691 if (inferior_ptid
!= null_ptid
&& current_inferior () == inf
)
693 /* If the current thread is dead, forget it. If it's not
694 executing, use it. Otherwise, still choose it (below), but
695 only if no other non-executing thread is found. */
696 curr_tp
= inferior_thread ();
697 if (curr_tp
->state
== THREAD_EXITED
)
699 else if (!curr_tp
->executing ())
703 for (thread_info
*tp
: inf
->non_exited_threads ())
705 if (!tp
->executing ())
711 /* If both the current thread and all live threads are executing,
712 prefer the current thread. */
716 /* Otherwise, just return an executing thread, if any. */
720 /* Return true if TP is an active thread. */
722 thread_alive (thread_info
*tp
)
724 if (tp
->state
== THREAD_EXITED
)
727 /* Ensure we're looking at the right target stack. */
728 gdb_assert (tp
->inf
== current_inferior ());
730 return target_thread_alive (tp
->ptid
);
733 /* See gdbthreads.h. */
736 switch_to_thread_if_alive (thread_info
*thr
)
738 scoped_restore_current_thread restore_thread
;
740 /* Switch inferior first, so that we're looking at the right target
742 switch_to_inferior_no_thread (thr
->inf
);
744 if (thread_alive (thr
))
746 switch_to_thread (thr
);
747 restore_thread
.dont_restore ();
754 /* See gdbthreads.h. */
759 scoped_restore_current_thread restore_thread
;
761 for (thread_info
*tp
: all_threads_safe ())
763 switch_to_inferior_no_thread (tp
->inf
);
765 if (!thread_alive (tp
))
770 /* See gdbthreads.h. */
773 delete_exited_threads (void)
775 for (thread_info
*tp
: all_threads_safe ())
776 if (tp
->state
== THREAD_EXITED
)
780 /* Return true value if stack temporaries are enabled for the thread
784 thread_stack_temporaries_enabled_p (thread_info
*tp
)
789 return tp
->stack_temporaries_enabled
;
792 /* Push V on to the stack temporaries of the thread with id PTID. */
795 push_thread_stack_temporary (thread_info
*tp
, struct value
*v
)
797 gdb_assert (tp
!= NULL
&& tp
->stack_temporaries_enabled
);
798 tp
->stack_temporaries
.push_back (v
);
801 /* Return true if VAL is among the stack temporaries of the thread
802 TP. Return false otherwise. */
805 value_in_thread_stack_temporaries (struct value
*val
, thread_info
*tp
)
807 gdb_assert (tp
!= NULL
&& tp
->stack_temporaries_enabled
);
808 for (value
*v
: tp
->stack_temporaries
)
815 /* Return the last of the stack temporaries for thread with id PTID.
816 Return NULL if there are no stack temporaries for the thread. */
819 get_last_thread_stack_temporary (thread_info
*tp
)
821 struct value
*lastval
= NULL
;
823 gdb_assert (tp
!= NULL
);
824 if (!tp
->stack_temporaries
.empty ())
825 lastval
= tp
->stack_temporaries
.back ();
831 thread_change_ptid (process_stratum_target
*targ
,
832 ptid_t old_ptid
, ptid_t new_ptid
)
834 struct inferior
*inf
;
835 struct thread_info
*tp
;
837 /* It can happen that what we knew as the target inferior id
838 changes. E.g, target remote may only discover the remote process
839 pid after adding the inferior to GDB's list. */
840 inf
= find_inferior_ptid (targ
, old_ptid
);
841 inf
->pid
= new_ptid
.pid ();
843 tp
= inf
->find_thread (old_ptid
);
844 gdb_assert (tp
!= nullptr);
846 int num_erased
= inf
->ptid_thread_map
.erase (old_ptid
);
847 gdb_assert (num_erased
== 1);
850 inf
->ptid_thread_map
[new_ptid
] = tp
;
852 gdb::observers::thread_ptid_changed
.notify (targ
, old_ptid
, new_ptid
);
855 /* See gdbthread.h. */
858 set_resumed (process_stratum_target
*targ
, ptid_t ptid
, bool resumed
)
860 for (thread_info
*tp
: all_non_exited_threads (targ
, ptid
))
861 tp
->set_resumed (resumed
);
864 /* Helper for set_running, that marks one thread either running or
868 set_running_thread (struct thread_info
*tp
, bool running
)
870 bool started
= false;
872 if (running
&& tp
->state
== THREAD_STOPPED
)
874 tp
->state
= running
? THREAD_RUNNING
: THREAD_STOPPED
;
876 threads_debug_printf ("thread: %s, running? %d%s",
877 tp
->ptid
.to_string ().c_str (), running
,
878 (started
? " (started)" : ""));
882 /* If the thread is now marked stopped, remove it from
883 the step-over queue, so that we don't try to resume
884 it until the user wants it to. */
885 if (thread_is_in_step_over_chain (tp
))
886 global_thread_step_over_chain_remove (tp
);
892 /* Notify interpreters and observers that the target was resumed. */
895 notify_target_resumed (ptid_t ptid
)
897 interps_notify_target_resumed (ptid
);
898 gdb::observers::target_resumed
.notify (ptid
);
900 /* We are about to resume the inferior. Close all cached BFDs so that
901 when the inferior next stops, and GDB regains control, we will spot
902 any on-disk changes to the BFDs we are using. */
903 bfd_cache_close_all ();
906 /* See gdbthread.h. */
909 thread_info::set_running (bool running
)
911 if (set_running_thread (this, running
))
912 notify_target_resumed (this->ptid
);
916 set_running (process_stratum_target
*targ
, ptid_t ptid
, bool running
)
918 /* We try not to notify the observer if no thread has actually
919 changed the running state -- merely to reduce the number of
920 messages to the MI frontend. A frontend is supposed to handle
921 multiple *running notifications just fine. */
922 bool any_started
= false;
924 for (thread_info
*tp
: all_non_exited_threads (targ
, ptid
))
925 if (set_running_thread (tp
, running
))
929 notify_target_resumed (ptid
);
933 set_executing (process_stratum_target
*targ
, ptid_t ptid
, bool executing
)
935 for (thread_info
*tp
: all_non_exited_threads (targ
, ptid
))
936 tp
->set_executing (executing
);
938 /* It only takes one running thread to spawn more threads. */
940 targ
->threads_executing
= true;
941 /* Only clear the flag if the caller is telling us everything is
943 else if (minus_one_ptid
== ptid
)
944 targ
->threads_executing
= false;
947 /* See gdbthread.h. */
950 threads_are_executing (process_stratum_target
*target
)
952 return target
->threads_executing
;
956 set_stop_requested (process_stratum_target
*targ
, ptid_t ptid
, bool stop
)
958 for (thread_info
*tp
: all_non_exited_threads (targ
, ptid
))
959 tp
->stop_requested
= stop
;
961 /* Call the stop requested observer so other components of GDB can
962 react to this request. */
964 gdb::observers::thread_stop_requested
.notify (ptid
);
968 finish_thread_state (process_stratum_target
*targ
, ptid_t ptid
)
970 bool any_started
= false;
972 for (thread_info
*tp
: all_non_exited_threads (targ
, ptid
))
973 if (set_running_thread (tp
, tp
->executing ()))
977 notify_target_resumed (ptid
);
980 /* See gdbthread.h. */
983 validate_registers_access (void)
985 /* No selected thread, no registers. */
986 if (inferior_ptid
== null_ptid
)
987 error (_("No thread selected."));
989 thread_info
*tp
= inferior_thread ();
991 /* Don't try to read from a dead thread. */
992 if (tp
->state
== THREAD_EXITED
)
993 error (_("The current thread has terminated"));
995 /* ... or from a spinning thread. FIXME: This isn't actually fully
996 correct. It'll allow an user-requested access (e.g., "print $pc"
997 at the prompt) when a thread is not executing for some internal
998 reason, but is marked running from the user's perspective. E.g.,
999 the thread is waiting for its turn in the step-over queue. */
1000 if (tp
->executing ())
1002 /* If we are replaying with the record-full subsystem, even though
1003 the thread is executing, it is always safe to read from it since
1004 replay execution is just GDB reading and writing to a regcache. */
1005 if (!record_full_is_replaying ())
1006 error (_("Selected thread is running."));
1010 /* See gdbthread.h. */
1013 can_access_registers_thread (thread_info
*thread
)
1015 /* No thread, no registers. */
1019 /* Don't try to read from a dead thread. */
1020 if (thread
->state
== THREAD_EXITED
)
1023 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
1024 if (thread
->executing ())
1026 /* See validate_registers_access. */
1027 if (!record_full_is_replaying ())
1035 pc_in_thread_step_range (CORE_ADDR pc
, struct thread_info
*thread
)
1037 return (pc
>= thread
->control
.step_range_start
1038 && pc
< thread
->control
.step_range_end
);
1041 /* The options for the "info threads" command. */
1043 struct info_threads_opts
1046 bool show_global_ids
= false;
1047 /* For "-running". */
1048 bool show_running_threads
= false;
1049 /* For "-stopped". */
1050 bool show_stopped_threads
= false;
1053 static const gdb::option::option_def info_threads_option_defs
[] = {
1055 gdb::option::flag_option_def
<info_threads_opts
> {
1057 [] (info_threads_opts
*opts
) { return &opts
->show_global_ids
; },
1058 N_("Show global thread IDs."),
1060 gdb::option::flag_option_def
<info_threads_opts
> {
1062 [] (info_threads_opts
*opts
) { return &opts
->show_running_threads
; },
1063 N_("Show running threads only."),
1065 gdb::option::flag_option_def
<info_threads_opts
> {
1067 [] (info_threads_opts
*opts
) { return &opts
->show_stopped_threads
; },
1068 N_("Show stopped threads only."),
1072 /* Helper for print_thread_info. Returns true if THR should be
1073 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
1074 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
1075 is true if REQUESTED_THREADS is list of global IDs, false if a list
1076 of per-inferior thread ids. If PID is not -1, only print THR if it
1077 is a thread from the process PID. Otherwise, threads from all
1078 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
1079 and PID is not -1, then the thread is printed if it belongs to the
1080 specified process. Otherwise, an error is raised. OPTS is the
1081 options of the "info threads" command. */
1084 should_print_thread (const char *requested_threads
,
1085 const info_threads_opts
&opts
, int default_inf_num
,
1086 int global_ids
, int pid
, thread_info
*thr
)
1088 if (requested_threads
!= NULL
&& *requested_threads
!= '\0')
1093 in_list
= number_is_in_list (requested_threads
, thr
->global_num
);
1095 in_list
= tid_is_in_list (requested_threads
, default_inf_num
,
1096 thr
->inf
->num
, thr
->per_inf_num
);
1101 if (pid
!= -1 && thr
->ptid
.pid () != pid
)
1103 if (requested_threads
!= NULL
&& *requested_threads
!= '\0')
1104 error (_("Requested thread not found in requested process"));
1108 if (thr
->state
== THREAD_EXITED
)
1111 bool is_stopped
= (thr
->state
== THREAD_STOPPED
);
1112 if (opts
.show_stopped_threads
&& is_stopped
)
1115 bool is_running
= (thr
->state
== THREAD_RUNNING
);
1116 if (opts
.show_running_threads
&& is_running
)
1119 /* If the user did not pass a filter flag, show the thread. */
1120 return (!opts
.show_stopped_threads
1121 && !opts
.show_running_threads
);
1124 /* Return the string to display in "info threads"'s "Target Id"
1128 thread_target_id_str (thread_info
*tp
)
1130 std::string target_id
= target_pid_to_str (tp
->ptid
);
1131 const char *extra_info
= target_extra_thread_info (tp
);
1132 const char *name
= thread_name (tp
);
1134 if (extra_info
!= nullptr && name
!= nullptr)
1135 return string_printf ("%s \"%s\" (%s)", target_id
.c_str (), name
,
1137 else if (extra_info
!= nullptr)
1138 return string_printf ("%s (%s)", target_id
.c_str (), extra_info
);
1139 else if (name
!= nullptr)
1140 return string_printf ("%s \"%s\"", target_id
.c_str (), name
);
1145 /* Print thread TP. GLOBAL_IDS indicates whether REQUESTED_THREADS
1146 is a list of global or per-inferior thread ids. */
1149 do_print_thread (ui_out
*uiout
, const char *requested_threads
,
1150 const info_threads_opts
&opts
, int global_ids
,
1151 int pid
, int default_inf_num
, thread_info
*tp
,
1152 thread_info
*current_thread
)
1156 /* In case REQUESTED_THREADS contains $_thread. */
1157 if (current_thread
!= nullptr)
1158 switch_to_thread (current_thread
);
1160 if (!should_print_thread (requested_threads
, opts
, default_inf_num
,
1161 global_ids
, pid
, tp
))
1164 ui_out_emit_tuple
tuple_emitter (uiout
, NULL
);
1166 if (!uiout
->is_mi_like_p ())
1168 if (tp
== current_thread
)
1169 uiout
->field_string ("current", "*");
1171 uiout
->field_skip ("current");
1173 uiout
->field_string ("id-in-tg", print_thread_id (tp
));
1176 if (opts
.show_global_ids
|| uiout
->is_mi_like_p ())
1177 uiout
->field_signed ("id", tp
->global_num
);
1179 /* Switch to the thread (and inferior / target). */
1180 switch_to_thread (tp
);
1182 /* For the CLI, we stuff everything into the target-id field.
1183 This is a gross hack to make the output come out looking
1184 correct. The underlying problem here is that ui-out has no
1185 way to specify that a field's space allocation should be
1186 shared by several fields. For MI, we do the right thing
1189 if (uiout
->is_mi_like_p ())
1191 uiout
->field_string ("target-id", target_pid_to_str (tp
->ptid
));
1193 const char *extra_info
= target_extra_thread_info (tp
);
1194 if (extra_info
!= nullptr)
1195 uiout
->field_string ("details", extra_info
);
1197 const char *name
= thread_name (tp
);
1199 uiout
->field_string ("name", name
);
1203 uiout
->field_string ("target-id", thread_target_id_str (tp
));
1206 if (tp
->state
== THREAD_RUNNING
)
1207 uiout
->text ("(running)\n");
1210 /* The switch above put us at the top of the stack (leaf
1212 print_stack_frame (get_selected_frame (NULL
),
1213 /* For MI output, print frame level. */
1214 uiout
->is_mi_like_p (),
1218 if (uiout
->is_mi_like_p ())
1220 const char *state
= "stopped";
1222 if (tp
->state
== THREAD_RUNNING
)
1224 uiout
->field_string ("state", state
);
1227 core
= target_core_of_thread (tp
->ptid
);
1228 if (uiout
->is_mi_like_p () && core
!= -1)
1229 uiout
->field_signed ("core", core
);
1232 /* Redirect output to a temporary buffer for the duration
1233 of do_print_thread. */
1236 print_thread (ui_out
*uiout
, const char *requested_threads
,
1237 const info_threads_opts
&opts
, int global_ids
, int pid
,
1238 int default_inf_num
, thread_info
*tp
, thread_info
*current_thread
)
1241 do_with_buffered_output (do_print_thread
, uiout
, requested_threads
,
1242 opts
, global_ids
, pid
, default_inf_num
, tp
,
1246 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1247 whether REQUESTED_THREADS is a list of global or per-inferior
1248 thread ids. OPTS is the options of the "info threads" command. */
1251 print_thread_info_1 (struct ui_out
*uiout
, const char *requested_threads
,
1252 const info_threads_opts
&opts
, int global_ids
, int pid
)
1254 int default_inf_num
= current_inferior ()->num
;
1256 update_thread_list ();
1258 /* Whether we saw any thread. */
1259 bool any_thread
= false;
1260 /* Whether the current thread is exited. */
1261 bool current_exited
= false;
1263 thread_info
*current_thread
= (inferior_ptid
!= null_ptid
1264 ? inferior_thread () : NULL
);
1267 /* For backward compatibility, we make a list for MI. A table is
1268 preferable for the CLI, though, because it shows table
1270 std::optional
<ui_out_emit_list
> list_emitter
;
1271 std::optional
<ui_out_emit_table
> table_emitter
;
1273 /* We'll be switching threads temporarily below. */
1274 scoped_restore_current_thread restore_thread
;
1276 if (uiout
->is_mi_like_p ())
1277 list_emitter
.emplace (uiout
, "threads");
1280 int n_matching_threads
= 0;
1281 /* The width of the "Target Id" column. Grown below to
1282 accommodate the largest entry. */
1283 size_t target_id_col_width
= 17;
1285 for (thread_info
*tp
: all_threads ())
1289 /* In case REQUESTED_THREADS contains $_thread. */
1290 if (current_thread
!= nullptr)
1291 switch_to_thread (current_thread
);
1293 if (!should_print_thread (requested_threads
, opts
,
1294 default_inf_num
, global_ids
, pid
, tp
))
1297 /* Switch inferiors so we're looking at the right
1299 switch_to_inferior_no_thread (tp
->inf
);
1302 = std::max (target_id_col_width
,
1303 thread_target_id_str (tp
).size ());
1305 ++n_matching_threads
;
1308 if (n_matching_threads
== 0)
1311 uiout
->message (_("No threads.\n"));
1313 uiout
->message (_("No threads matched.\n"));
1317 table_emitter
.emplace (uiout
, opts
.show_global_ids
? 5 : 4,
1318 n_matching_threads
, "threads");
1320 uiout
->table_header (1, ui_left
, "current", "");
1321 uiout
->table_header (4, ui_left
, "id-in-tg", "Id");
1322 if (opts
.show_global_ids
)
1323 uiout
->table_header (4, ui_left
, "id", "GId");
1324 uiout
->table_header (target_id_col_width
, ui_left
,
1325 "target-id", "Target Id");
1326 uiout
->table_header (1, ui_left
, "frame", "Frame");
1327 uiout
->table_body ();
1330 for (inferior
*inf
: all_inferiors ())
1331 for (thread_info
*tp
: inf
->threads ())
1333 if (tp
== current_thread
&& tp
->state
== THREAD_EXITED
)
1334 current_exited
= true;
1336 print_thread (uiout
, requested_threads
, opts
, global_ids
, pid
,
1337 default_inf_num
, tp
, current_thread
);
1340 /* This end scope restores the current thread and the frame
1341 selected before the "info threads" command, and it finishes the
1342 ui-out list or table. */
1345 if (pid
== -1 && requested_threads
== NULL
)
1347 if (uiout
->is_mi_like_p () && inferior_ptid
!= null_ptid
)
1348 uiout
->field_signed ("current-thread-id", current_thread
->global_num
);
1350 if (inferior_ptid
!= null_ptid
&& current_exited
)
1351 uiout
->message ("\n\
1352 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1353 print_thread_id (inferior_thread ()));
1354 else if (any_thread
&& inferior_ptid
== null_ptid
)
1355 uiout
->message ("\n\
1356 No selected thread. See `help thread'.\n");
1360 /* See gdbthread.h. */
1363 print_thread_info (struct ui_out
*uiout
, const char *requested_threads
,
1366 info_threads_opts opts
;
1367 print_thread_info_1 (uiout
, requested_threads
, opts
, 1, pid
);
1370 /* Create an option_def_group for the "info threads" options, with
1371 IT_OPTS as context. */
1373 static inline gdb::option::option_def_group
1374 make_info_threads_options_def_group (info_threads_opts
*it_opts
)
1376 return {{info_threads_option_defs
}, it_opts
};
1379 /* Implementation of the "info threads" command.
1381 Note: this has the drawback that it _really_ switches
1382 threads, which frees the frame cache. A no-side
1383 effects info-threads command would be nicer. */
1386 info_threads_command (const char *arg
, int from_tty
)
1388 info_threads_opts it_opts
;
1390 auto grp
= make_info_threads_options_def_group (&it_opts
);
1391 gdb::option::process_options
1392 (&arg
, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR
, grp
);
1394 print_thread_info_1 (current_uiout
, arg
, it_opts
, 0, -1);
1397 /* Completer for the "info threads" command. */
1400 info_threads_command_completer (struct cmd_list_element
*ignore
,
1401 completion_tracker
&tracker
,
1402 const char *text
, const char *word_ignored
)
1404 const auto grp
= make_info_threads_options_def_group (nullptr);
1406 if (gdb::option::complete_options
1407 (tracker
, &text
, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR
, grp
))
1410 /* Convenience to let the user know what the option can accept. */
1413 gdb::option::complete_on_all_options (tracker
, grp
);
1414 /* Keep this "ID" in sync with what "help info threads"
1416 tracker
.add_completion (make_unique_xstrdup ("ID"));
1420 /* See gdbthread.h. */
1423 switch_to_thread_no_regs (struct thread_info
*thread
)
1425 gdb_assert (thread
!= nullptr);
1426 threads_debug_printf ("thread = %s", thread
->ptid
.to_string ().c_str ());
1428 struct inferior
*inf
= thread
->inf
;
1430 set_current_program_space (inf
->pspace
);
1431 set_current_inferior (inf
);
1433 current_thread_
= thread
;
1434 inferior_ptid
= current_thread_
->ptid
;
1437 /* See gdbthread.h. */
1440 switch_to_no_thread ()
1442 if (current_thread_
== nullptr)
1445 threads_debug_printf ("thread = NONE");
1447 current_thread_
= nullptr;
1448 inferior_ptid
= null_ptid
;
1449 reinit_frame_cache ();
1452 /* See gdbthread.h. */
1455 switch_to_thread (thread_info
*thr
)
1457 gdb_assert (thr
!= NULL
);
1459 if (is_current_thread (thr
))
1462 switch_to_thread_no_regs (thr
);
1464 reinit_frame_cache ();
1467 /* See gdbsupport/common-gdbthread.h. */
1470 switch_to_thread (process_stratum_target
*proc_target
, ptid_t ptid
)
1472 thread_info
*thr
= proc_target
->find_thread (ptid
);
1473 switch_to_thread (thr
);
1479 scoped_restore_current_thread::restore ()
1481 /* If an entry of thread_info was previously selected, it won't be
1482 deleted because we've increased its refcount. The thread represented
1483 by this thread_info entry may have already exited (due to normal exit,
1484 detach, etc), so the thread_info.state is THREAD_EXITED. */
1485 if (m_thread
!= NULL
1486 /* If the previously selected thread belonged to a process that has
1487 in the mean time exited (or killed, detached, etc.), then don't revert
1488 back to it, but instead simply drop back to no thread selected. */
1490 switch_to_thread (m_thread
.get ());
1492 switch_to_inferior_no_thread (m_inf
.get ());
1494 /* The running state of the originally selected thread may have
1495 changed, so we have to recheck it here. */
1496 if (inferior_ptid
!= null_ptid
1498 && m_thread
->state
== THREAD_STOPPED
1499 && target_has_registers ()
1500 && target_has_stack ()
1501 && target_has_memory ())
1502 restore_selected_frame (m_selected_frame_id
, m_selected_frame_level
);
1505 scoped_restore_current_thread::~scoped_restore_current_thread ()
1508 m_lang
.dont_restore ();
1513 scoped_restore_current_thread::scoped_restore_current_thread ()
1515 m_inf
= inferior_ref::new_reference (current_inferior ());
1517 if (inferior_ptid
!= null_ptid
)
1519 m_thread
= thread_info_ref::new_reference (inferior_thread ());
1521 m_was_stopped
= m_thread
->state
== THREAD_STOPPED
;
1522 save_selected_frame (&m_selected_frame_id
, &m_selected_frame_level
);
1526 scoped_restore_current_thread::scoped_restore_current_thread
1527 (scoped_restore_current_thread
&&rhs
)
1528 : m_dont_restore (std::move (rhs
.m_dont_restore
)),
1529 m_thread (std::move (rhs
.m_thread
)),
1530 m_inf (std::move (rhs
.m_inf
)),
1531 m_selected_frame_id (std::move (rhs
.m_selected_frame_id
)),
1532 m_selected_frame_level (std::move (rhs
.m_selected_frame_level
)),
1533 m_was_stopped (std::move (rhs
.m_was_stopped
)),
1534 m_lang (std::move (rhs
.m_lang
))
1536 /* Deactivate the rhs. */
1537 rhs
.m_dont_restore
= true;
1540 /* See gdbthread.h. */
1543 show_thread_that_caused_stop (void)
1545 return highest_thread_num
> 1;
1548 /* See gdbthread.h. */
1551 show_inferior_qualified_tids (void)
1553 auto inf
= inferior_list
.begin ();
1557 return inf
!= inferior_list
.end ();
1560 /* See gdbthread.h. */
1563 print_thread_id (struct thread_info
*thr
)
1565 if (show_inferior_qualified_tids ())
1566 return print_full_thread_id (thr
);
1568 char *s
= get_print_cell ();
1570 gdb_assert (thr
!= nullptr);
1571 xsnprintf (s
, PRINT_CELL_SIZE
, "%d", thr
->per_inf_num
);
1575 /* See gdbthread.h. */
1578 print_full_thread_id (struct thread_info
*thr
)
1580 char *s
= get_print_cell ();
1582 gdb_assert (thr
!= nullptr);
1583 xsnprintf (s
, PRINT_CELL_SIZE
, "%d.%d", thr
->inf
->num
, thr
->per_inf_num
);
1587 /* Sort an array of struct thread_info pointers by thread ID (first by
1588 inferior number, and then by per-inferior thread number). Sorts in
1592 tp_array_compar_ascending (const thread_info_ref
&a
, const thread_info_ref
&b
)
1594 if (a
->inf
->num
!= b
->inf
->num
)
1595 return a
->inf
->num
< b
->inf
->num
;
1597 return (a
->per_inf_num
< b
->per_inf_num
);
1600 /* Sort an array of struct thread_info pointers by thread ID (first by
1601 inferior number, and then by per-inferior thread number). Sorts in
1602 descending order. */
1605 tp_array_compar_descending (const thread_info_ref
&a
, const thread_info_ref
&b
)
1607 if (a
->inf
->num
!= b
->inf
->num
)
1608 return a
->inf
->num
> b
->inf
->num
;
1610 return (a
->per_inf_num
> b
->per_inf_num
);
1613 /* See gdbthread.h. */
1616 thread_try_catch_cmd (thread_info
*thr
, std::optional
<int> ada_task
,
1617 const char *cmd
, int from_tty
,
1618 const qcs_flags
&flags
)
1620 gdb_assert (is_current_thread (thr
));
1622 /* The thread header is computed before running the command since
1623 the command can change the inferior, which is not permitted
1624 by thread_target_id_str. */
1625 std::string thr_header
;
1626 if (ada_task
.has_value ())
1627 thr_header
= string_printf (_("\nTask ID %d:\n"), *ada_task
);
1629 thr_header
= string_printf (_("\nThread %s (%s):\n"),
1630 print_thread_id (thr
),
1631 thread_target_id_str (thr
).c_str ());
1635 std::string cmd_result
;
1636 execute_command_to_string
1637 (cmd_result
, cmd
, from_tty
, gdb_stdout
->term_out ());
1638 if (!flags
.silent
|| cmd_result
.length () > 0)
1641 gdb_printf ("%s", thr_header
.c_str ());
1642 gdb_printf ("%s", cmd_result
.c_str ());
1645 catch (const gdb_exception_error
&ex
)
1650 gdb_printf ("%s", thr_header
.c_str ());
1652 gdb_printf ("%s\n", ex
.what ());
1659 /* Option definition of "thread apply"'s "-ascending" option. */
1661 static const gdb::option::flag_option_def
<> ascending_option_def
= {
1664 Call COMMAND for all threads in ascending order.\n\
1665 The default is descending order."),
1668 /* The qcs command line flags for the "thread apply" commands. Keep
1669 this in sync with the "frame apply" commands. */
1671 using qcs_flag_option_def
1672 = gdb::option::flag_option_def
<qcs_flags
>;
1674 static const gdb::option::option_def thr_qcs_flags_option_defs
[] = {
1675 qcs_flag_option_def
{
1676 "q", [] (qcs_flags
*opt
) { return &opt
->quiet
; },
1677 N_("Disables printing the thread information."),
1680 qcs_flag_option_def
{
1681 "c", [] (qcs_flags
*opt
) { return &opt
->cont
; },
1682 N_("Print any error raised by COMMAND and continue."),
1685 qcs_flag_option_def
{
1686 "s", [] (qcs_flags
*opt
) { return &opt
->silent
; },
1687 N_("Silently ignore any errors or empty output produced by COMMAND."),
1691 /* Create an option_def_group for the "thread apply all" options, with
1692 ASCENDING and FLAGS as context. */
1694 static inline std::array
<gdb::option::option_def_group
, 2>
1695 make_thread_apply_all_options_def_group (bool *ascending
,
1699 { {ascending_option_def
.def ()}, ascending
},
1700 { {thr_qcs_flags_option_defs
}, flags
},
1704 /* Create an option_def_group for the "thread apply" options, with
1705 FLAGS as context. */
1707 static inline gdb::option::option_def_group
1708 make_thread_apply_options_def_group (qcs_flags
*flags
)
1710 return {{thr_qcs_flags_option_defs
}, flags
};
1713 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1714 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1715 of two numbers separated by a hyphen. Examples:
1717 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1718 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1719 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1722 thread_apply_all_command (const char *cmd
, int from_tty
)
1724 bool ascending
= false;
1727 auto group
= make_thread_apply_all_options_def_group (&ascending
,
1729 gdb::option::process_options
1730 (&cmd
, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND
, group
);
1732 validate_flags_qcs ("thread apply all", &flags
);
1734 if (cmd
== NULL
|| *cmd
== '\000')
1735 error (_("Please specify a command at the end of 'thread apply all'"));
1737 update_thread_list ();
1739 int tc
= live_threads_count ();
1742 /* Save a copy of the thread list and increment each thread's
1743 refcount while executing the command in the context of each
1744 thread, in case the command is one that wipes threads. E.g.,
1745 detach, kill, disconnect, etc., or even normally continuing
1746 over an inferior or thread exit. */
1747 std::vector
<thread_info_ref
> thr_list_cpy
;
1748 thr_list_cpy
.reserve (tc
);
1750 for (thread_info
*tp
: all_non_exited_threads ())
1751 thr_list_cpy
.push_back (thread_info_ref::new_reference (tp
));
1752 gdb_assert (thr_list_cpy
.size () == tc
);
1754 auto *sorter
= (ascending
1755 ? tp_array_compar_ascending
1756 : tp_array_compar_descending
);
1757 std::sort (thr_list_cpy
.begin (), thr_list_cpy
.end (), sorter
);
1759 scoped_restore_current_thread restore_thread
;
1761 for (thread_info_ref
&thr
: thr_list_cpy
)
1762 if (switch_to_thread_if_alive (thr
.get ()))
1763 thread_try_catch_cmd (thr
.get (), {}, cmd
, from_tty
, flags
);
1767 /* Completer for "thread apply [ID list]". */
1770 thread_apply_command_completer (cmd_list_element
*ignore
,
1771 completion_tracker
&tracker
,
1772 const char *text
, const char * /*word*/)
1774 /* Don't leave this to complete_options because there's an early
1776 tracker
.set_use_custom_word_point (true);
1778 tid_range_parser parser
;
1779 parser
.init (text
, current_inferior ()->num
);
1783 while (!parser
.finished ())
1785 int inf_num
, thr_start
, thr_end
;
1787 if (!parser
.get_tid_range (&inf_num
, &thr_start
, &thr_end
))
1790 if (parser
.in_star_range () || parser
.in_thread_range ())
1791 parser
.skip_range ();
1794 catch (const gdb_exception_error
&ex
)
1796 /* get_tid_range throws if it parses a negative number, for
1797 example. But a seemingly negative number may be the start of
1798 an option instead. */
1801 const char *cmd
= parser
.cur_tok ();
1805 /* No thread ID list yet. */
1809 /* Check if we're past a valid thread ID list already. */
1810 if (parser
.finished ()
1811 && cmd
> text
&& !isspace (cmd
[-1]))
1814 /* We're past the thread ID list, advance word point. */
1815 tracker
.advance_custom_word_point_by (cmd
- text
);
1818 const auto group
= make_thread_apply_options_def_group (nullptr);
1819 if (gdb::option::complete_options
1820 (tracker
, &text
, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND
, group
))
1823 complete_nested_command_line (tracker
, text
);
1826 /* Completer for "thread apply all". */
1829 thread_apply_all_command_completer (cmd_list_element
*ignore
,
1830 completion_tracker
&tracker
,
1831 const char *text
, const char *word
)
1833 const auto group
= make_thread_apply_all_options_def_group (nullptr,
1835 if (gdb::option::complete_options
1836 (tracker
, &text
, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND
, group
))
1839 complete_nested_command_line (tracker
, text
);
1842 /* Implementation of the "thread apply" command. */
1845 thread_apply_command (const char *tidlist
, int from_tty
)
1848 const char *cmd
= NULL
;
1849 tid_range_parser parser
;
1851 if (tidlist
== NULL
|| *tidlist
== '\000')
1852 error (_("Please specify a thread ID list"));
1854 parser
.init (tidlist
, current_inferior ()->num
);
1855 while (!parser
.finished ())
1857 int inf_num
, thr_start
, thr_end
;
1859 if (!parser
.get_tid_range (&inf_num
, &thr_start
, &thr_end
))
1863 cmd
= parser
.cur_tok ();
1865 auto group
= make_thread_apply_options_def_group (&flags
);
1866 gdb::option::process_options
1867 (&cmd
, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND
, group
);
1869 validate_flags_qcs ("thread apply", &flags
);
1872 error (_("Please specify a command following the thread ID list"));
1874 if (tidlist
== cmd
|| isdigit (cmd
[0]))
1875 invalid_thread_id_error (cmd
);
1877 scoped_restore_current_thread restore_thread
;
1879 parser
.init (tidlist
, current_inferior ()->num
);
1880 while (!parser
.finished ())
1882 struct thread_info
*tp
= NULL
;
1883 struct inferior
*inf
;
1884 int inf_num
, thr_num
;
1886 parser
.get_tid (&inf_num
, &thr_num
);
1887 inf
= find_inferior_id (inf_num
);
1889 tp
= find_thread_id (inf
, thr_num
);
1891 if (parser
.in_star_range ())
1895 warning (_("Unknown inferior %d"), inf_num
);
1896 parser
.skip_range ();
1900 /* No use looking for threads past the highest thread number
1901 the inferior ever had. */
1902 if (thr_num
>= inf
->highest_thread_num
)
1903 parser
.skip_range ();
1905 /* Be quiet about unknown threads numbers. */
1912 if (show_inferior_qualified_tids () || parser
.tid_is_qualified ())
1913 warning (_("Unknown thread %d.%d"), inf_num
, thr_num
);
1915 warning (_("Unknown thread %d"), thr_num
);
1919 if (!switch_to_thread_if_alive (tp
))
1921 warning (_("Thread %s has terminated."), print_thread_id (tp
));
1925 thread_try_catch_cmd (tp
, {}, cmd
, from_tty
, flags
);
1930 /* Implementation of the "taas" command. */
1933 taas_command (const char *cmd
, int from_tty
)
1935 if (cmd
== NULL
|| *cmd
== '\0')
1936 error (_("Please specify a command to apply on all threads"));
1937 std::string expanded
= std::string ("thread apply all -s ") + cmd
;
1938 execute_command (expanded
.c_str (), from_tty
);
1941 /* Implementation of the "tfaas" command. */
1944 tfaas_command (const char *cmd
, int from_tty
)
1946 if (cmd
== NULL
|| *cmd
== '\0')
1947 error (_("Please specify a command to apply on all frames of all threads"));
1948 std::string expanded
1949 = std::string ("thread apply all -s -- frame apply all -s ") + cmd
;
1950 execute_command (expanded
.c_str (), from_tty
);
1953 /* Switch to the specified thread, or print the current thread. */
1956 thread_command (const char *tidstr
, int from_tty
)
1960 if (inferior_ptid
== null_ptid
)
1961 error (_("No thread selected"));
1963 if (target_has_stack ())
1965 struct thread_info
*tp
= inferior_thread ();
1967 if (tp
->state
== THREAD_EXITED
)
1968 gdb_printf (_("[Current thread is %s (%s) (exited)]\n"),
1969 print_thread_id (tp
),
1970 target_pid_to_str (inferior_ptid
).c_str ());
1972 gdb_printf (_("[Current thread is %s (%s)]\n"),
1973 print_thread_id (tp
),
1974 target_pid_to_str (inferior_ptid
).c_str ());
1977 error (_("No stack."));
1981 ptid_t previous_ptid
= inferior_ptid
;
1983 thread_select (tidstr
, parse_thread_id (tidstr
, NULL
));
1985 /* Print if the thread has not changed, otherwise an event will
1987 if (inferior_ptid
== previous_ptid
)
1989 print_selected_thread_frame (current_uiout
,
1990 USER_SELECTED_THREAD
1991 | USER_SELECTED_FRAME
);
1994 notify_user_selected_context_changed
1995 (USER_SELECTED_THREAD
| USER_SELECTED_FRAME
);
1999 /* Implementation of `thread name'. */
2002 thread_name_command (const char *arg
, int from_tty
)
2004 struct thread_info
*info
;
2006 if (inferior_ptid
== null_ptid
)
2007 error (_("No thread selected"));
2009 arg
= skip_spaces (arg
);
2011 info
= inferior_thread ();
2012 info
->set_name (arg
!= nullptr ? make_unique_xstrdup (arg
) : nullptr);
2015 /* Find thread ids with a name, target pid, or extra info matching ARG. */
2018 thread_find_command (const char *arg
, int from_tty
)
2021 unsigned long match
= 0;
2023 if (arg
== NULL
|| *arg
== '\0')
2024 error (_("Command requires an argument."));
2026 tmp
= re_comp (arg
);
2028 error (_("Invalid regexp (%s): %s"), tmp
, arg
);
2030 /* We're going to be switching threads. */
2031 scoped_restore_current_thread restore_thread
;
2033 update_thread_list ();
2035 for (thread_info
*tp
: all_threads ())
2037 switch_to_inferior_no_thread (tp
->inf
);
2039 if (tp
->name () != nullptr && re_exec (tp
->name ()))
2041 gdb_printf (_("Thread %s has name '%s'\n"),
2042 print_thread_id (tp
), tp
->name ());
2046 tmp
= target_thread_name (tp
);
2047 if (tmp
!= NULL
&& re_exec (tmp
))
2049 gdb_printf (_("Thread %s has target name '%s'\n"),
2050 print_thread_id (tp
), tmp
);
2054 std::string name
= target_pid_to_str (tp
->ptid
);
2055 if (!name
.empty () && re_exec (name
.c_str ()))
2057 gdb_printf (_("Thread %s has target id '%s'\n"),
2058 print_thread_id (tp
), name
.c_str ());
2062 tmp
= target_extra_thread_info (tp
);
2063 if (tmp
!= NULL
&& re_exec (tmp
))
2065 gdb_printf (_("Thread %s has extra info '%s'\n"),
2066 print_thread_id (tp
), tmp
);
2071 gdb_printf (_("No threads match '%s'\n"), arg
);
2074 /* Print notices when new threads are attached and detached. */
2075 bool print_thread_events
= true;
2077 show_print_thread_events (struct ui_file
*file
, int from_tty
,
2078 struct cmd_list_element
*c
, const char *value
)
2081 _("Printing of thread events is %s.\n"),
2085 /* See gdbthread.h. */
2088 thread_select (const char *tidstr
, thread_info
*tp
)
2090 if (!switch_to_thread_if_alive (tp
))
2091 error (_("Thread ID %s has terminated."), tidstr
);
2093 annotate_thread_changed ();
2095 /* Since the current thread may have changed, see if there is any
2096 exited thread we can now delete. */
2097 delete_exited_threads ();
2100 /* Print thread and frame switch command response. */
2103 print_selected_thread_frame (struct ui_out
*uiout
,
2104 user_selected_what selection
)
2106 struct thread_info
*tp
= inferior_thread ();
2108 if (selection
& USER_SELECTED_THREAD
)
2110 if (uiout
->is_mi_like_p ())
2112 uiout
->field_signed ("new-thread-id",
2113 inferior_thread ()->global_num
);
2117 uiout
->text ("[Switching to thread ");
2118 uiout
->field_string ("new-thread-id", print_thread_id (tp
));
2120 uiout
->text (target_pid_to_str (inferior_ptid
));
2125 if (tp
->state
== THREAD_RUNNING
)
2127 if (selection
& USER_SELECTED_THREAD
)
2128 uiout
->text ("(running)\n");
2130 else if (selection
& USER_SELECTED_FRAME
)
2132 if (selection
& USER_SELECTED_THREAD
)
2135 if (has_stack_frames ())
2136 print_stack_frame_to_uiout (uiout
, get_selected_frame (NULL
),
2141 /* Update the 'threads_executing' global based on the threads we know
2142 about right now. This is used by infrun to tell whether we should
2143 pull events out of the current target. */
2146 update_threads_executing (void)
2148 process_stratum_target
*targ
= current_inferior ()->process_target ();
2153 targ
->threads_executing
= false;
2155 for (inferior
*inf
: all_non_exited_inferiors (targ
))
2157 if (!inf
->has_execution ())
2160 /* If the process has no threads, then it must be we have a
2161 process-exit event pending. */
2162 if (inf
->thread_list
.empty ())
2164 targ
->threads_executing
= true;
2168 for (thread_info
*tp
: inf
->non_exited_threads ())
2170 if (tp
->executing ())
2172 targ
->threads_executing
= true;
2180 update_thread_list (void)
2182 target_update_thread_list ();
2183 update_threads_executing ();
2186 /* See gdbthread.h. */
2189 thread_name (thread_info
*thread
)
2191 /* Use the manually set name if there is one. */
2192 const char *name
= thread
->name ();
2193 if (name
!= nullptr)
2196 /* Otherwise, ask the target. Ensure we query the right target stack. */
2197 scoped_restore_current_thread restore_thread
;
2198 if (thread
->inf
!= current_inferior ())
2199 switch_to_inferior_no_thread (thread
->inf
);
2201 return target_thread_name (thread
);
2204 /* See gdbthread.h. */
2207 thread_state_string (enum thread_state state
)
2211 case THREAD_STOPPED
:
2214 case THREAD_RUNNING
:
2221 gdb_assert_not_reached ("unknown thread state");
2224 /* Return a new value for the selected thread's id. Return a value of
2225 0 if no thread is selected. If GLOBAL is true, return the thread's
2226 global number. Otherwise return the per-inferior number. */
2228 static struct value
*
2229 thread_num_make_value_helper (struct gdbarch
*gdbarch
, int global
)
2233 if (inferior_ptid
== null_ptid
)
2237 thread_info
*tp
= inferior_thread ();
2239 int_val
= tp
->global_num
;
2241 int_val
= tp
->per_inf_num
;
2244 return value_from_longest (builtin_type (gdbarch
)->builtin_int
, int_val
);
2247 /* Return a new value for the selected thread's per-inferior thread
2248 number. Return a value of 0 if no thread is selected, or no
2251 static struct value
*
2252 thread_id_per_inf_num_make_value (struct gdbarch
*gdbarch
,
2253 struct internalvar
*var
,
2256 return thread_num_make_value_helper (gdbarch
, 0);
2259 /* Return a new value for the selected thread's global id. Return a
2260 value of 0 if no thread is selected, or no threads exist. */
2262 static struct value
*
2263 global_thread_id_make_value (struct gdbarch
*gdbarch
, struct internalvar
*var
,
2266 return thread_num_make_value_helper (gdbarch
, 1);
2269 /* Return a new value for the number of non-exited threads in the current
2270 inferior. If there are no threads in the current inferior return a
2273 static struct value
*
2274 inferior_thread_count_make_value (struct gdbarch
*gdbarch
,
2275 struct internalvar
*var
, void *ignore
)
2279 update_thread_list ();
2281 if (inferior_ptid
!= null_ptid
)
2282 int_val
= current_inferior ()->non_exited_threads ().size ();
2284 return value_from_longest (builtin_type (gdbarch
)->builtin_int
, int_val
);
2287 /* Commands with a prefix of `thread'. */
2288 struct cmd_list_element
*thread_cmd_list
= NULL
;
2290 /* Implementation of `thread' variable. */
2292 static const struct internalvar_funcs thread_funcs
=
2294 thread_id_per_inf_num_make_value
,
2298 /* Implementation of `gthread' variable. */
2300 static const struct internalvar_funcs gthread_funcs
=
2302 global_thread_id_make_value
,
2306 /* Implementation of `_inferior_thread_count` convenience variable. */
2308 static const struct internalvar_funcs inferior_thread_count_funcs
=
2310 inferior_thread_count_make_value
,
2314 INIT_GDB_FILE (thread
)
2316 static struct cmd_list_element
*thread_apply_list
= NULL
;
2317 cmd_list_element
*c
;
2319 const auto info_threads_opts
= make_info_threads_options_def_group (nullptr);
2321 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2323 static std::string info_threads_help
2324 = gdb::option::build_help (_("\
2325 Display currently known threads.\n\
2326 Usage: info threads [OPTION]... [ID]...\n\
2327 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2328 Otherwise, all threads are displayed.\n\
2334 c
= add_info ("threads", info_threads_command
, info_threads_help
.c_str ());
2335 set_cmd_completer_handle_brkchars (c
, info_threads_command_completer
);
2337 cmd_list_element
*thread_cmd
2338 = add_prefix_cmd ("thread", class_run
, thread_command
, _("\
2339 Use this command to switch between threads.\n\
2340 The new thread ID must be currently known."),
2341 &thread_cmd_list
, 1, &cmdlist
);
2343 add_com_alias ("t", thread_cmd
, class_run
, 1);
2345 #define THREAD_APPLY_OPTION_HELP "\
2346 Prints per-inferior thread number and target system's thread id\n\
2347 followed by COMMAND output.\n\
2349 By default, an error raised during the execution of COMMAND\n\
2350 aborts \"thread apply\".\n\
2355 const auto thread_apply_opts
= make_thread_apply_options_def_group (nullptr);
2357 static std::string thread_apply_help
= gdb::option::build_help (_("\
2358 Apply a command to a list of threads.\n\
2359 Usage: thread apply ID... [OPTION]... COMMAND\n\
2360 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2361 THREAD_APPLY_OPTION_HELP
),
2364 c
= add_prefix_cmd ("apply", class_run
, thread_apply_command
,
2365 thread_apply_help
.c_str (),
2366 &thread_apply_list
, 1,
2368 set_cmd_completer_handle_brkchars (c
, thread_apply_command_completer
);
2370 const auto thread_apply_all_opts
2371 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2373 static std::string thread_apply_all_help
= gdb::option::build_help (_("\
2374 Apply a command to all threads.\n\
2376 Usage: thread apply all [OPTION]... COMMAND\n"
2377 THREAD_APPLY_OPTION_HELP
),
2378 thread_apply_all_opts
);
2380 c
= add_cmd ("all", class_run
, thread_apply_all_command
,
2381 thread_apply_all_help
.c_str (),
2382 &thread_apply_list
);
2383 set_cmd_completer_handle_brkchars (c
, thread_apply_all_command_completer
);
2385 c
= add_com ("taas", class_run
, taas_command
, _("\
2386 Apply a command to all threads (ignoring errors and empty output).\n\
2387 Usage: taas [OPTION]... COMMAND\n\
2388 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2389 See \"help thread apply all\" for available options."));
2390 set_cmd_completer_handle_brkchars (c
, thread_apply_all_command_completer
);
2392 c
= add_com ("tfaas", class_run
, tfaas_command
, _("\
2393 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2394 Usage: tfaas [OPTION]... COMMAND\n\
2395 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2396 See \"help frame apply all\" for available options."));
2397 set_cmd_completer_handle_brkchars (c
, frame_apply_all_cmd_completer
);
2399 add_cmd ("name", class_run
, thread_name_command
,
2400 _("Set the current thread's name.\n\
2401 Usage: thread name [NAME]\n\
2402 If NAME is not given, then any existing name is removed."), &thread_cmd_list
);
2404 add_cmd ("find", class_run
, thread_find_command
, _("\
2405 Find threads that match a regular expression.\n\
2406 Usage: thread find REGEXP\n\
2407 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2410 add_setshow_boolean_cmd ("thread-events", no_class
,
2411 &print_thread_events
, _("\
2412 Set printing of thread events (such as thread start and exit)."), _("\
2413 Show printing of thread events (such as thread start and exit)."), NULL
,
2415 show_print_thread_events
,
2416 &setprintlist
, &showprintlist
);
2418 add_setshow_boolean_cmd ("threads", class_maintenance
, &debug_threads
, _("\
2419 Set thread debugging."), _("\
2420 Show thread debugging."), _("\
2421 When on messages about thread creation and deletion are printed."),
2424 &setdebuglist
, &showdebuglist
);
2426 create_internalvar_type_lazy ("_thread", &thread_funcs
, NULL
);
2427 create_internalvar_type_lazy ("_gthread", >hread_funcs
, NULL
);
2428 create_internalvar_type_lazy ("_inferior_thread_count",
2429 &inferior_thread_count_funcs
, NULL
);