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