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