Non-stop inferior control.
[external/binutils.git] / gdb / thread.c
1 /* Multi-process/thread control for GDB, the GNU debugger.
2
3    Copyright (C) 1986, 1987, 1988, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4    2000, 2001, 2002, 2003, 2004, 2007, 2008 Free Software Foundation, Inc.
5
6    Contributed by Lynx Real-Time Systems, Inc.  Los Gatos, CA.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "environ.h"
28 #include "value.h"
29 #include "target.h"
30 #include "gdbthread.h"
31 #include "exceptions.h"
32 #include "command.h"
33 #include "gdbcmd.h"
34 #include "regcache.h"
35 #include "gdb.h"
36 #include "gdb_string.h"
37
38 #include <ctype.h>
39 #include <sys/types.h>
40 #include <signal.h>
41 #include "ui-out.h"
42 #include "observer.h"
43 #include "annotate.h"
44
45 #include "cli/cli-decode.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 static struct thread_info *thread_list = NULL;
56 static int highest_thread_num;
57
58 static struct thread_info *find_thread_id (int num);
59
60 static void thread_command (char *tidstr, int from_tty);
61 static void thread_apply_all_command (char *, int);
62 static int thread_alive (struct thread_info *);
63 static void info_threads_command (char *, int);
64 static void thread_apply_command (char *, int);
65 static void restore_current_thread (ptid_t);
66 static void prune_threads (void);
67
68 static int main_thread_running = 0;
69 static int main_thread_executing = 0;
70
71 void
72 delete_step_resume_breakpoint (void *arg)
73 {
74   struct breakpoint **breakpointp = (struct breakpoint **) arg;
75   struct thread_info *tp;
76
77   if (*breakpointp != NULL)
78     {
79       delete_breakpoint (*breakpointp);
80       for (tp = thread_list; tp; tp = tp->next)
81         if (tp->step_resume_breakpoint == *breakpointp)
82           tp->step_resume_breakpoint = NULL;
83
84       *breakpointp = NULL;
85     }
86 }
87
88 static void
89 free_thread (struct thread_info *tp)
90 {
91   /* NOTE: this will take care of any left-over step_resume breakpoints,
92      but not any user-specified thread-specific breakpoints.  We can not
93      delete the breakpoint straight-off, because the inferior might not
94      be stopped at the moment.  */
95   if (tp->step_resume_breakpoint)
96     tp->step_resume_breakpoint->disposition = disp_del_at_next_stop;
97
98   bpstat_clear (&tp->stop_bpstat);
99
100   /* FIXME: do I ever need to call the back-end to give it a
101      chance at this private data before deleting the thread?  */
102   if (tp->private)
103     xfree (tp->private);
104
105   xfree (tp);
106 }
107
108 void
109 init_thread_list (void)
110 {
111   struct thread_info *tp, *tpnext;
112
113   highest_thread_num = 0;
114   main_thread_running = 0;
115   main_thread_executing = 0;
116
117   if (!thread_list)
118     return;
119
120   for (tp = thread_list; tp; tp = tpnext)
121     {
122       tpnext = tp->next;
123       free_thread (tp);
124     }
125
126   thread_list = NULL;
127 }
128
129 struct thread_info *
130 add_thread_silent (ptid_t ptid)
131 {
132   struct thread_info *tp;
133
134   tp = (struct thread_info *) xmalloc (sizeof (*tp));
135   memset (tp, 0, sizeof (*tp));
136   tp->ptid = ptid;
137   tp->num = ++highest_thread_num;
138   tp->next = thread_list;
139   thread_list = tp;
140
141   observer_notify_new_thread (tp);
142
143   return tp;
144 }
145
146 struct thread_info *
147 add_thread_with_info (ptid_t ptid, struct private_thread_info *private)
148 {
149   struct thread_info *result = add_thread_silent (ptid);
150
151   result->private = private;
152
153   if (print_thread_events)
154     printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid));
155
156   annotate_new_thread ();
157   return result;
158 }
159
160 struct thread_info *
161 add_thread (ptid_t ptid)
162 {
163   return add_thread_with_info (ptid, NULL);
164 }
165
166 /* Delete thread PTID.  If SILENT, don't notify the observer of this
167    exit.  */
168 static void
169 delete_thread_1 (ptid_t ptid, int silent)
170 {
171   struct thread_info *tp, *tpprev;
172
173   tpprev = NULL;
174
175   for (tp = thread_list; tp; tpprev = tp, tp = tp->next)
176     if (ptid_equal (tp->ptid, ptid))
177       break;
178
179   if (!tp)
180     return;
181
182   if (tpprev)
183     tpprev->next = tp->next;
184   else
185     thread_list = tp->next;
186
187   if (!silent)
188     observer_notify_thread_exit (tp);
189
190   free_thread (tp);
191 }
192
193 void
194 delete_thread (ptid_t ptid)
195 {
196   delete_thread_1 (ptid, 0 /* not silent */);
197 }
198
199 void
200 delete_thread_silent (ptid_t ptid)
201 {
202   delete_thread_1 (ptid, 1 /* silent */);
203 }
204
205 static struct thread_info *
206 find_thread_id (int num)
207 {
208   struct thread_info *tp;
209
210   for (tp = thread_list; tp; tp = tp->next)
211     if (tp->num == num)
212       return tp;
213
214   return NULL;
215 }
216
217 /* Find a thread_info by matching PTID.  */
218 struct thread_info *
219 find_thread_pid (ptid_t ptid)
220 {
221   struct thread_info *tp;
222
223   for (tp = thread_list; tp; tp = tp->next)
224     if (ptid_equal (tp->ptid, ptid))
225       return tp;
226
227   return NULL;
228 }
229
230 /*
231  * Thread iterator function.
232  *
233  * Calls a callback function once for each thread, so long as
234  * the callback function returns false.  If the callback function
235  * returns true, the iteration will end and the current thread
236  * will be returned.  This can be useful for implementing a 
237  * search for a thread with arbitrary attributes, or for applying
238  * some operation to every thread.
239  *
240  * FIXME: some of the existing functionality, such as 
241  * "Thread apply all", might be rewritten using this functionality.
242  */
243
244 struct thread_info *
245 iterate_over_threads (int (*callback) (struct thread_info *, void *),
246                       void *data)
247 {
248   struct thread_info *tp;
249
250   for (tp = thread_list; tp; tp = tp->next)
251     if ((*callback) (tp, data))
252       return tp;
253
254   return NULL;
255 }
256
257 int
258 thread_count (void)
259 {
260   int result = 0;
261   struct thread_info *tp;
262
263   for (tp = thread_list; tp; tp = tp->next)
264     ++result;
265
266   return result;  
267 }
268
269 int
270 valid_thread_id (int num)
271 {
272   struct thread_info *tp;
273
274   for (tp = thread_list; tp; tp = tp->next)
275     if (tp->num == num)
276       return 1;
277
278   return 0;
279 }
280
281 int
282 pid_to_thread_id (ptid_t ptid)
283 {
284   struct thread_info *tp;
285
286   for (tp = thread_list; tp; tp = tp->next)
287     if (ptid_equal (tp->ptid, ptid))
288       return tp->num;
289
290   return 0;
291 }
292
293 ptid_t
294 thread_id_to_pid (int num)
295 {
296   struct thread_info *thread = find_thread_id (num);
297   if (thread)
298     return thread->ptid;
299   else
300     return pid_to_ptid (-1);
301 }
302
303 int
304 in_thread_list (ptid_t ptid)
305 {
306   struct thread_info *tp;
307
308   for (tp = thread_list; tp; tp = tp->next)
309     if (ptid_equal (tp->ptid, ptid))
310       return 1;
311
312   return 0;                     /* Never heard of 'im */
313 }
314
315 /* Print a list of thread ids currently known, and the total number of
316    threads. To be used from within catch_errors. */
317 static int
318 do_captured_list_thread_ids (struct ui_out *uiout, void *arg)
319 {
320   struct thread_info *tp;
321   int num = 0;
322   struct cleanup *cleanup_chain;
323
324   prune_threads ();
325   target_find_new_threads ();
326
327   cleanup_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "thread-ids");
328
329   for (tp = thread_list; tp; tp = tp->next)
330     {
331       num++;
332       ui_out_field_int (uiout, "thread-id", tp->num);
333     }
334
335   do_cleanups (cleanup_chain);
336   ui_out_field_int (uiout, "number-of-threads", num);
337   return GDB_RC_OK;
338 }
339
340 /* Official gdblib interface function to get a list of thread ids and
341    the total number. */
342 enum gdb_rc
343 gdb_list_thread_ids (struct ui_out *uiout, char **error_message)
344 {
345   if (catch_exceptions_with_msg (uiout, do_captured_list_thread_ids, NULL,
346                                  error_message, RETURN_MASK_ALL) < 0)
347     return GDB_RC_FAIL;
348   return GDB_RC_OK;
349 }
350
351 /* Load infrun state for the thread PID.  */
352
353 void
354 load_infrun_state (ptid_t ptid,
355                    CORE_ADDR *prev_pc,
356                    int *trap_expected,
357                    struct breakpoint **step_resume_breakpoint,
358                    CORE_ADDR *step_range_start,
359                    CORE_ADDR *step_range_end,
360                    struct frame_id *step_frame_id,
361                    int *stepping_over_breakpoint,
362                    int *stepping_through_solib_after_catch,
363                    bpstat *stepping_through_solib_catchpoints,
364                    int *current_line,
365                    struct symtab **current_symtab,
366                    struct continuation **continuations,
367                    struct continuation **intermediate_continuations,
368                    int *proceed_to_finish,
369                    enum step_over_calls_kind *step_over_calls,
370                    int *stop_step,
371                    int *step_multi,
372                    enum target_signal *stop_signal,
373                    bpstat *stop_bpstat)
374 {
375   struct thread_info *tp;
376
377   /* If we can't find the thread, then we're debugging a single threaded
378      process.  No need to do anything in that case.  */
379   tp = find_thread_id (pid_to_thread_id (ptid));
380   if (tp == NULL)
381     return;
382
383   *prev_pc = tp->prev_pc;
384   *trap_expected = tp->trap_expected;
385   *step_resume_breakpoint = tp->step_resume_breakpoint;
386   *step_range_start = tp->step_range_start;
387   *step_range_end = tp->step_range_end;
388   *step_frame_id = tp->step_frame_id;
389   *stepping_over_breakpoint = tp->stepping_over_breakpoint;
390   *stepping_through_solib_after_catch =
391     tp->stepping_through_solib_after_catch;
392   *stepping_through_solib_catchpoints =
393     tp->stepping_through_solib_catchpoints;
394   *current_line = tp->current_line;
395   *current_symtab = tp->current_symtab;
396
397   /* In all-stop mode, these are global state, while in non-stop mode,
398      they are per thread.  */
399   if (non_stop)
400     {
401       *continuations = tp->continuations;
402       tp->continuations = NULL;
403       *intermediate_continuations = tp->intermediate_continuations;
404       tp->intermediate_continuations = NULL;
405       *proceed_to_finish = tp->proceed_to_finish;
406       *step_over_calls = tp->step_over_calls;
407       *stop_step = tp->stop_step;
408       *step_multi = tp->step_multi;
409       *stop_signal = tp->stop_signal;
410
411       /* Swap instead of copy, so we only have to update one of
412          them.  */
413       *stop_bpstat = tp->stop_bpstat;
414       tp->stop_bpstat = 0;
415     }
416 }
417
418 /* Save infrun state for the thread PID.  */
419
420 void
421 save_infrun_state (ptid_t ptid,
422                    CORE_ADDR prev_pc,
423                    int trap_expected,
424                    struct breakpoint *step_resume_breakpoint,
425                    CORE_ADDR step_range_start,
426                    CORE_ADDR step_range_end,
427                    const struct frame_id *step_frame_id,
428                    int stepping_over_breakpoint,
429                    int stepping_through_solib_after_catch,
430                    bpstat stepping_through_solib_catchpoints,
431                    int current_line,
432                    struct symtab *current_symtab,
433                    struct continuation *continuations,
434                    struct continuation *intermediate_continuations,
435                    int proceed_to_finish,
436                    enum step_over_calls_kind step_over_calls,
437                    int stop_step,
438                    int step_multi,
439                    enum target_signal stop_signal,
440                    bpstat stop_bpstat)
441 {
442   struct thread_info *tp;
443
444   /* If we can't find the thread, then we're debugging a single-threaded
445      process.  Nothing to do in that case.  */
446   tp = find_thread_id (pid_to_thread_id (ptid));
447   if (tp == NULL)
448     return;
449
450   tp->prev_pc = prev_pc;
451   tp->trap_expected = trap_expected;
452   tp->step_resume_breakpoint = step_resume_breakpoint;
453   tp->step_range_start = step_range_start;
454   tp->step_range_end = step_range_end;
455   tp->step_frame_id = (*step_frame_id);
456   tp->stepping_over_breakpoint = stepping_over_breakpoint;
457   tp->stepping_through_solib_after_catch = stepping_through_solib_after_catch;
458   tp->stepping_through_solib_catchpoints = stepping_through_solib_catchpoints;
459   tp->current_line = current_line;
460   tp->current_symtab = current_symtab;
461
462   /* In all-stop mode, these are global state, while in non-stop mode,
463      they are per thread.  */
464   if (non_stop)
465     {
466       tp->continuations = continuations;
467       tp->intermediate_continuations = intermediate_continuations;
468       tp->proceed_to_finish = proceed_to_finish;
469       tp->step_over_calls = step_over_calls;
470       tp->stop_step = stop_step;
471       tp->step_multi = step_multi;
472       tp->stop_signal = stop_signal;
473       tp->stop_bpstat = stop_bpstat;
474     }
475 }
476
477 /* Return true if TP is an active thread. */
478 static int
479 thread_alive (struct thread_info *tp)
480 {
481   if (PIDGET (tp->ptid) == -1)
482     return 0;
483   if (!target_thread_alive (tp->ptid))
484     {
485       tp->ptid = pid_to_ptid (-1);      /* Mark it as dead */
486       return 0;
487     }
488   return 1;
489 }
490
491 static void
492 prune_threads (void)
493 {
494   struct thread_info *tp, *next;
495
496   for (tp = thread_list; tp; tp = next)
497     {
498       next = tp->next;
499       if (!thread_alive (tp))
500         delete_thread (tp->ptid);
501     }
502 }
503
504 void
505 set_running (ptid_t ptid, int running)
506 {
507   struct thread_info *tp;
508
509   if (!thread_list)
510     {
511       /* This is one of the targets that does not add main
512          thread to the thread list.  Just use a single
513          global flag to indicate that a thread is running.  
514
515          This problem is unique to ST programs.  For MT programs,
516          the main thread is always present in the thread list.  If it's
517          not, the first call to context_switch will mess up GDB internal
518          state.  */
519       if (running && !main_thread_running && !suppress_resume_observer)
520         observer_notify_target_resumed (ptid);
521       main_thread_running = running;
522       return;
523     }
524
525   /* We try not to notify the observer if no thread has actually changed 
526      the running state -- merely to reduce the number of messages to 
527      frontend.  Frontend is supposed to handle multiple *running just fine.  */
528   if (PIDGET (ptid) == -1)
529     {
530       int any_started = 0;
531       for (tp = thread_list; tp; tp = tp->next)
532         {
533           if (running && !tp->running_)
534             any_started = 1;
535           tp->running_ = running;
536         }
537       if (any_started && !suppress_resume_observer)
538         observer_notify_target_resumed (ptid);      
539     }
540   else
541     {
542       tp = find_thread_pid (ptid);
543       gdb_assert (tp);
544       if (running && !tp->running_ && !suppress_resume_observer)
545         observer_notify_target_resumed (ptid);
546       tp->running_ = running;
547     }  
548 }
549
550 int
551 is_running (ptid_t ptid)
552 {
553   struct thread_info *tp;
554
555   if (!target_has_execution)
556     return 0;
557
558   if (!thread_list)
559     return main_thread_running;
560
561   tp = find_thread_pid (ptid);
562   gdb_assert (tp);
563   return tp->running_;  
564 }
565
566 int
567 any_running (void)
568 {
569   struct thread_info *tp;
570
571   if (!target_has_execution)
572     return 0;
573
574   if (!thread_list)
575     return main_thread_running;
576
577   for (tp = thread_list; tp; tp = tp->next)
578     if (tp->running_)
579       return 1;
580
581   return 0;
582 }
583
584 int
585 is_executing (ptid_t ptid)
586 {
587   struct thread_info *tp;
588
589   if (!target_has_execution)
590     return 0;
591
592   if (!thread_list)
593     return main_thread_executing;
594
595   tp = find_thread_pid (ptid);
596   gdb_assert (tp);
597   return tp->executing_;
598 }
599
600 void
601 set_executing (ptid_t ptid, int executing)
602 {
603   struct thread_info *tp;
604
605   if (!thread_list)
606     {
607       /* This target does not add the main thread to the thread list.
608          Use a global flag to indicate that the thread is
609          executing.  */
610       main_thread_executing = executing;
611       return;
612     }
613
614   if (PIDGET (ptid) == -1)
615     {
616       for (tp = thread_list; tp; tp = tp->next)
617         tp->executing_ = executing;
618     }
619   else
620     {
621       tp = find_thread_pid (ptid);
622       gdb_assert (tp);
623       tp->executing_ = executing;
624     }
625 }
626
627 /* Prints the list of threads and their details on UIOUT.
628    This is a version of 'info_thread_command' suitable for
629    use from MI.  
630    If REQESTED_THREAD is not -1, it's the GDB id of the thread
631    that should be printed.  Otherwise, all threads are
632    printed.  */
633 void
634 print_thread_info (struct ui_out *uiout, int requested_thread)
635 {
636   struct thread_info *tp;
637   ptid_t current_ptid;
638   struct frame_info *cur_frame;
639   struct cleanup *old_chain;
640   struct frame_id saved_frame_id;
641   char *extra_info;
642   int current_thread = -1;
643
644   /* Backup current thread and selected frame.  */
645   if (!is_running (inferior_ptid))
646     saved_frame_id = get_frame_id (get_selected_frame (NULL));
647   else
648     saved_frame_id = null_frame_id;
649
650   old_chain = make_cleanup_restore_current_thread (inferior_ptid, saved_frame_id);
651   make_cleanup_ui_out_list_begin_end (uiout, "threads");
652
653   prune_threads ();
654   target_find_new_threads ();
655   current_ptid = inferior_ptid;
656   for (tp = thread_list; tp; tp = tp->next)
657     {
658       struct cleanup *chain2;
659
660       if (requested_thread != -1 && tp->num != requested_thread)
661         continue;
662
663       chain2 = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
664
665       if (ptid_equal (tp->ptid, current_ptid))
666         {
667           current_thread = tp->num;
668           ui_out_text (uiout, "* ");
669         }
670       else
671         ui_out_text (uiout, "  ");
672
673       ui_out_field_int (uiout, "id", tp->num);
674       ui_out_text (uiout, " ");
675       ui_out_field_string (uiout, "target-id", target_tid_to_str (tp->ptid));
676
677       extra_info = target_extra_thread_info (tp);
678       if (extra_info)
679         {
680           ui_out_text (uiout, " (");
681           ui_out_field_string (uiout, "details", extra_info);
682           ui_out_text (uiout, ")");
683         }
684       ui_out_text (uiout, "  ");
685       if (tp->running_)
686         ui_out_text (uiout, "(running)\n");
687       else
688         {
689           /* The switch below puts us at the top of the stack (leaf
690              frame).  */
691           switch_to_thread (tp->ptid);
692           print_stack_frame (get_selected_frame (NULL),
693                              /* For MI output, print frame level.  */
694                              ui_out_is_mi_like_p (uiout),
695                              LOCATION);
696         }
697
698       do_cleanups (chain2);
699     }
700
701   /* Restores the current thread and the frame selected before
702      the "info threads" command.  */
703   do_cleanups (old_chain);
704
705   if (requested_thread == -1)
706     {
707       gdb_assert (current_thread != -1 || !thread_list);
708       if (current_thread != -1 && ui_out_is_mi_like_p (uiout))
709         ui_out_field_int (uiout, "current-thread-id", current_thread);
710     }
711
712   if (is_running (inferior_ptid))
713     return;
714
715   /*  If case we were not able to find the original frame, print the
716       new selected frame.  */
717   if (frame_find_by_id (saved_frame_id) == NULL)
718     {
719       warning (_("Couldn't restore frame in current thread, at frame 0"));
720       /* For MI, we should probably have a notification about
721          current frame change.  But this error is not very likely, so
722          don't bother for now.  */
723       if (!ui_out_is_mi_like_p (uiout))
724         print_stack_frame (get_selected_frame (NULL), 0, LOCATION);
725     }
726 }
727
728
729 /* Print information about currently known threads 
730
731  * Note: this has the drawback that it _really_ switches
732  *       threads, which frees the frame cache.  A no-side
733  *       effects info-threads command would be nicer.
734  */
735
736 static void
737 info_threads_command (char *arg, int from_tty)
738 {
739   print_thread_info (uiout, -1);
740 }
741
742 /* Switch from one thread to another. */
743
744 void
745 switch_to_thread (ptid_t ptid)
746 {
747   if (ptid_equal (ptid, inferior_ptid))
748     return;
749
750   inferior_ptid = ptid;
751   reinit_frame_cache ();
752   registers_changed ();
753
754   if (!is_executing (ptid))
755     stop_pc = read_pc ();
756   else
757     stop_pc = ~(CORE_ADDR) 0;
758 }
759
760 static void
761 restore_current_thread (ptid_t ptid)
762 {
763   if (!ptid_equal (ptid, inferior_ptid))
764     {
765       switch_to_thread (ptid);
766     }
767 }
768
769 static void
770 restore_selected_frame (struct frame_id a_frame_id)
771 {
772   struct frame_info *selected_frame_info = NULL;
773
774   if (frame_id_eq (a_frame_id, null_frame_id))
775     return;        
776
777   if ((selected_frame_info = frame_find_by_id (a_frame_id)) != NULL)
778     {
779       select_frame (selected_frame_info);
780     }
781 }
782
783 struct current_thread_cleanup
784 {
785   ptid_t inferior_ptid;
786   struct frame_id selected_frame_id;
787 };
788
789 static void
790 do_restore_current_thread_cleanup (void *arg)
791 {
792   struct current_thread_cleanup *old = arg;
793   restore_current_thread (old->inferior_ptid);
794
795   /* A command like 'thread apply all $exec_command&' may change the
796      running state of the originally selected thread, so we have to
797      recheck it here.  */
798   if (!is_running (old->inferior_ptid))
799     restore_selected_frame (old->selected_frame_id);
800   xfree (old);
801 }
802
803 struct cleanup *
804 make_cleanup_restore_current_thread (ptid_t inferior_ptid, 
805                                      struct frame_id a_frame_id)
806 {
807   struct current_thread_cleanup *old
808     = xmalloc (sizeof (struct current_thread_cleanup));
809   old->inferior_ptid = inferior_ptid;
810   old->selected_frame_id = a_frame_id;
811   return make_cleanup (do_restore_current_thread_cleanup, old);
812 }
813
814 /* Apply a GDB command to a list of threads.  List syntax is a whitespace
815    seperated list of numbers, or ranges, or the keyword `all'.  Ranges consist
816    of two numbers seperated by a hyphen.  Examples:
817
818    thread apply 1 2 7 4 backtrace       Apply backtrace cmd to threads 1,2,7,4
819    thread apply 2-7 9 p foo(1)  Apply p foo(1) cmd to threads 2->7 & 9
820    thread apply all p x/i $pc   Apply x/i $pc cmd to all threads
821  */
822
823 static void
824 thread_apply_all_command (char *cmd, int from_tty)
825 {
826   struct thread_info *tp;
827   struct cleanup *old_chain = make_cleanup (null_cleanup, 0);
828   char *saved_cmd;
829   struct frame_id saved_frame_id;
830   ptid_t current_ptid;
831   int thread_has_changed = 0;
832
833   if (cmd == NULL || *cmd == '\000')
834     error (_("Please specify a command following the thread ID list"));
835   
836   current_ptid = inferior_ptid;
837
838   if (!is_running (inferior_ptid))
839     saved_frame_id = get_frame_id (get_selected_frame (NULL));
840   else
841     saved_frame_id = null_frame_id;
842   make_cleanup_restore_current_thread (inferior_ptid, saved_frame_id);
843
844   /* It is safe to update the thread list now, before
845      traversing it for "thread apply all".  MVS */
846   target_find_new_threads ();
847
848   /* Save a copy of the command in case it is clobbered by
849      execute_command */
850   saved_cmd = xstrdup (cmd);
851   make_cleanup (xfree, saved_cmd);
852   for (tp = thread_list; tp; tp = tp->next)
853     if (thread_alive (tp))
854       {
855         if (non_stop)
856           context_switch_to (tp->ptid);
857         else
858           switch_to_thread (tp->ptid);
859
860         printf_filtered (_("\nThread %d (%s):\n"),
861                          tp->num, target_tid_to_str (inferior_ptid));
862         execute_command (cmd, from_tty);
863         strcpy (cmd, saved_cmd);        /* Restore exact command used previously */
864       }
865
866   if (!ptid_equal (current_ptid, inferior_ptid))
867     thread_has_changed = 1;
868
869   do_cleanups (old_chain);
870   /* Print stack frame only if we changed thread.  */
871   if (thread_has_changed && !is_running (inferior_ptid))
872     print_stack_frame (get_current_frame (), 1, SRC_LINE);
873 }
874
875 static void
876 thread_apply_command (char *tidlist, int from_tty)
877 {
878   char *cmd;
879   char *p;
880   struct cleanup *old_chain;
881   struct cleanup *saved_cmd_cleanup_chain;
882   char *saved_cmd;
883   struct frame_id saved_frame_id;
884   ptid_t current_ptid;
885   int thread_has_changed = 0;
886
887   if (tidlist == NULL || *tidlist == '\000')
888     error (_("Please specify a thread ID list"));
889
890   for (cmd = tidlist; *cmd != '\000' && !isalpha (*cmd); cmd++);
891
892   if (*cmd == '\000')
893     error (_("Please specify a command following the thread ID list"));
894
895   current_ptid = inferior_ptid;
896
897   if (!is_running (inferior_ptid))
898     saved_frame_id = get_frame_id (get_selected_frame (NULL));
899   else
900     saved_frame_id = null_frame_id;
901   old_chain = make_cleanup_restore_current_thread (inferior_ptid, saved_frame_id);
902
903   /* Save a copy of the command in case it is clobbered by
904      execute_command */
905   saved_cmd = xstrdup (cmd);
906   saved_cmd_cleanup_chain = make_cleanup (xfree, (void *) saved_cmd);
907   while (tidlist < cmd)
908     {
909       struct thread_info *tp;
910       int start, end;
911
912       start = strtol (tidlist, &p, 10);
913       if (p == tidlist)
914         error (_("Error parsing %s"), tidlist);
915       tidlist = p;
916
917       while (*tidlist == ' ' || *tidlist == '\t')
918         tidlist++;
919
920       if (*tidlist == '-')      /* Got a range of IDs? */
921         {
922           tidlist++;            /* Skip the - */
923           end = strtol (tidlist, &p, 10);
924           if (p == tidlist)
925             error (_("Error parsing %s"), tidlist);
926           tidlist = p;
927
928           while (*tidlist == ' ' || *tidlist == '\t')
929             tidlist++;
930         }
931       else
932         end = start;
933
934       for (; start <= end; start++)
935         {
936           tp = find_thread_id (start);
937
938           if (!tp)
939             warning (_("Unknown thread %d."), start);
940           else if (!thread_alive (tp))
941             warning (_("Thread %d has terminated."), start);
942           else
943             {
944               if (non_stop)
945                 context_switch_to (tp->ptid);
946               else
947                 switch_to_thread (tp->ptid);
948               printf_filtered (_("\nThread %d (%s):\n"), tp->num,
949                                target_tid_to_str (inferior_ptid));
950               execute_command (cmd, from_tty);
951               strcpy (cmd, saved_cmd);  /* Restore exact command used previously */
952             }
953         }
954     }
955
956   if (!ptid_equal (current_ptid, inferior_ptid))
957     thread_has_changed = 1;
958
959   do_cleanups (saved_cmd_cleanup_chain);
960   do_cleanups (old_chain);
961   /* Print stack frame only if we changed thread.  */
962   if (thread_has_changed)
963     print_stack_frame (get_current_frame (), 1, SRC_LINE);
964 }
965
966 /* Switch to the specified thread.  Will dispatch off to thread_apply_command
967    if prefix of arg is `apply'.  */
968
969 static void
970 thread_command (char *tidstr, int from_tty)
971 {
972   if (!tidstr)
973     {
974       /* Don't generate an error, just say which thread is current. */
975       if (target_has_stack)
976         printf_filtered (_("[Current thread is %d (%s)]\n"),
977                          pid_to_thread_id (inferior_ptid),
978                          target_tid_to_str (inferior_ptid));
979       else
980         error (_("No stack."));
981       return;
982     }
983
984   annotate_thread_changed ();
985   gdb_thread_select (uiout, tidstr, NULL);
986 }
987
988 /* Print notices when new threads are attached and detached.  */
989 int print_thread_events = 1;
990 static void
991 show_print_thread_events (struct ui_file *file, int from_tty,
992                           struct cmd_list_element *c, const char *value)
993 {
994   fprintf_filtered (file, _("\
995 Printing of thread events is %s.\n"),
996                     value);
997 }
998
999 static int
1000 do_captured_thread_select (struct ui_out *uiout, void *tidstr)
1001 {
1002   int num;
1003   struct thread_info *tp;
1004
1005   num = value_as_long (parse_and_eval (tidstr));
1006
1007   tp = find_thread_id (num);
1008
1009   if (!tp)
1010     error (_("Thread ID %d not known."), num);
1011
1012   if (!thread_alive (tp))
1013     error (_("Thread ID %d has terminated."), num);
1014
1015   if (non_stop)
1016     context_switch_to (tp->ptid);
1017   else
1018     switch_to_thread (tp->ptid);
1019
1020   ui_out_text (uiout, "[Switching to thread ");
1021   ui_out_field_int (uiout, "new-thread-id", pid_to_thread_id (inferior_ptid));
1022   ui_out_text (uiout, " (");
1023   ui_out_text (uiout, target_tid_to_str (inferior_ptid));
1024   ui_out_text (uiout, ")]");
1025
1026   if (!tp->running_)
1027     print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
1028   else
1029     ui_out_text (uiout, "(running)\n");
1030
1031   return GDB_RC_OK;
1032 }
1033
1034 enum gdb_rc
1035 gdb_thread_select (struct ui_out *uiout, char *tidstr, char **error_message)
1036 {
1037   if (catch_exceptions_with_msg (uiout, do_captured_thread_select, tidstr,
1038                                  error_message, RETURN_MASK_ALL) < 0)
1039     return GDB_RC_FAIL;
1040   return GDB_RC_OK;
1041 }
1042
1043 /* Commands with a prefix of `thread'.  */
1044 struct cmd_list_element *thread_cmd_list = NULL;
1045
1046 void
1047 _initialize_thread (void)
1048 {
1049   static struct cmd_list_element *thread_apply_list = NULL;
1050   struct cmd_list_element *c;
1051
1052   c = add_info ("threads", info_threads_command,
1053                 _("IDs of currently known threads."));
1054   set_cmd_async_ok (c);
1055
1056   c = add_prefix_cmd ("thread", class_run, thread_command, _("\
1057 Use this command to switch between threads.\n\
1058 The new thread ID must be currently known."),
1059                       &thread_cmd_list, "thread ", 1, &cmdlist);
1060   set_cmd_async_ok (c);
1061
1062   add_prefix_cmd ("apply", class_run, thread_apply_command,
1063                   _("Apply a command to a list of threads."),
1064                   &thread_apply_list, "thread apply ", 1, &thread_cmd_list);
1065
1066   add_cmd ("all", class_run, thread_apply_all_command,
1067            _("Apply a command to all threads."), &thread_apply_list);
1068
1069   if (!xdb_commands)
1070     add_com_alias ("t", "thread", class_run, 1);
1071
1072   add_setshow_boolean_cmd ("thread-events", no_class,
1073          &print_thread_events, _("\
1074 Set printing of thread events (such as thread start and exit)."), _("\
1075 Show printing of thread events (such as thread start and exit)."), NULL,
1076          NULL,
1077          show_print_thread_events,
1078          &setprintlist, &showprintlist);
1079 }