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