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