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