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