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