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