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