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