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