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