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