Automatic date update in version.in
[binutils-gdb.git] / gdb / thread.c
blob60a1bef8cf0ac67b9f8a9ff471b49253788d3e6c
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 "value.h"
28 #include "target.h"
29 #include "gdbthread.h"
30 #include "command.h"
31 #include "gdbcmd.h"
32 #include "regcache.h"
33 #include "btrace.h"
35 #include <ctype.h>
36 #include <sys/types.h>
37 #include <signal.h>
38 #include "ui-out.h"
39 #include "observable.h"
40 #include "annotate.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-option.h"
43 #include "gdbsupport/gdb_regex.h"
44 #include "cli/cli-utils.h"
45 #include "thread-fsm.h"
46 #include "tid-parse.h"
47 #include <algorithm>
48 #include <optional>
49 #include "inline-frame.h"
50 #include "stack.h"
51 #include "interps.h"
53 /* See gdbthread.h. */
55 bool debug_threads = false;
57 /* Implement 'show debug threads'. */
59 static void
60 show_debug_threads (struct ui_file *file, int from_tty,
61 struct cmd_list_element *c, const char *value)
63 gdb_printf (file, _("Thread debugging is \"%s\".\n"), value);
66 /* Definition of struct thread_info exported to gdbthread.h. */
68 /* Prototypes for local functions. */
70 static int highest_thread_num;
72 /* The current/selected thread. */
73 static thread_info *current_thread_;
75 /* Returns true if THR is the current thread. */
77 static bool
78 is_current_thread (const thread_info *thr)
80 return thr == current_thread_;
83 struct thread_info*
84 inferior_thread (void)
86 gdb_assert (current_thread_ != nullptr);
87 return current_thread_;
90 /* Delete the breakpoint pointed at by BP_P, if there's one. */
92 static void
93 delete_thread_breakpoint (struct breakpoint **bp_p)
95 if (*bp_p != NULL)
97 delete_breakpoint (*bp_p);
98 *bp_p = NULL;
102 void
103 delete_step_resume_breakpoint (struct thread_info *tp)
105 if (tp != NULL)
106 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
109 void
110 delete_exception_resume_breakpoint (struct thread_info *tp)
112 if (tp != NULL)
113 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
116 /* See gdbthread.h. */
118 void
119 delete_single_step_breakpoints (struct thread_info *tp)
121 if (tp != NULL)
122 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
125 /* Delete the breakpoint pointed at by BP_P at the next stop, if
126 there's one. */
128 static void
129 delete_at_next_stop (struct breakpoint **bp)
131 if (*bp != NULL)
133 (*bp)->disposition = disp_del_at_next_stop;
134 *bp = NULL;
138 /* See gdbthread.h. */
141 thread_has_single_step_breakpoints_set (struct thread_info *tp)
143 return tp->control.single_step_breakpoints != NULL;
146 /* See gdbthread.h. */
149 thread_has_single_step_breakpoint_here (struct thread_info *tp,
150 const address_space *aspace,
151 CORE_ADDR addr)
153 struct breakpoint *ss_bps = tp->control.single_step_breakpoints;
155 return (ss_bps != NULL
156 && breakpoint_has_location_inserted_here (ss_bps, aspace, addr));
159 /* See gdbthread.h. */
161 void
162 thread_cancel_execution_command (struct thread_info *thr)
164 if (thr->thread_fsm () != nullptr)
166 std::unique_ptr<thread_fsm> fsm = thr->release_thread_fsm ();
167 fsm->clean_up (thr);
171 static void
172 clear_thread_inferior_resources (struct thread_info *tp)
174 /* NOTE: this will take care of any left-over step_resume breakpoints,
175 but not any user-specified thread-specific breakpoints. We can not
176 delete the breakpoint straight-off, because the inferior might not
177 be stopped at the moment. */
178 delete_at_next_stop (&tp->control.step_resume_breakpoint);
179 delete_at_next_stop (&tp->control.exception_resume_breakpoint);
180 delete_at_next_stop (&tp->control.single_step_breakpoints);
182 delete_longjmp_breakpoint_at_next_stop (tp->global_num);
184 bpstat_clear (&tp->control.stop_bpstat);
186 btrace_teardown (tp);
188 thread_cancel_execution_command (tp);
190 clear_inline_frame_state (tp);
193 /* Notify interpreters and observers that thread T has exited. */
195 static void
196 notify_thread_exited (thread_info *t, std::optional<ULONGEST> exit_code,
197 int silent)
199 if (!silent && print_thread_events)
201 if (exit_code.has_value ())
202 gdb_printf (_("[%s exited with code %s]\n"),
203 target_pid_to_str (t->ptid).c_str (),
204 pulongest (*exit_code));
205 else
206 gdb_printf (_("[%s exited]\n"),
207 target_pid_to_str (t->ptid).c_str ());
210 interps_notify_thread_exited (t, exit_code, silent);
211 gdb::observers::thread_exit.notify (t, exit_code, silent);
214 /* See gdbthread.h. */
216 void
217 set_thread_exited (thread_info *tp, std::optional<ULONGEST> exit_code,
218 bool silent)
220 /* Dead threads don't need to step-over. Remove from chain. */
221 if (thread_is_in_step_over_chain (tp))
222 global_thread_step_over_chain_remove (tp);
224 if (tp->state != THREAD_EXITED)
226 process_stratum_target *proc_target = tp->inf->process_target ();
228 /* Some targets unpush themselves from the inferior's target stack before
229 clearing the inferior's thread list (which marks all threads as exited,
230 and therefore leads to this function). In this case, the inferior's
231 process target will be nullptr when we arrive here.
233 See also the comment in inferior::unpush_target. */
234 if (proc_target != nullptr)
235 proc_target->maybe_remove_resumed_with_pending_wait_status (tp);
237 notify_thread_exited (tp, exit_code, silent);
239 /* Tag it as exited. */
240 tp->state = THREAD_EXITED;
242 /* Clear breakpoints, etc. associated with this thread. */
243 clear_thread_inferior_resources (tp);
245 /* Remove from the ptid_t map. We don't want for
246 inferior::find_thread to find exited threads. Also, the target
247 may reuse the ptid for a new thread, and there can only be
248 one value per key; adding a new thread with the same ptid_t
249 would overwrite the exited thread's ptid entry. */
250 size_t nr_deleted = tp->inf->ptid_thread_map.erase (tp->ptid);
251 gdb_assert (nr_deleted == 1);
255 void
256 init_thread_list (void)
258 highest_thread_num = 0;
260 for (inferior *inf : all_inferiors ())
261 inf->clear_thread_list ();
264 /* Allocate a new thread of inferior INF with target id PTID and add
265 it to the thread list. */
267 static struct thread_info *
268 new_thread (struct inferior *inf, ptid_t ptid)
270 thread_info *tp = new thread_info (inf, ptid);
272 threads_debug_printf ("creating a new thread object, inferior %d, ptid %s",
273 inf->num, ptid.to_string ().c_str ());
275 inf->thread_list.push_back (*tp);
277 /* A thread with this ptid should not exist in the map yet. */
278 gdb_assert (inf->ptid_thread_map.find (ptid) == inf->ptid_thread_map.end ());
280 inf->ptid_thread_map[ptid] = tp;
282 return tp;
285 /* Notify interpreters and observers that thread T has been created. */
287 static void
288 notify_new_thread (thread_info *t)
290 interps_notify_new_thread (t);
291 gdb::observers::new_thread.notify (t);
294 struct thread_info *
295 add_thread_silent (process_stratum_target *targ, ptid_t ptid)
297 gdb_assert (targ != nullptr);
299 inferior *inf = find_inferior_ptid (targ, ptid);
301 threads_debug_printf ("add thread to inferior %d, ptid %s, target %s",
302 inf->num, ptid.to_string ().c_str (),
303 targ->shortname ());
305 /* We may have an old thread with the same id in the thread list.
306 If we do, it must be dead, otherwise we wouldn't be adding a new
307 thread with the same id. The OS is reusing this id --- delete
308 the old thread, and create a new one. */
309 thread_info *tp = inf->find_thread (ptid);
310 if (tp != nullptr)
311 delete_thread (tp);
313 tp = new_thread (inf, ptid);
314 notify_new_thread (tp);
316 return tp;
319 struct thread_info *
320 add_thread_with_info (process_stratum_target *targ, ptid_t ptid,
321 private_thread_info_up priv)
323 thread_info *result = add_thread_silent (targ, ptid);
325 result->priv = std::move (priv);
327 if (print_thread_events)
328 gdb_printf (_("[New %s]\n"), target_pid_to_str (ptid).c_str ());
330 annotate_new_thread ();
331 return result;
334 struct thread_info *
335 add_thread (process_stratum_target *targ, ptid_t ptid)
337 return add_thread_with_info (targ, ptid, NULL);
340 private_thread_info::~private_thread_info () = default;
342 thread_info::thread_info (struct inferior *inf_, ptid_t ptid_)
343 : ptid (ptid_), inf (inf_)
345 gdb_assert (inf_ != NULL);
347 this->global_num = ++highest_thread_num;
348 this->per_inf_num = ++inf_->highest_thread_num;
350 /* Nothing to follow yet. */
351 this->pending_follow.set_spurious ();
354 /* See gdbthread.h. */
356 thread_info::~thread_info ()
358 threads_debug_printf ("thread %s", this->ptid.to_string ().c_str ());
361 /* See gdbthread.h. */
363 bool
364 thread_info::deletable () const
366 /* If this is the current thread, or there's code out there that
367 relies on it existing (refcount > 0) we can't delete yet. */
368 return refcount () == 0 && !is_current_thread (this);
371 /* See gdbthread.h. */
373 void
374 thread_info::set_executing (bool executing)
376 m_executing = executing;
377 if (executing)
378 this->clear_stop_pc ();
381 /* See gdbthread.h. */
383 void
384 thread_info::set_resumed (bool resumed)
386 if (resumed == m_resumed)
387 return;
389 process_stratum_target *proc_target = this->inf->process_target ();
391 /* If we transition from resumed to not resumed, we might need to remove
392 the thread from the resumed threads with pending statuses list. */
393 if (!resumed)
394 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
396 m_resumed = resumed;
398 /* If we transition from not resumed to resumed, we might need to add
399 the thread to the resumed threads with pending statuses list. */
400 if (resumed)
401 proc_target->maybe_add_resumed_with_pending_wait_status (this);
404 /* See gdbthread.h. */
406 void
407 thread_info::set_pending_waitstatus (const target_waitstatus &ws)
409 gdb_assert (!this->has_pending_waitstatus ());
411 m_suspend.waitstatus = ws;
412 m_suspend.waitstatus_pending_p = 1;
414 process_stratum_target *proc_target = this->inf->process_target ();
415 proc_target->maybe_add_resumed_with_pending_wait_status (this);
418 /* See gdbthread.h. */
420 void
421 thread_info::clear_pending_waitstatus ()
423 gdb_assert (this->has_pending_waitstatus ());
425 process_stratum_target *proc_target = this->inf->process_target ();
426 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
428 m_suspend.waitstatus_pending_p = 0;
431 /* See gdbthread.h. */
433 void
434 thread_info::set_thread_options (gdb_thread_options thread_options)
436 gdb_assert (this->state != THREAD_EXITED);
437 gdb_assert (!this->executing ());
439 if (m_thread_options == thread_options)
440 return;
442 m_thread_options = thread_options;
444 infrun_debug_printf ("[options for %s are now %s]",
445 this->ptid.to_string ().c_str (),
446 to_string (thread_options).c_str ());
449 /* See gdbthread.h. */
452 thread_is_in_step_over_chain (struct thread_info *tp)
454 return tp->step_over_list_node.is_linked ();
457 /* See gdbthread.h. */
460 thread_step_over_chain_length (const thread_step_over_list &l)
462 int num = 0;
464 for (const thread_info &thread ATTRIBUTE_UNUSED : l)
465 ++num;
467 return num;
470 /* See gdbthread.h. */
472 void
473 global_thread_step_over_chain_enqueue (struct thread_info *tp)
475 infrun_debug_printf ("enqueueing thread %s in global step over chain",
476 tp->ptid.to_string ().c_str ());
478 gdb_assert (!thread_is_in_step_over_chain (tp));
479 global_thread_step_over_list.push_back (*tp);
482 /* See gdbthread.h. */
484 void
485 global_thread_step_over_chain_enqueue_chain (thread_step_over_list &&list)
487 global_thread_step_over_list.splice (std::move (list));
490 /* See gdbthread.h. */
492 void
493 global_thread_step_over_chain_remove (struct thread_info *tp)
495 infrun_debug_printf ("removing thread %s from global step over chain",
496 tp->ptid.to_string ().c_str ());
498 gdb_assert (thread_is_in_step_over_chain (tp));
499 auto it = global_thread_step_over_list.iterator_to (*tp);
500 global_thread_step_over_list.erase (it);
503 /* Helper for the different delete_thread variants. */
505 static void
506 delete_thread_1 (thread_info *thr, std::optional<ULONGEST> exit_code,
507 bool silent)
509 gdb_assert (thr != nullptr);
511 threads_debug_printf ("deleting thread %s, exit_code = %s, silent = %d",
512 thr->ptid.to_string ().c_str (),
513 (exit_code.has_value ()
514 ? pulongest (*exit_code)
515 : "<none>"),
516 silent);
518 set_thread_exited (thr, exit_code, silent);
520 if (!thr->deletable ())
522 /* Will be really deleted some other time. */
523 return;
526 auto it = thr->inf->thread_list.iterator_to (*thr);
527 thr->inf->thread_list.erase (it);
529 gdb::observers::thread_deleted.notify (thr);
531 delete thr;
534 /* See gdbthread.h. */
536 void
537 delete_thread_with_exit_code (thread_info *thread, ULONGEST exit_code,
538 bool silent)
540 delete_thread_1 (thread, exit_code, silent);
543 /* See gdbthread.h. */
545 void
546 delete_thread (thread_info *thread)
548 delete_thread_1 (thread, {}, false /* not silent */);
551 void
552 delete_thread_silent (thread_info *thread)
554 delete_thread_1 (thread, {}, true /* not silent */);
557 struct thread_info *
558 find_thread_global_id (int global_id)
560 for (thread_info *tp : all_threads ())
561 if (tp->global_num == global_id)
562 return tp;
564 return NULL;
567 static struct thread_info *
568 find_thread_id (struct inferior *inf, int thr_num)
570 for (thread_info *tp : inf->threads ())
571 if (tp->per_inf_num == thr_num)
572 return tp;
574 return NULL;
577 /* See gdbthread.h. */
579 struct thread_info *
580 find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
581 struct inferior *inf)
583 return target_thread_handle_to_thread_info (handle.data (),
584 handle.size (),
585 inf);
589 * Thread iterator function.
591 * Calls a callback function once for each thread, so long as
592 * the callback function returns false. If the callback function
593 * returns true, the iteration will end and the current thread
594 * will be returned. This can be useful for implementing a
595 * search for a thread with arbitrary attributes, or for applying
596 * some operation to every thread.
598 * FIXME: some of the existing functionality, such as
599 * "Thread apply all", might be rewritten using this functionality.
602 struct thread_info *
603 iterate_over_threads (int (*callback) (struct thread_info *, void *),
604 void *data)
606 for (thread_info *tp : all_threads_safe ())
607 if ((*callback) (tp, data))
608 return tp;
610 return NULL;
613 /* See gdbthread.h. */
615 bool
616 any_thread_p ()
618 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
619 return true;
620 return false;
624 thread_count (process_stratum_target *proc_target)
626 auto rng = all_threads (proc_target);
627 return std::distance (rng.begin (), rng.end ());
630 /* Return the number of non-exited threads in the thread list. */
632 static int
633 live_threads_count (void)
635 auto rng = all_non_exited_threads ();
636 return std::distance (rng.begin (), rng.end ());
640 valid_global_thread_id (int global_id)
642 for (thread_info *tp : all_threads ())
643 if (tp->global_num == global_id)
644 return 1;
646 return 0;
649 bool
650 in_thread_list (process_stratum_target *targ, ptid_t ptid)
652 return targ->find_thread (ptid) != nullptr;
655 /* Finds the first thread of the inferior. */
657 thread_info *
658 first_thread_of_inferior (inferior *inf)
660 if (inf->thread_list.empty ())
661 return nullptr;
663 return &inf->thread_list.front ();
666 thread_info *
667 any_thread_of_inferior (inferior *inf)
669 gdb_assert (inf->pid != 0);
671 /* Prefer the current thread, if there's one. */
672 if (inf == current_inferior () && inferior_ptid != null_ptid)
673 return inferior_thread ();
675 for (thread_info *tp : inf->non_exited_threads ())
676 return tp;
678 return NULL;
681 thread_info *
682 any_live_thread_of_inferior (inferior *inf)
684 struct thread_info *curr_tp = NULL;
685 struct thread_info *tp_executing = NULL;
687 gdb_assert (inf != NULL && inf->pid != 0);
689 /* Prefer the current thread if it's not executing. */
690 if (inferior_ptid != null_ptid && current_inferior () == inf)
692 /* If the current thread is dead, forget it. If it's not
693 executing, use it. Otherwise, still choose it (below), but
694 only if no other non-executing thread is found. */
695 curr_tp = inferior_thread ();
696 if (curr_tp->state == THREAD_EXITED)
697 curr_tp = NULL;
698 else if (!curr_tp->executing ())
699 return curr_tp;
702 for (thread_info *tp : inf->non_exited_threads ())
704 if (!tp->executing ())
705 return tp;
707 tp_executing = tp;
710 /* If both the current thread and all live threads are executing,
711 prefer the current thread. */
712 if (curr_tp != NULL)
713 return curr_tp;
715 /* Otherwise, just return an executing thread, if any. */
716 return tp_executing;
719 /* Return true if TP is an active thread. */
720 static bool
721 thread_alive (thread_info *tp)
723 if (tp->state == THREAD_EXITED)
724 return false;
726 /* Ensure we're looking at the right target stack. */
727 gdb_assert (tp->inf == current_inferior ());
729 return target_thread_alive (tp->ptid);
732 /* See gdbthreads.h. */
734 bool
735 switch_to_thread_if_alive (thread_info *thr)
737 scoped_restore_current_thread restore_thread;
739 /* Switch inferior first, so that we're looking at the right target
740 stack. */
741 switch_to_inferior_no_thread (thr->inf);
743 if (thread_alive (thr))
745 switch_to_thread (thr);
746 restore_thread.dont_restore ();
747 return true;
750 return false;
753 /* See gdbthreads.h. */
755 void
756 prune_threads (void)
758 scoped_restore_current_thread restore_thread;
760 for (thread_info *tp : all_threads_safe ())
762 switch_to_inferior_no_thread (tp->inf);
764 if (!thread_alive (tp))
765 delete_thread (tp);
769 /* See gdbthreads.h. */
771 void
772 delete_exited_threads (void)
774 for (thread_info *tp : all_threads_safe ())
775 if (tp->state == THREAD_EXITED)
776 delete_thread (tp);
779 /* Return true value if stack temporaries are enabled for the thread
780 TP. */
782 bool
783 thread_stack_temporaries_enabled_p (thread_info *tp)
785 if (tp == NULL)
786 return false;
787 else
788 return tp->stack_temporaries_enabled;
791 /* Push V on to the stack temporaries of the thread with id PTID. */
793 void
794 push_thread_stack_temporary (thread_info *tp, struct value *v)
796 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
797 tp->stack_temporaries.push_back (v);
800 /* Return true if VAL is among the stack temporaries of the thread
801 TP. Return false otherwise. */
803 bool
804 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
806 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
807 for (value *v : tp->stack_temporaries)
808 if (v == val)
809 return true;
811 return false;
814 /* Return the last of the stack temporaries for thread with id PTID.
815 Return NULL if there are no stack temporaries for the thread. */
817 value *
818 get_last_thread_stack_temporary (thread_info *tp)
820 struct value *lastval = NULL;
822 gdb_assert (tp != NULL);
823 if (!tp->stack_temporaries.empty ())
824 lastval = tp->stack_temporaries.back ();
826 return lastval;
829 void
830 thread_change_ptid (process_stratum_target *targ,
831 ptid_t old_ptid, ptid_t new_ptid)
833 struct inferior *inf;
834 struct thread_info *tp;
836 /* It can happen that what we knew as the target inferior id
837 changes. E.g, target remote may only discover the remote process
838 pid after adding the inferior to GDB's list. */
839 inf = find_inferior_ptid (targ, old_ptid);
840 inf->pid = new_ptid.pid ();
842 tp = inf->find_thread (old_ptid);
843 gdb_assert (tp != nullptr);
845 int num_erased = inf->ptid_thread_map.erase (old_ptid);
846 gdb_assert (num_erased == 1);
848 tp->ptid = new_ptid;
849 inf->ptid_thread_map[new_ptid] = tp;
851 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
854 /* See gdbthread.h. */
856 void
857 set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
859 for (thread_info *tp : all_non_exited_threads (targ, ptid))
860 tp->set_resumed (resumed);
863 /* Helper for set_running, that marks one thread either running or
864 stopped. */
866 static bool
867 set_running_thread (struct thread_info *tp, bool running)
869 bool started = false;
871 if (running && tp->state == THREAD_STOPPED)
872 started = true;
873 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
875 threads_debug_printf ("thread: %s, running? %d%s",
876 tp->ptid.to_string ().c_str (), running,
877 (started ? " (started)" : ""));
879 if (!running)
881 /* If the thread is now marked stopped, remove it from
882 the step-over queue, so that we don't try to resume
883 it until the user wants it to. */
884 if (thread_is_in_step_over_chain (tp))
885 global_thread_step_over_chain_remove (tp);
888 return started;
891 /* Notify interpreters and observers that the target was resumed. */
893 static void
894 notify_target_resumed (ptid_t ptid)
896 interps_notify_target_resumed (ptid);
897 gdb::observers::target_resumed.notify (ptid);
899 /* We are about to resume the inferior. Close all cached BFDs so that
900 when the inferior next stops, and GDB regains control, we will spot
901 any on-disk changes to the BFDs we are using. */
902 bfd_cache_close_all ();
905 /* See gdbthread.h. */
907 void
908 thread_info::set_running (bool running)
910 if (set_running_thread (this, running))
911 notify_target_resumed (this->ptid);
914 void
915 set_running (process_stratum_target *targ, ptid_t ptid, bool running)
917 /* We try not to notify the observer if no thread has actually
918 changed the running state -- merely to reduce the number of
919 messages to the MI frontend. A frontend is supposed to handle
920 multiple *running notifications just fine. */
921 bool any_started = false;
923 for (thread_info *tp : all_non_exited_threads (targ, ptid))
924 if (set_running_thread (tp, running))
925 any_started = true;
927 if (any_started)
928 notify_target_resumed (ptid);
931 void
932 set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
934 for (thread_info *tp : all_non_exited_threads (targ, ptid))
935 tp->set_executing (executing);
937 /* It only takes one running thread to spawn more threads. */
938 if (executing)
939 targ->threads_executing = true;
940 /* Only clear the flag if the caller is telling us everything is
941 stopped. */
942 else if (minus_one_ptid == ptid)
943 targ->threads_executing = false;
946 /* See gdbthread.h. */
948 bool
949 threads_are_executing (process_stratum_target *target)
951 return target->threads_executing;
954 void
955 set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
957 for (thread_info *tp : all_non_exited_threads (targ, ptid))
958 tp->stop_requested = stop;
960 /* Call the stop requested observer so other components of GDB can
961 react to this request. */
962 if (stop)
963 gdb::observers::thread_stop_requested.notify (ptid);
966 void
967 finish_thread_state (process_stratum_target *targ, ptid_t ptid)
969 bool any_started = false;
971 for (thread_info *tp : all_non_exited_threads (targ, ptid))
972 if (set_running_thread (tp, tp->executing ()))
973 any_started = true;
975 if (any_started)
976 notify_target_resumed (ptid);
979 /* See gdbthread.h. */
981 void
982 validate_registers_access (void)
984 /* No selected thread, no registers. */
985 if (inferior_ptid == null_ptid)
986 error (_("No thread selected."));
988 thread_info *tp = inferior_thread ();
990 /* Don't try to read from a dead thread. */
991 if (tp->state == THREAD_EXITED)
992 error (_("The current thread has terminated"));
994 /* ... or from a spinning thread. FIXME: This isn't actually fully
995 correct. It'll allow an user-requested access (e.g., "print $pc"
996 at the prompt) when a thread is not executing for some internal
997 reason, but is marked running from the user's perspective. E.g.,
998 the thread is waiting for its turn in the step-over queue. */
999 if (tp->executing ())
1000 error (_("Selected thread is running."));
1003 /* See gdbthread.h. */
1005 bool
1006 can_access_registers_thread (thread_info *thread)
1008 /* No thread, no registers. */
1009 if (thread == NULL)
1010 return false;
1012 /* Don't try to read from a dead thread. */
1013 if (thread->state == THREAD_EXITED)
1014 return false;
1016 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
1017 if (thread->executing ())
1018 return false;
1020 return true;
1023 bool
1024 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
1026 return (pc >= thread->control.step_range_start
1027 && pc < thread->control.step_range_end);
1030 /* Helper for print_thread_info. Returns true if THR should be
1031 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
1032 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
1033 is true if REQUESTED_THREADS is list of global IDs, false if a list
1034 of per-inferior thread ids. If PID is not -1, only print THR if it
1035 is a thread from the process PID. Otherwise, threads from all
1036 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
1037 and PID is not -1, then the thread is printed if it belongs to the
1038 specified process. Otherwise, an error is raised. */
1040 static bool
1041 should_print_thread (const char *requested_threads, int default_inf_num,
1042 int global_ids, int pid, struct thread_info *thr)
1044 if (requested_threads != NULL && *requested_threads != '\0')
1046 int in_list;
1048 if (global_ids)
1049 in_list = number_is_in_list (requested_threads, thr->global_num);
1050 else
1051 in_list = tid_is_in_list (requested_threads, default_inf_num,
1052 thr->inf->num, thr->per_inf_num);
1053 if (!in_list)
1054 return false;
1057 if (pid != -1 && thr->ptid.pid () != pid)
1059 if (requested_threads != NULL && *requested_threads != '\0')
1060 error (_("Requested thread not found in requested process"));
1061 return false;
1064 if (thr->state == THREAD_EXITED)
1065 return false;
1067 return true;
1070 /* Return the string to display in "info threads"'s "Target Id"
1071 column, for TP. */
1073 static std::string
1074 thread_target_id_str (thread_info *tp)
1076 std::string target_id = target_pid_to_str (tp->ptid);
1077 const char *extra_info = target_extra_thread_info (tp);
1078 const char *name = thread_name (tp);
1080 if (extra_info != nullptr && name != nullptr)
1081 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1082 extra_info);
1083 else if (extra_info != nullptr)
1084 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1085 else if (name != nullptr)
1086 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1087 else
1088 return target_id;
1091 /* Print thread TP. GLOBAL_IDS indicates whether REQUESTED_THREADS
1092 is a list of global or per-inferior thread ids. */
1094 static void
1095 do_print_thread (ui_out *uiout, const char *requested_threads,
1096 int global_ids, int pid, int show_global_ids,
1097 int default_inf_num, thread_info *tp,
1098 thread_info *current_thread)
1100 int core;
1102 /* In case REQUESTED_THREADS contains $_thread. */
1103 if (current_thread != nullptr)
1104 switch_to_thread (current_thread);
1106 if (!should_print_thread (requested_threads, default_inf_num,
1107 global_ids, pid, tp))
1108 return;
1110 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1112 if (!uiout->is_mi_like_p ())
1114 if (tp == current_thread)
1115 uiout->field_string ("current", "*");
1116 else
1117 uiout->field_skip ("current");
1119 uiout->field_string ("id-in-tg", print_thread_id (tp));
1122 if (show_global_ids || uiout->is_mi_like_p ())
1123 uiout->field_signed ("id", tp->global_num);
1125 /* Switch to the thread (and inferior / target). */
1126 switch_to_thread (tp);
1128 /* For the CLI, we stuff everything into the target-id field.
1129 This is a gross hack to make the output come out looking
1130 correct. The underlying problem here is that ui-out has no
1131 way to specify that a field's space allocation should be
1132 shared by several fields. For MI, we do the right thing
1133 instead. */
1135 if (uiout->is_mi_like_p ())
1137 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1139 const char *extra_info = target_extra_thread_info (tp);
1140 if (extra_info != nullptr)
1141 uiout->field_string ("details", extra_info);
1143 const char *name = thread_name (tp);
1144 if (name != NULL)
1145 uiout->field_string ("name", name);
1147 else
1149 uiout->field_string ("target-id", thread_target_id_str (tp));
1152 if (tp->state == THREAD_RUNNING)
1153 uiout->text ("(running)\n");
1154 else
1156 /* The switch above put us at the top of the stack (leaf
1157 frame). */
1158 print_stack_frame (get_selected_frame (NULL),
1159 /* For MI output, print frame level. */
1160 uiout->is_mi_like_p (),
1161 LOCATION, 0);
1164 if (uiout->is_mi_like_p ())
1166 const char *state = "stopped";
1168 if (tp->state == THREAD_RUNNING)
1169 state = "running";
1170 uiout->field_string ("state", state);
1173 core = target_core_of_thread (tp->ptid);
1174 if (uiout->is_mi_like_p () && core != -1)
1175 uiout->field_signed ("core", core);
1178 /* Redirect output to a temporary buffer for the duration
1179 of do_print_thread. */
1181 static void
1182 print_thread (ui_out *uiout, const char *requested_threads,
1183 int global_ids, int pid, int show_global_ids,
1184 int default_inf_num, thread_info *tp, thread_info *current_thread)
1187 do_with_buffered_output (do_print_thread, uiout, requested_threads,
1188 global_ids, pid, show_global_ids,
1189 default_inf_num, tp, current_thread);
1192 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1193 whether REQUESTED_THREADS is a list of global or per-inferior
1194 thread ids. */
1196 static void
1197 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1198 int global_ids, int pid,
1199 int show_global_ids)
1201 int default_inf_num = current_inferior ()->num;
1203 update_thread_list ();
1205 /* Whether we saw any thread. */
1206 bool any_thread = false;
1207 /* Whether the current thread is exited. */
1208 bool current_exited = false;
1210 thread_info *current_thread = (inferior_ptid != null_ptid
1211 ? inferior_thread () : NULL);
1214 /* For backward compatibility, we make a list for MI. A table is
1215 preferable for the CLI, though, because it shows table
1216 headers. */
1217 std::optional<ui_out_emit_list> list_emitter;
1218 std::optional<ui_out_emit_table> table_emitter;
1220 /* We'll be switching threads temporarily below. */
1221 scoped_restore_current_thread restore_thread;
1223 if (uiout->is_mi_like_p ())
1224 list_emitter.emplace (uiout, "threads");
1225 else
1227 int n_threads = 0;
1228 /* The width of the "Target Id" column. Grown below to
1229 accommodate the largest entry. */
1230 size_t target_id_col_width = 17;
1232 for (thread_info *tp : all_threads ())
1234 /* In case REQUESTED_THREADS contains $_thread. */
1235 if (current_thread != nullptr)
1236 switch_to_thread (current_thread);
1238 if (!should_print_thread (requested_threads, default_inf_num,
1239 global_ids, pid, tp))
1240 continue;
1242 /* Switch inferiors so we're looking at the right
1243 target stack. */
1244 switch_to_inferior_no_thread (tp->inf);
1246 target_id_col_width
1247 = std::max (target_id_col_width,
1248 thread_target_id_str (tp).size ());
1250 ++n_threads;
1253 if (n_threads == 0)
1255 if (requested_threads == NULL || *requested_threads == '\0')
1256 uiout->message (_("No threads.\n"));
1257 else
1258 uiout->message (_("No threads match '%s'.\n"),
1259 requested_threads);
1260 return;
1263 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1264 n_threads, "threads");
1266 uiout->table_header (1, ui_left, "current", "");
1267 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1268 if (show_global_ids)
1269 uiout->table_header (4, ui_left, "id", "GId");
1270 uiout->table_header (target_id_col_width, ui_left,
1271 "target-id", "Target Id");
1272 uiout->table_header (1, ui_left, "frame", "Frame");
1273 uiout->table_body ();
1276 for (inferior *inf : all_inferiors ())
1277 for (thread_info *tp : inf->threads ())
1279 any_thread = true;
1281 if (tp == current_thread && tp->state == THREAD_EXITED)
1282 current_exited = true;
1284 print_thread (uiout, requested_threads, global_ids, pid,
1285 show_global_ids, default_inf_num, tp, current_thread);
1288 /* This end scope restores the current thread and the frame
1289 selected before the "info threads" command, and it finishes the
1290 ui-out list or table. */
1293 if (pid == -1 && requested_threads == NULL)
1295 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1296 uiout->field_signed ("current-thread-id", current_thread->global_num);
1298 if (inferior_ptid != null_ptid && current_exited)
1299 uiout->message ("\n\
1300 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1301 print_thread_id (inferior_thread ()));
1302 else if (any_thread && inferior_ptid == null_ptid)
1303 uiout->message ("\n\
1304 No selected thread. See `help thread'.\n");
1308 /* See gdbthread.h. */
1310 void
1311 print_thread_info (struct ui_out *uiout, const char *requested_threads,
1312 int pid)
1314 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1317 /* The options for the "info threads" command. */
1319 struct info_threads_opts
1321 /* For "-gid". */
1322 bool show_global_ids = false;
1325 static const gdb::option::option_def info_threads_option_defs[] = {
1327 gdb::option::flag_option_def<info_threads_opts> {
1328 "gid",
1329 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1330 N_("Show global thread IDs."),
1335 /* Create an option_def_group for the "info threads" options, with
1336 IT_OPTS as context. */
1338 static inline gdb::option::option_def_group
1339 make_info_threads_options_def_group (info_threads_opts *it_opts)
1341 return {{info_threads_option_defs}, it_opts};
1344 /* Implementation of the "info threads" command.
1346 Note: this has the drawback that it _really_ switches
1347 threads, which frees the frame cache. A no-side
1348 effects info-threads command would be nicer. */
1350 static void
1351 info_threads_command (const char *arg, int from_tty)
1353 info_threads_opts it_opts;
1355 auto grp = make_info_threads_options_def_group (&it_opts);
1356 gdb::option::process_options
1357 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1359 print_thread_info_1 (current_uiout, arg, 0, -1, it_opts.show_global_ids);
1362 /* Completer for the "info threads" command. */
1364 static void
1365 info_threads_command_completer (struct cmd_list_element *ignore,
1366 completion_tracker &tracker,
1367 const char *text, const char *word_ignored)
1369 const auto grp = make_info_threads_options_def_group (nullptr);
1371 if (gdb::option::complete_options
1372 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1373 return;
1375 /* Convenience to let the user know what the option can accept. */
1376 if (*text == '\0')
1378 gdb::option::complete_on_all_options (tracker, grp);
1379 /* Keep this "ID" in sync with what "help info threads"
1380 says. */
1381 tracker.add_completion (make_unique_xstrdup ("ID"));
1385 /* See gdbthread.h. */
1387 void
1388 switch_to_thread_no_regs (struct thread_info *thread)
1390 gdb_assert (thread != nullptr);
1391 threads_debug_printf ("thread = %s", thread->ptid.to_string ().c_str ());
1393 struct inferior *inf = thread->inf;
1395 set_current_program_space (inf->pspace);
1396 set_current_inferior (inf);
1398 current_thread_ = thread;
1399 inferior_ptid = current_thread_->ptid;
1402 /* See gdbthread.h. */
1404 void
1405 switch_to_no_thread ()
1407 if (current_thread_ == nullptr)
1408 return;
1410 threads_debug_printf ("thread = NONE");
1412 current_thread_ = nullptr;
1413 inferior_ptid = null_ptid;
1414 reinit_frame_cache ();
1417 /* See gdbthread.h. */
1419 void
1420 switch_to_thread (thread_info *thr)
1422 gdb_assert (thr != NULL);
1424 if (is_current_thread (thr))
1425 return;
1427 switch_to_thread_no_regs (thr);
1429 reinit_frame_cache ();
1432 /* See gdbsupport/common-gdbthread.h. */
1434 void
1435 switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
1437 thread_info *thr = proc_target->find_thread (ptid);
1438 switch_to_thread (thr);
1441 /* See frame.h. */
1443 void
1444 scoped_restore_current_thread::restore ()
1446 /* If an entry of thread_info was previously selected, it won't be
1447 deleted because we've increased its refcount. The thread represented
1448 by this thread_info entry may have already exited (due to normal exit,
1449 detach, etc), so the thread_info.state is THREAD_EXITED. */
1450 if (m_thread != NULL
1451 /* If the previously selected thread belonged to a process that has
1452 in the mean time exited (or killed, detached, etc.), then don't revert
1453 back to it, but instead simply drop back to no thread selected. */
1454 && m_inf->pid != 0)
1455 switch_to_thread (m_thread.get ());
1456 else
1457 switch_to_inferior_no_thread (m_inf.get ());
1459 /* The running state of the originally selected thread may have
1460 changed, so we have to recheck it here. */
1461 if (inferior_ptid != null_ptid
1462 && m_was_stopped
1463 && m_thread->state == THREAD_STOPPED
1464 && target_has_registers ()
1465 && target_has_stack ()
1466 && target_has_memory ())
1467 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1470 scoped_restore_current_thread::~scoped_restore_current_thread ()
1472 if (m_dont_restore)
1473 m_lang.dont_restore ();
1474 else
1475 restore ();
1478 scoped_restore_current_thread::scoped_restore_current_thread ()
1480 m_inf = inferior_ref::new_reference (current_inferior ());
1482 if (inferior_ptid != null_ptid)
1484 m_thread = thread_info_ref::new_reference (inferior_thread ());
1486 m_was_stopped = m_thread->state == THREAD_STOPPED;
1487 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
1491 scoped_restore_current_thread::scoped_restore_current_thread
1492 (scoped_restore_current_thread &&rhs)
1493 : m_dont_restore (std::move (rhs.m_dont_restore)),
1494 m_thread (std::move (rhs.m_thread)),
1495 m_inf (std::move (rhs.m_inf)),
1496 m_selected_frame_id (std::move (rhs.m_selected_frame_id)),
1497 m_selected_frame_level (std::move (rhs.m_selected_frame_level)),
1498 m_was_stopped (std::move (rhs.m_was_stopped)),
1499 m_lang (std::move (rhs.m_lang))
1501 /* Deactivate the rhs. */
1502 rhs.m_dont_restore = true;
1505 /* See gdbthread.h. */
1508 show_thread_that_caused_stop (void)
1510 return highest_thread_num > 1;
1513 /* See gdbthread.h. */
1516 show_inferior_qualified_tids (void)
1518 auto inf = inferior_list.begin ();
1519 if (inf->num != 1)
1520 return true;
1521 ++inf;
1522 return inf != inferior_list.end ();
1525 /* See gdbthread.h. */
1527 const char *
1528 print_thread_id (struct thread_info *thr)
1530 if (show_inferior_qualified_tids ())
1531 return print_full_thread_id (thr);
1533 char *s = get_print_cell ();
1535 gdb_assert (thr != nullptr);
1536 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1537 return s;
1540 /* See gdbthread.h. */
1542 const char *
1543 print_full_thread_id (struct thread_info *thr)
1545 char *s = get_print_cell ();
1547 gdb_assert (thr != nullptr);
1548 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1549 return s;
1552 /* Sort an array of struct thread_info pointers by thread ID (first by
1553 inferior number, and then by per-inferior thread number). Sorts in
1554 ascending order. */
1556 static bool
1557 tp_array_compar_ascending (const thread_info_ref &a, const thread_info_ref &b)
1559 if (a->inf->num != b->inf->num)
1560 return a->inf->num < b->inf->num;
1562 return (a->per_inf_num < b->per_inf_num);
1565 /* Sort an array of struct thread_info pointers by thread ID (first by
1566 inferior number, and then by per-inferior thread number). Sorts in
1567 descending order. */
1569 static bool
1570 tp_array_compar_descending (const thread_info_ref &a, const thread_info_ref &b)
1572 if (a->inf->num != b->inf->num)
1573 return a->inf->num > b->inf->num;
1575 return (a->per_inf_num > b->per_inf_num);
1578 /* See gdbthread.h. */
1580 void
1581 thread_try_catch_cmd (thread_info *thr, std::optional<int> ada_task,
1582 const char *cmd, int from_tty,
1583 const qcs_flags &flags)
1585 gdb_assert (is_current_thread (thr));
1587 /* The thread header is computed before running the command since
1588 the command can change the inferior, which is not permitted
1589 by thread_target_id_str. */
1590 std::string thr_header;
1591 if (ada_task.has_value ())
1592 thr_header = string_printf (_("\nTask ID %d:\n"), *ada_task);
1593 else
1594 thr_header = string_printf (_("\nThread %s (%s):\n"),
1595 print_thread_id (thr),
1596 thread_target_id_str (thr).c_str ());
1600 std::string cmd_result;
1601 execute_command_to_string
1602 (cmd_result, cmd, from_tty, gdb_stdout->term_out ());
1603 if (!flags.silent || cmd_result.length () > 0)
1605 if (!flags.quiet)
1606 gdb_printf ("%s", thr_header.c_str ());
1607 gdb_printf ("%s", cmd_result.c_str ());
1610 catch (const gdb_exception_error &ex)
1612 if (!flags.silent)
1614 if (!flags.quiet)
1615 gdb_printf ("%s", thr_header.c_str ());
1616 if (flags.cont)
1617 gdb_printf ("%s\n", ex.what ());
1618 else
1619 throw;
1624 /* Option definition of "thread apply"'s "-ascending" option. */
1626 static const gdb::option::flag_option_def<> ascending_option_def = {
1627 "ascending",
1628 N_("\
1629 Call COMMAND for all threads in ascending order.\n\
1630 The default is descending order."),
1633 /* The qcs command line flags for the "thread apply" commands. Keep
1634 this in sync with the "frame apply" commands. */
1636 using qcs_flag_option_def
1637 = gdb::option::flag_option_def<qcs_flags>;
1639 static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1640 qcs_flag_option_def {
1641 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1642 N_("Disables printing the thread information."),
1645 qcs_flag_option_def {
1646 "c", [] (qcs_flags *opt) { return &opt->cont; },
1647 N_("Print any error raised by COMMAND and continue."),
1650 qcs_flag_option_def {
1651 "s", [] (qcs_flags *opt) { return &opt->silent; },
1652 N_("Silently ignore any errors or empty output produced by COMMAND."),
1656 /* Create an option_def_group for the "thread apply all" options, with
1657 ASCENDING and FLAGS as context. */
1659 static inline std::array<gdb::option::option_def_group, 2>
1660 make_thread_apply_all_options_def_group (bool *ascending,
1661 qcs_flags *flags)
1663 return {{
1664 { {ascending_option_def.def ()}, ascending},
1665 { {thr_qcs_flags_option_defs}, flags },
1669 /* Create an option_def_group for the "thread apply" options, with
1670 FLAGS as context. */
1672 static inline gdb::option::option_def_group
1673 make_thread_apply_options_def_group (qcs_flags *flags)
1675 return {{thr_qcs_flags_option_defs}, flags};
1678 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1679 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1680 of two numbers separated by a hyphen. Examples:
1682 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1683 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1684 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1686 static void
1687 thread_apply_all_command (const char *cmd, int from_tty)
1689 bool ascending = false;
1690 qcs_flags flags;
1692 auto group = make_thread_apply_all_options_def_group (&ascending,
1693 &flags);
1694 gdb::option::process_options
1695 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1697 validate_flags_qcs ("thread apply all", &flags);
1699 if (cmd == NULL || *cmd == '\000')
1700 error (_("Please specify a command at the end of 'thread apply all'"));
1702 update_thread_list ();
1704 int tc = live_threads_count ();
1705 if (tc != 0)
1707 /* Save a copy of the thread list and increment each thread's
1708 refcount while executing the command in the context of each
1709 thread, in case the command is one that wipes threads. E.g.,
1710 detach, kill, disconnect, etc., or even normally continuing
1711 over an inferior or thread exit. */
1712 std::vector<thread_info_ref> thr_list_cpy;
1713 thr_list_cpy.reserve (tc);
1715 for (thread_info *tp : all_non_exited_threads ())
1716 thr_list_cpy.push_back (thread_info_ref::new_reference (tp));
1717 gdb_assert (thr_list_cpy.size () == tc);
1719 auto *sorter = (ascending
1720 ? tp_array_compar_ascending
1721 : tp_array_compar_descending);
1722 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
1724 scoped_restore_current_thread restore_thread;
1726 for (thread_info_ref &thr : thr_list_cpy)
1727 if (switch_to_thread_if_alive (thr.get ()))
1728 thread_try_catch_cmd (thr.get (), {}, cmd, from_tty, flags);
1732 /* Completer for "thread apply [ID list]". */
1734 static void
1735 thread_apply_command_completer (cmd_list_element *ignore,
1736 completion_tracker &tracker,
1737 const char *text, const char * /*word*/)
1739 /* Don't leave this to complete_options because there's an early
1740 return below. */
1741 tracker.set_use_custom_word_point (true);
1743 tid_range_parser parser;
1744 parser.init (text, current_inferior ()->num);
1748 while (!parser.finished ())
1750 int inf_num, thr_start, thr_end;
1752 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1753 break;
1755 if (parser.in_star_range () || parser.in_thread_range ())
1756 parser.skip_range ();
1759 catch (const gdb_exception_error &ex)
1761 /* get_tid_range throws if it parses a negative number, for
1762 example. But a seemingly negative number may be the start of
1763 an option instead. */
1766 const char *cmd = parser.cur_tok ();
1768 if (cmd == text)
1770 /* No thread ID list yet. */
1771 return;
1774 /* Check if we're past a valid thread ID list already. */
1775 if (parser.finished ()
1776 && cmd > text && !isspace (cmd[-1]))
1777 return;
1779 /* We're past the thread ID list, advance word point. */
1780 tracker.advance_custom_word_point_by (cmd - text);
1781 text = cmd;
1783 const auto group = make_thread_apply_options_def_group (nullptr);
1784 if (gdb::option::complete_options
1785 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1786 return;
1788 complete_nested_command_line (tracker, text);
1791 /* Completer for "thread apply all". */
1793 static void
1794 thread_apply_all_command_completer (cmd_list_element *ignore,
1795 completion_tracker &tracker,
1796 const char *text, const char *word)
1798 const auto group = make_thread_apply_all_options_def_group (nullptr,
1799 nullptr);
1800 if (gdb::option::complete_options
1801 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1802 return;
1804 complete_nested_command_line (tracker, text);
1807 /* Implementation of the "thread apply" command. */
1809 static void
1810 thread_apply_command (const char *tidlist, int from_tty)
1812 qcs_flags flags;
1813 const char *cmd = NULL;
1814 tid_range_parser parser;
1816 if (tidlist == NULL || *tidlist == '\000')
1817 error (_("Please specify a thread ID list"));
1819 parser.init (tidlist, current_inferior ()->num);
1820 while (!parser.finished ())
1822 int inf_num, thr_start, thr_end;
1824 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1825 break;
1828 cmd = parser.cur_tok ();
1830 auto group = make_thread_apply_options_def_group (&flags);
1831 gdb::option::process_options
1832 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1834 validate_flags_qcs ("thread apply", &flags);
1836 if (*cmd == '\0')
1837 error (_("Please specify a command following the thread ID list"));
1839 if (tidlist == cmd || isdigit (cmd[0]))
1840 invalid_thread_id_error (cmd);
1842 scoped_restore_current_thread restore_thread;
1844 parser.init (tidlist, current_inferior ()->num);
1845 while (!parser.finished ())
1847 struct thread_info *tp = NULL;
1848 struct inferior *inf;
1849 int inf_num, thr_num;
1851 parser.get_tid (&inf_num, &thr_num);
1852 inf = find_inferior_id (inf_num);
1853 if (inf != NULL)
1854 tp = find_thread_id (inf, thr_num);
1856 if (parser.in_star_range ())
1858 if (inf == NULL)
1860 warning (_("Unknown inferior %d"), inf_num);
1861 parser.skip_range ();
1862 continue;
1865 /* No use looking for threads past the highest thread number
1866 the inferior ever had. */
1867 if (thr_num >= inf->highest_thread_num)
1868 parser.skip_range ();
1870 /* Be quiet about unknown threads numbers. */
1871 if (tp == NULL)
1872 continue;
1875 if (tp == NULL)
1877 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1878 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1879 else
1880 warning (_("Unknown thread %d"), thr_num);
1881 continue;
1884 if (!switch_to_thread_if_alive (tp))
1886 warning (_("Thread %s has terminated."), print_thread_id (tp));
1887 continue;
1890 thread_try_catch_cmd (tp, {}, cmd, from_tty, flags);
1895 /* Implementation of the "taas" command. */
1897 static void
1898 taas_command (const char *cmd, int from_tty)
1900 if (cmd == NULL || *cmd == '\0')
1901 error (_("Please specify a command to apply on all threads"));
1902 std::string expanded = std::string ("thread apply all -s ") + cmd;
1903 execute_command (expanded.c_str (), from_tty);
1906 /* Implementation of the "tfaas" command. */
1908 static void
1909 tfaas_command (const char *cmd, int from_tty)
1911 if (cmd == NULL || *cmd == '\0')
1912 error (_("Please specify a command to apply on all frames of all threads"));
1913 std::string expanded
1914 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1915 execute_command (expanded.c_str (), from_tty);
1918 /* Switch to the specified thread, or print the current thread. */
1920 void
1921 thread_command (const char *tidstr, int from_tty)
1923 if (tidstr == NULL)
1925 if (inferior_ptid == null_ptid)
1926 error (_("No thread selected"));
1928 if (target_has_stack ())
1930 struct thread_info *tp = inferior_thread ();
1932 if (tp->state == THREAD_EXITED)
1933 gdb_printf (_("[Current thread is %s (%s) (exited)]\n"),
1934 print_thread_id (tp),
1935 target_pid_to_str (inferior_ptid).c_str ());
1936 else
1937 gdb_printf (_("[Current thread is %s (%s)]\n"),
1938 print_thread_id (tp),
1939 target_pid_to_str (inferior_ptid).c_str ());
1941 else
1942 error (_("No stack."));
1944 else
1946 ptid_t previous_ptid = inferior_ptid;
1948 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1950 /* Print if the thread has not changed, otherwise an event will
1951 be sent. */
1952 if (inferior_ptid == previous_ptid)
1954 print_selected_thread_frame (current_uiout,
1955 USER_SELECTED_THREAD
1956 | USER_SELECTED_FRAME);
1958 else
1959 notify_user_selected_context_changed
1960 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1964 /* Implementation of `thread name'. */
1966 static void
1967 thread_name_command (const char *arg, int from_tty)
1969 struct thread_info *info;
1971 if (inferior_ptid == null_ptid)
1972 error (_("No thread selected"));
1974 arg = skip_spaces (arg);
1976 info = inferior_thread ();
1977 info->set_name (arg != nullptr ? make_unique_xstrdup (arg) : nullptr);
1980 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1982 static void
1983 thread_find_command (const char *arg, int from_tty)
1985 const char *tmp;
1986 unsigned long match = 0;
1988 if (arg == NULL || *arg == '\0')
1989 error (_("Command requires an argument."));
1991 tmp = re_comp (arg);
1992 if (tmp != 0)
1993 error (_("Invalid regexp (%s): %s"), tmp, arg);
1995 /* We're going to be switching threads. */
1996 scoped_restore_current_thread restore_thread;
1998 update_thread_list ();
2000 for (thread_info *tp : all_threads ())
2002 switch_to_inferior_no_thread (tp->inf);
2004 if (tp->name () != nullptr && re_exec (tp->name ()))
2006 gdb_printf (_("Thread %s has name '%s'\n"),
2007 print_thread_id (tp), tp->name ());
2008 match++;
2011 tmp = target_thread_name (tp);
2012 if (tmp != NULL && re_exec (tmp))
2014 gdb_printf (_("Thread %s has target name '%s'\n"),
2015 print_thread_id (tp), tmp);
2016 match++;
2019 std::string name = target_pid_to_str (tp->ptid);
2020 if (!name.empty () && re_exec (name.c_str ()))
2022 gdb_printf (_("Thread %s has target id '%s'\n"),
2023 print_thread_id (tp), name.c_str ());
2024 match++;
2027 tmp = target_extra_thread_info (tp);
2028 if (tmp != NULL && re_exec (tmp))
2030 gdb_printf (_("Thread %s has extra info '%s'\n"),
2031 print_thread_id (tp), tmp);
2032 match++;
2035 if (!match)
2036 gdb_printf (_("No threads match '%s'\n"), arg);
2039 /* Print notices when new threads are attached and detached. */
2040 bool print_thread_events = true;
2041 static void
2042 show_print_thread_events (struct ui_file *file, int from_tty,
2043 struct cmd_list_element *c, const char *value)
2045 gdb_printf (file,
2046 _("Printing of thread events is %s.\n"),
2047 value);
2050 /* See gdbthread.h. */
2052 void
2053 thread_select (const char *tidstr, thread_info *tp)
2055 if (!switch_to_thread_if_alive (tp))
2056 error (_("Thread ID %s has terminated."), tidstr);
2058 annotate_thread_changed ();
2060 /* Since the current thread may have changed, see if there is any
2061 exited thread we can now delete. */
2062 delete_exited_threads ();
2065 /* Print thread and frame switch command response. */
2067 void
2068 print_selected_thread_frame (struct ui_out *uiout,
2069 user_selected_what selection)
2071 struct thread_info *tp = inferior_thread ();
2073 if (selection & USER_SELECTED_THREAD)
2075 if (uiout->is_mi_like_p ())
2077 uiout->field_signed ("new-thread-id",
2078 inferior_thread ()->global_num);
2080 else
2082 uiout->text ("[Switching to thread ");
2083 uiout->field_string ("new-thread-id", print_thread_id (tp));
2084 uiout->text (" (");
2085 uiout->text (target_pid_to_str (inferior_ptid));
2086 uiout->text (")]");
2090 if (tp->state == THREAD_RUNNING)
2092 if (selection & USER_SELECTED_THREAD)
2093 uiout->text ("(running)\n");
2095 else if (selection & USER_SELECTED_FRAME)
2097 if (selection & USER_SELECTED_THREAD)
2098 uiout->text ("\n");
2100 if (has_stack_frames ())
2101 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
2102 1, SRC_AND_LOC, 1);
2106 /* Update the 'threads_executing' global based on the threads we know
2107 about right now. This is used by infrun to tell whether we should
2108 pull events out of the current target. */
2110 static void
2111 update_threads_executing (void)
2113 process_stratum_target *targ = current_inferior ()->process_target ();
2115 if (targ == NULL)
2116 return;
2118 targ->threads_executing = false;
2120 for (inferior *inf : all_non_exited_inferiors (targ))
2122 if (!inf->has_execution ())
2123 continue;
2125 /* If the process has no threads, then it must be we have a
2126 process-exit event pending. */
2127 if (inf->thread_list.empty ())
2129 targ->threads_executing = true;
2130 return;
2133 for (thread_info *tp : inf->non_exited_threads ())
2135 if (tp->executing ())
2137 targ->threads_executing = true;
2138 return;
2144 void
2145 update_thread_list (void)
2147 target_update_thread_list ();
2148 update_threads_executing ();
2151 /* See gdbthread.h. */
2153 const char *
2154 thread_name (thread_info *thread)
2156 /* Use the manually set name if there is one. */
2157 const char *name = thread->name ();
2158 if (name != nullptr)
2159 return name;
2161 /* Otherwise, ask the target. Ensure we query the right target stack. */
2162 scoped_restore_current_thread restore_thread;
2163 if (thread->inf != current_inferior ())
2164 switch_to_inferior_no_thread (thread->inf);
2166 return target_thread_name (thread);
2169 /* See gdbthread.h. */
2171 const char *
2172 thread_state_string (enum thread_state state)
2174 switch (state)
2176 case THREAD_STOPPED:
2177 return "STOPPED";
2179 case THREAD_RUNNING:
2180 return "RUNNING";
2182 case THREAD_EXITED:
2183 return "EXITED";
2186 gdb_assert_not_reached ("unknown thread state");
2189 /* Return a new value for the selected thread's id. Return a value of
2190 0 if no thread is selected. If GLOBAL is true, return the thread's
2191 global number. Otherwise return the per-inferior number. */
2193 static struct value *
2194 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2196 int int_val;
2198 if (inferior_ptid == null_ptid)
2199 int_val = 0;
2200 else
2202 thread_info *tp = inferior_thread ();
2203 if (global)
2204 int_val = tp->global_num;
2205 else
2206 int_val = tp->per_inf_num;
2209 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2212 /* Return a new value for the selected thread's per-inferior thread
2213 number. Return a value of 0 if no thread is selected, or no
2214 threads exist. */
2216 static struct value *
2217 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2218 struct internalvar *var,
2219 void *ignore)
2221 return thread_num_make_value_helper (gdbarch, 0);
2224 /* Return a new value for the selected thread's global id. Return a
2225 value of 0 if no thread is selected, or no threads exist. */
2227 static struct value *
2228 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2229 void *ignore)
2231 return thread_num_make_value_helper (gdbarch, 1);
2234 /* Return a new value for the number of non-exited threads in the current
2235 inferior. If there are no threads in the current inferior return a
2236 value of 0. */
2238 static struct value *
2239 inferior_thread_count_make_value (struct gdbarch *gdbarch,
2240 struct internalvar *var, void *ignore)
2242 int int_val = 0;
2244 update_thread_list ();
2246 if (inferior_ptid != null_ptid)
2247 int_val = current_inferior ()->non_exited_threads ().size ();
2249 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2252 /* Commands with a prefix of `thread'. */
2253 struct cmd_list_element *thread_cmd_list = NULL;
2255 /* Implementation of `thread' variable. */
2257 static const struct internalvar_funcs thread_funcs =
2259 thread_id_per_inf_num_make_value,
2260 NULL,
2263 /* Implementation of `gthread' variable. */
2265 static const struct internalvar_funcs gthread_funcs =
2267 global_thread_id_make_value,
2268 NULL,
2271 /* Implementation of `_inferior_thread_count` convenience variable. */
2273 static const struct internalvar_funcs inferior_thread_count_funcs =
2275 inferior_thread_count_make_value,
2276 NULL,
2279 void _initialize_thread ();
2280 void
2281 _initialize_thread ()
2283 static struct cmd_list_element *thread_apply_list = NULL;
2284 cmd_list_element *c;
2286 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2288 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2289 suggests. */
2290 static std::string info_threads_help
2291 = gdb::option::build_help (_("\
2292 Display currently known threads.\n\
2293 Usage: info threads [OPTION]... [ID]...\n\
2294 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2295 Otherwise, all threads are displayed.\n\
2297 Options:\n\
2298 %OPTIONS%"),
2299 info_threads_opts);
2301 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2302 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
2304 cmd_list_element *thread_cmd
2305 = add_prefix_cmd ("thread", class_run, thread_command, _("\
2306 Use this command to switch between threads.\n\
2307 The new thread ID must be currently known."),
2308 &thread_cmd_list, 1, &cmdlist);
2310 add_com_alias ("t", thread_cmd, class_run, 1);
2312 #define THREAD_APPLY_OPTION_HELP "\
2313 Prints per-inferior thread number and target system's thread id\n\
2314 followed by COMMAND output.\n\
2316 By default, an error raised during the execution of COMMAND\n\
2317 aborts \"thread apply\".\n\
2319 Options:\n\
2320 %OPTIONS%"
2322 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2324 static std::string thread_apply_help = gdb::option::build_help (_("\
2325 Apply a command to a list of threads.\n\
2326 Usage: thread apply ID... [OPTION]... COMMAND\n\
2327 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2328 THREAD_APPLY_OPTION_HELP),
2329 thread_apply_opts);
2331 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2332 thread_apply_help.c_str (),
2333 &thread_apply_list, 1,
2334 &thread_cmd_list);
2335 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
2337 const auto thread_apply_all_opts
2338 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2340 static std::string thread_apply_all_help = gdb::option::build_help (_("\
2341 Apply a command to all threads.\n\
2343 Usage: thread apply all [OPTION]... COMMAND\n"
2344 THREAD_APPLY_OPTION_HELP),
2345 thread_apply_all_opts);
2347 c = add_cmd ("all", class_run, thread_apply_all_command,
2348 thread_apply_all_help.c_str (),
2349 &thread_apply_list);
2350 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2352 c = add_com ("taas", class_run, taas_command, _("\
2353 Apply a command to all threads (ignoring errors and empty output).\n\
2354 Usage: taas [OPTION]... COMMAND\n\
2355 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2356 See \"help thread apply all\" for available options."));
2357 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2359 c = add_com ("tfaas", class_run, tfaas_command, _("\
2360 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2361 Usage: tfaas [OPTION]... COMMAND\n\
2362 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2363 See \"help frame apply all\" for available options."));
2364 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
2366 add_cmd ("name", class_run, thread_name_command,
2367 _("Set the current thread's name.\n\
2368 Usage: thread name [NAME]\n\
2369 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2371 add_cmd ("find", class_run, thread_find_command, _("\
2372 Find threads that match a regular expression.\n\
2373 Usage: thread find REGEXP\n\
2374 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2375 &thread_cmd_list);
2377 add_setshow_boolean_cmd ("thread-events", no_class,
2378 &print_thread_events, _("\
2379 Set printing of thread events (such as thread start and exit)."), _("\
2380 Show printing of thread events (such as thread start and exit)."), NULL,
2381 NULL,
2382 show_print_thread_events,
2383 &setprintlist, &showprintlist);
2385 add_setshow_boolean_cmd ("threads", class_maintenance, &debug_threads, _("\
2386 Set thread debugging."), _("\
2387 Show thread debugging."), _("\
2388 When on messages about thread creation and deletion are printed."),
2389 nullptr,
2390 show_debug_threads,
2391 &setdebuglist, &showdebuglist);
2393 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2394 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);
2395 create_internalvar_type_lazy ("_inferior_thread_count",
2396 &inferior_thread_count_funcs, NULL);