gas/testsuite/
[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, 2009
5    Free Software Foundation, Inc.
6
7    Contributed by Lynx Real-Time Systems, Inc.  Los Gatos, CA.
8
9    This file is part of GDB.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
23
24 #include "defs.h"
25 #include "symtab.h"
26 #include "frame.h"
27 #include "inferior.h"
28 #include "environ.h"
29 #include "value.h"
30 #include "target.h"
31 #include "gdbthread.h"
32 #include "exceptions.h"
33 #include "command.h"
34 #include "gdbcmd.h"
35 #include "regcache.h"
36 #include "gdb.h"
37 #include "gdb_string.h"
38
39 #include <ctype.h>
40 #include <sys/types.h>
41 #include <signal.h>
42 #include "ui-out.h"
43 #include "observer.h"
44 #include "annotate.h"
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 void thread_command (char *tidstr, int from_tty);
59 static void thread_apply_all_command (char *, int);
60 static int thread_alive (struct thread_info *);
61 static void info_threads_command (char *, int);
62 static void thread_apply_command (char *, int);
63 static void restore_current_thread (ptid_t);
64 static void prune_threads (void);
65
66 /* Frontend view of the thread state.  Possible extensions: stepping,
67    finishing, until(ling),...  */
68 enum thread_state
69 {
70   THREAD_STOPPED,
71   THREAD_RUNNING,
72   THREAD_EXITED,
73 };
74
75 struct thread_info*
76 inferior_thread (void)
77 {
78   struct thread_info *tp = find_thread_pid (inferior_ptid);
79   gdb_assert (tp);
80   return tp;
81 }
82
83 void
84 delete_step_resume_breakpoint (struct thread_info *tp)
85 {
86   if (tp && tp->step_resume_breakpoint)
87     {
88       delete_breakpoint (tp->step_resume_breakpoint);
89       tp->step_resume_breakpoint = NULL;
90     }
91 }
92
93 static void
94 clear_thread_inferior_resources (struct thread_info *tp)
95 {
96   /* NOTE: this will take care of any left-over step_resume breakpoints,
97      but not any user-specified thread-specific breakpoints.  We can not
98      delete the breakpoint straight-off, because the inferior might not
99      be stopped at the moment.  */
100   if (tp->step_resume_breakpoint)
101     {
102       tp->step_resume_breakpoint->disposition = disp_del_at_next_stop;
103       tp->step_resume_breakpoint = NULL;
104     }
105
106   bpstat_clear (&tp->stop_bpstat);
107
108   discard_all_intermediate_continuations_thread (tp);
109   discard_all_continuations_thread (tp);
110 }
111
112 static void
113 free_thread (struct thread_info *tp)
114 {
115   clear_thread_inferior_resources (tp);
116
117   /* FIXME: do I ever need to call the back-end to give it a
118      chance at this private data before deleting the thread?  */
119   if (tp->private)
120     xfree (tp->private);
121
122   xfree (tp);
123 }
124
125 void
126 init_thread_list (void)
127 {
128   struct thread_info *tp, *tpnext;
129
130   highest_thread_num = 0;
131
132   if (!thread_list)
133     return;
134
135   for (tp = thread_list; tp; tp = tpnext)
136     {
137       tpnext = tp->next;
138       free_thread (tp);
139     }
140
141   thread_list = NULL;
142 }
143
144 struct thread_info *
145 add_thread_silent (ptid_t ptid)
146 {
147   struct thread_info *tp;
148
149   tp = find_thread_pid (ptid);
150   if (tp)
151     /* Found an old thread with the same id.  It has to be dead,
152        otherwise we wouldn't be adding a new thread with the same id.
153        The OS is reusing this id --- delete it, and recreate a new
154        one.  */
155     {
156       /* In addition to deleting the thread, if this is the current
157          thread, then we need to take care that delete_thread doesn't
158          really delete the thread if it is inferior_ptid.  Create a
159          new template thread in the list with an invalid ptid, switch
160          to it, delete the original thread, reset the new thread's
161          ptid, and switch to it.  */
162
163       if (ptid_equal (inferior_ptid, ptid))
164         {
165           tp = xmalloc (sizeof (*tp));
166           memset (tp, 0, sizeof (*tp));
167           tp->ptid = minus_one_ptid;
168           tp->num = ++highest_thread_num;
169           tp->next = thread_list;
170           thread_list = tp;
171
172           /* Make switch_to_thread not read from the thread.  */
173           tp->state_ = THREAD_EXITED;
174           switch_to_thread (minus_one_ptid);
175
176           /* Now we can delete it.  */
177           delete_thread (ptid);
178
179           /* Now reset its ptid, and reswitch inferior_ptid to it.  */
180           tp->ptid = ptid;
181           tp->state_ = THREAD_STOPPED;
182           switch_to_thread (ptid);
183
184           observer_notify_new_thread (tp);
185
186           /* All done.  */
187           return tp;
188         }
189       else
190         /* Just go ahead and delete it.  */
191         delete_thread (ptid);
192     }
193
194   tp = (struct thread_info *) xmalloc (sizeof (*tp));
195   memset (tp, 0, sizeof (*tp));
196   tp->ptid = ptid;
197   tp->num = ++highest_thread_num;
198   tp->next = thread_list;
199   thread_list = tp;
200
201   observer_notify_new_thread (tp);
202
203   return tp;
204 }
205
206 struct thread_info *
207 add_thread_with_info (ptid_t ptid, struct private_thread_info *private)
208 {
209   struct thread_info *result = add_thread_silent (ptid);
210
211   result->private = private;
212
213   if (print_thread_events)
214     printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid));
215
216   annotate_new_thread ();
217   return result;
218 }
219
220 struct thread_info *
221 add_thread (ptid_t ptid)
222 {
223   return add_thread_with_info (ptid, NULL);
224 }
225
226 /* Delete thread PTID.  If SILENT, don't notify the observer of this
227    exit.  */
228 static void
229 delete_thread_1 (ptid_t ptid, int silent)
230 {
231   struct thread_info *tp, *tpprev;
232
233   tpprev = NULL;
234
235   for (tp = thread_list; tp; tpprev = tp, tp = tp->next)
236     if (ptid_equal (tp->ptid, ptid))
237       break;
238
239   if (!tp)
240     return;
241
242   /* If this is the current thread, or there's code out there that
243      relies on it existing (refcount > 0) we can't delete yet.  Mark
244      it as exited, and notify it.  */
245   if (tp->refcount > 0
246       || ptid_equal (tp->ptid, inferior_ptid))
247     {
248       if (tp->state_ != THREAD_EXITED)
249         {
250           observer_notify_thread_exit (tp, silent);
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 (tp->state_ != THREAD_EXITED)
270     observer_notify_thread_exit (tp, silent);
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 /* Finds the first thread of the inferior given by PID.  If PID is -1,
405    return the first thread in the list.  */
406
407 struct thread_info *
408 first_thread_of_process (int pid)
409 {
410   struct thread_info *tp, *ret = NULL;
411
412   for (tp = thread_list; tp; tp = tp->next)
413     if (pid == -1 || ptid_get_pid (tp->ptid) == pid)
414       if (ret == NULL || tp->num < ret->num)
415         ret = tp;
416
417   return ret;
418 }
419
420 /* Print a list of thread ids currently known, and the total number of
421    threads. To be used from within catch_errors. */
422 static int
423 do_captured_list_thread_ids (struct ui_out *uiout, void *arg)
424 {
425   struct thread_info *tp;
426   int num = 0;
427   struct cleanup *cleanup_chain;
428   int current_thread = -1;
429
430   prune_threads ();
431   target_find_new_threads ();
432
433   cleanup_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "thread-ids");
434
435   for (tp = thread_list; tp; tp = tp->next)
436     {
437       if (tp->state_ == THREAD_EXITED)
438         continue;
439
440       if (ptid_equal (tp->ptid, inferior_ptid))
441         current_thread = tp->num;
442
443       num++;
444       ui_out_field_int (uiout, "thread-id", tp->num);
445     }
446
447   do_cleanups (cleanup_chain);
448
449   if (current_thread != -1)
450     ui_out_field_int (uiout, "current-thread-id", current_thread);
451   ui_out_field_int (uiout, "number-of-threads", num);
452   return GDB_RC_OK;
453 }
454
455 /* Official gdblib interface function to get a list of thread ids and
456    the total number. */
457 enum gdb_rc
458 gdb_list_thread_ids (struct ui_out *uiout, char **error_message)
459 {
460   if (catch_exceptions_with_msg (uiout, do_captured_list_thread_ids, NULL,
461                                  error_message, RETURN_MASK_ALL) < 0)
462     return GDB_RC_FAIL;
463   return GDB_RC_OK;
464 }
465
466 /* Return true if TP is an active thread. */
467 static int
468 thread_alive (struct thread_info *tp)
469 {
470   if (tp->state_ == THREAD_EXITED)
471     return 0;
472   if (!target_thread_alive (tp->ptid))
473     return 0;
474   return 1;
475 }
476
477 static void
478 prune_threads (void)
479 {
480   struct thread_info *tp, *next;
481
482   for (tp = thread_list; tp; tp = next)
483     {
484       next = tp->next;
485       if (!thread_alive (tp))
486         delete_thread (tp->ptid);
487     }
488 }
489
490 void
491 thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid)
492 {
493   struct inferior *inf;
494   struct thread_info *tp;
495
496   /* It can happen that what we knew as the target inferior id
497      changes.  E.g, target remote may only discover the remote process
498      pid after adding the inferior to GDB's list.  */
499   inf = find_inferior_pid (ptid_get_pid (old_ptid));
500   inf->pid = ptid_get_pid (new_ptid);
501
502   tp = find_thread_pid (old_ptid);
503   tp->ptid = new_ptid;
504
505   observer_notify_thread_ptid_changed (old_ptid, new_ptid);
506 }
507
508 void
509 set_running (ptid_t ptid, int running)
510 {
511   struct thread_info *tp;
512
513   /* We try not to notify the observer if no thread has actually changed 
514      the running state -- merely to reduce the number of messages to 
515      frontend.  Frontend is supposed to handle multiple *running just fine.  */
516   if (PIDGET (ptid) == -1)
517     {
518       int any_started = 0;
519       for (tp = thread_list; tp; tp = tp->next)
520         {
521           if (tp->state_ == THREAD_EXITED)
522             continue;
523           if (running && tp->state_ == THREAD_STOPPED)
524             any_started = 1;
525           tp->state_ = running ? THREAD_RUNNING : THREAD_STOPPED;
526         }
527       if (any_started)
528         observer_notify_target_resumed (ptid);
529     }
530   else
531     {
532       int started = 0;
533       tp = find_thread_pid (ptid);
534       gdb_assert (tp);
535       gdb_assert (tp->state_ != THREAD_EXITED);
536       if (running && tp->state_ == THREAD_STOPPED)
537         started = 1;
538       tp->state_ = running ? THREAD_RUNNING : THREAD_STOPPED;
539       if (started)
540         observer_notify_target_resumed (ptid);
541     }
542 }
543
544 static int
545 is_thread_state (ptid_t ptid, enum thread_state state)
546 {
547   struct thread_info *tp;
548
549   if (!target_has_execution)
550     return 0;
551
552   tp = find_thread_pid (ptid);
553   gdb_assert (tp);
554   return tp->state_ == state;
555 }
556
557 int
558 is_stopped (ptid_t ptid)
559 {
560   /* Without execution, this property is always true.  */
561   if (!target_has_execution)
562     return 1;
563
564   return is_thread_state (ptid, THREAD_STOPPED);
565 }
566
567 int
568 is_exited (ptid_t ptid)
569 {
570   /* Without execution, this property is always false.  */
571   if (!target_has_execution)
572     return 0;
573
574   return is_thread_state (ptid, THREAD_EXITED);
575 }
576
577 int
578 is_running (ptid_t ptid)
579 {
580    /* Without execution, this property is always false.  */
581   if (!target_has_execution)
582     return 0;
583
584   return is_thread_state (ptid, THREAD_RUNNING);
585 }
586
587 int
588 any_running (void)
589 {
590   struct thread_info *tp;
591
592   if (!target_has_execution)
593     return 0;
594
595   for (tp = thread_list; tp; tp = tp->next)
596     if (tp->state_ == THREAD_RUNNING)
597       return 1;
598
599   return 0;
600 }
601
602 int
603 is_executing (ptid_t ptid)
604 {
605   struct thread_info *tp;
606
607   if (!target_has_execution)
608     return 0;
609
610   tp = find_thread_pid (ptid);
611   gdb_assert (tp);
612   return tp->executing_;
613 }
614
615 void
616 set_executing (ptid_t ptid, int executing)
617 {
618   struct thread_info *tp;
619
620   if (PIDGET (ptid) == -1)
621     {
622       for (tp = thread_list; tp; tp = tp->next)
623         tp->executing_ = executing;
624     }
625   else
626     {
627       tp = find_thread_pid (ptid);
628       gdb_assert (tp);
629       tp->executing_ = executing;
630     }
631 }
632
633 void
634 set_stop_requested (ptid_t ptid, int stop)
635 {
636   struct thread_info *tp;
637   int all = ptid_equal (ptid, minus_one_ptid);
638
639   if (all || ptid_is_pid (ptid))
640     {
641       for (tp = thread_list; tp; tp = tp->next)
642         if (all || ptid_get_pid (tp->ptid) == ptid_get_pid (ptid))
643           tp->stop_requested = stop;
644     }
645   else
646     {
647       tp = find_thread_pid (ptid);
648       gdb_assert (tp);
649       tp->stop_requested = stop;
650     }
651
652   /* Call the stop requested observer so other components of GDB can
653      react to this request.  */
654   if (stop)
655     observer_notify_thread_stop_requested (ptid);
656 }
657
658 void
659 finish_thread_state (ptid_t ptid)
660 {
661   struct thread_info *tp;
662   int all;
663   int any_started = 0;
664
665   all = ptid_equal (ptid, minus_one_ptid);
666
667   if (all || ptid_is_pid (ptid))
668     {
669       for (tp = thread_list; tp; tp = tp->next)
670         {
671           if (tp->state_ == THREAD_EXITED)
672             continue;
673           if (all || ptid_get_pid (ptid) == ptid_get_pid (tp->ptid))
674             {
675               if (tp->executing_ && tp->state_ == THREAD_STOPPED)
676                 any_started = 1;
677               tp->state_ = tp->executing_ ? THREAD_RUNNING : THREAD_STOPPED;
678             }
679         }
680     }
681   else
682     {
683       tp = find_thread_pid (ptid);
684       gdb_assert (tp);
685       if (tp->state_ != THREAD_EXITED)
686         {
687           if (tp->executing_ && tp->state_ == THREAD_STOPPED)
688             any_started = 1;
689           tp->state_ = tp->executing_ ? THREAD_RUNNING : THREAD_STOPPED;
690         }
691     }
692
693   if (any_started)
694     observer_notify_target_resumed (ptid);
695 }
696
697 void
698 finish_thread_state_cleanup (void *arg)
699 {
700   ptid_t *ptid_p = arg;
701
702   gdb_assert (arg);
703
704   finish_thread_state (*ptid_p);
705 }
706
707 /* Prints the list of threads and their details on UIOUT.
708    This is a version of 'info_thread_command' suitable for
709    use from MI.  
710    If REQUESTED_THREAD is not -1, it's the GDB id of the thread
711    that should be printed.  Otherwise, all threads are
712    printed.  
713    If PID is not -1, only print threads from the process PID.
714    Otherwise, threads from all attached PIDs are printed.   
715    If both REQUESTED_THREAD and PID are not -1, then the thread
716    is printed if it belongs to the specified process.  Otherwise,
717    an error is raised.  */
718 void
719 print_thread_info (struct ui_out *uiout, int requested_thread, int pid)
720 {
721   struct thread_info *tp;
722   ptid_t current_ptid;
723   struct cleanup *old_chain;
724   char *extra_info;
725   int current_thread = -1;
726
727   prune_threads ();
728   target_find_new_threads ();
729   current_ptid = inferior_ptid;
730
731   /* We'll be switching threads temporarily.  */
732   old_chain = make_cleanup_restore_current_thread ();
733
734   make_cleanup_ui_out_list_begin_end (uiout, "threads");
735   for (tp = thread_list; tp; tp = tp->next)
736     {
737       struct cleanup *chain2;
738
739       if (requested_thread != -1 && tp->num != requested_thread)
740         continue;
741
742       if (pid != -1 && PIDGET (tp->ptid) != pid)
743         {
744           if (requested_thread != -1)
745             error (_("Requested thread not found in requested process"));
746           continue;
747         }
748
749       if (ptid_equal (tp->ptid, current_ptid))
750         current_thread = tp->num;
751
752       if (tp->state_ == THREAD_EXITED)
753         continue;
754
755       chain2 = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
756
757       if (ptid_equal (tp->ptid, current_ptid))
758         ui_out_text (uiout, "* ");
759       else
760         ui_out_text (uiout, "  ");
761
762       ui_out_field_int (uiout, "id", tp->num);
763       ui_out_text (uiout, " ");
764       ui_out_field_string (uiout, "target-id", target_pid_to_str (tp->ptid));
765
766       extra_info = target_extra_thread_info (tp);
767       if (extra_info)
768         {
769           ui_out_text (uiout, " (");
770           ui_out_field_string (uiout, "details", extra_info);
771           ui_out_text (uiout, ")");
772         }
773       ui_out_text (uiout, "  ");
774
775       if (tp->state_ == THREAD_RUNNING)
776         ui_out_text (uiout, "(running)\n");
777       else
778         {
779           /* The switch below puts us at the top of the stack (leaf
780              frame).  */
781           switch_to_thread (tp->ptid);
782           print_stack_frame (get_selected_frame (NULL),
783                              /* For MI output, print frame level.  */
784                              ui_out_is_mi_like_p (uiout),
785                              LOCATION);
786         }
787
788       if (ui_out_is_mi_like_p (uiout))
789         {
790           char *state = "stopped";
791           if (tp->state_ == THREAD_RUNNING)
792             state = "running";
793           ui_out_field_string (uiout, "state", state);
794         }
795
796       do_cleanups (chain2);
797     }
798
799   /* Restores the current thread and the frame selected before
800      the "info threads" command.  */
801   do_cleanups (old_chain);
802
803   if (pid == -1 && requested_thread == -1)
804     {
805       gdb_assert (current_thread != -1
806                   || !thread_list
807                   || ptid_equal (inferior_ptid, null_ptid));
808       if (current_thread != -1 && ui_out_is_mi_like_p (uiout))
809         ui_out_field_int (uiout, "current-thread-id", current_thread);
810
811       if (current_thread != -1 && is_exited (current_ptid))
812         ui_out_message (uiout, 0, "\n\
813 The current thread <Thread ID %d> has terminated.  See `help thread'.\n",
814                         current_thread);
815       else if (thread_list
816                && current_thread == -1
817                && ptid_equal (current_ptid, null_ptid))
818         ui_out_message (uiout, 0, "\n\
819 No selected thread.  See `help thread'.\n");
820     }
821 }
822
823
824 /* Print information about currently known threads 
825
826  * Note: this has the drawback that it _really_ switches
827  *       threads, which frees the frame cache.  A no-side
828  *       effects info-threads command would be nicer.
829  */
830
831 static void
832 info_threads_command (char *arg, int from_tty)
833 {
834   print_thread_info (uiout, -1, -1);
835 }
836
837 /* Switch from one thread to another. */
838
839 void
840 switch_to_thread (ptid_t ptid)
841 {
842   if (ptid_equal (ptid, inferior_ptid))
843     return;
844
845   inferior_ptid = ptid;
846   reinit_frame_cache ();
847   registers_changed ();
848
849   /* We don't check for is_stopped, because we're called at times
850      while in the TARGET_RUNNING state, e.g., while handling an
851      internal event.  */
852   if (!ptid_equal (inferior_ptid, null_ptid)
853       && !is_exited (ptid)
854       && !is_executing (ptid))
855     stop_pc = read_pc ();
856   else
857     stop_pc = ~(CORE_ADDR) 0;
858 }
859
860 static void
861 restore_current_thread (ptid_t ptid)
862 {
863   switch_to_thread (ptid);
864 }
865
866 static void
867 restore_selected_frame (struct frame_id a_frame_id, int frame_level)
868 {
869   struct frame_info *frame = NULL;
870   int count;
871
872   gdb_assert (frame_level >= 0);
873
874   /* Restore by level first, check if the frame id is the same as
875      expected.  If that fails, try restoring by frame id.  If that
876      fails, nothing to do, just warn the user.  */
877
878   count = frame_level;
879   frame = find_relative_frame (get_current_frame (), &count);
880   if (count == 0
881       && frame != NULL
882       /* Either the frame ids match, of they're both invalid.  The
883          latter case is not failsafe, but since it's highly unlikely
884          the search by level finds the wrong frame, it's 99.9(9)% of
885          the time (for all practical purposes) safe.  */
886       && (frame_id_eq (get_frame_id (frame), a_frame_id)
887           /* Note: could be better to check every frame_id
888              member for equality here.  */
889           || (!frame_id_p (get_frame_id (frame))
890               && !frame_id_p (a_frame_id))))
891     {
892       /* Cool, all is fine.  */
893       select_frame (frame);
894       return;
895     }
896
897   frame = frame_find_by_id (a_frame_id);
898   if (frame != NULL)
899     {
900       /* Cool, refound it.  */
901       select_frame (frame);
902       return;
903     }
904
905   /* Nothing else to do, the frame layout really changed.  Select the
906      innermost stack frame.  */
907   select_frame (get_current_frame ());
908
909   /* Warn the user.  */
910   if (!ui_out_is_mi_like_p (uiout))
911     {
912       warning (_("\
913 Couldn't restore frame #%d in current thread, at reparsed frame #0\n"),
914                frame_level);
915       /* For MI, we should probably have a notification about
916          current frame change.  But this error is not very
917          likely, so don't bother for now.  */
918       print_stack_frame (get_selected_frame (NULL), 1, SRC_LINE);
919     }
920 }
921
922 struct current_thread_cleanup
923 {
924   ptid_t inferior_ptid;
925   struct frame_id selected_frame_id;
926   int selected_frame_level;
927   int was_stopped;
928 };
929
930 static void
931 do_restore_current_thread_cleanup (void *arg)
932 {
933   struct thread_info *tp;
934   struct current_thread_cleanup *old = arg;
935
936   tp = find_thread_pid (old->inferior_ptid);
937
938   /* If the previously selected thread belonged to a process that has
939      in the mean time been deleted (due to normal exit, detach, etc.),
940      then don't revert back to it, but instead simply drop back to no
941      thread selected.  */
942   if (tp
943       && find_inferior_pid (ptid_get_pid (tp->ptid)) != NULL)
944     restore_current_thread (old->inferior_ptid);
945   else
946     restore_current_thread (null_ptid);
947
948   /* The running state of the originally selected thread may have
949      changed, so we have to recheck it here.  */
950   if (!ptid_equal (inferior_ptid, null_ptid)
951       && old->was_stopped
952       && is_stopped (inferior_ptid)
953       && target_has_registers
954       && target_has_stack
955       && target_has_memory)
956     restore_selected_frame (old->selected_frame_id,
957                             old->selected_frame_level);
958 }
959
960 static void
961 restore_current_thread_cleanup_dtor (void *arg)
962 {
963   struct current_thread_cleanup *old = arg;
964   struct thread_info *tp;
965   tp = find_thread_pid (old->inferior_ptid);
966   if (tp)
967     tp->refcount--;
968   xfree (old);
969 }
970
971 struct cleanup *
972 make_cleanup_restore_current_thread (void)
973 {
974   struct thread_info *tp;
975   struct frame_info *frame;
976   struct current_thread_cleanup *old;
977
978   old = xmalloc (sizeof (struct current_thread_cleanup));
979   old->inferior_ptid = inferior_ptid;
980
981   if (!ptid_equal (inferior_ptid, null_ptid))
982     {
983       old->was_stopped = is_stopped (inferior_ptid);
984       if (old->was_stopped
985           && target_has_registers
986           && target_has_stack
987           && target_has_memory)
988         frame = get_selected_frame (NULL);
989       else
990         frame = NULL;
991
992       old->selected_frame_id = get_frame_id (frame);
993       old->selected_frame_level = frame_relative_level (frame);
994
995       tp = find_thread_pid (inferior_ptid);
996       if (tp)
997         tp->refcount++;
998     }
999
1000   return make_cleanup_dtor (do_restore_current_thread_cleanup, old,
1001                             restore_current_thread_cleanup_dtor);
1002 }
1003
1004 /* Apply a GDB command to a list of threads.  List syntax is a whitespace
1005    seperated list of numbers, or ranges, or the keyword `all'.  Ranges consist
1006    of two numbers seperated by a hyphen.  Examples:
1007
1008    thread apply 1 2 7 4 backtrace       Apply backtrace cmd to threads 1,2,7,4
1009    thread apply 2-7 9 p foo(1)  Apply p foo(1) cmd to threads 2->7 & 9
1010    thread apply all p x/i $pc   Apply x/i $pc cmd to all threads
1011  */
1012
1013 static void
1014 thread_apply_all_command (char *cmd, int from_tty)
1015 {
1016   struct thread_info *tp;
1017   struct cleanup *old_chain;
1018   char *saved_cmd;
1019
1020   if (cmd == NULL || *cmd == '\000')
1021     error (_("Please specify a command following the thread ID list"));
1022
1023   prune_threads ();
1024   target_find_new_threads ();
1025
1026   old_chain = make_cleanup_restore_current_thread ();
1027
1028   /* Save a copy of the command in case it is clobbered by
1029      execute_command */
1030   saved_cmd = xstrdup (cmd);
1031   make_cleanup (xfree, saved_cmd);
1032   for (tp = thread_list; tp; tp = tp->next)
1033     if (thread_alive (tp))
1034       {
1035         switch_to_thread (tp->ptid);
1036
1037         printf_filtered (_("\nThread %d (%s):\n"),
1038                          tp->num, target_pid_to_str (inferior_ptid));
1039         execute_command (cmd, from_tty);
1040         strcpy (cmd, saved_cmd);        /* Restore exact command used previously */
1041       }
1042
1043   do_cleanups (old_chain);
1044 }
1045
1046 static void
1047 thread_apply_command (char *tidlist, int from_tty)
1048 {
1049   char *cmd;
1050   char *p;
1051   struct cleanup *old_chain;
1052   char *saved_cmd;
1053
1054   if (tidlist == NULL || *tidlist == '\000')
1055     error (_("Please specify a thread ID list"));
1056
1057   for (cmd = tidlist; *cmd != '\000' && !isalpha (*cmd); cmd++);
1058
1059   if (*cmd == '\000')
1060     error (_("Please specify a command following the thread ID list"));
1061
1062   /* Save a copy of the command in case it is clobbered by
1063      execute_command */
1064   saved_cmd = xstrdup (cmd);
1065   old_chain = make_cleanup (xfree, saved_cmd);
1066   while (tidlist < cmd)
1067     {
1068       struct thread_info *tp;
1069       int start, end;
1070
1071       start = strtol (tidlist, &p, 10);
1072       if (p == tidlist)
1073         error (_("Error parsing %s"), tidlist);
1074       tidlist = p;
1075
1076       while (*tidlist == ' ' || *tidlist == '\t')
1077         tidlist++;
1078
1079       if (*tidlist == '-')      /* Got a range of IDs? */
1080         {
1081           tidlist++;            /* Skip the - */
1082           end = strtol (tidlist, &p, 10);
1083           if (p == tidlist)
1084             error (_("Error parsing %s"), tidlist);
1085           tidlist = p;
1086
1087           while (*tidlist == ' ' || *tidlist == '\t')
1088             tidlist++;
1089         }
1090       else
1091         end = start;
1092
1093       make_cleanup_restore_current_thread ();
1094
1095       for (; start <= end; start++)
1096         {
1097           tp = find_thread_id (start);
1098
1099           if (!tp)
1100             warning (_("Unknown thread %d."), start);
1101           else if (!thread_alive (tp))
1102             warning (_("Thread %d has terminated."), start);
1103           else
1104             {
1105               switch_to_thread (tp->ptid);
1106
1107               printf_filtered (_("\nThread %d (%s):\n"), tp->num,
1108                                target_pid_to_str (inferior_ptid));
1109               execute_command (cmd, from_tty);
1110
1111               /* Restore exact command used previously.  */
1112               strcpy (cmd, saved_cmd);
1113             }
1114         }
1115     }
1116
1117   do_cleanups (old_chain);
1118 }
1119
1120 /* Switch to the specified thread.  Will dispatch off to thread_apply_command
1121    if prefix of arg is `apply'.  */
1122
1123 static void
1124 thread_command (char *tidstr, int from_tty)
1125 {
1126   if (!tidstr)
1127     {
1128       if (ptid_equal (inferior_ptid, null_ptid))
1129         error (_("No thread selected"));
1130
1131       if (target_has_stack)
1132         {
1133           if (is_exited (inferior_ptid))
1134             printf_filtered (_("[Current thread is %d (%s) (exited)]\n"),
1135                              pid_to_thread_id (inferior_ptid),
1136                              target_pid_to_str (inferior_ptid));
1137           else
1138             printf_filtered (_("[Current thread is %d (%s)]\n"),
1139                              pid_to_thread_id (inferior_ptid),
1140                              target_pid_to_str (inferior_ptid));
1141         }
1142       else
1143         error (_("No stack."));
1144       return;
1145     }
1146
1147   gdb_thread_select (uiout, tidstr, NULL);
1148 }
1149
1150 /* Print notices when new threads are attached and detached.  */
1151 int print_thread_events = 1;
1152 static void
1153 show_print_thread_events (struct ui_file *file, int from_tty,
1154                           struct cmd_list_element *c, const char *value)
1155 {
1156   fprintf_filtered (file, _("\
1157 Printing of thread events is %s.\n"),
1158                     value);
1159 }
1160
1161 static int
1162 do_captured_thread_select (struct ui_out *uiout, void *tidstr)
1163 {
1164   int num;
1165   struct thread_info *tp;
1166
1167   num = value_as_long (parse_and_eval (tidstr));
1168
1169   tp = find_thread_id (num);
1170
1171   if (!tp)
1172     error (_("Thread ID %d not known."), num);
1173
1174   if (!thread_alive (tp))
1175     error (_("Thread ID %d has terminated."), num);
1176
1177   switch_to_thread (tp->ptid);
1178
1179   annotate_thread_changed ();
1180
1181   ui_out_text (uiout, "[Switching to thread ");
1182   ui_out_field_int (uiout, "new-thread-id", pid_to_thread_id (inferior_ptid));
1183   ui_out_text (uiout, " (");
1184   ui_out_text (uiout, target_pid_to_str (inferior_ptid));
1185   ui_out_text (uiout, ")]");
1186
1187   /* Note that we can't reach this with an exited thread, due to the
1188      thread_alive check above.  */
1189   if (tp->state_ == THREAD_RUNNING)
1190     ui_out_text (uiout, "(running)\n");
1191   else
1192     print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
1193
1194   /* Since the current thread may have changed, see if there is any
1195      exited thread we can now delete.  */
1196   prune_threads ();
1197
1198   return GDB_RC_OK;
1199 }
1200
1201 enum gdb_rc
1202 gdb_thread_select (struct ui_out *uiout, char *tidstr, char **error_message)
1203 {
1204   if (catch_exceptions_with_msg (uiout, do_captured_thread_select, tidstr,
1205                                  error_message, RETURN_MASK_ALL) < 0)
1206     return GDB_RC_FAIL;
1207   return GDB_RC_OK;
1208 }
1209
1210 /* Commands with a prefix of `thread'.  */
1211 struct cmd_list_element *thread_cmd_list = NULL;
1212
1213 void
1214 _initialize_thread (void)
1215 {
1216   static struct cmd_list_element *thread_apply_list = NULL;
1217
1218   add_info ("threads", info_threads_command,
1219             _("IDs of currently known threads."));
1220
1221   add_prefix_cmd ("thread", class_run, thread_command, _("\
1222 Use this command to switch between threads.\n\
1223 The new thread ID must be currently known."),
1224                   &thread_cmd_list, "thread ", 1, &cmdlist);
1225
1226   add_prefix_cmd ("apply", class_run, thread_apply_command,
1227                   _("Apply a command to a list of threads."),
1228                   &thread_apply_list, "thread apply ", 1, &thread_cmd_list);
1229
1230   add_cmd ("all", class_run, thread_apply_all_command,
1231            _("Apply a command to all threads."), &thread_apply_list);
1232
1233   if (!xdb_commands)
1234     add_com_alias ("t", "thread", class_run, 1);
1235
1236   add_setshow_boolean_cmd ("thread-events", no_class,
1237          &print_thread_events, _("\
1238 Set printing of thread events (such as thread start and exit)."), _("\
1239 Show printing of thread events (such as thread start and exit)."), NULL,
1240          NULL,
1241          show_print_thread_events,
1242          &setprintlist, &showprintlist);
1243 }