gdb, testsuite: Fix return value in gdb.base/foll-fork.exp
[binutils-gdb.git] / gdb / thread.c
blob4ee469368610ebc0dbb7a057e549d256720100fe
1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 Contributed by Lynx Real-Time Systems, Inc. Los Gatos, CA.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "language.h"
23 #include "symtab.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbsupport/environ.h"
27 #include "top.h"
28 #include "value.h"
29 #include "target.h"
30 #include "gdbthread.h"
31 #include "command.h"
32 #include "cli/cli-cmds.h"
33 #include "regcache.h"
34 #include "btrace.h"
36 #include <ctype.h>
37 #include <sys/types.h>
38 #include <signal.h>
39 #include "ui-out.h"
40 #include "observable.h"
41 #include "annotate.h"
42 #include "cli/cli-decode.h"
43 #include "cli/cli-option.h"
44 #include "gdbsupport/gdb_regex.h"
45 #include "cli/cli-utils.h"
46 #include "thread-fsm.h"
47 #include "tid-parse.h"
48 #include <algorithm>
49 #include <optional>
50 #include "inline-frame.h"
51 #include "stack.h"
52 #include "interps.h"
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 gdb::observers::thread_deleted.notify (thr);
532 delete thr;
535 /* See gdbthread.h. */
537 void
538 delete_thread_with_exit_code (thread_info *thread, ULONGEST exit_code,
539 bool silent)
541 delete_thread_1 (thread, exit_code, silent);
544 /* See gdbthread.h. */
546 void
547 delete_thread (thread_info *thread)
549 delete_thread_1 (thread, {}, false /* not silent */);
552 void
553 delete_thread_silent (thread_info *thread)
555 delete_thread_1 (thread, {}, true /* not silent */);
558 struct thread_info *
559 find_thread_global_id (int global_id)
561 for (thread_info *tp : all_threads ())
562 if (tp->global_num == global_id)
563 return tp;
565 return NULL;
568 static struct thread_info *
569 find_thread_id (struct inferior *inf, int thr_num)
571 for (thread_info *tp : inf->threads ())
572 if (tp->per_inf_num == thr_num)
573 return tp;
575 return NULL;
578 /* See gdbthread.h. */
580 struct thread_info *
581 find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
582 struct inferior *inf)
584 return target_thread_handle_to_thread_info (handle.data (),
585 handle.size (),
586 inf);
590 * Thread iterator function.
592 * Calls a callback function once for each thread, so long as
593 * the callback function returns false. If the callback function
594 * returns true, the iteration will end and the current thread
595 * will be returned. This can be useful for implementing a
596 * search for a thread with arbitrary attributes, or for applying
597 * some operation to every thread.
599 * FIXME: some of the existing functionality, such as
600 * "Thread apply all", might be rewritten using this functionality.
603 struct thread_info *
604 iterate_over_threads (int (*callback) (struct thread_info *, void *),
605 void *data)
607 for (thread_info *tp : all_threads_safe ())
608 if ((*callback) (tp, data))
609 return tp;
611 return NULL;
614 /* See gdbthread.h. */
616 bool
617 any_thread_p ()
619 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
620 return true;
621 return false;
625 thread_count (process_stratum_target *proc_target)
627 auto rng = all_threads (proc_target);
628 return std::distance (rng.begin (), rng.end ());
631 /* Return the number of non-exited threads in the thread list. */
633 static int
634 live_threads_count (void)
636 auto rng = all_non_exited_threads ();
637 return std::distance (rng.begin (), rng.end ());
641 valid_global_thread_id (int global_id)
643 for (thread_info *tp : all_threads ())
644 if (tp->global_num == global_id)
645 return 1;
647 return 0;
650 bool
651 in_thread_list (process_stratum_target *targ, ptid_t ptid)
653 return targ->find_thread (ptid) != nullptr;
656 /* Finds the first thread of the inferior. */
658 thread_info *
659 first_thread_of_inferior (inferior *inf)
661 if (inf->thread_list.empty ())
662 return nullptr;
664 return &inf->thread_list.front ();
667 thread_info *
668 any_thread_of_inferior (inferior *inf)
670 gdb_assert (inf->pid != 0);
672 /* Prefer the current thread, if there's one. */
673 if (inf == current_inferior () && inferior_ptid != null_ptid)
674 return inferior_thread ();
676 for (thread_info *tp : inf->non_exited_threads ())
677 return tp;
679 return NULL;
682 thread_info *
683 any_live_thread_of_inferior (inferior *inf)
685 struct thread_info *curr_tp = NULL;
686 struct thread_info *tp_executing = NULL;
688 gdb_assert (inf != NULL && inf->pid != 0);
690 /* Prefer the current thread if it's not executing. */
691 if (inferior_ptid != null_ptid && current_inferior () == inf)
693 /* If the current thread is dead, forget it. If it's not
694 executing, use it. Otherwise, still choose it (below), but
695 only if no other non-executing thread is found. */
696 curr_tp = inferior_thread ();
697 if (curr_tp->state == THREAD_EXITED)
698 curr_tp = NULL;
699 else if (!curr_tp->executing ())
700 return curr_tp;
703 for (thread_info *tp : inf->non_exited_threads ())
705 if (!tp->executing ())
706 return tp;
708 tp_executing = tp;
711 /* If both the current thread and all live threads are executing,
712 prefer the current thread. */
713 if (curr_tp != NULL)
714 return curr_tp;
716 /* Otherwise, just return an executing thread, if any. */
717 return tp_executing;
720 /* Return true if TP is an active thread. */
721 static bool
722 thread_alive (thread_info *tp)
724 if (tp->state == THREAD_EXITED)
725 return false;
727 /* Ensure we're looking at the right target stack. */
728 gdb_assert (tp->inf == current_inferior ());
730 return target_thread_alive (tp->ptid);
733 /* See gdbthreads.h. */
735 bool
736 switch_to_thread_if_alive (thread_info *thr)
738 scoped_restore_current_thread restore_thread;
740 /* Switch inferior first, so that we're looking at the right target
741 stack. */
742 switch_to_inferior_no_thread (thr->inf);
744 if (thread_alive (thr))
746 switch_to_thread (thr);
747 restore_thread.dont_restore ();
748 return true;
751 return false;
754 /* See gdbthreads.h. */
756 void
757 prune_threads (void)
759 scoped_restore_current_thread restore_thread;
761 for (thread_info *tp : all_threads_safe ())
763 switch_to_inferior_no_thread (tp->inf);
765 if (!thread_alive (tp))
766 delete_thread (tp);
770 /* See gdbthreads.h. */
772 void
773 delete_exited_threads (void)
775 for (thread_info *tp : all_threads_safe ())
776 if (tp->state == THREAD_EXITED)
777 delete_thread (tp);
780 /* Return true value if stack temporaries are enabled for the thread
781 TP. */
783 bool
784 thread_stack_temporaries_enabled_p (thread_info *tp)
786 if (tp == NULL)
787 return false;
788 else
789 return tp->stack_temporaries_enabled;
792 /* Push V on to the stack temporaries of the thread with id PTID. */
794 void
795 push_thread_stack_temporary (thread_info *tp, struct value *v)
797 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
798 tp->stack_temporaries.push_back (v);
801 /* Return true if VAL is among the stack temporaries of the thread
802 TP. Return false otherwise. */
804 bool
805 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
807 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
808 for (value *v : tp->stack_temporaries)
809 if (v == val)
810 return true;
812 return false;
815 /* Return the last of the stack temporaries for thread with id PTID.
816 Return NULL if there are no stack temporaries for the thread. */
818 value *
819 get_last_thread_stack_temporary (thread_info *tp)
821 struct value *lastval = NULL;
823 gdb_assert (tp != NULL);
824 if (!tp->stack_temporaries.empty ())
825 lastval = tp->stack_temporaries.back ();
827 return lastval;
830 void
831 thread_change_ptid (process_stratum_target *targ,
832 ptid_t old_ptid, ptid_t new_ptid)
834 struct inferior *inf;
835 struct thread_info *tp;
837 /* It can happen that what we knew as the target inferior id
838 changes. E.g, target remote may only discover the remote process
839 pid after adding the inferior to GDB's list. */
840 inf = find_inferior_ptid (targ, old_ptid);
841 inf->pid = new_ptid.pid ();
843 tp = inf->find_thread (old_ptid);
844 gdb_assert (tp != nullptr);
846 int num_erased = inf->ptid_thread_map.erase (old_ptid);
847 gdb_assert (num_erased == 1);
849 tp->ptid = new_ptid;
850 inf->ptid_thread_map[new_ptid] = tp;
852 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
855 /* See gdbthread.h. */
857 void
858 set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
860 for (thread_info *tp : all_non_exited_threads (targ, ptid))
861 tp->set_resumed (resumed);
864 /* Helper for set_running, that marks one thread either running or
865 stopped. */
867 static bool
868 set_running_thread (struct thread_info *tp, bool running)
870 bool started = false;
872 if (running && tp->state == THREAD_STOPPED)
873 started = true;
874 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
876 threads_debug_printf ("thread: %s, running? %d%s",
877 tp->ptid.to_string ().c_str (), running,
878 (started ? " (started)" : ""));
880 if (!running)
882 /* If the thread is now marked stopped, remove it from
883 the step-over queue, so that we don't try to resume
884 it until the user wants it to. */
885 if (thread_is_in_step_over_chain (tp))
886 global_thread_step_over_chain_remove (tp);
889 return started;
892 /* Notify interpreters and observers that the target was resumed. */
894 static void
895 notify_target_resumed (ptid_t ptid)
897 interps_notify_target_resumed (ptid);
898 gdb::observers::target_resumed.notify (ptid);
900 /* We are about to resume the inferior. Close all cached BFDs so that
901 when the inferior next stops, and GDB regains control, we will spot
902 any on-disk changes to the BFDs we are using. */
903 bfd_cache_close_all ();
906 /* See gdbthread.h. */
908 void
909 thread_info::set_running (bool running)
911 if (set_running_thread (this, running))
912 notify_target_resumed (this->ptid);
915 void
916 set_running (process_stratum_target *targ, ptid_t ptid, bool running)
918 /* We try not to notify the observer if no thread has actually
919 changed the running state -- merely to reduce the number of
920 messages to the MI frontend. A frontend is supposed to handle
921 multiple *running notifications just fine. */
922 bool any_started = false;
924 for (thread_info *tp : all_non_exited_threads (targ, ptid))
925 if (set_running_thread (tp, running))
926 any_started = true;
928 if (any_started)
929 notify_target_resumed (ptid);
932 void
933 set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
935 for (thread_info *tp : all_non_exited_threads (targ, ptid))
936 tp->set_executing (executing);
938 /* It only takes one running thread to spawn more threads. */
939 if (executing)
940 targ->threads_executing = true;
941 /* Only clear the flag if the caller is telling us everything is
942 stopped. */
943 else if (minus_one_ptid == ptid)
944 targ->threads_executing = false;
947 /* See gdbthread.h. */
949 bool
950 threads_are_executing (process_stratum_target *target)
952 return target->threads_executing;
955 void
956 set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
958 for (thread_info *tp : all_non_exited_threads (targ, ptid))
959 tp->stop_requested = stop;
961 /* Call the stop requested observer so other components of GDB can
962 react to this request. */
963 if (stop)
964 gdb::observers::thread_stop_requested.notify (ptid);
967 void
968 finish_thread_state (process_stratum_target *targ, ptid_t ptid)
970 bool any_started = false;
972 for (thread_info *tp : all_non_exited_threads (targ, ptid))
973 if (set_running_thread (tp, tp->executing ()))
974 any_started = true;
976 if (any_started)
977 notify_target_resumed (ptid);
980 /* See gdbthread.h. */
982 void
983 validate_registers_access (void)
985 /* No selected thread, no registers. */
986 if (inferior_ptid == null_ptid)
987 error (_("No thread selected."));
989 thread_info *tp = inferior_thread ();
991 /* Don't try to read from a dead thread. */
992 if (tp->state == THREAD_EXITED)
993 error (_("The current thread has terminated"));
995 /* ... or from a spinning thread. FIXME: This isn't actually fully
996 correct. It'll allow an user-requested access (e.g., "print $pc"
997 at the prompt) when a thread is not executing for some internal
998 reason, but is marked running from the user's perspective. E.g.,
999 the thread is waiting for its turn in the step-over queue. */
1000 if (tp->executing ())
1001 error (_("Selected thread is running."));
1004 /* See gdbthread.h. */
1006 bool
1007 can_access_registers_thread (thread_info *thread)
1009 /* No thread, no registers. */
1010 if (thread == NULL)
1011 return false;
1013 /* Don't try to read from a dead thread. */
1014 if (thread->state == THREAD_EXITED)
1015 return false;
1017 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
1018 if (thread->executing ())
1019 return false;
1021 return true;
1024 bool
1025 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
1027 return (pc >= thread->control.step_range_start
1028 && pc < thread->control.step_range_end);
1031 /* Helper for print_thread_info. Returns true if THR should be
1032 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
1033 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
1034 is true if REQUESTED_THREADS is list of global IDs, false if a list
1035 of per-inferior thread ids. If PID is not -1, only print THR if it
1036 is a thread from the process PID. Otherwise, threads from all
1037 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
1038 and PID is not -1, then the thread is printed if it belongs to the
1039 specified process. Otherwise, an error is raised. */
1041 static bool
1042 should_print_thread (const char *requested_threads, int default_inf_num,
1043 int global_ids, int pid, struct thread_info *thr)
1045 if (requested_threads != NULL && *requested_threads != '\0')
1047 int in_list;
1049 if (global_ids)
1050 in_list = number_is_in_list (requested_threads, thr->global_num);
1051 else
1052 in_list = tid_is_in_list (requested_threads, default_inf_num,
1053 thr->inf->num, thr->per_inf_num);
1054 if (!in_list)
1055 return false;
1058 if (pid != -1 && thr->ptid.pid () != pid)
1060 if (requested_threads != NULL && *requested_threads != '\0')
1061 error (_("Requested thread not found in requested process"));
1062 return false;
1065 if (thr->state == THREAD_EXITED)
1066 return false;
1068 return true;
1071 /* Return the string to display in "info threads"'s "Target Id"
1072 column, for TP. */
1074 static std::string
1075 thread_target_id_str (thread_info *tp)
1077 std::string target_id = target_pid_to_str (tp->ptid);
1078 const char *extra_info = target_extra_thread_info (tp);
1079 const char *name = thread_name (tp);
1081 if (extra_info != nullptr && name != nullptr)
1082 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1083 extra_info);
1084 else if (extra_info != nullptr)
1085 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1086 else if (name != nullptr)
1087 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1088 else
1089 return target_id;
1092 /* Print thread TP. GLOBAL_IDS indicates whether REQUESTED_THREADS
1093 is a list of global or per-inferior thread ids. */
1095 static void
1096 do_print_thread (ui_out *uiout, const char *requested_threads,
1097 int global_ids, int pid, int show_global_ids,
1098 int default_inf_num, thread_info *tp,
1099 thread_info *current_thread)
1101 int core;
1103 /* In case REQUESTED_THREADS contains $_thread. */
1104 if (current_thread != nullptr)
1105 switch_to_thread (current_thread);
1107 if (!should_print_thread (requested_threads, default_inf_num,
1108 global_ids, pid, tp))
1109 return;
1111 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1113 if (!uiout->is_mi_like_p ())
1115 if (tp == current_thread)
1116 uiout->field_string ("current", "*");
1117 else
1118 uiout->field_skip ("current");
1120 uiout->field_string ("id-in-tg", print_thread_id (tp));
1123 if (show_global_ids || uiout->is_mi_like_p ())
1124 uiout->field_signed ("id", tp->global_num);
1126 /* Switch to the thread (and inferior / target). */
1127 switch_to_thread (tp);
1129 /* For the CLI, we stuff everything into the target-id field.
1130 This is a gross hack to make the output come out looking
1131 correct. The underlying problem here is that ui-out has no
1132 way to specify that a field's space allocation should be
1133 shared by several fields. For MI, we do the right thing
1134 instead. */
1136 if (uiout->is_mi_like_p ())
1138 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1140 const char *extra_info = target_extra_thread_info (tp);
1141 if (extra_info != nullptr)
1142 uiout->field_string ("details", extra_info);
1144 const char *name = thread_name (tp);
1145 if (name != NULL)
1146 uiout->field_string ("name", name);
1148 else
1150 uiout->field_string ("target-id", thread_target_id_str (tp));
1153 if (tp->state == THREAD_RUNNING)
1154 uiout->text ("(running)\n");
1155 else
1157 /* The switch above put us at the top of the stack (leaf
1158 frame). */
1159 print_stack_frame (get_selected_frame (NULL),
1160 /* For MI output, print frame level. */
1161 uiout->is_mi_like_p (),
1162 LOCATION, 0);
1165 if (uiout->is_mi_like_p ())
1167 const char *state = "stopped";
1169 if (tp->state == THREAD_RUNNING)
1170 state = "running";
1171 uiout->field_string ("state", state);
1174 core = target_core_of_thread (tp->ptid);
1175 if (uiout->is_mi_like_p () && core != -1)
1176 uiout->field_signed ("core", core);
1179 /* Redirect output to a temporary buffer for the duration
1180 of do_print_thread. */
1182 static void
1183 print_thread (ui_out *uiout, const char *requested_threads,
1184 int global_ids, int pid, int show_global_ids,
1185 int default_inf_num, thread_info *tp, thread_info *current_thread)
1188 do_with_buffered_output (do_print_thread, uiout, requested_threads,
1189 global_ids, pid, show_global_ids,
1190 default_inf_num, tp, current_thread);
1193 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1194 whether REQUESTED_THREADS is a list of global or per-inferior
1195 thread ids. */
1197 static void
1198 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1199 int global_ids, int pid,
1200 int show_global_ids)
1202 int default_inf_num = current_inferior ()->num;
1204 update_thread_list ();
1206 /* Whether we saw any thread. */
1207 bool any_thread = false;
1208 /* Whether the current thread is exited. */
1209 bool current_exited = false;
1211 thread_info *current_thread = (inferior_ptid != null_ptid
1212 ? inferior_thread () : NULL);
1215 /* For backward compatibility, we make a list for MI. A table is
1216 preferable for the CLI, though, because it shows table
1217 headers. */
1218 std::optional<ui_out_emit_list> list_emitter;
1219 std::optional<ui_out_emit_table> table_emitter;
1221 /* We'll be switching threads temporarily below. */
1222 scoped_restore_current_thread restore_thread;
1224 if (uiout->is_mi_like_p ())
1225 list_emitter.emplace (uiout, "threads");
1226 else
1228 int n_threads = 0;
1229 /* The width of the "Target Id" column. Grown below to
1230 accommodate the largest entry. */
1231 size_t target_id_col_width = 17;
1233 for (thread_info *tp : all_threads ())
1235 /* In case REQUESTED_THREADS contains $_thread. */
1236 if (current_thread != nullptr)
1237 switch_to_thread (current_thread);
1239 if (!should_print_thread (requested_threads, default_inf_num,
1240 global_ids, pid, tp))
1241 continue;
1243 /* Switch inferiors so we're looking at the right
1244 target stack. */
1245 switch_to_inferior_no_thread (tp->inf);
1247 target_id_col_width
1248 = std::max (target_id_col_width,
1249 thread_target_id_str (tp).size ());
1251 ++n_threads;
1254 if (n_threads == 0)
1256 if (requested_threads == NULL || *requested_threads == '\0')
1257 uiout->message (_("No threads.\n"));
1258 else
1259 uiout->message (_("No threads match '%s'.\n"),
1260 requested_threads);
1261 return;
1264 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1265 n_threads, "threads");
1267 uiout->table_header (1, ui_left, "current", "");
1268 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1269 if (show_global_ids)
1270 uiout->table_header (4, ui_left, "id", "GId");
1271 uiout->table_header (target_id_col_width, ui_left,
1272 "target-id", "Target Id");
1273 uiout->table_header (1, ui_left, "frame", "Frame");
1274 uiout->table_body ();
1277 for (inferior *inf : all_inferiors ())
1278 for (thread_info *tp : inf->threads ())
1280 any_thread = true;
1282 if (tp == current_thread && tp->state == THREAD_EXITED)
1283 current_exited = true;
1285 print_thread (uiout, requested_threads, global_ids, pid,
1286 show_global_ids, default_inf_num, tp, current_thread);
1289 /* This end scope restores the current thread and the frame
1290 selected before the "info threads" command, and it finishes the
1291 ui-out list or table. */
1294 if (pid == -1 && requested_threads == NULL)
1296 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1297 uiout->field_signed ("current-thread-id", current_thread->global_num);
1299 if (inferior_ptid != null_ptid && current_exited)
1300 uiout->message ("\n\
1301 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1302 print_thread_id (inferior_thread ()));
1303 else if (any_thread && inferior_ptid == null_ptid)
1304 uiout->message ("\n\
1305 No selected thread. See `help thread'.\n");
1309 /* See gdbthread.h. */
1311 void
1312 print_thread_info (struct ui_out *uiout, const char *requested_threads,
1313 int pid)
1315 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1318 /* The options for the "info threads" command. */
1320 struct info_threads_opts
1322 /* For "-gid". */
1323 bool show_global_ids = false;
1326 static const gdb::option::option_def info_threads_option_defs[] = {
1328 gdb::option::flag_option_def<info_threads_opts> {
1329 "gid",
1330 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1331 N_("Show global thread IDs."),
1336 /* Create an option_def_group for the "info threads" options, with
1337 IT_OPTS as context. */
1339 static inline gdb::option::option_def_group
1340 make_info_threads_options_def_group (info_threads_opts *it_opts)
1342 return {{info_threads_option_defs}, it_opts};
1345 /* Implementation of the "info threads" command.
1347 Note: this has the drawback that it _really_ switches
1348 threads, which frees the frame cache. A no-side
1349 effects info-threads command would be nicer. */
1351 static void
1352 info_threads_command (const char *arg, int from_tty)
1354 info_threads_opts it_opts;
1356 auto grp = make_info_threads_options_def_group (&it_opts);
1357 gdb::option::process_options
1358 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1360 print_thread_info_1 (current_uiout, arg, 0, -1, it_opts.show_global_ids);
1363 /* Completer for the "info threads" command. */
1365 static void
1366 info_threads_command_completer (struct cmd_list_element *ignore,
1367 completion_tracker &tracker,
1368 const char *text, const char *word_ignored)
1370 const auto grp = make_info_threads_options_def_group (nullptr);
1372 if (gdb::option::complete_options
1373 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1374 return;
1376 /* Convenience to let the user know what the option can accept. */
1377 if (*text == '\0')
1379 gdb::option::complete_on_all_options (tracker, grp);
1380 /* Keep this "ID" in sync with what "help info threads"
1381 says. */
1382 tracker.add_completion (make_unique_xstrdup ("ID"));
1386 /* See gdbthread.h. */
1388 void
1389 switch_to_thread_no_regs (struct thread_info *thread)
1391 gdb_assert (thread != nullptr);
1392 threads_debug_printf ("thread = %s", thread->ptid.to_string ().c_str ());
1394 struct inferior *inf = thread->inf;
1396 set_current_program_space (inf->pspace);
1397 set_current_inferior (inf);
1399 current_thread_ = thread;
1400 inferior_ptid = current_thread_->ptid;
1403 /* See gdbthread.h. */
1405 void
1406 switch_to_no_thread ()
1408 if (current_thread_ == nullptr)
1409 return;
1411 threads_debug_printf ("thread = NONE");
1413 current_thread_ = nullptr;
1414 inferior_ptid = null_ptid;
1415 reinit_frame_cache ();
1418 /* See gdbthread.h. */
1420 void
1421 switch_to_thread (thread_info *thr)
1423 gdb_assert (thr != NULL);
1425 if (is_current_thread (thr))
1426 return;
1428 switch_to_thread_no_regs (thr);
1430 reinit_frame_cache ();
1433 /* See gdbsupport/common-gdbthread.h. */
1435 void
1436 switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
1438 thread_info *thr = proc_target->find_thread (ptid);
1439 switch_to_thread (thr);
1442 /* See frame.h. */
1444 void
1445 scoped_restore_current_thread::restore ()
1447 /* If an entry of thread_info was previously selected, it won't be
1448 deleted because we've increased its refcount. The thread represented
1449 by this thread_info entry may have already exited (due to normal exit,
1450 detach, etc), so the thread_info.state is THREAD_EXITED. */
1451 if (m_thread != NULL
1452 /* If the previously selected thread belonged to a process that has
1453 in the mean time exited (or killed, detached, etc.), then don't revert
1454 back to it, but instead simply drop back to no thread selected. */
1455 && m_inf->pid != 0)
1456 switch_to_thread (m_thread.get ());
1457 else
1458 switch_to_inferior_no_thread (m_inf.get ());
1460 /* The running state of the originally selected thread may have
1461 changed, so we have to recheck it here. */
1462 if (inferior_ptid != null_ptid
1463 && m_was_stopped
1464 && m_thread->state == THREAD_STOPPED
1465 && target_has_registers ()
1466 && target_has_stack ()
1467 && target_has_memory ())
1468 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1471 scoped_restore_current_thread::~scoped_restore_current_thread ()
1473 if (m_dont_restore)
1474 m_lang.dont_restore ();
1475 else
1476 restore ();
1479 scoped_restore_current_thread::scoped_restore_current_thread ()
1481 m_inf = inferior_ref::new_reference (current_inferior ());
1483 if (inferior_ptid != null_ptid)
1485 m_thread = thread_info_ref::new_reference (inferior_thread ());
1487 m_was_stopped = m_thread->state == THREAD_STOPPED;
1488 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
1492 scoped_restore_current_thread::scoped_restore_current_thread
1493 (scoped_restore_current_thread &&rhs)
1494 : m_dont_restore (std::move (rhs.m_dont_restore)),
1495 m_thread (std::move (rhs.m_thread)),
1496 m_inf (std::move (rhs.m_inf)),
1497 m_selected_frame_id (std::move (rhs.m_selected_frame_id)),
1498 m_selected_frame_level (std::move (rhs.m_selected_frame_level)),
1499 m_was_stopped (std::move (rhs.m_was_stopped)),
1500 m_lang (std::move (rhs.m_lang))
1502 /* Deactivate the rhs. */
1503 rhs.m_dont_restore = true;
1506 /* See gdbthread.h. */
1509 show_thread_that_caused_stop (void)
1511 return highest_thread_num > 1;
1514 /* See gdbthread.h. */
1517 show_inferior_qualified_tids (void)
1519 auto inf = inferior_list.begin ();
1520 if (inf->num != 1)
1521 return true;
1522 ++inf;
1523 return inf != inferior_list.end ();
1526 /* See gdbthread.h. */
1528 const char *
1529 print_thread_id (struct thread_info *thr)
1531 if (show_inferior_qualified_tids ())
1532 return print_full_thread_id (thr);
1534 char *s = get_print_cell ();
1536 gdb_assert (thr != nullptr);
1537 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1538 return s;
1541 /* See gdbthread.h. */
1543 const char *
1544 print_full_thread_id (struct thread_info *thr)
1546 char *s = get_print_cell ();
1548 gdb_assert (thr != nullptr);
1549 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1550 return s;
1553 /* Sort an array of struct thread_info pointers by thread ID (first by
1554 inferior number, and then by per-inferior thread number). Sorts in
1555 ascending order. */
1557 static bool
1558 tp_array_compar_ascending (const thread_info_ref &a, const thread_info_ref &b)
1560 if (a->inf->num != b->inf->num)
1561 return a->inf->num < b->inf->num;
1563 return (a->per_inf_num < b->per_inf_num);
1566 /* Sort an array of struct thread_info pointers by thread ID (first by
1567 inferior number, and then by per-inferior thread number). Sorts in
1568 descending order. */
1570 static bool
1571 tp_array_compar_descending (const thread_info_ref &a, const thread_info_ref &b)
1573 if (a->inf->num != b->inf->num)
1574 return a->inf->num > b->inf->num;
1576 return (a->per_inf_num > b->per_inf_num);
1579 /* See gdbthread.h. */
1581 void
1582 thread_try_catch_cmd (thread_info *thr, std::optional<int> ada_task,
1583 const char *cmd, int from_tty,
1584 const qcs_flags &flags)
1586 gdb_assert (is_current_thread (thr));
1588 /* The thread header is computed before running the command since
1589 the command can change the inferior, which is not permitted
1590 by thread_target_id_str. */
1591 std::string thr_header;
1592 if (ada_task.has_value ())
1593 thr_header = string_printf (_("\nTask ID %d:\n"), *ada_task);
1594 else
1595 thr_header = string_printf (_("\nThread %s (%s):\n"),
1596 print_thread_id (thr),
1597 thread_target_id_str (thr).c_str ());
1601 std::string cmd_result;
1602 execute_command_to_string
1603 (cmd_result, cmd, from_tty, gdb_stdout->term_out ());
1604 if (!flags.silent || cmd_result.length () > 0)
1606 if (!flags.quiet)
1607 gdb_printf ("%s", thr_header.c_str ());
1608 gdb_printf ("%s", cmd_result.c_str ());
1611 catch (const gdb_exception_error &ex)
1613 if (!flags.silent)
1615 if (!flags.quiet)
1616 gdb_printf ("%s", thr_header.c_str ());
1617 if (flags.cont)
1618 gdb_printf ("%s\n", ex.what ());
1619 else
1620 throw;
1625 /* Option definition of "thread apply"'s "-ascending" option. */
1627 static const gdb::option::flag_option_def<> ascending_option_def = {
1628 "ascending",
1629 N_("\
1630 Call COMMAND for all threads in ascending order.\n\
1631 The default is descending order."),
1634 /* The qcs command line flags for the "thread apply" commands. Keep
1635 this in sync with the "frame apply" commands. */
1637 using qcs_flag_option_def
1638 = gdb::option::flag_option_def<qcs_flags>;
1640 static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1641 qcs_flag_option_def {
1642 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1643 N_("Disables printing the thread information."),
1646 qcs_flag_option_def {
1647 "c", [] (qcs_flags *opt) { return &opt->cont; },
1648 N_("Print any error raised by COMMAND and continue."),
1651 qcs_flag_option_def {
1652 "s", [] (qcs_flags *opt) { return &opt->silent; },
1653 N_("Silently ignore any errors or empty output produced by COMMAND."),
1657 /* Create an option_def_group for the "thread apply all" options, with
1658 ASCENDING and FLAGS as context. */
1660 static inline std::array<gdb::option::option_def_group, 2>
1661 make_thread_apply_all_options_def_group (bool *ascending,
1662 qcs_flags *flags)
1664 return {{
1665 { {ascending_option_def.def ()}, ascending},
1666 { {thr_qcs_flags_option_defs}, flags },
1670 /* Create an option_def_group for the "thread apply" options, with
1671 FLAGS as context. */
1673 static inline gdb::option::option_def_group
1674 make_thread_apply_options_def_group (qcs_flags *flags)
1676 return {{thr_qcs_flags_option_defs}, flags};
1679 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1680 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1681 of two numbers separated by a hyphen. Examples:
1683 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1684 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1685 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1687 static void
1688 thread_apply_all_command (const char *cmd, int from_tty)
1690 bool ascending = false;
1691 qcs_flags flags;
1693 auto group = make_thread_apply_all_options_def_group (&ascending,
1694 &flags);
1695 gdb::option::process_options
1696 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1698 validate_flags_qcs ("thread apply all", &flags);
1700 if (cmd == NULL || *cmd == '\000')
1701 error (_("Please specify a command at the end of 'thread apply all'"));
1703 update_thread_list ();
1705 int tc = live_threads_count ();
1706 if (tc != 0)
1708 /* Save a copy of the thread list and increment each thread's
1709 refcount while executing the command in the context of each
1710 thread, in case the command is one that wipes threads. E.g.,
1711 detach, kill, disconnect, etc., or even normally continuing
1712 over an inferior or thread exit. */
1713 std::vector<thread_info_ref> thr_list_cpy;
1714 thr_list_cpy.reserve (tc);
1716 for (thread_info *tp : all_non_exited_threads ())
1717 thr_list_cpy.push_back (thread_info_ref::new_reference (tp));
1718 gdb_assert (thr_list_cpy.size () == tc);
1720 auto *sorter = (ascending
1721 ? tp_array_compar_ascending
1722 : tp_array_compar_descending);
1723 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
1725 scoped_restore_current_thread restore_thread;
1727 for (thread_info_ref &thr : thr_list_cpy)
1728 if (switch_to_thread_if_alive (thr.get ()))
1729 thread_try_catch_cmd (thr.get (), {}, cmd, from_tty, flags);
1733 /* Completer for "thread apply [ID list]". */
1735 static void
1736 thread_apply_command_completer (cmd_list_element *ignore,
1737 completion_tracker &tracker,
1738 const char *text, const char * /*word*/)
1740 /* Don't leave this to complete_options because there's an early
1741 return below. */
1742 tracker.set_use_custom_word_point (true);
1744 tid_range_parser parser;
1745 parser.init (text, current_inferior ()->num);
1749 while (!parser.finished ())
1751 int inf_num, thr_start, thr_end;
1753 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1754 break;
1756 if (parser.in_star_range () || parser.in_thread_range ())
1757 parser.skip_range ();
1760 catch (const gdb_exception_error &ex)
1762 /* get_tid_range throws if it parses a negative number, for
1763 example. But a seemingly negative number may be the start of
1764 an option instead. */
1767 const char *cmd = parser.cur_tok ();
1769 if (cmd == text)
1771 /* No thread ID list yet. */
1772 return;
1775 /* Check if we're past a valid thread ID list already. */
1776 if (parser.finished ()
1777 && cmd > text && !isspace (cmd[-1]))
1778 return;
1780 /* We're past the thread ID list, advance word point. */
1781 tracker.advance_custom_word_point_by (cmd - text);
1782 text = cmd;
1784 const auto group = make_thread_apply_options_def_group (nullptr);
1785 if (gdb::option::complete_options
1786 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1787 return;
1789 complete_nested_command_line (tracker, text);
1792 /* Completer for "thread apply all". */
1794 static void
1795 thread_apply_all_command_completer (cmd_list_element *ignore,
1796 completion_tracker &tracker,
1797 const char *text, const char *word)
1799 const auto group = make_thread_apply_all_options_def_group (nullptr,
1800 nullptr);
1801 if (gdb::option::complete_options
1802 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1803 return;
1805 complete_nested_command_line (tracker, text);
1808 /* Implementation of the "thread apply" command. */
1810 static void
1811 thread_apply_command (const char *tidlist, int from_tty)
1813 qcs_flags flags;
1814 const char *cmd = NULL;
1815 tid_range_parser parser;
1817 if (tidlist == NULL || *tidlist == '\000')
1818 error (_("Please specify a thread ID list"));
1820 parser.init (tidlist, current_inferior ()->num);
1821 while (!parser.finished ())
1823 int inf_num, thr_start, thr_end;
1825 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1826 break;
1829 cmd = parser.cur_tok ();
1831 auto group = make_thread_apply_options_def_group (&flags);
1832 gdb::option::process_options
1833 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1835 validate_flags_qcs ("thread apply", &flags);
1837 if (*cmd == '\0')
1838 error (_("Please specify a command following the thread ID list"));
1840 if (tidlist == cmd || isdigit (cmd[0]))
1841 invalid_thread_id_error (cmd);
1843 scoped_restore_current_thread restore_thread;
1845 parser.init (tidlist, current_inferior ()->num);
1846 while (!parser.finished ())
1848 struct thread_info *tp = NULL;
1849 struct inferior *inf;
1850 int inf_num, thr_num;
1852 parser.get_tid (&inf_num, &thr_num);
1853 inf = find_inferior_id (inf_num);
1854 if (inf != NULL)
1855 tp = find_thread_id (inf, thr_num);
1857 if (parser.in_star_range ())
1859 if (inf == NULL)
1861 warning (_("Unknown inferior %d"), inf_num);
1862 parser.skip_range ();
1863 continue;
1866 /* No use looking for threads past the highest thread number
1867 the inferior ever had. */
1868 if (thr_num >= inf->highest_thread_num)
1869 parser.skip_range ();
1871 /* Be quiet about unknown threads numbers. */
1872 if (tp == NULL)
1873 continue;
1876 if (tp == NULL)
1878 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1879 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1880 else
1881 warning (_("Unknown thread %d"), thr_num);
1882 continue;
1885 if (!switch_to_thread_if_alive (tp))
1887 warning (_("Thread %s has terminated."), print_thread_id (tp));
1888 continue;
1891 thread_try_catch_cmd (tp, {}, cmd, from_tty, flags);
1896 /* Implementation of the "taas" command. */
1898 static void
1899 taas_command (const char *cmd, int from_tty)
1901 if (cmd == NULL || *cmd == '\0')
1902 error (_("Please specify a command to apply on all threads"));
1903 std::string expanded = std::string ("thread apply all -s ") + cmd;
1904 execute_command (expanded.c_str (), from_tty);
1907 /* Implementation of the "tfaas" command. */
1909 static void
1910 tfaas_command (const char *cmd, int from_tty)
1912 if (cmd == NULL || *cmd == '\0')
1913 error (_("Please specify a command to apply on all frames of all threads"));
1914 std::string expanded
1915 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1916 execute_command (expanded.c_str (), from_tty);
1919 /* Switch to the specified thread, or print the current thread. */
1921 void
1922 thread_command (const char *tidstr, int from_tty)
1924 if (tidstr == NULL)
1926 if (inferior_ptid == null_ptid)
1927 error (_("No thread selected"));
1929 if (target_has_stack ())
1931 struct thread_info *tp = inferior_thread ();
1933 if (tp->state == THREAD_EXITED)
1934 gdb_printf (_("[Current thread is %s (%s) (exited)]\n"),
1935 print_thread_id (tp),
1936 target_pid_to_str (inferior_ptid).c_str ());
1937 else
1938 gdb_printf (_("[Current thread is %s (%s)]\n"),
1939 print_thread_id (tp),
1940 target_pid_to_str (inferior_ptid).c_str ());
1942 else
1943 error (_("No stack."));
1945 else
1947 ptid_t previous_ptid = inferior_ptid;
1949 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1951 /* Print if the thread has not changed, otherwise an event will
1952 be sent. */
1953 if (inferior_ptid == previous_ptid)
1955 print_selected_thread_frame (current_uiout,
1956 USER_SELECTED_THREAD
1957 | USER_SELECTED_FRAME);
1959 else
1960 notify_user_selected_context_changed
1961 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1965 /* Implementation of `thread name'. */
1967 static void
1968 thread_name_command (const char *arg, int from_tty)
1970 struct thread_info *info;
1972 if (inferior_ptid == null_ptid)
1973 error (_("No thread selected"));
1975 arg = skip_spaces (arg);
1977 info = inferior_thread ();
1978 info->set_name (arg != nullptr ? make_unique_xstrdup (arg) : nullptr);
1981 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1983 static void
1984 thread_find_command (const char *arg, int from_tty)
1986 const char *tmp;
1987 unsigned long match = 0;
1989 if (arg == NULL || *arg == '\0')
1990 error (_("Command requires an argument."));
1992 tmp = re_comp (arg);
1993 if (tmp != 0)
1994 error (_("Invalid regexp (%s): %s"), tmp, arg);
1996 /* We're going to be switching threads. */
1997 scoped_restore_current_thread restore_thread;
1999 update_thread_list ();
2001 for (thread_info *tp : all_threads ())
2003 switch_to_inferior_no_thread (tp->inf);
2005 if (tp->name () != nullptr && re_exec (tp->name ()))
2007 gdb_printf (_("Thread %s has name '%s'\n"),
2008 print_thread_id (tp), tp->name ());
2009 match++;
2012 tmp = target_thread_name (tp);
2013 if (tmp != NULL && re_exec (tmp))
2015 gdb_printf (_("Thread %s has target name '%s'\n"),
2016 print_thread_id (tp), tmp);
2017 match++;
2020 std::string name = target_pid_to_str (tp->ptid);
2021 if (!name.empty () && re_exec (name.c_str ()))
2023 gdb_printf (_("Thread %s has target id '%s'\n"),
2024 print_thread_id (tp), name.c_str ());
2025 match++;
2028 tmp = target_extra_thread_info (tp);
2029 if (tmp != NULL && re_exec (tmp))
2031 gdb_printf (_("Thread %s has extra info '%s'\n"),
2032 print_thread_id (tp), tmp);
2033 match++;
2036 if (!match)
2037 gdb_printf (_("No threads match '%s'\n"), arg);
2040 /* Print notices when new threads are attached and detached. */
2041 bool print_thread_events = true;
2042 static void
2043 show_print_thread_events (struct ui_file *file, int from_tty,
2044 struct cmd_list_element *c, const char *value)
2046 gdb_printf (file,
2047 _("Printing of thread events is %s.\n"),
2048 value);
2051 /* See gdbthread.h. */
2053 void
2054 thread_select (const char *tidstr, thread_info *tp)
2056 if (!switch_to_thread_if_alive (tp))
2057 error (_("Thread ID %s has terminated."), tidstr);
2059 annotate_thread_changed ();
2061 /* Since the current thread may have changed, see if there is any
2062 exited thread we can now delete. */
2063 delete_exited_threads ();
2066 /* Print thread and frame switch command response. */
2068 void
2069 print_selected_thread_frame (struct ui_out *uiout,
2070 user_selected_what selection)
2072 struct thread_info *tp = inferior_thread ();
2074 if (selection & USER_SELECTED_THREAD)
2076 if (uiout->is_mi_like_p ())
2078 uiout->field_signed ("new-thread-id",
2079 inferior_thread ()->global_num);
2081 else
2083 uiout->text ("[Switching to thread ");
2084 uiout->field_string ("new-thread-id", print_thread_id (tp));
2085 uiout->text (" (");
2086 uiout->text (target_pid_to_str (inferior_ptid));
2087 uiout->text (")]");
2091 if (tp->state == THREAD_RUNNING)
2093 if (selection & USER_SELECTED_THREAD)
2094 uiout->text ("(running)\n");
2096 else if (selection & USER_SELECTED_FRAME)
2098 if (selection & USER_SELECTED_THREAD)
2099 uiout->text ("\n");
2101 if (has_stack_frames ())
2102 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
2103 1, SRC_AND_LOC, 1);
2107 /* Update the 'threads_executing' global based on the threads we know
2108 about right now. This is used by infrun to tell whether we should
2109 pull events out of the current target. */
2111 static void
2112 update_threads_executing (void)
2114 process_stratum_target *targ = current_inferior ()->process_target ();
2116 if (targ == NULL)
2117 return;
2119 targ->threads_executing = false;
2121 for (inferior *inf : all_non_exited_inferiors (targ))
2123 if (!inf->has_execution ())
2124 continue;
2126 /* If the process has no threads, then it must be we have a
2127 process-exit event pending. */
2128 if (inf->thread_list.empty ())
2130 targ->threads_executing = true;
2131 return;
2134 for (thread_info *tp : inf->non_exited_threads ())
2136 if (tp->executing ())
2138 targ->threads_executing = true;
2139 return;
2145 void
2146 update_thread_list (void)
2148 target_update_thread_list ();
2149 update_threads_executing ();
2152 /* See gdbthread.h. */
2154 const char *
2155 thread_name (thread_info *thread)
2157 /* Use the manually set name if there is one. */
2158 const char *name = thread->name ();
2159 if (name != nullptr)
2160 return name;
2162 /* Otherwise, ask the target. Ensure we query the right target stack. */
2163 scoped_restore_current_thread restore_thread;
2164 if (thread->inf != current_inferior ())
2165 switch_to_inferior_no_thread (thread->inf);
2167 return target_thread_name (thread);
2170 /* See gdbthread.h. */
2172 const char *
2173 thread_state_string (enum thread_state state)
2175 switch (state)
2177 case THREAD_STOPPED:
2178 return "STOPPED";
2180 case THREAD_RUNNING:
2181 return "RUNNING";
2183 case THREAD_EXITED:
2184 return "EXITED";
2187 gdb_assert_not_reached ("unknown thread state");
2190 /* Return a new value for the selected thread's id. Return a value of
2191 0 if no thread is selected. If GLOBAL is true, return the thread's
2192 global number. Otherwise return the per-inferior number. */
2194 static struct value *
2195 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2197 int int_val;
2199 if (inferior_ptid == null_ptid)
2200 int_val = 0;
2201 else
2203 thread_info *tp = inferior_thread ();
2204 if (global)
2205 int_val = tp->global_num;
2206 else
2207 int_val = tp->per_inf_num;
2210 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2213 /* Return a new value for the selected thread's per-inferior thread
2214 number. Return a value of 0 if no thread is selected, or no
2215 threads exist. */
2217 static struct value *
2218 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2219 struct internalvar *var,
2220 void *ignore)
2222 return thread_num_make_value_helper (gdbarch, 0);
2225 /* Return a new value for the selected thread's global id. Return a
2226 value of 0 if no thread is selected, or no threads exist. */
2228 static struct value *
2229 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2230 void *ignore)
2232 return thread_num_make_value_helper (gdbarch, 1);
2235 /* Return a new value for the number of non-exited threads in the current
2236 inferior. If there are no threads in the current inferior return a
2237 value of 0. */
2239 static struct value *
2240 inferior_thread_count_make_value (struct gdbarch *gdbarch,
2241 struct internalvar *var, void *ignore)
2243 int int_val = 0;
2245 update_thread_list ();
2247 if (inferior_ptid != null_ptid)
2248 int_val = current_inferior ()->non_exited_threads ().size ();
2250 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2253 /* Commands with a prefix of `thread'. */
2254 struct cmd_list_element *thread_cmd_list = NULL;
2256 /* Implementation of `thread' variable. */
2258 static const struct internalvar_funcs thread_funcs =
2260 thread_id_per_inf_num_make_value,
2261 NULL,
2264 /* Implementation of `gthread' variable. */
2266 static const struct internalvar_funcs gthread_funcs =
2268 global_thread_id_make_value,
2269 NULL,
2272 /* Implementation of `_inferior_thread_count` convenience variable. */
2274 static const struct internalvar_funcs inferior_thread_count_funcs =
2276 inferior_thread_count_make_value,
2277 NULL,
2280 void _initialize_thread ();
2281 void
2282 _initialize_thread ()
2284 static struct cmd_list_element *thread_apply_list = NULL;
2285 cmd_list_element *c;
2287 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2289 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2290 suggests. */
2291 static std::string info_threads_help
2292 = gdb::option::build_help (_("\
2293 Display currently known threads.\n\
2294 Usage: info threads [OPTION]... [ID]...\n\
2295 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2296 Otherwise, all threads are displayed.\n\
2298 Options:\n\
2299 %OPTIONS%"),
2300 info_threads_opts);
2302 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2303 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
2305 cmd_list_element *thread_cmd
2306 = add_prefix_cmd ("thread", class_run, thread_command, _("\
2307 Use this command to switch between threads.\n\
2308 The new thread ID must be currently known."),
2309 &thread_cmd_list, 1, &cmdlist);
2311 add_com_alias ("t", thread_cmd, class_run, 1);
2313 #define THREAD_APPLY_OPTION_HELP "\
2314 Prints per-inferior thread number and target system's thread id\n\
2315 followed by COMMAND output.\n\
2317 By default, an error raised during the execution of COMMAND\n\
2318 aborts \"thread apply\".\n\
2320 Options:\n\
2321 %OPTIONS%"
2323 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2325 static std::string thread_apply_help = gdb::option::build_help (_("\
2326 Apply a command to a list of threads.\n\
2327 Usage: thread apply ID... [OPTION]... COMMAND\n\
2328 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2329 THREAD_APPLY_OPTION_HELP),
2330 thread_apply_opts);
2332 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2333 thread_apply_help.c_str (),
2334 &thread_apply_list, 1,
2335 &thread_cmd_list);
2336 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
2338 const auto thread_apply_all_opts
2339 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2341 static std::string thread_apply_all_help = gdb::option::build_help (_("\
2342 Apply a command to all threads.\n\
2344 Usage: thread apply all [OPTION]... COMMAND\n"
2345 THREAD_APPLY_OPTION_HELP),
2346 thread_apply_all_opts);
2348 c = add_cmd ("all", class_run, thread_apply_all_command,
2349 thread_apply_all_help.c_str (),
2350 &thread_apply_list);
2351 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2353 c = add_com ("taas", class_run, taas_command, _("\
2354 Apply a command to all threads (ignoring errors and empty output).\n\
2355 Usage: taas [OPTION]... COMMAND\n\
2356 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2357 See \"help thread apply all\" for available options."));
2358 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2360 c = add_com ("tfaas", class_run, tfaas_command, _("\
2361 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2362 Usage: tfaas [OPTION]... COMMAND\n\
2363 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2364 See \"help frame apply all\" for available options."));
2365 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
2367 add_cmd ("name", class_run, thread_name_command,
2368 _("Set the current thread's name.\n\
2369 Usage: thread name [NAME]\n\
2370 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2372 add_cmd ("find", class_run, thread_find_command, _("\
2373 Find threads that match a regular expression.\n\
2374 Usage: thread find REGEXP\n\
2375 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2376 &thread_cmd_list);
2378 add_setshow_boolean_cmd ("thread-events", no_class,
2379 &print_thread_events, _("\
2380 Set printing of thread events (such as thread start and exit)."), _("\
2381 Show printing of thread events (such as thread start and exit)."), NULL,
2382 NULL,
2383 show_print_thread_events,
2384 &setprintlist, &showprintlist);
2386 add_setshow_boolean_cmd ("threads", class_maintenance, &debug_threads, _("\
2387 Set thread debugging."), _("\
2388 Show thread debugging."), _("\
2389 When on messages about thread creation and deletion are printed."),
2390 nullptr,
2391 show_debug_threads,
2392 &setdebuglist, &showdebuglist);
2394 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2395 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);
2396 create_internalvar_type_lazy ("_inferior_thread_count",
2397 &inferior_thread_count_funcs, NULL);