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