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