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