]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/thread.c
gdb/alpha: Redefine fpcr with fpcr_flags type
[thirdparty/binutils-gdb.git] / gdb / thread.c
CommitLineData
c906108c 1/* Multi-process/thread control for GDB, the GNU debugger.
8926118c 2
d01e8234 3 Copyright (C) 1986-2025 Free Software Foundation, Inc.
8926118c 4
b6ba6518 5 Contributed by Lynx Real-Time Systems, Inc. Los Gatos, CA.
c906108c 6
c5aa993b 7 This file is part of GDB.
c906108c 8
c5aa993b
JM
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
a9762ec7 11 the Free Software Foundation; either version 3 of the License, or
c5aa993b 12 (at your option) any later version.
c906108c 13
c5aa993b
JM
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.
c906108c 18
c5aa993b 19 You should have received a copy of the GNU General Public License
a9762ec7 20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c906108c 21
83b6e1f1 22#include "language.h"
c906108c
SS
23#include "symtab.h"
24#include "frame.h"
25#include "inferior.h"
268a13a5 26#include "gdbsupport/environ.h"
824dd26e 27#include "top.h"
c906108c
SS
28#include "value.h"
29#include "target.h"
30#include "gdbthread.h"
31#include "command.h"
5b9707eb 32#include "cli/cli-cmds.h"
4e052eda 33#include "regcache.h"
02d27625 34#include "btrace.h"
c906108c
SS
35
36#include <ctype.h>
37#include <sys/types.h>
38#include <signal.h>
8b93c638 39#include "ui-out.h"
76727919 40#include "observable.h"
d4fc5b1e 41#include "annotate.h"
94cc34af 42#include "cli/cli-decode.h"
6665660a 43#include "cli/cli-option.h"
d322d6d6 44#include "gdbsupport/gdb_regex.h"
aea5b279 45#include "cli/cli-utils.h"
243a9253 46#include "thread-fsm.h"
5d5658a1 47#include "tid-parse.h"
c6609450 48#include <algorithm>
6b09f134 49#include <optional>
08036331 50#include "inline-frame.h"
5d707134 51#include "stack.h"
30e7e0a9 52#include "interps.h"
2f46cda8 53#include "record-full.h"
94cc34af 54
5b0a3d62
AB
55/* See gdbthread.h. */
56
57bool debug_threads = false;
58
59/* Implement 'show debug threads'. */
60
61static void
62show_debug_threads (struct ui_file *file, int from_tty,
63 struct cmd_list_element *c, const char *value)
64{
6cb06a8c 65 gdb_printf (file, _("Thread debugging is \"%s\".\n"), value);
5b0a3d62
AB
66}
67
c378eb4e 68/* Definition of struct thread_info exported to gdbthread.h. */
c906108c 69
c378eb4e 70/* Prototypes for local functions. */
c906108c 71
c906108c
SS
72static int highest_thread_num;
73
3922b302
PA
74/* The current/selected thread. */
75static thread_info *current_thread_;
76
3922b302
PA
77/* Returns true if THR is the current thread. */
78
79static bool
80is_current_thread (const thread_info *thr)
81{
82 return thr == current_thread_;
83}
054e8d9e 84
a5321aa4 85struct thread_info*
4e1c45ea 86inferior_thread (void)
8601f500 87{
3922b302
PA
88 gdb_assert (current_thread_ != nullptr);
89 return current_thread_;
4e1c45ea 90}
8601f500 91
5b834a0a
PA
92/* Delete the breakpoint pointed at by BP_P, if there's one. */
93
94static void
95delete_thread_breakpoint (struct breakpoint **bp_p)
4e1c45ea 96{
5b834a0a 97 if (*bp_p != NULL)
8601f500 98 {
5b834a0a
PA
99 delete_breakpoint (*bp_p);
100 *bp_p = NULL;
8601f500
MS
101 }
102}
103
5b834a0a
PA
104void
105delete_step_resume_breakpoint (struct thread_info *tp)
106{
107 if (tp != NULL)
108 delete_thread_breakpoint (&tp->control.step_resume_breakpoint);
109}
110
186c406b
TT
111void
112delete_exception_resume_breakpoint (struct thread_info *tp)
113{
5b834a0a
PA
114 if (tp != NULL)
115 delete_thread_breakpoint (&tp->control.exception_resume_breakpoint);
116}
117
34b7e8a6
PA
118/* See gdbthread.h. */
119
120void
121delete_single_step_breakpoints (struct thread_info *tp)
122{
123 if (tp != NULL)
124 delete_thread_breakpoint (&tp->control.single_step_breakpoints);
125}
126
5b834a0a
PA
127/* Delete the breakpoint pointed at by BP_P at the next stop, if
128 there's one. */
129
130static void
131delete_at_next_stop (struct breakpoint **bp)
132{
133 if (*bp != NULL)
186c406b 134 {
5b834a0a
PA
135 (*bp)->disposition = disp_del_at_next_stop;
136 *bp = NULL;
186c406b
TT
137 }
138}
139
34b7e8a6
PA
140/* See gdbthread.h. */
141
142int
143thread_has_single_step_breakpoints_set (struct thread_info *tp)
144{
145 return tp->control.single_step_breakpoints != NULL;
146}
147
148/* See gdbthread.h. */
149
150int
151thread_has_single_step_breakpoint_here (struct thread_info *tp,
accd0bcd 152 const address_space *aspace,
34b7e8a6
PA
153 CORE_ADDR addr)
154{
155 struct breakpoint *ss_bps = tp->control.single_step_breakpoints;
156
157 return (ss_bps != NULL
158 && breakpoint_has_location_inserted_here (ss_bps, aspace, addr));
159}
160
243a9253
PA
161/* See gdbthread.h. */
162
163void
164thread_cancel_execution_command (struct thread_info *thr)
165{
573269a8 166 if (thr->thread_fsm () != nullptr)
243a9253 167 {
573269a8
LS
168 std::unique_ptr<thread_fsm> fsm = thr->release_thread_fsm ();
169 fsm->clean_up (thr);
243a9253
PA
170 }
171}
172
7c952b6d 173static void
4f8d22e3 174clear_thread_inferior_resources (struct thread_info *tp)
7c952b6d
ND
175{
176 /* NOTE: this will take care of any left-over step_resume breakpoints,
4d8453a5
DJ
177 but not any user-specified thread-specific breakpoints. We can not
178 delete the breakpoint straight-off, because the inferior might not
179 be stopped at the moment. */
5b834a0a
PA
180 delete_at_next_stop (&tp->control.step_resume_breakpoint);
181 delete_at_next_stop (&tp->control.exception_resume_breakpoint);
34b7e8a6 182 delete_at_next_stop (&tp->control.single_step_breakpoints);
186c406b 183
5d5658a1 184 delete_longjmp_breakpoint_at_next_stop (tp->global_num);
f59f708a 185
16c381f0 186 bpstat_clear (&tp->control.stop_bpstat);
95e54da7 187
02d27625
MM
188 btrace_teardown (tp);
189
243a9253 190 thread_cancel_execution_command (tp);
08036331 191
5b6d1e4f 192 clear_inline_frame_state (tp);
4f8d22e3
PA
193}
194
8e7af843
SM
195/* Notify interpreters and observers that thread T has exited. */
196
197static void
6b09f134 198notify_thread_exited (thread_info *t, std::optional<ULONGEST> exit_code,
9d7d58e7 199 int silent)
8e7af843 200{
9d7d58e7
PA
201 if (!silent && print_thread_events)
202 {
203 if (exit_code.has_value ())
204 gdb_printf (_("[%s exited with code %s]\n"),
205 target_pid_to_str (t->ptid).c_str (),
206 pulongest (*exit_code));
207 else
208 gdb_printf (_("[%s exited]\n"),
209 target_pid_to_str (t->ptid).c_str ());
210 }
211
212 interps_notify_thread_exited (t, exit_code, silent);
213 gdb::observers::thread_exit.notify (t, exit_code, silent);
8e7af843
SM
214}
215
bf809310 216/* See gdbthread.h. */
803bdfe4 217
bf809310 218void
6b09f134 219set_thread_exited (thread_info *tp, std::optional<ULONGEST> exit_code,
9d7d58e7 220 bool silent)
803bdfe4 221{
28d5518b 222 /* Dead threads don't need to step-over. Remove from chain. */
8b6a69b2 223 if (thread_is_in_step_over_chain (tp))
28d5518b 224 global_thread_step_over_chain_remove (tp);
803bdfe4
YQ
225
226 if (tp->state != THREAD_EXITED)
227 {
a66f7298
SM
228 process_stratum_target *proc_target = tp->inf->process_target ();
229
230 /* Some targets unpush themselves from the inferior's target stack before
287de656
SM
231 clearing the inferior's thread list (which marks all threads as exited,
232 and therefore leads to this function). In this case, the inferior's
233 process target will be nullptr when we arrive here.
a66f7298 234
287de656 235 See also the comment in inferior::unpush_target. */
a66f7298
SM
236 if (proc_target != nullptr)
237 proc_target->maybe_remove_resumed_with_pending_wait_status (tp);
238
9d7d58e7 239 notify_thread_exited (tp, exit_code, silent);
803bdfe4
YQ
240
241 /* Tag it as exited. */
242 tp->state = THREAD_EXITED;
243
244 /* Clear breakpoints, etc. associated with this thread. */
245 clear_thread_inferior_resources (tp);
922cc93d
SM
246
247 /* Remove from the ptid_t map. We don't want for
3c8af02f 248 inferior::find_thread to find exited threads. Also, the target
922cc93d
SM
249 may reuse the ptid for a new thread, and there can only be
250 one value per key; adding a new thread with the same ptid_t
251 would overwrite the exited thread's ptid entry. */
252 size_t nr_deleted = tp->inf->ptid_thread_map.erase (tp->ptid);
253 gdb_assert (nr_deleted == 1);
803bdfe4
YQ
254 }
255}
256
c906108c 257void
fba45db2 258init_thread_list (void)
c906108c 259{
7c952b6d 260 highest_thread_num = 0;
8ea051c5 261
bf809310 262 for (inferior *inf : all_inferiors ())
604fe2d9 263 inf->clear_thread_list ();
c906108c
SS
264}
265
5d5658a1
PA
266/* Allocate a new thread of inferior INF with target id PTID and add
267 it to the thread list. */
e58b0e63
PA
268
269static struct thread_info *
5d5658a1 270new_thread (struct inferior *inf, ptid_t ptid)
e58b0e63 271{
12316564 272 thread_info *tp = new thread_info (inf, ptid);
b05b1202 273
5b0a3d62
AB
274 threads_debug_printf ("creating a new thread object, inferior %d, ptid %s",
275 inf->num, ptid.to_string ().c_str ());
276
bf809310 277 inf->thread_list.push_back (*tp);
e58b0e63 278
922cc93d
SM
279 /* A thread with this ptid should not exist in the map yet. */
280 gdb_assert (inf->ptid_thread_map.find (ptid) == inf->ptid_thread_map.end ());
281
282 inf->ptid_thread_map[ptid] = tp;
283
e58b0e63
PA
284 return tp;
285}
286
30e7e0a9
SM
287/* Notify interpreters and observers that thread T has been created. */
288
289static void
290notify_new_thread (thread_info *t)
291{
292 interps_notify_new_thread (t);
293 gdb::observers::new_thread.notify (t);
294}
295
0d06e24b 296struct thread_info *
5b6d1e4f 297add_thread_silent (process_stratum_target *targ, ptid_t ptid)
c906108c 298{
f53fc427
SM
299 gdb_assert (targ != nullptr);
300
3922b302 301 inferior *inf = find_inferior_ptid (targ, ptid);
5b6d1e4f 302
5b0a3d62
AB
303 threads_debug_printf ("add thread to inferior %d, ptid %s, target %s",
304 inf->num, ptid.to_string ().c_str (),
305 targ->shortname ());
306
3922b302
PA
307 /* We may have an old thread with the same id in the thread list.
308 If we do, it must be dead, otherwise we wouldn't be adding a new
309 thread with the same id. The OS is reusing this id --- delete
310 the old thread, and create a new one. */
3c8af02f 311 thread_info *tp = inf->find_thread (ptid);
3922b302
PA
312 if (tp != nullptr)
313 delete_thread (tp);
4f8d22e3 314
5d5658a1 315 tp = new_thread (inf, ptid);
30e7e0a9 316 notify_new_thread (tp);
cfc01461 317
0d06e24b 318 return tp;
c906108c
SS
319}
320
93815fbf 321struct thread_info *
5b6d1e4f 322add_thread_with_info (process_stratum_target *targ, ptid_t ptid,
d0ffdf64 323 private_thread_info_up priv)
93815fbf 324{
5b6d1e4f 325 thread_info *result = add_thread_silent (targ, ptid);
93815fbf 326
d0ffdf64 327 result->priv = std::move (priv);
17faa917 328
93815fbf 329 if (print_thread_events)
6cb06a8c 330 gdb_printf (_("[New %s]\n"), target_pid_to_str (ptid).c_str ());
d4fc5b1e
NR
331
332 annotate_new_thread ();
93815fbf
VP
333 return result;
334}
335
17faa917 336struct thread_info *
5b6d1e4f 337add_thread (process_stratum_target *targ, ptid_t ptid)
17faa917 338{
5b6d1e4f 339 return add_thread_with_info (targ, ptid, NULL);
17faa917
DJ
340}
341
7aabaf9d
SM
342private_thread_info::~private_thread_info () = default;
343
12316564
YQ
344thread_info::thread_info (struct inferior *inf_, ptid_t ptid_)
345 : ptid (ptid_), inf (inf_)
346{
347 gdb_assert (inf_ != NULL);
348
349 this->global_num = ++highest_thread_num;
350 this->per_inf_num = ++inf_->highest_thread_num;
351
352 /* Nothing to follow yet. */
183be222 353 this->pending_follow.set_spurious ();
12316564
YQ
354}
355
08036331
PA
356/* See gdbthread.h. */
357
5b0a3d62
AB
358thread_info::~thread_info ()
359{
360 threads_debug_printf ("thread %s", this->ptid.to_string ().c_str ());
361}
362
363/* See gdbthread.h. */
364
08036331
PA
365bool
366thread_info::deletable () const
367{
368 /* If this is the current thread, or there's code out there that
369 relies on it existing (refcount > 0) we can't delete yet. */
5b6d1e4f 370 return refcount () == 0 && !is_current_thread (this);
08036331
PA
371}
372
c2829269
PA
373/* See gdbthread.h. */
374
611841bb
AB
375void
376thread_info::set_executing (bool executing)
377{
378 m_executing = executing;
379 if (executing)
351031f2 380 this->clear_stop_pc ();
611841bb
AB
381}
382
383/* See gdbthread.h. */
384
a66f7298
SM
385void
386thread_info::set_resumed (bool resumed)
387{
388 if (resumed == m_resumed)
389 return;
390
391 process_stratum_target *proc_target = this->inf->process_target ();
392
393 /* If we transition from resumed to not resumed, we might need to remove
394 the thread from the resumed threads with pending statuses list. */
395 if (!resumed)
396 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
397
398 m_resumed = resumed;
399
400 /* If we transition from not resumed to resumed, we might need to add
401 the thread to the resumed threads with pending statuses list. */
402 if (resumed)
403 proc_target->maybe_add_resumed_with_pending_wait_status (this);
404}
405
406/* See gdbthread.h. */
407
1edb66d8
SM
408void
409thread_info::set_pending_waitstatus (const target_waitstatus &ws)
410{
411 gdb_assert (!this->has_pending_waitstatus ());
412
413 m_suspend.waitstatus = ws;
414 m_suspend.waitstatus_pending_p = 1;
a66f7298
SM
415
416 process_stratum_target *proc_target = this->inf->process_target ();
417 proc_target->maybe_add_resumed_with_pending_wait_status (this);
1edb66d8
SM
418}
419
420/* See gdbthread.h. */
421
422void
423thread_info::clear_pending_waitstatus ()
424{
425 gdb_assert (this->has_pending_waitstatus ());
426
a66f7298
SM
427 process_stratum_target *proc_target = this->inf->process_target ();
428 proc_target->maybe_remove_resumed_with_pending_wait_status (this);
429
1edb66d8
SM
430 m_suspend.waitstatus_pending_p = 0;
431}
432
433/* See gdbthread.h. */
434
65c459ab
PA
435void
436thread_info::set_thread_options (gdb_thread_options thread_options)
437{
21d48304
PA
438 gdb_assert (this->state != THREAD_EXITED);
439 gdb_assert (!this->executing ());
440
65c459ab
PA
441 if (m_thread_options == thread_options)
442 return;
443
444 m_thread_options = thread_options;
445
446 infrun_debug_printf ("[options for %s are now %s]",
447 this->ptid.to_string ().c_str (),
448 to_string (thread_options).c_str ());
449}
450
451/* See gdbthread.h. */
452
c2829269
PA
453int
454thread_is_in_step_over_chain (struct thread_info *tp)
455{
8b6a69b2 456 return tp->step_over_list_node.is_linked ();
c2829269
PA
457}
458
459/* See gdbthread.h. */
460
187b041e 461int
8b6a69b2 462thread_step_over_chain_length (const thread_step_over_list &l)
187b041e 463{
c316c0b2 464 int num = 0;
187b041e 465
8b6a69b2 466 for (const thread_info &thread ATTRIBUTE_UNUSED : l)
187b041e
SM
467 ++num;
468
469 return num;
470}
471
472/* See gdbthread.h. */
473
c2829269 474void
28d5518b 475global_thread_step_over_chain_enqueue (struct thread_info *tp)
c2829269 476{
187b041e 477 infrun_debug_printf ("enqueueing thread %s in global step over chain",
e53c95d4 478 tp->ptid.to_string ().c_str ());
187b041e 479
8b6a69b2
SM
480 gdb_assert (!thread_is_in_step_over_chain (tp));
481 global_thread_step_over_list.push_back (*tp);
c2829269
PA
482}
483
484/* See gdbthread.h. */
485
187b041e 486void
8b6a69b2 487global_thread_step_over_chain_enqueue_chain (thread_step_over_list &&list)
187b041e 488{
8b6a69b2 489 global_thread_step_over_list.splice (std::move (list));
187b041e
SM
490}
491
492/* See gdbthread.h. */
493
c2829269 494void
28d5518b 495global_thread_step_over_chain_remove (struct thread_info *tp)
c2829269 496{
187b041e 497 infrun_debug_printf ("removing thread %s from global step over chain",
e53c95d4 498 tp->ptid.to_string ().c_str ());
187b041e 499
8b6a69b2
SM
500 gdb_assert (thread_is_in_step_over_chain (tp));
501 auto it = global_thread_step_over_list.iterator_to (*tp);
502 global_thread_step_over_list.erase (it);
c2829269
PA
503}
504
9d7d58e7 505/* Helper for the different delete_thread variants. */
00431a78 506
86be3050 507static void
6b09f134 508delete_thread_1 (thread_info *thr, std::optional<ULONGEST> exit_code,
9d7d58e7 509 bool silent)
c906108c 510{
2eab46b1 511 gdb_assert (thr != nullptr);
c906108c 512
9d7d58e7
PA
513 threads_debug_printf ("deleting thread %s, exit_code = %s, silent = %d",
514 thr->ptid.to_string ().c_str (),
515 (exit_code.has_value ()
516 ? pulongest (*exit_code)
517 : "<none>"),
518 silent);
5b0a3d62 519
9d7d58e7 520 set_thread_exited (thr, exit_code, silent);
c906108c 521
bf809310 522 if (!thr->deletable ())
8c25b497 523 {
4f8d22e3
PA
524 /* Will be really deleted some other time. */
525 return;
526 }
527
bf809310
PA
528 auto it = thr->inf->thread_list.iterator_to (*thr);
529 thr->inf->thread_list.erase (it);
c906108c 530
7d1fd671
PA
531 gdb::observers::thread_deleted.notify (thr);
532
bf809310 533 delete thr;
c906108c
SS
534}
535
86be3050
PA
536/* See gdbthread.h. */
537
9d7d58e7
PA
538void
539delete_thread_with_exit_code (thread_info *thread, ULONGEST exit_code,
540 bool silent)
541{
542 delete_thread_1 (thread, exit_code, silent);
543}
544
545/* See gdbthread.h. */
546
86be3050
PA
547void
548delete_thread (thread_info *thread)
549{
9d7d58e7 550 delete_thread_1 (thread, {}, false /* not silent */);
86be3050
PA
551}
552
553void
554delete_thread_silent (thread_info *thread)
555{
9d7d58e7 556 delete_thread_1 (thread, {}, true /* not silent */);
86be3050
PA
557}
558
1e92afda 559struct thread_info *
5d5658a1 560find_thread_global_id (int global_id)
c906108c 561{
08036331 562 for (thread_info *tp : all_threads ())
5d5658a1
PA
563 if (tp->global_num == global_id)
564 return tp;
565
566 return NULL;
567}
568
569static struct thread_info *
570find_thread_id (struct inferior *inf, int thr_num)
571{
08036331
PA
572 for (thread_info *tp : inf->threads ())
573 if (tp->per_inf_num == thr_num)
c906108c
SS
574 return tp;
575
576 return NULL;
577}
578
5b6d1e4f 579/* See gdbthread.h. */
e04ee09e 580
e04ee09e 581struct thread_info *
50a82723
KB
582find_thread_by_handle (gdb::array_view<const gdb_byte> handle,
583 struct inferior *inf)
e04ee09e 584{
50a82723
KB
585 return target_thread_handle_to_thread_info (handle.data (),
586 handle.size (),
587 inf);
e04ee09e
KB
588}
589
0d06e24b
JM
590/*
591 * Thread iterator function.
592 *
593 * Calls a callback function once for each thread, so long as
594 * the callback function returns false. If the callback function
595 * returns true, the iteration will end and the current thread
ae0eee42 596 * will be returned. This can be useful for implementing a
0d06e24b
JM
597 * search for a thread with arbitrary attributes, or for applying
598 * some operation to every thread.
599 *
ae0eee42 600 * FIXME: some of the existing functionality, such as
0d06e24b
JM
601 * "Thread apply all", might be rewritten using this functionality.
602 */
603
604struct thread_info *
58984e4a 605iterate_over_threads (gdb::function_view<bool (struct thread_info *)> callback)
0d06e24b 606{
08036331 607 for (thread_info *tp : all_threads_safe ())
58984e4a 608 if (callback (tp))
08036331 609 return tp;
0d06e24b
JM
610
611 return NULL;
612}
613
08036331
PA
614/* See gdbthread.h. */
615
616bool
617any_thread_p ()
618{
619 for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
620 return true;
621 return false;
622}
623
20874c92 624int
5b6d1e4f 625thread_count (process_stratum_target *proc_target)
20874c92 626{
5b6d1e4f 627 auto rng = all_threads (proc_target);
08036331 628 return std::distance (rng.begin (), rng.end ());
20874c92
VP
629}
630
c6609450
PA
631/* Return the number of non-exited threads in the thread list. */
632
633static int
634live_threads_count (void)
635{
08036331
PA
636 auto rng = all_non_exited_threads ();
637 return std::distance (rng.begin (), rng.end ());
c6609450
PA
638}
639
c906108c 640int
5d5658a1 641valid_global_thread_id (int global_id)
c906108c 642{
08036331 643 for (thread_info *tp : all_threads ())
5d5658a1 644 if (tp->global_num == global_id)
c906108c
SS
645 return 1;
646
647 return 0;
648}
649
5b6d1e4f
PA
650bool
651in_thread_list (process_stratum_target *targ, ptid_t ptid)
c906108c 652{
9213a6d7 653 return targ->find_thread (ptid) != nullptr;
c906108c 654}
8926118c 655
00431a78 656/* Finds the first thread of the inferior. */
bad34192 657
00431a78
PA
658thread_info *
659first_thread_of_inferior (inferior *inf)
bad34192 660{
bf809310
PA
661 if (inf->thread_list.empty ())
662 return nullptr;
663
664 return &inf->thread_list.front ();
bad34192
PA
665}
666
00431a78
PA
667thread_info *
668any_thread_of_inferior (inferior *inf)
2277426b 669{
00431a78 670 gdb_assert (inf->pid != 0);
32990ada 671
219f56b4
PA
672 /* Prefer the current thread, if there's one. */
673 if (inf == current_inferior () && inferior_ptid != null_ptid)
32990ada
PA
674 return inferior_thread ();
675
08036331
PA
676 for (thread_info *tp : inf->non_exited_threads ())
677 return tp;
2277426b
PA
678
679 return NULL;
680}
681
00431a78
PA
682thread_info *
683any_live_thread_of_inferior (inferior *inf)
6c95b8df 684{
32990ada 685 struct thread_info *curr_tp = NULL;
9941e0c5 686 struct thread_info *tp_executing = NULL;
6c95b8df 687
00431a78 688 gdb_assert (inf != NULL && inf->pid != 0);
32990ada
PA
689
690 /* Prefer the current thread if it's not executing. */
00431a78 691 if (inferior_ptid != null_ptid && current_inferior () == inf)
32990ada
PA
692 {
693 /* If the current thread is dead, forget it. If it's not
694 executing, use it. Otherwise, still choose it (below), but
695 only if no other non-executing thread is found. */
696 curr_tp = inferior_thread ();
697 if (curr_tp->state == THREAD_EXITED)
698 curr_tp = NULL;
611841bb 699 else if (!curr_tp->executing ())
32990ada
PA
700 return curr_tp;
701 }
702
08036331
PA
703 for (thread_info *tp : inf->non_exited_threads ())
704 {
611841bb 705 if (!tp->executing ())
08036331 706 return tp;
32990ada 707
08036331
PA
708 tp_executing = tp;
709 }
6c95b8df 710
32990ada
PA
711 /* If both the current thread and all live threads are executing,
712 prefer the current thread. */
713 if (curr_tp != NULL)
714 return curr_tp;
715
716 /* Otherwise, just return an executing thread, if any. */
9941e0c5 717 return tp_executing;
6c95b8df
PA
718}
719
c378eb4e 720/* Return true if TP is an active thread. */
f3f8ece4
PA
721static bool
722thread_alive (thread_info *tp)
c906108c 723{
30596231 724 if (tp->state == THREAD_EXITED)
f3f8ece4
PA
725 return false;
726
727 /* Ensure we're looking at the right target stack. */
728 gdb_assert (tp->inf == current_inferior ());
729
730 return target_thread_alive (tp->ptid);
731}
732
bc75fb44 733/* See gdbthreads.h. */
f3f8ece4 734
bc75fb44 735bool
f3f8ece4
PA
736switch_to_thread_if_alive (thread_info *thr)
737{
738 scoped_restore_current_thread restore_thread;
739
740 /* Switch inferior first, so that we're looking at the right target
741 stack. */
742 switch_to_inferior_no_thread (thr->inf);
743
744 if (thread_alive (thr))
745 {
746 switch_to_thread (thr);
747 restore_thread.dont_restore ();
748 return true;
749 }
750
751 return false;
c906108c
SS
752}
753
e8032dde
PA
754/* See gdbthreads.h. */
755
756void
fba45db2 757prune_threads (void)
c906108c 758{
f3f8ece4
PA
759 scoped_restore_current_thread restore_thread;
760
08036331 761 for (thread_info *tp : all_threads_safe ())
f3f8ece4
PA
762 {
763 switch_to_inferior_no_thread (tp->inf);
764
765 if (!thread_alive (tp))
766 delete_thread (tp);
767 }
c906108c
SS
768}
769
8a06aea7
PA
770/* See gdbthreads.h. */
771
772void
773delete_exited_threads (void)
774{
08036331
PA
775 for (thread_info *tp : all_threads_safe ())
776 if (tp->state == THREAD_EXITED)
777 delete_thread (tp);
8a06aea7
PA
778}
779
85102364 780/* Return true value if stack temporaries are enabled for the thread
00431a78 781 TP. */
6c659fc2 782
fdf07f3a 783bool
00431a78 784thread_stack_temporaries_enabled_p (thread_info *tp)
6c659fc2 785{
6c659fc2 786 if (tp == NULL)
fdf07f3a 787 return false;
6c659fc2
SC
788 else
789 return tp->stack_temporaries_enabled;
790}
791
792/* Push V on to the stack temporaries of the thread with id PTID. */
793
794void
00431a78 795push_thread_stack_temporary (thread_info *tp, struct value *v)
6c659fc2 796{
6c659fc2 797 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
fdf07f3a 798 tp->stack_temporaries.push_back (v);
6c659fc2
SC
799}
800
fdf07f3a 801/* Return true if VAL is among the stack temporaries of the thread
00431a78 802 TP. Return false otherwise. */
6c659fc2 803
fdf07f3a 804bool
00431a78 805value_in_thread_stack_temporaries (struct value *val, thread_info *tp)
6c659fc2 806{
6c659fc2 807 gdb_assert (tp != NULL && tp->stack_temporaries_enabled);
52941706 808 for (value *v : tp->stack_temporaries)
fdf07f3a
TT
809 if (v == val)
810 return true;
6c659fc2 811
fdf07f3a 812 return false;
6c659fc2
SC
813}
814
815/* Return the last of the stack temporaries for thread with id PTID.
816 Return NULL if there are no stack temporaries for the thread. */
817
00431a78
PA
818value *
819get_last_thread_stack_temporary (thread_info *tp)
6c659fc2
SC
820{
821 struct value *lastval = NULL;
6c659fc2
SC
822
823 gdb_assert (tp != NULL);
fdf07f3a
TT
824 if (!tp->stack_temporaries.empty ())
825 lastval = tp->stack_temporaries.back ();
6c659fc2
SC
826
827 return lastval;
828}
829
5231c1fd 830void
5b6d1e4f
PA
831thread_change_ptid (process_stratum_target *targ,
832 ptid_t old_ptid, ptid_t new_ptid)
5231c1fd 833{
82f73884
PA
834 struct inferior *inf;
835 struct thread_info *tp;
836
837 /* It can happen that what we knew as the target inferior id
838 changes. E.g, target remote may only discover the remote process
839 pid after adding the inferior to GDB's list. */
5b6d1e4f 840 inf = find_inferior_ptid (targ, old_ptid);
e99b03dc 841 inf->pid = new_ptid.pid ();
82f73884 842
3c8af02f 843 tp = inf->find_thread (old_ptid);
922cc93d
SM
844 gdb_assert (tp != nullptr);
845
846 int num_erased = inf->ptid_thread_map.erase (old_ptid);
847 gdb_assert (num_erased == 1);
848
5231c1fd 849 tp->ptid = new_ptid;
922cc93d 850 inf->ptid_thread_map[new_ptid] = tp;
5231c1fd 851
b161a60d 852 gdb::observers::thread_ptid_changed.notify (targ, old_ptid, new_ptid);
5231c1fd
PA
853}
854
372316f1
PA
855/* See gdbthread.h. */
856
857void
5b6d1e4f 858set_resumed (process_stratum_target *targ, ptid_t ptid, bool resumed)
372316f1 859{
5b6d1e4f 860 for (thread_info *tp : all_non_exited_threads (targ, ptid))
7846f3aa 861 tp->set_resumed (resumed);
372316f1
PA
862}
863
4d9d9d04
PA
864/* Helper for set_running, that marks one thread either running or
865 stopped. */
866
719546c4
SM
867static bool
868set_running_thread (struct thread_info *tp, bool running)
4d9d9d04 869{
719546c4 870 bool started = false;
4d9d9d04
PA
871
872 if (running && tp->state == THREAD_STOPPED)
719546c4 873 started = true;
4d9d9d04
PA
874 tp->state = running ? THREAD_RUNNING : THREAD_STOPPED;
875
58fd1204
AB
876 threads_debug_printf ("thread: %s, running? %d%s",
877 tp->ptid.to_string ().c_str (), running,
f9e2163a 878 (started ? " (started)" : ""));
58fd1204 879
4d9d9d04
PA
880 if (!running)
881 {
882 /* If the thread is now marked stopped, remove it from
883 the step-over queue, so that we don't try to resume
884 it until the user wants it to. */
8b6a69b2 885 if (thread_is_in_step_over_chain (tp))
28d5518b 886 global_thread_step_over_chain_remove (tp);
4d9d9d04
PA
887 }
888
889 return started;
890}
891
52d98df7
SM
892/* Notify interpreters and observers that the target was resumed. */
893
894static void
895notify_target_resumed (ptid_t ptid)
896{
897 interps_notify_target_resumed (ptid);
898 gdb::observers::target_resumed.notify (ptid);
96619f15
AB
899
900 /* We are about to resume the inferior. Close all cached BFDs so that
901 when the inferior next stops, and GDB regains control, we will spot
902 any on-disk changes to the BFDs we are using. */
903 bfd_cache_close_all ();
52d98df7
SM
904}
905
00431a78
PA
906/* See gdbthread.h. */
907
908void
909thread_info::set_running (bool running)
910{
911 if (set_running_thread (this, running))
52d98df7 912 notify_target_resumed (this->ptid);
00431a78
PA
913}
914
e1ac3328 915void
5b6d1e4f 916set_running (process_stratum_target *targ, ptid_t ptid, bool running)
e1ac3328 917{
08036331
PA
918 /* We try not to notify the observer if no thread has actually
919 changed the running state -- merely to reduce the number of
920 messages to the MI frontend. A frontend is supposed to handle
921 multiple *running notifications just fine. */
922 bool any_started = false;
e1ac3328 923
5b6d1e4f 924 for (thread_info *tp : all_non_exited_threads (targ, ptid))
08036331
PA
925 if (set_running_thread (tp, running))
926 any_started = true;
4d9d9d04 927
4d9d9d04 928 if (any_started)
52d98df7 929 notify_target_resumed (ptid);
e1ac3328
VP
930}
931
8ea051c5 932void
5b6d1e4f 933set_executing (process_stratum_target *targ, ptid_t ptid, bool executing)
8ea051c5 934{
5b6d1e4f 935 for (thread_info *tp : all_non_exited_threads (targ, ptid))
611841bb 936 tp->set_executing (executing);
8ea051c5 937
08036331 938 /* It only takes one running thread to spawn more threads. */
b57bacec 939 if (executing)
5b6d1e4f 940 targ->threads_executing = true;
b57bacec
PA
941 /* Only clear the flag if the caller is telling us everything is
942 stopped. */
9295a5a9 943 else if (minus_one_ptid == ptid)
5b6d1e4f 944 targ->threads_executing = false;
b57bacec
PA
945}
946
947/* See gdbthread.h. */
948
5b6d1e4f
PA
949bool
950threads_are_executing (process_stratum_target *target)
b57bacec 951{
5b6d1e4f 952 return target->threads_executing;
8ea051c5
PA
953}
954
252fbfc8 955void
5b6d1e4f 956set_stop_requested (process_stratum_target *targ, ptid_t ptid, bool stop)
252fbfc8 957{
5b6d1e4f 958 for (thread_info *tp : all_non_exited_threads (targ, ptid))
08036331 959 tp->stop_requested = stop;
252fbfc8
PA
960
961 /* Call the stop requested observer so other components of GDB can
962 react to this request. */
963 if (stop)
76727919 964 gdb::observers::thread_stop_requested.notify (ptid);
252fbfc8
PA
965}
966
29f49a6a 967void
5b6d1e4f 968finish_thread_state (process_stratum_target *targ, ptid_t ptid)
29f49a6a 969{
08036331 970 bool any_started = false;
29f49a6a 971
5b6d1e4f 972 for (thread_info *tp : all_non_exited_threads (targ, ptid))
611841bb 973 if (set_running_thread (tp, tp->executing ()))
08036331 974 any_started = true;
29f49a6a
PA
975
976 if (any_started)
52d98df7 977 notify_target_resumed (ptid);
29f49a6a
PA
978}
979
a911d87a
PA
980/* See gdbthread.h. */
981
982void
983validate_registers_access (void)
984{
985 /* No selected thread, no registers. */
9295a5a9 986 if (inferior_ptid == null_ptid)
a911d87a
PA
987 error (_("No thread selected."));
988
00431a78
PA
989 thread_info *tp = inferior_thread ();
990
a911d87a 991 /* Don't try to read from a dead thread. */
00431a78 992 if (tp->state == THREAD_EXITED)
a911d87a
PA
993 error (_("The current thread has terminated"));
994
995 /* ... or from a spinning thread. FIXME: This isn't actually fully
996 correct. It'll allow an user-requested access (e.g., "print $pc"
997 at the prompt) when a thread is not executing for some internal
998 reason, but is marked running from the user's perspective. E.g.,
999 the thread is waiting for its turn in the step-over queue. */
611841bb 1000 if (tp->executing ())
2f46cda8
GL
1001 {
1002 /* If we are replaying with the record-full subsystem, even though
1003 the thread is executing, it is always safe to read from it since
1004 replay execution is just GDB reading and writing to a regcache. */
1005 if (!record_full_is_replaying ())
1006 error (_("Selected thread is running."));
1007 }
a911d87a
PA
1008}
1009
cf77c34e
MM
1010/* See gdbthread.h. */
1011
1012bool
00431a78 1013can_access_registers_thread (thread_info *thread)
cf77c34e
MM
1014{
1015 /* No thread, no registers. */
00431a78 1016 if (thread == NULL)
cf77c34e
MM
1017 return false;
1018
1019 /* Don't try to read from a dead thread. */
00431a78 1020 if (thread->state == THREAD_EXITED)
cf77c34e
MM
1021 return false;
1022
1023 /* ... or from a spinning thread. FIXME: see validate_registers_access. */
611841bb 1024 if (thread->executing ())
2f46cda8
GL
1025 {
1026 /* See validate_registers_access. */
1027 if (!record_full_is_replaying ())
1028 return false;
1029 }
cf77c34e
MM
1030
1031 return true;
1032}
1033
6ec27270 1034bool
ce4c476a
PA
1035pc_in_thread_step_range (CORE_ADDR pc, struct thread_info *thread)
1036{
1037 return (pc >= thread->control.step_range_start
1038 && pc < thread->control.step_range_end);
1039}
1040
32c39bab
TBA
1041/* The options for the "info threads" command. */
1042
1043struct info_threads_opts
1044{
1045 /* For "-gid". */
1046 bool show_global_ids = false;
be437614
TBA
1047 /* For "-running". */
1048 bool show_running_threads = false;
1049 /* For "-stopped". */
1050 bool show_stopped_threads = false;
32c39bab
TBA
1051};
1052
1053static const gdb::option::option_def info_threads_option_defs[] = {
1054
1055 gdb::option::flag_option_def<info_threads_opts> {
1056 "gid",
1057 [] (info_threads_opts *opts) { return &opts->show_global_ids; },
1058 N_("Show global thread IDs."),
1059 },
be437614
TBA
1060 gdb::option::flag_option_def<info_threads_opts> {
1061 "running",
1062 [] (info_threads_opts *opts) { return &opts->show_running_threads; },
1063 N_("Show running threads only."),
1064 },
1065 gdb::option::flag_option_def<info_threads_opts> {
1066 "stopped",
1067 [] (info_threads_opts *opts) { return &opts->show_stopped_threads; },
1068 N_("Show stopped threads only."),
1069 },
32c39bab
TBA
1070};
1071
5d5658a1
PA
1072/* Helper for print_thread_info. Returns true if THR should be
1073 printed. If REQUESTED_THREADS, a list of GDB ids/ranges, is not
1074 NULL, only print THR if its ID is included in the list. GLOBAL_IDS
1075 is true if REQUESTED_THREADS is list of global IDs, false if a list
1076 of per-inferior thread ids. If PID is not -1, only print THR if it
1077 is a thread from the process PID. Otherwise, threads from all
1078 attached PIDs are printed. If both REQUESTED_THREADS is not NULL
1079 and PID is not -1, then the thread is printed if it belongs to the
32c39bab
TBA
1080 specified process. Otherwise, an error is raised. OPTS is the
1081 options of the "info threads" command. */
5d5658a1 1082
9278aa61 1083static bool
32c39bab
TBA
1084should_print_thread (const char *requested_threads,
1085 const info_threads_opts &opts, int default_inf_num,
1086 int global_ids, int pid, thread_info *thr)
5d5658a1
PA
1087{
1088 if (requested_threads != NULL && *requested_threads != '\0')
1089 {
1090 int in_list;
1091
1092 if (global_ids)
1093 in_list = number_is_in_list (requested_threads, thr->global_num);
1094 else
1095 in_list = tid_is_in_list (requested_threads, default_inf_num,
1096 thr->inf->num, thr->per_inf_num);
1097 if (!in_list)
9278aa61 1098 return false;
5d5658a1
PA
1099 }
1100
e99b03dc 1101 if (pid != -1 && thr->ptid.pid () != pid)
5d5658a1
PA
1102 {
1103 if (requested_threads != NULL && *requested_threads != '\0')
1104 error (_("Requested thread not found in requested process"));
9278aa61 1105 return false;
5d5658a1
PA
1106 }
1107
1108 if (thr->state == THREAD_EXITED)
9278aa61 1109 return false;
5d5658a1 1110
be437614
TBA
1111 bool is_stopped = (thr->state == THREAD_STOPPED);
1112 if (opts.show_stopped_threads && is_stopped)
1113 return true;
1114
1115 bool is_running = (thr->state == THREAD_RUNNING);
1116 if (opts.show_running_threads && is_running)
1117 return true;
1118
1119 /* If the user did not pass a filter flag, show the thread. */
1120 return (!opts.show_stopped_threads
1121 && !opts.show_running_threads);
5d5658a1
PA
1122}
1123
75acb486
PA
1124/* Return the string to display in "info threads"'s "Target Id"
1125 column, for TP. */
1126
1127static std::string
1128thread_target_id_str (thread_info *tp)
1129{
a068643d 1130 std::string target_id = target_pid_to_str (tp->ptid);
75acb486 1131 const char *extra_info = target_extra_thread_info (tp);
25558938 1132 const char *name = thread_name (tp);
75acb486
PA
1133
1134 if (extra_info != nullptr && name != nullptr)
a068643d
TT
1135 return string_printf ("%s \"%s\" (%s)", target_id.c_str (), name,
1136 extra_info);
75acb486 1137 else if (extra_info != nullptr)
a068643d 1138 return string_printf ("%s (%s)", target_id.c_str (), extra_info);
75acb486 1139 else if (name != nullptr)
a068643d 1140 return string_printf ("%s \"%s\"", target_id.c_str (), name);
75acb486
PA
1141 else
1142 return target_id;
1143}
1144
519d6343
AM
1145/* Print thread TP. GLOBAL_IDS indicates whether REQUESTED_THREADS
1146 is a list of global or per-inferior thread ids. */
1147
1148static void
1149do_print_thread (ui_out *uiout, const char *requested_threads,
32c39bab
TBA
1150 const info_threads_opts &opts, int global_ids,
1151 int pid, int default_inf_num, thread_info *tp,
519d6343
AM
1152 thread_info *current_thread)
1153{
1154 int core;
1155
1156 /* In case REQUESTED_THREADS contains $_thread. */
1157 if (current_thread != nullptr)
1158 switch_to_thread (current_thread);
1159
32c39bab 1160 if (!should_print_thread (requested_threads, opts, default_inf_num,
519d6343
AM
1161 global_ids, pid, tp))
1162 return;
1163
1164 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1165
1166 if (!uiout->is_mi_like_p ())
1167 {
1168 if (tp == current_thread)
1169 uiout->field_string ("current", "*");
1170 else
1171 uiout->field_skip ("current");
1172
1173 uiout->field_string ("id-in-tg", print_thread_id (tp));
1174 }
1175
32c39bab 1176 if (opts.show_global_ids || uiout->is_mi_like_p ())
519d6343
AM
1177 uiout->field_signed ("id", tp->global_num);
1178
1179 /* Switch to the thread (and inferior / target). */
1180 switch_to_thread (tp);
1181
1182 /* For the CLI, we stuff everything into the target-id field.
1183 This is a gross hack to make the output come out looking
1184 correct. The underlying problem here is that ui-out has no
1185 way to specify that a field's space allocation should be
1186 shared by several fields. For MI, we do the right thing
1187 instead. */
1188
1189 if (uiout->is_mi_like_p ())
1190 {
1191 uiout->field_string ("target-id", target_pid_to_str (tp->ptid));
1192
1193 const char *extra_info = target_extra_thread_info (tp);
1194 if (extra_info != nullptr)
1195 uiout->field_string ("details", extra_info);
1196
1197 const char *name = thread_name (tp);
1198 if (name != NULL)
1199 uiout->field_string ("name", name);
1200 }
1201 else
1202 {
1203 uiout->field_string ("target-id", thread_target_id_str (tp));
1204 }
1205
1206 if (tp->state == THREAD_RUNNING)
1207 uiout->text ("(running)\n");
1208 else
1209 {
1210 /* The switch above put us at the top of the stack (leaf
1211 frame). */
1212 print_stack_frame (get_selected_frame (NULL),
1213 /* For MI output, print frame level. */
1214 uiout->is_mi_like_p (),
1215 LOCATION, 0);
1216 }
1217
1218 if (uiout->is_mi_like_p ())
1219 {
1220 const char *state = "stopped";
1221
1222 if (tp->state == THREAD_RUNNING)
1223 state = "running";
1224 uiout->field_string ("state", state);
1225 }
1226
1227 core = target_core_of_thread (tp->ptid);
1228 if (uiout->is_mi_like_p () && core != -1)
1229 uiout->field_signed ("core", core);
1230}
1231
1232/* Redirect output to a temporary buffer for the duration
1233 of do_print_thread. */
1234
1235static void
1236print_thread (ui_out *uiout, const char *requested_threads,
32c39bab 1237 const info_threads_opts &opts, int global_ids, int pid,
519d6343
AM
1238 int default_inf_num, thread_info *tp, thread_info *current_thread)
1239
1240{
1241 do_with_buffered_output (do_print_thread, uiout, requested_threads,
32c39bab
TBA
1242 opts, global_ids, pid, default_inf_num, tp,
1243 current_thread);
519d6343
AM
1244}
1245
5d5658a1
PA
1246/* Like print_thread_info, but in addition, GLOBAL_IDS indicates
1247 whether REQUESTED_THREADS is a list of global or per-inferior
32c39bab 1248 thread ids. OPTS is the options of the "info threads" command. */
5d5658a1
PA
1249
1250static void
1d12d88f 1251print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
32c39bab 1252 const info_threads_opts &opts, int global_ids, int pid)
c906108c 1253{
5d5658a1 1254 int default_inf_num = current_inferior ()->num;
c906108c 1255
dc146f7c 1256 update_thread_list ();
00431a78
PA
1257
1258 /* Whether we saw any thread. */
1259 bool any_thread = false;
1260 /* Whether the current thread is exited. */
1261 bool current_exited = false;
1262
1263 thread_info *current_thread = (inferior_ptid != null_ptid
1264 ? inferior_thread () : NULL);
4f8d22e3 1265
f8cc3da6
TT
1266 {
1267 /* For backward compatibility, we make a list for MI. A table is
1268 preferable for the CLI, though, because it shows table
1269 headers. */
6b09f134
LS
1270 std::optional<ui_out_emit_list> list_emitter;
1271 std::optional<ui_out_emit_table> table_emitter;
f8cc3da6 1272
f3f8ece4
PA
1273 /* We'll be switching threads temporarily below. */
1274 scoped_restore_current_thread restore_thread;
1275
f8cc3da6
TT
1276 if (uiout->is_mi_like_p ())
1277 list_emitter.emplace (uiout, "threads");
1278 else
1279 {
be437614 1280 int n_matching_threads = 0;
75acb486
PA
1281 /* The width of the "Target Id" column. Grown below to
1282 accommodate the largest entry. */
1283 size_t target_id_col_width = 17;
a7658b96 1284
08036331 1285 for (thread_info *tp : all_threads ())
f8cc3da6 1286 {
be437614
TBA
1287 any_thread = true;
1288
52e0b52e
HD
1289 /* In case REQUESTED_THREADS contains $_thread. */
1290 if (current_thread != nullptr)
1291 switch_to_thread (current_thread);
1292
32c39bab
TBA
1293 if (!should_print_thread (requested_threads, opts,
1294 default_inf_num, global_ids, pid, tp))
f8cc3da6 1295 continue;
a7658b96 1296
85413975
AH
1297 /* Switch inferiors so we're looking at the right
1298 target stack. */
1299 switch_to_inferior_no_thread (tp->inf);
1300
1301 target_id_col_width
1302 = std::max (target_id_col_width,
1303 thread_target_id_str (tp).size ());
75acb486 1304
be437614 1305 ++n_matching_threads;
f8cc3da6 1306 }
a7658b96 1307
be437614 1308 if (n_matching_threads == 0)
f8cc3da6 1309 {
be437614 1310 if (!any_thread)
f8cc3da6
TT
1311 uiout->message (_("No threads.\n"));
1312 else
0ea1e5df 1313 uiout->message (_("No threads matched.\n"));
f8cc3da6
TT
1314 return;
1315 }
a7658b96 1316
32c39bab 1317 table_emitter.emplace (uiout, opts.show_global_ids ? 5 : 4,
be437614 1318 n_matching_threads, "threads");
a7658b96 1319
f8cc3da6 1320 uiout->table_header (1, ui_left, "current", "");
0d64823e 1321 uiout->table_header (4, ui_left, "id-in-tg", "Id");
32c39bab 1322 if (opts.show_global_ids)
f8cc3da6 1323 uiout->table_header (4, ui_left, "id", "GId");
75acb486
PA
1324 uiout->table_header (target_id_col_width, ui_left,
1325 "target-id", "Target Id");
f8cc3da6
TT
1326 uiout->table_header (1, ui_left, "frame", "Frame");
1327 uiout->table_body ();
1328 }
a7658b96 1329
08036331
PA
1330 for (inferior *inf : all_inferiors ())
1331 for (thread_info *tp : inf->threads ())
3061113b 1332 {
3061113b
SM
1333 if (tp == current_thread && tp->state == THREAD_EXITED)
1334 current_exited = true;
1335
32c39bab
TBA
1336 print_thread (uiout, requested_threads, opts, global_ids, pid,
1337 default_inf_num, tp, current_thread);
3061113b 1338 }
c906108c 1339
5ed8105e 1340 /* This end scope restores the current thread and the frame
f8cc3da6
TT
1341 selected before the "info threads" command, and it finishes the
1342 ui-out list or table. */
5ed8105e
PA
1343 }
1344
aea5b279 1345 if (pid == -1 && requested_threads == NULL)
8e8901c5 1346 {
00431a78 1347 if (uiout->is_mi_like_p () && inferior_ptid != null_ptid)
381befee 1348 uiout->field_signed ("current-thread-id", current_thread->global_num);
5d5658a1 1349
00431a78 1350 if (inferior_ptid != null_ptid && current_exited)
112e8700 1351 uiout->message ("\n\
5d5658a1
PA
1352The current thread <Thread ID %s> has terminated. See `help thread'.\n",
1353 print_thread_id (inferior_thread ()));
00431a78 1354 else if (any_thread && inferior_ptid == null_ptid)
112e8700 1355 uiout->message ("\n\
d729566a 1356No selected thread. See `help thread'.\n");
c906108c 1357 }
c906108c
SS
1358}
1359
5d5658a1 1360/* See gdbthread.h. */
8e8901c5 1361
5d5658a1 1362void
24c54127
TT
1363print_thread_info (struct ui_out *uiout, const char *requested_threads,
1364 int pid)
5d5658a1 1365{
32c39bab
TBA
1366 info_threads_opts opts;
1367 print_thread_info_1 (uiout, requested_threads, opts, 1, pid);
5d5658a1
PA
1368}
1369
54d66006
PA
1370/* Create an option_def_group for the "info threads" options, with
1371 IT_OPTS as context. */
1372
1373static inline gdb::option::option_def_group
1374make_info_threads_options_def_group (info_threads_opts *it_opts)
1375{
1376 return {{info_threads_option_defs}, it_opts};
1377}
1378
5d5658a1 1379/* Implementation of the "info threads" command.
60f98dde
MS
1380
1381 Note: this has the drawback that it _really_ switches
ae0eee42
PA
1382 threads, which frees the frame cache. A no-side
1383 effects info-threads command would be nicer. */
8e8901c5
VP
1384
1385static void
1d12d88f 1386info_threads_command (const char *arg, int from_tty)
8e8901c5 1387{
54d66006
PA
1388 info_threads_opts it_opts;
1389
1390 auto grp = make_info_threads_options_def_group (&it_opts);
1391 gdb::option::process_options
1392 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1393
32c39bab 1394 print_thread_info_1 (current_uiout, arg, it_opts, 0, -1);
54d66006
PA
1395}
1396
1397/* Completer for the "info threads" command. */
c84f6bbf 1398
54d66006
PA
1399static void
1400info_threads_command_completer (struct cmd_list_element *ignore,
1401 completion_tracker &tracker,
1402 const char *text, const char *word_ignored)
1403{
1404 const auto grp = make_info_threads_options_def_group (nullptr);
1405
1406 if (gdb::option::complete_options
1407 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1408 return;
1409
1410 /* Convenience to let the user know what the option can accept. */
1411 if (*text == '\0')
c84f6bbf 1412 {
54d66006
PA
1413 gdb::option::complete_on_all_options (tracker, grp);
1414 /* Keep this "ID" in sync with what "help info threads"
1415 says. */
1416 tracker.add_completion (make_unique_xstrdup ("ID"));
c84f6bbf 1417 }
8e8901c5
VP
1418}
1419
6efcd9a8
PA
1420/* See gdbthread.h. */
1421
1422void
1423switch_to_thread_no_regs (struct thread_info *thread)
1424{
58fd1204
AB
1425 gdb_assert (thread != nullptr);
1426 threads_debug_printf ("thread = %s", thread->ptid.to_string ().c_str ());
1427
3a3fd0fd 1428 struct inferior *inf = thread->inf;
6efcd9a8 1429
6efcd9a8
PA
1430 set_current_program_space (inf->pspace);
1431 set_current_inferior (inf);
1432
3922b302
PA
1433 current_thread_ = thread;
1434 inferior_ptid = current_thread_->ptid;
6efcd9a8
PA
1435}
1436
00431a78 1437/* See gdbthread.h. */
c906108c 1438
00431a78 1439void
3a3fd0fd 1440switch_to_no_thread ()
c906108c 1441{
3922b302 1442 if (current_thread_ == nullptr)
3a3fd0fd 1443 return;
6c95b8df 1444
58fd1204
AB
1445 threads_debug_printf ("thread = NONE");
1446
3922b302 1447 current_thread_ = nullptr;
3a3fd0fd
PA
1448 inferior_ptid = null_ptid;
1449 reinit_frame_cache ();
3a3fd0fd
PA
1450}
1451
00431a78 1452/* See gdbthread.h. */
6c95b8df 1453
00431a78 1454void
3a3fd0fd
PA
1455switch_to_thread (thread_info *thr)
1456{
1457 gdb_assert (thr != NULL);
1458
5b6d1e4f 1459 if (is_current_thread (thr))
c906108c
SS
1460 return;
1461
3a3fd0fd
PA
1462 switch_to_thread_no_regs (thr);
1463
35f196d9 1464 reinit_frame_cache ();
c906108c
SS
1465}
1466
268a13a5 1467/* See gdbsupport/common-gdbthread.h. */
3a3fd0fd
PA
1468
1469void
5b6d1e4f 1470switch_to_thread (process_stratum_target *proc_target, ptid_t ptid)
c906108c 1471{
9213a6d7 1472 thread_info *thr = proc_target->find_thread (ptid);
00431a78 1473 switch_to_thread (thr);
99b3d574
DP
1474}
1475
79952e69
PA
1476/* See frame.h. */
1477
873657b9
PA
1478void
1479scoped_restore_current_thread::restore ()
6ecce94d 1480{
803bdfe4
YQ
1481 /* If an entry of thread_info was previously selected, it won't be
1482 deleted because we've increased its refcount. The thread represented
1483 by this thread_info entry may have already exited (due to normal exit,
1484 detach, etc), so the thread_info.state is THREAD_EXITED. */
5ed8105e 1485 if (m_thread != NULL
803bdfe4
YQ
1486 /* If the previously selected thread belonged to a process that has
1487 in the mean time exited (or killed, detached, etc.), then don't revert
1488 back to it, but instead simply drop back to no thread selected. */
5ed8105e 1489 && m_inf->pid != 0)
cce20f10 1490 switch_to_thread (m_thread.get ());
88fc996f 1491 else
cce20f10 1492 switch_to_inferior_no_thread (m_inf.get ());
94cc34af 1493
4f8d22e3
PA
1494 /* The running state of the originally selected thread may have
1495 changed, so we have to recheck it here. */
9295a5a9 1496 if (inferior_ptid != null_ptid
5ed8105e 1497 && m_was_stopped
00431a78 1498 && m_thread->state == THREAD_STOPPED
9dccd06e 1499 && target_has_registers ()
841de120 1500 && target_has_stack ()
a739972c 1501 && target_has_memory ())
5ed8105e 1502 restore_selected_frame (m_selected_frame_id, m_selected_frame_level);
873657b9
PA
1503}
1504
1505scoped_restore_current_thread::~scoped_restore_current_thread ()
1506{
0a008773
TT
1507 if (m_dont_restore)
1508 m_lang.dont_restore ();
1509 else
79952e69 1510 restore ();
6ecce94d
AC
1511}
1512
5ed8105e 1513scoped_restore_current_thread::scoped_restore_current_thread ()
6ecce94d 1514{
cce20f10 1515 m_inf = inferior_ref::new_reference (current_inferior ());
4f8d22e3 1516
9295a5a9 1517 if (inferior_ptid != null_ptid)
d729566a 1518 {
cce20f10
PA
1519 m_thread = thread_info_ref::new_reference (inferior_thread ());
1520
cce20f10 1521 m_was_stopped = m_thread->state == THREAD_STOPPED;
79952e69 1522 save_selected_frame (&m_selected_frame_id, &m_selected_frame_level);
d729566a 1523 }
6ecce94d
AC
1524}
1525
348da456
SM
1526scoped_restore_current_thread::scoped_restore_current_thread
1527 (scoped_restore_current_thread &&rhs)
1528 : m_dont_restore (std::move (rhs.m_dont_restore)),
1529 m_thread (std::move (rhs.m_thread)),
1530 m_inf (std::move (rhs.m_inf)),
1531 m_selected_frame_id (std::move (rhs.m_selected_frame_id)),
1532 m_selected_frame_level (std::move (rhs.m_selected_frame_level)),
1533 m_was_stopped (std::move (rhs.m_was_stopped)),
1534 m_lang (std::move (rhs.m_lang))
1535{
1536 /* Deactivate the rhs. */
1537 rhs.m_dont_restore = true;
1538}
1539
43792cf0
PA
1540/* See gdbthread.h. */
1541
f303dbd6
PA
1542int
1543show_thread_that_caused_stop (void)
1544{
1545 return highest_thread_num > 1;
1546}
1547
1548/* See gdbthread.h. */
1549
5d5658a1
PA
1550int
1551show_inferior_qualified_tids (void)
1552{
08bdefb5
PA
1553 auto inf = inferior_list.begin ();
1554 if (inf->num != 1)
1555 return true;
1556 ++inf;
1557 return inf != inferior_list.end ();
5d5658a1
PA
1558}
1559
1560/* See gdbthread.h. */
1561
43792cf0
PA
1562const char *
1563print_thread_id (struct thread_info *thr)
1564{
442716d4
AB
1565 if (show_inferior_qualified_tids ())
1566 return print_full_thread_id (thr);
1567
1568 char *s = get_print_cell ();
1569
2968b79f 1570 gdb_assert (thr != nullptr);
442716d4
AB
1571 xsnprintf (s, PRINT_CELL_SIZE, "%d", thr->per_inf_num);
1572 return s;
1573}
2968b79f 1574
442716d4
AB
1575/* See gdbthread.h. */
1576
1577const char *
1578print_full_thread_id (struct thread_info *thr)
1579{
43792cf0
PA
1580 char *s = get_print_cell ();
1581
442716d4
AB
1582 gdb_assert (thr != nullptr);
1583 xsnprintf (s, PRINT_CELL_SIZE, "%d.%d", thr->inf->num, thr->per_inf_num);
43792cf0
PA
1584 return s;
1585}
1586
6665660a
PA
1587/* Sort an array of struct thread_info pointers by thread ID (first by
1588 inferior number, and then by per-inferior thread number). Sorts in
1589 ascending order. */
253828f1 1590
6665660a 1591static bool
bfcb9db8 1592tp_array_compar_ascending (const thread_info_ref &a, const thread_info_ref &b)
6665660a
PA
1593{
1594 if (a->inf->num != b->inf->num)
1595 return a->inf->num < b->inf->num;
1596
1597 return (a->per_inf_num < b->per_inf_num);
1598}
253828f1 1599
6665660a
PA
1600/* Sort an array of struct thread_info pointers by thread ID (first by
1601 inferior number, and then by per-inferior thread number). Sorts in
1602 descending order. */
253828f1 1603
c6609450 1604static bool
bfcb9db8 1605tp_array_compar_descending (const thread_info_ref &a, const thread_info_ref &b)
253828f1 1606{
5d5658a1 1607 if (a->inf->num != b->inf->num)
6665660a 1608 return a->inf->num > b->inf->num;
253828f1 1609
6665660a 1610 return (a->per_inf_num > b->per_inf_num);
253828f1
JK
1611}
1612
bc75fb44 1613/* See gdbthread.h. */
1fe75df7 1614
bc75fb44 1615void
6b09f134 1616thread_try_catch_cmd (thread_info *thr, std::optional<int> ada_task,
bc75fb44
TT
1617 const char *cmd, int from_tty,
1618 const qcs_flags &flags)
1fe75df7 1619{
0f93c3a2 1620 gdb_assert (is_current_thread (thr));
b65ce565
JG
1621
1622 /* The thread header is computed before running the command since
1623 the command can change the inferior, which is not permitted
1624 by thread_target_id_str. */
bc75fb44
TT
1625 std::string thr_header;
1626 if (ada_task.has_value ())
1627 thr_header = string_printf (_("\nTask ID %d:\n"), *ada_task);
1628 else
1629 thr_header = string_printf (_("\nThread %s (%s):\n"),
1630 print_thread_id (thr),
1631 thread_target_id_str (thr).c_str ());
b65ce565 1632
a70b8144 1633 try
1fe75df7 1634 {
84a6adfd
TV
1635 std::string cmd_result;
1636 execute_command_to_string
1637 (cmd_result, cmd, from_tty, gdb_stdout->term_out ());
1fe75df7
PW
1638 if (!flags.silent || cmd_result.length () > 0)
1639 {
1640 if (!flags.quiet)
6cb06a8c
TT
1641 gdb_printf ("%s", thr_header.c_str ());
1642 gdb_printf ("%s", cmd_result.c_str ());
1fe75df7
PW
1643 }
1644 }
230d2906 1645 catch (const gdb_exception_error &ex)
1fe75df7
PW
1646 {
1647 if (!flags.silent)
1648 {
1649 if (!flags.quiet)
6cb06a8c 1650 gdb_printf ("%s", thr_header.c_str ());
1fe75df7 1651 if (flags.cont)
6cb06a8c 1652 gdb_printf ("%s\n", ex.what ());
1fe75df7 1653 else
eedc3f4f 1654 throw;
1fe75df7
PW
1655 }
1656 }
1fe75df7
PW
1657}
1658
6665660a
PA
1659/* Option definition of "thread apply"'s "-ascending" option. */
1660
1661static const gdb::option::flag_option_def<> ascending_option_def = {
1662 "ascending",
1663 N_("\
1664Call COMMAND for all threads in ascending order.\n\
1665The default is descending order."),
1666};
1667
1668/* The qcs command line flags for the "thread apply" commands. Keep
1669 this in sync with the "frame apply" commands. */
1670
1671using qcs_flag_option_def
1672 = gdb::option::flag_option_def<qcs_flags>;
1673
1674static const gdb::option::option_def thr_qcs_flags_option_defs[] = {
1675 qcs_flag_option_def {
1676 "q", [] (qcs_flags *opt) { return &opt->quiet; },
1677 N_("Disables printing the thread information."),
1678 },
1679
1680 qcs_flag_option_def {
1681 "c", [] (qcs_flags *opt) { return &opt->cont; },
1682 N_("Print any error raised by COMMAND and continue."),
1683 },
1684
1685 qcs_flag_option_def {
1686 "s", [] (qcs_flags *opt) { return &opt->silent; },
1687 N_("Silently ignore any errors or empty output produced by COMMAND."),
1688 },
1689};
1690
1691/* Create an option_def_group for the "thread apply all" options, with
1692 ASCENDING and FLAGS as context. */
1693
1694static inline std::array<gdb::option::option_def_group, 2>
491144b5 1695make_thread_apply_all_options_def_group (bool *ascending,
6665660a
PA
1696 qcs_flags *flags)
1697{
1698 return {{
66eb1ed3
PA
1699 { {ascending_option_def.def ()}, ascending},
1700 { {thr_qcs_flags_option_defs}, flags },
6665660a
PA
1701 }};
1702}
1703
1704/* Create an option_def_group for the "thread apply" options, with
1705 FLAGS as context. */
1706
1707static inline gdb::option::option_def_group
1708make_thread_apply_options_def_group (qcs_flags *flags)
1709{
66eb1ed3 1710 return {{thr_qcs_flags_option_defs}, flags};
6665660a
PA
1711}
1712
c906108c 1713/* Apply a GDB command to a list of threads. List syntax is a whitespace
224608c3
PW
1714 separated list of numbers, or ranges, or the keyword `all'. Ranges consist
1715 of two numbers separated by a hyphen. Examples:
c906108c 1716
c5aa993b
JM
1717 thread apply 1 2 7 4 backtrace Apply backtrace cmd to threads 1,2,7,4
1718 thread apply 2-7 9 p foo(1) Apply p foo(1) cmd to threads 2->7 & 9
224608c3 1719 thread apply all x/i $pc Apply x/i $pc cmd to all threads. */
c906108c
SS
1720
1721static void
5fed81ff 1722thread_apply_all_command (const char *cmd, int from_tty)
c906108c 1723{
491144b5 1724 bool ascending = false;
1fe75df7
PW
1725 qcs_flags flags;
1726
6665660a
PA
1727 auto group = make_thread_apply_all_options_def_group (&ascending,
1728 &flags);
1729 gdb::option::process_options
1730 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1fe75df7 1731
6665660a 1732 validate_flags_qcs ("thread apply all", &flags);
253828f1 1733
c906108c 1734 if (cmd == NULL || *cmd == '\000')
1fe75df7 1735 error (_("Please specify a command at the end of 'thread apply all'"));
94cc34af 1736
dc146f7c 1737 update_thread_list ();
e9d196c5 1738
c6609450 1739 int tc = live_threads_count ();
a25d8bf9 1740 if (tc != 0)
054e8d9e 1741 {
c6609450
PA
1742 /* Save a copy of the thread list and increment each thread's
1743 refcount while executing the command in the context of each
1744 thread, in case the command is one that wipes threads. E.g.,
1745 detach, kill, disconnect, etc., or even normally continuing
1746 over an inferior or thread exit. */
bfcb9db8 1747 std::vector<thread_info_ref> thr_list_cpy;
c6609450 1748 thr_list_cpy.reserve (tc);
054e8d9e 1749
08036331 1750 for (thread_info *tp : all_non_exited_threads ())
bfcb9db8 1751 thr_list_cpy.push_back (thread_info_ref::new_reference (tp));
08036331 1752 gdb_assert (thr_list_cpy.size () == tc);
054e8d9e 1753
6665660a
PA
1754 auto *sorter = (ascending
1755 ? tp_array_compar_ascending
1756 : tp_array_compar_descending);
1757 std::sort (thr_list_cpy.begin (), thr_list_cpy.end (), sorter);
054e8d9e 1758
5ed8105e
PA
1759 scoped_restore_current_thread restore_thread;
1760
bfcb9db8
TT
1761 for (thread_info_ref &thr : thr_list_cpy)
1762 if (switch_to_thread_if_alive (thr.get ()))
bc75fb44 1763 thread_try_catch_cmd (thr.get (), {}, cmd, from_tty, flags);
054e8d9e 1764 }
c906108c
SS
1765}
1766
6665660a
PA
1767/* Completer for "thread apply [ID list]". */
1768
1769static void
1770thread_apply_command_completer (cmd_list_element *ignore,
1771 completion_tracker &tracker,
1772 const char *text, const char * /*word*/)
1773{
1774 /* Don't leave this to complete_options because there's an early
1775 return below. */
1776 tracker.set_use_custom_word_point (true);
1777
1778 tid_range_parser parser;
1779 parser.init (text, current_inferior ()->num);
1780
1781 try
1782 {
1783 while (!parser.finished ())
1784 {
1785 int inf_num, thr_start, thr_end;
1786
1787 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
1788 break;
1789
1790 if (parser.in_star_range () || parser.in_thread_range ())
1791 parser.skip_range ();
1792 }
1793 }
1794 catch (const gdb_exception_error &ex)
1795 {
1796 /* get_tid_range throws if it parses a negative number, for
1797 example. But a seemingly negative number may be the start of
1798 an option instead. */
1799 }
1800
1801 const char *cmd = parser.cur_tok ();
1802
1803 if (cmd == text)
1804 {
1805 /* No thread ID list yet. */
1806 return;
1807 }
1808
1809 /* Check if we're past a valid thread ID list already. */
1810 if (parser.finished ()
1811 && cmd > text && !isspace (cmd[-1]))
1812 return;
1813
1814 /* We're past the thread ID list, advance word point. */
1815 tracker.advance_custom_word_point_by (cmd - text);
1816 text = cmd;
1817
1818 const auto group = make_thread_apply_options_def_group (nullptr);
1819 if (gdb::option::complete_options
1820 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1821 return;
1822
1823 complete_nested_command_line (tracker, text);
1824}
1825
1826/* Completer for "thread apply all". */
1827
1828static void
1829thread_apply_all_command_completer (cmd_list_element *ignore,
1830 completion_tracker &tracker,
1831 const char *text, const char *word)
1832{
1833 const auto group = make_thread_apply_all_options_def_group (nullptr,
1834 nullptr);
1835 if (gdb::option::complete_options
1836 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
1837 return;
1838
1839 complete_nested_command_line (tracker, text);
1840}
1841
43792cf0
PA
1842/* Implementation of the "thread apply" command. */
1843
c906108c 1844static void
981a3fb3 1845thread_apply_command (const char *tidlist, int from_tty)
c906108c 1846{
1fe75df7 1847 qcs_flags flags;
95a6b0a1 1848 const char *cmd = NULL;
bfd28288 1849 tid_range_parser parser;
c906108c
SS
1850
1851 if (tidlist == NULL || *tidlist == '\000')
8a3fe4f8 1852 error (_("Please specify a thread ID list"));
c906108c 1853
bfd28288
PA
1854 parser.init (tidlist, current_inferior ()->num);
1855 while (!parser.finished ())
3f5b7598
PA
1856 {
1857 int inf_num, thr_start, thr_end;
c906108c 1858
bfd28288 1859 if (!parser.get_tid_range (&inf_num, &thr_start, &thr_end))
b9a3f842 1860 break;
3f5b7598
PA
1861 }
1862
b9a3f842
PA
1863 cmd = parser.cur_tok ();
1864
6665660a
PA
1865 auto group = make_thread_apply_options_def_group (&flags);
1866 gdb::option::process_options
1867 (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
1868
1869 validate_flags_qcs ("thread apply", &flags);
1fe75df7 1870
b9a3f842 1871 if (*cmd == '\0')
8a3fe4f8 1872 error (_("Please specify a command following the thread ID list"));
c906108c 1873
f7e13587 1874 if (tidlist == cmd || isdigit (cmd[0]))
3f5b7598
PA
1875 invalid_thread_id_error (cmd);
1876
5ed8105e 1877 scoped_restore_current_thread restore_thread;
c906108c 1878
bfd28288 1879 parser.init (tidlist, current_inferior ()->num);
b9a3f842 1880 while (!parser.finished ())
5d5658a1
PA
1881 {
1882 struct thread_info *tp = NULL;
1883 struct inferior *inf;
1884 int inf_num, thr_num;
65fc9b77 1885
bfd28288 1886 parser.get_tid (&inf_num, &thr_num);
5d5658a1
PA
1887 inf = find_inferior_id (inf_num);
1888 if (inf != NULL)
1889 tp = find_thread_id (inf, thr_num);
71ef29a8 1890
bfd28288 1891 if (parser.in_star_range ())
71ef29a8
PA
1892 {
1893 if (inf == NULL)
1894 {
1895 warning (_("Unknown inferior %d"), inf_num);
bfd28288 1896 parser.skip_range ();
71ef29a8
PA
1897 continue;
1898 }
1899
1900 /* No use looking for threads past the highest thread number
1901 the inferior ever had. */
1902 if (thr_num >= inf->highest_thread_num)
bfd28288 1903 parser.skip_range ();
71ef29a8
PA
1904
1905 /* Be quiet about unknown threads numbers. */
1906 if (tp == NULL)
1907 continue;
1908 }
1909
5d5658a1
PA
1910 if (tp == NULL)
1911 {
bfd28288 1912 if (show_inferior_qualified_tids () || parser.tid_is_qualified ())
5d5658a1
PA
1913 warning (_("Unknown thread %d.%d"), inf_num, thr_num);
1914 else
1915 warning (_("Unknown thread %d"), thr_num);
1916 continue;
1917 }
c906108c 1918
f3f8ece4 1919 if (!switch_to_thread_if_alive (tp))
65ebfb52 1920 {
5d5658a1
PA
1921 warning (_("Thread %s has terminated."), print_thread_id (tp));
1922 continue;
1923 }
4f8d22e3 1924
bc75fb44 1925 thread_try_catch_cmd (tp, {}, cmd, from_tty, flags);
c906108c
SS
1926 }
1927}
1928
1fe75df7
PW
1929
1930/* Implementation of the "taas" command. */
1931
1932static void
1933taas_command (const char *cmd, int from_tty)
1934{
e0fad1ea
PW
1935 if (cmd == NULL || *cmd == '\0')
1936 error (_("Please specify a command to apply on all threads"));
1fe75df7
PW
1937 std::string expanded = std::string ("thread apply all -s ") + cmd;
1938 execute_command (expanded.c_str (), from_tty);
1939}
1940
1941/* Implementation of the "tfaas" command. */
1942
1943static void
1944tfaas_command (const char *cmd, int from_tty)
1945{
e0fad1ea
PW
1946 if (cmd == NULL || *cmd == '\0')
1947 error (_("Please specify a command to apply on all frames of all threads"));
1fe75df7 1948 std::string expanded
5d707134 1949 = std::string ("thread apply all -s -- frame apply all -s ") + cmd;
1fe75df7
PW
1950 execute_command (expanded.c_str (), from_tty);
1951}
1952
224608c3 1953/* Switch to the specified thread, or print the current thread. */
c906108c 1954
f0e8c4c5 1955void
981a3fb3 1956thread_command (const char *tidstr, int from_tty)
c906108c 1957{
4034d0ff 1958 if (tidstr == NULL)
c906108c 1959 {
9295a5a9 1960 if (inferior_ptid == null_ptid)
d729566a
PA
1961 error (_("No thread selected"));
1962
841de120 1963 if (target_has_stack ())
4f8d22e3 1964 {
43792cf0
PA
1965 struct thread_info *tp = inferior_thread ();
1966
00431a78 1967 if (tp->state == THREAD_EXITED)
6cb06a8c
TT
1968 gdb_printf (_("[Current thread is %s (%s) (exited)]\n"),
1969 print_thread_id (tp),
1970 target_pid_to_str (inferior_ptid).c_str ());
4f8d22e3 1971 else
6cb06a8c
TT
1972 gdb_printf (_("[Current thread is %s (%s)]\n"),
1973 print_thread_id (tp),
1974 target_pid_to_str (inferior_ptid).c_str ());
4f8d22e3 1975 }
c906108c 1976 else
8a3fe4f8 1977 error (_("No stack."));
c906108c 1978 }
4034d0ff
AT
1979 else
1980 {
1981 ptid_t previous_ptid = inferior_ptid;
4034d0ff 1982
65630365 1983 thread_select (tidstr, parse_thread_id (tidstr, NULL));
c5394b80 1984
ae0eee42
PA
1985 /* Print if the thread has not changed, otherwise an event will
1986 be sent. */
9295a5a9 1987 if (inferior_ptid == previous_ptid)
4034d0ff
AT
1988 {
1989 print_selected_thread_frame (current_uiout,
1990 USER_SELECTED_THREAD
1991 | USER_SELECTED_FRAME);
1992 }
1993 else
77cd03e2
SM
1994 notify_user_selected_context_changed
1995 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
4034d0ff 1996 }
c5394b80
JM
1997}
1998
4694da01
TT
1999/* Implementation of `thread name'. */
2000
2001static void
fc41a75b 2002thread_name_command (const char *arg, int from_tty)
4694da01
TT
2003{
2004 struct thread_info *info;
2005
9295a5a9 2006 if (inferior_ptid == null_ptid)
4694da01
TT
2007 error (_("No thread selected"));
2008
529480d0 2009 arg = skip_spaces (arg);
4694da01
TT
2010
2011 info = inferior_thread ();
25558938 2012 info->set_name (arg != nullptr ? make_unique_xstrdup (arg) : nullptr);
4694da01
TT
2013}
2014
60f98dde
MS
2015/* Find thread ids with a name, target pid, or extra info matching ARG. */
2016
2017static void
fc41a75b 2018thread_find_command (const char *arg, int from_tty)
60f98dde 2019{
73ede765 2020 const char *tmp;
60f98dde
MS
2021 unsigned long match = 0;
2022
2023 if (arg == NULL || *arg == '\0')
2024 error (_("Command requires an argument."));
2025
2026 tmp = re_comp (arg);
2027 if (tmp != 0)
2028 error (_("Invalid regexp (%s): %s"), tmp, arg);
2029
e8ef12b9
PA
2030 /* We're going to be switching threads. */
2031 scoped_restore_current_thread restore_thread;
2032
60f98dde 2033 update_thread_list ();
e8ef12b9 2034
08036331 2035 for (thread_info *tp : all_threads ())
60f98dde 2036 {
e8ef12b9
PA
2037 switch_to_inferior_no_thread (tp->inf);
2038
25558938 2039 if (tp->name () != nullptr && re_exec (tp->name ()))
60f98dde 2040 {
6cb06a8c
TT
2041 gdb_printf (_("Thread %s has name '%s'\n"),
2042 print_thread_id (tp), tp->name ());
60f98dde
MS
2043 match++;
2044 }
2045
2046 tmp = target_thread_name (tp);
2047 if (tmp != NULL && re_exec (tmp))
2048 {
6cb06a8c
TT
2049 gdb_printf (_("Thread %s has target name '%s'\n"),
2050 print_thread_id (tp), tmp);
60f98dde
MS
2051 match++;
2052 }
2053
a068643d
TT
2054 std::string name = target_pid_to_str (tp->ptid);
2055 if (!name.empty () && re_exec (name.c_str ()))
60f98dde 2056 {
6cb06a8c
TT
2057 gdb_printf (_("Thread %s has target id '%s'\n"),
2058 print_thread_id (tp), name.c_str ());
60f98dde
MS
2059 match++;
2060 }
2061
2062 tmp = target_extra_thread_info (tp);
2063 if (tmp != NULL && re_exec (tmp))
2064 {
6cb06a8c
TT
2065 gdb_printf (_("Thread %s has extra info '%s'\n"),
2066 print_thread_id (tp), tmp);
60f98dde
MS
2067 match++;
2068 }
2069 }
2070 if (!match)
6cb06a8c 2071 gdb_printf (_("No threads match '%s'\n"), arg);
60f98dde
MS
2072}
2073
93815fbf 2074/* Print notices when new threads are attached and detached. */
491144b5 2075bool print_thread_events = true;
93815fbf
VP
2076static void
2077show_print_thread_events (struct ui_file *file, int from_tty,
ae0eee42 2078 struct cmd_list_element *c, const char *value)
93815fbf 2079{
6cb06a8c
TT
2080 gdb_printf (file,
2081 _("Printing of thread events is %s.\n"),
2082 value);
93815fbf
VP
2083}
2084
65630365 2085/* See gdbthread.h. */
c906108c 2086
65630365
PA
2087void
2088thread_select (const char *tidstr, thread_info *tp)
2089{
f3f8ece4 2090 if (!switch_to_thread_if_alive (tp))
5d5658a1 2091 error (_("Thread ID %s has terminated."), tidstr);
c906108c 2092
db5a7484
NR
2093 annotate_thread_changed ();
2094
4034d0ff
AT
2095 /* Since the current thread may have changed, see if there is any
2096 exited thread we can now delete. */
a05575d3 2097 delete_exited_threads ();
4034d0ff
AT
2098}
2099
2100/* Print thread and frame switch command response. */
2101
2102void
2103print_selected_thread_frame (struct ui_out *uiout,
2104 user_selected_what selection)
2105{
2106 struct thread_info *tp = inferior_thread ();
4034d0ff
AT
2107
2108 if (selection & USER_SELECTED_THREAD)
5d5658a1 2109 {
112e8700 2110 if (uiout->is_mi_like_p ())
4034d0ff 2111 {
381befee
TT
2112 uiout->field_signed ("new-thread-id",
2113 inferior_thread ()->global_num);
4034d0ff
AT
2114 }
2115 else
2116 {
112e8700
SM
2117 uiout->text ("[Switching to thread ");
2118 uiout->field_string ("new-thread-id", print_thread_id (tp));
2119 uiout->text (" (");
4915bfdc 2120 uiout->text (target_pid_to_str (inferior_ptid));
112e8700 2121 uiout->text (")]");
4034d0ff 2122 }
5d5658a1 2123 }
c5394b80 2124
30596231 2125 if (tp->state == THREAD_RUNNING)
98871305 2126 {
4034d0ff 2127 if (selection & USER_SELECTED_THREAD)
112e8700 2128 uiout->text ("(running)\n");
98871305 2129 }
4034d0ff
AT
2130 else if (selection & USER_SELECTED_FRAME)
2131 {
2132 if (selection & USER_SELECTED_THREAD)
112e8700 2133 uiout->text ("\n");
4f8d22e3 2134
4034d0ff
AT
2135 if (has_stack_frames ())
2136 print_stack_frame_to_uiout (uiout, get_selected_frame (NULL),
2137 1, SRC_AND_LOC, 1);
2138 }
c5394b80
JM
2139}
2140
b57bacec 2141/* Update the 'threads_executing' global based on the threads we know
5b6d1e4f
PA
2142 about right now. This is used by infrun to tell whether we should
2143 pull events out of the current target. */
b57bacec
PA
2144
2145static void
2146update_threads_executing (void)
2147{
5b6d1e4f
PA
2148 process_stratum_target *targ = current_inferior ()->process_target ();
2149
2150 if (targ == NULL)
2151 return;
2152
2153 targ->threads_executing = false;
2154
2155 for (inferior *inf : all_non_exited_inferiors (targ))
b57bacec 2156 {
5b6d1e4f
PA
2157 if (!inf->has_execution ())
2158 continue;
2159
2160 /* If the process has no threads, then it must be we have a
2161 process-exit event pending. */
bf809310 2162 if (inf->thread_list.empty ())
5b6d1e4f
PA
2163 {
2164 targ->threads_executing = true;
2165 return;
2166 }
2167
2168 for (thread_info *tp : inf->non_exited_threads ())
b57bacec 2169 {
611841bb 2170 if (tp->executing ())
5b6d1e4f
PA
2171 {
2172 targ->threads_executing = true;
2173 return;
2174 }
b57bacec
PA
2175 }
2176 }
2177}
2178
dc146f7c
VP
2179void
2180update_thread_list (void)
2181{
e8032dde 2182 target_update_thread_list ();
b57bacec 2183 update_threads_executing ();
dc146f7c
VP
2184}
2185
25558938
SM
2186/* See gdbthread.h. */
2187
2188const char *
2189thread_name (thread_info *thread)
2190{
2191 /* Use the manually set name if there is one. */
2192 const char *name = thread->name ();
2193 if (name != nullptr)
2194 return name;
2195
2196 /* Otherwise, ask the target. Ensure we query the right target stack. */
2197 scoped_restore_current_thread restore_thread;
2198 if (thread->inf != current_inferior ())
2199 switch_to_inferior_no_thread (thread->inf);
2200
2201 return target_thread_name (thread);
2202}
2203
993248f4
AB
2204/* See gdbthread.h. */
2205
2206const char *
2207thread_state_string (enum thread_state state)
2208{
2209 switch (state)
2210 {
2211 case THREAD_STOPPED:
2212 return "STOPPED";
2213
2214 case THREAD_RUNNING:
2215 return "RUNNING";
2216
2217 case THREAD_EXITED:
2218 return "EXITED";
2219 }
2220
2221 gdb_assert_not_reached ("unknown thread state");
2222}
2223
663f6d42
PA
2224/* Return a new value for the selected thread's id. Return a value of
2225 0 if no thread is selected. If GLOBAL is true, return the thread's
2226 global number. Otherwise return the per-inferior number. */
2227
2228static struct value *
2229thread_num_make_value_helper (struct gdbarch *gdbarch, int global)
2230{
663f6d42
PA
2231 int int_val;
2232
00431a78 2233 if (inferior_ptid == null_ptid)
663f6d42 2234 int_val = 0;
663f6d42 2235 else
00431a78
PA
2236 {
2237 thread_info *tp = inferior_thread ();
2238 if (global)
2239 int_val = tp->global_num;
2240 else
2241 int_val = tp->per_inf_num;
2242 }
663f6d42
PA
2243
2244 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2245}
2246
5d5658a1
PA
2247/* Return a new value for the selected thread's per-inferior thread
2248 number. Return a value of 0 if no thread is selected, or no
2249 threads exist. */
6aed2dbc
SS
2250
2251static struct value *
ae0eee42
PA
2252thread_id_per_inf_num_make_value (struct gdbarch *gdbarch,
2253 struct internalvar *var,
663f6d42 2254 void *ignore)
6aed2dbc 2255{
663f6d42
PA
2256 return thread_num_make_value_helper (gdbarch, 0);
2257}
2258
2259/* Return a new value for the selected thread's global id. Return a
2260 value of 0 if no thread is selected, or no threads exist. */
6aed2dbc 2261
663f6d42
PA
2262static struct value *
2263global_thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
2264 void *ignore)
2265{
2266 return thread_num_make_value_helper (gdbarch, 1);
6aed2dbc
SS
2267}
2268
cbda14de
AB
2269/* Return a new value for the number of non-exited threads in the current
2270 inferior. If there are no threads in the current inferior return a
2271 value of 0. */
2272
2273static struct value *
2274inferior_thread_count_make_value (struct gdbarch *gdbarch,
2275 struct internalvar *var, void *ignore)
2276{
2277 int int_val = 0;
2278
75b2eb97
AB
2279 update_thread_list ();
2280
cbda14de
AB
2281 if (inferior_ptid != null_ptid)
2282 int_val = current_inferior ()->non_exited_threads ().size ();
2283
2284 return value_from_longest (builtin_type (gdbarch)->builtin_int, int_val);
2285}
2286
c906108c
SS
2287/* Commands with a prefix of `thread'. */
2288struct cmd_list_element *thread_cmd_list = NULL;
2289
22d2b532
SDJ
2290/* Implementation of `thread' variable. */
2291
2292static const struct internalvar_funcs thread_funcs =
2293{
663f6d42
PA
2294 thread_id_per_inf_num_make_value,
2295 NULL,
663f6d42
PA
2296};
2297
2298/* Implementation of `gthread' variable. */
2299
2300static const struct internalvar_funcs gthread_funcs =
2301{
2302 global_thread_id_make_value,
22d2b532 2303 NULL,
22d2b532
SDJ
2304};
2305
cbda14de
AB
2306/* Implementation of `_inferior_thread_count` convenience variable. */
2307
2308static const struct internalvar_funcs inferior_thread_count_funcs =
2309{
2310 inferior_thread_count_make_value,
2311 NULL,
2312};
2313
5fe70629 2314INIT_GDB_FILE (thread)
c906108c
SS
2315{
2316 static struct cmd_list_element *thread_apply_list = NULL;
5d707134 2317 cmd_list_element *c;
c906108c 2318
54d66006
PA
2319 const auto info_threads_opts = make_info_threads_options_def_group (nullptr);
2320
2321 /* Note: keep this "ID" in sync with what "info threads [TAB]"
2322 suggests. */
2323 static std::string info_threads_help
2324 = gdb::option::build_help (_("\
2325Display currently known threads.\n\
2326Usage: info threads [OPTION]... [ID]...\n\
3c6eb4d4
TBA
2327If ID is given, it is a space-separated list of IDs of threads to display.\n\
2328Otherwise, all threads are displayed.\n\
54d66006
PA
2329\n\
2330Options:\n\
3c6eb4d4 2331%OPTIONS%"),
54d66006
PA
2332 info_threads_opts);
2333
2334 c = add_info ("threads", info_threads_command, info_threads_help.c_str ());
2335 set_cmd_completer_handle_brkchars (c, info_threads_command_completer);
c906108c 2336
3947f654
SM
2337 cmd_list_element *thread_cmd
2338 = add_prefix_cmd ("thread", class_run, thread_command, _("\
1bedd215
AC
2339Use this command to switch between threads.\n\
2340The new thread ID must be currently known."),
3947f654
SM
2341 &thread_cmd_list, 1, &cmdlist);
2342
2343 add_com_alias ("t", thread_cmd, class_run, 1);
c906108c 2344
6665660a 2345#define THREAD_APPLY_OPTION_HELP "\
1fe75df7
PW
2346Prints per-inferior thread number and target system's thread id\n\
2347followed by COMMAND output.\n\
6665660a
PA
2348\n\
2349By default, an error raised during the execution of COMMAND\n\
2350aborts \"thread apply\".\n\
2351\n\
2352Options:\n\
2353%OPTIONS%"
2354
2355 const auto thread_apply_opts = make_thread_apply_options_def_group (nullptr);
2356
8abfcabc 2357 static std::string thread_apply_help = gdb::option::build_help (_("\
6665660a
PA
2358Apply a command to a list of threads.\n\
2359Usage: thread apply ID... [OPTION]... COMMAND\n\
1fe75df7 2360ID is a space-separated list of IDs of threads to apply COMMAND on.\n"
6665660a
PA
2361THREAD_APPLY_OPTION_HELP),
2362 thread_apply_opts);
2363
2364 c = add_prefix_cmd ("apply", class_run, thread_apply_command,
2365 thread_apply_help.c_str (),
2f822da5 2366 &thread_apply_list, 1,
6665660a
PA
2367 &thread_cmd_list);
2368 set_cmd_completer_handle_brkchars (c, thread_apply_command_completer);
c906108c 2369
6665660a
PA
2370 const auto thread_apply_all_opts
2371 = make_thread_apply_all_options_def_group (nullptr, nullptr);
2372
8abfcabc 2373 static std::string thread_apply_all_help = gdb::option::build_help (_("\
253828f1
JK
2374Apply a command to all threads.\n\
2375\n\
6665660a
PA
2376Usage: thread apply all [OPTION]... COMMAND\n"
2377THREAD_APPLY_OPTION_HELP),
2378 thread_apply_all_opts);
2379
2380 c = add_cmd ("all", class_run, thread_apply_all_command,
2381 thread_apply_all_help.c_str (),
2382 &thread_apply_list);
2383 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
c906108c 2384
6665660a 2385 c = add_com ("taas", class_run, taas_command, _("\
1fe75df7 2386Apply a command to all threads (ignoring errors and empty output).\n\
6665660a
PA
2387Usage: taas [OPTION]... COMMAND\n\
2388shortcut for 'thread apply all -s [OPTION]... COMMAND'\n\
2389See \"help thread apply all\" for available options."));
2390 set_cmd_completer_handle_brkchars (c, thread_apply_all_command_completer);
1fe75df7 2391
5d707134 2392 c = add_com ("tfaas", class_run, tfaas_command, _("\
1fe75df7 2393Apply a command to all frames of all threads (ignoring errors and empty output).\n\
5d707134
PA
2394Usage: tfaas [OPTION]... COMMAND\n\
2395shortcut for 'thread apply all -s -- frame apply all -s [OPTION]... COMMAND'\n\
2396See \"help frame apply all\" for available options."));
2397 set_cmd_completer_handle_brkchars (c, frame_apply_all_cmd_completer);
1fe75df7 2398
4694da01
TT
2399 add_cmd ("name", class_run, thread_name_command,
2400 _("Set the current thread's name.\n\
2401Usage: thread name [NAME]\n\
2402If NAME is not given, then any existing name is removed."), &thread_cmd_list);
2403
60f98dde
MS
2404 add_cmd ("find", class_run, thread_find_command, _("\
2405Find threads that match a regular expression.\n\
2406Usage: thread find REGEXP\n\
2407Will display thread ids whose name, target ID, or extra info matches REGEXP."),
2408 &thread_cmd_list);
2409
93815fbf 2410 add_setshow_boolean_cmd ("thread-events", no_class,
ae0eee42 2411 &print_thread_events, _("\
11c68c47
EZ
2412Set printing of thread events (such as thread start and exit)."), _("\
2413Show printing of thread events (such as thread start and exit)."), NULL,
ae0eee42
PA
2414 NULL,
2415 show_print_thread_events,
2416 &setprintlist, &showprintlist);
6aed2dbc 2417
5b0a3d62
AB
2418 add_setshow_boolean_cmd ("threads", class_maintenance, &debug_threads, _("\
2419Set thread debugging."), _("\
2420Show thread debugging."), _("\
2421When on messages about thread creation and deletion are printed."),
2422 nullptr,
2423 show_debug_threads,
2424 &setdebuglist, &showdebuglist);
2425
22d2b532 2426 create_internalvar_type_lazy ("_thread", &thread_funcs, NULL);
663f6d42 2427 create_internalvar_type_lazy ("_gthread", &gthread_funcs, NULL);
cbda14de
AB
2428 create_internalvar_type_lazy ("_inferior_thread_count",
2429 &inferior_thread_count_funcs, NULL);
c906108c 2430}