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