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