Automatic Copyright Year update after running gdb/copyright.py
[binutils-gdb.git] / gdb / thread.c
blob8a7d142bab56e7d01257c452dc57c6804bb0ea64
1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2022 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 "defs.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 "gdb_regex.h"
44 #include "cli/cli-utils.h"
45 #include "thread-fsm.h"
46 #include "tid-parse.h"
47 #include <algorithm>
48 #include "gdbsupport/gdb_optional.h"
49 #include "inline-frame.h"
50 #include "stack.h"
52 /* See gdbthread.h. */
54 bool debug_threads = false;
56 /* Implement 'show debug threads'. */
58 static void
59 show_debug_threads (struct ui_file *file, int from_tty,
60 struct cmd_list_element *c, const char *value)
62 fprintf_filtered (file, _("Thread debugging is \"%s\".\n"), value);
65 /* Definition of struct thread_info exported to gdbthread.h. */
67 /* Prototypes for local functions. */
69 static int highest_thread_num;
71 /* The current/selected thread. */
72 static thread_info *current_thread_;
74 /* Returns true if THR is the current thread. */
76 static bool
77 is_current_thread (const thread_info *thr)
79 return thr == current_thread_;
82 struct thread_info*
83 inferior_thread (void)
85 gdb_assert (current_thread_ != nullptr);
86 return current_thread_;
89 /* Delete the breakpoint pointed at by BP_P, if there's one. */
91 static void
92 delete_thread_breakpoint (struct breakpoint **bp_p)
94 if (*bp_p != NULL)
96 delete_breakpoint (*bp_p);
97 *bp_p = NULL;
101 void
102 delete_step_resume_breakpoint (struct thread_info *tp)
104 if (tp != NULL)
105 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
108 void
109 delete_exception_resume_breakpoint (struct thread_info *tp)
111 if (tp != NULL)
112 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
115 /* See gdbthread.h. */
117 void
118 delete_single_step_breakpoints (struct thread_info *tp)
120 if (tp != NULL)
121 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
124 /* Delete the breakpoint pointed at by BP_P at the next stop, if
125 there's one. */
127 static void
128 delete_at_next_stop (struct breakpoint **bp)
130 if (*bp != NULL)
132 (*bp)->disposition = disp_del_at_next_stop;
133 *bp = NULL;
137 /* See gdbthread.h. */
140 thread_has_single_step_breakpoints_set (struct thread_info *tp)
142 return tp->control.single_step_breakpoints != NULL;
145 /* See gdbthread.h. */
148 thread_has_single_step_breakpoint_here (struct thread_info *tp,
149 const address_space *aspace,
150 CORE_ADDR addr)
152 struct breakpoint *ss_bps = tp->control.single_step_breakpoints;
154 return (ss_bps != NULL
155 && breakpoint_has_location_inserted_here (ss_bps, aspace, addr));
158 /* See gdbthread.h. */
160 void
161 thread_cancel_execution_command (struct thread_info *thr)
163 if (thr->thread_fsm != NULL)
165 thr->thread_fsm->clean_up (thr);
166 delete thr->thread_fsm;
167 thr->thread_fsm = NULL;
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 /* See gdbthread.h. */
195 void
196 set_thread_exited (thread_info *tp, bool silent)
198 /* Dead threads don't need to step-over. Remove from chain. */
199 if (thread_is_in_step_over_chain (tp))
200 global_thread_step_over_chain_remove (tp);
202 if (tp->state != THREAD_EXITED)
204 process_stratum_target *proc_target = tp->inf->process_target ();
206 /* Some targets unpush themselves from the inferior's target stack before
207 clearing the inferior's thread list (which marks all threads as exited,
208 and therefore leads to this function). In this case, the inferior's
209 process target will be nullptr when we arrive here.
211 See also the comment in inferior::unpush_target. */
212 if (proc_target != nullptr)
213 proc_target->maybe_remove_resumed_with_pending_wait_status (tp);
215 gdb::observers::thread_exit.notify (tp, silent);
217 /* Tag it as exited. */
218 tp->state = THREAD_EXITED;
220 /* Clear breakpoints, etc. associated with this thread. */
221 clear_thread_inferior_resources (tp);
223 /* Remove from the ptid_t map. We don't want for
224 find_thread_ptid to find exited threads. Also, the target
225 may reuse the ptid for a new thread, and there can only be
226 one value per key; adding a new thread with the same ptid_t
227 would overwrite the exited thread's ptid entry. */
228 size_t nr_deleted = tp->inf->ptid_thread_map.erase (tp->ptid);
229 gdb_assert (nr_deleted == 1);
233 void
234 init_thread_list (void)
236 highest_thread_num = 0;
238 for (inferior *inf : all_inferiors ())
239 inf->clear_thread_list (true);
242 /* Allocate a new thread of inferior INF with target id PTID and add
243 it to the thread list. */
245 static struct thread_info *
246 new_thread (struct inferior *inf, ptid_t ptid)
248 thread_info *tp = new thread_info (inf, ptid);
250 threads_debug_printf ("creating a new thread object, inferior %d, ptid %s",
251 inf->num, ptid.to_string ().c_str ());
253 inf->thread_list.push_back (*tp);
255 /* A thread with this ptid should not exist in the map yet. */
256 gdb_assert (inf->ptid_thread_map.find (ptid) == inf->ptid_thread_map.end ());
258 inf->ptid_thread_map[ptid] = tp;
260 return tp;
263 struct thread_info *
264 add_thread_silent (process_stratum_target *targ, ptid_t ptid)
266 gdb_assert (targ != nullptr);
268 inferior *inf = find_inferior_ptid (targ, ptid);
270 threads_debug_printf ("add thread to inferior %d, ptid %s, target %s",
271 inf->num, ptid.to_string ().c_str (),
272 targ->shortname ());
274 /* We may have an old thread with the same id in the thread list.
275 If we do, it must be dead, otherwise we wouldn't be adding a new
276 thread with the same id. The OS is reusing this id --- delete
277 the old thread, and create a new one. */
278 thread_info *tp = find_thread_ptid (inf, ptid);
279 if (tp != nullptr)
280 delete_thread (tp);
282 tp = new_thread (inf, ptid);
283 gdb::observers::new_thread.notify (tp);
285 return tp;
288 struct thread_info *
289 add_thread_with_info (process_stratum_target *targ, ptid_t ptid,
290 private_thread_info *priv)
292 thread_info *result = add_thread_silent (targ, ptid);
294 result->priv.reset (priv);
296 if (print_thread_events)
297 printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid).c_str ());
299 annotate_new_thread ();
300 return result;
303 struct thread_info *
304 add_thread (process_stratum_target *targ, ptid_t ptid)
306 return add_thread_with_info (targ, ptid, NULL);
309 private_thread_info::~private_thread_info () = default;
311 thread_info::thread_info (struct inferior *inf_, ptid_t ptid_)
312 : ptid (ptid_), inf (inf_)
314 gdb_assert (inf_ != NULL);
316 this->global_num = ++highest_thread_num;
317 this->per_inf_num = ++inf_->highest_thread_num;
319 /* Nothing to follow yet. */
320 this->pending_follow.set_spurious ();
323 /* See gdbthread.h. */
325 thread_info::~thread_info ()
327 threads_debug_printf ("thread %s", this->ptid.to_string ().c_str ());
330 /* See gdbthread.h. */
332 bool
333 thread_info::deletable () const
335 /* If this is the current thread, or there's code out there that
336 relies on it existing (refcount > 0) we can't delete yet. */
337 return refcount () == 0 && !is_current_thread (this);
340 /* See gdbthread.h. */
342 void
343 thread_info::set_executing (bool executing)
345 m_executing = executing;
346 if (executing)
347 this->clear_stop_pc ();
350 /* See gdbthread.h. */
352 void
353 thread_info::set_resumed (bool resumed)
355 if (resumed == m_resumed)
356 return;
358 process_stratum_target *proc_target = this->inf->process_target ();
360 /* If we transition from resumed to not resumed, we might need to remove
361 the thread from the resumed threads with pending statuses list. */
362 if (!resumed)
363 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
365 m_resumed = resumed;
367 /* If we transition from not resumed to resumed, we might need to add
368 the thread to the resumed threads with pending statuses list. */
369 if (resumed)
370 proc_target->maybe_add_resumed_with_pending_wait_status (this);
373 /* See gdbthread.h. */
375 void
376 thread_info::set_pending_waitstatus (const target_waitstatus &ws)
378 gdb_assert (!this->has_pending_waitstatus ());
380 m_suspend.waitstatus = ws;
381 m_suspend.waitstatus_pending_p = 1;
383 process_stratum_target *proc_target = this->inf->process_target ();
384 proc_target->maybe_add_resumed_with_pending_wait_status (this);
387 /* See gdbthread.h. */
389 void
390 thread_info::clear_pending_waitstatus ()
392 gdb_assert (this->has_pending_waitstatus ());
394 process_stratum_target *proc_target = this->inf->process_target ();
395 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
397 m_suspend.waitstatus_pending_p = 0;
400 /* See gdbthread.h. */
403 thread_is_in_step_over_chain (struct thread_info *tp)
405 return tp->step_over_list_node.is_linked ();
408 /* See gdbthread.h. */
411 thread_step_over_chain_length (const thread_step_over_list &l)
413 int num = 0;
415 for (const thread_info &thread ATTRIBUTE_UNUSED : l)
416 ++num;
418 return num;
421 /* See gdbthread.h. */
423 void
424 global_thread_step_over_chain_enqueue (struct thread_info *tp)
426 infrun_debug_printf ("enqueueing thread %s in global step over chain",
427 target_pid_to_str (tp->ptid).c_str ());
429 gdb_assert (!thread_is_in_step_over_chain (tp));
430 global_thread_step_over_list.push_back (*tp);
433 /* See gdbthread.h. */
435 void
436 global_thread_step_over_chain_enqueue_chain (thread_step_over_list &&list)
438 global_thread_step_over_list.splice (std::move (list));
441 /* See gdbthread.h. */
443 void
444 global_thread_step_over_chain_remove (struct thread_info *tp)
446 infrun_debug_printf ("removing thread %s from global step over chain",
447 target_pid_to_str (tp->ptid).c_str ());
449 gdb_assert (thread_is_in_step_over_chain (tp));
450 auto it = global_thread_step_over_list.iterator_to (*tp);
451 global_thread_step_over_list.erase (it);
454 /* Delete the thread referenced by THR. If SILENT, don't notify
455 the observer of this exit.
457 THR must not be NULL or a failed assertion will be raised. */
459 static void
460 delete_thread_1 (thread_info *thr, bool silent)
462 gdb_assert (thr != nullptr);
464 threads_debug_printf ("deleting thread %s, silent = %d",
465 thr->ptid.to_string ().c_str (), silent);
467 set_thread_exited (thr, silent);
469 if (!thr->deletable ())
471 /* Will be really deleted some other time. */
472 return;
475 auto it = thr->inf->thread_list.iterator_to (*thr);
476 thr->inf->thread_list.erase (it);
478 delete thr;
481 /* See gdbthread.h. */
483 void
484 delete_thread (thread_info *thread)
486 delete_thread_1 (thread, false /* not silent */);
489 void
490 delete_thread_silent (thread_info *thread)
492 delete_thread_1 (thread, true /* silent */);
495 struct thread_info *
496 find_thread_global_id (int global_id)
498 for (thread_info *tp : all_threads ())
499 if (tp->global_num == global_id)
500 return tp;
502 return NULL;
505 static struct thread_info *
506 find_thread_id (struct inferior *inf, int thr_num)
508 for (thread_info *tp : inf->threads ())
509 if (tp->per_inf_num == thr_num)
510 return tp;
512 return NULL;
515 /* See gdbthread.h. */
517 struct thread_info *
518 find_thread_ptid (process_stratum_target *targ, ptid_t ptid)
520 inferior *inf = find_inferior_ptid (targ, ptid);
521 if (inf == NULL)
522 return NULL;
523 return find_thread_ptid (inf, ptid);
526 /* See gdbthread.h. */
528 struct thread_info *
529 find_thread_ptid (inferior *inf, ptid_t ptid)
531 gdb_assert (inf != nullptr);
533 auto it = inf->ptid_thread_map.find (ptid);
534 if (it != inf->ptid_thread_map.end ())
535 return it->second;
536 else
537 return nullptr;
540 /* See gdbthread.h. */
542 struct thread_info *
543 find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
544 struct inferior *inf)
546 return target_thread_handle_to_thread_info (handle.data (),
547 handle.size (),
548 inf);
552 * Thread iterator function.
554 * Calls a callback function once for each thread, so long as
555 * the callback function returns false. If the callback function
556 * returns true, the iteration will end and the current thread
557 * will be returned. This can be useful for implementing a
558 * search for a thread with arbitrary attributes, or for applying
559 * some operation to every thread.
561 * FIXME: some of the existing functionality, such as
562 * "Thread apply all", might be rewritten using this functionality.
565 struct thread_info *
566 iterate_over_threads (int (*callback) (struct thread_info *, void *),
567 void *data)
569 for (thread_info *tp : all_threads_safe ())
570 if ((*callback) (tp, data))
571 return tp;
573 return NULL;
576 /* See gdbthread.h. */
578 bool
579 any_thread_p ()
581 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
582 return true;
583 return false;
587 thread_count (process_stratum_target *proc_target)
589 auto rng = all_threads (proc_target);
590 return std::distance (rng.begin (), rng.end ());
593 /* Return the number of non-exited threads in the thread list. */
595 static int
596 live_threads_count (void)
598 auto rng = all_non_exited_threads ();
599 return std::distance (rng.begin (), rng.end ());
603 valid_global_thread_id (int global_id)
605 for (thread_info *tp : all_threads ())
606 if (tp->global_num == global_id)
607 return 1;
609 return 0;
612 bool
613 in_thread_list (process_stratum_target *targ, ptid_t ptid)
615 return find_thread_ptid (targ, ptid) != nullptr;
618 /* Finds the first thread of the inferior. */
620 thread_info *
621 first_thread_of_inferior (inferior *inf)
623 if (inf->thread_list.empty ())
624 return nullptr;
626 return &inf->thread_list.front ();
629 thread_info *
630 any_thread_of_inferior (inferior *inf)
632 gdb_assert (inf->pid != 0);
634 /* Prefer the current thread, if there's one. */
635 if (inf == current_inferior () && inferior_ptid != null_ptid)
636 return inferior_thread ();
638 for (thread_info *tp : inf->non_exited_threads ())
639 return tp;
641 return NULL;
644 thread_info *
645 any_live_thread_of_inferior (inferior *inf)
647 struct thread_info *curr_tp = NULL;
648 struct thread_info *tp_executing = NULL;
650 gdb_assert (inf != NULL && inf->pid != 0);
652 /* Prefer the current thread if it's not executing. */
653 if (inferior_ptid != null_ptid && current_inferior () == inf)
655 /* If the current thread is dead, forget it. If it's not
656 executing, use it. Otherwise, still choose it (below), but
657 only if no other non-executing thread is found. */
658 curr_tp = inferior_thread ();
659 if (curr_tp->state == THREAD_EXITED)
660 curr_tp = NULL;
661 else if (!curr_tp->executing ())
662 return curr_tp;
665 for (thread_info *tp : inf->non_exited_threads ())
667 if (!tp->executing ())
668 return tp;
670 tp_executing = tp;
673 /* If both the current thread and all live threads are executing,
674 prefer the current thread. */
675 if (curr_tp != NULL)
676 return curr_tp;
678 /* Otherwise, just return an executing thread, if any. */
679 return tp_executing;
682 /* Return true if TP is an active thread. */
683 static bool
684 thread_alive (thread_info *tp)
686 if (tp->state == THREAD_EXITED)
687 return false;
689 /* Ensure we're looking at the right target stack. */
690 gdb_assert (tp->inf == current_inferior ());
692 return target_thread_alive (tp->ptid);
695 /* See gdbthreads.h. */
697 bool
698 switch_to_thread_if_alive (thread_info *thr)
700 scoped_restore_current_thread restore_thread;
702 /* Switch inferior first, so that we're looking at the right target
703 stack. */
704 switch_to_inferior_no_thread (thr->inf);
706 if (thread_alive (thr))
708 switch_to_thread (thr);
709 restore_thread.dont_restore ();
710 return true;
713 return false;
716 /* See gdbthreads.h. */
718 void
719 prune_threads (void)
721 scoped_restore_current_thread restore_thread;
723 for (thread_info *tp : all_threads_safe ())
725 switch_to_inferior_no_thread (tp->inf);
727 if (!thread_alive (tp))
728 delete_thread (tp);
732 /* See gdbthreads.h. */
734 void
735 delete_exited_threads (void)
737 for (thread_info *tp : all_threads_safe ())
738 if (tp->state == THREAD_EXITED)
739 delete_thread (tp);
742 /* Return true value if stack temporaries are enabled for the thread
743 TP. */
745 bool
746 thread_stack_temporaries_enabled_p (thread_info *tp)
748 if (tp == NULL)
749 return false;
750 else
751 return tp->stack_temporaries_enabled;
754 /* Push V on to the stack temporaries of the thread with id PTID. */
756 void
757 push_thread_stack_temporary (thread_info *tp, struct value *v)
759 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
760 tp->stack_temporaries.push_back (v);
763 /* Return true if VAL is among the stack temporaries of the thread
764 TP. Return false otherwise. */
766 bool
767 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
769 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
770 for (value *v : tp->stack_temporaries)
771 if (v == val)
772 return true;
774 return false;
777 /* Return the last of the stack temporaries for thread with id PTID.
778 Return NULL if there are no stack temporaries for the thread. */
780 value *
781 get_last_thread_stack_temporary (thread_info *tp)
783 struct value *lastval = NULL;
785 gdb_assert (tp != NULL);
786 if (!tp->stack_temporaries.empty ())
787 lastval = tp->stack_temporaries.back ();
789 return lastval;
792 void
793 thread_change_ptid (process_stratum_target *targ,
794 ptid_t old_ptid, ptid_t new_ptid)
796 struct inferior *inf;
797 struct thread_info *tp;
799 /* It can happen that what we knew as the target inferior id
800 changes. E.g, target remote may only discover the remote process
801 pid after adding the inferior to GDB's list. */
802 inf = find_inferior_ptid (targ, old_ptid);
803 inf->pid = new_ptid.pid ();
805 tp = find_thread_ptid (inf, old_ptid);
806 gdb_assert (tp != nullptr);
808 int num_erased = inf->ptid_thread_map.erase (old_ptid);
809 gdb_assert (num_erased == 1);
811 tp->ptid = new_ptid;
812 inf->ptid_thread_map[new_ptid] = tp;
814 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
817 /* See gdbthread.h. */
819 void
820 set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
822 for (thread_info *tp : all_non_exited_threads (targ, ptid))
823 tp->set_resumed (resumed);
826 /* Helper for set_running, that marks one thread either running or
827 stopped. */
829 static bool
830 set_running_thread (struct thread_info *tp, bool running)
832 bool started = false;
834 if (running && tp->state == THREAD_STOPPED)
835 started = true;
836 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
838 if (!running)
840 /* If the thread is now marked stopped, remove it from
841 the step-over queue, so that we don't try to resume
842 it until the user wants it to. */
843 if (thread_is_in_step_over_chain (tp))
844 global_thread_step_over_chain_remove (tp);
847 return started;
850 /* See gdbthread.h. */
852 void
853 thread_info::set_running (bool running)
855 if (set_running_thread (this, running))
856 gdb::observers::target_resumed.notify (this->ptid);
859 void
860 set_running (process_stratum_target *targ, ptid_t ptid, bool running)
862 /* We try not to notify the observer if no thread has actually
863 changed the running state -- merely to reduce the number of
864 messages to the MI frontend. A frontend is supposed to handle
865 multiple *running notifications just fine. */
866 bool any_started = false;
868 for (thread_info *tp : all_non_exited_threads (targ, ptid))
869 if (set_running_thread (tp, running))
870 any_started = true;
872 if (any_started)
873 gdb::observers::target_resumed.notify (ptid);
876 void
877 set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
879 for (thread_info *tp : all_non_exited_threads (targ, ptid))
880 tp->set_executing (executing);
882 /* It only takes one running thread to spawn more threads. */
883 if (executing)
884 targ->threads_executing = true;
885 /* Only clear the flag if the caller is telling us everything is
886 stopped. */
887 else if (minus_one_ptid == ptid)
888 targ->threads_executing = false;
891 /* See gdbthread.h. */
893 bool
894 threads_are_executing (process_stratum_target *target)
896 return target->threads_executing;
899 void
900 set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
902 for (thread_info *tp : all_non_exited_threads (targ, ptid))
903 tp->stop_requested = stop;
905 /* Call the stop requested observer so other components of GDB can
906 react to this request. */
907 if (stop)
908 gdb::observers::thread_stop_requested.notify (ptid);
911 void
912 finish_thread_state (process_stratum_target *targ, ptid_t ptid)
914 bool any_started = false;
916 for (thread_info *tp : all_non_exited_threads (targ, ptid))
917 if (set_running_thread (tp, tp->executing ()))
918 any_started = true;
920 if (any_started)
921 gdb::observers::target_resumed.notify (ptid);
924 /* See gdbthread.h. */
926 void
927 validate_registers_access (void)
929 /* No selected thread, no registers. */
930 if (inferior_ptid == null_ptid)
931 error (_("No thread selected."));
933 thread_info *tp = inferior_thread ();
935 /* Don't try to read from a dead thread. */
936 if (tp->state == THREAD_EXITED)
937 error (_("The current thread has terminated"));
939 /* ... or from a spinning thread. FIXME: This isn't actually fully
940 correct. It'll allow an user-requested access (e.g., "print $pc"
941 at the prompt) when a thread is not executing for some internal
942 reason, but is marked running from the user's perspective. E.g.,
943 the thread is waiting for its turn in the step-over queue. */
944 if (tp->executing ())
945 error (_("Selected thread is running."));
948 /* See gdbthread.h. */
950 bool
951 can_access_registers_thread (thread_info *thread)
953 /* No thread, no registers. */
954 if (thread == NULL)
955 return false;
957 /* Don't try to read from a dead thread. */
958 if (thread->state == THREAD_EXITED)
959 return false;
961 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
962 if (thread->executing ())
963 return false;
965 return true;
969 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
971 return (pc >= thread->control.step_range_start
972 && pc < thread->control.step_range_end);
975 /* Helper for print_thread_info. Returns true if THR should be
976 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
977 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
978 is true if REQUESTED_THREADS is list of global IDs, false if a list
979 of per-inferior thread ids. If PID is not -1, only print THR if it
980 is a thread from the process PID. Otherwise, threads from all
981 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
982 and PID is not -1, then the thread is printed if it belongs to the
983 specified process. Otherwise, an error is raised. */
985 static int
986 should_print_thread (const char *requested_threads, int default_inf_num,
987 int global_ids, int pid, struct thread_info *thr)
989 if (requested_threads != NULL && *requested_threads != '\0')
991 int in_list;
993 if (global_ids)
994 in_list = number_is_in_list (requested_threads, thr->global_num);
995 else
996 in_list = tid_is_in_list (requested_threads, default_inf_num,
997 thr->inf->num, thr->per_inf_num);
998 if (!in_list)
999 return 0;
1002 if (pid != -1 && thr->ptid.pid () != pid)
1004 if (requested_threads != NULL && *requested_threads != '\0')
1005 error (_("Requested thread not found in requested process"));
1006 return 0;
1009 if (thr->state == THREAD_EXITED)
1010 return 0;
1012 return 1;
1015 /* Return the string to display in "info threads"'s "Target Id"
1016 column, for TP. */
1018 static std::string
1019 thread_target_id_str (thread_info *tp)
1021 std::string target_id = target_pid_to_str (tp->ptid);
1022 const char *extra_info = target_extra_thread_info (tp);
1023 const char *name = thread_name (tp);
1025 if (extra_info != nullptr && name != nullptr)
1026 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1027 extra_info);
1028 else if (extra_info != nullptr)
1029 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1030 else if (name != nullptr)
1031 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1032 else
1033 return target_id;
1036 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1037 whether REQUESTED_THREADS is a list of global or per-inferior
1038 thread ids. */
1040 static void
1041 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1042 int global_ids, int pid,
1043 int show_global_ids)
1045 int default_inf_num = current_inferior ()->num;
1047 update_thread_list ();
1049 /* Whether we saw any thread. */
1050 bool any_thread = false;
1051 /* Whether the current thread is exited. */
1052 bool current_exited = false;
1054 thread_info *current_thread = (inferior_ptid != null_ptid
1055 ? inferior_thread () : NULL);
1058 /* For backward compatibility, we make a list for MI. A table is
1059 preferable for the CLI, though, because it shows table
1060 headers. */
1061 gdb::optional<ui_out_emit_list> list_emitter;
1062 gdb::optional<ui_out_emit_table> table_emitter;
1064 /* We'll be switching threads temporarily below. */
1065 scoped_restore_current_thread restore_thread;
1067 if (uiout->is_mi_like_p ())
1068 list_emitter.emplace (uiout, "threads");
1069 else
1071 int n_threads = 0;
1072 /* The width of the "Target Id" column. Grown below to
1073 accommodate the largest entry. */
1074 size_t target_id_col_width = 17;
1076 for (thread_info *tp : all_threads ())
1078 if (!should_print_thread (requested_threads, default_inf_num,
1079 global_ids, pid, tp))
1080 continue;
1082 if (!uiout->is_mi_like_p ())
1084 /* Switch inferiors so we're looking at the right
1085 target stack. */
1086 switch_to_inferior_no_thread (tp->inf);
1088 target_id_col_width
1089 = std::max (target_id_col_width,
1090 thread_target_id_str (tp).size ());
1093 ++n_threads;
1096 if (n_threads == 0)
1098 if (requested_threads == NULL || *requested_threads == '\0')
1099 uiout->message (_("No threads.\n"));
1100 else
1101 uiout->message (_("No threads match '%s'.\n"),
1102 requested_threads);
1103 return;
1106 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1107 n_threads, "threads");
1109 uiout->table_header (1, ui_left, "current", "");
1110 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1111 if (show_global_ids)
1112 uiout->table_header (4, ui_left, "id", "GId");
1113 uiout->table_header (target_id_col_width, ui_left,
1114 "target-id", "Target Id");
1115 uiout->table_header (1, ui_left, "frame", "Frame");
1116 uiout->table_body ();
1119 for (inferior *inf : all_inferiors ())
1120 for (thread_info *tp : inf->threads ())
1122 int core;
1124 any_thread = true;
1125 if (tp == current_thread && tp->state == THREAD_EXITED)
1126 current_exited = true;
1128 if (!should_print_thread (requested_threads, default_inf_num,
1129 global_ids, pid, tp))
1130 continue;
1132 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1134 if (!uiout->is_mi_like_p ())
1136 if (tp == current_thread)
1137 uiout->field_string ("current", "*");
1138 else
1139 uiout->field_skip ("current");
1141 uiout->field_string ("id-in-tg", print_thread_id (tp));
1144 if (show_global_ids || uiout->is_mi_like_p ())
1145 uiout->field_signed ("id", tp->global_num);
1147 /* Switch to the thread (and inferior / target). */
1148 switch_to_thread (tp);
1150 /* For the CLI, we stuff everything into the target-id field.
1151 This is a gross hack to make the output come out looking
1152 correct. The underlying problem here is that ui-out has no
1153 way to specify that a field's space allocation should be
1154 shared by several fields. For MI, we do the right thing
1155 instead. */
1157 if (uiout->is_mi_like_p ())
1159 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1161 const char *extra_info = target_extra_thread_info (tp);
1162 if (extra_info != nullptr)
1163 uiout->field_string ("details", extra_info);
1165 const char *name = thread_name (tp);
1166 if (name != NULL)
1167 uiout->field_string ("name", name);
1169 else
1171 uiout->field_string ("target-id", thread_target_id_str (tp));
1174 if (tp->state == THREAD_RUNNING)
1175 uiout->text ("(running)\n");
1176 else
1178 /* The switch above put us at the top of the stack (leaf
1179 frame). */
1180 print_stack_frame (get_selected_frame (NULL),
1181 /* For MI output, print frame level. */
1182 uiout->is_mi_like_p (),
1183 LOCATION, 0);
1186 if (uiout->is_mi_like_p ())
1188 const char *state = "stopped";
1190 if (tp->state == THREAD_RUNNING)
1191 state = "running";
1192 uiout->field_string ("state", state);
1195 core = target_core_of_thread (tp->ptid);
1196 if (uiout->is_mi_like_p () && core != -1)
1197 uiout->field_signed ("core", core);
1200 /* This end scope restores the current thread and the frame
1201 selected before the "info threads" command, and it finishes the
1202 ui-out list or table. */
1205 if (pid == -1 && requested_threads == NULL)
1207 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1208 uiout->field_signed ("current-thread-id", current_thread->global_num);
1210 if (inferior_ptid != null_ptid && current_exited)
1211 uiout->message ("\n\
1212 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1213 print_thread_id (inferior_thread ()));
1214 else if (any_thread && inferior_ptid == null_ptid)
1215 uiout->message ("\n\
1216 No selected thread. See `help thread'.\n");
1220 /* See gdbthread.h. */
1222 void
1223 print_thread_info (struct ui_out *uiout, const char *requested_threads,
1224 int pid)
1226 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1229 /* The options for the "info threads" command. */
1231 struct info_threads_opts
1233 /* For "-gid". */
1234 bool show_global_ids = false;
1237 static const gdb::option::option_def info_threads_option_defs[] = {
1239 gdb::option::flag_option_def<info_threads_opts> {
1240 "gid",
1241 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1242 N_("Show global thread IDs."),
1247 /* Create an option_def_group for the "info threads" options, with
1248 IT_OPTS as context. */
1250 static inline gdb::option::option_def_group
1251 make_info_threads_options_def_group (info_threads_opts *it_opts)
1253 return {{info_threads_option_defs}, it_opts};
1256 /* Implementation of the "info threads" command.
1258 Note: this has the drawback that it _really_ switches
1259 threads, which frees the frame cache. A no-side
1260 effects info-threads command would be nicer. */
1262 static void
1263 info_threads_command (const char *arg, int from_tty)
1265 info_threads_opts it_opts;
1267 auto grp = make_info_threads_options_def_group (&it_opts);
1268 gdb::option::process_options
1269 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1271 print_thread_info_1 (current_uiout, arg, 0, -1, it_opts.show_global_ids);
1274 /* Completer for the "info threads" command. */
1276 static void
1277 info_threads_command_completer (struct cmd_list_element *ignore,
1278 completion_tracker &tracker,
1279 const char *text, const char *word_ignored)
1281 const auto grp = make_info_threads_options_def_group (nullptr);
1283 if (gdb::option::complete_options
1284 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1285 return;
1287 /* Convenience to let the user know what the option can accept. */
1288 if (*text == '\0')
1290 gdb::option::complete_on_all_options (tracker, grp);
1291 /* Keep this "ID" in sync with what "help info threads"
1292 says. */
1293 tracker.add_completion (make_unique_xstrdup ("ID"));
1297 /* See gdbthread.h. */
1299 void
1300 switch_to_thread_no_regs (struct thread_info *thread)
1302 struct inferior *inf = thread->inf;
1304 set_current_program_space (inf->pspace);
1305 set_current_inferior (inf);
1307 current_thread_ = thread;
1308 inferior_ptid = current_thread_->ptid;
1311 /* See gdbthread.h. */
1313 void
1314 switch_to_no_thread ()
1316 if (current_thread_ == nullptr)
1317 return;
1319 current_thread_ = nullptr;
1320 inferior_ptid = null_ptid;
1321 reinit_frame_cache ();
1324 /* See gdbthread.h. */
1326 void
1327 switch_to_thread (thread_info *thr)
1329 gdb_assert (thr != NULL);
1331 if (is_current_thread (thr))
1332 return;
1334 switch_to_thread_no_regs (thr);
1336 reinit_frame_cache ();
1339 /* See gdbsupport/common-gdbthread.h. */
1341 void
1342 switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
1344 thread_info *thr = find_thread_ptid (proc_target, ptid);
1345 switch_to_thread (thr);
1348 /* See frame.h. */
1350 void
1351 scoped_restore_current_thread::restore ()
1353 /* If an entry of thread_info was previously selected, it won't be
1354 deleted because we've increased its refcount. The thread represented
1355 by this thread_info entry may have already exited (due to normal exit,
1356 detach, etc), so the thread_info.state is THREAD_EXITED. */
1357 if (m_thread != NULL
1358 /* If the previously selected thread belonged to a process that has
1359 in the mean time exited (or killed, detached, etc.), then don't revert
1360 back to it, but instead simply drop back to no thread selected. */
1361 && m_inf->pid != 0)
1362 switch_to_thread (m_thread.get ());
1363 else
1364 switch_to_inferior_no_thread (m_inf.get ());
1366 /* The running state of the originally selected thread may have
1367 changed, so we have to recheck it here. */
1368 if (inferior_ptid != null_ptid
1369 && m_was_stopped
1370 && m_thread->state == THREAD_STOPPED
1371 && target_has_registers ()
1372 && target_has_stack ()
1373 && target_has_memory ())
1374 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1376 set_language (m_lang);
1379 scoped_restore_current_thread::~scoped_restore_current_thread ()
1381 if (!m_dont_restore)
1382 restore ();
1385 scoped_restore_current_thread::scoped_restore_current_thread ()
1387 m_inf = inferior_ref::new_reference (current_inferior ());
1389 m_lang = current_language->la_language;
1391 if (inferior_ptid != null_ptid)
1393 m_thread = thread_info_ref::new_reference (inferior_thread ());
1395 m_was_stopped = m_thread->state == THREAD_STOPPED;
1396 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
1400 /* See gdbthread.h. */
1403 show_thread_that_caused_stop (void)
1405 return highest_thread_num > 1;
1408 /* See gdbthread.h. */
1411 show_inferior_qualified_tids (void)
1413 auto inf = inferior_list.begin ();
1414 if (inf->num != 1)
1415 return true;
1416 ++inf;
1417 return inf != inferior_list.end ();
1420 /* See gdbthread.h. */
1422 const char *
1423 print_thread_id (struct thread_info *thr)
1425 char *s = get_print_cell ();
1427 if (show_inferior_qualified_tids ())
1428 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1429 else
1430 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1431 return s;
1434 /* Sort an array of struct thread_info pointers by thread ID (first by
1435 inferior number, and then by per-inferior thread number). Sorts in
1436 ascending order. */
1438 static bool
1439 tp_array_compar_ascending (const thread_info_ref &a, const thread_info_ref &b)
1441 if (a->inf->num != b->inf->num)
1442 return a->inf->num < b->inf->num;
1444 return (a->per_inf_num < b->per_inf_num);
1447 /* Sort an array of struct thread_info pointers by thread ID (first by
1448 inferior number, and then by per-inferior thread number). Sorts in
1449 descending order. */
1451 static bool
1452 tp_array_compar_descending (const thread_info_ref &a, const thread_info_ref &b)
1454 if (a->inf->num != b->inf->num)
1455 return a->inf->num > b->inf->num;
1457 return (a->per_inf_num > b->per_inf_num);
1460 /* See gdbthread.h. */
1462 void
1463 thread_try_catch_cmd (thread_info *thr, gdb::optional<int> ada_task,
1464 const char *cmd, int from_tty,
1465 const qcs_flags &flags)
1467 gdb_assert (is_current_thread (thr));
1469 /* The thread header is computed before running the command since
1470 the command can change the inferior, which is not permitted
1471 by thread_target_id_str. */
1472 std::string thr_header;
1473 if (ada_task.has_value ())
1474 thr_header = string_printf (_("\nTask ID %d:\n"), *ada_task);
1475 else
1476 thr_header = string_printf (_("\nThread %s (%s):\n"),
1477 print_thread_id (thr),
1478 thread_target_id_str (thr).c_str ());
1482 std::string cmd_result;
1483 execute_command_to_string
1484 (cmd_result, cmd, from_tty, gdb_stdout->term_out ());
1485 if (!flags.silent || cmd_result.length () > 0)
1487 if (!flags.quiet)
1488 printf_filtered ("%s", thr_header.c_str ());
1489 printf_filtered ("%s", cmd_result.c_str ());
1492 catch (const gdb_exception_error &ex)
1494 if (!flags.silent)
1496 if (!flags.quiet)
1497 printf_filtered ("%s", thr_header.c_str ());
1498 if (flags.cont)
1499 printf_filtered ("%s\n", ex.what ());
1500 else
1501 throw;
1506 /* Option definition of "thread apply"'s "-ascending" option. */
1508 static const gdb::option::flag_option_def<> ascending_option_def = {
1509 "ascending",
1510 N_("\
1511 Call COMMAND for all threads in ascending order.\n\
1512 The default is descending order."),
1515 /* The qcs command line flags for the "thread apply" commands. Keep
1516 this in sync with the "frame apply" commands. */
1518 using qcs_flag_option_def
1519 = gdb::option::flag_option_def<qcs_flags>;
1521 static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1522 qcs_flag_option_def {
1523 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1524 N_("Disables printing the thread information."),
1527 qcs_flag_option_def {
1528 "c", [] (qcs_flags *opt) { return &opt->cont; },
1529 N_("Print any error raised by COMMAND and continue."),
1532 qcs_flag_option_def {
1533 "s", [] (qcs_flags *opt) { return &opt->silent; },
1534 N_("Silently ignore any errors or empty output produced by COMMAND."),
1538 /* Create an option_def_group for the "thread apply all" options, with
1539 ASCENDING and FLAGS as context. */
1541 static inline std::array<gdb::option::option_def_group, 2>
1542 make_thread_apply_all_options_def_group (bool *ascending,
1543 qcs_flags *flags)
1545 return {{
1546 { {ascending_option_def.def ()}, ascending},
1547 { {thr_qcs_flags_option_defs}, flags },
1551 /* Create an option_def_group for the "thread apply" options, with
1552 FLAGS as context. */
1554 static inline gdb::option::option_def_group
1555 make_thread_apply_options_def_group (qcs_flags *flags)
1557 return {{thr_qcs_flags_option_defs}, flags};
1560 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1561 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1562 of two numbers separated by a hyphen. Examples:
1564 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1565 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1566 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1568 static void
1569 thread_apply_all_command (const char *cmd, int from_tty)
1571 bool ascending = false;
1572 qcs_flags flags;
1574 auto group = make_thread_apply_all_options_def_group (&ascending,
1575 &flags);
1576 gdb::option::process_options
1577 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1579 validate_flags_qcs ("thread apply all", &flags);
1581 if (cmd == NULL || *cmd == '\000')
1582 error (_("Please specify a command at the end of 'thread apply all'"));
1584 update_thread_list ();
1586 int tc = live_threads_count ();
1587 if (tc != 0)
1589 /* Save a copy of the thread list and increment each thread's
1590 refcount while executing the command in the context of each
1591 thread, in case the command is one that wipes threads. E.g.,
1592 detach, kill, disconnect, etc., or even normally continuing
1593 over an inferior or thread exit. */
1594 std::vector<thread_info_ref> thr_list_cpy;
1595 thr_list_cpy.reserve (tc);
1597 for (thread_info *tp : all_non_exited_threads ())
1598 thr_list_cpy.push_back (thread_info_ref::new_reference (tp));
1599 gdb_assert (thr_list_cpy.size () == tc);
1601 auto *sorter = (ascending
1602 ? tp_array_compar_ascending
1603 : tp_array_compar_descending);
1604 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
1606 scoped_restore_current_thread restore_thread;
1608 for (thread_info_ref &thr : thr_list_cpy)
1609 if (switch_to_thread_if_alive (thr.get ()))
1610 thread_try_catch_cmd (thr.get (), {}, cmd, from_tty, flags);
1614 /* Completer for "thread apply [ID list]". */
1616 static void
1617 thread_apply_command_completer (cmd_list_element *ignore,
1618 completion_tracker &tracker,
1619 const char *text, const char * /*word*/)
1621 /* Don't leave this to complete_options because there's an early
1622 return below. */
1623 tracker.set_use_custom_word_point (true);
1625 tid_range_parser parser;
1626 parser.init (text, current_inferior ()->num);
1630 while (!parser.finished ())
1632 int inf_num, thr_start, thr_end;
1634 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1635 break;
1637 if (parser.in_star_range () || parser.in_thread_range ())
1638 parser.skip_range ();
1641 catch (const gdb_exception_error &ex)
1643 /* get_tid_range throws if it parses a negative number, for
1644 example. But a seemingly negative number may be the start of
1645 an option instead. */
1648 const char *cmd = parser.cur_tok ();
1650 if (cmd == text)
1652 /* No thread ID list yet. */
1653 return;
1656 /* Check if we're past a valid thread ID list already. */
1657 if (parser.finished ()
1658 && cmd > text && !isspace (cmd[-1]))
1659 return;
1661 /* We're past the thread ID list, advance word point. */
1662 tracker.advance_custom_word_point_by (cmd - text);
1663 text = cmd;
1665 const auto group = make_thread_apply_options_def_group (nullptr);
1666 if (gdb::option::complete_options
1667 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1668 return;
1670 complete_nested_command_line (tracker, text);
1673 /* Completer for "thread apply all". */
1675 static void
1676 thread_apply_all_command_completer (cmd_list_element *ignore,
1677 completion_tracker &tracker,
1678 const char *text, const char *word)
1680 const auto group = make_thread_apply_all_options_def_group (nullptr,
1681 nullptr);
1682 if (gdb::option::complete_options
1683 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1684 return;
1686 complete_nested_command_line (tracker, text);
1689 /* Implementation of the "thread apply" command. */
1691 static void
1692 thread_apply_command (const char *tidlist, int from_tty)
1694 qcs_flags flags;
1695 const char *cmd = NULL;
1696 tid_range_parser parser;
1698 if (tidlist == NULL || *tidlist == '\000')
1699 error (_("Please specify a thread ID list"));
1701 parser.init (tidlist, current_inferior ()->num);
1702 while (!parser.finished ())
1704 int inf_num, thr_start, thr_end;
1706 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1707 break;
1710 cmd = parser.cur_tok ();
1712 auto group = make_thread_apply_options_def_group (&flags);
1713 gdb::option::process_options
1714 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1716 validate_flags_qcs ("thread apply", &flags);
1718 if (*cmd == '\0')
1719 error (_("Please specify a command following the thread ID list"));
1721 if (tidlist == cmd || isdigit (cmd[0]))
1722 invalid_thread_id_error (cmd);
1724 scoped_restore_current_thread restore_thread;
1726 parser.init (tidlist, current_inferior ()->num);
1727 while (!parser.finished ())
1729 struct thread_info *tp = NULL;
1730 struct inferior *inf;
1731 int inf_num, thr_num;
1733 parser.get_tid (&inf_num, &thr_num);
1734 inf = find_inferior_id (inf_num);
1735 if (inf != NULL)
1736 tp = find_thread_id (inf, thr_num);
1738 if (parser.in_star_range ())
1740 if (inf == NULL)
1742 warning (_("Unknown inferior %d"), inf_num);
1743 parser.skip_range ();
1744 continue;
1747 /* No use looking for threads past the highest thread number
1748 the inferior ever had. */
1749 if (thr_num >= inf->highest_thread_num)
1750 parser.skip_range ();
1752 /* Be quiet about unknown threads numbers. */
1753 if (tp == NULL)
1754 continue;
1757 if (tp == NULL)
1759 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1760 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1761 else
1762 warning (_("Unknown thread %d"), thr_num);
1763 continue;
1766 if (!switch_to_thread_if_alive (tp))
1768 warning (_("Thread %s has terminated."), print_thread_id (tp));
1769 continue;
1772 thread_try_catch_cmd (tp, {}, cmd, from_tty, flags);
1777 /* Implementation of the "taas" command. */
1779 static void
1780 taas_command (const char *cmd, int from_tty)
1782 if (cmd == NULL || *cmd == '\0')
1783 error (_("Please specify a command to apply on all threads"));
1784 std::string expanded = std::string ("thread apply all -s ") + cmd;
1785 execute_command (expanded.c_str (), from_tty);
1788 /* Implementation of the "tfaas" command. */
1790 static void
1791 tfaas_command (const char *cmd, int from_tty)
1793 if (cmd == NULL || *cmd == '\0')
1794 error (_("Please specify a command to apply on all frames of all threads"));
1795 std::string expanded
1796 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1797 execute_command (expanded.c_str (), from_tty);
1800 /* Switch to the specified thread, or print the current thread. */
1802 void
1803 thread_command (const char *tidstr, int from_tty)
1805 if (tidstr == NULL)
1807 if (inferior_ptid == null_ptid)
1808 error (_("No thread selected"));
1810 if (target_has_stack ())
1812 struct thread_info *tp = inferior_thread ();
1814 if (tp->state == THREAD_EXITED)
1815 printf_filtered (_("[Current thread is %s (%s) (exited)]\n"),
1816 print_thread_id (tp),
1817 target_pid_to_str (inferior_ptid).c_str ());
1818 else
1819 printf_filtered (_("[Current thread is %s (%s)]\n"),
1820 print_thread_id (tp),
1821 target_pid_to_str (inferior_ptid).c_str ());
1823 else
1824 error (_("No stack."));
1826 else
1828 ptid_t previous_ptid = inferior_ptid;
1830 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1832 /* Print if the thread has not changed, otherwise an event will
1833 be sent. */
1834 if (inferior_ptid == previous_ptid)
1836 print_selected_thread_frame (current_uiout,
1837 USER_SELECTED_THREAD
1838 | USER_SELECTED_FRAME);
1840 else
1842 gdb::observers::user_selected_context_changed.notify
1843 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1848 /* Implementation of `thread name'. */
1850 static void
1851 thread_name_command (const char *arg, int from_tty)
1853 struct thread_info *info;
1855 if (inferior_ptid == null_ptid)
1856 error (_("No thread selected"));
1858 arg = skip_spaces (arg);
1860 info = inferior_thread ();
1861 info->set_name (arg != nullptr ? make_unique_xstrdup (arg) : nullptr);
1864 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1866 static void
1867 thread_find_command (const char *arg, int from_tty)
1869 const char *tmp;
1870 unsigned long match = 0;
1872 if (arg == NULL || *arg == '\0')
1873 error (_("Command requires an argument."));
1875 tmp = re_comp (arg);
1876 if (tmp != 0)
1877 error (_("Invalid regexp (%s): %s"), tmp, arg);
1879 /* We're going to be switching threads. */
1880 scoped_restore_current_thread restore_thread;
1882 update_thread_list ();
1884 for (thread_info *tp : all_threads ())
1886 switch_to_inferior_no_thread (tp->inf);
1888 if (tp->name () != nullptr && re_exec (tp->name ()))
1890 printf_filtered (_("Thread %s has name '%s'\n"),
1891 print_thread_id (tp), tp->name ());
1892 match++;
1895 tmp = target_thread_name (tp);
1896 if (tmp != NULL && re_exec (tmp))
1898 printf_filtered (_("Thread %s has target name '%s'\n"),
1899 print_thread_id (tp), tmp);
1900 match++;
1903 std::string name = target_pid_to_str (tp->ptid);
1904 if (!name.empty () && re_exec (name.c_str ()))
1906 printf_filtered (_("Thread %s has target id '%s'\n"),
1907 print_thread_id (tp), name.c_str ());
1908 match++;
1911 tmp = target_extra_thread_info (tp);
1912 if (tmp != NULL && re_exec (tmp))
1914 printf_filtered (_("Thread %s has extra info '%s'\n"),
1915 print_thread_id (tp), tmp);
1916 match++;
1919 if (!match)
1920 printf_filtered (_("No threads match '%s'\n"), arg);
1923 /* Print notices when new threads are attached and detached. */
1924 bool print_thread_events = true;
1925 static void
1926 show_print_thread_events (struct ui_file *file, int from_tty,
1927 struct cmd_list_element *c, const char *value)
1929 fprintf_filtered (file,
1930 _("Printing of thread events is %s.\n"),
1931 value);
1934 /* See gdbthread.h. */
1936 void
1937 thread_select (const char *tidstr, thread_info *tp)
1939 if (!switch_to_thread_if_alive (tp))
1940 error (_("Thread ID %s has terminated."), tidstr);
1942 annotate_thread_changed ();
1944 /* Since the current thread may have changed, see if there is any
1945 exited thread we can now delete. */
1946 delete_exited_threads ();
1949 /* Print thread and frame switch command response. */
1951 void
1952 print_selected_thread_frame (struct ui_out *uiout,
1953 user_selected_what selection)
1955 struct thread_info *tp = inferior_thread ();
1957 if (selection & USER_SELECTED_THREAD)
1959 if (uiout->is_mi_like_p ())
1961 uiout->field_signed ("new-thread-id",
1962 inferior_thread ()->global_num);
1964 else
1966 uiout->text ("[Switching to thread ");
1967 uiout->field_string ("new-thread-id", print_thread_id (tp));
1968 uiout->text (" (");
1969 uiout->text (target_pid_to_str (inferior_ptid));
1970 uiout->text (")]");
1974 if (tp->state == THREAD_RUNNING)
1976 if (selection & USER_SELECTED_THREAD)
1977 uiout->text ("(running)\n");
1979 else if (selection & USER_SELECTED_FRAME)
1981 if (selection & USER_SELECTED_THREAD)
1982 uiout->text ("\n");
1984 if (has_stack_frames ())
1985 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
1986 1, SRC_AND_LOC, 1);
1990 /* Update the 'threads_executing' global based on the threads we know
1991 about right now. This is used by infrun to tell whether we should
1992 pull events out of the current target. */
1994 static void
1995 update_threads_executing (void)
1997 process_stratum_target *targ = current_inferior ()->process_target ();
1999 if (targ == NULL)
2000 return;
2002 targ->threads_executing = false;
2004 for (inferior *inf : all_non_exited_inferiors (targ))
2006 if (!inf->has_execution ())
2007 continue;
2009 /* If the process has no threads, then it must be we have a
2010 process-exit event pending. */
2011 if (inf->thread_list.empty ())
2013 targ->threads_executing = true;
2014 return;
2017 for (thread_info *tp : inf->non_exited_threads ())
2019 if (tp->executing ())
2021 targ->threads_executing = true;
2022 return;
2028 void
2029 update_thread_list (void)
2031 target_update_thread_list ();
2032 update_threads_executing ();
2035 /* See gdbthread.h. */
2037 const char *
2038 thread_name (thread_info *thread)
2040 /* Use the manually set name if there is one. */
2041 const char *name = thread->name ();
2042 if (name != nullptr)
2043 return name;
2045 /* Otherwise, ask the target. Ensure we query the right target stack. */
2046 scoped_restore_current_thread restore_thread;
2047 if (thread->inf != current_inferior ())
2048 switch_to_inferior_no_thread (thread->inf);
2050 return target_thread_name (thread);
2053 /* Return a new value for the selected thread's id. Return a value of
2054 0 if no thread is selected. If GLOBAL is true, return the thread's
2055 global number. Otherwise return the per-inferior number. */
2057 static struct value *
2058 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2060 int int_val;
2062 if (inferior_ptid == null_ptid)
2063 int_val = 0;
2064 else
2066 thread_info *tp = inferior_thread ();
2067 if (global)
2068 int_val = tp->global_num;
2069 else
2070 int_val = tp->per_inf_num;
2073 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2076 /* Return a new value for the selected thread's per-inferior thread
2077 number. Return a value of 0 if no thread is selected, or no
2078 threads exist. */
2080 static struct value *
2081 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2082 struct internalvar *var,
2083 void *ignore)
2085 return thread_num_make_value_helper (gdbarch, 0);
2088 /* Return a new value for the selected thread's global id. Return a
2089 value of 0 if no thread is selected, or no threads exist. */
2091 static struct value *
2092 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2093 void *ignore)
2095 return thread_num_make_value_helper (gdbarch, 1);
2098 /* Commands with a prefix of `thread'. */
2099 struct cmd_list_element *thread_cmd_list = NULL;
2101 /* Implementation of `thread' variable. */
2103 static const struct internalvar_funcs thread_funcs =
2105 thread_id_per_inf_num_make_value,
2106 NULL,
2107 NULL
2110 /* Implementation of `gthread' variable. */
2112 static const struct internalvar_funcs gthread_funcs =
2114 global_thread_id_make_value,
2115 NULL,
2116 NULL
2119 void _initialize_thread ();
2120 void
2121 _initialize_thread ()
2123 static struct cmd_list_element *thread_apply_list = NULL;
2124 cmd_list_element *c;
2126 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2128 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2129 suggests. */
2130 static std::string info_threads_help
2131 = gdb::option::build_help (_("\
2132 Display currently known threads.\n\
2133 Usage: info threads [OPTION]... [ID]...\n\
2134 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2135 Otherwise, all threads are displayed.\n\
2137 Options:\n\
2138 %OPTIONS%"),
2139 info_threads_opts);
2141 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2142 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
2144 cmd_list_element *thread_cmd
2145 = add_prefix_cmd ("thread", class_run, thread_command, _("\
2146 Use this command to switch between threads.\n\
2147 The new thread ID must be currently known."),
2148 &thread_cmd_list, 1, &cmdlist);
2150 add_com_alias ("t", thread_cmd, class_run, 1);
2152 #define THREAD_APPLY_OPTION_HELP "\
2153 Prints per-inferior thread number and target system's thread id\n\
2154 followed by COMMAND output.\n\
2156 By default, an error raised during the execution of COMMAND\n\
2157 aborts \"thread apply\".\n\
2159 Options:\n\
2160 %OPTIONS%"
2162 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2164 static std::string thread_apply_help = gdb::option::build_help (_("\
2165 Apply a command to a list of threads.\n\
2166 Usage: thread apply ID... [OPTION]... COMMAND\n\
2167 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2168 THREAD_APPLY_OPTION_HELP),
2169 thread_apply_opts);
2171 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2172 thread_apply_help.c_str (),
2173 &thread_apply_list, 1,
2174 &thread_cmd_list);
2175 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
2177 const auto thread_apply_all_opts
2178 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2180 static std::string thread_apply_all_help = gdb::option::build_help (_("\
2181 Apply a command to all threads.\n\
2183 Usage: thread apply all [OPTION]... COMMAND\n"
2184 THREAD_APPLY_OPTION_HELP),
2185 thread_apply_all_opts);
2187 c = add_cmd ("all", class_run, thread_apply_all_command,
2188 thread_apply_all_help.c_str (),
2189 &thread_apply_list);
2190 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2192 c = add_com ("taas", class_run, taas_command, _("\
2193 Apply a command to all threads (ignoring errors and empty output).\n\
2194 Usage: taas [OPTION]... COMMAND\n\
2195 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2196 See \"help thread apply all\" for available options."));
2197 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2199 c = add_com ("tfaas", class_run, tfaas_command, _("\
2200 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2201 Usage: tfaas [OPTION]... COMMAND\n\
2202 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2203 See \"help frame apply all\" for available options."));
2204 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
2206 add_cmd ("name", class_run, thread_name_command,
2207 _("Set the current thread's name.\n\
2208 Usage: thread name [NAME]\n\
2209 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2211 add_cmd ("find", class_run, thread_find_command, _("\
2212 Find threads that match a regular expression.\n\
2213 Usage: thread find REGEXP\n\
2214 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2215 &thread_cmd_list);
2217 add_setshow_boolean_cmd ("thread-events", no_class,
2218 &print_thread_events, _("\
2219 Set printing of thread events (such as thread start and exit)."), _("\
2220 Show printing of thread events (such as thread start and exit)."), NULL,
2221 NULL,
2222 show_print_thread_events,
2223 &setprintlist, &showprintlist);
2225 add_setshow_boolean_cmd ("threads", class_maintenance, &debug_threads, _("\
2226 Set thread debugging."), _("\
2227 Show thread debugging."), _("\
2228 When on messages about thread creation and deletion are printed."),
2229 nullptr,
2230 show_debug_threads,
2231 &setdebuglist, &showdebuglist);
2233 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2234 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);