gdb/configure: Add --with-libgmp-prefix option
[binutils-gdb.git] / gdb / thread.c
blob32d14e8662c57d39a2943961b9301b5b402ab75e
1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2020 Free Software Foundation, Inc.
5 Contributed by Lynx Real-Time Systems, Inc. Los Gatos, CA.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "defs.h"
23 #include "symtab.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbsupport/environ.h"
27 #include "value.h"
28 #include "target.h"
29 #include "gdbthread.h"
30 #include "command.h"
31 #include "gdbcmd.h"
32 #include "regcache.h"
33 #include "btrace.h"
35 #include <ctype.h>
36 #include <sys/types.h>
37 #include <signal.h>
38 #include "ui-out.h"
39 #include "observable.h"
40 #include "annotate.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-option.h"
43 #include "gdb_regex.h"
44 #include "cli/cli-utils.h"
45 #include "thread-fsm.h"
46 #include "tid-parse.h"
47 #include <algorithm>
48 #include "gdbsupport/gdb_optional.h"
49 #include "inline-frame.h"
50 #include "stack.h"
52 /* Definition of struct thread_info exported to gdbthread.h. */
54 /* Prototypes for local functions. */
56 static int highest_thread_num;
58 /* The current/selected thread. */
59 static thread_info *current_thread_;
61 /* RAII type used to increase / decrease the refcount of each thread
62 in a given list of threads. */
64 class scoped_inc_dec_ref
66 public:
67 explicit scoped_inc_dec_ref (const std::vector<thread_info *> &thrds)
68 : m_thrds (thrds)
70 for (thread_info *thr : m_thrds)
71 thr->incref ();
74 ~scoped_inc_dec_ref ()
76 for (thread_info *thr : m_thrds)
77 thr->decref ();
80 private:
81 const std::vector<thread_info *> &m_thrds;
84 /* Returns true if THR is the current thread. */
86 static bool
87 is_current_thread (const thread_info *thr)
89 return thr == current_thread_;
92 struct thread_info*
93 inferior_thread (void)
95 gdb_assert (current_thread_ != nullptr);
96 return current_thread_;
99 /* Delete the breakpoint pointed at by BP_P, if there's one. */
101 static void
102 delete_thread_breakpoint (struct breakpoint **bp_p)
104 if (*bp_p != NULL)
106 delete_breakpoint (*bp_p);
107 *bp_p = NULL;
111 void
112 delete_step_resume_breakpoint (struct thread_info *tp)
114 if (tp != NULL)
115 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
118 void
119 delete_exception_resume_breakpoint (struct thread_info *tp)
121 if (tp != NULL)
122 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
125 /* See gdbthread.h. */
127 void
128 delete_single_step_breakpoints (struct thread_info *tp)
130 if (tp != NULL)
131 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
134 /* Delete the breakpoint pointed at by BP_P at the next stop, if
135 there's one. */
137 static void
138 delete_at_next_stop (struct breakpoint **bp)
140 if (*bp != NULL)
142 (*bp)->disposition = disp_del_at_next_stop;
143 *bp = NULL;
147 /* See gdbthread.h. */
150 thread_has_single_step_breakpoints_set (struct thread_info *tp)
152 return tp->control.single_step_breakpoints != NULL;
155 /* See gdbthread.h. */
158 thread_has_single_step_breakpoint_here (struct thread_info *tp,
159 const address_space *aspace,
160 CORE_ADDR addr)
162 struct breakpoint *ss_bps = tp->control.single_step_breakpoints;
164 return (ss_bps != NULL
165 && breakpoint_has_location_inserted_here (ss_bps, aspace, addr));
168 /* See gdbthread.h. */
170 void
171 thread_cancel_execution_command (struct thread_info *thr)
173 if (thr->thread_fsm != NULL)
175 thr->thread_fsm->clean_up (thr);
176 delete thr->thread_fsm;
177 thr->thread_fsm = NULL;
181 static void
182 clear_thread_inferior_resources (struct thread_info *tp)
184 /* NOTE: this will take care of any left-over step_resume breakpoints,
185 but not any user-specified thread-specific breakpoints. We can not
186 delete the breakpoint straight-off, because the inferior might not
187 be stopped at the moment. */
188 delete_at_next_stop (&tp->control.step_resume_breakpoint);
189 delete_at_next_stop (&tp->control.exception_resume_breakpoint);
190 delete_at_next_stop (&tp->control.single_step_breakpoints);
192 delete_longjmp_breakpoint_at_next_stop (tp->global_num);
194 bpstat_clear (&tp->control.stop_bpstat);
196 btrace_teardown (tp);
198 thread_cancel_execution_command (tp);
200 clear_inline_frame_state (tp);
203 /* Set the TP's state as exited. */
205 static void
206 set_thread_exited (thread_info *tp, bool silent)
208 /* Dead threads don't need to step-over. Remove from queue. */
209 if (tp->step_over_next != NULL)
210 thread_step_over_chain_remove (tp);
212 if (tp->state != THREAD_EXITED)
214 gdb::observers::thread_exit.notify (tp, silent);
216 /* Tag it as exited. */
217 tp->state = THREAD_EXITED;
219 /* Clear breakpoints, etc. associated with this thread. */
220 clear_thread_inferior_resources (tp);
224 void
225 init_thread_list (void)
227 highest_thread_num = 0;
229 for (thread_info *tp : all_threads_safe ())
231 inferior *inf = tp->inf;
233 if (tp->deletable ())
234 delete tp;
235 else
236 set_thread_exited (tp, 1);
238 inf->thread_list = NULL;
242 /* Allocate a new thread of inferior INF with target id PTID and add
243 it to the thread list. */
245 static struct thread_info *
246 new_thread (struct inferior *inf, ptid_t ptid)
248 thread_info *tp = new thread_info (inf, ptid);
250 if (inf->thread_list == NULL)
251 inf->thread_list = tp;
252 else
254 struct thread_info *last;
256 for (last = inf->thread_list; last->next != NULL; last = last->next)
257 gdb_assert (ptid != last->ptid
258 || last->state == THREAD_EXITED);
260 gdb_assert (ptid != last->ptid
261 || last->state == THREAD_EXITED);
263 last->next = tp;
266 return tp;
269 struct thread_info *
270 add_thread_silent (process_stratum_target *targ, ptid_t ptid)
272 inferior *inf = find_inferior_ptid (targ, ptid);
274 /* We may have an old thread with the same id in the thread list.
275 If we do, it must be dead, otherwise we wouldn't be adding a new
276 thread with the same id. The OS is reusing this id --- delete
277 the old thread, and create a new one. */
278 thread_info *tp = find_thread_ptid (inf, ptid);
279 if (tp != nullptr)
280 delete_thread (tp);
282 tp = new_thread (inf, ptid);
283 gdb::observers::new_thread.notify (tp);
285 return tp;
288 struct thread_info *
289 add_thread_with_info (process_stratum_target *targ, ptid_t ptid,
290 private_thread_info *priv)
292 thread_info *result = add_thread_silent (targ, ptid);
294 result->priv.reset (priv);
296 if (print_thread_events)
297 printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid).c_str ());
299 annotate_new_thread ();
300 return result;
303 struct thread_info *
304 add_thread (process_stratum_target *targ, ptid_t ptid)
306 return add_thread_with_info (targ, ptid, NULL);
309 private_thread_info::~private_thread_info () = default;
311 thread_info::thread_info (struct inferior *inf_, ptid_t ptid_)
312 : ptid (ptid_), inf (inf_)
314 gdb_assert (inf_ != NULL);
316 this->global_num = ++highest_thread_num;
317 this->per_inf_num = ++inf_->highest_thread_num;
319 /* Nothing to follow yet. */
320 memset (&this->pending_follow, 0, sizeof (this->pending_follow));
321 this->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
322 this->suspend.waitstatus.kind = TARGET_WAITKIND_IGNORE;
325 thread_info::~thread_info ()
327 xfree (this->name);
330 /* See gdbthread.h. */
332 bool
333 thread_info::deletable () const
335 /* If this is the current thread, or there's code out there that
336 relies on it existing (refcount > 0) we can't delete yet. */
337 return refcount () == 0 && !is_current_thread (this);
340 /* Add TP to the end of the step-over chain LIST_P. */
342 static void
343 step_over_chain_enqueue (struct thread_info **list_p, struct thread_info *tp)
345 gdb_assert (tp->step_over_next == NULL);
346 gdb_assert (tp->step_over_prev == NULL);
348 if (*list_p == NULL)
350 *list_p = tp;
351 tp->step_over_prev = tp->step_over_next = tp;
353 else
355 struct thread_info *head = *list_p;
356 struct thread_info *tail = head->step_over_prev;
358 tp->step_over_prev = tail;
359 tp->step_over_next = head;
360 head->step_over_prev = tp;
361 tail->step_over_next = tp;
365 /* Remove TP from step-over chain LIST_P. */
367 static void
368 step_over_chain_remove (struct thread_info **list_p, struct thread_info *tp)
370 gdb_assert (tp->step_over_next != NULL);
371 gdb_assert (tp->step_over_prev != NULL);
373 if (*list_p == tp)
375 if (tp == tp->step_over_next)
376 *list_p = NULL;
377 else
378 *list_p = tp->step_over_next;
381 tp->step_over_prev->step_over_next = tp->step_over_next;
382 tp->step_over_next->step_over_prev = tp->step_over_prev;
383 tp->step_over_prev = tp->step_over_next = NULL;
386 /* See gdbthread.h. */
388 struct thread_info *
389 thread_step_over_chain_next (struct thread_info *tp)
391 struct thread_info *next = tp->step_over_next;
393 return (next == step_over_queue_head ? NULL : next);
396 /* See gdbthread.h. */
399 thread_is_in_step_over_chain (struct thread_info *tp)
401 return (tp->step_over_next != NULL);
404 /* See gdbthread.h. */
406 void
407 thread_step_over_chain_enqueue (struct thread_info *tp)
409 step_over_chain_enqueue (&step_over_queue_head, tp);
412 /* See gdbthread.h. */
414 void
415 thread_step_over_chain_remove (struct thread_info *tp)
417 step_over_chain_remove (&step_over_queue_head, tp);
420 /* Delete the thread referenced by THR. If SILENT, don't notify
421 the observer of this exit.
423 THR must not be NULL or a failed assertion will be raised. */
425 static void
426 delete_thread_1 (thread_info *thr, bool silent)
428 gdb_assert (thr != nullptr);
430 struct thread_info *tp, *tpprev = NULL;
432 for (tp = thr->inf->thread_list; tp; tpprev = tp, tp = tp->next)
433 if (tp == thr)
434 break;
436 if (!tp)
437 return;
439 set_thread_exited (tp, silent);
441 if (!tp->deletable ())
443 /* Will be really deleted some other time. */
444 return;
447 if (tpprev)
448 tpprev->next = tp->next;
449 else
450 tp->inf->thread_list = tp->next;
452 delete tp;
455 /* See gdbthread.h. */
457 void
458 delete_thread (thread_info *thread)
460 delete_thread_1 (thread, false /* not silent */);
463 void
464 delete_thread_silent (thread_info *thread)
466 delete_thread_1 (thread, true /* silent */);
469 struct thread_info *
470 find_thread_global_id (int global_id)
472 for (thread_info *tp : all_threads ())
473 if (tp->global_num == global_id)
474 return tp;
476 return NULL;
479 static struct thread_info *
480 find_thread_id (struct inferior *inf, int thr_num)
482 for (thread_info *tp : inf->threads ())
483 if (tp->per_inf_num == thr_num)
484 return tp;
486 return NULL;
489 /* See gdbthread.h. */
491 struct thread_info *
492 find_thread_ptid (process_stratum_target *targ, ptid_t ptid)
494 inferior *inf = find_inferior_ptid (targ, ptid);
495 if (inf == NULL)
496 return NULL;
497 return find_thread_ptid (inf, ptid);
500 /* See gdbthread.h. */
502 struct thread_info *
503 find_thread_ptid (inferior *inf, ptid_t ptid)
505 for (thread_info *tp : inf->non_exited_threads ())
506 if (tp->ptid == ptid)
507 return tp;
509 return NULL;
512 /* See gdbthread.h. */
514 struct thread_info *
515 find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
516 struct inferior *inf)
518 return target_thread_handle_to_thread_info (handle.data (),
519 handle.size (),
520 inf);
524 * Thread iterator function.
526 * Calls a callback function once for each thread, so long as
527 * the callback function returns false. If the callback function
528 * returns true, the iteration will end and the current thread
529 * will be returned. This can be useful for implementing a
530 * search for a thread with arbitrary attributes, or for applying
531 * some operation to every thread.
533 * FIXME: some of the existing functionality, such as
534 * "Thread apply all", might be rewritten using this functionality.
537 struct thread_info *
538 iterate_over_threads (int (*callback) (struct thread_info *, void *),
539 void *data)
541 for (thread_info *tp : all_threads_safe ())
542 if ((*callback) (tp, data))
543 return tp;
545 return NULL;
548 /* See gdbthread.h. */
550 bool
551 any_thread_p ()
553 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
554 return true;
555 return false;
559 thread_count (process_stratum_target *proc_target)
561 auto rng = all_threads (proc_target);
562 return std::distance (rng.begin (), rng.end ());
565 /* Return the number of non-exited threads in the thread list. */
567 static int
568 live_threads_count (void)
570 auto rng = all_non_exited_threads ();
571 return std::distance (rng.begin (), rng.end ());
575 valid_global_thread_id (int global_id)
577 for (thread_info *tp : all_threads ())
578 if (tp->global_num == global_id)
579 return 1;
581 return 0;
584 bool
585 in_thread_list (process_stratum_target *targ, ptid_t ptid)
587 return find_thread_ptid (targ, ptid) != nullptr;
590 /* Finds the first thread of the inferior. */
592 thread_info *
593 first_thread_of_inferior (inferior *inf)
595 return inf->thread_list;
598 thread_info *
599 any_thread_of_inferior (inferior *inf)
601 gdb_assert (inf->pid != 0);
603 /* Prefer the current thread. */
604 if (inf == current_inferior ())
605 return inferior_thread ();
607 for (thread_info *tp : inf->non_exited_threads ())
608 return tp;
610 return NULL;
613 thread_info *
614 any_live_thread_of_inferior (inferior *inf)
616 struct thread_info *curr_tp = NULL;
617 struct thread_info *tp_executing = NULL;
619 gdb_assert (inf != NULL && inf->pid != 0);
621 /* Prefer the current thread if it's not executing. */
622 if (inferior_ptid != null_ptid && current_inferior () == inf)
624 /* If the current thread is dead, forget it. If it's not
625 executing, use it. Otherwise, still choose it (below), but
626 only if no other non-executing thread is found. */
627 curr_tp = inferior_thread ();
628 if (curr_tp->state == THREAD_EXITED)
629 curr_tp = NULL;
630 else if (!curr_tp->executing)
631 return curr_tp;
634 for (thread_info *tp : inf->non_exited_threads ())
636 if (!tp->executing)
637 return tp;
639 tp_executing = tp;
642 /* If both the current thread and all live threads are executing,
643 prefer the current thread. */
644 if (curr_tp != NULL)
645 return curr_tp;
647 /* Otherwise, just return an executing thread, if any. */
648 return tp_executing;
651 /* Return true if TP is an active thread. */
652 static bool
653 thread_alive (thread_info *tp)
655 if (tp->state == THREAD_EXITED)
656 return false;
658 /* Ensure we're looking at the right target stack. */
659 gdb_assert (tp->inf == current_inferior ());
661 return target_thread_alive (tp->ptid);
664 /* Switch to thread TP if it is alive. Returns true if successfully
665 switched, false otherwise. */
667 static bool
668 switch_to_thread_if_alive (thread_info *thr)
670 scoped_restore_current_thread restore_thread;
672 /* Switch inferior first, so that we're looking at the right target
673 stack. */
674 switch_to_inferior_no_thread (thr->inf);
676 if (thread_alive (thr))
678 switch_to_thread (thr);
679 restore_thread.dont_restore ();
680 return true;
683 return false;
686 /* See gdbthreads.h. */
688 void
689 prune_threads (void)
691 scoped_restore_current_thread restore_thread;
693 for (thread_info *tp : all_threads_safe ())
695 switch_to_inferior_no_thread (tp->inf);
697 if (!thread_alive (tp))
698 delete_thread (tp);
702 /* See gdbthreads.h. */
704 void
705 delete_exited_threads (void)
707 for (thread_info *tp : all_threads_safe ())
708 if (tp->state == THREAD_EXITED)
709 delete_thread (tp);
712 /* Return true value if stack temporaries are enabled for the thread
713 TP. */
715 bool
716 thread_stack_temporaries_enabled_p (thread_info *tp)
718 if (tp == NULL)
719 return false;
720 else
721 return tp->stack_temporaries_enabled;
724 /* Push V on to the stack temporaries of the thread with id PTID. */
726 void
727 push_thread_stack_temporary (thread_info *tp, struct value *v)
729 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
730 tp->stack_temporaries.push_back (v);
733 /* Return true if VAL is among the stack temporaries of the thread
734 TP. Return false otherwise. */
736 bool
737 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
739 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
740 for (value *v : tp->stack_temporaries)
741 if (v == val)
742 return true;
744 return false;
747 /* Return the last of the stack temporaries for thread with id PTID.
748 Return NULL if there are no stack temporaries for the thread. */
750 value *
751 get_last_thread_stack_temporary (thread_info *tp)
753 struct value *lastval = NULL;
755 gdb_assert (tp != NULL);
756 if (!tp->stack_temporaries.empty ())
757 lastval = tp->stack_temporaries.back ();
759 return lastval;
762 void
763 thread_change_ptid (process_stratum_target *targ,
764 ptid_t old_ptid, ptid_t new_ptid)
766 struct inferior *inf;
767 struct thread_info *tp;
769 /* It can happen that what we knew as the target inferior id
770 changes. E.g, target remote may only discover the remote process
771 pid after adding the inferior to GDB's list. */
772 inf = find_inferior_ptid (targ, old_ptid);
773 inf->pid = new_ptid.pid ();
775 tp = find_thread_ptid (inf, old_ptid);
776 tp->ptid = new_ptid;
778 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
781 /* See gdbthread.h. */
783 void
784 set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
786 for (thread_info *tp : all_non_exited_threads (targ, ptid))
787 tp->resumed = resumed;
790 /* Helper for set_running, that marks one thread either running or
791 stopped. */
793 static bool
794 set_running_thread (struct thread_info *tp, bool running)
796 bool started = false;
798 if (running && tp->state == THREAD_STOPPED)
799 started = true;
800 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
802 if (!running)
804 /* If the thread is now marked stopped, remove it from
805 the step-over queue, so that we don't try to resume
806 it until the user wants it to. */
807 if (tp->step_over_next != NULL)
808 thread_step_over_chain_remove (tp);
811 return started;
814 /* See gdbthread.h. */
816 void
817 thread_info::set_running (bool running)
819 if (set_running_thread (this, running))
820 gdb::observers::target_resumed.notify (this->ptid);
823 void
824 set_running (process_stratum_target *targ, ptid_t ptid, bool running)
826 /* We try not to notify the observer if no thread has actually
827 changed the running state -- merely to reduce the number of
828 messages to the MI frontend. A frontend is supposed to handle
829 multiple *running notifications just fine. */
830 bool any_started = false;
832 for (thread_info *tp : all_non_exited_threads (targ, ptid))
833 if (set_running_thread (tp, running))
834 any_started = true;
836 if (any_started)
837 gdb::observers::target_resumed.notify (ptid);
841 /* Helper for set_executing. Set's the thread's 'executing' field
842 from EXECUTING, and if EXECUTING is true also clears the thread's
843 stop_pc. */
845 static void
846 set_executing_thread (thread_info *thr, bool executing)
848 thr->executing = executing;
849 if (executing)
850 thr->suspend.stop_pc = ~(CORE_ADDR) 0;
853 void
854 set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
856 for (thread_info *tp : all_non_exited_threads (targ, ptid))
857 set_executing_thread (tp, executing);
859 /* It only takes one running thread to spawn more threads. */
860 if (executing)
861 targ->threads_executing = true;
862 /* Only clear the flag if the caller is telling us everything is
863 stopped. */
864 else if (minus_one_ptid == ptid)
865 targ->threads_executing = false;
868 /* See gdbthread.h. */
870 bool
871 threads_are_executing (process_stratum_target *target)
873 return target->threads_executing;
876 void
877 set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
879 for (thread_info *tp : all_non_exited_threads (targ, ptid))
880 tp->stop_requested = stop;
882 /* Call the stop requested observer so other components of GDB can
883 react to this request. */
884 if (stop)
885 gdb::observers::thread_stop_requested.notify (ptid);
888 void
889 finish_thread_state (process_stratum_target *targ, ptid_t ptid)
891 bool any_started = false;
893 for (thread_info *tp : all_non_exited_threads (targ, ptid))
894 if (set_running_thread (tp, tp->executing))
895 any_started = true;
897 if (any_started)
898 gdb::observers::target_resumed.notify (ptid);
901 /* See gdbthread.h. */
903 void
904 validate_registers_access (void)
906 /* No selected thread, no registers. */
907 if (inferior_ptid == null_ptid)
908 error (_("No thread selected."));
910 thread_info *tp = inferior_thread ();
912 /* Don't try to read from a dead thread. */
913 if (tp->state == THREAD_EXITED)
914 error (_("The current thread has terminated"));
916 /* ... or from a spinning thread. FIXME: This isn't actually fully
917 correct. It'll allow an user-requested access (e.g., "print $pc"
918 at the prompt) when a thread is not executing for some internal
919 reason, but is marked running from the user's perspective. E.g.,
920 the thread is waiting for its turn in the step-over queue. */
921 if (tp->executing)
922 error (_("Selected thread is running."));
925 /* See gdbthread.h. */
927 bool
928 can_access_registers_thread (thread_info *thread)
930 /* No thread, no registers. */
931 if (thread == NULL)
932 return false;
934 /* Don't try to read from a dead thread. */
935 if (thread->state == THREAD_EXITED)
936 return false;
938 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
939 if (thread->executing)
940 return false;
942 return true;
946 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
948 return (pc >= thread->control.step_range_start
949 && pc < thread->control.step_range_end);
952 /* Helper for print_thread_info. Returns true if THR should be
953 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
954 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
955 is true if REQUESTED_THREADS is list of global IDs, false if a list
956 of per-inferior thread ids. If PID is not -1, only print THR if it
957 is a thread from the process PID. Otherwise, threads from all
958 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
959 and PID is not -1, then the thread is printed if it belongs to the
960 specified process. Otherwise, an error is raised. */
962 static int
963 should_print_thread (const char *requested_threads, int default_inf_num,
964 int global_ids, int pid, struct thread_info *thr)
966 if (requested_threads != NULL && *requested_threads != '\0')
968 int in_list;
970 if (global_ids)
971 in_list = number_is_in_list (requested_threads, thr->global_num);
972 else
973 in_list = tid_is_in_list (requested_threads, default_inf_num,
974 thr->inf->num, thr->per_inf_num);
975 if (!in_list)
976 return 0;
979 if (pid != -1 && thr->ptid.pid () != pid)
981 if (requested_threads != NULL && *requested_threads != '\0')
982 error (_("Requested thread not found in requested process"));
983 return 0;
986 if (thr->state == THREAD_EXITED)
987 return 0;
989 return 1;
992 /* Return the string to display in "info threads"'s "Target Id"
993 column, for TP. */
995 static std::string
996 thread_target_id_str (thread_info *tp)
998 std::string target_id = target_pid_to_str (tp->ptid);
999 const char *extra_info = target_extra_thread_info (tp);
1000 const char *name = tp->name != nullptr ? tp->name : target_thread_name (tp);
1002 if (extra_info != nullptr && name != nullptr)
1003 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1004 extra_info);
1005 else if (extra_info != nullptr)
1006 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1007 else if (name != nullptr)
1008 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1009 else
1010 return target_id;
1013 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1014 whether REQUESTED_THREADS is a list of global or per-inferior
1015 thread ids. */
1017 static void
1018 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1019 int global_ids, int pid,
1020 int show_global_ids)
1022 int default_inf_num = current_inferior ()->num;
1024 update_thread_list ();
1026 /* Whether we saw any thread. */
1027 bool any_thread = false;
1028 /* Whether the current thread is exited. */
1029 bool current_exited = false;
1031 thread_info *current_thread = (inferior_ptid != null_ptid
1032 ? inferior_thread () : NULL);
1035 /* For backward compatibility, we make a list for MI. A table is
1036 preferable for the CLI, though, because it shows table
1037 headers. */
1038 gdb::optional<ui_out_emit_list> list_emitter;
1039 gdb::optional<ui_out_emit_table> table_emitter;
1041 /* We'll be switching threads temporarily below. */
1042 scoped_restore_current_thread restore_thread;
1044 if (uiout->is_mi_like_p ())
1045 list_emitter.emplace (uiout, "threads");
1046 else
1048 int n_threads = 0;
1049 /* The width of the "Target Id" column. Grown below to
1050 accommodate the largest entry. */
1051 size_t target_id_col_width = 17;
1053 for (thread_info *tp : all_threads ())
1055 if (!should_print_thread (requested_threads, default_inf_num,
1056 global_ids, pid, tp))
1057 continue;
1059 if (!uiout->is_mi_like_p ())
1061 /* Switch inferiors so we're looking at the right
1062 target stack. */
1063 switch_to_inferior_no_thread (tp->inf);
1065 target_id_col_width
1066 = std::max (target_id_col_width,
1067 thread_target_id_str (tp).size ());
1070 ++n_threads;
1073 if (n_threads == 0)
1075 if (requested_threads == NULL || *requested_threads == '\0')
1076 uiout->message (_("No threads.\n"));
1077 else
1078 uiout->message (_("No threads match '%s'.\n"),
1079 requested_threads);
1080 return;
1083 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1084 n_threads, "threads");
1086 uiout->table_header (1, ui_left, "current", "");
1087 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1088 if (show_global_ids)
1089 uiout->table_header (4, ui_left, "id", "GId");
1090 uiout->table_header (target_id_col_width, ui_left,
1091 "target-id", "Target Id");
1092 uiout->table_header (1, ui_left, "frame", "Frame");
1093 uiout->table_body ();
1096 for (inferior *inf : all_inferiors ())
1097 for (thread_info *tp : inf->threads ())
1099 int core;
1101 any_thread = true;
1102 if (tp == current_thread && tp->state == THREAD_EXITED)
1103 current_exited = true;
1105 if (!should_print_thread (requested_threads, default_inf_num,
1106 global_ids, pid, tp))
1107 continue;
1109 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1111 if (!uiout->is_mi_like_p ())
1113 if (tp == current_thread)
1114 uiout->field_string ("current", "*");
1115 else
1116 uiout->field_skip ("current");
1118 uiout->field_string ("id-in-tg", print_thread_id (tp));
1121 if (show_global_ids || uiout->is_mi_like_p ())
1122 uiout->field_signed ("id", tp->global_num);
1124 /* Switch to the thread (and inferior / target). */
1125 switch_to_thread (tp);
1127 /* For the CLI, we stuff everything into the target-id field.
1128 This is a gross hack to make the output come out looking
1129 correct. The underlying problem here is that ui-out has no
1130 way to specify that a field's space allocation should be
1131 shared by several fields. For MI, we do the right thing
1132 instead. */
1134 if (uiout->is_mi_like_p ())
1136 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1138 const char *extra_info = target_extra_thread_info (tp);
1139 if (extra_info != nullptr)
1140 uiout->field_string ("details", extra_info);
1142 const char *name = (tp->name != nullptr
1143 ? tp->name
1144 : target_thread_name (tp));
1145 if (name != NULL)
1146 uiout->field_string ("name", name);
1148 else
1150 uiout->field_string ("target-id",
1151 thread_target_id_str (tp).c_str ());
1154 if (tp->state == THREAD_RUNNING)
1155 uiout->text ("(running)\n");
1156 else
1158 /* The switch above put us at the top of the stack (leaf
1159 frame). */
1160 print_stack_frame (get_selected_frame (NULL),
1161 /* For MI output, print frame level. */
1162 uiout->is_mi_like_p (),
1163 LOCATION, 0);
1166 if (uiout->is_mi_like_p ())
1168 const char *state = "stopped";
1170 if (tp->state == THREAD_RUNNING)
1171 state = "running";
1172 uiout->field_string ("state", state);
1175 core = target_core_of_thread (tp->ptid);
1176 if (uiout->is_mi_like_p () && core != -1)
1177 uiout->field_signed ("core", core);
1180 /* This end scope restores the current thread and the frame
1181 selected before the "info threads" command, and it finishes the
1182 ui-out list or table. */
1185 if (pid == -1 && requested_threads == NULL)
1187 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1188 uiout->field_signed ("current-thread-id", current_thread->global_num);
1190 if (inferior_ptid != null_ptid && current_exited)
1191 uiout->message ("\n\
1192 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1193 print_thread_id (inferior_thread ()));
1194 else if (any_thread && inferior_ptid == null_ptid)
1195 uiout->message ("\n\
1196 No selected thread. See `help thread'.\n");
1200 /* See gdbthread.h. */
1202 void
1203 print_thread_info (struct ui_out *uiout, const char *requested_threads,
1204 int pid)
1206 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1209 /* The options for the "info threads" command. */
1211 struct info_threads_opts
1213 /* For "-gid". */
1214 bool show_global_ids = false;
1217 static const gdb::option::option_def info_threads_option_defs[] = {
1219 gdb::option::flag_option_def<info_threads_opts> {
1220 "gid",
1221 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1222 N_("Show global thread IDs."),
1227 /* Create an option_def_group for the "info threads" options, with
1228 IT_OPTS as context. */
1230 static inline gdb::option::option_def_group
1231 make_info_threads_options_def_group (info_threads_opts *it_opts)
1233 return {{info_threads_option_defs}, it_opts};
1236 /* Implementation of the "info threads" command.
1238 Note: this has the drawback that it _really_ switches
1239 threads, which frees the frame cache. A no-side
1240 effects info-threads command would be nicer. */
1242 static void
1243 info_threads_command (const char *arg, int from_tty)
1245 info_threads_opts it_opts;
1247 auto grp = make_info_threads_options_def_group (&it_opts);
1248 gdb::option::process_options
1249 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1251 print_thread_info_1 (current_uiout, arg, 0, -1, it_opts.show_global_ids);
1254 /* Completer for the "info threads" command. */
1256 static void
1257 info_threads_command_completer (struct cmd_list_element *ignore,
1258 completion_tracker &tracker,
1259 const char *text, const char *word_ignored)
1261 const auto grp = make_info_threads_options_def_group (nullptr);
1263 if (gdb::option::complete_options
1264 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1265 return;
1267 /* Convenience to let the user know what the option can accept. */
1268 if (*text == '\0')
1270 gdb::option::complete_on_all_options (tracker, grp);
1271 /* Keep this "ID" in sync with what "help info threads"
1272 says. */
1273 tracker.add_completion (make_unique_xstrdup ("ID"));
1277 /* See gdbthread.h. */
1279 void
1280 switch_to_thread_no_regs (struct thread_info *thread)
1282 struct inferior *inf = thread->inf;
1284 set_current_program_space (inf->pspace);
1285 set_current_inferior (inf);
1287 current_thread_ = thread;
1288 inferior_ptid = current_thread_->ptid;
1291 /* See gdbthread.h. */
1293 void
1294 switch_to_no_thread ()
1296 if (current_thread_ == nullptr)
1297 return;
1299 current_thread_ = nullptr;
1300 inferior_ptid = null_ptid;
1301 reinit_frame_cache ();
1304 /* See gdbthread.h. */
1306 void
1307 switch_to_thread (thread_info *thr)
1309 gdb_assert (thr != NULL);
1311 if (is_current_thread (thr))
1312 return;
1314 switch_to_thread_no_regs (thr);
1316 reinit_frame_cache ();
1319 /* See gdbsupport/common-gdbthread.h. */
1321 void
1322 switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
1324 thread_info *thr = find_thread_ptid (proc_target, ptid);
1325 switch_to_thread (thr);
1328 /* See frame.h. */
1330 void
1331 scoped_restore_current_thread::restore ()
1333 /* If an entry of thread_info was previously selected, it won't be
1334 deleted because we've increased its refcount. The thread represented
1335 by this thread_info entry may have already exited (due to normal exit,
1336 detach, etc), so the thread_info.state is THREAD_EXITED. */
1337 if (m_thread != NULL
1338 /* If the previously selected thread belonged to a process that has
1339 in the mean time exited (or killed, detached, etc.), then don't revert
1340 back to it, but instead simply drop back to no thread selected. */
1341 && m_inf->pid != 0)
1342 switch_to_thread (m_thread.get ());
1343 else
1344 switch_to_inferior_no_thread (m_inf.get ());
1346 /* The running state of the originally selected thread may have
1347 changed, so we have to recheck it here. */
1348 if (inferior_ptid != null_ptid
1349 && m_was_stopped
1350 && m_thread->state == THREAD_STOPPED
1351 && target_has_registers ()
1352 && target_has_stack ()
1353 && target_has_memory ())
1354 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1356 set_language (m_lang);
1359 scoped_restore_current_thread::~scoped_restore_current_thread ()
1361 if (!m_dont_restore)
1362 restore ();
1365 scoped_restore_current_thread::scoped_restore_current_thread ()
1367 m_inf = inferior_ref::new_reference (current_inferior ());
1369 m_lang = current_language->la_language;
1371 if (inferior_ptid != null_ptid)
1373 m_thread = thread_info_ref::new_reference (inferior_thread ());
1375 m_was_stopped = m_thread->state == THREAD_STOPPED;
1376 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
1380 /* See gdbthread.h. */
1383 show_thread_that_caused_stop (void)
1385 return highest_thread_num > 1;
1388 /* See gdbthread.h. */
1391 show_inferior_qualified_tids (void)
1393 return (inferior_list->next != NULL || inferior_list->num != 1);
1396 /* See gdbthread.h. */
1398 const char *
1399 print_thread_id (struct thread_info *thr)
1401 char *s = get_print_cell ();
1403 if (show_inferior_qualified_tids ())
1404 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1405 else
1406 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1407 return s;
1410 /* Sort an array of struct thread_info pointers by thread ID (first by
1411 inferior number, and then by per-inferior thread number). Sorts in
1412 ascending order. */
1414 static bool
1415 tp_array_compar_ascending (const thread_info *a, const thread_info *b)
1417 if (a->inf->num != b->inf->num)
1418 return a->inf->num < b->inf->num;
1420 return (a->per_inf_num < b->per_inf_num);
1423 /* Sort an array of struct thread_info pointers by thread ID (first by
1424 inferior number, and then by per-inferior thread number). Sorts in
1425 descending order. */
1427 static bool
1428 tp_array_compar_descending (const thread_info *a, const thread_info *b)
1430 if (a->inf->num != b->inf->num)
1431 return a->inf->num > b->inf->num;
1433 return (a->per_inf_num > b->per_inf_num);
1436 /* Switch to thread THR and execute CMD.
1437 FLAGS.QUIET controls the printing of the thread information.
1438 FLAGS.CONT and FLAGS.SILENT control how to handle errors. */
1440 static void
1441 thr_try_catch_cmd (thread_info *thr, const char *cmd, int from_tty,
1442 const qcs_flags &flags)
1444 switch_to_thread (thr);
1446 /* The thread header is computed before running the command since
1447 the command can change the inferior, which is not permitted
1448 by thread_target_id_str. */
1449 std::string thr_header =
1450 string_printf (_("\nThread %s (%s):\n"), print_thread_id (thr),
1451 thread_target_id_str (thr).c_str ());
1455 std::string cmd_result = execute_command_to_string
1456 (cmd, from_tty, gdb_stdout->term_out ());
1457 if (!flags.silent || cmd_result.length () > 0)
1459 if (!flags.quiet)
1460 printf_filtered ("%s", thr_header.c_str ());
1461 printf_filtered ("%s", cmd_result.c_str ());
1464 catch (const gdb_exception_error &ex)
1466 if (!flags.silent)
1468 if (!flags.quiet)
1469 printf_filtered ("%s", thr_header.c_str ());
1470 if (flags.cont)
1471 printf_filtered ("%s\n", ex.what ());
1472 else
1473 throw;
1478 /* Option definition of "thread apply"'s "-ascending" option. */
1480 static const gdb::option::flag_option_def<> ascending_option_def = {
1481 "ascending",
1482 N_("\
1483 Call COMMAND for all threads in ascending order.\n\
1484 The default is descending order."),
1487 /* The qcs command line flags for the "thread apply" commands. Keep
1488 this in sync with the "frame apply" commands. */
1490 using qcs_flag_option_def
1491 = gdb::option::flag_option_def<qcs_flags>;
1493 static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1494 qcs_flag_option_def {
1495 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1496 N_("Disables printing the thread information."),
1499 qcs_flag_option_def {
1500 "c", [] (qcs_flags *opt) { return &opt->cont; },
1501 N_("Print any error raised by COMMAND and continue."),
1504 qcs_flag_option_def {
1505 "s", [] (qcs_flags *opt) { return &opt->silent; },
1506 N_("Silently ignore any errors or empty output produced by COMMAND."),
1510 /* Create an option_def_group for the "thread apply all" options, with
1511 ASCENDING and FLAGS as context. */
1513 static inline std::array<gdb::option::option_def_group, 2>
1514 make_thread_apply_all_options_def_group (bool *ascending,
1515 qcs_flags *flags)
1517 return {{
1518 { {ascending_option_def.def ()}, ascending},
1519 { {thr_qcs_flags_option_defs}, flags },
1523 /* Create an option_def_group for the "thread apply" options, with
1524 FLAGS as context. */
1526 static inline gdb::option::option_def_group
1527 make_thread_apply_options_def_group (qcs_flags *flags)
1529 return {{thr_qcs_flags_option_defs}, flags};
1532 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1533 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1534 of two numbers separated by a hyphen. Examples:
1536 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1537 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1538 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1540 static void
1541 thread_apply_all_command (const char *cmd, int from_tty)
1543 bool ascending = false;
1544 qcs_flags flags;
1546 auto group = make_thread_apply_all_options_def_group (&ascending,
1547 &flags);
1548 gdb::option::process_options
1549 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1551 validate_flags_qcs ("thread apply all", &flags);
1553 if (cmd == NULL || *cmd == '\000')
1554 error (_("Please specify a command at the end of 'thread apply all'"));
1556 update_thread_list ();
1558 int tc = live_threads_count ();
1559 if (tc != 0)
1561 /* Save a copy of the thread list and increment each thread's
1562 refcount while executing the command in the context of each
1563 thread, in case the command is one that wipes threads. E.g.,
1564 detach, kill, disconnect, etc., or even normally continuing
1565 over an inferior or thread exit. */
1566 std::vector<thread_info *> thr_list_cpy;
1567 thr_list_cpy.reserve (tc);
1569 for (thread_info *tp : all_non_exited_threads ())
1570 thr_list_cpy.push_back (tp);
1571 gdb_assert (thr_list_cpy.size () == tc);
1573 /* Increment the refcounts, and restore them back on scope
1574 exit. */
1575 scoped_inc_dec_ref inc_dec_ref (thr_list_cpy);
1577 auto *sorter = (ascending
1578 ? tp_array_compar_ascending
1579 : tp_array_compar_descending);
1580 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
1582 scoped_restore_current_thread restore_thread;
1584 for (thread_info *thr : thr_list_cpy)
1585 if (switch_to_thread_if_alive (thr))
1586 thr_try_catch_cmd (thr, cmd, from_tty, flags);
1590 /* Completer for "thread apply [ID list]". */
1592 static void
1593 thread_apply_command_completer (cmd_list_element *ignore,
1594 completion_tracker &tracker,
1595 const char *text, const char * /*word*/)
1597 /* Don't leave this to complete_options because there's an early
1598 return below. */
1599 tracker.set_use_custom_word_point (true);
1601 tid_range_parser parser;
1602 parser.init (text, current_inferior ()->num);
1606 while (!parser.finished ())
1608 int inf_num, thr_start, thr_end;
1610 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1611 break;
1613 if (parser.in_star_range () || parser.in_thread_range ())
1614 parser.skip_range ();
1617 catch (const gdb_exception_error &ex)
1619 /* get_tid_range throws if it parses a negative number, for
1620 example. But a seemingly negative number may be the start of
1621 an option instead. */
1624 const char *cmd = parser.cur_tok ();
1626 if (cmd == text)
1628 /* No thread ID list yet. */
1629 return;
1632 /* Check if we're past a valid thread ID list already. */
1633 if (parser.finished ()
1634 && cmd > text && !isspace (cmd[-1]))
1635 return;
1637 /* We're past the thread ID list, advance word point. */
1638 tracker.advance_custom_word_point_by (cmd - text);
1639 text = cmd;
1641 const auto group = make_thread_apply_options_def_group (nullptr);
1642 if (gdb::option::complete_options
1643 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1644 return;
1646 complete_nested_command_line (tracker, text);
1649 /* Completer for "thread apply all". */
1651 static void
1652 thread_apply_all_command_completer (cmd_list_element *ignore,
1653 completion_tracker &tracker,
1654 const char *text, const char *word)
1656 const auto group = make_thread_apply_all_options_def_group (nullptr,
1657 nullptr);
1658 if (gdb::option::complete_options
1659 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1660 return;
1662 complete_nested_command_line (tracker, text);
1665 /* Implementation of the "thread apply" command. */
1667 static void
1668 thread_apply_command (const char *tidlist, int from_tty)
1670 qcs_flags flags;
1671 const char *cmd = NULL;
1672 tid_range_parser parser;
1674 if (tidlist == NULL || *tidlist == '\000')
1675 error (_("Please specify a thread ID list"));
1677 parser.init (tidlist, current_inferior ()->num);
1678 while (!parser.finished ())
1680 int inf_num, thr_start, thr_end;
1682 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1683 break;
1686 cmd = parser.cur_tok ();
1688 auto group = make_thread_apply_options_def_group (&flags);
1689 gdb::option::process_options
1690 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1692 validate_flags_qcs ("thread apply", &flags);
1694 if (*cmd == '\0')
1695 error (_("Please specify a command following the thread ID list"));
1697 if (tidlist == cmd || isdigit (cmd[0]))
1698 invalid_thread_id_error (cmd);
1700 scoped_restore_current_thread restore_thread;
1702 parser.init (tidlist, current_inferior ()->num);
1703 while (!parser.finished ())
1705 struct thread_info *tp = NULL;
1706 struct inferior *inf;
1707 int inf_num, thr_num;
1709 parser.get_tid (&inf_num, &thr_num);
1710 inf = find_inferior_id (inf_num);
1711 if (inf != NULL)
1712 tp = find_thread_id (inf, thr_num);
1714 if (parser.in_star_range ())
1716 if (inf == NULL)
1718 warning (_("Unknown inferior %d"), inf_num);
1719 parser.skip_range ();
1720 continue;
1723 /* No use looking for threads past the highest thread number
1724 the inferior ever had. */
1725 if (thr_num >= inf->highest_thread_num)
1726 parser.skip_range ();
1728 /* Be quiet about unknown threads numbers. */
1729 if (tp == NULL)
1730 continue;
1733 if (tp == NULL)
1735 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1736 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1737 else
1738 warning (_("Unknown thread %d"), thr_num);
1739 continue;
1742 if (!switch_to_thread_if_alive (tp))
1744 warning (_("Thread %s has terminated."), print_thread_id (tp));
1745 continue;
1748 thr_try_catch_cmd (tp, cmd, from_tty, flags);
1753 /* Implementation of the "taas" command. */
1755 static void
1756 taas_command (const char *cmd, int from_tty)
1758 if (cmd == NULL || *cmd == '\0')
1759 error (_("Please specify a command to apply on all threads"));
1760 std::string expanded = std::string ("thread apply all -s ") + cmd;
1761 execute_command (expanded.c_str (), from_tty);
1764 /* Implementation of the "tfaas" command. */
1766 static void
1767 tfaas_command (const char *cmd, int from_tty)
1769 if (cmd == NULL || *cmd == '\0')
1770 error (_("Please specify a command to apply on all frames of all threads"));
1771 std::string expanded
1772 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1773 execute_command (expanded.c_str (), from_tty);
1776 /* Switch to the specified thread, or print the current thread. */
1778 void
1779 thread_command (const char *tidstr, int from_tty)
1781 if (tidstr == NULL)
1783 if (inferior_ptid == null_ptid)
1784 error (_("No thread selected"));
1786 if (target_has_stack ())
1788 struct thread_info *tp = inferior_thread ();
1790 if (tp->state == THREAD_EXITED)
1791 printf_filtered (_("[Current thread is %s (%s) (exited)]\n"),
1792 print_thread_id (tp),
1793 target_pid_to_str (inferior_ptid).c_str ());
1794 else
1795 printf_filtered (_("[Current thread is %s (%s)]\n"),
1796 print_thread_id (tp),
1797 target_pid_to_str (inferior_ptid).c_str ());
1799 else
1800 error (_("No stack."));
1802 else
1804 ptid_t previous_ptid = inferior_ptid;
1806 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1808 /* Print if the thread has not changed, otherwise an event will
1809 be sent. */
1810 if (inferior_ptid == previous_ptid)
1812 print_selected_thread_frame (current_uiout,
1813 USER_SELECTED_THREAD
1814 | USER_SELECTED_FRAME);
1816 else
1818 gdb::observers::user_selected_context_changed.notify
1819 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1824 /* Implementation of `thread name'. */
1826 static void
1827 thread_name_command (const char *arg, int from_tty)
1829 struct thread_info *info;
1831 if (inferior_ptid == null_ptid)
1832 error (_("No thread selected"));
1834 arg = skip_spaces (arg);
1836 info = inferior_thread ();
1837 xfree (info->name);
1838 info->name = arg ? xstrdup (arg) : NULL;
1841 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1843 static void
1844 thread_find_command (const char *arg, int from_tty)
1846 const char *tmp;
1847 unsigned long match = 0;
1849 if (arg == NULL || *arg == '\0')
1850 error (_("Command requires an argument."));
1852 tmp = re_comp (arg);
1853 if (tmp != 0)
1854 error (_("Invalid regexp (%s): %s"), tmp, arg);
1856 /* We're going to be switching threads. */
1857 scoped_restore_current_thread restore_thread;
1859 update_thread_list ();
1861 for (thread_info *tp : all_threads ())
1863 switch_to_inferior_no_thread (tp->inf);
1865 if (tp->name != NULL && re_exec (tp->name))
1867 printf_filtered (_("Thread %s has name '%s'\n"),
1868 print_thread_id (tp), tp->name);
1869 match++;
1872 tmp = target_thread_name (tp);
1873 if (tmp != NULL && re_exec (tmp))
1875 printf_filtered (_("Thread %s has target name '%s'\n"),
1876 print_thread_id (tp), tmp);
1877 match++;
1880 std::string name = target_pid_to_str (tp->ptid);
1881 if (!name.empty () && re_exec (name.c_str ()))
1883 printf_filtered (_("Thread %s has target id '%s'\n"),
1884 print_thread_id (tp), name.c_str ());
1885 match++;
1888 tmp = target_extra_thread_info (tp);
1889 if (tmp != NULL && re_exec (tmp))
1891 printf_filtered (_("Thread %s has extra info '%s'\n"),
1892 print_thread_id (tp), tmp);
1893 match++;
1896 if (!match)
1897 printf_filtered (_("No threads match '%s'\n"), arg);
1900 /* Print notices when new threads are attached and detached. */
1901 bool print_thread_events = true;
1902 static void
1903 show_print_thread_events (struct ui_file *file, int from_tty,
1904 struct cmd_list_element *c, const char *value)
1906 fprintf_filtered (file,
1907 _("Printing of thread events is %s.\n"),
1908 value);
1911 /* See gdbthread.h. */
1913 void
1914 thread_select (const char *tidstr, thread_info *tp)
1916 if (!switch_to_thread_if_alive (tp))
1917 error (_("Thread ID %s has terminated."), tidstr);
1919 annotate_thread_changed ();
1921 /* Since the current thread may have changed, see if there is any
1922 exited thread we can now delete. */
1923 delete_exited_threads ();
1926 /* Print thread and frame switch command response. */
1928 void
1929 print_selected_thread_frame (struct ui_out *uiout,
1930 user_selected_what selection)
1932 struct thread_info *tp = inferior_thread ();
1934 if (selection & USER_SELECTED_THREAD)
1936 if (uiout->is_mi_like_p ())
1938 uiout->field_signed ("new-thread-id",
1939 inferior_thread ()->global_num);
1941 else
1943 uiout->text ("[Switching to thread ");
1944 uiout->field_string ("new-thread-id", print_thread_id (tp));
1945 uiout->text (" (");
1946 uiout->text (target_pid_to_str (inferior_ptid).c_str ());
1947 uiout->text (")]");
1951 if (tp->state == THREAD_RUNNING)
1953 if (selection & USER_SELECTED_THREAD)
1954 uiout->text ("(running)\n");
1956 else if (selection & USER_SELECTED_FRAME)
1958 if (selection & USER_SELECTED_THREAD)
1959 uiout->text ("\n");
1961 if (has_stack_frames ())
1962 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
1963 1, SRC_AND_LOC, 1);
1967 /* Update the 'threads_executing' global based on the threads we know
1968 about right now. This is used by infrun to tell whether we should
1969 pull events out of the current target. */
1971 static void
1972 update_threads_executing (void)
1974 process_stratum_target *targ = current_inferior ()->process_target ();
1976 if (targ == NULL)
1977 return;
1979 targ->threads_executing = false;
1981 for (inferior *inf : all_non_exited_inferiors (targ))
1983 if (!inf->has_execution ())
1984 continue;
1986 /* If the process has no threads, then it must be we have a
1987 process-exit event pending. */
1988 if (inf->thread_list == NULL)
1990 targ->threads_executing = true;
1991 return;
1994 for (thread_info *tp : inf->non_exited_threads ())
1996 if (tp->executing)
1998 targ->threads_executing = true;
1999 return;
2005 void
2006 update_thread_list (void)
2008 target_update_thread_list ();
2009 update_threads_executing ();
2012 /* Return a new value for the selected thread's id. Return a value of
2013 0 if no thread is selected. If GLOBAL is true, return the thread's
2014 global number. Otherwise return the per-inferior number. */
2016 static struct value *
2017 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2019 int int_val;
2021 if (inferior_ptid == null_ptid)
2022 int_val = 0;
2023 else
2025 thread_info *tp = inferior_thread ();
2026 if (global)
2027 int_val = tp->global_num;
2028 else
2029 int_val = tp->per_inf_num;
2032 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2035 /* Return a new value for the selected thread's per-inferior thread
2036 number. Return a value of 0 if no thread is selected, or no
2037 threads exist. */
2039 static struct value *
2040 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2041 struct internalvar *var,
2042 void *ignore)
2044 return thread_num_make_value_helper (gdbarch, 0);
2047 /* Return a new value for the selected thread's global id. Return a
2048 value of 0 if no thread is selected, or no threads exist. */
2050 static struct value *
2051 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2052 void *ignore)
2054 return thread_num_make_value_helper (gdbarch, 1);
2057 /* Commands with a prefix of `thread'. */
2058 struct cmd_list_element *thread_cmd_list = NULL;
2060 /* Implementation of `thread' variable. */
2062 static const struct internalvar_funcs thread_funcs =
2064 thread_id_per_inf_num_make_value,
2065 NULL,
2066 NULL
2069 /* Implementation of `gthread' variable. */
2071 static const struct internalvar_funcs gthread_funcs =
2073 global_thread_id_make_value,
2074 NULL,
2075 NULL
2078 void _initialize_thread ();
2079 void
2080 _initialize_thread ()
2082 static struct cmd_list_element *thread_apply_list = NULL;
2083 cmd_list_element *c;
2085 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2087 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2088 suggests. */
2089 static std::string info_threads_help
2090 = gdb::option::build_help (_("\
2091 Display currently known threads.\n\
2092 Usage: info threads [OPTION]... [ID]...\n\
2093 If ID is given, it is a space-separated list of IDs of threads to display.\n\
2094 Otherwise, all threads are displayed.\n\
2096 Options:\n\
2097 %OPTIONS%"),
2098 info_threads_opts);
2100 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2101 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
2103 add_prefix_cmd ("thread", class_run, thread_command, _("\
2104 Use this command to switch between threads.\n\
2105 The new thread ID must be currently known."),
2106 &thread_cmd_list, "thread ", 1, &cmdlist);
2108 #define THREAD_APPLY_OPTION_HELP "\
2109 Prints per-inferior thread number and target system's thread id\n\
2110 followed by COMMAND output.\n\
2112 By default, an error raised during the execution of COMMAND\n\
2113 aborts \"thread apply\".\n\
2115 Options:\n\
2116 %OPTIONS%"
2118 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2120 static std::string thread_apply_help = gdb::option::build_help (_("\
2121 Apply a command to a list of threads.\n\
2122 Usage: thread apply ID... [OPTION]... COMMAND\n\
2123 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
2124 THREAD_APPLY_OPTION_HELP),
2125 thread_apply_opts);
2127 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2128 thread_apply_help.c_str (),
2129 &thread_apply_list, "thread apply ", 1,
2130 &thread_cmd_list);
2131 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
2133 const auto thread_apply_all_opts
2134 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2136 static std::string thread_apply_all_help = gdb::option::build_help (_("\
2137 Apply a command to all threads.\n\
2139 Usage: thread apply all [OPTION]... COMMAND\n"
2140 THREAD_APPLY_OPTION_HELP),
2141 thread_apply_all_opts);
2143 c = add_cmd ("all", class_run, thread_apply_all_command,
2144 thread_apply_all_help.c_str (),
2145 &thread_apply_list);
2146 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2148 c = add_com ("taas", class_run, taas_command, _("\
2149 Apply a command to all threads (ignoring errors and empty output).\n\
2150 Usage: taas [OPTION]... COMMAND\n\
2151 shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2152 See \"help thread apply all\" for available options."));
2153 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
2155 c = add_com ("tfaas", class_run, tfaas_command, _("\
2156 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
2157 Usage: tfaas [OPTION]... COMMAND\n\
2158 shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2159 See \"help frame apply all\" for available options."));
2160 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
2162 add_cmd ("name", class_run, thread_name_command,
2163 _("Set the current thread's name.\n\
2164 Usage: thread name [NAME]\n\
2165 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2167 add_cmd ("find", class_run, thread_find_command, _("\
2168 Find threads that match a regular expression.\n\
2169 Usage: thread find REGEXP\n\
2170 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2171 &thread_cmd_list);
2173 add_com_alias ("t", "thread", class_run, 1);
2175 add_setshow_boolean_cmd ("thread-events", no_class,
2176 &print_thread_events, _("\
2177 Set printing of thread events (such as thread start and exit)."), _("\
2178 Show printing of thread events (such as thread start and exit)."), NULL,
2179 NULL,
2180 show_print_thread_events,
2181 &setprintlist, &showprintlist);
2183 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2184 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);