Add translations for various sub-directories
[binutils-gdb.git] / gdb / thread.c
blob5892b158603a7d11cb7c7efc3346f01714797201
1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2024 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/>. */
22 #include "language.h"
23 #include "symtab.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbsupport/environ.h"
27 #include "top.h"
28 #include "value.h"
29 #include "target.h"
30 #include "gdbthread.h"
31 #include "command.h"
32 #include "cli/cli-cmds.h"
33 #include "regcache.h"
34 #include "btrace.h"
36 #include <ctype.h>
37 #include <sys/types.h>
38 #include <signal.h>
39 #include "ui-out.h"
40 #include "observable.h"
41 #include "annotate.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"
48 #include <algorithm>
49 #include <optional>
50 #include "inline-frame.h"
51 #include "stack.h"
52 #include "interps.h"
53 #include "record-full.h"
55 /* See gdbthread.h. */
57 bool debug_threads = false;
59 /* Implement 'show debug threads'. */
61 static void
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. */
79 static bool
80 is_current_thread (const thread_info *thr)
82 return thr == current_thread_;
85 struct thread_info*
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. */
94 static void
95 delete_thread_breakpoint (struct breakpoint **bp_p)
97 if (*bp_p != NULL)
99 delete_breakpoint (*bp_p);
100 *bp_p = NULL;
104 void
105 delete_step_resume_breakpoint (struct thread_info *tp)
107 if (tp != NULL)
108 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
111 void
112 delete_exception_resume_breakpoint (struct thread_info *tp)
114 if (tp != NULL)
115 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
118 /* See gdbthread.h. */
120 void
121 delete_single_step_breakpoints (struct thread_info *tp)
123 if (tp != NULL)
124 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
127 /* Delete the breakpoint pointed at by BP_P at the next stop, if
128 there's one. */
130 static void
131 delete_at_next_stop (struct breakpoint **bp)
133 if (*bp != NULL)
135 (*bp)->disposition = disp_del_at_next_stop;
136 *bp = NULL;
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,
153 CORE_ADDR addr)
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. */
163 void
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 ();
169 fsm->clean_up (thr);
173 static void
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. */
197 static void
198 notify_thread_exited (thread_info *t, std::optional<ULONGEST> exit_code,
199 int silent)
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));
207 else
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. */
218 void
219 set_thread_exited (thread_info *tp, std::optional<ULONGEST> exit_code,
220 bool silent)
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);
257 void
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;
284 return tp;
287 /* Notify interpreters and observers that thread T has been created. */
289 static void
290 notify_new_thread (thread_info *t)
292 interps_notify_new_thread (t);
293 gdb::observers::new_thread.notify (t);
296 struct thread_info *
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 (),
305 targ->shortname ());
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);
312 if (tp != nullptr)
313 delete_thread (tp);
315 tp = new_thread (inf, ptid);
316 notify_new_thread (tp);
318 return tp;
321 struct thread_info *
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 ();
333 return result;
336 struct thread_info *
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. */
365 bool
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. */
375 void
376 thread_info::set_executing (bool executing)
378 m_executing = executing;
379 if (executing)
380 this->clear_stop_pc ();
383 /* See gdbthread.h. */
385 void
386 thread_info::set_resumed (bool resumed)
388 if (resumed == m_resumed)
389 return;
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. */
395 if (!resumed)
396 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
398 m_resumed = resumed;
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. */
402 if (resumed)
403 proc_target->maybe_add_resumed_with_pending_wait_status (this);
406 /* See gdbthread.h. */
408 void
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. */
422 void
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. */
435 void
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)
442 return;
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)
464 int num = 0;
466 for (const thread_info &thread ATTRIBUTE_UNUSED : l)
467 ++num;
469 return num;
472 /* See gdbthread.h. */
474 void
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. */
486 void
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. */
494 void
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. */
507 static void
508 delete_thread_1 (thread_info *thr, std::optional<ULONGEST> exit_code,
509 bool silent)
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)
517 : "<none>"),
518 silent);
520 set_thread_exited (thr, exit_code, silent);
522 if (!thr->deletable ())
524 /* Will be really deleted some other time. */
525 return;
528 auto it = thr->inf->thread_list.iterator_to (*thr);
529 thr->inf->thread_list.erase (it);
531 gdb::observers::thread_deleted.notify (thr);
533 delete thr;
536 /* See gdbthread.h. */
538 void
539 delete_thread_with_exit_code (thread_info *thread, ULONGEST exit_code,
540 bool silent)
542 delete_thread_1 (thread, exit_code, silent);
545 /* See gdbthread.h. */
547 void
548 delete_thread (thread_info *thread)
550 delete_thread_1 (thread, {}, false /* not silent */);
553 void
554 delete_thread_silent (thread_info *thread)
556 delete_thread_1 (thread, {}, true /* not silent */);
559 struct thread_info *
560 find_thread_global_id (int global_id)
562 for (thread_info *tp : all_threads ())
563 if (tp->global_num == global_id)
564 return tp;
566 return NULL;
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)
574 return tp;
576 return NULL;
579 /* See gdbthread.h. */
581 struct thread_info *
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 (),
586 handle.size (),
587 inf);
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.
604 struct thread_info *
605 iterate_over_threads (int (*callback) (struct thread_info *, void *),
606 void *data)
608 for (thread_info *tp : all_threads_safe ())
609 if ((*callback) (tp, data))
610 return tp;
612 return NULL;
615 /* See gdbthread.h. */
617 bool
618 any_thread_p ()
620 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
621 return true;
622 return false;
626 thread_count (process_stratum_target *proc_target)
628 auto rng = all_threads (proc_target);
629 return std::distance (rng.begin (), rng.end ());
632 /* Return the number of non-exited threads in the thread list. */
634 static int
635 live_threads_count (void)
637 auto rng = all_non_exited_threads ();
638 return std::distance (rng.begin (), rng.end ());
642 valid_global_thread_id (int global_id)
644 for (thread_info *tp : all_threads ())
645 if (tp->global_num == global_id)
646 return 1;
648 return 0;
651 bool
652 in_thread_list (process_stratum_target *targ, ptid_t ptid)
654 return targ->find_thread (ptid) != nullptr;
657 /* Finds the first thread of the inferior. */
659 thread_info *
660 first_thread_of_inferior (inferior *inf)
662 if (inf->thread_list.empty ())
663 return nullptr;
665 return &inf->thread_list.front ();
668 thread_info *
669 any_thread_of_inferior (inferior *inf)
671 gdb_assert (inf->pid != 0);
673 /* Prefer the current thread, if there's one. */
674 if (inf == current_inferior () && inferior_ptid != null_ptid)
675 return inferior_thread ();
677 for (thread_info *tp : inf->non_exited_threads ())
678 return tp;
680 return NULL;
683 thread_info *
684 any_live_thread_of_inferior (inferior *inf)
686 struct thread_info *curr_tp = NULL;
687 struct thread_info *tp_executing = NULL;
689 gdb_assert (inf != NULL && inf->pid != 0);
691 /* Prefer the current thread if it's not executing. */
692 if (inferior_ptid != null_ptid && current_inferior () == inf)
694 /* If the current thread is dead, forget it. If it's not
695 executing, use it. Otherwise, still choose it (below), but
696 only if no other non-executing thread is found. */
697 curr_tp = inferior_thread ();
698 if (curr_tp->state == THREAD_EXITED)
699 curr_tp = NULL;
700 else if (!curr_tp->executing ())
701 return curr_tp;
704 for (thread_info *tp : inf->non_exited_threads ())
706 if (!tp->executing ())
707 return tp;
709 tp_executing = tp;
712 /* If both the current thread and all live threads are executing,
713 prefer the current thread. */
714 if (curr_tp != NULL)
715 return curr_tp;
717 /* Otherwise, just return an executing thread, if any. */
718 return tp_executing;
721 /* Return true if TP is an active thread. */
722 static bool
723 thread_alive (thread_info *tp)
725 if (tp->state == THREAD_EXITED)
726 return false;
728 /* Ensure we're looking at the right target stack. */
729 gdb_assert (tp->inf == current_inferior ());
731 return target_thread_alive (tp->ptid);
734 /* See gdbthreads.h. */
736 bool
737 switch_to_thread_if_alive (thread_info *thr)
739 scoped_restore_current_thread restore_thread;
741 /* Switch inferior first, so that we're looking at the right target
742 stack. */
743 switch_to_inferior_no_thread (thr->inf);
745 if (thread_alive (thr))
747 switch_to_thread (thr);
748 restore_thread.dont_restore ();
749 return true;
752 return false;
755 /* See gdbthreads.h. */
757 void
758 prune_threads (void)
760 scoped_restore_current_thread restore_thread;
762 for (thread_info *tp : all_threads_safe ())
764 switch_to_inferior_no_thread (tp->inf);
766 if (!thread_alive (tp))
767 delete_thread (tp);
771 /* See gdbthreads.h. */
773 void
774 delete_exited_threads (void)
776 for (thread_info *tp : all_threads_safe ())
777 if (tp->state == THREAD_EXITED)
778 delete_thread (tp);
781 /* Return true value if stack temporaries are enabled for the thread
782 TP. */
784 bool
785 thread_stack_temporaries_enabled_p (thread_info *tp)
787 if (tp == NULL)
788 return false;
789 else
790 return tp->stack_temporaries_enabled;
793 /* Push V on to the stack temporaries of the thread with id PTID. */
795 void
796 push_thread_stack_temporary (thread_info *tp, struct value *v)
798 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
799 tp->stack_temporaries.push_back (v);
802 /* Return true if VAL is among the stack temporaries of the thread
803 TP. Return false otherwise. */
805 bool
806 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
808 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
809 for (value *v : tp->stack_temporaries)
810 if (v == val)
811 return true;
813 return false;
816 /* Return the last of the stack temporaries for thread with id PTID.
817 Return NULL if there are no stack temporaries for the thread. */
819 value *
820 get_last_thread_stack_temporary (thread_info *tp)
822 struct value *lastval = NULL;
824 gdb_assert (tp != NULL);
825 if (!tp->stack_temporaries.empty ())
826 lastval = tp->stack_temporaries.back ();
828 return lastval;
831 void
832 thread_change_ptid (process_stratum_target *targ,
833 ptid_t old_ptid, ptid_t new_ptid)
835 struct inferior *inf;
836 struct thread_info *tp;
838 /* It can happen that what we knew as the target inferior id
839 changes. E.g, target remote may only discover the remote process
840 pid after adding the inferior to GDB's list. */
841 inf = find_inferior_ptid (targ, old_ptid);
842 inf->pid = new_ptid.pid ();
844 tp = inf->find_thread (old_ptid);
845 gdb_assert (tp != nullptr);
847 int num_erased = inf->ptid_thread_map.erase (old_ptid);
848 gdb_assert (num_erased == 1);
850 tp->ptid = new_ptid;
851 inf->ptid_thread_map[new_ptid] = tp;
853 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
856 /* See gdbthread.h. */
858 void
859 set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
861 for (thread_info *tp : all_non_exited_threads (targ, ptid))
862 tp->set_resumed (resumed);
865 /* Helper for set_running, that marks one thread either running or
866 stopped. */
868 static bool
869 set_running_thread (struct thread_info *tp, bool running)
871 bool started = false;
873 if (running && tp->state == THREAD_STOPPED)
874 started = true;
875 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
877 threads_debug_printf ("thread: %s, running? %d%s",
878 tp->ptid.to_string ().c_str (), running,
879 (started ? " (started)" : ""));
881 if (!running)
883 /* If the thread is now marked stopped, remove it from
884 the step-over queue, so that we don't try to resume
885 it until the user wants it to. */
886 if (thread_is_in_step_over_chain (tp))
887 global_thread_step_over_chain_remove (tp);
890 return started;
893 /* Notify interpreters and observers that the target was resumed. */
895 static void
896 notify_target_resumed (ptid_t ptid)
898 interps_notify_target_resumed (ptid);
899 gdb::observers::target_resumed.notify (ptid);
901 /* We are about to resume the inferior. Close all cached BFDs so that
902 when the inferior next stops, and GDB regains control, we will spot
903 any on-disk changes to the BFDs we are using. */
904 bfd_cache_close_all ();
907 /* See gdbthread.h. */
909 void
910 thread_info::set_running (bool running)
912 if (set_running_thread (this, running))
913 notify_target_resumed (this->ptid);
916 void
917 set_running (process_stratum_target *targ, ptid_t ptid, bool running)
919 /* We try not to notify the observer if no thread has actually
920 changed the running state -- merely to reduce the number of
921 messages to the MI frontend. A frontend is supposed to handle
922 multiple *running notifications just fine. */
923 bool any_started = false;
925 for (thread_info *tp : all_non_exited_threads (targ, ptid))
926 if (set_running_thread (tp, running))
927 any_started = true;
929 if (any_started)
930 notify_target_resumed (ptid);
933 void
934 set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
936 for (thread_info *tp : all_non_exited_threads (targ, ptid))
937 tp->set_executing (executing);
939 /* It only takes one running thread to spawn more threads. */
940 if (executing)
941 targ->threads_executing = true;
942 /* Only clear the flag if the caller is telling us everything is
943 stopped. */
944 else if (minus_one_ptid == ptid)
945 targ->threads_executing = false;
948 /* See gdbthread.h. */
950 bool
951 threads_are_executing (process_stratum_target *target)
953 return target->threads_executing;
956 void
957 set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
959 for (thread_info *tp : all_non_exited_threads (targ, ptid))
960 tp->stop_requested = stop;
962 /* Call the stop requested observer so other components of GDB can
963 react to this request. */
964 if (stop)
965 gdb::observers::thread_stop_requested.notify (ptid);
968 void
969 finish_thread_state (process_stratum_target *targ, ptid_t ptid)
971 bool any_started = false;
973 for (thread_info *tp : all_non_exited_threads (targ, ptid))
974 if (set_running_thread (tp, tp->executing ()))
975 any_started = true;
977 if (any_started)
978 notify_target_resumed (ptid);
981 /* See gdbthread.h. */
983 void
984 validate_registers_access (void)
986 /* No selected thread, no registers. */
987 if (inferior_ptid == null_ptid)
988 error (_("No thread selected."));
990 thread_info *tp = inferior_thread ();
992 /* Don't try to read from a dead thread. */
993 if (tp->state == THREAD_EXITED)
994 error (_("The current thread has terminated"));
996 /* ... or from a spinning thread. FIXME: This isn't actually fully
997 correct. It'll allow an user-requested access (e.g., "print $pc"
998 at the prompt) when a thread is not executing for some internal
999 reason, but is marked running from the user's perspective. E.g.,
1000 the thread is waiting for its turn in the step-over queue. */
1001 if (tp->executing ())
1003 /* If we are replaying with the record-full subsystem, even though
1004 the thread is executing, it is always safe to read from it since
1005 replay execution is just GDB reading and writing to a regcache. */
1006 if (!record_full_is_replaying ())
1007 error (_("Selected thread is running."));
1011 /* See gdbthread.h. */
1013 bool
1014 can_access_registers_thread (thread_info *thread)
1016 /* No thread, no registers. */
1017 if (thread == NULL)
1018 return false;
1020 /* Don't try to read from a dead thread. */
1021 if (thread->state == THREAD_EXITED)
1022 return false;
1024 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
1025 if (thread->executing ())
1027 /* See validate_registers_access. */
1028 if (!record_full_is_replaying ())
1029 return false;
1032 return true;
1035 bool
1036 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
1038 return (pc >= thread->control.step_range_start
1039 && pc < thread->control.step_range_end);
1042 /* Helper for print_thread_info. Returns true if THR should be
1043 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
1044 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
1045 is true if REQUESTED_THREADS is list of global IDs, false if a list
1046 of per-inferior thread ids. If PID is not -1, only print THR if it
1047 is a thread from the process PID. Otherwise, threads from all
1048 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
1049 and PID is not -1, then the thread is printed if it belongs to the
1050 specified process. Otherwise, an error is raised. */
1052 static bool
1053 should_print_thread (const char *requested_threads, int default_inf_num,
1054 int global_ids, int pid, struct thread_info *thr)
1056 if (requested_threads != NULL && *requested_threads != '\0')
1058 int in_list;
1060 if (global_ids)
1061 in_list = number_is_in_list (requested_threads, thr->global_num);
1062 else
1063 in_list = tid_is_in_list (requested_threads, default_inf_num,
1064 thr->inf->num, thr->per_inf_num);
1065 if (!in_list)
1066 return false;
1069 if (pid != -1 && thr->ptid.pid () != pid)
1071 if (requested_threads != NULL && *requested_threads != '\0')
1072 error (_("Requested thread not found in requested process"));
1073 return false;
1076 if (thr->state == THREAD_EXITED)
1077 return false;
1079 return true;
1082 /* Return the string to display in "info threads"'s "Target Id"
1083 column, for TP. */
1085 static std::string
1086 thread_target_id_str (thread_info *tp)
1088 std::string target_id = target_pid_to_str (tp->ptid);
1089 const char *extra_info = target_extra_thread_info (tp);
1090 const char *name = thread_name (tp);
1092 if (extra_info != nullptr && name != nullptr)
1093 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1094 extra_info);
1095 else if (extra_info != nullptr)
1096 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1097 else if (name != nullptr)
1098 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1099 else
1100 return target_id;
1103 /* Print thread TP. GLOBAL_IDS indicates whether REQUESTED_THREADS
1104 is a list of global or per-inferior thread ids. */
1106 static void
1107 do_print_thread (ui_out *uiout, const char *requested_threads,
1108 int global_ids, int pid, int show_global_ids,
1109 int default_inf_num, thread_info *tp,
1110 thread_info *current_thread)
1112 int core;
1114 /* In case REQUESTED_THREADS contains $_thread. */
1115 if (current_thread != nullptr)
1116 switch_to_thread (current_thread);
1118 if (!should_print_thread (requested_threads, default_inf_num,
1119 global_ids, pid, tp))
1120 return;
1122 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1124 if (!uiout->is_mi_like_p ())
1126 if (tp == current_thread)
1127 uiout->field_string ("current", "*");
1128 else
1129 uiout->field_skip ("current");
1131 uiout->field_string ("id-in-tg", print_thread_id (tp));
1134 if (show_global_ids || uiout->is_mi_like_p ())
1135 uiout->field_signed ("id", tp->global_num);
1137 /* Switch to the thread (and inferior / target). */
1138 switch_to_thread (tp);
1140 /* For the CLI, we stuff everything into the target-id field.
1141 This is a gross hack to make the output come out looking
1142 correct. The underlying problem here is that ui-out has no
1143 way to specify that a field's space allocation should be
1144 shared by several fields. For MI, we do the right thing
1145 instead. */
1147 if (uiout->is_mi_like_p ())
1149 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1151 const char *extra_info = target_extra_thread_info (tp);
1152 if (extra_info != nullptr)
1153 uiout->field_string ("details", extra_info);
1155 const char *name = thread_name (tp);
1156 if (name != NULL)
1157 uiout->field_string ("name", name);
1159 else
1161 uiout->field_string ("target-id", thread_target_id_str (tp));
1164 if (tp->state == THREAD_RUNNING)
1165 uiout->text ("(running)\n");
1166 else
1168 /* The switch above put us at the top of the stack (leaf
1169 frame). */
1170 print_stack_frame (get_selected_frame (NULL),
1171 /* For MI output, print frame level. */
1172 uiout->is_mi_like_p (),
1173 LOCATION, 0);
1176 if (uiout->is_mi_like_p ())
1178 const char *state = "stopped";
1180 if (tp->state == THREAD_RUNNING)
1181 state = "running";
1182 uiout->field_string ("state", state);
1185 core = target_core_of_thread (tp->ptid);
1186 if (uiout->is_mi_like_p () && core != -1)
1187 uiout->field_signed ("core", core);
1190 /* Redirect output to a temporary buffer for the duration
1191 of do_print_thread. */
1193 static void
1194 print_thread (ui_out *uiout, const char *requested_threads,
1195 int global_ids, int pid, int show_global_ids,
1196 int default_inf_num, thread_info *tp, thread_info *current_thread)
1199 do_with_buffered_output (do_print_thread, uiout, requested_threads,
1200 global_ids, pid, show_global_ids,
1201 default_inf_num, tp, current_thread);
1204 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1205 whether REQUESTED_THREADS is a list of global or per-inferior
1206 thread ids. */
1208 static void
1209 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1210 int global_ids, int pid,
1211 int show_global_ids)
1213 int default_inf_num = current_inferior ()->num;
1215 update_thread_list ();
1217 /* Whether we saw any thread. */
1218 bool any_thread = false;
1219 /* Whether the current thread is exited. */
1220 bool current_exited = false;
1222 thread_info *current_thread = (inferior_ptid != null_ptid
1223 ? inferior_thread () : NULL);
1226 /* For backward compatibility, we make a list for MI. A table is
1227 preferable for the CLI, though, because it shows table
1228 headers. */
1229 std::optional<ui_out_emit_list> list_emitter;
1230 std::optional<ui_out_emit_table> table_emitter;
1232 /* We'll be switching threads temporarily below. */
1233 scoped_restore_current_thread restore_thread;
1235 if (uiout->is_mi_like_p ())
1236 list_emitter.emplace (uiout, "threads");
1237 else
1239 int n_threads = 0;
1240 /* The width of the "Target Id" column. Grown below to
1241 accommodate the largest entry. */
1242 size_t target_id_col_width = 17;
1244 for (thread_info *tp : all_threads ())
1246 /* In case REQUESTED_THREADS contains $_thread. */
1247 if (current_thread != nullptr)
1248 switch_to_thread (current_thread);
1250 if (!should_print_thread (requested_threads, default_inf_num,
1251 global_ids, pid, tp))
1252 continue;
1254 /* Switch inferiors so we're looking at the right
1255 target stack. */
1256 switch_to_inferior_no_thread (tp->inf);
1258 target_id_col_width
1259 = std::max (target_id_col_width,
1260 thread_target_id_str (tp).size ());
1262 ++n_threads;
1265 if (n_threads == 0)
1267 if (requested_threads == NULL || *requested_threads == '\0')
1268 uiout->message (_("No threads.\n"));
1269 else
1270 uiout->message (_("No threads match '%s'.\n"),
1271 requested_threads);
1272 return;
1275 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1276 n_threads, "threads");
1278 uiout->table_header (1, ui_left, "current", "");
1279 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1280 if (show_global_ids)
1281 uiout->table_header (4, ui_left, "id", "GId");
1282 uiout->table_header (target_id_col_width, ui_left,
1283 "target-id", "Target Id");
1284 uiout->table_header (1, ui_left, "frame", "Frame");
1285 uiout->table_body ();
1288 for (inferior *inf : all_inferiors ())
1289 for (thread_info *tp : inf->threads ())
1291 any_thread = true;
1293 if (tp == current_thread && tp->state == THREAD_EXITED)
1294 current_exited = true;
1296 print_thread (uiout, requested_threads, global_ids, pid,
1297 show_global_ids, default_inf_num, tp, current_thread);
1300 /* This end scope restores the current thread and the frame
1301 selected before the "info threads" command, and it finishes the
1302 ui-out list or table. */
1305 if (pid == -1 && requested_threads == NULL)
1307 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1308 uiout->field_signed ("current-thread-id", current_thread->global_num);
1310 if (inferior_ptid != null_ptid && current_exited)
1311 uiout->message ("\n\
1312 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1313 print_thread_id (inferior_thread ()));
1314 else if (any_thread && inferior_ptid == null_ptid)
1315 uiout->message ("\n\
1316 No selected thread. See `help thread'.\n");
1320 /* See gdbthread.h. */
1322 void
1323 print_thread_info (struct ui_out *uiout, const char *requested_threads,
1324 int pid)
1326 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1329 /* The options for the "info threads" command. */
1331 struct info_threads_opts
1333 /* For "-gid". */
1334 bool show_global_ids = false;
1337 static const gdb::option::option_def info_threads_option_defs[] = {
1339 gdb::option::flag_option_def<info_threads_opts> {
1340 "gid",
1341 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1342 N_("Show global thread IDs."),
1347 /* Create an option_def_group for the "info threads" options, with
1348 IT_OPTS as context. */
1350 static inline gdb::option::option_def_group
1351 make_info_threads_options_def_group (info_threads_opts *it_opts)
1353 return {{info_threads_option_defs}, it_opts};
1356 /* Implementation of the "info threads" command.
1358 Note: this has the drawback that it _really_ switches
1359 threads, which frees the frame cache. A no-side
1360 effects info-threads command would be nicer. */
1362 static void
1363 info_threads_command (const char *arg, int from_tty)
1365 info_threads_opts it_opts;
1367 auto grp = make_info_threads_options_def_group (&it_opts);
1368 gdb::option::process_options
1369 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1371 print_thread_info_1 (current_uiout, arg, 0, -1, it_opts.show_global_ids);
1374 /* Completer for the "info threads" command. */
1376 static void
1377 info_threads_command_completer (struct cmd_list_element *ignore,
1378 completion_tracker &tracker,
1379 const char *text, const char *word_ignored)
1381 const auto grp = make_info_threads_options_def_group (nullptr);
1383 if (gdb::option::complete_options
1384 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1385 return;
1387 /* Convenience to let the user know what the option can accept. */
1388 if (*text == '\0')
1390 gdb::option::complete_on_all_options (tracker, grp);
1391 /* Keep this "ID" in sync with what "help info threads"
1392 says. */
1393 tracker.add_completion (make_unique_xstrdup ("ID"));
1397 /* See gdbthread.h. */
1399 void
1400 switch_to_thread_no_regs (struct thread_info *thread)
1402 gdb_assert (thread != nullptr);
1403 threads_debug_printf ("thread = %s", thread->ptid.to_string ().c_str ());
1405 struct inferior *inf = thread->inf;
1407 set_current_program_space (inf->pspace);
1408 set_current_inferior (inf);
1410 current_thread_ = thread;
1411 inferior_ptid = current_thread_->ptid;
1414 /* See gdbthread.h. */
1416 void
1417 switch_to_no_thread ()
1419 if (current_thread_ == nullptr)
1420 return;
1422 threads_debug_printf ("thread = NONE");
1424 current_thread_ = nullptr;
1425 inferior_ptid = null_ptid;
1426 reinit_frame_cache ();
1429 /* See gdbthread.h. */
1431 void
1432 switch_to_thread (thread_info *thr)
1434 gdb_assert (thr != NULL);
1436 if (is_current_thread (thr))
1437 return;
1439 switch_to_thread_no_regs (thr);
1441 reinit_frame_cache ();
1444 /* See gdbsupport/common-gdbthread.h. */
1446 void
1447 switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
1449 thread_info *thr = proc_target->find_thread (ptid);
1450 switch_to_thread (thr);
1453 /* See frame.h. */
1455 void
1456 scoped_restore_current_thread::restore ()
1458 /* If an entry of thread_info was previously selected, it won't be
1459 deleted because we've increased its refcount. The thread represented
1460 by this thread_info entry may have already exited (due to normal exit,
1461 detach, etc), so the thread_info.state is THREAD_EXITED. */
1462 if (m_thread != NULL
1463 /* If the previously selected thread belonged to a process that has
1464 in the mean time exited (or killed, detached, etc.), then don't revert
1465 back to it, but instead simply drop back to no thread selected. */
1466 && m_inf->pid != 0)
1467 switch_to_thread (m_thread.get ());
1468 else
1469 switch_to_inferior_no_thread (m_inf.get ());
1471 /* The running state of the originally selected thread may have
1472 changed, so we have to recheck it here. */
1473 if (inferior_ptid != null_ptid
1474 && m_was_stopped
1475 && m_thread->state == THREAD_STOPPED
1476 && target_has_registers ()
1477 && target_has_stack ()
1478 && target_has_memory ())
1479 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1482 scoped_restore_current_thread::~scoped_restore_current_thread ()
1484 if (m_dont_restore)
1485 m_lang.dont_restore ();
1486 else
1487 restore ();
1490 scoped_restore_current_thread::scoped_restore_current_thread ()
1492 m_inf = inferior_ref::new_reference (current_inferior ());
1494 if (inferior_ptid != null_ptid)
1496 m_thread = thread_info_ref::new_reference (inferior_thread ());
1498 m_was_stopped = m_thread->state == THREAD_STOPPED;
1499 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
1503 scoped_restore_current_thread::scoped_restore_current_thread
1504 (scoped_restore_current_thread &&rhs)
1505 : m_dont_restore (std::move (rhs.m_dont_restore)),
1506 m_thread (std::move (rhs.m_thread)),
1507 m_inf (std::move (rhs.m_inf)),
1508 m_selected_frame_id (std::move (rhs.m_selected_frame_id)),
1509 m_selected_frame_level (std::move (rhs.m_selected_frame_level)),
1510 m_was_stopped (std::move (rhs.m_was_stopped)),
1511 m_lang (std::move (rhs.m_lang))
1513 /* Deactivate the rhs. */
1514 rhs.m_dont_restore = true;
1517 /* See gdbthread.h. */
1520 show_thread_that_caused_stop (void)
1522 return highest_thread_num > 1;
1525 /* See gdbthread.h. */
1528 show_inferior_qualified_tids (void)
1530 auto inf = inferior_list.begin ();
1531 if (inf->num != 1)
1532 return true;
1533 ++inf;
1534 return inf != inferior_list.end ();
1537 /* See gdbthread.h. */
1539 const char *
1540 print_thread_id (struct thread_info *thr)
1542 if (show_inferior_qualified_tids ())
1543 return print_full_thread_id (thr);
1545 char *s = get_print_cell ();
1547 gdb_assert (thr != nullptr);
1548 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1549 return s;
1552 /* See gdbthread.h. */
1554 const char *
1555 print_full_thread_id (struct thread_info *thr)
1557 char *s = get_print_cell ();
1559 gdb_assert (thr != nullptr);
1560 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1561 return s;
1564 /* Sort an array of struct thread_info pointers by thread ID (first by
1565 inferior number, and then by per-inferior thread number). Sorts in
1566 ascending order. */
1568 static bool
1569 tp_array_compar_ascending (const thread_info_ref &a, const thread_info_ref &b)
1571 if (a->inf->num != b->inf->num)
1572 return a->inf->num < b->inf->num;
1574 return (a->per_inf_num < b->per_inf_num);
1577 /* Sort an array of struct thread_info pointers by thread ID (first by
1578 inferior number, and then by per-inferior thread number). Sorts in
1579 descending order. */
1581 static bool
1582 tp_array_compar_descending (const thread_info_ref &a, const thread_info_ref &b)
1584 if (a->inf->num != b->inf->num)
1585 return a->inf->num > b->inf->num;
1587 return (a->per_inf_num > b->per_inf_num);
1590 /* See gdbthread.h. */
1592 void
1593 thread_try_catch_cmd (thread_info *thr, std::optional<int> ada_task,
1594 const char *cmd, int from_tty,
1595 const qcs_flags &flags)
1597 gdb_assert (is_current_thread (thr));
1599 /* The thread header is computed before running the command since
1600 the command can change the inferior, which is not permitted
1601 by thread_target_id_str. */
1602 std::string thr_header;
1603 if (ada_task.has_value ())
1604 thr_header = string_printf (_("\nTask ID %d:\n"), *ada_task);
1605 else
1606 thr_header = string_printf (_("\nThread %s (%s):\n"),
1607 print_thread_id (thr),
1608 thread_target_id_str (thr).c_str ());
1612 std::string cmd_result;
1613 execute_command_to_string
1614 (cmd_result, cmd, from_tty, gdb_stdout->term_out ());
1615 if (!flags.silent || cmd_result.length () > 0)
1617 if (!flags.quiet)
1618 gdb_printf ("%s", thr_header.c_str ());
1619 gdb_printf ("%s", cmd_result.c_str ());
1622 catch (const gdb_exception_error &ex)
1624 if (!flags.silent)
1626 if (!flags.quiet)
1627 gdb_printf ("%s", thr_header.c_str ());
1628 if (flags.cont)
1629 gdb_printf ("%s\n", ex.what ());
1630 else
1631 throw;
1636 /* Option definition of "thread apply"'s "-ascending" option. */
1638 static const gdb::option::flag_option_def<> ascending_option_def = {
1639 "ascending",
1640 N_("\
1641 Call COMMAND for all threads in ascending order.\n\
1642 The default is descending order."),
1645 /* The qcs command line flags for the "thread apply" commands. Keep
1646 this in sync with the "frame apply" commands. */
1648 using qcs_flag_option_def
1649 = gdb::option::flag_option_def<qcs_flags>;
1651 static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1652 qcs_flag_option_def {
1653 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1654 N_("Disables printing the thread information."),
1657 qcs_flag_option_def {
1658 "c", [] (qcs_flags *opt) { return &opt->cont; },
1659 N_("Print any error raised by COMMAND and continue."),
1662 qcs_flag_option_def {
1663 "s", [] (qcs_flags *opt) { return &opt->silent; },
1664 N_("Silently ignore any errors or empty output produced by COMMAND."),
1668 /* Create an option_def_group for the "thread apply all" options, with
1669 ASCENDING and FLAGS as context. */
1671 static inline std::array<gdb::option::option_def_group, 2>
1672 make_thread_apply_all_options_def_group (bool *ascending,
1673 qcs_flags *flags)
1675 return {{
1676 { {ascending_option_def.def ()}, ascending},
1677 { {thr_qcs_flags_option_defs}, flags },
1681 /* Create an option_def_group for the "thread apply" options, with
1682 FLAGS as context. */
1684 static inline gdb::option::option_def_group
1685 make_thread_apply_options_def_group (qcs_flags *flags)
1687 return {{thr_qcs_flags_option_defs}, flags};
1690 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1691 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1692 of two numbers separated by a hyphen. Examples:
1694 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1695 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1696 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1698 static void
1699 thread_apply_all_command (const char *cmd, int from_tty)
1701 bool ascending = false;
1702 qcs_flags flags;
1704 auto group = make_thread_apply_all_options_def_group (&ascending,
1705 &flags);
1706 gdb::option::process_options
1707 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1709 validate_flags_qcs ("thread apply all", &flags);
1711 if (cmd == NULL || *cmd == '\000')
1712 error (_("Please specify a command at the end of 'thread apply all'"));
1714 update_thread_list ();
1716 int tc = live_threads_count ();
1717 if (tc != 0)
1719 /* Save a copy of the thread list and increment each thread's
1720 refcount while executing the command in the context of each
1721 thread, in case the command is one that wipes threads. E.g.,
1722 detach, kill, disconnect, etc., or even normally continuing
1723 over an inferior or thread exit. */
1724 std::vector<thread_info_ref> thr_list_cpy;
1725 thr_list_cpy.reserve (tc);
1727 for (thread_info *tp : all_non_exited_threads ())
1728 thr_list_cpy.push_back (thread_info_ref::new_reference (tp));
1729 gdb_assert (thr_list_cpy.size () == tc);
1731 auto *sorter = (ascending
1732 ? tp_array_compar_ascending
1733 : tp_array_compar_descending);
1734 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
1736 scoped_restore_current_thread restore_thread;
1738 for (thread_info_ref &thr : thr_list_cpy)
1739 if (switch_to_thread_if_alive (thr.get ()))
1740 thread_try_catch_cmd (thr.get (), {}, cmd, from_tty, flags);
1744 /* Completer for "thread apply [ID list]". */
1746 static void
1747 thread_apply_command_completer (cmd_list_element *ignore,
1748 completion_tracker &tracker,
1749 const char *text, const char * /*word*/)
1751 /* Don't leave this to complete_options because there's an early
1752 return below. */
1753 tracker.set_use_custom_word_point (true);
1755 tid_range_parser parser;
1756 parser.init (text, current_inferior ()->num);
1760 while (!parser.finished ())
1762 int inf_num, thr_start, thr_end;
1764 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1765 break;
1767 if (parser.in_star_range () || parser.in_thread_range ())
1768 parser.skip_range ();
1771 catch (const gdb_exception_error &ex)
1773 /* get_tid_range throws if it parses a negative number, for
1774 example. But a seemingly negative number may be the start of
1775 an option instead. */
1778 const char *cmd = parser.cur_tok ();
1780 if (cmd == text)
1782 /* No thread ID list yet. */
1783 return;
1786 /* Check if we're past a valid thread ID list already. */
1787 if (parser.finished ()
1788 && cmd > text && !isspace (cmd[-1]))
1789 return;
1791 /* We're past the thread ID list, advance word point. */
1792 tracker.advance_custom_word_point_by (cmd - text);
1793 text = cmd;
1795 const auto group = make_thread_apply_options_def_group (nullptr);
1796 if (gdb::option::complete_options
1797 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1798 return;
1800 complete_nested_command_line (tracker, text);
1803 /* Completer for "thread apply all". */
1805 static void
1806 thread_apply_all_command_completer (cmd_list_element *ignore,
1807 completion_tracker &tracker,
1808 const char *text, const char *word)
1810 const auto group = make_thread_apply_all_options_def_group (nullptr,
1811 nullptr);
1812 if (gdb::option::complete_options
1813 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1814 return;
1816 complete_nested_command_line (tracker, text);
1819 /* Implementation of the "thread apply" command. */
1821 static void
1822 thread_apply_command (const char *tidlist, int from_tty)
1824 qcs_flags flags;
1825 const char *cmd = NULL;
1826 tid_range_parser parser;
1828 if (tidlist == NULL || *tidlist == '\000')
1829 error (_("Please specify a thread ID list"));
1831 parser.init (tidlist, current_inferior ()->num);
1832 while (!parser.finished ())
1834 int inf_num, thr_start, thr_end;
1836 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1837 break;
1840 cmd = parser.cur_tok ();
1842 auto group = make_thread_apply_options_def_group (&flags);
1843 gdb::option::process_options
1844 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1846 validate_flags_qcs ("thread apply", &flags);
1848 if (*cmd == '\0')
1849 error (_("Please specify a command following the thread ID list"));
1851 if (tidlist == cmd || isdigit (cmd[0]))
1852 invalid_thread_id_error (cmd);
1854 scoped_restore_current_thread restore_thread;
1856 parser.init (tidlist, current_inferior ()->num);
1857 while (!parser.finished ())
1859 struct thread_info *tp = NULL;
1860 struct inferior *inf;
1861 int inf_num, thr_num;
1863 parser.get_tid (&inf_num, &thr_num);
1864 inf = find_inferior_id (inf_num);
1865 if (inf != NULL)
1866 tp = find_thread_id (inf, thr_num);
1868 if (parser.in_star_range ())
1870 if (inf == NULL)
1872 warning (_("Unknown inferior %d"), inf_num);
1873 parser.skip_range ();
1874 continue;
1877 /* No use looking for threads past the highest thread number
1878 the inferior ever had. */
1879 if (thr_num >= inf->highest_thread_num)
1880 parser.skip_range ();
1882 /* Be quiet about unknown threads numbers. */
1883 if (tp == NULL)
1884 continue;
1887 if (tp == NULL)
1889 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1890 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1891 else
1892 warning (_("Unknown thread %d"), thr_num);
1893 continue;
1896 if (!switch_to_thread_if_alive (tp))
1898 warning (_("Thread %s has terminated."), print_thread_id (tp));
1899 continue;
1902 thread_try_catch_cmd (tp, {}, cmd, from_tty, flags);
1907 /* Implementation of the "taas" command. */
1909 static void
1910 taas_command (const char *cmd, int from_tty)
1912 if (cmd == NULL || *cmd == '\0')
1913 error (_("Please specify a command to apply on all threads"));
1914 std::string expanded = std::string ("thread apply all -s ") + cmd;
1915 execute_command (expanded.c_str (), from_tty);
1918 /* Implementation of the "tfaas" command. */
1920 static void
1921 tfaas_command (const char *cmd, int from_tty)
1923 if (cmd == NULL || *cmd == '\0')
1924 error (_("Please specify a command to apply on all frames of all threads"));
1925 std::string expanded
1926 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1927 execute_command (expanded.c_str (), from_tty);
1930 /* Switch to the specified thread, or print the current thread. */
1932 void
1933 thread_command (const char *tidstr, int from_tty)
1935 if (tidstr == NULL)
1937 if (inferior_ptid == null_ptid)
1938 error (_("No thread selected"));
1940 if (target_has_stack ())
1942 struct thread_info *tp = inferior_thread ();
1944 if (tp->state == THREAD_EXITED)
1945 gdb_printf (_("[Current thread is %s (%s) (exited)]\n"),
1946 print_thread_id (tp),
1947 target_pid_to_str (inferior_ptid).c_str ());
1948 else
1949 gdb_printf (_("[Current thread is %s (%s)]\n"),
1950 print_thread_id (tp),
1951 target_pid_to_str (inferior_ptid).c_str ());
1953 else
1954 error (_("No stack."));
1956 else
1958 ptid_t previous_ptid = inferior_ptid;
1960 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1962 /* Print if the thread has not changed, otherwise an event will
1963 be sent. */
1964 if (inferior_ptid == previous_ptid)
1966 print_selected_thread_frame (current_uiout,
1967 USER_SELECTED_THREAD
1968 | USER_SELECTED_FRAME);
1970 else
1971 notify_user_selected_context_changed
1972 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1976 /* Implementation of `thread name'. */
1978 static void
1979 thread_name_command (const char *arg, int from_tty)
1981 struct thread_info *info;
1983 if (inferior_ptid == null_ptid)
1984 error (_("No thread selected"));
1986 arg = skip_spaces (arg);
1988 info = inferior_thread ();
1989 info->set_name (arg != nullptr ? make_unique_xstrdup (arg) : nullptr);
1992 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1994 static void
1995 thread_find_command (const char *arg, int from_tty)
1997 const char *tmp;
1998 unsigned long match = 0;
2000 if (arg == NULL || *arg == '\0')
2001 error (_("Command requires an argument."));
2003 tmp = re_comp (arg);
2004 if (tmp != 0)
2005 error (_("Invalid regexp (%s): %s"), tmp, arg);
2007 /* We're going to be switching threads. */
2008 scoped_restore_current_thread restore_thread;
2010 update_thread_list ();
2012 for (thread_info *tp : all_threads ())
2014 switch_to_inferior_no_thread (tp->inf);
2016 if (tp->name () != nullptr && re_exec (tp->name ()))
2018 gdb_printf (_("Thread %s has name '%s'\n"),
2019 print_thread_id (tp), tp->name ());
2020 match++;
2023 tmp = target_thread_name (tp);
2024 if (tmp != NULL && re_exec (tmp))
2026 gdb_printf (_("Thread %s has target name '%s'\n"),
2027 print_thread_id (tp), tmp);
2028 match++;
2031 std::string name = target_pid_to_str (tp->ptid);
2032 if (!name.empty () && re_exec (name.c_str ()))
2034 gdb_printf (_("Thread %s has target id '%s'\n"),
2035 print_thread_id (tp), name.c_str ());
2036 match++;
2039 tmp = target_extra_thread_info (tp);
2040 if (tmp != NULL && re_exec (tmp))
2042 gdb_printf (_("Thread %s has extra info '%s'\n"),
2043 print_thread_id (tp), tmp);
2044 match++;
2047 if (!match)
2048 gdb_printf (_("No threads match '%s'\n"), arg);
2051 /* Print notices when new threads are attached and detached. */
2052 bool print_thread_events = true;
2053 static void
2054 show_print_thread_events (struct ui_file *file, int from_tty,
2055 struct cmd_list_element *c, const char *value)
2057 gdb_printf (file,
2058 _("Printing of thread events is %s.\n"),
2059 value);
2062 /* See gdbthread.h. */
2064 void
2065 thread_select (const char *tidstr, thread_info *tp)
2067 if (!switch_to_thread_if_alive (tp))
2068 error (_("Thread ID %s has terminated."), tidstr);
2070 annotate_thread_changed ();
2072 /* Since the current thread may have changed, see if there is any
2073 exited thread we can now delete. */
2074 delete_exited_threads ();
2077 /* Print thread and frame switch command response. */
2079 void
2080 print_selected_thread_frame (struct ui_out *uiout,
2081 user_selected_what selection)
2083 struct thread_info *tp = inferior_thread ();
2085 if (selection & USER_SELECTED_THREAD)
2087 if (uiout->is_mi_like_p ())
2089 uiout->field_signed ("new-thread-id",
2090 inferior_thread ()->global_num);
2092 else
2094 uiout->text ("[Switching to thread ");
2095 uiout->field_string ("new-thread-id", print_thread_id (tp));
2096 uiout->text (" (");
2097 uiout->text (target_pid_to_str (inferior_ptid));
2098 uiout->text (")]");
2102 if (tp->state == THREAD_RUNNING)
2104 if (selection & USER_SELECTED_THREAD)
2105 uiout->text ("(running)\n");
2107 else if (selection & USER_SELECTED_FRAME)
2109 if (selection & USER_SELECTED_THREAD)
2110 uiout->text ("\n");
2112 if (has_stack_frames ())
2113 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
2114 1, SRC_AND_LOC, 1);
2118 /* Update the 'threads_executing' global based on the threads we know
2119 about right now. This is used by infrun to tell whether we should
2120 pull events out of the current target. */
2122 static void
2123 update_threads_executing (void)
2125 process_stratum_target *targ = current_inferior ()->process_target ();
2127 if (targ == NULL)
2128 return;
2130 targ->threads_executing = false;
2132 for (inferior *inf : all_non_exited_inferiors (targ))
2134 if (!inf->has_execution ())
2135 continue;
2137 /* If the process has no threads, then it must be we have a
2138 process-exit event pending. */
2139 if (inf->thread_list.empty ())
2141 targ->threads_executing = true;
2142 return;
2145 for (thread_info *tp : inf->non_exited_threads ())
2147 if (tp->executing ())
2149 targ->threads_executing = true;
2150 return;
2156 void
2157 update_thread_list (void)
2159 target_update_thread_list ();
2160 update_threads_executing ();
2163 /* See gdbthread.h. */
2165 const char *
2166 thread_name (thread_info *thread)
2168 /* Use the manually set name if there is one. */
2169 const char *name = thread->name ();
2170 if (name != nullptr)
2171 return name;
2173 /* Otherwise, ask the target. Ensure we query the right target stack. */
2174 scoped_restore_current_thread restore_thread;
2175 if (thread->inf != current_inferior ())
2176 switch_to_inferior_no_thread (thread->inf);
2178 return target_thread_name (thread);
2181 /* See gdbthread.h. */
2183 const char *
2184 thread_state_string (enum thread_state state)
2186 switch (state)
2188 case THREAD_STOPPED:
2189 return "STOPPED";
2191 case THREAD_RUNNING:
2192 return "RUNNING";
2194 case THREAD_EXITED:
2195 return "EXITED";
2198 gdb_assert_not_reached ("unknown thread state");
2201 /* Return a new value for the selected thread's id. Return a value of
2202 0 if no thread is selected. If GLOBAL is true, return the thread's
2203 global number. Otherwise return the per-inferior number. */
2205 static struct value *
2206 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2208 int int_val;
2210 if (inferior_ptid == null_ptid)
2211 int_val = 0;
2212 else
2214 thread_info *tp = inferior_thread ();
2215 if (global)
2216 int_val = tp->global_num;
2217 else
2218 int_val = tp->per_inf_num;
2221 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2224 /* Return a new value for the selected thread's per-inferior thread
2225 number. Return a value of 0 if no thread is selected, or no
2226 threads exist. */
2228 static struct value *
2229 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2230 struct internalvar *var,
2231 void *ignore)
2233 return thread_num_make_value_helper (gdbarch, 0);
2236 /* Return a new value for the selected thread's global id. Return a
2237 value of 0 if no thread is selected, or no threads exist. */
2239 static struct value *
2240 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2241 void *ignore)
2243 return thread_num_make_value_helper (gdbarch, 1);
2246 /* Return a new value for the number of non-exited threads in the current
2247 inferior. If there are no threads in the current inferior return a
2248 value of 0. */
2250 static struct value *
2251 inferior_thread_count_make_value (struct gdbarch *gdbarch,
2252 struct internalvar *var, void *ignore)
2254 int int_val = 0;
2256 update_thread_list ();
2258 if (inferior_ptid != null_ptid)
2259 int_val = current_inferior ()->non_exited_threads ().size ();
2261 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2264 /* Commands with a prefix of `thread'. */
2265 struct cmd_list_element *thread_cmd_list = NULL;
2267 /* Implementation of `thread' variable. */
2269 static const struct internalvar_funcs thread_funcs =
2271 thread_id_per_inf_num_make_value,
2272 NULL,
2275 /* Implementation of `gthread' variable. */
2277 static const struct internalvar_funcs gthread_funcs =
2279 global_thread_id_make_value,
2280 NULL,
2283 /* Implementation of `_inferior_thread_count` convenience variable. */
2285 static const struct internalvar_funcs inferior_thread_count_funcs =
2287 inferior_thread_count_make_value,
2288 NULL,
2291 void _initialize_thread ();
2292 void
2293 _initialize_thread ()
2295 static struct cmd_list_element *thread_apply_list = NULL;
2296 cmd_list_element *c;
2298 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2300 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2301 suggests. */
2302 static std::string info_threads_help
2303 = gdb::option::build_help (_("\
2304 Display currently known threads.\n\
2305 Usage: info threads [OPTION]... [ID]...\n\
2306 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2307 Otherwise, all threads are displayed.\n\
2309 Options:\n\
2310 %OPTIONS%"),
2311 info_threads_opts);
2313 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2314 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
2316 cmd_list_element *thread_cmd
2317 = add_prefix_cmd ("thread", class_run, thread_command, _("\
2318 Use this command to switch between threads.\n\
2319 The new thread ID must be currently known."),
2320 &thread_cmd_list, 1, &cmdlist);
2322 add_com_alias ("t", thread_cmd, class_run, 1);
2324 #define THREAD_APPLY_OPTION_HELP "\
2325 Prints per-inferior thread number and target system's thread id\n\
2326 followed by COMMAND output.\n\
2328 By default, an error raised during the execution of COMMAND\n\
2329 aborts \"thread apply\".\n\
2331 Options:\n\
2332 %OPTIONS%"
2334 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2336 static std::string thread_apply_help = gdb::option::build_help (_("\
2337 Apply a command to a list of threads.\n\
2338 Usage: thread apply ID... [OPTION]... COMMAND\n\
2339 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2340 THREAD_APPLY_OPTION_HELP),
2341 thread_apply_opts);
2343 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2344 thread_apply_help.c_str (),
2345 &thread_apply_list, 1,
2346 &thread_cmd_list);
2347 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
2349 const auto thread_apply_all_opts
2350 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2352 static std::string thread_apply_all_help = gdb::option::build_help (_("\
2353 Apply a command to all threads.\n\
2355 Usage: thread apply all [OPTION]... COMMAND\n"
2356 THREAD_APPLY_OPTION_HELP),
2357 thread_apply_all_opts);
2359 c = add_cmd ("all", class_run, thread_apply_all_command,
2360 thread_apply_all_help.c_str (),
2361 &thread_apply_list);
2362 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2364 c = add_com ("taas", class_run, taas_command, _("\
2365 Apply a command to all threads (ignoring errors and empty output).\n\
2366 Usage: taas [OPTION]... COMMAND\n\
2367 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2368 See \"help thread apply all\" for available options."));
2369 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2371 c = add_com ("tfaas", class_run, tfaas_command, _("\
2372 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2373 Usage: tfaas [OPTION]... COMMAND\n\
2374 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2375 See \"help frame apply all\" for available options."));
2376 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
2378 add_cmd ("name", class_run, thread_name_command,
2379 _("Set the current thread's name.\n\
2380 Usage: thread name [NAME]\n\
2381 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2383 add_cmd ("find", class_run, thread_find_command, _("\
2384 Find threads that match a regular expression.\n\
2385 Usage: thread find REGEXP\n\
2386 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2387 &thread_cmd_list);
2389 add_setshow_boolean_cmd ("thread-events", no_class,
2390 &print_thread_events, _("\
2391 Set printing of thread events (such as thread start and exit)."), _("\
2392 Show printing of thread events (such as thread start and exit)."), NULL,
2393 NULL,
2394 show_print_thread_events,
2395 &setprintlist, &showprintlist);
2397 add_setshow_boolean_cmd ("threads", class_maintenance, &debug_threads, _("\
2398 Set thread debugging."), _("\
2399 Show thread debugging."), _("\
2400 When on messages about thread creation and deletion are printed."),
2401 nullptr,
2402 show_debug_threads,
2403 &setdebuglist, &showdebuglist);
2405 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2406 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);
2407 create_internalvar_type_lazy ("_inferior_thread_count",
2408 &inferior_thread_count_funcs, NULL);