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