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