* inferior.h (step_over_calls): Delete.
[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 #include "cli/cli-decode.h"
45
46 /* Definition of struct thread_info exported to gdbthread.h */
47
48 /* Prototypes for exported functions. */
49
50 void _initialize_thread (void);
51
52 /* Prototypes for local functions. */
53
54 static struct thread_info *thread_list = NULL;
55 static int highest_thread_num;
56
57 static void thread_command (char *tidstr, int from_tty);
58 static void thread_apply_all_command (char *, int);
59 static int thread_alive (struct thread_info *);
60 static void info_threads_command (char *, int);
61 static void thread_apply_command (char *, int);
62 static void restore_current_thread (ptid_t);
63 static void prune_threads (void);
64
65 /* Frontend view of the thread state.  Possible extensions: stepping,
66    finishing, until(ling),...  */
67 enum thread_state
68 {
69   THREAD_STOPPED,
70   THREAD_RUNNING,
71   THREAD_EXITED,
72 };
73
74 static enum thread_state main_thread_state = THREAD_STOPPED;
75 static int main_thread_executing = 0;
76
77 extern struct thread_info*
78 inferior_thread (void)
79 {
80   struct thread_info *tp = find_thread_pid (inferior_ptid);
81   gdb_assert (tp);
82   return tp;
83 }
84
85 void
86 delete_step_resume_breakpoint (struct thread_info *tp)
87 {
88   if (tp && tp->step_resume_breakpoint)
89     {
90       delete_breakpoint (tp->step_resume_breakpoint);
91       tp->step_resume_breakpoint = NULL;
92     }
93 }
94
95 static void
96 clear_thread_inferior_resources (struct thread_info *tp)
97 {
98   /* NOTE: this will take care of any left-over step_resume breakpoints,
99      but not any user-specified thread-specific breakpoints.  We can not
100      delete the breakpoint straight-off, because the inferior might not
101      be stopped at the moment.  */
102   if (tp->step_resume_breakpoint)
103     {
104       tp->step_resume_breakpoint->disposition = disp_del_at_next_stop;
105       tp->step_resume_breakpoint = NULL;
106     }
107
108   bpstat_clear (&tp->stop_bpstat);
109 }
110
111 static void
112 free_thread (struct thread_info *tp)
113 {
114   clear_thread_inferior_resources (tp);
115
116   /* FIXME: do I ever need to call the back-end to give it a
117      chance at this private data before deleting the thread?  */
118   if (tp->private)
119     xfree (tp->private);
120
121   xfree (tp);
122 }
123
124 void
125 init_thread_list (void)
126 {
127   struct thread_info *tp, *tpnext;
128
129   highest_thread_num = 0;
130   main_thread_state = THREAD_STOPPED;
131   main_thread_executing = 0;
132
133   if (!thread_list)
134     return;
135
136   for (tp = thread_list; tp; tp = tpnext)
137     {
138       tpnext = tp->next;
139       free_thread (tp);
140     }
141
142   thread_list = NULL;
143 }
144
145 struct thread_info *
146 add_thread_silent (ptid_t ptid)
147 {
148   struct thread_info *tp;
149
150   tp = find_thread_pid (ptid);
151   if (tp)
152     /* Found an old thread with the same id.  It has to be dead,
153        otherwise we wouldn't be adding a new thread with the same id.
154        The OS is reusing this id --- delete it, and recreate a new
155        one.  */
156     {
157       /* In addition to deleting the thread, if this is the current
158          thread, then we need to also get rid of the current infrun
159          context, and take care that delete_thread doesn't really
160          delete the thread if it is inferior_ptid.  Create a new
161          template thread in the list with an invalid ptid, context
162          switch to it, delete the original thread, reset the new
163          thread's ptid, and switch to it.  */
164
165       if (ptid_equal (inferior_ptid, ptid))
166         {
167           tp = xmalloc (sizeof (*tp));
168           memset (tp, 0, sizeof (*tp));
169           tp->ptid = minus_one_ptid;
170           tp->num = ++highest_thread_num;
171           tp->next = thread_list;
172           thread_list = tp;
173           context_switch_to (minus_one_ptid);
174
175           /* Now we can delete it.  */
176           delete_thread (ptid);
177
178           /* Since the context is already set to this new thread,
179              reset its ptid, and reswitch inferior_ptid to it.  */
180           tp->ptid = ptid;
181           switch_to_thread (ptid);
182
183           observer_notify_new_thread (tp);
184
185           /* All done.  */
186           return tp;
187         }
188       else
189         /* Just go ahead and delete it.  */
190         delete_thread (ptid);
191     }
192
193   tp = (struct thread_info *) xmalloc (sizeof (*tp));
194   memset (tp, 0, sizeof (*tp));
195   tp->ptid = ptid;
196   tp->num = ++highest_thread_num;
197   tp->next = thread_list;
198   thread_list = tp;
199
200   observer_notify_new_thread (tp);
201
202   return tp;
203 }
204
205 struct thread_info *
206 add_thread_with_info (ptid_t ptid, struct private_thread_info *private)
207 {
208   struct thread_info *result = add_thread_silent (ptid);
209
210   result->private = private;
211
212   if (print_thread_events)
213     printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid));
214
215   annotate_new_thread ();
216   return result;
217 }
218
219 struct thread_info *
220 add_thread (ptid_t ptid)
221 {
222   return add_thread_with_info (ptid, NULL);
223 }
224
225 /* Delete thread PTID.  If SILENT, don't notify the observer of this
226    exit.  */
227 static void
228 delete_thread_1 (ptid_t ptid, int silent)
229 {
230   struct thread_info *tp, *tpprev;
231
232   tpprev = NULL;
233
234   for (tp = thread_list; tp; tpprev = tp, tp = tp->next)
235     if (ptid_equal (tp->ptid, ptid))
236       break;
237
238   if (!tp)
239     return;
240
241   /* If this is the current thread, or there's code out there that
242      relies on it existing (refcount > 0) we can't delete yet.  Mark
243      it as exited, and notify it.  */
244   if (tp->refcount > 0
245       || ptid_equal (tp->ptid, inferior_ptid))
246     {
247       if (tp->state_ != THREAD_EXITED)
248         {
249           if (!silent)
250             observer_notify_thread_exit (tp);
251
252           /* Tag it as exited.  */
253           tp->state_ = THREAD_EXITED;
254
255           /* Clear breakpoints, etc. associated with this thread.  */
256           clear_thread_inferior_resources (tp);
257         }
258
259        /* Will be really deleted some other time.  */
260        return;
261      }
262
263   if (tpprev)
264     tpprev->next = tp->next;
265   else
266     thread_list = tp->next;
267
268   /* Notify thread exit, but only if we haven't already.  */
269   if (!silent && tp->state_ != THREAD_EXITED)
270     observer_notify_thread_exit (tp);
271
272   free_thread (tp);
273 }
274
275 /* Delete thread PTID and notify of thread exit.  If this is
276    inferior_ptid, don't actually delete it, but tag it as exited and
277    do the notification.  If PTID is the user selected thread, clear
278    it.  */
279 void
280 delete_thread (ptid_t ptid)
281 {
282   delete_thread_1 (ptid, 0 /* not silent */);
283 }
284
285 void
286 delete_thread_silent (ptid_t ptid)
287 {
288   delete_thread_1 (ptid, 1 /* silent */);
289 }
290
291 struct thread_info *
292 find_thread_id (int num)
293 {
294   struct thread_info *tp;
295
296   for (tp = thread_list; tp; tp = tp->next)
297     if (tp->num == num)
298       return tp;
299
300   return NULL;
301 }
302
303 /* Find a thread_info by matching PTID.  */
304 struct thread_info *
305 find_thread_pid (ptid_t ptid)
306 {
307   struct thread_info *tp;
308
309   for (tp = thread_list; tp; tp = tp->next)
310     if (ptid_equal (tp->ptid, ptid))
311       return tp;
312
313   return NULL;
314 }
315
316 /*
317  * Thread iterator function.
318  *
319  * Calls a callback function once for each thread, so long as
320  * the callback function returns false.  If the callback function
321  * returns true, the iteration will end and the current thread
322  * will be returned.  This can be useful for implementing a 
323  * search for a thread with arbitrary attributes, or for applying
324  * some operation to every thread.
325  *
326  * FIXME: some of the existing functionality, such as 
327  * "Thread apply all", might be rewritten using this functionality.
328  */
329
330 struct thread_info *
331 iterate_over_threads (int (*callback) (struct thread_info *, void *),
332                       void *data)
333 {
334   struct thread_info *tp, *next;
335
336   for (tp = thread_list; tp; tp = next)
337     {
338       next = tp->next;
339       if ((*callback) (tp, data))
340         return tp;
341     }
342
343   return NULL;
344 }
345
346 int
347 thread_count (void)
348 {
349   int result = 0;
350   struct thread_info *tp;
351
352   for (tp = thread_list; tp; tp = tp->next)
353     ++result;
354
355   return result;  
356 }
357
358 int
359 valid_thread_id (int num)
360 {
361   struct thread_info *tp;
362
363   for (tp = thread_list; tp; tp = tp->next)
364     if (tp->num == num)
365       return 1;
366
367   return 0;
368 }
369
370 int
371 pid_to_thread_id (ptid_t ptid)
372 {
373   struct thread_info *tp;
374
375   for (tp = thread_list; tp; tp = tp->next)
376     if (ptid_equal (tp->ptid, ptid))
377       return tp->num;
378
379   return 0;
380 }
381
382 ptid_t
383 thread_id_to_pid (int num)
384 {
385   struct thread_info *thread = find_thread_id (num);
386   if (thread)
387     return thread->ptid;
388   else
389     return pid_to_ptid (-1);
390 }
391
392 int
393 in_thread_list (ptid_t ptid)
394 {
395   struct thread_info *tp;
396
397   for (tp = thread_list; tp; tp = tp->next)
398     if (ptid_equal (tp->ptid, ptid))
399       return 1;
400
401   return 0;                     /* Never heard of 'im */
402 }
403
404 /* Print a list of thread ids currently known, and the total number of
405    threads. To be used from within catch_errors. */
406 static int
407 do_captured_list_thread_ids (struct ui_out *uiout, void *arg)
408 {
409   struct thread_info *tp;
410   int num = 0;
411   struct cleanup *cleanup_chain;
412
413   prune_threads ();
414   target_find_new_threads ();
415
416   cleanup_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "thread-ids");
417
418   for (tp = thread_list; tp; tp = tp->next)
419     {
420       if (tp->state_ == THREAD_EXITED)
421         continue;
422       num++;
423       ui_out_field_int (uiout, "thread-id", tp->num);
424     }
425
426   do_cleanups (cleanup_chain);
427   ui_out_field_int (uiout, "number-of-threads", num);
428   return GDB_RC_OK;
429 }
430
431 /* Official gdblib interface function to get a list of thread ids and
432    the total number. */
433 enum gdb_rc
434 gdb_list_thread_ids (struct ui_out *uiout, char **error_message)
435 {
436   if (catch_exceptions_with_msg (uiout, do_captured_list_thread_ids, NULL,
437                                  error_message, RETURN_MASK_ALL) < 0)
438     return GDB_RC_FAIL;
439   return GDB_RC_OK;
440 }
441
442 /* Load infrun state for the thread PID.  */
443
444 void
445 load_infrun_state (ptid_t ptid,
446                    struct continuation **continuations,
447                    struct continuation **intermediate_continuations,
448                    int *proceed_to_finish,
449                    int *stop_step,
450                    int *step_multi,
451                    enum target_signal *stop_signal,
452                    bpstat *stop_bpstat)
453 {
454   struct thread_info *tp;
455
456   /* If we can't find the thread, then we're debugging a single threaded
457      process.  No need to do anything in that case.  */
458   tp = find_thread_id (pid_to_thread_id (ptid));
459   if (tp == NULL)
460     return;
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       *continuations = tp->continuations;
467       tp->continuations = NULL;
468       *intermediate_continuations = tp->intermediate_continuations;
469       tp->intermediate_continuations = NULL;
470       *proceed_to_finish = tp->proceed_to_finish;
471       *stop_step = tp->stop_step;
472       *step_multi = tp->step_multi;
473       *stop_signal = tp->stop_signal;
474
475       /* Swap instead of copy, so we only have to update one of
476          them.  */
477       *stop_bpstat = tp->stop_bpstat;
478       tp->stop_bpstat = 0;
479     }
480 }
481
482 /* Save infrun state for the thread PID.  */
483
484 void
485 save_infrun_state (ptid_t ptid,
486                    struct continuation *continuations,
487                    struct continuation *intermediate_continuations,
488                    int proceed_to_finish,
489                    int stop_step,
490                    int step_multi,
491                    enum target_signal stop_signal,
492                    bpstat stop_bpstat)
493 {
494   struct thread_info *tp;
495
496   /* If we can't find the thread, then we're debugging a single-threaded
497      process.  Nothing to do in that case.  */
498   tp = find_thread_id (pid_to_thread_id (ptid));
499   if (tp == NULL)
500     return;
501
502   /* In all-stop mode, these are global state, while in non-stop mode,
503      they are per thread.  */
504   if (non_stop)
505     {
506       tp->continuations = continuations;
507       tp->intermediate_continuations = intermediate_continuations;
508       tp->proceed_to_finish = proceed_to_finish;
509       tp->stop_step = stop_step;
510       tp->step_multi = step_multi;
511       tp->stop_signal = stop_signal;
512       tp->stop_bpstat = stop_bpstat;
513     }
514 }
515
516 /* Return true if TP is an active thread. */
517 static int
518 thread_alive (struct thread_info *tp)
519 {
520   if (tp->state_ == THREAD_EXITED)
521     return 0;
522   if (!target_thread_alive (tp->ptid))
523     return 0;
524   return 1;
525 }
526
527 static void
528 prune_threads (void)
529 {
530   struct thread_info *tp, *next;
531
532   for (tp = thread_list; tp; tp = next)
533     {
534       next = tp->next;
535       if (!thread_alive (tp))
536         delete_thread (tp->ptid);
537     }
538 }
539
540 void
541 thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid)
542 {
543   struct thread_info * tp = find_thread_pid (old_ptid);
544   tp->ptid = new_ptid;
545
546   observer_notify_thread_ptid_changed (old_ptid, new_ptid);
547 }
548
549 void
550 set_running (ptid_t ptid, int running)
551 {
552   struct thread_info *tp;
553
554   if (!thread_list)
555     {
556       /* This is one of the targets that does not add main
557          thread to the thread list.  Just use a single
558          global flag to indicate that a thread is running.  
559
560          This problem is unique to ST programs.  For MT programs,
561          the main thread is always present in the thread list.  If it's
562          not, the first call to context_switch will mess up GDB internal
563          state.  */
564       if (running
565           && main_thread_state != THREAD_RUNNING
566           && !suppress_resume_observer)
567         observer_notify_target_resumed (ptid);
568       main_thread_state = running ? THREAD_RUNNING : THREAD_STOPPED;
569       return;
570     }
571
572   /* We try not to notify the observer if no thread has actually changed 
573      the running state -- merely to reduce the number of messages to 
574      frontend.  Frontend is supposed to handle multiple *running just fine.  */
575   if (PIDGET (ptid) == -1)
576     {
577       int any_started = 0;
578       for (tp = thread_list; tp; tp = tp->next)
579         {
580           if (tp->state_ == THREAD_EXITED)
581             continue;
582           if (running && tp->state_ == THREAD_STOPPED)
583             any_started = 1;
584           tp->state_ = running ? THREAD_RUNNING : THREAD_STOPPED;
585         }
586       if (any_started && !suppress_resume_observer)
587         observer_notify_target_resumed (ptid);      
588     }
589   else
590     {
591       int started = 0;
592       tp = find_thread_pid (ptid);
593       gdb_assert (tp);
594       gdb_assert (tp->state_ != THREAD_EXITED);
595       if (running && tp->state_ == THREAD_STOPPED)
596         started = 1;
597       tp->state_ = running ? THREAD_RUNNING : THREAD_STOPPED;
598       if (started && !suppress_resume_observer)
599         observer_notify_target_resumed (ptid);
600     }
601 }
602
603 static int
604 is_thread_state (ptid_t ptid, enum thread_state state)
605 {
606   struct thread_info *tp;
607
608   if (!target_has_execution)
609     return 0;
610
611   if (!thread_list)
612     return main_thread_state == state;
613
614   tp = find_thread_pid (ptid);
615   gdb_assert (tp);
616   return tp->state_ == state;
617 }
618
619 int
620 is_stopped (ptid_t ptid)
621 {
622   /* Without execution, this property is always true.  */
623   if (!target_has_execution)
624     return 1;
625
626   return is_thread_state (ptid, THREAD_STOPPED);
627 }
628
629 int
630 is_exited (ptid_t ptid)
631 {
632   /* Without execution, this property is always false.  */
633   if (!target_has_execution)
634     return 0;
635
636   return is_thread_state (ptid, THREAD_EXITED);
637 }
638
639 int
640 is_running (ptid_t ptid)
641 {
642    /* Without execution, this property is always false.  */
643   if (!target_has_execution)
644     return 0;
645
646   return is_thread_state (ptid, THREAD_RUNNING);
647 }
648
649 int
650 any_running (void)
651 {
652   struct thread_info *tp;
653
654   if (!target_has_execution)
655     return 0;
656
657   if (!thread_list)
658     return main_thread_state == THREAD_RUNNING;
659
660   for (tp = thread_list; tp; tp = tp->next)
661     if (tp->state_ == THREAD_RUNNING)
662       return 1;
663
664   return 0;
665 }
666
667 int
668 is_executing (ptid_t ptid)
669 {
670   struct thread_info *tp;
671
672   if (!target_has_execution)
673     return 0;
674
675   if (!thread_list)
676     return main_thread_executing;
677
678   tp = find_thread_pid (ptid);
679   gdb_assert (tp);
680   return tp->executing_;
681 }
682
683 void
684 set_executing (ptid_t ptid, int executing)
685 {
686   struct thread_info *tp;
687
688   if (!thread_list)
689     {
690       /* This target does not add the main thread to the thread list.
691          Use a global flag to indicate that the thread is
692          executing.  */
693       main_thread_executing = executing;
694       return;
695     }
696
697   if (PIDGET (ptid) == -1)
698     {
699       for (tp = thread_list; tp; tp = tp->next)
700         tp->executing_ = executing;
701     }
702   else
703     {
704       tp = find_thread_pid (ptid);
705       gdb_assert (tp);
706       tp->executing_ = executing;
707     }
708 }
709
710 /* Prints the list of threads and their details on UIOUT.
711    This is a version of 'info_thread_command' suitable for
712    use from MI.  
713    If REQUESTED_THREAD is not -1, it's the GDB id of the thread
714    that should be printed.  Otherwise, all threads are
715    printed.  */
716 void
717 print_thread_info (struct ui_out *uiout, int requested_thread)
718 {
719   struct thread_info *tp;
720   ptid_t current_ptid;
721   struct cleanup *old_chain;
722   char *extra_info;
723   int current_thread = -1;
724
725   prune_threads ();
726   target_find_new_threads ();
727   current_ptid = inferior_ptid;
728
729   /* We'll be switching threads temporarily.  */
730   old_chain = make_cleanup_restore_current_thread ();
731
732   make_cleanup_ui_out_list_begin_end (uiout, "threads");
733   for (tp = thread_list; tp; tp = tp->next)
734     {
735       struct cleanup *chain2;
736
737       if (requested_thread != -1 && tp->num != requested_thread)
738         continue;
739
740       if (ptid_equal (tp->ptid, current_ptid))
741         current_thread = tp->num;
742
743       if (tp->state_ == THREAD_EXITED)
744         continue;
745
746       chain2 = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
747
748       if (ptid_equal (tp->ptid, current_ptid))
749         ui_out_text (uiout, "* ");
750       else
751         ui_out_text (uiout, "  ");
752
753       ui_out_field_int (uiout, "id", tp->num);
754       ui_out_text (uiout, " ");
755       ui_out_field_string (uiout, "target-id", target_tid_to_str (tp->ptid));
756
757       if (tp->state_ != THREAD_EXITED)
758         {
759           extra_info = target_extra_thread_info (tp);
760           if (extra_info)
761             {
762               ui_out_text (uiout, " (");
763               ui_out_field_string (uiout, "details", extra_info);
764               ui_out_text (uiout, ")");
765             }
766           ui_out_text (uiout, "  ");
767         }
768
769       if (tp->state_ == THREAD_RUNNING)
770         ui_out_text (uiout, "(running)\n");
771       else
772         {
773           /* The switch below puts us at the top of the stack (leaf
774              frame).  */
775           switch_to_thread (tp->ptid);
776           print_stack_frame (get_selected_frame (NULL),
777                              /* For MI output, print frame level.  */
778                              ui_out_is_mi_like_p (uiout),
779                              LOCATION);
780         }
781
782       if (ui_out_is_mi_like_p (uiout))
783         {
784           char *state = "stopped";
785           if (tp->state_ == THREAD_EXITED)
786             state = "exited";
787           else if (tp->state_ == THREAD_RUNNING)
788             state = "running";
789           ui_out_field_string (uiout, "state", state);
790         }
791
792       do_cleanups (chain2);
793     }
794
795   /* Restores the current thread and the frame selected before
796      the "info threads" command.  */
797   do_cleanups (old_chain);
798
799   if (requested_thread == -1)
800     {
801       gdb_assert (current_thread != -1
802                   || !thread_list);
803       if (current_thread != -1 && ui_out_is_mi_like_p (uiout))
804         ui_out_field_int (uiout, "current-thread-id", current_thread);
805
806       if (current_thread != -1 && is_exited (current_ptid))
807         ui_out_message (uiout, 0, "\n\
808 The current thread <Thread ID %d> has terminated.  See `help thread'.\n",
809                         current_thread);
810     }
811 }
812
813
814 /* Print information about currently known threads 
815
816  * Note: this has the drawback that it _really_ switches
817  *       threads, which frees the frame cache.  A no-side
818  *       effects info-threads command would be nicer.
819  */
820
821 static void
822 info_threads_command (char *arg, int from_tty)
823 {
824   print_thread_info (uiout, -1);
825 }
826
827 /* Switch from one thread to another. */
828
829 void
830 switch_to_thread (ptid_t ptid)
831 {
832   if (ptid_equal (ptid, inferior_ptid))
833     return;
834
835   inferior_ptid = ptid;
836   reinit_frame_cache ();
837   registers_changed ();
838
839   /* We don't check for is_stopped, because we're called at times
840      while in the TARGET_RUNNING state, e.g., while handling an
841      internal event.  */
842   if (!is_exited (ptid) && !is_executing (ptid))
843     stop_pc = read_pc ();
844   else
845     stop_pc = ~(CORE_ADDR) 0;
846 }
847
848 static void
849 restore_current_thread (ptid_t ptid)
850 {
851   if (!ptid_equal (ptid, inferior_ptid))
852     {
853       if (non_stop)
854         context_switch_to (ptid);
855       else
856         switch_to_thread (ptid);
857     }
858 }
859
860 static void
861 restore_selected_frame (struct frame_id a_frame_id, int frame_level)
862 {
863   struct frame_info *frame = NULL;
864   int count;
865
866   gdb_assert (frame_level >= 0);
867
868   /* Restore by level first, check if the frame id is the same as
869      expected.  If that fails, try restoring by frame id.  If that
870      fails, nothing to do, just warn the user.  */
871
872   count = frame_level;
873   frame = find_relative_frame (get_current_frame (), &count);
874   if (count == 0
875       && frame != NULL
876       /* Either the frame ids match, of they're both invalid.  The
877          latter case is not failsafe, but since it's highly unlikely
878          the search by level finds the wrong frame, it's 99.9(9)% of
879          the time (for all practical purposes) safe.  */
880       && (frame_id_eq (get_frame_id (frame), a_frame_id)
881           /* Note: could be better to check every frame_id
882              member for equality here.  */
883           || (!frame_id_p (get_frame_id (frame))
884               && !frame_id_p (a_frame_id))))
885     {
886       /* Cool, all is fine.  */
887       select_frame (frame);
888       return;
889     }
890
891   frame = frame_find_by_id (a_frame_id);
892   if (frame != NULL)
893     {
894       /* Cool, refound it.  */
895       select_frame (frame);
896       return;
897     }
898
899   /* Nothing else to do, the frame layout really changed.  Select the
900      innermost stack frame.  */
901   select_frame (get_current_frame ());
902
903   /* Warn the user.  */
904   if (!ui_out_is_mi_like_p (uiout))
905     {
906       warning (_("\
907 Couldn't restore frame #%d in current thread, at reparsed frame #0\n"),
908                frame_level);
909       /* For MI, we should probably have a notification about
910          current frame change.  But this error is not very
911          likely, so don't bother for now.  */
912       print_stack_frame (get_selected_frame (NULL), 1, SRC_LINE);
913     }
914 }
915
916 struct current_thread_cleanup
917 {
918   ptid_t inferior_ptid;
919   struct frame_id selected_frame_id;
920   int selected_frame_level;
921   int was_stopped;
922 };
923
924 static void
925 do_restore_current_thread_cleanup (void *arg)
926 {
927   struct thread_info *tp;
928   struct current_thread_cleanup *old = arg;
929   restore_current_thread (old->inferior_ptid);
930
931   /* The running state of the originally selected thread may have
932      changed, so we have to recheck it here.  */
933   if (old->was_stopped
934       && is_stopped (inferior_ptid)
935       && target_has_registers
936       && target_has_stack
937       && target_has_memory)
938     restore_selected_frame (old->selected_frame_id,
939                             old->selected_frame_level);
940 }
941
942 static void
943 restore_current_thread_cleanup_dtor (void *arg)
944 {
945   struct current_thread_cleanup *old = arg;
946   struct thread_info *tp;
947   tp = find_thread_pid (old->inferior_ptid);
948   if (tp)
949     tp->refcount--;
950   xfree (old);
951 }
952
953 struct cleanup *
954 make_cleanup_restore_current_thread (void)
955 {
956   struct thread_info *tp;
957   struct frame_info *frame;
958   struct current_thread_cleanup *old;
959
960   old = xmalloc (sizeof (struct current_thread_cleanup));
961   old->inferior_ptid = inferior_ptid;
962   old->was_stopped = is_stopped (inferior_ptid);
963   if (old->was_stopped
964       && target_has_registers
965       && target_has_stack
966       && target_has_memory)
967     frame = get_selected_frame (NULL);
968   else
969     frame = NULL;
970
971   old->selected_frame_id = get_frame_id (frame);
972   old->selected_frame_level = frame_relative_level (frame);
973
974   tp = find_thread_pid (inferior_ptid);
975   if (tp)
976     tp->refcount++;
977
978   return make_cleanup_dtor (do_restore_current_thread_cleanup, old,
979                             restore_current_thread_cleanup_dtor);
980 }
981
982 /* Apply a GDB command to a list of threads.  List syntax is a whitespace
983    seperated list of numbers, or ranges, or the keyword `all'.  Ranges consist
984    of two numbers seperated by a hyphen.  Examples:
985
986    thread apply 1 2 7 4 backtrace       Apply backtrace cmd to threads 1,2,7,4
987    thread apply 2-7 9 p foo(1)  Apply p foo(1) cmd to threads 2->7 & 9
988    thread apply all p x/i $pc   Apply x/i $pc cmd to all threads
989  */
990
991 static void
992 thread_apply_all_command (char *cmd, int from_tty)
993 {
994   struct thread_info *tp;
995   struct cleanup *old_chain;
996   char *saved_cmd;
997
998   if (cmd == NULL || *cmd == '\000')
999     error (_("Please specify a command following the thread ID list"));
1000
1001   prune_threads ();
1002   target_find_new_threads ();
1003
1004   old_chain = make_cleanup_restore_current_thread ();
1005
1006   /* Save a copy of the command in case it is clobbered by
1007      execute_command */
1008   saved_cmd = xstrdup (cmd);
1009   make_cleanup (xfree, saved_cmd);
1010   for (tp = thread_list; tp; tp = tp->next)
1011     if (thread_alive (tp))
1012       {
1013         if (non_stop)
1014           context_switch_to (tp->ptid);
1015         else
1016           switch_to_thread (tp->ptid);
1017
1018         printf_filtered (_("\nThread %d (%s):\n"),
1019                          tp->num, target_tid_to_str (inferior_ptid));
1020         execute_command (cmd, from_tty);
1021         strcpy (cmd, saved_cmd);        /* Restore exact command used previously */
1022       }
1023
1024   do_cleanups (old_chain);
1025 }
1026
1027 static void
1028 thread_apply_command (char *tidlist, int from_tty)
1029 {
1030   char *cmd;
1031   char *p;
1032   struct cleanup *old_chain;
1033   char *saved_cmd;
1034
1035   if (tidlist == NULL || *tidlist == '\000')
1036     error (_("Please specify a thread ID list"));
1037
1038   for (cmd = tidlist; *cmd != '\000' && !isalpha (*cmd); cmd++);
1039
1040   if (*cmd == '\000')
1041     error (_("Please specify a command following the thread ID list"));
1042
1043   /* Save a copy of the command in case it is clobbered by
1044      execute_command */
1045   saved_cmd = xstrdup (cmd);
1046   old_chain = make_cleanup (xfree, saved_cmd);
1047   while (tidlist < cmd)
1048     {
1049       struct thread_info *tp;
1050       int start, end;
1051
1052       start = strtol (tidlist, &p, 10);
1053       if (p == tidlist)
1054         error (_("Error parsing %s"), tidlist);
1055       tidlist = p;
1056
1057       while (*tidlist == ' ' || *tidlist == '\t')
1058         tidlist++;
1059
1060       if (*tidlist == '-')      /* Got a range of IDs? */
1061         {
1062           tidlist++;            /* Skip the - */
1063           end = strtol (tidlist, &p, 10);
1064           if (p == tidlist)
1065             error (_("Error parsing %s"), tidlist);
1066           tidlist = p;
1067
1068           while (*tidlist == ' ' || *tidlist == '\t')
1069             tidlist++;
1070         }
1071       else
1072         end = start;
1073
1074       make_cleanup_restore_current_thread ();
1075
1076       for (; start <= end; start++)
1077         {
1078           tp = find_thread_id (start);
1079
1080           if (!tp)
1081             warning (_("Unknown thread %d."), start);
1082           else if (!thread_alive (tp))
1083             warning (_("Thread %d has terminated."), start);
1084           else
1085             {
1086               if (non_stop)
1087                 context_switch_to (tp->ptid);
1088               else
1089                 switch_to_thread (tp->ptid);
1090
1091               printf_filtered (_("\nThread %d (%s):\n"), tp->num,
1092                                target_tid_to_str (inferior_ptid));
1093               execute_command (cmd, from_tty);
1094
1095               /* Restore exact command used previously.  */
1096               strcpy (cmd, saved_cmd);
1097             }
1098         }
1099     }
1100
1101   do_cleanups (old_chain);
1102 }
1103
1104 /* Switch to the specified thread.  Will dispatch off to thread_apply_command
1105    if prefix of arg is `apply'.  */
1106
1107 static void
1108 thread_command (char *tidstr, int from_tty)
1109 {
1110   if (!tidstr)
1111     {
1112       if (target_has_stack)
1113         {
1114           if (is_exited (inferior_ptid))
1115             printf_filtered (_("[Current thread is %d (%s) (exited)]\n"),
1116                              pid_to_thread_id (inferior_ptid),
1117                              target_tid_to_str (inferior_ptid));
1118           else
1119             printf_filtered (_("[Current thread is %d (%s)]\n"),
1120                              pid_to_thread_id (inferior_ptid),
1121                              target_tid_to_str (inferior_ptid));
1122         }
1123       else
1124         error (_("No stack."));
1125       return;
1126     }
1127
1128   annotate_thread_changed ();
1129   gdb_thread_select (uiout, tidstr, NULL);
1130 }
1131
1132 /* Print notices when new threads are attached and detached.  */
1133 int print_thread_events = 1;
1134 static void
1135 show_print_thread_events (struct ui_file *file, int from_tty,
1136                           struct cmd_list_element *c, const char *value)
1137 {
1138   fprintf_filtered (file, _("\
1139 Printing of thread events is %s.\n"),
1140                     value);
1141 }
1142
1143 static int
1144 do_captured_thread_select (struct ui_out *uiout, void *tidstr)
1145 {
1146   int num;
1147   struct thread_info *tp;
1148
1149   num = value_as_long (parse_and_eval (tidstr));
1150
1151   tp = find_thread_id (num);
1152
1153   if (!tp)
1154     error (_("Thread ID %d not known."), num);
1155
1156   if (!thread_alive (tp))
1157     error (_("Thread ID %d has terminated."), num);
1158
1159   if (non_stop)
1160     context_switch_to (tp->ptid);
1161   else
1162     switch_to_thread (tp->ptid);
1163
1164   ui_out_text (uiout, "[Switching to thread ");
1165   ui_out_field_int (uiout, "new-thread-id", pid_to_thread_id (inferior_ptid));
1166   ui_out_text (uiout, " (");
1167   ui_out_text (uiout, target_tid_to_str (inferior_ptid));
1168   ui_out_text (uiout, ")]");
1169
1170   /* Note that we can't reach this with an exited thread, due to the
1171      thread_alive check above.  */
1172   if (tp->state_ == THREAD_RUNNING)
1173     ui_out_text (uiout, "(running)\n");
1174   else
1175     print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
1176
1177   /* Since the current thread may have changed, see if there is any
1178      exited thread we can now delete.  */
1179   prune_threads ();
1180
1181   return GDB_RC_OK;
1182 }
1183
1184 enum gdb_rc
1185 gdb_thread_select (struct ui_out *uiout, char *tidstr, char **error_message)
1186 {
1187   if (catch_exceptions_with_msg (uiout, do_captured_thread_select, tidstr,
1188                                  error_message, RETURN_MASK_ALL) < 0)
1189     return GDB_RC_FAIL;
1190   return GDB_RC_OK;
1191 }
1192
1193 /* Commands with a prefix of `thread'.  */
1194 struct cmd_list_element *thread_cmd_list = NULL;
1195
1196 void
1197 _initialize_thread (void)
1198 {
1199   static struct cmd_list_element *thread_apply_list = NULL;
1200   struct cmd_list_element *c;
1201
1202   c = add_info ("threads", info_threads_command,
1203                 _("IDs of currently known threads."));
1204   set_cmd_no_selected_thread_ok (c);
1205
1206   c = add_prefix_cmd ("thread", class_run, thread_command, _("\
1207 Use this command to switch between threads.\n\
1208 The new thread ID must be currently known."),
1209                       &thread_cmd_list, "thread ", 1, &cmdlist);
1210   set_cmd_no_selected_thread_ok (c);
1211
1212   c = add_prefix_cmd ("apply", class_run, thread_apply_command,
1213                       _("Apply a command to a list of threads."),
1214                       &thread_apply_list, "thread apply ", 1, &thread_cmd_list);
1215   set_cmd_no_selected_thread_ok (c);
1216
1217   c = add_cmd ("all", class_run, thread_apply_all_command,
1218                _("Apply a command to all threads."), &thread_apply_list);
1219   set_cmd_no_selected_thread_ok (c);
1220
1221   if (!xdb_commands)
1222     add_com_alias ("t", "thread", class_run, 1);
1223
1224   add_setshow_boolean_cmd ("thread-events", no_class,
1225          &print_thread_events, _("\
1226 Set printing of thread events (such as thread start and exit)."), _("\
1227 Show printing of thread events (such as thread start and exit)."), NULL,
1228          NULL,
1229          show_print_thread_events,
1230          &setprintlist, &showprintlist);
1231 }