2011-02-15 Michael Snyder <msnyder@vmware.com>
[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, 2010, 2011
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 #include "gdb_regex.h"
47
48 /* Definition of struct thread_info exported to gdbthread.h.  */
49
50 /* Prototypes for exported functions.  */
51
52 void _initialize_thread (void);
53
54 /* Prototypes for local functions.  */
55
56 static struct thread_info *thread_list = NULL;
57 static int highest_thread_num;
58
59 static void thread_command (char *tidstr, int from_tty);
60 static void thread_apply_all_command (char *, int);
61 static int thread_alive (struct thread_info *);
62 static void info_threads_command (char *, int);
63 static void thread_apply_command (char *, int);
64 static void restore_current_thread (ptid_t);
65 static void prune_threads (void);
66
67 /* Frontend view of the thread state.  Possible extensions: stepping,
68    finishing, until(ling),...  */
69 enum thread_state
70 {
71   THREAD_STOPPED,
72   THREAD_RUNNING,
73   THREAD_EXITED,
74 };
75
76 struct thread_info*
77 inferior_thread (void)
78 {
79   struct thread_info *tp = find_thread_ptid (inferior_ptid);
80   gdb_assert (tp);
81   return tp;
82 }
83
84 void
85 delete_step_resume_breakpoint (struct thread_info *tp)
86 {
87   if (tp && tp->control.step_resume_breakpoint)
88     {
89       delete_breakpoint (tp->control.step_resume_breakpoint);
90       tp->control.step_resume_breakpoint = NULL;
91     }
92 }
93
94 void
95 delete_exception_resume_breakpoint (struct thread_info *tp)
96 {
97   if (tp && tp->control.exception_resume_breakpoint)
98     {
99       delete_breakpoint (tp->control.exception_resume_breakpoint);
100       tp->control.exception_resume_breakpoint = NULL;
101     }
102 }
103
104 static void
105 clear_thread_inferior_resources (struct thread_info *tp)
106 {
107   /* NOTE: this will take care of any left-over step_resume breakpoints,
108      but not any user-specified thread-specific breakpoints.  We can not
109      delete the breakpoint straight-off, because the inferior might not
110      be stopped at the moment.  */
111   if (tp->control.step_resume_breakpoint)
112     {
113       tp->control.step_resume_breakpoint->disposition = disp_del_at_next_stop;
114       tp->control.step_resume_breakpoint = NULL;
115     }
116
117   if (tp->control.exception_resume_breakpoint)
118     {
119       tp->control.exception_resume_breakpoint->disposition
120         = disp_del_at_next_stop;
121       tp->control.exception_resume_breakpoint = NULL;
122     }
123
124   bpstat_clear (&tp->control.stop_bpstat);
125
126   discard_all_intermediate_continuations_thread (tp);
127   discard_all_continuations_thread (tp);
128
129   delete_longjmp_breakpoint (tp->num);
130 }
131
132 static void
133 free_thread (struct thread_info *tp)
134 {
135   clear_thread_inferior_resources (tp);
136
137   if (tp->private)
138     {
139       if (tp->private_dtor)
140         tp->private_dtor (tp->private);
141       else
142         xfree (tp->private);
143     }
144
145   xfree (tp->name);
146   xfree (tp);
147 }
148
149 void
150 init_thread_list (void)
151 {
152   struct thread_info *tp, *tpnext;
153
154   highest_thread_num = 0;
155
156   if (!thread_list)
157     return;
158
159   for (tp = thread_list; tp; tp = tpnext)
160     {
161       tpnext = tp->next;
162       free_thread (tp);
163     }
164
165   thread_list = NULL;
166 }
167
168 /* Allocate a new thread with target id PTID and add it to the thread
169    list.  */
170
171 static struct thread_info *
172 new_thread (ptid_t ptid)
173 {
174   struct thread_info *tp;
175
176   tp = xcalloc (1, sizeof (*tp));
177
178   tp->ptid = ptid;
179   tp->num = ++highest_thread_num;
180   tp->next = thread_list;
181   thread_list = tp;
182
183   /* Nothing to follow yet.  */
184   tp->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
185   tp->state_ = THREAD_STOPPED;
186
187   return tp;
188 }
189
190 struct thread_info *
191 add_thread_silent (ptid_t ptid)
192 {
193   struct thread_info *tp;
194
195   tp = find_thread_ptid (ptid);
196   if (tp)
197     /* Found an old thread with the same id.  It has to be dead,
198        otherwise we wouldn't be adding a new thread with the same id.
199        The OS is reusing this id --- delete it, and recreate a new
200        one.  */
201     {
202       /* In addition to deleting the thread, if this is the current
203          thread, then we need to take care that delete_thread doesn't
204          really delete the thread if it is inferior_ptid.  Create a
205          new template thread in the list with an invalid ptid, switch
206          to it, delete the original thread, reset the new thread's
207          ptid, and switch to it.  */
208
209       if (ptid_equal (inferior_ptid, ptid))
210         {
211           tp = new_thread (null_ptid);
212
213           /* Make switch_to_thread not read from the thread.  */
214           tp->state_ = THREAD_EXITED;
215           switch_to_thread (null_ptid);
216
217           /* Now we can delete it.  */
218           delete_thread (ptid);
219
220           /* Now reset its ptid, and reswitch inferior_ptid to it.  */
221           tp->ptid = ptid;
222           tp->state_ = THREAD_STOPPED;
223           switch_to_thread (ptid);
224
225           observer_notify_new_thread (tp);
226
227           /* All done.  */
228           return tp;
229         }
230       else
231         /* Just go ahead and delete it.  */
232         delete_thread (ptid);
233     }
234
235   tp = new_thread (ptid);
236   observer_notify_new_thread (tp);
237
238   return tp;
239 }
240
241 struct thread_info *
242 add_thread_with_info (ptid_t ptid, struct private_thread_info *private)
243 {
244   struct thread_info *result = add_thread_silent (ptid);
245
246   result->private = private;
247
248   if (print_thread_events)
249     printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid));
250
251   annotate_new_thread ();
252   return result;
253 }
254
255 struct thread_info *
256 add_thread (ptid_t ptid)
257 {
258   return add_thread_with_info (ptid, NULL);
259 }
260
261 /* Delete thread PTID.  If SILENT, don't notify the observer of this
262    exit.  */
263 static void
264 delete_thread_1 (ptid_t ptid, int silent)
265 {
266   struct thread_info *tp, *tpprev;
267
268   tpprev = NULL;
269
270   for (tp = thread_list; tp; tpprev = tp, tp = tp->next)
271     if (ptid_equal (tp->ptid, ptid))
272       break;
273
274   if (!tp)
275     return;
276
277   /* If this is the current thread, or there's code out there that
278      relies on it existing (refcount > 0) we can't delete yet.  Mark
279      it as exited, and notify it.  */
280   if (tp->refcount > 0
281       || ptid_equal (tp->ptid, inferior_ptid))
282     {
283       if (tp->state_ != THREAD_EXITED)
284         {
285           observer_notify_thread_exit (tp, silent);
286
287           /* Tag it as exited.  */
288           tp->state_ = THREAD_EXITED;
289
290           /* Clear breakpoints, etc. associated with this thread.  */
291           clear_thread_inferior_resources (tp);
292         }
293
294        /* Will be really deleted some other time.  */
295        return;
296      }
297
298   if (tpprev)
299     tpprev->next = tp->next;
300   else
301     thread_list = tp->next;
302
303   /* Notify thread exit, but only if we haven't already.  */
304   if (tp->state_ != THREAD_EXITED)
305     observer_notify_thread_exit (tp, silent);
306
307   free_thread (tp);
308 }
309
310 /* Delete thread PTID and notify of thread exit.  If this is
311    inferior_ptid, don't actually delete it, but tag it as exited and
312    do the notification.  If PTID is the user selected thread, clear
313    it.  */
314 void
315 delete_thread (ptid_t ptid)
316 {
317   delete_thread_1 (ptid, 0 /* not silent */);
318 }
319
320 void
321 delete_thread_silent (ptid_t ptid)
322 {
323   delete_thread_1 (ptid, 1 /* silent */);
324 }
325
326 struct thread_info *
327 find_thread_id (int num)
328 {
329   struct thread_info *tp;
330
331   for (tp = thread_list; tp; tp = tp->next)
332     if (tp->num == num)
333       return tp;
334
335   return NULL;
336 }
337
338 /* Find a thread_info by matching PTID.  */
339 struct thread_info *
340 find_thread_ptid (ptid_t ptid)
341 {
342   struct thread_info *tp;
343
344   for (tp = thread_list; tp; tp = tp->next)
345     if (ptid_equal (tp->ptid, ptid))
346       return tp;
347
348   return NULL;
349 }
350
351 /*
352  * Thread iterator function.
353  *
354  * Calls a callback function once for each thread, so long as
355  * the callback function returns false.  If the callback function
356  * returns true, the iteration will end and the current thread
357  * will be returned.  This can be useful for implementing a 
358  * search for a thread with arbitrary attributes, or for applying
359  * some operation to every thread.
360  *
361  * FIXME: some of the existing functionality, such as 
362  * "Thread apply all", might be rewritten using this functionality.
363  */
364
365 struct thread_info *
366 iterate_over_threads (int (*callback) (struct thread_info *, void *),
367                       void *data)
368 {
369   struct thread_info *tp, *next;
370
371   for (tp = thread_list; tp; tp = next)
372     {
373       next = tp->next;
374       if ((*callback) (tp, data))
375         return tp;
376     }
377
378   return NULL;
379 }
380
381 int
382 thread_count (void)
383 {
384   int result = 0;
385   struct thread_info *tp;
386
387   for (tp = thread_list; tp; tp = tp->next)
388     ++result;
389
390   return result;  
391 }
392
393 int
394 valid_thread_id (int num)
395 {
396   struct thread_info *tp;
397
398   for (tp = thread_list; tp; tp = tp->next)
399     if (tp->num == num)
400       return 1;
401
402   return 0;
403 }
404
405 int
406 pid_to_thread_id (ptid_t ptid)
407 {
408   struct thread_info *tp;
409
410   for (tp = thread_list; tp; tp = tp->next)
411     if (ptid_equal (tp->ptid, ptid))
412       return tp->num;
413
414   return 0;
415 }
416
417 ptid_t
418 thread_id_to_pid (int num)
419 {
420   struct thread_info *thread = find_thread_id (num);
421
422   if (thread)
423     return thread->ptid;
424   else
425     return pid_to_ptid (-1);
426 }
427
428 int
429 in_thread_list (ptid_t ptid)
430 {
431   struct thread_info *tp;
432
433   for (tp = thread_list; tp; tp = tp->next)
434     if (ptid_equal (tp->ptid, ptid))
435       return 1;
436
437   return 0;                     /* Never heard of 'im.  */
438 }
439
440 /* Finds the first thread of the inferior given by PID.  If PID is -1,
441    return the first thread in the list.  */
442
443 struct thread_info *
444 first_thread_of_process (int pid)
445 {
446   struct thread_info *tp, *ret = NULL;
447
448   for (tp = thread_list; tp; tp = tp->next)
449     if (pid == -1 || ptid_get_pid (tp->ptid) == pid)
450       if (ret == NULL || tp->num < ret->num)
451         ret = tp;
452
453   return ret;
454 }
455
456 struct thread_info *
457 any_thread_of_process (int pid)
458 {
459   struct thread_info *tp;
460
461   for (tp = thread_list; tp; tp = tp->next)
462     if (ptid_get_pid (tp->ptid) == pid)
463       return tp;
464
465   return NULL;
466 }
467
468 struct thread_info *
469 any_live_thread_of_process (int pid)
470 {
471   struct thread_info *tp;
472   struct thread_info *tp_running = NULL;
473
474   for (tp = thread_list; tp; tp = tp->next)
475     if (ptid_get_pid (tp->ptid) == pid)
476       {
477         if (tp->state_ == THREAD_STOPPED)
478           return tp;
479         else if (tp->state_ == THREAD_RUNNING)
480           tp_running = tp;
481       }
482
483   return tp_running;
484 }
485
486 /* Print a list of thread ids currently known, and the total number of
487    threads.  To be used from within catch_errors.  */
488 static int
489 do_captured_list_thread_ids (struct ui_out *uiout, void *arg)
490 {
491   struct thread_info *tp;
492   int num = 0;
493   struct cleanup *cleanup_chain;
494   int current_thread = -1;
495
496   update_thread_list ();
497
498   cleanup_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "thread-ids");
499
500   for (tp = thread_list; tp; tp = tp->next)
501     {
502       if (tp->state_ == THREAD_EXITED)
503         continue;
504
505       if (ptid_equal (tp->ptid, inferior_ptid))
506         current_thread = tp->num;
507
508       num++;
509       ui_out_field_int (uiout, "thread-id", tp->num);
510     }
511
512   do_cleanups (cleanup_chain);
513
514   if (current_thread != -1)
515     ui_out_field_int (uiout, "current-thread-id", current_thread);
516   ui_out_field_int (uiout, "number-of-threads", num);
517   return GDB_RC_OK;
518 }
519
520 /* Official gdblib interface function to get a list of thread ids and
521    the total number.  */
522 enum gdb_rc
523 gdb_list_thread_ids (struct ui_out *uiout, char **error_message)
524 {
525   if (catch_exceptions_with_msg (uiout, do_captured_list_thread_ids, NULL,
526                                  error_message, RETURN_MASK_ALL) < 0)
527     return GDB_RC_FAIL;
528   return GDB_RC_OK;
529 }
530
531 /* Return true if TP is an active thread.  */
532 static int
533 thread_alive (struct thread_info *tp)
534 {
535   if (tp->state_ == THREAD_EXITED)
536     return 0;
537   if (!target_thread_alive (tp->ptid))
538     return 0;
539   return 1;
540 }
541
542 static void
543 prune_threads (void)
544 {
545   struct thread_info *tp, *next;
546
547   for (tp = thread_list; tp; tp = next)
548     {
549       next = tp->next;
550       if (!thread_alive (tp))
551         delete_thread (tp->ptid);
552     }
553 }
554
555 void
556 thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid)
557 {
558   struct inferior *inf;
559   struct thread_info *tp;
560
561   /* It can happen that what we knew as the target inferior id
562      changes.  E.g, target remote may only discover the remote process
563      pid after adding the inferior to GDB's list.  */
564   inf = find_inferior_pid (ptid_get_pid (old_ptid));
565   inf->pid = ptid_get_pid (new_ptid);
566
567   tp = find_thread_ptid (old_ptid);
568   tp->ptid = new_ptid;
569
570   observer_notify_thread_ptid_changed (old_ptid, new_ptid);
571 }
572
573 void
574 set_running (ptid_t ptid, int running)
575 {
576   struct thread_info *tp;
577   int all = ptid_equal (ptid, minus_one_ptid);
578
579   /* We try not to notify the observer if no thread has actually changed 
580      the running state -- merely to reduce the number of messages to 
581      frontend.  Frontend is supposed to handle multiple *running just fine.  */
582   if (all || ptid_is_pid (ptid))
583     {
584       int any_started = 0;
585
586       for (tp = thread_list; tp; tp = tp->next)
587         if (all || ptid_get_pid (tp->ptid) == ptid_get_pid (ptid))
588           {
589             if (tp->state_ == THREAD_EXITED)
590               continue;
591             if (running && tp->state_ == THREAD_STOPPED)
592               any_started = 1;
593             tp->state_ = running ? THREAD_RUNNING : THREAD_STOPPED;
594           }
595       if (any_started)
596         observer_notify_target_resumed (ptid);
597     }
598   else
599     {
600       int started = 0;
601
602       tp = find_thread_ptid (ptid);
603       gdb_assert (tp);
604       gdb_assert (tp->state_ != THREAD_EXITED);
605       if (running && tp->state_ == THREAD_STOPPED)
606         started = 1;
607       tp->state_ = running ? THREAD_RUNNING : THREAD_STOPPED;
608       if (started)
609         observer_notify_target_resumed (ptid);
610     }
611 }
612
613 static int
614 is_thread_state (ptid_t ptid, enum thread_state state)
615 {
616   struct thread_info *tp;
617
618   tp = find_thread_ptid (ptid);
619   gdb_assert (tp);
620   return tp->state_ == state;
621 }
622
623 int
624 is_stopped (ptid_t ptid)
625 {
626   return is_thread_state (ptid, THREAD_STOPPED);
627 }
628
629 int
630 is_exited (ptid_t ptid)
631 {
632   return is_thread_state (ptid, THREAD_EXITED);
633 }
634
635 int
636 is_running (ptid_t ptid)
637 {
638   return is_thread_state (ptid, THREAD_RUNNING);
639 }
640
641 int
642 any_running (void)
643 {
644   struct thread_info *tp;
645
646   for (tp = thread_list; tp; tp = tp->next)
647     if (tp->state_ == THREAD_RUNNING)
648       return 1;
649
650   return 0;
651 }
652
653 int
654 is_executing (ptid_t ptid)
655 {
656   struct thread_info *tp;
657
658   tp = find_thread_ptid (ptid);
659   gdb_assert (tp);
660   return tp->executing_;
661 }
662
663 void
664 set_executing (ptid_t ptid, int executing)
665 {
666   struct thread_info *tp;
667   int all = ptid_equal (ptid, minus_one_ptid);
668
669   if (all || ptid_is_pid (ptid))
670     {
671       for (tp = thread_list; tp; tp = tp->next)
672         if (all || ptid_get_pid (tp->ptid) == ptid_get_pid (ptid))
673           tp->executing_ = executing;
674     }
675   else
676     {
677       tp = find_thread_ptid (ptid);
678       gdb_assert (tp);
679       tp->executing_ = executing;
680     }
681 }
682
683 void
684 set_stop_requested (ptid_t ptid, int stop)
685 {
686   struct thread_info *tp;
687   int all = ptid_equal (ptid, minus_one_ptid);
688
689   if (all || ptid_is_pid (ptid))
690     {
691       for (tp = thread_list; tp; tp = tp->next)
692         if (all || ptid_get_pid (tp->ptid) == ptid_get_pid (ptid))
693           tp->stop_requested = stop;
694     }
695   else
696     {
697       tp = find_thread_ptid (ptid);
698       gdb_assert (tp);
699       tp->stop_requested = stop;
700     }
701
702   /* Call the stop requested observer so other components of GDB can
703      react to this request.  */
704   if (stop)
705     observer_notify_thread_stop_requested (ptid);
706 }
707
708 void
709 finish_thread_state (ptid_t ptid)
710 {
711   struct thread_info *tp;
712   int all;
713   int any_started = 0;
714
715   all = ptid_equal (ptid, minus_one_ptid);
716
717   if (all || ptid_is_pid (ptid))
718     {
719       for (tp = thread_list; tp; tp = tp->next)
720         {
721           if (tp->state_ == THREAD_EXITED)
722             continue;
723           if (all || ptid_get_pid (ptid) == ptid_get_pid (tp->ptid))
724             {
725               if (tp->executing_ && tp->state_ == THREAD_STOPPED)
726                 any_started = 1;
727               tp->state_ = tp->executing_ ? THREAD_RUNNING : THREAD_STOPPED;
728             }
729         }
730     }
731   else
732     {
733       tp = find_thread_ptid (ptid);
734       gdb_assert (tp);
735       if (tp->state_ != THREAD_EXITED)
736         {
737           if (tp->executing_ && tp->state_ == THREAD_STOPPED)
738             any_started = 1;
739           tp->state_ = tp->executing_ ? THREAD_RUNNING : THREAD_STOPPED;
740         }
741     }
742
743   if (any_started)
744     observer_notify_target_resumed (ptid);
745 }
746
747 void
748 finish_thread_state_cleanup (void *arg)
749 {
750   ptid_t *ptid_p = arg;
751
752   gdb_assert (arg);
753
754   finish_thread_state (*ptid_p);
755 }
756
757 /* Prints the list of threads and their details on UIOUT.
758    This is a version of 'info_thread_command' suitable for
759    use from MI.
760    If REQUESTED_THREAD is not -1, it's the GDB id of the thread
761    that should be printed.  Otherwise, all threads are
762    printed.
763    If PID is not -1, only print threads from the process PID.
764    Otherwise, threads from all attached PIDs are printed.
765    If both REQUESTED_THREAD and PID are not -1, then the thread
766    is printed if it belongs to the specified process.  Otherwise,
767    an error is raised.  */
768 void
769 print_thread_info (struct ui_out *uiout, int requested_thread, int pid)
770 {
771   struct thread_info *tp;
772   ptid_t current_ptid;
773   struct cleanup *old_chain;
774   char *extra_info, *name, *target_id;
775   int current_thread = -1;
776
777   update_thread_list ();
778   current_ptid = inferior_ptid;
779
780   /* We'll be switching threads temporarily.  */
781   old_chain = make_cleanup_restore_current_thread ();
782
783   /* For backward compatibility, we make a list for MI.  A table is
784      preferable for the CLI, though, because it shows table
785      headers.  */
786   if (ui_out_is_mi_like_p (uiout))
787     make_cleanup_ui_out_list_begin_end (uiout, "threads");
788   else
789     {
790       int n_threads = 0;
791
792       for (tp = thread_list; tp; tp = tp->next)
793         {
794           if (requested_thread != -1 && tp->num != requested_thread)
795             continue;
796
797           if (pid != -1 && PIDGET (tp->ptid) != pid)
798             continue;
799
800           if (tp->state_ == THREAD_EXITED)
801             continue;
802
803           ++n_threads;
804         }
805
806       if (n_threads == 0)
807         {
808           if (requested_thread == -1)
809             ui_out_message (uiout, 0, _("No threads.\n"));
810           else
811             ui_out_message (uiout, 0, _("No thread %d.\n"), requested_thread);
812           do_cleanups (old_chain);
813           return;
814         }
815
816       make_cleanup_ui_out_table_begin_end (uiout, 4, n_threads, "threads");
817
818       ui_out_table_header (uiout, 1, ui_left, "current", "");
819       ui_out_table_header (uiout, 4, ui_left, "id", "Id");
820       ui_out_table_header (uiout, 17, ui_left, "target-id", "Target Id");
821       ui_out_table_header (uiout, 1, ui_left, "frame", "Frame");
822       ui_out_table_body (uiout);
823     }
824
825   for (tp = thread_list; tp; tp = tp->next)
826     {
827       struct cleanup *chain2;
828       int core;
829
830       if (requested_thread != -1 && tp->num != requested_thread)
831         continue;
832
833       if (pid != -1 && PIDGET (tp->ptid) != pid)
834         {
835           if (requested_thread != -1)
836             error (_("Requested thread not found in requested process"));
837           continue;
838         }
839
840       if (ptid_equal (tp->ptid, current_ptid))
841         current_thread = tp->num;
842
843       if (tp->state_ == THREAD_EXITED)
844         continue;
845
846       chain2 = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
847
848       if (ui_out_is_mi_like_p (uiout))
849         {
850           /* Compatibility.  */
851           if (ptid_equal (tp->ptid, current_ptid))
852             ui_out_text (uiout, "* ");
853           else
854             ui_out_text (uiout, "  ");
855         }
856       else
857         {
858           if (ptid_equal (tp->ptid, current_ptid))
859             ui_out_field_string (uiout, "current", "*");
860           else
861             ui_out_field_skip (uiout, "current");
862         }
863
864       ui_out_field_int (uiout, "id", tp->num);
865
866       /* For the CLI, we stuff everything into the target-id field.
867          This is a gross hack to make the output come out looking
868          correct.  The underlying problem here is that ui-out has no
869          way to specify that a field's space allocation should be
870          shared by several fields.  For MI, we do the right thing
871          instead.  */
872
873       target_id = target_pid_to_str (tp->ptid);
874       extra_info = target_extra_thread_info (tp);
875       name = tp->name ? tp->name : target_thread_name (tp);
876
877       if (ui_out_is_mi_like_p (uiout))
878         {
879           ui_out_field_string (uiout, "target-id", target_id);
880           if (extra_info)
881             ui_out_field_string (uiout, "details", extra_info);
882           if (name)
883             ui_out_field_string (uiout, "name", name);
884         }
885       else
886         {
887           struct cleanup *str_cleanup;
888           char *contents;
889
890           if (extra_info && name)
891             contents = xstrprintf ("%s \"%s\" (%s)", target_id,
892                                    name, extra_info);
893           else if (extra_info)
894             contents = xstrprintf ("%s (%s)", target_id, extra_info);
895           else if (name)
896             contents = xstrprintf ("%s \"%s\"", target_id, name);
897           else
898             contents = xstrdup (target_id);
899           str_cleanup = make_cleanup (xfree, contents);
900
901           ui_out_field_string (uiout, "target-id", contents);
902           do_cleanups (str_cleanup);
903         }
904
905       if (tp->state_ == THREAD_RUNNING)
906         ui_out_text (uiout, "(running)\n");
907       else
908         {
909           /* The switch below puts us at the top of the stack (leaf
910              frame).  */
911           switch_to_thread (tp->ptid);
912           print_stack_frame (get_selected_frame (NULL),
913                              /* For MI output, print frame level.  */
914                              ui_out_is_mi_like_p (uiout),
915                              LOCATION);
916         }
917
918       if (ui_out_is_mi_like_p (uiout))
919         {
920           char *state = "stopped";
921
922           if (tp->state_ == THREAD_RUNNING)
923             state = "running";
924           ui_out_field_string (uiout, "state", state);
925         }
926
927       core = target_core_of_thread (tp->ptid);
928       if (ui_out_is_mi_like_p (uiout) && core != -1)
929         ui_out_field_int (uiout, "core", core);
930
931       do_cleanups (chain2);
932     }
933
934   /* Restores the current thread and the frame selected before
935      the "info threads" command.  */
936   do_cleanups (old_chain);
937
938   if (pid == -1 && requested_thread == -1)
939     {
940       gdb_assert (current_thread != -1
941                   || !thread_list
942                   || ptid_equal (inferior_ptid, null_ptid));
943       if (current_thread != -1 && ui_out_is_mi_like_p (uiout))
944         ui_out_field_int (uiout, "current-thread-id", current_thread);
945
946       if (current_thread != -1 && is_exited (current_ptid))
947         ui_out_message (uiout, 0, "\n\
948 The current thread <Thread ID %d> has terminated.  See `help thread'.\n",
949                         current_thread);
950       else if (thread_list
951                && current_thread == -1
952                && ptid_equal (current_ptid, null_ptid))
953         ui_out_message (uiout, 0, "\n\
954 No selected thread.  See `help thread'.\n");
955     }
956 }
957
958 /* Print information about currently known threads 
959
960    Optional ARG is a thread id, or list of thread ids.
961
962    Note: this has the drawback that it _really_ switches
963          threads, which frees the frame cache.  A no-side
964          effects info-threads command would be nicer.  */
965
966 static void
967 info_threads_command (char *arg, int from_tty)
968 {
969   int tid = -1;
970
971   if (arg == NULL || *arg == '\0')
972     {
973       print_thread_info (uiout, -1, -1);
974       return;
975     }
976
977   while (arg != NULL && *arg != '\0')
978     {
979       int tmp_tid = strtol (arg, &arg, 0);
980       unsigned int highrange;
981
982       if (tmp_tid <= 0)
983         error ("invalid thread id %d\n", tmp_tid);
984
985       tid = tmp_tid;
986       print_thread_info (uiout, tid, -1);
987
988       while (*arg == ' ' || *arg == '\t')
989         ++arg;
990
991       if (*arg == '-')
992         {
993           /* Do a range of threads.  Must be in ascending order.  */
994           ++arg;        /* Skip the hyphen.  */
995           highrange = strtoul (arg, &arg, 0);
996           if (highrange < tid)
997             error (_("inverted range"));
998
999           /* Do the threads in the range (first one already done).  */
1000           while (tid < highrange)
1001             {
1002               print_thread_info (uiout, ++tid, -1);
1003             }
1004         }
1005     }
1006 }
1007
1008 /* Switch from one thread to another.  */
1009
1010 void
1011 switch_to_thread (ptid_t ptid)
1012 {
1013   /* Switch the program space as well, if we can infer it from the now
1014      current thread.  Otherwise, it's up to the caller to select the
1015      space it wants.  */
1016   if (!ptid_equal (ptid, null_ptid))
1017     {
1018       struct inferior *inf;
1019
1020       inf = find_inferior_pid (ptid_get_pid (ptid));
1021       gdb_assert (inf != NULL);
1022       set_current_program_space (inf->pspace);
1023       set_current_inferior (inf);
1024     }
1025
1026   if (ptid_equal (ptid, inferior_ptid))
1027     return;
1028
1029   inferior_ptid = ptid;
1030   reinit_frame_cache ();
1031   registers_changed ();
1032
1033   /* We don't check for is_stopped, because we're called at times
1034      while in the TARGET_RUNNING state, e.g., while handling an
1035      internal event.  */
1036   if (!ptid_equal (inferior_ptid, null_ptid)
1037       && !is_exited (ptid)
1038       && !is_executing (ptid))
1039     stop_pc = regcache_read_pc (get_thread_regcache (ptid));
1040   else
1041     stop_pc = ~(CORE_ADDR) 0;
1042 }
1043
1044 static void
1045 restore_current_thread (ptid_t ptid)
1046 {
1047   switch_to_thread (ptid);
1048 }
1049
1050 static void
1051 restore_selected_frame (struct frame_id a_frame_id, int frame_level)
1052 {
1053   struct frame_info *frame = NULL;
1054   int count;
1055
1056   gdb_assert (frame_level >= 0);
1057
1058   /* Restore by level first, check if the frame id is the same as
1059      expected.  If that fails, try restoring by frame id.  If that
1060      fails, nothing to do, just warn the user.  */
1061
1062   count = frame_level;
1063   frame = find_relative_frame (get_current_frame (), &count);
1064   if (count == 0
1065       && frame != NULL
1066       /* The frame ids must match - either both valid or both outer_frame_id.
1067          The latter case is not failsafe, but since it's highly unlikely
1068          the search by level finds the wrong frame, it's 99.9(9)% of
1069          the time (for all practical purposes) safe.  */
1070       && frame_id_eq (get_frame_id (frame), a_frame_id))
1071     {
1072       /* Cool, all is fine.  */
1073       select_frame (frame);
1074       return;
1075     }
1076
1077   frame = frame_find_by_id (a_frame_id);
1078   if (frame != NULL)
1079     {
1080       /* Cool, refound it.  */
1081       select_frame (frame);
1082       return;
1083     }
1084
1085   /* Nothing else to do, the frame layout really changed.  Select the
1086      innermost stack frame.  */
1087   select_frame (get_current_frame ());
1088
1089   /* Warn the user.  */
1090   if (frame_level > 0 && !ui_out_is_mi_like_p (uiout))
1091     {
1092       warning (_("Couldn't restore frame #%d in "
1093                  "current thread, at reparsed frame #0\n"),
1094                frame_level);
1095       /* For MI, we should probably have a notification about
1096          current frame change.  But this error is not very
1097          likely, so don't bother for now.  */
1098       print_stack_frame (get_selected_frame (NULL), 1, SRC_LINE);
1099     }
1100 }
1101
1102 struct current_thread_cleanup
1103 {
1104   ptid_t inferior_ptid;
1105   struct frame_id selected_frame_id;
1106   int selected_frame_level;
1107   int was_stopped;
1108   int inf_id;
1109 };
1110
1111 static void
1112 do_restore_current_thread_cleanup (void *arg)
1113 {
1114   struct thread_info *tp;
1115   struct current_thread_cleanup *old = arg;
1116
1117   tp = find_thread_ptid (old->inferior_ptid);
1118
1119   /* If the previously selected thread belonged to a process that has
1120      in the mean time been deleted (due to normal exit, detach, etc.),
1121      then don't revert back to it, but instead simply drop back to no
1122      thread selected.  */
1123   if (tp
1124       && find_inferior_pid (ptid_get_pid (tp->ptid)) != NULL)
1125     restore_current_thread (old->inferior_ptid);
1126   else
1127     {
1128       restore_current_thread (null_ptid);
1129       set_current_inferior (find_inferior_id (old->inf_id));
1130     }
1131
1132   /* The running state of the originally selected thread may have
1133      changed, so we have to recheck it here.  */
1134   if (!ptid_equal (inferior_ptid, null_ptid)
1135       && old->was_stopped
1136       && is_stopped (inferior_ptid)
1137       && target_has_registers
1138       && target_has_stack
1139       && target_has_memory)
1140     restore_selected_frame (old->selected_frame_id,
1141                             old->selected_frame_level);
1142 }
1143
1144 static void
1145 restore_current_thread_cleanup_dtor (void *arg)
1146 {
1147   struct current_thread_cleanup *old = arg;
1148   struct thread_info *tp;
1149
1150   tp = find_thread_ptid (old->inferior_ptid);
1151   if (tp)
1152     tp->refcount--;
1153   xfree (old);
1154 }
1155
1156 struct cleanup *
1157 make_cleanup_restore_current_thread (void)
1158 {
1159   struct thread_info *tp;
1160   struct frame_info *frame;
1161   struct current_thread_cleanup *old;
1162
1163   old = xmalloc (sizeof (struct current_thread_cleanup));
1164   old->inferior_ptid = inferior_ptid;
1165   old->inf_id = current_inferior ()->num;
1166
1167   if (!ptid_equal (inferior_ptid, null_ptid))
1168     {
1169       old->was_stopped = is_stopped (inferior_ptid);
1170       if (old->was_stopped
1171           && target_has_registers
1172           && target_has_stack
1173           && target_has_memory)
1174         frame = get_selected_frame (NULL);
1175       else
1176         frame = NULL;
1177
1178       old->selected_frame_id = get_frame_id (frame);
1179       old->selected_frame_level = frame_relative_level (frame);
1180
1181       tp = find_thread_ptid (inferior_ptid);
1182       if (tp)
1183         tp->refcount++;
1184     }
1185
1186   return make_cleanup_dtor (do_restore_current_thread_cleanup, old,
1187                             restore_current_thread_cleanup_dtor);
1188 }
1189
1190 /* Apply a GDB command to a list of threads.  List syntax is a whitespace
1191    seperated list of numbers, or ranges, or the keyword `all'.  Ranges consist
1192    of two numbers seperated by a hyphen.  Examples:
1193
1194    thread apply 1 2 7 4 backtrace       Apply backtrace cmd to threads 1,2,7,4
1195    thread apply 2-7 9 p foo(1)  Apply p foo(1) cmd to threads 2->7 & 9
1196    thread apply all p x/i $pc   Apply x/i $pc cmd to all threads.  */
1197
1198 static void
1199 thread_apply_all_command (char *cmd, int from_tty)
1200 {
1201   struct thread_info *tp;
1202   struct cleanup *old_chain;
1203   char *saved_cmd;
1204
1205   if (cmd == NULL || *cmd == '\000')
1206     error (_("Please specify a command following the thread ID list"));
1207
1208   update_thread_list ();
1209
1210   old_chain = make_cleanup_restore_current_thread ();
1211
1212   /* Save a copy of the command in case it is clobbered by
1213      execute_command.  */
1214   saved_cmd = xstrdup (cmd);
1215   make_cleanup (xfree, saved_cmd);
1216   for (tp = thread_list; tp; tp = tp->next)
1217     if (thread_alive (tp))
1218       {
1219         switch_to_thread (tp->ptid);
1220
1221         printf_filtered (_("\nThread %d (%s):\n"),
1222                          tp->num, target_pid_to_str (inferior_ptid));
1223         execute_command (cmd, from_tty);
1224         strcpy (cmd, saved_cmd);        /* Restore exact command used
1225                                            previously.  */
1226       }
1227
1228   do_cleanups (old_chain);
1229 }
1230
1231 static void
1232 thread_apply_command (char *tidlist, int from_tty)
1233 {
1234   char *cmd;
1235   char *p;
1236   struct cleanup *old_chain;
1237   char *saved_cmd;
1238
1239   if (tidlist == NULL || *tidlist == '\000')
1240     error (_("Please specify a thread ID list"));
1241
1242   for (cmd = tidlist; *cmd != '\000' && !isalpha (*cmd); cmd++);
1243
1244   if (*cmd == '\000')
1245     error (_("Please specify a command following the thread ID list"));
1246
1247   /* Save a copy of the command in case it is clobbered by
1248      execute_command.  */
1249   saved_cmd = xstrdup (cmd);
1250   old_chain = make_cleanup (xfree, saved_cmd);
1251   while (tidlist < cmd)
1252     {
1253       struct thread_info *tp;
1254       int start, end;
1255
1256       start = strtol (tidlist, &p, 10);
1257       if (p == tidlist)
1258         error (_("Error parsing %s"), tidlist);
1259       tidlist = p;
1260
1261       while (*tidlist == ' ' || *tidlist == '\t')
1262         tidlist++;
1263
1264       if (*tidlist == '-')      /* Got a range of IDs?  */
1265         {
1266           tidlist++;            /* Skip the - */
1267           end = strtol (tidlist, &p, 10);
1268           if (p == tidlist)
1269             error (_("Error parsing %s"), tidlist);
1270           tidlist = p;
1271
1272           while (*tidlist == ' ' || *tidlist == '\t')
1273             tidlist++;
1274         }
1275       else
1276         end = start;
1277
1278       make_cleanup_restore_current_thread ();
1279
1280       for (; start <= end; start++)
1281         {
1282           tp = find_thread_id (start);
1283
1284           if (!tp)
1285             warning (_("Unknown thread %d."), start);
1286           else if (!thread_alive (tp))
1287             warning (_("Thread %d has terminated."), start);
1288           else
1289             {
1290               switch_to_thread (tp->ptid);
1291
1292               printf_filtered (_("\nThread %d (%s):\n"), tp->num,
1293                                target_pid_to_str (inferior_ptid));
1294               execute_command (cmd, from_tty);
1295
1296               /* Restore exact command used previously.  */
1297               strcpy (cmd, saved_cmd);
1298             }
1299         }
1300     }
1301
1302   do_cleanups (old_chain);
1303 }
1304
1305 /* Switch to the specified thread.  Will dispatch off to thread_apply_command
1306    if prefix of arg is `apply'.  */
1307
1308 static void
1309 thread_command (char *tidstr, int from_tty)
1310 {
1311   if (!tidstr)
1312     {
1313       if (ptid_equal (inferior_ptid, null_ptid))
1314         error (_("No thread selected"));
1315
1316       if (target_has_stack)
1317         {
1318           if (is_exited (inferior_ptid))
1319             printf_filtered (_("[Current thread is %d (%s) (exited)]\n"),
1320                              pid_to_thread_id (inferior_ptid),
1321                              target_pid_to_str (inferior_ptid));
1322           else
1323             printf_filtered (_("[Current thread is %d (%s)]\n"),
1324                              pid_to_thread_id (inferior_ptid),
1325                              target_pid_to_str (inferior_ptid));
1326         }
1327       else
1328         error (_("No stack."));
1329       return;
1330     }
1331
1332   gdb_thread_select (uiout, tidstr, NULL);
1333 }
1334
1335 /* Implementation of `thread name'.  */
1336
1337 static void
1338 thread_name_command (char *arg, int from_tty)
1339 {
1340   struct thread_info *info;
1341
1342   if (ptid_equal (inferior_ptid, null_ptid))
1343     error (_("No thread selected"));
1344
1345   while (arg && isspace (*arg))
1346     ++arg;
1347
1348   info = inferior_thread ();
1349   xfree (info->name);
1350   info->name = arg ? xstrdup (arg) : NULL;
1351 }
1352
1353 /* Find thread ids with a name, target pid, or extra info matching ARG.  */
1354
1355 static void
1356 thread_find_command (char *arg, int from_tty)
1357 {
1358   struct thread_info *tp;
1359   char *tmp;
1360   unsigned long match = 0;
1361
1362   if (arg == NULL || *arg == '\0')
1363     error (_("Command requires an argument."));
1364
1365   tmp = re_comp (arg);
1366   if (tmp != 0)
1367     error (_("Invalid regexp (%s): %s"), tmp, arg);
1368
1369   update_thread_list ();
1370   for (tp = thread_list; tp; tp = tp->next)
1371     {
1372       if (tp->name != NULL && re_exec (tp->name))
1373         {
1374           printf_filtered (_("Thread %d has name '%s'\n"),
1375                            tp->num, tp->name);
1376           match++;
1377         }
1378
1379       tmp = target_thread_name (tp);
1380       if (tmp != NULL && re_exec (tmp))
1381         {
1382           printf_filtered (_("Thread %d has target name '%s'\n"),
1383                            tp->num, tmp);
1384           match++;
1385         }
1386
1387       tmp = target_pid_to_str (tp->ptid);
1388       if (tmp != NULL && re_exec (tmp))
1389         {
1390           printf_filtered (_("Thread %d has target id '%s'\n"),
1391                            tp->num, tmp);
1392           match++;
1393         }
1394
1395       tmp = target_extra_thread_info (tp);
1396       if (tmp != NULL && re_exec (tmp))
1397         {
1398           printf_filtered (_("Thread %d has extra info '%s'\n"),
1399                            tp->num, tmp);
1400           match++;
1401         }
1402     }
1403   if (!match)
1404     printf_filtered (_("No threads match '%s'\n"), arg);
1405 }
1406
1407 /* Print notices when new threads are attached and detached.  */
1408 int print_thread_events = 1;
1409 static void
1410 show_print_thread_events (struct ui_file *file, int from_tty,
1411                           struct cmd_list_element *c, const char *value)
1412 {
1413   fprintf_filtered (file,
1414                     _("Printing of thread events is %s.\n"),
1415                     value);
1416 }
1417
1418 static int
1419 do_captured_thread_select (struct ui_out *uiout, void *tidstr)
1420 {
1421   int num;
1422   struct thread_info *tp;
1423
1424   num = value_as_long (parse_and_eval (tidstr));
1425
1426   tp = find_thread_id (num);
1427
1428   if (!tp)
1429     error (_("Thread ID %d not known."), num);
1430
1431   if (!thread_alive (tp))
1432     error (_("Thread ID %d has terminated."), num);
1433
1434   switch_to_thread (tp->ptid);
1435
1436   annotate_thread_changed ();
1437
1438   ui_out_text (uiout, "[Switching to thread ");
1439   ui_out_field_int (uiout, "new-thread-id", pid_to_thread_id (inferior_ptid));
1440   ui_out_text (uiout, " (");
1441   ui_out_text (uiout, target_pid_to_str (inferior_ptid));
1442   ui_out_text (uiout, ")]");
1443
1444   /* Note that we can't reach this with an exited thread, due to the
1445      thread_alive check above.  */
1446   if (tp->state_ == THREAD_RUNNING)
1447     ui_out_text (uiout, "(running)\n");
1448   else
1449     {
1450       ui_out_text (uiout, "\n");
1451       print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
1452     }
1453
1454   /* Since the current thread may have changed, see if there is any
1455      exited thread we can now delete.  */
1456   prune_threads ();
1457
1458   return GDB_RC_OK;
1459 }
1460
1461 enum gdb_rc
1462 gdb_thread_select (struct ui_out *uiout, char *tidstr, char **error_message)
1463 {
1464   if (catch_exceptions_with_msg (uiout, do_captured_thread_select, tidstr,
1465                                  error_message, RETURN_MASK_ALL) < 0)
1466     return GDB_RC_FAIL;
1467   return GDB_RC_OK;
1468 }
1469
1470 void
1471 update_thread_list (void)
1472 {
1473   prune_threads ();
1474   target_find_new_threads ();
1475 }
1476
1477 /* Return a new value for the selected thread's id.  Return a value of 0 if
1478    no thread is selected, or no threads exist.  */
1479
1480 static struct value *
1481 thread_id_make_value (struct gdbarch *gdbarch, struct internalvar *var)
1482 {
1483   struct thread_info *tp = find_thread_ptid (inferior_ptid);
1484
1485   return value_from_longest (builtin_type (gdbarch)->builtin_int,
1486                              (tp ? tp->num : 0));
1487 }
1488
1489 /* Commands with a prefix of `thread'.  */
1490 struct cmd_list_element *thread_cmd_list = NULL;
1491
1492 void
1493 _initialize_thread (void)
1494 {
1495   static struct cmd_list_element *thread_apply_list = NULL;
1496
1497   add_info ("threads", info_threads_command, 
1498             _("Display currently known threads.\n\
1499 Usage: info threads [ID]...\n\
1500 Optional arguments are thread IDs with spaces between.\n\
1501 If no arguments, all threads are displayed."));
1502
1503   add_prefix_cmd ("thread", class_run, thread_command, _("\
1504 Use this command to switch between threads.\n\
1505 The new thread ID must be currently known."),
1506                   &thread_cmd_list, "thread ", 1, &cmdlist);
1507
1508   add_prefix_cmd ("apply", class_run, thread_apply_command,
1509                   _("Apply a command to a list of threads."),
1510                   &thread_apply_list, "thread apply ", 1, &thread_cmd_list);
1511
1512   add_cmd ("all", class_run, thread_apply_all_command,
1513            _("Apply a command to all threads."), &thread_apply_list);
1514
1515   add_cmd ("name", class_run, thread_name_command,
1516            _("Set the current thread's name.\n\
1517 Usage: thread name [NAME]\n\
1518 If NAME is not given, then any existing name is removed."), &thread_cmd_list);
1519
1520   add_cmd ("find", class_run, thread_find_command, _("\
1521 Find threads that match a regular expression.\n\
1522 Usage: thread find REGEXP\n\
1523 Will display thread ids whose name, target ID, or extra info matches REGEXP."),
1524            &thread_cmd_list);
1525
1526   if (!xdb_commands)
1527     add_com_alias ("t", "thread", class_run, 1);
1528
1529   add_setshow_boolean_cmd ("thread-events", no_class,
1530          &print_thread_events, _("\
1531 Set printing of thread events (such as thread start and exit)."), _("\
1532 Show printing of thread events (such as thread start and exit)."), NULL,
1533          NULL,
1534          show_print_thread_events,
1535          &setprintlist, &showprintlist);
1536
1537   create_internalvar_type_lazy ("_thread", thread_id_make_value);
1538 }