1 /* Multi-process/thread control for GDB, the GNU debugger.
3 Copyright (C) 1986-2019 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/>. */
26 #include "common/environ.h"
29 #include "gdbthread.h"
36 #include <sys/types.h>
39 #include "observable.h"
41 #include "cli/cli-decode.h"
42 #include "gdb_regex.h"
43 #include "cli/cli-utils.h"
44 #include "thread-fsm.h"
45 #include "tid-parse.h"
47 #include "common/gdb_optional.h"
48 #include "inline-frame.h"
50 /* Definition of struct thread_info exported to gdbthread.h. */
52 /* Prototypes for local functions. */
54 static int highest_thread_num;
56 /* True if any thread is, or may be executing. We need to track this
57 separately because until we fully sync the thread list, we won't
58 know whether the target is fully stopped, even if we see stop
59 events for all known threads, because any of those threads may have
60 spawned new threads we haven't heard of yet. */
61 static int threads_executing;
63 static int thread_alive (struct thread_info *);
65 /* RAII type used to increase / decrease the refcount of each thread
66 in a given list of threads. */
68 class scoped_inc_dec_ref
71 explicit scoped_inc_dec_ref (const std::vector<thread_info *> &thrds)
74 for (thread_info *thr : m_thrds)
78 ~scoped_inc_dec_ref ()
80 for (thread_info *thr : m_thrds)
85 const std::vector<thread_info *> &m_thrds;
90 inferior_thread (void)
92 struct thread_info *tp = find_thread_ptid (inferior_ptid);
97 /* Delete the breakpoint pointed at by BP_P, if there's one. */
100 delete_thread_breakpoint (struct breakpoint **bp_p)
104 delete_breakpoint (*bp_p);
110 delete_step_resume_breakpoint (struct thread_info *tp)
113 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
117 delete_exception_resume_breakpoint (struct thread_info *tp)
120 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
123 /* See gdbthread.h. */
126 delete_single_step_breakpoints (struct thread_info *tp)
129 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
132 /* Delete the breakpoint pointed at by BP_P at the next stop, if
136 delete_at_next_stop (struct breakpoint **bp)
140 (*bp)->disposition = disp_del_at_next_stop;
145 /* See gdbthread.h. */
148 thread_has_single_step_breakpoints_set (struct thread_info *tp)
150 return tp->control.single_step_breakpoints != NULL;
153 /* See gdbthread.h. */
156 thread_has_single_step_breakpoint_here (struct thread_info *tp,
157 const address_space *aspace,
160 struct breakpoint *ss_bps = tp->control.single_step_breakpoints;
162 return (ss_bps != NULL
163 && breakpoint_has_location_inserted_here (ss_bps, aspace, addr));
166 /* See gdbthread.h. */
169 thread_cancel_execution_command (struct thread_info *thr)
171 if (thr->thread_fsm != NULL)
173 thr->thread_fsm->clean_up (thr);
174 delete thr->thread_fsm;
175 thr->thread_fsm = NULL;
180 clear_thread_inferior_resources (struct thread_info *tp)
182 /* NOTE: this will take care of any left-over step_resume breakpoints,
183 but not any user-specified thread-specific breakpoints. We can not
184 delete the breakpoint straight-off, because the inferior might not
185 be stopped at the moment. */
186 delete_at_next_stop (&tp->control.step_resume_breakpoint);
187 delete_at_next_stop (&tp->control.exception_resume_breakpoint);
188 delete_at_next_stop (&tp->control.single_step_breakpoints);
190 delete_longjmp_breakpoint_at_next_stop (tp->global_num);
192 bpstat_clear (&tp->control.stop_bpstat);
194 btrace_teardown (tp);
196 thread_cancel_execution_command (tp);
198 clear_inline_frame_state (tp->ptid);
201 /* Set the TP's state as exited. */
204 set_thread_exited (thread_info *tp, int silent)
206 /* Dead threads don't need to step-over. Remove from queue. */
207 if (tp->step_over_next != NULL)
208 thread_step_over_chain_remove (tp);
210 if (tp->state != THREAD_EXITED)
212 gdb::observers::thread_exit.notify (tp, silent);
214 /* Tag it as exited. */
215 tp->state = THREAD_EXITED;
217 /* Clear breakpoints, etc. associated with this thread. */
218 clear_thread_inferior_resources (tp);
223 init_thread_list (void)
225 highest_thread_num = 0;
227 for (thread_info *tp : all_threads_safe ())
229 inferior *inf = tp->inf;
231 if (tp->deletable ())
234 set_thread_exited (tp, 1);
236 inf->thread_list = NULL;
240 /* Allocate a new thread of inferior INF with target id PTID and add
241 it to the thread list. */
243 static struct thread_info *
244 new_thread (struct inferior *inf, ptid_t ptid)
246 thread_info *tp = new thread_info (inf, ptid);
248 if (inf->thread_list == NULL)
249 inf->thread_list = tp;
252 struct thread_info *last;
254 for (last = inf->thread_list; last->next != NULL; last = last->next)
263 add_thread_silent (ptid_t ptid)
265 struct inferior *inf = find_inferior_ptid (ptid);
266 gdb_assert (inf != NULL);
268 thread_info *tp = find_thread_ptid (inf, ptid);
270 /* Found an old thread with the same id. It has to be dead,
271 otherwise we wouldn't be adding a new thread with the same id.
272 The OS is reusing this id --- delete it, and recreate a new
275 /* In addition to deleting the thread, if this is the current
276 thread, then we need to take care that delete_thread doesn't
277 really delete the thread if it is inferior_ptid. Create a
278 new template thread in the list with an invalid ptid, switch
279 to it, delete the original thread, reset the new thread's
280 ptid, and switch to it. */
282 if (inferior_ptid == ptid)
284 thread_info *new_thr = new_thread (inf, null_ptid);
286 /* Make switch_to_thread not read from the thread. */
287 new_thr->state = THREAD_EXITED;
288 switch_to_no_thread ();
290 /* Now we can delete it. */
293 /* Now reset its ptid, and reswitch inferior_ptid to it. */
294 new_thr->ptid = ptid;
295 new_thr->state = THREAD_STOPPED;
296 switch_to_thread (new_thr);
298 gdb::observers::new_thread.notify (new_thr);
304 /* Just go ahead and delete it. */
308 tp = new_thread (inf, ptid);
309 gdb::observers::new_thread.notify (tp);
315 add_thread_with_info (ptid_t ptid, private_thread_info *priv)
317 struct thread_info *result = add_thread_silent (ptid);
319 result->priv.reset (priv);
321 if (print_thread_events)
322 printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid).c_str ());
324 annotate_new_thread ();
329 add_thread (ptid_t ptid)
331 return add_thread_with_info (ptid, NULL);
334 private_thread_info::~private_thread_info () = default;
336 thread_info::thread_info (struct inferior *inf_, ptid_t ptid_)
337 : ptid (ptid_), inf (inf_)
339 gdb_assert (inf_ != NULL);
341 this->global_num = ++highest_thread_num;
342 this->per_inf_num = ++inf_->highest_thread_num;
344 /* Nothing to follow yet. */
345 memset (&this->pending_follow, 0, sizeof (this->pending_follow));
346 this->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
347 this->suspend.waitstatus.kind = TARGET_WAITKIND_IGNORE;
350 thread_info::~thread_info ()
355 /* See gdbthread.h. */
358 thread_info::deletable () const
360 /* If this is the current thread, or there's code out there that
361 relies on it existing (refcount > 0) we can't delete yet. */
362 return refcount () == 0 && ptid != inferior_ptid;
365 /* Add TP to the end of the step-over chain LIST_P. */
368 step_over_chain_enqueue (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);
376 tp->step_over_prev = tp->step_over_next = tp;
380 struct thread_info *head = *list_p;
381 struct thread_info *tail = head->step_over_prev;
383 tp->step_over_prev = tail;
384 tp->step_over_next = head;
385 head->step_over_prev = tp;
386 tail->step_over_next = tp;
390 /* Remove TP from step-over chain LIST_P. */
393 step_over_chain_remove (struct thread_info **list_p, struct thread_info *tp)
395 gdb_assert (tp->step_over_next != NULL);
396 gdb_assert (tp->step_over_prev != NULL);
400 if (tp == tp->step_over_next)
403 *list_p = tp->step_over_next;
406 tp->step_over_prev->step_over_next = tp->step_over_next;
407 tp->step_over_next->step_over_prev = tp->step_over_prev;
408 tp->step_over_prev = tp->step_over_next = NULL;
411 /* See gdbthread.h. */
414 thread_step_over_chain_next (struct thread_info *tp)
416 struct thread_info *next = tp->step_over_next;
418 return (next == step_over_queue_head ? NULL : next);
421 /* See gdbthread.h. */
424 thread_is_in_step_over_chain (struct thread_info *tp)
426 return (tp->step_over_next != NULL);
429 /* See gdbthread.h. */
432 thread_step_over_chain_enqueue (struct thread_info *tp)
434 step_over_chain_enqueue (&step_over_queue_head, tp);
437 /* See gdbthread.h. */
440 thread_step_over_chain_remove (struct thread_info *tp)
442 step_over_chain_remove (&step_over_queue_head, tp);
445 /* Delete the thread referenced by THR. If SILENT, don't notifyi
446 the observer of this exit.
448 THR must not be NULL or a failed assertion will be raised. */
451 delete_thread_1 (thread_info *thr, bool silent)
453 gdb_assert (thr != nullptr);
455 struct thread_info *tp, *tpprev = NULL;
457 for (tp = thr->inf->thread_list; tp; tpprev = tp, tp = tp->next)
464 set_thread_exited (tp, silent);
466 if (!tp->deletable ())
468 /* Will be really deleted some other time. */
473 tpprev->next = tp->next;
475 tp->inf->thread_list = tp->next;
480 /* Delete thread THREAD and notify of thread exit. If this is the
481 current thread, don't actually delete it, but tag it as exited and
482 do the notification. If this is the user selected thread, clear
486 delete_thread (thread_info *thread)
488 delete_thread_1 (thread, false /* not silent */);
492 delete_thread_silent (thread_info *thread)
494 delete_thread_1 (thread, true /* silent */);
498 find_thread_global_id (int global_id)
500 for (thread_info *tp : all_threads ())
501 if (tp->global_num == global_id)
507 static struct thread_info *
508 find_thread_id (struct inferior *inf, int thr_num)
510 for (thread_info *tp : inf->threads ())
511 if (tp->per_inf_num == thr_num)
517 /* Find a thread_info by matching PTID. */
520 find_thread_ptid (ptid_t ptid)
522 inferior *inf = find_inferior_ptid (ptid);
525 return find_thread_ptid (inf, ptid);
528 /* See gdbthread.h. */
531 find_thread_ptid (inferior *inf, ptid_t ptid)
533 for (thread_info *tp : inf->threads ())
534 if (tp->ptid == ptid)
540 /* See gdbthread.h. */
543 find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
544 struct inferior *inf)
546 return target_thread_handle_to_thread_info (handle.data (),
552 * Thread iterator function.
554 * Calls a callback function once for each thread, so long as
555 * the callback function returns false. If the callback function
556 * returns true, the iteration will end and the current thread
557 * will be returned. This can be useful for implementing a
558 * search for a thread with arbitrary attributes, or for applying
559 * some operation to every thread.
561 * FIXME: some of the existing functionality, such as
562 * "Thread apply all", might be rewritten using this functionality.
566 iterate_over_threads (int (*callback) (struct thread_info *, void *),
569 for (thread_info *tp : all_threads_safe ())
570 if ((*callback) (tp, data))
576 /* See gdbthread.h. */
581 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
589 auto rng = all_threads ();
590 return std::distance (rng.begin (), rng.end ());
593 /* Return the number of non-exited threads in the thread list. */
596 live_threads_count (void)
598 auto rng = all_non_exited_threads ();
599 return std::distance (rng.begin (), rng.end ());
603 valid_global_thread_id (int global_id)
605 for (thread_info *tp : all_threads ())
606 if (tp->global_num == global_id)
613 in_thread_list (ptid_t ptid)
615 return find_thread_ptid (ptid) != nullptr;
618 /* Finds the first thread of the inferior. */
621 first_thread_of_inferior (inferior *inf)
623 return inf->thread_list;
627 any_thread_of_inferior (inferior *inf)
629 gdb_assert (inf->pid != 0);
631 /* Prefer the current thread. */
632 if (inf == current_inferior ())
633 return inferior_thread ();
635 for (thread_info *tp : inf->non_exited_threads ())
642 any_live_thread_of_inferior (inferior *inf)
644 struct thread_info *curr_tp = NULL;
645 struct thread_info *tp_executing = NULL;
647 gdb_assert (inf != NULL && inf->pid != 0);
649 /* Prefer the current thread if it's not executing. */
650 if (inferior_ptid != null_ptid && current_inferior () == inf)
652 /* If the current thread is dead, forget it. If it's not
653 executing, use it. Otherwise, still choose it (below), but
654 only if no other non-executing thread is found. */
655 curr_tp = inferior_thread ();
656 if (curr_tp->state == THREAD_EXITED)
658 else if (!curr_tp->executing)
662 for (thread_info *tp : inf->non_exited_threads ())
670 /* If both the current thread and all live threads are executing,
671 prefer the current thread. */
675 /* Otherwise, just return an executing thread, if any. */
679 /* Return true if TP is an active thread. */
681 thread_alive (struct thread_info *tp)
683 if (tp->state == THREAD_EXITED)
685 if (!target_thread_alive (tp->ptid))
690 /* See gdbthreads.h. */
695 for (thread_info *tp : all_threads_safe ())
696 if (!thread_alive (tp))
700 /* See gdbthreads.h. */
703 delete_exited_threads (void)
705 for (thread_info *tp : all_threads_safe ())
706 if (tp->state == THREAD_EXITED)
710 /* Return true value if stack temporaies are enabled for the thread
714 thread_stack_temporaries_enabled_p (thread_info *tp)
719 return tp->stack_temporaries_enabled;
722 /* Push V on to the stack temporaries of the thread with id PTID. */
725 push_thread_stack_temporary (thread_info *tp, struct value *v)
727 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
728 tp->stack_temporaries.push_back (v);
731 /* Return true if VAL is among the stack temporaries of the thread
732 TP. Return false otherwise. */
735 value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
737 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
738 for (value *v : tp->stack_temporaries)
745 /* Return the last of the stack temporaries for thread with id PTID.
746 Return NULL if there are no stack temporaries for the thread. */
749 get_last_thread_stack_temporary (thread_info *tp)
751 struct value *lastval = NULL;
753 gdb_assert (tp != NULL);
754 if (!tp->stack_temporaries.empty ())
755 lastval = tp->stack_temporaries.back ();
761 thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid)
763 struct inferior *inf;
764 struct thread_info *tp;
766 /* It can happen that what we knew as the target inferior id
767 changes. E.g, target remote may only discover the remote process
768 pid after adding the inferior to GDB's list. */
769 inf = find_inferior_ptid (old_ptid);
770 inf->pid = new_ptid.pid ();
772 tp = find_thread_ptid (inf, old_ptid);
775 gdb::observers::thread_ptid_changed.notify (old_ptid, new_ptid);
778 /* See gdbthread.h. */
781 set_resumed (ptid_t ptid, int resumed)
783 for (thread_info *tp : all_non_exited_threads (ptid))
784 tp->resumed = resumed;
787 /* Helper for set_running, that marks one thread either running or
791 set_running_thread (struct thread_info *tp, int running)
795 if (running && tp->state == THREAD_STOPPED)
797 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
801 /* If the thread is now marked stopped, remove it from
802 the step-over queue, so that we don't try to resume
803 it until the user wants it to. */
804 if (tp->step_over_next != NULL)
805 thread_step_over_chain_remove (tp);
811 /* See gdbthread.h. */
814 thread_info::set_running (bool running)
816 if (set_running_thread (this, running))
817 gdb::observers::target_resumed.notify (this->ptid);
821 set_running (ptid_t ptid, int running)
823 /* We try not to notify the observer if no thread has actually
824 changed the running state -- merely to reduce the number of
825 messages to the MI frontend. A frontend is supposed to handle
826 multiple *running notifications just fine. */
827 bool any_started = false;
829 for (thread_info *tp : all_non_exited_threads (ptid))
830 if (set_running_thread (tp, running))
834 gdb::observers::target_resumed.notify (ptid);
838 /* Helper for set_executing. Set's the thread's 'executing' field
839 from EXECUTING, and if EXECUTING is true also clears the thread's
843 set_executing_thread (thread_info *thr, bool executing)
845 thr->executing = executing;
847 thr->suspend.stop_pc = ~(CORE_ADDR) 0;
851 set_executing (ptid_t ptid, int executing)
853 for (thread_info *tp : all_non_exited_threads (ptid))
854 set_executing_thread (tp, executing);
856 /* It only takes one running thread to spawn more threads. */
858 threads_executing = 1;
859 /* Only clear the flag if the caller is telling us everything is
861 else if (minus_one_ptid == ptid)
862 threads_executing = 0;
865 /* See gdbthread.h. */
868 threads_are_executing (void)
870 return threads_executing;
874 set_stop_requested (ptid_t ptid, int stop)
876 for (thread_info *tp : all_non_exited_threads (ptid))
877 tp->stop_requested = stop;
879 /* Call the stop requested observer so other components of GDB can
880 react to this request. */
882 gdb::observers::thread_stop_requested.notify (ptid);
886 finish_thread_state (ptid_t ptid)
888 bool any_started = false;
890 for (thread_info *tp : all_non_exited_threads (ptid))
891 if (set_running_thread (tp, tp->executing))
895 gdb::observers::target_resumed.notify (ptid);
898 /* See gdbthread.h. */
901 validate_registers_access (void)
903 /* No selected thread, no registers. */
904 if (inferior_ptid == null_ptid)
905 error (_("No thread selected."));
907 thread_info *tp = inferior_thread ();
909 /* Don't try to read from a dead thread. */
910 if (tp->state == THREAD_EXITED)
911 error (_("The current thread has terminated"));
913 /* ... or from a spinning thread. FIXME: This isn't actually fully
914 correct. It'll allow an user-requested access (e.g., "print $pc"
915 at the prompt) when a thread is not executing for some internal
916 reason, but is marked running from the user's perspective. E.g.,
917 the thread is waiting for its turn in the step-over queue. */
919 error (_("Selected thread is running."));
922 /* See gdbthread.h. */
925 can_access_registers_thread (thread_info *thread)
927 /* No thread, no registers. */
931 /* Don't try to read from a dead thread. */
932 if (thread->state == THREAD_EXITED)
935 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
936 if (thread->executing)
943 pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
945 return (pc >= thread->control.step_range_start
946 && pc < thread->control.step_range_end);
949 /* Helper for print_thread_info. Returns true if THR should be
950 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
951 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
952 is true if REQUESTED_THREADS is list of global IDs, false if a list
953 of per-inferior thread ids. If PID is not -1, only print THR if it
954 is a thread from the process PID. Otherwise, threads from all
955 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
956 and PID is not -1, then the thread is printed if it belongs to the
957 specified process. Otherwise, an error is raised. */
960 should_print_thread (const char *requested_threads, int default_inf_num,
961 int global_ids, int pid, struct thread_info *thr)
963 if (requested_threads != NULL && *requested_threads != '\0')
968 in_list = number_is_in_list (requested_threads, thr->global_num);
970 in_list = tid_is_in_list (requested_threads, default_inf_num,
971 thr->inf->num, thr->per_inf_num);
976 if (pid != -1 && thr->ptid.pid () != pid)
978 if (requested_threads != NULL && *requested_threads != '\0')
979 error (_("Requested thread not found in requested process"));
983 if (thr->state == THREAD_EXITED)
989 /* Return the string to display in "info threads"'s "Target Id"
993 thread_target_id_str (thread_info *tp)
995 std::string target_id = target_pid_to_str (tp->ptid);
996 const char *extra_info = target_extra_thread_info (tp);
997 const char *name = tp->name != nullptr ? tp->name : target_thread_name (tp);
999 if (extra_info != nullptr && name != nullptr)
1000 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1002 else if (extra_info != nullptr)
1003 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
1004 else if (name != nullptr)
1005 return string_printf ("%s \"%s\"", target_id.c_str (), name);
1010 /* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1011 whether REQUESTED_THREADS is a list of global or per-inferior
1015 print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
1016 int global_ids, int pid,
1017 int show_global_ids)
1019 int default_inf_num = current_inferior ()->num;
1021 update_thread_list ();
1023 /* Whether we saw any thread. */
1024 bool any_thread = false;
1025 /* Whether the current thread is exited. */
1026 bool current_exited = false;
1028 thread_info *current_thread = (inferior_ptid != null_ptid
1029 ? inferior_thread () : NULL);
1032 /* For backward compatibility, we make a list for MI. A table is
1033 preferable for the CLI, though, because it shows table
1035 gdb::optional<ui_out_emit_list> list_emitter;
1036 gdb::optional<ui_out_emit_table> table_emitter;
1038 if (uiout->is_mi_like_p ())
1039 list_emitter.emplace (uiout, "threads");
1043 /* The width of the "Target Id" column. Grown below to
1044 accommodate the largest entry. */
1045 size_t target_id_col_width = 17;
1047 for (thread_info *tp : all_threads ())
1049 if (!should_print_thread (requested_threads, default_inf_num,
1050 global_ids, pid, tp))
1053 if (!uiout->is_mi_like_p ())
1056 = std::max (target_id_col_width,
1057 thread_target_id_str (tp).size ());
1065 if (requested_threads == NULL || *requested_threads == '\0')
1066 uiout->message (_("No threads.\n"));
1068 uiout->message (_("No threads match '%s'.\n"),
1073 table_emitter.emplace (uiout, show_global_ids ? 5 : 4,
1074 n_threads, "threads");
1076 uiout->table_header (1, ui_left, "current", "");
1077 uiout->table_header (4, ui_left, "id-in-tg", "Id");
1078 if (show_global_ids)
1079 uiout->table_header (4, ui_left, "id", "GId");
1080 uiout->table_header (target_id_col_width, ui_left,
1081 "target-id", "Target Id");
1082 uiout->table_header (1, ui_left, "frame", "Frame");
1083 uiout->table_body ();
1086 /* We'll be switching threads temporarily. */
1087 scoped_restore_current_thread restore_thread;
1089 for (inferior *inf : all_inferiors ())
1090 for (thread_info *tp : inf->threads ())
1095 if (tp == current_thread && tp->state == THREAD_EXITED)
1096 current_exited = true;
1098 if (!should_print_thread (requested_threads, default_inf_num,
1099 global_ids, pid, tp))
1102 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1104 if (!uiout->is_mi_like_p ())
1106 if (tp == current_thread)
1107 uiout->field_string ("current", "*");
1109 uiout->field_skip ("current");
1111 uiout->field_string ("id-in-tg", print_thread_id (tp));
1114 if (show_global_ids || uiout->is_mi_like_p ())
1115 uiout->field_int ("id", tp->global_num);
1117 /* For the CLI, we stuff everything into the target-id field.
1118 This is a gross hack to make the output come out looking
1119 correct. The underlying problem here is that ui-out has no
1120 way to specify that a field's space allocation should be
1121 shared by several fields. For MI, we do the right thing
1124 if (uiout->is_mi_like_p ())
1126 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1128 const char *extra_info = target_extra_thread_info (tp);
1129 if (extra_info != nullptr)
1130 uiout->field_string ("details", extra_info);
1132 const char *name = (tp->name != nullptr
1134 : target_thread_name (tp));
1136 uiout->field_string ("name", name);
1140 uiout->field_string ("target-id",
1141 thread_target_id_str (tp).c_str ());
1144 if (tp->state == THREAD_RUNNING)
1145 uiout->text ("(running)\n");
1148 /* The switch below puts us at the top of the stack (leaf
1150 switch_to_thread (tp);
1151 print_stack_frame (get_selected_frame (NULL),
1152 /* For MI output, print frame level. */
1153 uiout->is_mi_like_p (),
1157 if (uiout->is_mi_like_p ())
1159 const char *state = "stopped";
1161 if (tp->state == THREAD_RUNNING)
1163 uiout->field_string ("state", state);
1166 core = target_core_of_thread (tp->ptid);
1167 if (uiout->is_mi_like_p () && core != -1)
1168 uiout->field_int ("core", core);
1171 /* This end scope restores the current thread and the frame
1172 selected before the "info threads" command, and it finishes the
1173 ui-out list or table. */
1176 if (pid == -1 && requested_threads == NULL)
1178 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
1179 uiout->field_int ("current-thread-id", current_thread->global_num);
1181 if (inferior_ptid != null_ptid && current_exited)
1182 uiout->message ("\n\
1183 The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1184 print_thread_id (inferior_thread ()));
1185 else if (any_thread && inferior_ptid == null_ptid)
1186 uiout->message ("\n\
1187 No selected thread. See `help thread'.\n");
1191 /* See gdbthread.h. */
1194 print_thread_info (struct ui_out *uiout, char *requested_threads, int pid)
1196 print_thread_info_1 (uiout, requested_threads, 1, pid, 0);
1199 /* Implementation of the "info threads" command.
1201 Note: this has the drawback that it _really_ switches
1202 threads, which frees the frame cache. A no-side
1203 effects info-threads command would be nicer. */
1206 info_threads_command (const char *arg, int from_tty)
1208 int show_global_ids = 0;
1211 && check_for_argument (&arg, "-gid", sizeof ("-gid") - 1))
1213 arg = skip_spaces (arg);
1214 show_global_ids = 1;
1217 print_thread_info_1 (current_uiout, arg, 0, -1, show_global_ids);
1220 /* See gdbthread.h. */
1223 switch_to_thread_no_regs (struct thread_info *thread)
1225 struct inferior *inf = thread->inf;
1227 set_current_program_space (inf->pspace);
1228 set_current_inferior (inf);
1230 inferior_ptid = thread->ptid;
1233 /* See gdbthread.h. */
1236 switch_to_no_thread ()
1238 if (inferior_ptid == null_ptid)
1241 inferior_ptid = null_ptid;
1242 reinit_frame_cache ();
1245 /* See gdbthread.h. */
1248 switch_to_thread (thread_info *thr)
1250 gdb_assert (thr != NULL);
1252 if (inferior_ptid == thr->ptid)
1255 switch_to_thread_no_regs (thr);
1257 reinit_frame_cache ();
1260 /* See common/common-gdbthread.h. */
1263 switch_to_thread (ptid_t ptid)
1265 thread_info *thr = find_thread_ptid (ptid);
1266 switch_to_thread (thr);
1270 restore_selected_frame (struct frame_id a_frame_id, int frame_level)
1272 struct frame_info *frame = NULL;
1275 /* This means there was no selected frame. */
1276 if (frame_level == -1)
1278 select_frame (NULL);
1282 gdb_assert (frame_level >= 0);
1284 /* Restore by level first, check if the frame id is the same as
1285 expected. If that fails, try restoring by frame id. If that
1286 fails, nothing to do, just warn the user. */
1288 count = frame_level;
1289 frame = find_relative_frame (get_current_frame (), &count);
1292 /* The frame ids must match - either both valid or both outer_frame_id.
1293 The latter case is not failsafe, but since it's highly unlikely
1294 the search by level finds the wrong frame, it's 99.9(9)% of
1295 the time (for all practical purposes) safe. */
1296 && frame_id_eq (get_frame_id (frame), a_frame_id))
1298 /* Cool, all is fine. */
1299 select_frame (frame);
1303 frame = frame_find_by_id (a_frame_id);
1306 /* Cool, refound it. */
1307 select_frame (frame);
1311 /* Nothing else to do, the frame layout really changed. Select the
1312 innermost stack frame. */
1313 select_frame (get_current_frame ());
1315 /* Warn the user. */
1316 if (frame_level > 0 && !current_uiout->is_mi_like_p ())
1318 warning (_("Couldn't restore frame #%d in "
1319 "current thread. Bottom (innermost) frame selected:"),
1321 /* For MI, we should probably have a notification about
1322 current frame change. But this error is not very
1323 likely, so don't bother for now. */
1324 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
1328 scoped_restore_current_thread::~scoped_restore_current_thread ()
1330 /* If an entry of thread_info was previously selected, it won't be
1331 deleted because we've increased its refcount. The thread represented
1332 by this thread_info entry may have already exited (due to normal exit,
1333 detach, etc), so the thread_info.state is THREAD_EXITED. */
1334 if (m_thread != NULL
1335 /* If the previously selected thread belonged to a process that has
1336 in the mean time exited (or killed, detached, etc.), then don't revert
1337 back to it, but instead simply drop back to no thread selected. */
1339 switch_to_thread (m_thread);
1342 switch_to_no_thread ();
1343 set_current_inferior (m_inf);
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
1350 && m_thread->state == THREAD_STOPPED
1351 && target_has_registers
1353 && target_has_memory)
1354 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
1356 if (m_thread != NULL)
1357 m_thread->decref ();
1361 scoped_restore_current_thread::scoped_restore_current_thread ()
1364 m_inf = current_inferior ();
1366 if (inferior_ptid != null_ptid)
1368 thread_info *tp = inferior_thread ();
1369 struct frame_info *frame;
1371 m_was_stopped = tp->state == THREAD_STOPPED;
1373 && target_has_registers
1375 && target_has_memory)
1377 /* When processing internal events, there might not be a
1378 selected frame. If we naively call get_selected_frame
1379 here, then we can end up reading debuginfo for the
1380 current frame, but we don't generally need the debuginfo
1382 frame = get_selected_frame_if_set ();
1387 m_selected_frame_id = get_frame_id (frame);
1388 m_selected_frame_level = frame_relative_level (frame);
1397 /* See gdbthread.h. */
1400 show_thread_that_caused_stop (void)
1402 return highest_thread_num > 1;
1405 /* See gdbthread.h. */
1408 show_inferior_qualified_tids (void)
1410 return (inferior_list->next != NULL || inferior_list->num != 1);
1413 /* See gdbthread.h. */
1416 print_thread_id (struct thread_info *thr)
1418 char *s = get_print_cell ();
1420 if (show_inferior_qualified_tids ())
1421 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
1423 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1427 /* If true, tp_array_compar should sort in ascending order, otherwise
1428 in descending order. */
1430 static bool tp_array_compar_ascending;
1432 /* Sort an array for struct thread_info pointers by thread ID (first
1433 by inferior number, and then by per-inferior thread number). The
1434 order is determined by TP_ARRAY_COMPAR_ASCENDING. */
1437 tp_array_compar (const thread_info *a, const thread_info *b)
1439 if (a->inf->num != b->inf->num)
1441 if (tp_array_compar_ascending)
1442 return a->inf->num < b->inf->num;
1444 return a->inf->num > b->inf->num;
1447 if (tp_array_compar_ascending)
1448 return (a->per_inf_num < b->per_inf_num);
1450 return (a->per_inf_num > b->per_inf_num);
1453 /* Switch to thread THR and execute CMD.
1454 FLAGS.QUIET controls the printing of the thread information.
1455 FLAGS.CONT and FLAGS.SILENT control how to handle errors. */
1458 thr_try_catch_cmd (thread_info *thr, const char *cmd, int from_tty,
1459 const qcs_flags &flags)
1461 switch_to_thread (thr);
1464 std::string cmd_result = execute_command_to_string
1465 (cmd, from_tty, gdb_stdout->term_out ());
1466 if (!flags.silent || cmd_result.length () > 0)
1469 printf_filtered (_("\nThread %s (%s):\n"),
1470 print_thread_id (thr),
1471 target_pid_to_str (inferior_ptid).c_str ());
1472 printf_filtered ("%s", cmd_result.c_str ());
1475 catch (const gdb_exception_error &ex)
1480 printf_filtered (_("\nThread %s (%s):\n"),
1481 print_thread_id (thr),
1482 target_pid_to_str (inferior_ptid).c_str ());
1484 printf_filtered ("%s\n", ex.what ());
1491 /* Apply a GDB command to a list of threads. List syntax is a whitespace
1492 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1493 of two numbers separated by a hyphen. Examples:
1495 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1496 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
1497 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
1500 thread_apply_all_command (const char *cmd, int from_tty)
1504 tp_array_compar_ascending = false;
1508 if (check_for_argument (&cmd, "-ascending", strlen ("-ascending")))
1510 cmd = skip_spaces (cmd);
1511 tp_array_compar_ascending = true;
1515 if (parse_flags_qcs ("thread apply all", &cmd, &flags))
1521 if (cmd == NULL || *cmd == '\000')
1522 error (_("Please specify a command at the end of 'thread apply all'"));
1524 update_thread_list ();
1526 int tc = live_threads_count ();
1529 /* Save a copy of the thread list and increment each thread's
1530 refcount while executing the command in the context of each
1531 thread, in case the command is one that wipes threads. E.g.,
1532 detach, kill, disconnect, etc., or even normally continuing
1533 over an inferior or thread exit. */
1534 std::vector<thread_info *> thr_list_cpy;
1535 thr_list_cpy.reserve (tc);
1537 for (thread_info *tp : all_non_exited_threads ())
1538 thr_list_cpy.push_back (tp);
1539 gdb_assert (thr_list_cpy.size () == tc);
1541 /* Increment the refcounts, and restore them back on scope
1543 scoped_inc_dec_ref inc_dec_ref (thr_list_cpy);
1545 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), tp_array_compar);
1547 scoped_restore_current_thread restore_thread;
1549 for (thread_info *thr : thr_list_cpy)
1550 if (thread_alive (thr))
1551 thr_try_catch_cmd (thr, cmd, from_tty, flags);
1555 /* Implementation of the "thread apply" command. */
1558 thread_apply_command (const char *tidlist, int from_tty)
1561 const char *cmd = NULL;
1562 const char *cmd_or_flags;
1563 tid_range_parser parser;
1565 if (tidlist == NULL || *tidlist == '\000')
1566 error (_("Please specify a thread ID list"));
1568 parser.init (tidlist, current_inferior ()->num);
1569 while (!parser.finished ())
1571 int inf_num, thr_start, thr_end;
1573 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1575 cmd = parser.cur_tok ();
1581 while (cmd != NULL && parse_flags_qcs ("thread apply", &cmd, &flags))
1585 error (_("Please specify a command following the thread ID list"));
1587 if (tidlist == cmd || !isalpha (cmd[0]))
1588 invalid_thread_id_error (cmd);
1590 scoped_restore_current_thread restore_thread;
1592 parser.init (tidlist, current_inferior ()->num);
1593 while (!parser.finished () && parser.cur_tok () < cmd_or_flags)
1595 struct thread_info *tp = NULL;
1596 struct inferior *inf;
1597 int inf_num, thr_num;
1599 parser.get_tid (&inf_num, &thr_num);
1600 inf = find_inferior_id (inf_num);
1602 tp = find_thread_id (inf, thr_num);
1604 if (parser.in_star_range ())
1608 warning (_("Unknown inferior %d"), inf_num);
1609 parser.skip_range ();
1613 /* No use looking for threads past the highest thread number
1614 the inferior ever had. */
1615 if (thr_num >= inf->highest_thread_num)
1616 parser.skip_range ();
1618 /* Be quiet about unknown threads numbers. */
1625 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
1626 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1628 warning (_("Unknown thread %d"), thr_num);
1632 if (!thread_alive (tp))
1634 warning (_("Thread %s has terminated."), print_thread_id (tp));
1638 thr_try_catch_cmd (tp, cmd, from_tty, flags);
1643 /* Implementation of the "taas" command. */
1646 taas_command (const char *cmd, int from_tty)
1648 std::string expanded = std::string ("thread apply all -s ") + cmd;
1649 execute_command (expanded.c_str (), from_tty);
1652 /* Implementation of the "tfaas" command. */
1655 tfaas_command (const char *cmd, int from_tty)
1657 std::string expanded
1658 = std::string ("thread apply all -s frame apply all -s ") + cmd;
1659 execute_command (expanded.c_str (), from_tty);
1662 /* Switch to the specified thread, or print the current thread. */
1665 thread_command (const char *tidstr, int from_tty)
1669 if (inferior_ptid == null_ptid)
1670 error (_("No thread selected"));
1672 if (target_has_stack)
1674 struct thread_info *tp = inferior_thread ();
1676 if (tp->state == THREAD_EXITED)
1677 printf_filtered (_("[Current thread is %s (%s) (exited)]\n"),
1678 print_thread_id (tp),
1679 target_pid_to_str (inferior_ptid).c_str ());
1681 printf_filtered (_("[Current thread is %s (%s)]\n"),
1682 print_thread_id (tp),
1683 target_pid_to_str (inferior_ptid).c_str ());
1686 error (_("No stack."));
1690 ptid_t previous_ptid = inferior_ptid;
1692 thread_select (tidstr, parse_thread_id (tidstr, NULL));
1694 /* Print if the thread has not changed, otherwise an event will
1696 if (inferior_ptid == previous_ptid)
1698 print_selected_thread_frame (current_uiout,
1699 USER_SELECTED_THREAD
1700 | USER_SELECTED_FRAME);
1704 gdb::observers::user_selected_context_changed.notify
1705 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
1710 /* Implementation of `thread name'. */
1713 thread_name_command (const char *arg, int from_tty)
1715 struct thread_info *info;
1717 if (inferior_ptid == null_ptid)
1718 error (_("No thread selected"));
1720 arg = skip_spaces (arg);
1722 info = inferior_thread ();
1724 info->name = arg ? xstrdup (arg) : NULL;
1727 /* Find thread ids with a name, target pid, or extra info matching ARG. */
1730 thread_find_command (const char *arg, int from_tty)
1733 unsigned long match = 0;
1735 if (arg == NULL || *arg == '\0')
1736 error (_("Command requires an argument."));
1738 tmp = re_comp (arg);
1740 error (_("Invalid regexp (%s): %s"), tmp, arg);
1742 update_thread_list ();
1743 for (thread_info *tp : all_threads ())
1745 if (tp->name != NULL && re_exec (tp->name))
1747 printf_filtered (_("Thread %s has name '%s'\n"),
1748 print_thread_id (tp), tp->name);
1752 tmp = target_thread_name (tp);
1753 if (tmp != NULL && re_exec (tmp))
1755 printf_filtered (_("Thread %s has target name '%s'\n"),
1756 print_thread_id (tp), tmp);
1760 std::string name = target_pid_to_str (tp->ptid);
1761 if (!name.empty () && re_exec (name.c_str ()))
1763 printf_filtered (_("Thread %s has target id '%s'\n"),
1764 print_thread_id (tp), name.c_str ());
1768 tmp = target_extra_thread_info (tp);
1769 if (tmp != NULL && re_exec (tmp))
1771 printf_filtered (_("Thread %s has extra info '%s'\n"),
1772 print_thread_id (tp), tmp);
1777 printf_filtered (_("No threads match '%s'\n"), arg);
1780 /* Print notices when new threads are attached and detached. */
1781 int print_thread_events = 1;
1783 show_print_thread_events (struct ui_file *file, int from_tty,
1784 struct cmd_list_element *c, const char *value)
1786 fprintf_filtered (file,
1787 _("Printing of thread events is %s.\n"),
1791 /* See gdbthread.h. */
1794 thread_select (const char *tidstr, thread_info *tp)
1796 if (!thread_alive (tp))
1797 error (_("Thread ID %s has terminated."), tidstr);
1799 switch_to_thread (tp);
1801 annotate_thread_changed ();
1803 /* Since the current thread may have changed, see if there is any
1804 exited thread we can now delete. */
1808 /* Print thread and frame switch command response. */
1811 print_selected_thread_frame (struct ui_out *uiout,
1812 user_selected_what selection)
1814 struct thread_info *tp = inferior_thread ();
1816 if (selection & USER_SELECTED_THREAD)
1818 if (uiout->is_mi_like_p ())
1820 uiout->field_int ("new-thread-id",
1821 inferior_thread ()->global_num);
1825 uiout->text ("[Switching to thread ");
1826 uiout->field_string ("new-thread-id", print_thread_id (tp));
1828 uiout->text (target_pid_to_str (inferior_ptid).c_str ());
1833 if (tp->state == THREAD_RUNNING)
1835 if (selection & USER_SELECTED_THREAD)
1836 uiout->text ("(running)\n");
1838 else if (selection & USER_SELECTED_FRAME)
1840 if (selection & USER_SELECTED_THREAD)
1843 if (has_stack_frames ())
1844 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
1849 /* Update the 'threads_executing' global based on the threads we know
1853 update_threads_executing (void)
1855 threads_executing = 0;
1856 for (thread_info *tp : all_non_exited_threads ())
1860 threads_executing = 1;
1867 update_thread_list (void)
1869 target_update_thread_list ();
1870 update_threads_executing ();
1873 /* Return a new value for the selected thread's id. Return a value of
1874 0 if no thread is selected. If GLOBAL is true, return the thread's
1875 global number. Otherwise return the per-inferior number. */
1877 static struct value *
1878 thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
1882 if (inferior_ptid == null_ptid)
1886 thread_info *tp = inferior_thread ();
1888 int_val = tp->global_num;
1890 int_val = tp->per_inf_num;
1893 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
1896 /* Return a new value for the selected thread's per-inferior thread
1897 number. Return a value of 0 if no thread is selected, or no
1900 static struct value *
1901 thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
1902 struct internalvar *var,
1905 return thread_num_make_value_helper (gdbarch, 0);
1908 /* Return a new value for the selected thread's global id. Return a
1909 value of 0 if no thread is selected, or no threads exist. */
1911 static struct value *
1912 global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
1915 return thread_num_make_value_helper (gdbarch, 1);
1918 /* Commands with a prefix of `thread'. */
1919 struct cmd_list_element *thread_cmd_list = NULL;
1921 /* Implementation of `thread' variable. */
1923 static const struct internalvar_funcs thread_funcs =
1925 thread_id_per_inf_num_make_value,
1930 /* Implementation of `gthread' variable. */
1932 static const struct internalvar_funcs gthread_funcs =
1934 global_thread_id_make_value,
1940 _initialize_thread (void)
1942 static struct cmd_list_element *thread_apply_list = NULL;
1944 add_info ("threads", info_threads_command,
1945 _("Display currently known threads.\n\
1946 Usage: info threads [-gid] [ID]...\n\
1947 -gid: Show global thread IDs.\n\
1948 If ID is given, it is a space-separated list of IDs of threads to display.\n\
1949 Otherwise, all threads are displayed."));
1951 add_prefix_cmd ("thread", class_run, thread_command, _("\
1952 Use this command to switch between threads.\n\
1953 The new thread ID must be currently known."),
1954 &thread_cmd_list, "thread ", 1, &cmdlist);
1956 #define THREAD_APPLY_FLAGS_HELP "\
1957 Prints per-inferior thread number and target system's thread id\n\
1958 followed by COMMAND output.\n\
1959 FLAG arguments are -q (quiet), -c (continue), -s (silent).\n\
1960 Flag -q disables printing the thread information.\n\
1961 By default, if a COMMAND raises an error, thread apply is aborted.\n\
1962 Flag -c indicates to print the error and continue.\n\
1963 Flag -s indicates to silently ignore a COMMAND that raises an error\n\
1964 or produces no output."
1966 add_prefix_cmd ("apply", class_run, thread_apply_command,
1967 _("Apply a command to a list of threads.\n\
1968 Usage: thread apply ID... [FLAG]... COMMAND\n\
1969 ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
1970 THREAD_APPLY_FLAGS_HELP),
1971 &thread_apply_list, "thread apply ", 1, &thread_cmd_list);
1973 add_cmd ("all", class_run, thread_apply_all_command,
1975 Apply a command to all threads.\n\
1977 Usage: thread apply all [-ascending] [FLAG]... COMMAND\n\
1978 -ascending: Call COMMAND for all threads in ascending order.\n\
1979 The default is descending order.\n"
1980 THREAD_APPLY_FLAGS_HELP),
1981 &thread_apply_list);
1983 add_com ("taas", class_run, taas_command, _("\
1984 Apply a command to all threads (ignoring errors and empty output).\n\
1985 Usage: taas COMMAND\n\
1986 shortcut for 'thread apply all -s COMMAND'"));
1988 add_com ("tfaas", class_run, tfaas_command, _("\
1989 Apply a command to all frames of all threads (ignoring errors and empty output).\n\
1990 Usage: tfaas COMMAND\n\
1991 shortcut for 'thread apply all -s frame apply all -s COMMAND'"));
1993 add_cmd ("name", class_run, thread_name_command,
1994 _("Set the current thread's name.\n\
1995 Usage: thread name [NAME]\n\
1996 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
1998 add_cmd ("find", class_run, thread_find_command, _("\
1999 Find threads that match a regular expression.\n\
2000 Usage: thread find REGEXP\n\
2001 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2004 add_com_alias ("t", "thread", class_run, 1);
2006 add_setshow_boolean_cmd ("thread-events", no_class,
2007 &print_thread_events, _("\
2008 Set printing of thread events (such as thread start and exit)."), _("\
2009 Show printing of thread events (such as thread start and exit)."), NULL,
2011 show_print_thread_events,
2012 &setprintlist, &showprintlist);
2014 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
2015 create_internalvar_type_lazy ("_gthread", >hread_funcs, NULL);