Automatic date update in version.in
[binutils-gdb.git] / gdb / thread.c
blob85bdbaa6cd8b84bacac1c78389ceb2acf372467a
1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2023 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 "language.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "gdbsupport/environ.h"
28 #include "value.h"
29 #include "target.h"
30 #include "gdbthread.h"
31 #include "command.h"
32 #include "gdbcmd.h"
33 #include "regcache.h"
34 #include "btrace.h"
36 #include <ctype.h>
37 #include <sys/types.h>
38 #include <signal.h>
39 #include "ui-out.h"
40 #include "observable.h"
41 #include "annotate.h"
42 #include "cli/cli-decode.h"
43 #include "cli/cli-option.h"
44 #include "gdbsupport/gdb_regex.h"
45 #include "cli/cli-utils.h"
46 #include "thread-fsm.h"
47 #include "tid-parse.h"
48 #include <algorithm>
49 #include <optional>
50 #include "inline-frame.h"
51 #include "stack.h"
52 #include "interps.h"
54 /* See gdbthread.h. */
56 bool debug_threads = false;
58 /* Implement 'show debug threads'. */
60 static void
61 show_debug_threads (struct ui_file *file, int from_tty,
62 struct cmd_list_element *c, const char *value)
64 gdb_printf (file, _("Thread debugging is \"%s\".\n"), value);
67 /* Definition of struct thread_info exported to gdbthread.h. */
69 /* Prototypes for local functions. */
71 static int highest_thread_num;
73 /* The current/selected thread. */
74 static thread_info *current_thread_;
76 /* Returns true if THR is the current thread. */
78 static bool
79 is_current_thread (const thread_info *thr)
81 return thr == current_thread_;
84 struct thread_info*
85 inferior_thread (void)
87 gdb_assert (current_thread_ != nullptr);
88 return current_thread_;
91 /* Delete the breakpoint pointed at by BP_P, if there's one. */
93 static void
94 delete_thread_breakpoint (struct breakpoint **bp_p)
96 if (*bp_p != NULL)
98 delete_breakpoint (*bp_p);
99 *bp_p = NULL;
103 void
104 delete_step_resume_breakpoint (struct thread_info *tp)
106 if (tp != NULL)
107 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
110 void
111 delete_exception_resume_breakpoint (struct thread_info *tp)
113 if (tp != NULL)
114 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
117 /* See gdbthread.h. */
119 void
120 delete_single_step_breakpoints (struct thread_info *tp)
122 if (tp != NULL)
123 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
126 /* Delete the breakpoint pointed at by BP_P at the next stop, if
127 there's one. */
129 static void
130 delete_at_next_stop (struct breakpoint **bp)
132 if (*bp != NULL)
134 (*bp)->disposition = disp_del_at_next_stop;
135 *bp = NULL;
139 /* See gdbthread.h. */
142 thread_has_single_step_breakpoints_set (struct thread_info *tp)
144 return tp->control.single_step_breakpoints != NULL;
147 /* See gdbthread.h. */
150 thread_has_single_step_breakpoint_here (struct thread_info *tp,
151 const address_space *aspace,
152 CORE_ADDR addr)
154 struct breakpoint *ss_bps = tp->control.single_step_breakpoints;
156 return (ss_bps != NULL
157 && breakpoint_has_location_inserted_here (ss_bps, aspace, addr));
160 /* See gdbthread.h. */
162 void
163 thread_cancel_execution_command (struct thread_info *thr)
165 if (thr->thread_fsm () != nullptr)
167 std::unique_ptr<thread_fsm> fsm = thr->release_thread_fsm ();
168 fsm->clean_up (thr);
172 static void
173 clear_thread_inferior_resources (struct thread_info *tp)
175 /* NOTE: this will take care of any left-over step_resume breakpoints,
176 but not any user-specified thread-specific breakpoints. We can not
177 delete the breakpoint straight-off, because the inferior might not
178 be stopped at the moment. */
179 delete_at_next_stop (&tp->control.step_resume_breakpoint);
180 delete_at_next_stop (&tp->control.exception_resume_breakpoint);
181 delete_at_next_stop (&tp->control.single_step_breakpoints);
183 delete_longjmp_breakpoint_at_next_stop (tp->global_num);
185 bpstat_clear (&tp->control.stop_bpstat);
187 btrace_teardown (tp);
189 thread_cancel_execution_command (tp);
191 clear_inline_frame_state (tp);
194 /* Notify interpreters and observers that thread T has exited. */
196 static void
197 notify_thread_exited (thread_info *t, std::optional<ULONGEST> exit_code,
198 int silent)
200 if (!silent && print_thread_events)
202 if (exit_code.has_value ())
203 gdb_printf (_("[%s exited with code %s]\n"),
204 target_pid_to_str (t->ptid).c_str (),
205 pulongest (*exit_code));
206 else
207 gdb_printf (_("[%s exited]\n"),
208 target_pid_to_str (t->ptid).c_str ());
211 interps_notify_thread_exited (t, exit_code, silent);
212 gdb::observers::thread_exit.notify (t, exit_code, silent);
215 /* See gdbthread.h. */
217 void
218 set_thread_exited (thread_info *tp, std::optional<ULONGEST> exit_code,
219 bool silent)
221 /* Dead threads don't need to step-over. Remove from chain. */
222 if (thread_is_in_step_over_chain (tp))
223 global_thread_step_over_chain_remove (tp);
225 if (tp->state != THREAD_EXITED)
227 process_stratum_target *proc_target = tp->inf->process_target ();
229 /* Some targets unpush themselves from the inferior's target stack before
230 clearing the inferior's thread list (which marks all threads as exited,
231 and therefore leads to this function). In this case, the inferior's
232 process target will be nullptr when we arrive here.
234 See also the comment in inferior::unpush_target. */
235 if (proc_target != nullptr)
236 proc_target->maybe_remove_resumed_with_pending_wait_status (tp);
238 notify_thread_exited (tp, exit_code, silent);
240 /* Tag it as exited. */
241 tp->state = THREAD_EXITED;
243 /* Clear breakpoints, etc. associated with this thread. */
244 clear_thread_inferior_resources (tp);
246 /* Remove from the ptid_t map. We don't want for
247 inferior::find_thread to find exited threads. Also, the target
248 may reuse the ptid for a new thread, and there can only be
249 one value per key; adding a new thread with the same ptid_t
250 would overwrite the exited thread's ptid entry. */
251 size_t nr_deleted = tp->inf->ptid_thread_map.erase (tp->ptid);
252 gdb_assert (nr_deleted == 1);
256 void
257 init_thread_list (void)
259 highest_thread_num = 0;
261 for (inferior *inf : all_inferiors ())
262 inf->clear_thread_list ();
265 /* Allocate a new thread of inferior INF with target id PTID and add
266 it to the thread list. */
268 static struct thread_info *
269 new_thread (struct inferior *inf, ptid_t ptid)
271 thread_info *tp = new thread_info (inf, ptid);
273 threads_debug_printf ("creating a new thread object, inferior %d, ptid %s",
274 inf->num, ptid.to_string ().c_str ());
276 inf->thread_list.push_back (*tp);
278 /* A thread with this ptid should not exist in the map yet. */
279 gdb_assert (inf->ptid_thread_map.find (ptid) == inf->ptid_thread_map.end ());
281 inf->ptid_thread_map[ptid] = tp;
283 return tp;
286 /* Notify interpreters and observers that thread T has been created. */
288 static void
289 notify_new_thread (thread_info *t)
291 interps_notify_new_thread (t);
292 gdb::observers::new_thread.notify (t);
295 struct thread_info *
296 add_thread_silent (process_stratum_target *targ, ptid_t ptid)
298 gdb_assert (targ != nullptr);
300 inferior *inf = find_inferior_ptid (targ, ptid);
302 threads_debug_printf ("add thread to inferior %d, ptid %s, target %s",
303 inf->num, ptid.to_string ().c_str (),
304 targ->shortname ());
306 /* We may have an old thread with the same id in the thread list.
307 If we do, it must be dead, otherwise we wouldn't be adding a new
308 thread with the same id. The OS is reusing this id --- delete
309 the old thread, and create a new one. */
310 thread_info *tp = inf->find_thread (ptid);
311 if (tp != nullptr)
312 delete_thread (tp);
314 tp = new_thread (inf, ptid);
315 notify_new_thread (tp);
317 return tp;
320 struct thread_info *
321 add_thread_with_info (process_stratum_target *targ, ptid_t ptid,
322 private_thread_info_up priv)
324 thread_info *result = add_thread_silent (targ, ptid);
326 result->priv = std::move (priv);
328 if (print_thread_events)
329 gdb_printf (_("[New %s]\n"), target_pid_to_str (ptid).c_str ());
331 annotate_new_thread ();
332 return result;
335 struct thread_info *
336 add_thread (process_stratum_target *targ, ptid_t ptid)
338 return add_thread_with_info (targ, ptid, NULL);
341 private_thread_info::~private_thread_info () = default;
343 thread_info::thread_info (struct inferior *inf_, ptid_t ptid_)
344 : ptid (ptid_), inf (inf_)
346 gdb_assert (inf_ != NULL);
348 this->global_num = ++highest_thread_num;
349 this->per_inf_num = ++inf_->highest_thread_num;
351 /* Nothing to follow yet. */
352 this->pending_follow.set_spurious ();
355 /* See gdbthread.h. */
357 thread_info::~thread_info ()
359 threads_debug_printf ("thread %s", this->ptid.to_string ().c_str ());
362 /* See gdbthread.h. */
364 bool
365 thread_info::deletable () const
367 /* If this is the current thread, or there's code out there that
368 relies on it existing (refcount > 0) we can't delete yet. */
369 return refcount () == 0 && !is_current_thread (this);
372 /* See gdbthread.h. */
374 void
375 thread_info::set_executing (bool executing)
377 m_executing = executing;
378 if (executing)
379 this->clear_stop_pc ();
382 /* See gdbthread.h. */
384 void
385 thread_info::set_resumed (bool resumed)
387 if (resumed == m_resumed)
388 return;
390 process_stratum_target *proc_target = this->inf->process_target ();
392 /* If we transition from resumed to not resumed, we might need to remove
393 the thread from the resumed threads with pending statuses list. */
394 if (!resumed)
395 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
397 m_resumed = resumed;
399 /* If we transition from not resumed to resumed, we might need to add
400 the thread to the resumed threads with pending statuses list. */
401 if (resumed)
402 proc_target->maybe_add_resumed_with_pending_wait_status (this);
405 /* See gdbthread.h. */
407 void
408 thread_info::set_pending_waitstatus (const target_waitstatus &ws)
410 gdb_assert (!this->has_pending_waitstatus ());
412 m_suspend.waitstatus = ws;
413 m_suspend.waitstatus_pending_p = 1;
415 process_stratum_target *proc_target = this->inf->process_target ();
416 proc_target->maybe_add_resumed_with_pending_wait_status (this);
419 /* See gdbthread.h. */
421 void
422 thread_info::clear_pending_waitstatus ()
424 gdb_assert (this->has_pending_waitstatus ());
426 process_stratum_target *proc_target = this->inf->process_target ();
427 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
429 m_suspend.waitstatus_pending_p = 0;
432 /* See gdbthread.h. */
434 void
435 thread_info::set_thread_options (gdb_thread_options thread_options)
437 gdb_assert (this->state != THREAD_EXITED);
438 gdb_assert (!this->executing ());
440 if (m_thread_options == thread_options)
441 return;
443 m_thread_options = thread_options;
445 infrun_debug_printf ("[options for %s are now %s]",
446 this->ptid.to_string ().c_str (),
447 to_string (thread_options).c_str ());
450 /* See gdbthread.h. */
453 thread_is_in_step_over_chain (struct thread_info *tp)
455 return tp->step_over_list_node.is_linked ();
458 /* See gdbthread.h. */
461 thread_step_over_chain_length (const thread_step_over_list &l)
463 int num = 0;
465 for (const thread_info &thread ATTRIBUTE_UNUSED : l)
466 ++num;
468 return num;
471 /* See gdbthread.h. */
473 void
474 global_thread_step_over_chain_enqueue (struct thread_info *tp)
476 infrun_debug_printf ("enqueueing thread %s in global step over chain",
477 tp->ptid.to_string ().c_str ());
479 gdb_assert (!thread_is_in_step_over_chain (tp));
480 global_thread_step_over_list.push_back (*tp);
483 /* See gdbthread.h. */
485 void
486 global_thread_step_over_chain_enqueue_chain (thread_step_over_list &&list)
488 global_thread_step_over_list.splice (std::move (list));
491 /* See gdbthread.h. */
493 void
494 global_thread_step_over_chain_remove (struct thread_info *tp)
496 infrun_debug_printf ("removing thread %s from global step over chain",
497 tp->ptid.to_string ().c_str ());
499 gdb_assert (thread_is_in_step_over_chain (tp));
500 auto it = global_thread_step_over_list.iterator_to (*tp);
501 global_thread_step_over_list.erase (it);
504 /* Helper for the different delete_thread variants. */
506 static void
507 delete_thread_1 (thread_info *thr, std::optional<ULONGEST> exit_code,
508 bool silent)
510 gdb_assert (thr != nullptr);
512 threads_debug_printf ("deleting thread %s, exit_code = %s, silent = %d",
513 thr->ptid.to_string ().c_str (),
514 (exit_code.has_value ()
515 ? pulongest (*exit_code)
516 : "<none>"),
517 silent);
519 set_thread_exited (thr, exit_code, silent);
521 if (!thr->deletable ())
523 /* Will be really deleted some other time. */
524 return;
527 auto it = thr->inf->thread_list.iterator_to (*thr);
528 thr->inf->thread_list.erase (it);
530 delete thr;
533 /* See gdbthread.h. */
535 void
536 delete_thread_with_exit_code (thread_info *thread, ULONGEST exit_code,
537 bool silent)
539 delete_thread_1 (thread, exit_code, silent);
542 /* See gdbthread.h. */
544 void
545 delete_thread (thread_info *thread)
547 delete_thread_1 (thread, {}, false /* not silent */);
550 void
551 delete_thread_silent (thread_info *thread)
553 delete_thread_1 (thread, {}, true /* not silent */);
556 struct thread_info *
557 find_thread_global_id (int global_id)
559 for (thread_info *tp : all_threads ())
560 if (tp->global_num == global_id)
561 return tp;
563 return NULL;
566 static struct thread_info *
567 find_thread_id (struct inferior *inf, int thr_num)
569 for (thread_info *tp : inf->threads ())
570 if (tp->per_inf_num == thr_num)
571 return tp;
573 return NULL;
576 /* See gdbthread.h. */
578 struct thread_info *
579 find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
580 struct inferior *inf)
582 return target_thread_handle_to_thread_info (handle.data (),
583 handle.size (),
584 inf);
588 * Thread iterator function.
590 * Calls a callback function once for each thread, so long as
591 * the callback function returns false. If the callback function
592 * returns true, the iteration will end and the current thread
593 * will be returned. This can be useful for implementing a
594 * search for a thread with arbitrary attributes, or for applying
595 * some operation to every thread.
597 * FIXME: some of the existing functionality, such as
598 * "Thread apply all", might be rewritten using this functionality.
601 struct thread_info *
602 iterate_over_threads (int (*callback) (struct thread_info *, void *),
603 void *data)
605 for (thread_info *tp : all_threads_safe ())
606 if ((*callback) (tp, data))
607 return tp;
609 return NULL;
612 /* See gdbthread.h. */
614 bool
615 any_thread_p ()
617 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
618 return true;
619 return false;
623 thread_count (process_stratum_target *proc_target)
625 auto rng = all_threads (proc_target);
626 return std::distance (rng.begin (), rng.end ());
629 /* Return the number of non-exited threads in the thread list. */
631 static int
632 live_threads_count (void)
634 auto rng = all_non_exited_threads ();
635 return std::distance (rng.begin (), rng.end ());
639 valid_global_thread_id (int global_id)
641 for (thread_info *tp : all_threads ())
642 if (tp->global_num == global_id)
643 return 1;
645 return 0;
648 bool
649 in_thread_list (process_stratum_target *targ, ptid_t ptid)
651 return targ->find_thread (ptid) != nullptr;
654 /* Finds the first thread of the inferior. */
656 thread_info *
657 first_thread_of_inferior (inferior *inf)
659 if (inf->thread_list.empty ())
660 return nullptr;
662 return &inf->thread_list.front ();
665 thread_info *
666 any_thread_of_inferior (inferior *inf)
668 gdb_assert (inf->pid != 0);
670 /* Prefer the current thread, if there's one. */
671 if (inf == current_inferior () && inferior_ptid != null_ptid)
672 return inferior_thread ();
674 for (thread_info *tp : inf->non_exited_threads ())
675 return tp;
677 return NULL;
680 thread_info *
681 any_live_thread_of_inferior (inferior *inf)
683 struct thread_info *curr_tp = NULL;
684 struct thread_info *tp_executing = NULL;
686 gdb_assert (inf != NULL && inf->pid != 0);
688 /* Prefer the current thread if it's not executing. */
689 if (inferior_ptid != null_ptid && current_inferior () == inf)
691 /* If the current thread is dead, forget it. If it's not
692 executing, use it. Otherwise, still choose it (below), but
693 only if no other non-executing thread is found. */
694 curr_tp = inferior_thread ();
695 if (curr_tp->state == THREAD_EXITED)
696 curr_tp = NULL;
697 else if (!curr_tp->executing ())
698 return curr_tp;
701 for (thread_info *tp : inf->non_exited_threads ())
703 if (!tp->executing ())
704 return tp;
706 tp_executing = tp;
709 /* If both the current thread and all live threads are executing,
710 prefer the current thread. */
711 if (curr_tp != NULL)
712 return curr_tp;
714 /* Otherwise, just return an executing thread, if any. */
715 return tp_executing;
718 /* Return true if TP is an active thread. */
719 static bool
720 thread_alive (thread_info *tp)
722 if (tp->state == THREAD_EXITED)
723 return false;
725 /* Ensure we're looking at the right target stack. */
726 gdb_assert (tp->inf == current_inferior ());
728 return target_thread_alive (tp->ptid);
731 /* See gdbthreads.h. */
733 bool
734 switch_to_thread_if_alive (thread_info *thr)
736 scoped_restore_current_thread restore_thread;
738 /* Switch inferior first, so that we're looking at the right target
739 stack. */
740 switch_to_inferior_no_thread (thr->inf);
742 if (thread_alive (thr))
744 switch_to_thread (thr);
745 restore_thread.dont_restore ();
746 return true;
749 return false;
752 /* See gdbthreads.h. */
754 void
755 prune_threads (void)
757 scoped_restore_current_thread restore_thread;
759 for (thread_info *tp : all_threads_safe ())
761 switch_to_inferior_no_thread (tp->inf);
763 if (!thread_alive (tp))
764 delete_thread (tp);
768 /* See gdbthreads.h. */
770 void
771 delete_exited_threads (void)
773 for (thread_info *tp : all_threads_safe ())
774 if (tp->state == THREAD_EXITED)
775 delete_thread (tp);
778 /* Return true value if stack temporaries are enabled for the thread
779 TP. */
781 bool
782 thread_stack_temporaries_enabled_p (thread_info *tp)
784 if (tp == NULL)
785 return false;
786 else
787 return tp->stack_temporaries_enabled;
790 /* Push V on to the stack temporaries of the thread with id PTID. */
792 void
793 push_thread_stack_temporary (thread_info *tp, struct value *v)
795 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
796 tp->stack_temporaries.push_back (v);
799 /* Return true if VAL is among the stack temporaries of the thread
800 TP. Return false otherwise. */
802 bool
803 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
805 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
806 for (value *v : tp->stack_temporaries)
807 if (v == val)
808 return true;
810 return false;
813 /* Return the last of the stack temporaries for thread with id PTID.
814 Return NULL if there are no stack temporaries for the thread. */
816 value *
817 get_last_thread_stack_temporary (thread_info *tp)
819 struct value *lastval = NULL;
821 gdb_assert (tp != NULL);
822 if (!tp->stack_temporaries.empty ())
823 lastval = tp->stack_temporaries.back ();
825 return lastval;
828 void
829 thread_change_ptid (process_stratum_target *targ,
830 ptid_t old_ptid, ptid_t new_ptid)
832 struct inferior *inf;
833 struct thread_info *tp;
835 /* It can happen that what we knew as the target inferior id
836 changes. E.g, target remote may only discover the remote process
837 pid after adding the inferior to GDB's list. */
838 inf = find_inferior_ptid (targ, old_ptid);
839 inf->pid = new_ptid.pid ();
841 tp = inf->find_thread (old_ptid);
842 gdb_assert (tp != nullptr);
844 int num_erased = inf->ptid_thread_map.erase (old_ptid);
845 gdb_assert (num_erased == 1);
847 tp->ptid = new_ptid;
848 inf->ptid_thread_map[new_ptid] = tp;
850 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
853 /* See gdbthread.h. */
855 void
856 set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
858 for (thread_info *tp : all_non_exited_threads (targ, ptid))
859 tp->set_resumed (resumed);
862 /* Helper for set_running, that marks one thread either running or
863 stopped. */
865 static bool
866 set_running_thread (struct thread_info *tp, bool running)
868 bool started = false;
870 if (running && tp->state == THREAD_STOPPED)
871 started = true;
872 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
874 threads_debug_printf ("thread: %s, running? %d%s",
875 tp->ptid.to_string ().c_str (), running,
876 (started ? " (started)" : ""));
878 if (!running)
880 /* If the thread is now marked stopped, remove it from
881 the step-over queue, so that we don't try to resume
882 it until the user wants it to. */
883 if (thread_is_in_step_over_chain (tp))
884 global_thread_step_over_chain_remove (tp);
887 return started;
890 /* Notify interpreters and observers that the target was resumed. */
892 static void
893 notify_target_resumed (ptid_t ptid)
895 interps_notify_target_resumed (ptid);
896 gdb::observers::target_resumed.notify (ptid);
898 /* We are about to resume the inferior. Close all cached BFDs so that
899 when the inferior next stops, and GDB regains control, we will spot
900 any on-disk changes to the BFDs we are using. */
901 bfd_cache_close_all ();
904 /* See gdbthread.h. */
906 void
907 thread_info::set_running (bool running)
909 if (set_running_thread (this, running))
910 notify_target_resumed (this->ptid);
913 void
914 set_running (process_stratum_target *targ, ptid_t ptid, bool running)
916 /* We try not to notify the observer if no thread has actually
917 changed the running state -- merely to reduce the number of
918 messages to the MI frontend. A frontend is supposed to handle
919 multiple *running notifications just fine. */
920 bool any_started = false;
922 for (thread_info *tp : all_non_exited_threads (targ, ptid))
923 if (set_running_thread (tp, running))
924 any_started = true;
926 if (any_started)
927 notify_target_resumed (ptid);
930 void
931 set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
933 for (thread_info *tp : all_non_exited_threads (targ, ptid))
934 tp->set_executing (executing);
936 /* It only takes one running thread to spawn more threads. */
937 if (executing)
938 targ->threads_executing = true;
939 /* Only clear the flag if the caller is telling us everything is
940 stopped. */
941 else if (minus_one_ptid == ptid)
942 targ->threads_executing = false;
945 /* See gdbthread.h. */
947 bool
948 threads_are_executing (process_stratum_target *target)
950 return target->threads_executing;
953 void
954 set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
956 for (thread_info *tp : all_non_exited_threads (targ, ptid))
957 tp->stop_requested = stop;
959 /* Call the stop requested observer so other components of GDB can
960 react to this request. */
961 if (stop)
962 gdb::observers::thread_stop_requested.notify (ptid);
965 void
966 finish_thread_state (process_stratum_target *targ, ptid_t ptid)
968 bool any_started = false;
970 for (thread_info *tp : all_non_exited_threads (targ, ptid))
971 if (set_running_thread (tp, tp->executing ()))
972 any_started = true;
974 if (any_started)
975 notify_target_resumed (ptid);
978 /* See gdbthread.h. */
980 void
981 validate_registers_access (void)
983 /* No selected thread, no registers. */
984 if (inferior_ptid == null_ptid)
985 error (_("No thread selected."));
987 thread_info *tp = inferior_thread ();
989 /* Don't try to read from a dead thread. */
990 if (tp->state == THREAD_EXITED)
991 error (_("The current thread has terminated"));
993 /* ... or from a spinning thread. FIXME: This isn't actually fully
994 correct. It'll allow an user-requested access (e.g., "print $pc"
995 at the prompt) when a thread is not executing for some internal
996 reason, but is marked running from the user's perspective. E.g.,
997 the thread is waiting for its turn in the step-over queue. */
998 if (tp->executing ())
999 error (_("Selected thread is running."));
1002 /* See gdbthread.h. */
1004 bool
1005 can_access_registers_thread (thread_info *thread)
1007 /* No thread, no registers. */
1008 if (thread == NULL)
1009 return false;
1011 /* Don't try to read from a dead thread. */
1012 if (thread->state == THREAD_EXITED)
1013 return false;
1015 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
1016 if (thread->executing ())
1017 return false;
1019 return true;
1022 bool
1023 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
1025 return (pc >= thread->control.step_range_start
1026 && pc < thread->control.step_range_end);
1029 /* Helper for print_thread_info. Returns true if THR should be
1030 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
1031 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
1032 is true if REQUESTED_THREADS is list of global IDs, false if a list
1033 of per-inferior thread ids. If PID is not -1, only print THR if it
1034 is a thread from the process PID. Otherwise, threads from all
1035 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
1036 and PID is not -1, then the thread is printed if it belongs to the
1037 specified process. Otherwise, an error is raised. */
1039 static bool
1040 should_print_thread (const char *requested_threads, int default_inf_num,
1041 int global_ids, int pid, struct thread_info *thr)
1043 if (requested_threads != NULL && *requested_threads != '\0')
1045 int in_list;
1047 if (global_ids)
1048 in_list = number_is_in_list (requested_threads, thr->global_num);
1049 else
1050 in_list = tid_is_in_list (requested_threads, default_inf_num,
1051 thr->inf->num, thr->per_inf_num);
1052 if (!in_list)
1053 return false;
1056 if (pid != -1 && thr->ptid.pid () != pid)
1058 if (requested_threads != NULL && *requested_threads != '\0')
1059 error (_("Requested thread not found in requested process"));
1060 return false;
1063 if (thr->state == THREAD_EXITED)
1064 return false;
1066 return true;
1069 /* Return the string to display in "info threads"'s "Target Id"
1070 column, for TP. */
1072 static std::string
1073 thread_target_id_str (thread_info *tp)
1075 std::string target_id = target_pid_to_str (tp->ptid);
1076 const char *extra_info = target_extra_thread_info (tp);
1077 const char *name = thread_name (tp);
1079 if (extra_info != nullptr && name != nullptr)
1080 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1081 extra_info);
1082 else if (extra_info != nullptr)
1083 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1084 else if (name != nullptr)
1085 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1086 else
1087 return target_id;
1090 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1091 whether REQUESTED_THREADS is a list of global or per-inferior
1092 thread ids. */
1094 static void
1095 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1096 int global_ids, int pid,
1097 int show_global_ids)
1099 int default_inf_num = current_inferior ()->num;
1101 update_thread_list ();
1103 /* Whether we saw any thread. */
1104 bool any_thread = false;
1105 /* Whether the current thread is exited. */
1106 bool current_exited = false;
1108 thread_info *current_thread = (inferior_ptid != null_ptid
1109 ? inferior_thread () : NULL);
1112 /* For backward compatibility, we make a list for MI. A table is
1113 preferable for the CLI, though, because it shows table
1114 headers. */
1115 std::optional<ui_out_emit_list> list_emitter;
1116 std::optional<ui_out_emit_table> table_emitter;
1118 /* We'll be switching threads temporarily below. */
1119 scoped_restore_current_thread restore_thread;
1121 if (uiout->is_mi_like_p ())
1122 list_emitter.emplace (uiout, "threads");
1123 else
1125 int n_threads = 0;
1126 /* The width of the "Target Id" column. Grown below to
1127 accommodate the largest entry. */
1128 size_t target_id_col_width = 17;
1130 for (thread_info *tp : all_threads ())
1132 /* In case REQUESTED_THREADS contains $_thread. */
1133 if (current_thread != nullptr)
1134 switch_to_thread (current_thread);
1136 if (!should_print_thread (requested_threads, default_inf_num,
1137 global_ids, pid, tp))
1138 continue;
1140 /* Switch inferiors so we're looking at the right
1141 target stack. */
1142 switch_to_inferior_no_thread (tp->inf);
1144 target_id_col_width
1145 = std::max (target_id_col_width,
1146 thread_target_id_str (tp).size ());
1148 ++n_threads;
1151 if (n_threads == 0)
1153 if (requested_threads == NULL || *requested_threads == '\0')
1154 uiout->message (_("No threads.\n"));
1155 else
1156 uiout->message (_("No threads match '%s'.\n"),
1157 requested_threads);
1158 return;
1161 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1162 n_threads, "threads");
1164 uiout->table_header (1, ui_left, "current", "");
1165 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1166 if (show_global_ids)
1167 uiout->table_header (4, ui_left, "id", "GId");
1168 uiout->table_header (target_id_col_width, ui_left,
1169 "target-id", "Target Id");
1170 uiout->table_header (1, ui_left, "frame", "Frame");
1171 uiout->table_body ();
1174 for (inferior *inf : all_inferiors ())
1175 for (thread_info *tp : inf->threads ())
1177 int core;
1179 any_thread = true;
1180 if (tp == current_thread && tp->state == THREAD_EXITED)
1181 current_exited = true;
1183 /* In case REQUESTED_THREADS contains $_thread. */
1184 if (current_thread != nullptr)
1185 switch_to_thread (current_thread);
1187 if (!should_print_thread (requested_threads, default_inf_num,
1188 global_ids, pid, tp))
1189 continue;
1191 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1193 if (!uiout->is_mi_like_p ())
1195 if (tp == current_thread)
1196 uiout->field_string ("current", "*");
1197 else
1198 uiout->field_skip ("current");
1200 uiout->field_string ("id-in-tg", print_thread_id (tp));
1203 if (show_global_ids || uiout->is_mi_like_p ())
1204 uiout->field_signed ("id", tp->global_num);
1206 /* Switch to the thread (and inferior / target). */
1207 switch_to_thread (tp);
1209 /* For the CLI, we stuff everything into the target-id field.
1210 This is a gross hack to make the output come out looking
1211 correct. The underlying problem here is that ui-out has no
1212 way to specify that a field's space allocation should be
1213 shared by several fields. For MI, we do the right thing
1214 instead. */
1216 if (uiout->is_mi_like_p ())
1218 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1220 const char *extra_info = target_extra_thread_info (tp);
1221 if (extra_info != nullptr)
1222 uiout->field_string ("details", extra_info);
1224 const char *name = thread_name (tp);
1225 if (name != NULL)
1226 uiout->field_string ("name", name);
1228 else
1230 uiout->field_string ("target-id", thread_target_id_str (tp));
1233 if (tp->state == THREAD_RUNNING)
1234 uiout->text ("(running)\n");
1235 else
1237 /* The switch above put us at the top of the stack (leaf
1238 frame). */
1239 print_stack_frame (get_selected_frame (NULL),
1240 /* For MI output, print frame level. */
1241 uiout->is_mi_like_p (),
1242 LOCATION, 0);
1245 if (uiout->is_mi_like_p ())
1247 const char *state = "stopped";
1249 if (tp->state == THREAD_RUNNING)
1250 state = "running";
1251 uiout->field_string ("state", state);
1254 core = target_core_of_thread (tp->ptid);
1255 if (uiout->is_mi_like_p () && core != -1)
1256 uiout->field_signed ("core", core);
1259 /* This end scope restores the current thread and the frame
1260 selected before the "info threads" command, and it finishes the
1261 ui-out list or table. */
1264 if (pid == -1 && requested_threads == NULL)
1266 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1267 uiout->field_signed ("current-thread-id", current_thread->global_num);
1269 if (inferior_ptid != null_ptid && current_exited)
1270 uiout->message ("\n\
1271 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1272 print_thread_id (inferior_thread ()));
1273 else if (any_thread && inferior_ptid == null_ptid)
1274 uiout->message ("\n\
1275 No selected thread. See `help thread'.\n");
1279 /* See gdbthread.h. */
1281 void
1282 print_thread_info (struct ui_out *uiout, const char *requested_threads,
1283 int pid)
1285 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1288 /* The options for the "info threads" command. */
1290 struct info_threads_opts
1292 /* For "-gid". */
1293 bool show_global_ids = false;
1296 static const gdb::option::option_def info_threads_option_defs[] = {
1298 gdb::option::flag_option_def<info_threads_opts> {
1299 "gid",
1300 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1301 N_("Show global thread IDs."),
1306 /* Create an option_def_group for the "info threads" options, with
1307 IT_OPTS as context. */
1309 static inline gdb::option::option_def_group
1310 make_info_threads_options_def_group (info_threads_opts *it_opts)
1312 return {{info_threads_option_defs}, it_opts};
1315 /* Implementation of the "info threads" command.
1317 Note: this has the drawback that it _really_ switches
1318 threads, which frees the frame cache. A no-side
1319 effects info-threads command would be nicer. */
1321 static void
1322 info_threads_command (const char *arg, int from_tty)
1324 info_threads_opts it_opts;
1326 auto grp = make_info_threads_options_def_group (&it_opts);
1327 gdb::option::process_options
1328 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1330 print_thread_info_1 (current_uiout, arg, 0, -1, it_opts.show_global_ids);
1333 /* Completer for the "info threads" command. */
1335 static void
1336 info_threads_command_completer (struct cmd_list_element *ignore,
1337 completion_tracker &tracker,
1338 const char *text, const char *word_ignored)
1340 const auto grp = make_info_threads_options_def_group (nullptr);
1342 if (gdb::option::complete_options
1343 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1344 return;
1346 /* Convenience to let the user know what the option can accept. */
1347 if (*text == '\0')
1349 gdb::option::complete_on_all_options (tracker, grp);
1350 /* Keep this "ID" in sync with what "help info threads"
1351 says. */
1352 tracker.add_completion (make_unique_xstrdup ("ID"));
1356 /* See gdbthread.h. */
1358 void
1359 switch_to_thread_no_regs (struct thread_info *thread)
1361 gdb_assert (thread != nullptr);
1362 threads_debug_printf ("thread = %s", thread->ptid.to_string ().c_str ());
1364 struct inferior *inf = thread->inf;
1366 set_current_program_space (inf->pspace);
1367 set_current_inferior (inf);
1369 current_thread_ = thread;
1370 inferior_ptid = current_thread_->ptid;
1373 /* See gdbthread.h. */
1375 void
1376 switch_to_no_thread ()
1378 if (current_thread_ == nullptr)
1379 return;
1381 threads_debug_printf ("thread = NONE");
1383 current_thread_ = nullptr;
1384 inferior_ptid = null_ptid;
1385 reinit_frame_cache ();
1388 /* See gdbthread.h. */
1390 void
1391 switch_to_thread (thread_info *thr)
1393 gdb_assert (thr != NULL);
1395 if (is_current_thread (thr))
1396 return;
1398 switch_to_thread_no_regs (thr);
1400 reinit_frame_cache ();
1403 /* See gdbsupport/common-gdbthread.h. */
1405 void
1406 switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
1408 thread_info *thr = proc_target->find_thread (ptid);
1409 switch_to_thread (thr);
1412 /* See frame.h. */
1414 void
1415 scoped_restore_current_thread::restore ()
1417 /* If an entry of thread_info was previously selected, it won't be
1418 deleted because we've increased its refcount. The thread represented
1419 by this thread_info entry may have already exited (due to normal exit,
1420 detach, etc), so the thread_info.state is THREAD_EXITED. */
1421 if (m_thread != NULL
1422 /* If the previously selected thread belonged to a process that has
1423 in the mean time exited (or killed, detached, etc.), then don't revert
1424 back to it, but instead simply drop back to no thread selected. */
1425 && m_inf->pid != 0)
1426 switch_to_thread (m_thread.get ());
1427 else
1428 switch_to_inferior_no_thread (m_inf.get ());
1430 /* The running state of the originally selected thread may have
1431 changed, so we have to recheck it here. */
1432 if (inferior_ptid != null_ptid
1433 && m_was_stopped
1434 && m_thread->state == THREAD_STOPPED
1435 && target_has_registers ()
1436 && target_has_stack ()
1437 && target_has_memory ())
1438 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1440 set_language (m_lang);
1443 scoped_restore_current_thread::~scoped_restore_current_thread ()
1445 if (!m_dont_restore)
1446 restore ();
1449 scoped_restore_current_thread::scoped_restore_current_thread ()
1451 m_inf = inferior_ref::new_reference (current_inferior ());
1453 m_lang = current_language->la_language;
1455 if (inferior_ptid != null_ptid)
1457 m_thread = thread_info_ref::new_reference (inferior_thread ());
1459 m_was_stopped = m_thread->state == THREAD_STOPPED;
1460 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
1464 scoped_restore_current_thread::scoped_restore_current_thread
1465 (scoped_restore_current_thread &&rhs)
1466 : m_dont_restore (std::move (rhs.m_dont_restore)),
1467 m_thread (std::move (rhs.m_thread)),
1468 m_inf (std::move (rhs.m_inf)),
1469 m_selected_frame_id (std::move (rhs.m_selected_frame_id)),
1470 m_selected_frame_level (std::move (rhs.m_selected_frame_level)),
1471 m_was_stopped (std::move (rhs.m_was_stopped)),
1472 m_lang (std::move (rhs.m_lang))
1474 /* Deactivate the rhs. */
1475 rhs.m_dont_restore = true;
1478 /* See gdbthread.h. */
1481 show_thread_that_caused_stop (void)
1483 return highest_thread_num > 1;
1486 /* See gdbthread.h. */
1489 show_inferior_qualified_tids (void)
1491 auto inf = inferior_list.begin ();
1492 if (inf->num != 1)
1493 return true;
1494 ++inf;
1495 return inf != inferior_list.end ();
1498 /* See gdbthread.h. */
1500 const char *
1501 print_thread_id (struct thread_info *thr)
1503 if (show_inferior_qualified_tids ())
1504 return print_full_thread_id (thr);
1506 char *s = get_print_cell ();
1508 gdb_assert (thr != nullptr);
1509 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1510 return s;
1513 /* See gdbthread.h. */
1515 const char *
1516 print_full_thread_id (struct thread_info *thr)
1518 char *s = get_print_cell ();
1520 gdb_assert (thr != nullptr);
1521 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1522 return s;
1525 /* Sort an array of struct thread_info pointers by thread ID (first by
1526 inferior number, and then by per-inferior thread number). Sorts in
1527 ascending order. */
1529 static bool
1530 tp_array_compar_ascending (const thread_info_ref &a, const thread_info_ref &b)
1532 if (a->inf->num != b->inf->num)
1533 return a->inf->num < b->inf->num;
1535 return (a->per_inf_num < b->per_inf_num);
1538 /* Sort an array of struct thread_info pointers by thread ID (first by
1539 inferior number, and then by per-inferior thread number). Sorts in
1540 descending order. */
1542 static bool
1543 tp_array_compar_descending (const thread_info_ref &a, const thread_info_ref &b)
1545 if (a->inf->num != b->inf->num)
1546 return a->inf->num > b->inf->num;
1548 return (a->per_inf_num > b->per_inf_num);
1551 /* See gdbthread.h. */
1553 void
1554 thread_try_catch_cmd (thread_info *thr, std::optional<int> ada_task,
1555 const char *cmd, int from_tty,
1556 const qcs_flags &flags)
1558 gdb_assert (is_current_thread (thr));
1560 /* The thread header is computed before running the command since
1561 the command can change the inferior, which is not permitted
1562 by thread_target_id_str. */
1563 std::string thr_header;
1564 if (ada_task.has_value ())
1565 thr_header = string_printf (_("\nTask ID %d:\n"), *ada_task);
1566 else
1567 thr_header = string_printf (_("\nThread %s (%s):\n"),
1568 print_thread_id (thr),
1569 thread_target_id_str (thr).c_str ());
1573 std::string cmd_result;
1574 execute_command_to_string
1575 (cmd_result, cmd, from_tty, gdb_stdout->term_out ());
1576 if (!flags.silent || cmd_result.length () > 0)
1578 if (!flags.quiet)
1579 gdb_printf ("%s", thr_header.c_str ());
1580 gdb_printf ("%s", cmd_result.c_str ());
1583 catch (const gdb_exception_error &ex)
1585 if (!flags.silent)
1587 if (!flags.quiet)
1588 gdb_printf ("%s", thr_header.c_str ());
1589 if (flags.cont)
1590 gdb_printf ("%s\n", ex.what ());
1591 else
1592 throw;
1597 /* Option definition of "thread apply"'s "-ascending" option. */
1599 static const gdb::option::flag_option_def<> ascending_option_def = {
1600 "ascending",
1601 N_("\
1602 Call COMMAND for all threads in ascending order.\n\
1603 The default is descending order."),
1606 /* The qcs command line flags for the "thread apply" commands. Keep
1607 this in sync with the "frame apply" commands. */
1609 using qcs_flag_option_def
1610 = gdb::option::flag_option_def<qcs_flags>;
1612 static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1613 qcs_flag_option_def {
1614 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1615 N_("Disables printing the thread information."),
1618 qcs_flag_option_def {
1619 "c", [] (qcs_flags *opt) { return &opt->cont; },
1620 N_("Print any error raised by COMMAND and continue."),
1623 qcs_flag_option_def {
1624 "s", [] (qcs_flags *opt) { return &opt->silent; },
1625 N_("Silently ignore any errors or empty output produced by COMMAND."),
1629 /* Create an option_def_group for the "thread apply all" options, with
1630 ASCENDING and FLAGS as context. */
1632 static inline std::array<gdb::option::option_def_group, 2>
1633 make_thread_apply_all_options_def_group (bool *ascending,
1634 qcs_flags *flags)
1636 return {{
1637 { {ascending_option_def.def ()}, ascending},
1638 { {thr_qcs_flags_option_defs}, flags },
1642 /* Create an option_def_group for the "thread apply" options, with
1643 FLAGS as context. */
1645 static inline gdb::option::option_def_group
1646 make_thread_apply_options_def_group (qcs_flags *flags)
1648 return {{thr_qcs_flags_option_defs}, flags};
1651 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1652 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1653 of two numbers separated by a hyphen. Examples:
1655 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1656 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1657 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1659 static void
1660 thread_apply_all_command (const char *cmd, int from_tty)
1662 bool ascending = false;
1663 qcs_flags flags;
1665 auto group = make_thread_apply_all_options_def_group (&ascending,
1666 &flags);
1667 gdb::option::process_options
1668 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1670 validate_flags_qcs ("thread apply all", &flags);
1672 if (cmd == NULL || *cmd == '\000')
1673 error (_("Please specify a command at the end of 'thread apply all'"));
1675 update_thread_list ();
1677 int tc = live_threads_count ();
1678 if (tc != 0)
1680 /* Save a copy of the thread list and increment each thread's
1681 refcount while executing the command in the context of each
1682 thread, in case the command is one that wipes threads. E.g.,
1683 detach, kill, disconnect, etc., or even normally continuing
1684 over an inferior or thread exit. */
1685 std::vector<thread_info_ref> thr_list_cpy;
1686 thr_list_cpy.reserve (tc);
1688 for (thread_info *tp : all_non_exited_threads ())
1689 thr_list_cpy.push_back (thread_info_ref::new_reference (tp));
1690 gdb_assert (thr_list_cpy.size () == tc);
1692 auto *sorter = (ascending
1693 ? tp_array_compar_ascending
1694 : tp_array_compar_descending);
1695 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
1697 scoped_restore_current_thread restore_thread;
1699 for (thread_info_ref &thr : thr_list_cpy)
1700 if (switch_to_thread_if_alive (thr.get ()))
1701 thread_try_catch_cmd (thr.get (), {}, cmd, from_tty, flags);
1705 /* Completer for "thread apply [ID list]". */
1707 static void
1708 thread_apply_command_completer (cmd_list_element *ignore,
1709 completion_tracker &tracker,
1710 const char *text, const char * /*word*/)
1712 /* Don't leave this to complete_options because there's an early
1713 return below. */
1714 tracker.set_use_custom_word_point (true);
1716 tid_range_parser parser;
1717 parser.init (text, current_inferior ()->num);
1721 while (!parser.finished ())
1723 int inf_num, thr_start, thr_end;
1725 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1726 break;
1728 if (parser.in_star_range () || parser.in_thread_range ())
1729 parser.skip_range ();
1732 catch (const gdb_exception_error &ex)
1734 /* get_tid_range throws if it parses a negative number, for
1735 example. But a seemingly negative number may be the start of
1736 an option instead. */
1739 const char *cmd = parser.cur_tok ();
1741 if (cmd == text)
1743 /* No thread ID list yet. */
1744 return;
1747 /* Check if we're past a valid thread ID list already. */
1748 if (parser.finished ()
1749 && cmd > text && !isspace (cmd[-1]))
1750 return;
1752 /* We're past the thread ID list, advance word point. */
1753 tracker.advance_custom_word_point_by (cmd - text);
1754 text = cmd;
1756 const auto group = make_thread_apply_options_def_group (nullptr);
1757 if (gdb::option::complete_options
1758 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1759 return;
1761 complete_nested_command_line (tracker, text);
1764 /* Completer for "thread apply all". */
1766 static void
1767 thread_apply_all_command_completer (cmd_list_element *ignore,
1768 completion_tracker &tracker,
1769 const char *text, const char *word)
1771 const auto group = make_thread_apply_all_options_def_group (nullptr,
1772 nullptr);
1773 if (gdb::option::complete_options
1774 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1775 return;
1777 complete_nested_command_line (tracker, text);
1780 /* Implementation of the "thread apply" command. */
1782 static void
1783 thread_apply_command (const char *tidlist, int from_tty)
1785 qcs_flags flags;
1786 const char *cmd = NULL;
1787 tid_range_parser parser;
1789 if (tidlist == NULL || *tidlist == '\000')
1790 error (_("Please specify a thread ID list"));
1792 parser.init (tidlist, current_inferior ()->num);
1793 while (!parser.finished ())
1795 int inf_num, thr_start, thr_end;
1797 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1798 break;
1801 cmd = parser.cur_tok ();
1803 auto group = make_thread_apply_options_def_group (&flags);
1804 gdb::option::process_options
1805 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1807 validate_flags_qcs ("thread apply", &flags);
1809 if (*cmd == '\0')
1810 error (_("Please specify a command following the thread ID list"));
1812 if (tidlist == cmd || isdigit (cmd[0]))
1813 invalid_thread_id_error (cmd);
1815 scoped_restore_current_thread restore_thread;
1817 parser.init (tidlist, current_inferior ()->num);
1818 while (!parser.finished ())
1820 struct thread_info *tp = NULL;
1821 struct inferior *inf;
1822 int inf_num, thr_num;
1824 parser.get_tid (&inf_num, &thr_num);
1825 inf = find_inferior_id (inf_num);
1826 if (inf != NULL)
1827 tp = find_thread_id (inf, thr_num);
1829 if (parser.in_star_range ())
1831 if (inf == NULL)
1833 warning (_("Unknown inferior %d"), inf_num);
1834 parser.skip_range ();
1835 continue;
1838 /* No use looking for threads past the highest thread number
1839 the inferior ever had. */
1840 if (thr_num >= inf->highest_thread_num)
1841 parser.skip_range ();
1843 /* Be quiet about unknown threads numbers. */
1844 if (tp == NULL)
1845 continue;
1848 if (tp == NULL)
1850 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1851 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1852 else
1853 warning (_("Unknown thread %d"), thr_num);
1854 continue;
1857 if (!switch_to_thread_if_alive (tp))
1859 warning (_("Thread %s has terminated."), print_thread_id (tp));
1860 continue;
1863 thread_try_catch_cmd (tp, {}, cmd, from_tty, flags);
1868 /* Implementation of the "taas" command. */
1870 static void
1871 taas_command (const char *cmd, int from_tty)
1873 if (cmd == NULL || *cmd == '\0')
1874 error (_("Please specify a command to apply on all threads"));
1875 std::string expanded = std::string ("thread apply all -s ") + cmd;
1876 execute_command (expanded.c_str (), from_tty);
1879 /* Implementation of the "tfaas" command. */
1881 static void
1882 tfaas_command (const char *cmd, int from_tty)
1884 if (cmd == NULL || *cmd == '\0')
1885 error (_("Please specify a command to apply on all frames of all threads"));
1886 std::string expanded
1887 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1888 execute_command (expanded.c_str (), from_tty);
1891 /* Switch to the specified thread, or print the current thread. */
1893 void
1894 thread_command (const char *tidstr, int from_tty)
1896 if (tidstr == NULL)
1898 if (inferior_ptid == null_ptid)
1899 error (_("No thread selected"));
1901 if (target_has_stack ())
1903 struct thread_info *tp = inferior_thread ();
1905 if (tp->state == THREAD_EXITED)
1906 gdb_printf (_("[Current thread is %s (%s) (exited)]\n"),
1907 print_thread_id (tp),
1908 target_pid_to_str (inferior_ptid).c_str ());
1909 else
1910 gdb_printf (_("[Current thread is %s (%s)]\n"),
1911 print_thread_id (tp),
1912 target_pid_to_str (inferior_ptid).c_str ());
1914 else
1915 error (_("No stack."));
1917 else
1919 ptid_t previous_ptid = inferior_ptid;
1921 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1923 /* Print if the thread has not changed, otherwise an event will
1924 be sent. */
1925 if (inferior_ptid == previous_ptid)
1927 print_selected_thread_frame (current_uiout,
1928 USER_SELECTED_THREAD
1929 | USER_SELECTED_FRAME);
1931 else
1932 notify_user_selected_context_changed
1933 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1937 /* Implementation of `thread name'. */
1939 static void
1940 thread_name_command (const char *arg, int from_tty)
1942 struct thread_info *info;
1944 if (inferior_ptid == null_ptid)
1945 error (_("No thread selected"));
1947 arg = skip_spaces (arg);
1949 info = inferior_thread ();
1950 info->set_name (arg != nullptr ? make_unique_xstrdup (arg) : nullptr);
1953 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1955 static void
1956 thread_find_command (const char *arg, int from_tty)
1958 const char *tmp;
1959 unsigned long match = 0;
1961 if (arg == NULL || *arg == '\0')
1962 error (_("Command requires an argument."));
1964 tmp = re_comp (arg);
1965 if (tmp != 0)
1966 error (_("Invalid regexp (%s): %s"), tmp, arg);
1968 /* We're going to be switching threads. */
1969 scoped_restore_current_thread restore_thread;
1971 update_thread_list ();
1973 for (thread_info *tp : all_threads ())
1975 switch_to_inferior_no_thread (tp->inf);
1977 if (tp->name () != nullptr && re_exec (tp->name ()))
1979 gdb_printf (_("Thread %s has name '%s'\n"),
1980 print_thread_id (tp), tp->name ());
1981 match++;
1984 tmp = target_thread_name (tp);
1985 if (tmp != NULL && re_exec (tmp))
1987 gdb_printf (_("Thread %s has target name '%s'\n"),
1988 print_thread_id (tp), tmp);
1989 match++;
1992 std::string name = target_pid_to_str (tp->ptid);
1993 if (!name.empty () && re_exec (name.c_str ()))
1995 gdb_printf (_("Thread %s has target id '%s'\n"),
1996 print_thread_id (tp), name.c_str ());
1997 match++;
2000 tmp = target_extra_thread_info (tp);
2001 if (tmp != NULL && re_exec (tmp))
2003 gdb_printf (_("Thread %s has extra info '%s'\n"),
2004 print_thread_id (tp), tmp);
2005 match++;
2008 if (!match)
2009 gdb_printf (_("No threads match '%s'\n"), arg);
2012 /* Print notices when new threads are attached and detached. */
2013 bool print_thread_events = true;
2014 static void
2015 show_print_thread_events (struct ui_file *file, int from_tty,
2016 struct cmd_list_element *c, const char *value)
2018 gdb_printf (file,
2019 _("Printing of thread events is %s.\n"),
2020 value);
2023 /* See gdbthread.h. */
2025 void
2026 thread_select (const char *tidstr, thread_info *tp)
2028 if (!switch_to_thread_if_alive (tp))
2029 error (_("Thread ID %s has terminated."), tidstr);
2031 annotate_thread_changed ();
2033 /* Since the current thread may have changed, see if there is any
2034 exited thread we can now delete. */
2035 delete_exited_threads ();
2038 /* Print thread and frame switch command response. */
2040 void
2041 print_selected_thread_frame (struct ui_out *uiout,
2042 user_selected_what selection)
2044 struct thread_info *tp = inferior_thread ();
2046 if (selection & USER_SELECTED_THREAD)
2048 if (uiout->is_mi_like_p ())
2050 uiout->field_signed ("new-thread-id",
2051 inferior_thread ()->global_num);
2053 else
2055 uiout->text ("[Switching to thread ");
2056 uiout->field_string ("new-thread-id", print_thread_id (tp));
2057 uiout->text (" (");
2058 uiout->text (target_pid_to_str (inferior_ptid));
2059 uiout->text (")]");
2063 if (tp->state == THREAD_RUNNING)
2065 if (selection & USER_SELECTED_THREAD)
2066 uiout->text ("(running)\n");
2068 else if (selection & USER_SELECTED_FRAME)
2070 if (selection & USER_SELECTED_THREAD)
2071 uiout->text ("\n");
2073 if (has_stack_frames ())
2074 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
2075 1, SRC_AND_LOC, 1);
2079 /* Update the 'threads_executing' global based on the threads we know
2080 about right now. This is used by infrun to tell whether we should
2081 pull events out of the current target. */
2083 static void
2084 update_threads_executing (void)
2086 process_stratum_target *targ = current_inferior ()->process_target ();
2088 if (targ == NULL)
2089 return;
2091 targ->threads_executing = false;
2093 for (inferior *inf : all_non_exited_inferiors (targ))
2095 if (!inf->has_execution ())
2096 continue;
2098 /* If the process has no threads, then it must be we have a
2099 process-exit event pending. */
2100 if (inf->thread_list.empty ())
2102 targ->threads_executing = true;
2103 return;
2106 for (thread_info *tp : inf->non_exited_threads ())
2108 if (tp->executing ())
2110 targ->threads_executing = true;
2111 return;
2117 void
2118 update_thread_list (void)
2120 target_update_thread_list ();
2121 update_threads_executing ();
2124 /* See gdbthread.h. */
2126 const char *
2127 thread_name (thread_info *thread)
2129 /* Use the manually set name if there is one. */
2130 const char *name = thread->name ();
2131 if (name != nullptr)
2132 return name;
2134 /* Otherwise, ask the target. Ensure we query the right target stack. */
2135 scoped_restore_current_thread restore_thread;
2136 if (thread->inf != current_inferior ())
2137 switch_to_inferior_no_thread (thread->inf);
2139 return target_thread_name (thread);
2142 /* See gdbthread.h. */
2144 const char *
2145 thread_state_string (enum thread_state state)
2147 switch (state)
2149 case THREAD_STOPPED:
2150 return "STOPPED";
2152 case THREAD_RUNNING:
2153 return "RUNNING";
2155 case THREAD_EXITED:
2156 return "EXITED";
2159 gdb_assert_not_reached ("unknown thread state");
2162 /* Return a new value for the selected thread's id. Return a value of
2163 0 if no thread is selected. If GLOBAL is true, return the thread's
2164 global number. Otherwise return the per-inferior number. */
2166 static struct value *
2167 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2169 int int_val;
2171 if (inferior_ptid == null_ptid)
2172 int_val = 0;
2173 else
2175 thread_info *tp = inferior_thread ();
2176 if (global)
2177 int_val = tp->global_num;
2178 else
2179 int_val = tp->per_inf_num;
2182 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2185 /* Return a new value for the selected thread's per-inferior thread
2186 number. Return a value of 0 if no thread is selected, or no
2187 threads exist. */
2189 static struct value *
2190 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2191 struct internalvar *var,
2192 void *ignore)
2194 return thread_num_make_value_helper (gdbarch, 0);
2197 /* Return a new value for the selected thread's global id. Return a
2198 value of 0 if no thread is selected, or no threads exist. */
2200 static struct value *
2201 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2202 void *ignore)
2204 return thread_num_make_value_helper (gdbarch, 1);
2207 /* Return a new value for the number of non-exited threads in the current
2208 inferior. If there are no threads in the current inferior return a
2209 value of 0. */
2211 static struct value *
2212 inferior_thread_count_make_value (struct gdbarch *gdbarch,
2213 struct internalvar *var, void *ignore)
2215 int int_val = 0;
2217 update_thread_list ();
2219 if (inferior_ptid != null_ptid)
2220 int_val = current_inferior ()->non_exited_threads ().size ();
2222 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2225 /* Commands with a prefix of `thread'. */
2226 struct cmd_list_element *thread_cmd_list = NULL;
2228 /* Implementation of `thread' variable. */
2230 static const struct internalvar_funcs thread_funcs =
2232 thread_id_per_inf_num_make_value,
2233 NULL,
2236 /* Implementation of `gthread' variable. */
2238 static const struct internalvar_funcs gthread_funcs =
2240 global_thread_id_make_value,
2241 NULL,
2244 /* Implementation of `_inferior_thread_count` convenience variable. */
2246 static const struct internalvar_funcs inferior_thread_count_funcs =
2248 inferior_thread_count_make_value,
2249 NULL,
2252 void _initialize_thread ();
2253 void
2254 _initialize_thread ()
2256 static struct cmd_list_element *thread_apply_list = NULL;
2257 cmd_list_element *c;
2259 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2261 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2262 suggests. */
2263 static std::string info_threads_help
2264 = gdb::option::build_help (_("\
2265 Display currently known threads.\n\
2266 Usage: info threads [OPTION]... [ID]...\n\
2267 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2268 Otherwise, all threads are displayed.\n\
2270 Options:\n\
2271 %OPTIONS%"),
2272 info_threads_opts);
2274 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2275 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
2277 cmd_list_element *thread_cmd
2278 = add_prefix_cmd ("thread", class_run, thread_command, _("\
2279 Use this command to switch between threads.\n\
2280 The new thread ID must be currently known."),
2281 &thread_cmd_list, 1, &cmdlist);
2283 add_com_alias ("t", thread_cmd, class_run, 1);
2285 #define THREAD_APPLY_OPTION_HELP "\
2286 Prints per-inferior thread number and target system's thread id\n\
2287 followed by COMMAND output.\n\
2289 By default, an error raised during the execution of COMMAND\n\
2290 aborts \"thread apply\".\n\
2292 Options:\n\
2293 %OPTIONS%"
2295 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2297 static std::string thread_apply_help = gdb::option::build_help (_("\
2298 Apply a command to a list of threads.\n\
2299 Usage: thread apply ID... [OPTION]... COMMAND\n\
2300 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2301 THREAD_APPLY_OPTION_HELP),
2302 thread_apply_opts);
2304 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2305 thread_apply_help.c_str (),
2306 &thread_apply_list, 1,
2307 &thread_cmd_list);
2308 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
2310 const auto thread_apply_all_opts
2311 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2313 static std::string thread_apply_all_help = gdb::option::build_help (_("\
2314 Apply a command to all threads.\n\
2316 Usage: thread apply all [OPTION]... COMMAND\n"
2317 THREAD_APPLY_OPTION_HELP),
2318 thread_apply_all_opts);
2320 c = add_cmd ("all", class_run, thread_apply_all_command,
2321 thread_apply_all_help.c_str (),
2322 &thread_apply_list);
2323 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2325 c = add_com ("taas", class_run, taas_command, _("\
2326 Apply a command to all threads (ignoring errors and empty output).\n\
2327 Usage: taas [OPTION]... COMMAND\n\
2328 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2329 See \"help thread apply all\" for available options."));
2330 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2332 c = add_com ("tfaas", class_run, tfaas_command, _("\
2333 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2334 Usage: tfaas [OPTION]... COMMAND\n\
2335 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2336 See \"help frame apply all\" for available options."));
2337 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
2339 add_cmd ("name", class_run, thread_name_command,
2340 _("Set the current thread's name.\n\
2341 Usage: thread name [NAME]\n\
2342 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2344 add_cmd ("find", class_run, thread_find_command, _("\
2345 Find threads that match a regular expression.\n\
2346 Usage: thread find REGEXP\n\
2347 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2348 &thread_cmd_list);
2350 add_setshow_boolean_cmd ("thread-events", no_class,
2351 &print_thread_events, _("\
2352 Set printing of thread events (such as thread start and exit)."), _("\
2353 Show printing of thread events (such as thread start and exit)."), NULL,
2354 NULL,
2355 show_print_thread_events,
2356 &setprintlist, &showprintlist);
2358 add_setshow_boolean_cmd ("threads", class_maintenance, &debug_threads, _("\
2359 Set thread debugging."), _("\
2360 Show thread debugging."), _("\
2361 When on messages about thread creation and deletion are printed."),
2362 nullptr,
2363 show_debug_threads,
2364 &setdebuglist, &showdebuglist);
2366 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2367 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);
2368 create_internalvar_type_lazy ("_inferior_thread_count",
2369 &inferior_thread_count_funcs, NULL);