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