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