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