* ada-tasks.c (task_states,long_task_states): Add new states
[external/binutils.git] / gdb / ada-tasks.c
1 /* Copyright (C) 1992, 1993, 1994, 1997, 1998, 1999, 2000, 2003, 2004, 2005,
2    2007, 2008, 2009 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include "defs.h"
20 #include "observer.h"
21 #include "gdbcmd.h"
22 #include "target.h"
23 #include "ada-lang.h"
24 #include "gdbcore.h"
25 #include "inferior.h"
26 #include "gdbthread.h"
27
28 /* The name of the array in the GNAT runtime where the Ada Task Control
29    Block of each task is stored.  */
30 #define KNOWN_TASKS_NAME "system__tasking__debug__known_tasks"
31
32 /* The maximum number of tasks known to the Ada runtime */
33 static const int MAX_NUMBER_OF_KNOWN_TASKS = 1000;
34
35 enum task_states
36 {
37   Unactivated,
38   Runnable,
39   Terminated,
40   Activator_Sleep,
41   Acceptor_Sleep,
42   Entry_Caller_Sleep,
43   Async_Select_Sleep,
44   Delay_Sleep,
45   Master_Completion_Sleep,
46   Master_Phase_2_Sleep,
47   Interrupt_Server_Idle_Sleep,
48   Interrupt_Server_Blocked_Interrupt_Sleep,
49   Timer_Server_Sleep,
50   AST_Server_Sleep,
51   Asynchronous_Hold,
52   Interrupt_Server_Blocked_On_Event_Flag,
53   Activating,
54   Acceptor_Delay_Sleep
55 };
56
57 /* A short description corresponding to each possible task state.  */
58 static const char *task_states[] = {
59   N_("Unactivated"),
60   N_("Runnable"),
61   N_("Terminated"),
62   N_("Child Activation Wait"),
63   N_("Accept or Select Term"),
64   N_("Waiting on entry call"),
65   N_("Async Select Wait"),
66   N_("Delay Sleep"),
67   N_("Child Termination Wait"),
68   N_("Wait Child in Term Alt"),
69   "",
70   "",
71   "",
72   "",
73   N_("Asynchronous Hold"),
74   "",
75   N_("Activating"),
76   N_("Selective Wait")
77 };
78
79 /* A longer description corresponding to each possible task state.  */
80 static const char *long_task_states[] = {
81   N_("Unactivated"),
82   N_("Runnable"),
83   N_("Terminated"),
84   N_("Waiting for child activation"),
85   N_("Blocked in accept or select with terminate"),
86   N_("Waiting on entry call"),
87   N_("Asynchronous Selective Wait"),
88   N_("Delay Sleep"),
89   N_("Waiting for children termination"),
90   N_("Waiting for children in terminate alternative"),
91   "",
92   "",
93   "",
94   "",
95   N_("Asynchronous Hold"),
96   "",
97   N_("Activating"),
98   N_("Blocked in selective wait statement")
99 };
100
101 /* The index of certain important fields in the Ada Task Control Block
102    record and sub-records.  */
103
104 struct tcb_fieldnos
105 {
106   /* Fields in record Ada_Task_Control_Block.  */
107   int common;
108   int entry_calls;
109   int atc_nesting_level;
110
111   /* Fields in record Common_ATCB.  */
112   int state;
113   int parent;
114   int priority;
115   int image;
116   int image_len;     /* This field may be missing.  */
117   int call;
118   int ll;
119
120   /* Fields in Task_Primitives.Private_Data.  */
121   int ll_thread;
122   int ll_lwp;        /* This field may be missing.  */
123
124   /* Fields in Common_ATCB.Call.all.  */
125   int call_self;
126 };
127
128 /* The type description for the ATCB record and subrecords, and
129    the associated tcb_fieldnos. For efficiency reasons, these are made
130    static globals so that we can compute them only once the first time
131    and reuse them later.  Set to NULL if the types haven't been computed
132    yet, or if they may be obsolete (for instance after having loaded
133    a new binary).  */
134
135 static struct type *atcb_type = NULL;
136 static struct type *atcb_common_type = NULL;
137 static struct type *atcb_ll_type = NULL;
138 static struct type *atcb_call_type = NULL;
139 static struct tcb_fieldnos fieldno;
140
141 /* Set to 1 when the cached address of System.Tasking.Debug.Known_Tasks
142    might be stale and so needs to be recomputed.  */
143 static int ada_tasks_check_symbol_table = 1;
144
145 /* The list of Ada tasks.
146  
147    Note: To each task we associate a number that the user can use to
148    reference it - this number is printed beside each task in the tasks
149    info listing displayed by "info tasks".  This number is equal to
150    its index in the vector + 1.  Reciprocally, to compute the index
151    of a task in the vector, we need to substract 1 from its number.  */
152 typedef struct ada_task_info ada_task_info_s;
153 DEF_VEC_O(ada_task_info_s);
154 static VEC(ada_task_info_s) *task_list = NULL;
155
156 /* When non-zero, this flag indicates that the current task_list
157    is obsolete, and should be recomputed before it is accessed.  */
158 static int stale_task_list_p = 1;
159
160 /* Return the task number of the task whose ptid is PTID, or zero
161    if the task could not be found.  */
162
163 static int
164 ada_get_task_number (ptid_t ptid)
165 {
166   int i;
167
168   for (i=0; i < VEC_length (ada_task_info_s, task_list); i++)
169     if (ptid_equal (VEC_index (ada_task_info_s, task_list, i)->ptid, ptid))
170       return i + 1;
171
172   return 0;  /* No matching task found.  */
173 }
174
175 /* Return the task number of the task that matches TASK_ID, or zero
176    if the task could not be found.  */
177  
178 static int
179 get_task_number_from_id (CORE_ADDR task_id)
180 {
181   int i;
182
183   for (i = 0; i < VEC_length (ada_task_info_s, task_list); i++)
184     {
185       struct ada_task_info *task_info =
186         VEC_index (ada_task_info_s, task_list, i);
187
188       if (task_info->task_id == task_id)
189         return i + 1;
190     }
191
192   /* Task not found.  Return 0.  */
193   return 0;
194 }
195
196 /* Return non-zero if TASK_NUM is a valid task number.  */
197
198 int
199 valid_task_id (int task_num)
200 {
201   return (task_num > 0
202           && task_num <= VEC_length (ada_task_info_s, task_list));
203 }
204
205 /* Extract the contents of the value as a string whose length is LENGTH,
206    and store the result in DEST.  */
207
208 static void
209 value_as_string (char *dest, struct value *val, int length)
210 {
211   memcpy (dest, value_contents (val), length);
212   dest[length] = '\0';
213 }
214
215 /* Extract the string image from the fat string corresponding to VAL,
216    and store it in DEST.  If the string length is greater than MAX_LEN,
217    then truncate the result to the first MAX_LEN characters of the fat
218    string.  */
219
220 static void
221 read_fat_string_value (char *dest, struct value *val, int max_len)
222 {
223   struct value *array_val;
224   struct value *bounds_val;
225   int len;
226
227   /* The following variables are made static to avoid recomputing them
228      each time this function is called.  */
229   static int initialize_fieldnos = 1;
230   static int array_fieldno;
231   static int bounds_fieldno;
232   static int upper_bound_fieldno;
233
234   /* Get the index of the fields that we will need to read in order
235      to extract the string from the fat string.  */
236   if (initialize_fieldnos)
237     {
238       struct type *type = value_type (val);
239       struct type *bounds_type;
240
241       array_fieldno = ada_get_field_index (type, "P_ARRAY", 0);
242       bounds_fieldno = ada_get_field_index (type, "P_BOUNDS", 0);
243
244       bounds_type = TYPE_FIELD_TYPE (type, bounds_fieldno);
245       if (TYPE_CODE (bounds_type) == TYPE_CODE_PTR)
246         bounds_type = TYPE_TARGET_TYPE (bounds_type);
247       if (TYPE_CODE (bounds_type) != TYPE_CODE_STRUCT)
248         error (_("Unknown task name format. Aborting"));
249       upper_bound_fieldno = ada_get_field_index (bounds_type, "UB0", 0);
250
251       initialize_fieldnos = 0;
252     }
253
254   /* Get the size of the task image by checking the value of the bounds.
255      The lower bound is always 1, so we only need to read the upper bound.  */
256   bounds_val = value_ind (value_field (val, bounds_fieldno));
257   len = value_as_long (value_field (bounds_val, upper_bound_fieldno));
258
259   /* Make sure that we do not read more than max_len characters...  */
260   if (len > max_len)
261     len = max_len;
262
263   /* Extract LEN characters from the fat string.  */
264   array_val = value_ind (value_field (val, array_fieldno));
265   read_memory (VALUE_ADDRESS (array_val), dest, len);
266
267   /* Add the NUL character to close the string.  */
268   dest[len] = '\0';
269 }
270
271 /* Return the address of the Known_Tasks array maintained in
272    the Ada Runtime.  Return NULL if the array could not be found,
273    meaning that the inferior program probably does not use tasking.
274
275    In order to provide a fast response time, this function caches
276    the Known_Tasks array address after the lookup during the first
277    call. Subsequent calls will simply return this cached address.  */
278
279 static CORE_ADDR
280 get_known_tasks_addr (void)
281 {
282   static CORE_ADDR known_tasks_addr = 0;
283
284   if (ada_tasks_check_symbol_table)
285     {
286       struct symbol *sym;
287       struct minimal_symbol *msym;
288
289       msym = lookup_minimal_symbol (KNOWN_TASKS_NAME, NULL, NULL);
290       if (msym != NULL)
291         known_tasks_addr = SYMBOL_VALUE_ADDRESS (msym);
292       else
293         {
294           if (target_lookup_symbol (KNOWN_TASKS_NAME, &known_tasks_addr) != 0)
295             return 0;
296         }
297
298       /* FIXME: brobecker 2003-03-05: Here would be a much better place
299          to attach the ada-tasks observers, instead of doing this
300          unconditionaly in _initialize_tasks. This would avoid an
301          unecessary notification when the inferior does not use tasking
302          or as long as the user does not use the ada-tasks commands.
303          Unfortunately, this is not possible for the moment: the current
304          code resets ada__tasks_check_symbol_table back to 1 whenever
305          symbols for a new program are being loaded. If we place the
306          observers intialization here, we will end up adding new observers
307          everytime we do the check for Ada tasking-related symbols
308          above. This would currently have benign effects, but is still
309          undesirable. The cleanest approach is probably to create a new
310          observer to notify us when the user is debugging a new program.
311          We would then reset ada__tasks_check_symbol_table back to 1
312          during the notification, but also detach all observers.
313          BTW: observers are probably not reentrant, so detaching during
314          a notification may not be the safest thing to do... Sigh...
315          But creating the new observer would be a good idea in any case,
316          since this allow us to make ada__tasks_check_symbol_table
317          static, which is a good bonus.  */
318       ada_tasks_check_symbol_table = 0;
319     }
320
321   return known_tasks_addr;
322 }
323
324 /* Get from the debugging information the type description of all types
325    related to the Ada Task Control Block that will be needed in order to
326    read the list of known tasks in the Ada runtime.  Also return the
327    associated ATCB_FIELDNOS.
328
329    Error handling:  Any data missing from the debugging info will cause
330    an error to be raised, and none of the return values to be set.
331    Users of this function can depend on the fact that all or none of the
332    return values will be set.  */
333
334 static void
335 get_tcb_types_info (struct type **atcb_type,
336                     struct type **atcb_common_type,
337                     struct type **atcb_ll_type,
338                     struct type **atcb_call_type,
339                     struct tcb_fieldnos *atcb_fieldnos)
340 {
341   struct type *type;
342   struct type *common_type;
343   struct type *ll_type;
344   struct type *call_type;
345   struct tcb_fieldnos fieldnos;
346
347   const char *atcb_name = "system__tasking__ada_task_control_block___XVE";
348   const char *atcb_name_fixed = "system__tasking__ada_task_control_block";
349   const char *common_atcb_name = "system__tasking__common_atcb";
350   const char *private_data_name = "system__task_primitives__private_data";
351   const char *entry_call_record_name = "system__tasking__entry_call_record";
352
353   struct symbol *atcb_sym =
354     lookup_symbol (atcb_name, NULL, VAR_DOMAIN, NULL);
355   const struct symbol *common_atcb_sym =
356     lookup_symbol (common_atcb_name, NULL, VAR_DOMAIN, NULL);
357   const struct symbol *private_data_sym =
358     lookup_symbol (private_data_name, NULL, VAR_DOMAIN, NULL);
359   const struct symbol *entry_call_record_sym =
360     lookup_symbol (entry_call_record_name, NULL, VAR_DOMAIN, NULL);
361
362   if (atcb_sym == NULL || atcb_sym->type == NULL)
363     {
364       /* In Ravenscar run-time libs, the  ATCB does not have a dynamic
365          size, so the symbol name differs.  */
366       atcb_sym = lookup_symbol (atcb_name_fixed, NULL, VAR_DOMAIN, NULL);
367
368       if (atcb_sym == NULL || atcb_sym->type == NULL)
369         error (_("Cannot find Ada_Task_Control_Block type. Aborting"));
370
371       type = atcb_sym->type;
372     }
373   else
374     {
375       /* Get a static representation of the type record
376          Ada_Task_Control_Block.  */
377       type = atcb_sym->type;
378       type = ada_template_to_fixed_record_type_1 (type, NULL, 0, NULL, 0);
379     }
380
381   if (common_atcb_sym == NULL || common_atcb_sym->type == NULL)
382     error (_("Cannot find Common_ATCB type. Aborting"));
383   if (private_data_sym == NULL || private_data_sym->type == NULL)
384     error (_("Cannot find Private_Data type. Aborting"));
385   if (entry_call_record_sym == NULL || entry_call_record_sym->type == NULL)
386     error (_("Cannot find Entry_Call_Record type. Aborting"));
387
388   /* Get the type for Ada_Task_Control_Block.Common.  */
389   common_type = common_atcb_sym->type;
390
391   /* Get the type for Ada_Task_Control_Bloc.Common.Call.LL.  */
392   ll_type = private_data_sym->type;
393
394   /* Get the type for Common_ATCB.Call.all.  */
395   call_type = entry_call_record_sym->type;
396
397   /* Get the field indices.  */
398   fieldnos.common = ada_get_field_index (type, "common", 0);
399   fieldnos.entry_calls = ada_get_field_index (type, "entry_calls", 1);
400   fieldnos.atc_nesting_level =
401     ada_get_field_index (type, "atc_nesting_level", 1);
402   fieldnos.state = ada_get_field_index (common_type, "state", 0);
403   fieldnos.parent = ada_get_field_index (common_type, "parent", 1);
404   fieldnos.priority = ada_get_field_index (common_type, "base_priority", 0);
405   fieldnos.image = ada_get_field_index (common_type, "task_image", 1);
406   fieldnos.image_len = ada_get_field_index (common_type, "task_image_len", 1);
407   fieldnos.call = ada_get_field_index (common_type, "call", 1);
408   fieldnos.ll = ada_get_field_index (common_type, "ll", 0);
409   fieldnos.ll_thread = ada_get_field_index (ll_type, "thread", 0);
410   fieldnos.ll_lwp = ada_get_field_index (ll_type, "lwp", 1);
411   fieldnos.call_self = ada_get_field_index (call_type, "self", 0);
412
413   /* On certain platforms such as x86-windows, the "lwp" field has been
414      named "thread_id".  This field will likely be renamed in the future,
415      but we need to support both possibilities to avoid an unnecessary
416      dependency on a recent compiler.  We therefore try locating the
417      "thread_id" field in place of the "lwp" field if we did not find
418      the latter.  */
419   if (fieldnos.ll_lwp < 0)
420     fieldnos.ll_lwp = ada_get_field_index (ll_type, "thread_id", 1);
421
422   /* Set all the out parameters all at once, now that we are certain
423      that there are no potential error() anymore.  */
424   *atcb_type = type;
425   *atcb_common_type = common_type;
426   *atcb_ll_type = ll_type;
427   *atcb_call_type = call_type;
428   *atcb_fieldnos = fieldnos;
429 }
430
431 /* Build the PTID of the task from its COMMON_VALUE, which is the "Common"
432    component of its ATCB record.  This PTID needs to match the PTID used
433    by the thread layer.  */
434
435 static ptid_t
436 ptid_from_atcb_common (struct value *common_value)
437 {
438   long thread = 0;
439   CORE_ADDR lwp = 0;
440   struct value *ll_value;
441   ptid_t ptid;
442
443   ll_value = value_field (common_value, fieldno.ll);
444
445   if (fieldno.ll_lwp >= 0)
446     lwp = value_as_address (value_field (ll_value, fieldno.ll_lwp));
447   thread = value_as_long (value_field (ll_value, fieldno.ll_thread));
448
449   ptid = target_get_ada_task_ptid (lwp, thread);
450
451   return ptid;
452 }
453
454 /* Read the ATCB data of a given task given its TASK_ID (which is in practice
455    the address of its assocated ATCB record), and store the result inside
456    TASK_INFO.  */
457
458 static void
459 read_atcb (CORE_ADDR task_id, struct ada_task_info *task_info)
460 {
461   struct value *tcb_value;
462   struct value *common_value;
463   struct value *atc_nesting_level_value;
464   struct value *entry_calls_value;
465   struct value *entry_calls_value_element;
466   int called_task_fieldno = -1;
467   const char ravenscar_task_name[] = "Ravenscar task";
468
469   if (atcb_type == NULL)
470     get_tcb_types_info (&atcb_type, &atcb_common_type, &atcb_ll_type,
471                         &atcb_call_type, &fieldno);
472
473   tcb_value = value_from_contents_and_address (atcb_type, NULL, task_id);
474   common_value = value_field (tcb_value, fieldno.common);
475
476   /* Fill in the task_id.  */
477
478   task_info->task_id = task_id;
479
480   /* Compute the name of the task.
481
482      Depending on the GNAT version used, the task image is either a fat
483      string, or a thin array of characters.  Older versions of GNAT used
484      to use fat strings, and therefore did not need an extra field in
485      the ATCB to store the string length. For efficiency reasons, newer
486      versions of GNAT replaced the fat string by a static buffer, but this
487      also required the addition of a new field named "Image_Len" containing
488      the length of the task name. The method used to extract the task name
489      is selected depending on the existence of this field.
490
491      In some run-time libs (e.g. Ravenscar), the name is not in the ATCB;
492      we may want to get it from the first user frame of the stack. For now,
493      we just give a dummy name.  */
494
495   if (fieldno.image_len == -1)
496     {
497       if (fieldno.image >= 0)
498         read_fat_string_value (task_info->name,
499                                value_field (common_value, fieldno.image),
500                                sizeof (task_info->name) - 1);
501       else
502         strcpy (task_info->name, ravenscar_task_name);
503     }
504   else
505     {
506       int len = value_as_long (value_field (common_value, fieldno.image_len));
507
508       value_as_string (task_info->name,
509                        value_field (common_value, fieldno.image), len);
510     }
511
512   /* Compute the task state and priority.  */
513
514   task_info->state = value_as_long (value_field (common_value, fieldno.state));
515   task_info->priority =
516     value_as_long (value_field (common_value, fieldno.priority));
517
518   /* If the ATCB contains some information about the parent task,
519      then compute it as well.  Otherwise, zero.  */
520
521   if (fieldno.parent >= 0)
522     task_info->parent =
523       value_as_address (value_field (common_value, fieldno.parent));
524   else
525     task_info->parent = 0;
526   
527
528   /* If the ATCB contains some information about entry calls, then
529      compute the "called_task" as well.  Otherwise, zero.  */
530
531   if (fieldno.atc_nesting_level > 0 && fieldno.entry_calls > 0) 
532     {
533       /* Let My_ATCB be the Ada task control block of a task calling the
534          entry of another task; then the Task_Id of the called task is
535          in My_ATCB.Entry_Calls (My_ATCB.ATC_Nesting_Level).Called_Task.  */
536       atc_nesting_level_value = value_field (tcb_value,
537                                              fieldno.atc_nesting_level);
538       entry_calls_value =
539         ada_coerce_to_simple_array_ptr (value_field (tcb_value,
540                                                      fieldno.entry_calls));
541       entry_calls_value_element =
542         value_subscript (entry_calls_value, atc_nesting_level_value);
543       called_task_fieldno =
544         ada_get_field_index (value_type (entry_calls_value_element),
545                              "called_task", 0);
546       task_info->called_task =
547         value_as_address (value_field (entry_calls_value_element,
548                                        called_task_fieldno));
549     }
550   else
551     {
552       task_info->called_task = 0;
553     }
554
555   /* If the ATCB cotnains some information about RV callers,
556      then compute the "caller_task".  Otherwise, zero.  */
557
558   task_info->caller_task = 0;
559   if (fieldno.call >= 0)
560     {
561       /* Get the ID of the caller task from Common_ATCB.Call.all.Self.
562          If Common_ATCB.Call is null, then there is no caller.  */
563       const CORE_ADDR call =
564         value_as_address (value_field (common_value, fieldno.call));
565       struct value *call_val;
566
567       if (call != 0)
568         {
569           call_val =
570             value_from_contents_and_address (atcb_call_type, NULL, call);
571           task_info->caller_task =
572             value_as_address (value_field (call_val, fieldno.call_self));
573         }
574     }
575
576   /* And finally, compute the task ptid.  */
577
578   if (ada_task_is_alive (task_info))
579     task_info->ptid = ptid_from_atcb_common (common_value);
580   else
581     task_info->ptid = null_ptid;
582 }
583
584 /* Read the ATCB info of the given task (identified by TASK_ID), and
585    add the result to the TASK_LIST.  */
586
587 static void
588 add_ada_task (CORE_ADDR task_id)
589 {
590   struct ada_task_info task_info;
591
592   read_atcb (task_id, &task_info);
593   VEC_safe_push (ada_task_info_s, task_list, &task_info);
594 }
595
596 /* Read the Known_Tasks array from the inferior memory, and store
597    it in TASK_LIST.  Return non-zero upon success.  */
598
599 static int
600 read_known_tasks_array (void)
601 {
602   const int target_ptr_byte =
603     gdbarch_ptr_bit (current_gdbarch) / TARGET_CHAR_BIT;
604   const CORE_ADDR known_tasks_addr = get_known_tasks_addr ();
605   const int known_tasks_size = target_ptr_byte * MAX_NUMBER_OF_KNOWN_TASKS;
606   gdb_byte *known_tasks = alloca (known_tasks_size);
607   int i;
608
609   /* Step 1: Clear the current list, if necessary.  */
610   VEC_truncate (ada_task_info_s, task_list, 0);
611
612   /* If the application does not use task, then no more needs to be done.
613      It is important to have the task list cleared (see above) before we
614      return, as we don't want a stale task list to be used...  This can
615      happen for instance when debugging a non-multitasking program after
616      having debugged a multitasking one.  */
617   if (known_tasks_addr == 0)
618     return 0;
619
620   /* Step 2: Build a new list by reading the ATCBs from the Known_Tasks
621      array in the Ada runtime.  */
622   read_memory (known_tasks_addr, known_tasks, known_tasks_size);
623   for (i = 0; i < MAX_NUMBER_OF_KNOWN_TASKS; i++)
624     {
625       struct type *data_ptr_type =
626         builtin_type (current_gdbarch)->builtin_data_ptr;
627       CORE_ADDR task_id =
628         extract_typed_address (known_tasks + i * target_ptr_byte,
629                                data_ptr_type);
630
631       if (task_id != 0)
632         add_ada_task (task_id);
633     }
634
635   /* Step 3: Unset stale_task_list_p, to avoid re-reading the Known_Tasks
636      array unless needed.  Then report a success.  */
637   stale_task_list_p = 0;
638
639   return 1;
640 }
641
642 /* Builds the task_list by reading the Known_Tasks array from
643    the inferior.  Prints an appropriate message and returns non-zero
644    if it failed to build this list.  */
645
646 int
647 ada_build_task_list (int warn_if_null)
648 {
649   if (!target_has_stack)
650     error (_("Cannot inspect Ada tasks when program is not running"));
651
652   if (stale_task_list_p)
653     read_known_tasks_array ();
654
655   if (task_list == NULL)
656     {
657       if (warn_if_null)
658         printf_filtered (_("Your application does not use any Ada tasks.\n"));
659       return 0;
660     }
661
662   return 1;
663 }
664
665 /* Return non-zero iff the task STATE corresponds to a non-terminated
666    task state.  */
667
668 int
669 ada_task_is_alive (struct ada_task_info *task_info)
670 {
671   return (task_info->state != Terminated);
672 }
673
674 /* Print a one-line description of the task whose number is TASKNO.
675    The formatting should fit the "info tasks" array.  */
676
677 static void
678 short_task_info (int taskno)
679 {
680   const struct ada_task_info *const task_info =
681     VEC_index (ada_task_info_s, task_list, taskno - 1);
682   int active_task_p;
683
684   gdb_assert (task_info != NULL);
685
686   /* Print a star if this task is the current task (or the task currently
687      selected).  */
688
689   active_task_p = ptid_equal (task_info->ptid, inferior_ptid);
690   if (active_task_p)
691     printf_filtered ("*");
692   else
693     printf_filtered (" ");
694
695   /* Print the task number.  */
696   printf_filtered ("%3d", taskno);
697
698   /* Print the Task ID.  */
699   printf_filtered (" %9lx", (long) task_info->task_id);
700
701   /* Print the Task ID of the task parent.  */
702   printf_filtered (" %4d", get_task_number_from_id (task_info->parent));
703
704   /* Print the base priority of the task.  */
705   printf_filtered (" %3d", task_info->priority);
706
707   /* Print the task current state.  */
708   if (task_info->caller_task)
709     printf_filtered (_(" Accepting RV with %-4d"),
710                      get_task_number_from_id (task_info->caller_task));
711   else if (task_info->state == Entry_Caller_Sleep && task_info->called_task)
712     printf_filtered (_(" Waiting on RV with %-3d"),
713                      get_task_number_from_id (task_info->called_task));
714   else if (task_info->state == Runnable && active_task_p)
715     /* Replace "Runnable" by "Running" since this is the active task.  */
716     printf_filtered (" %-22s", _("Running"));
717   else
718     printf_filtered (" %-22s", _(task_states[task_info->state]));
719
720   /* Finally, print the task name.  */
721   if (task_info->name[0] != '\0')
722     printf_filtered (" %s\n", task_info->name);
723   else
724     printf_filtered (_(" <no name>\n"));
725 }
726
727 /* Print a list containing a short description of all Ada tasks.  */
728 /* FIXME: Shouldn't we be using ui_out??? */
729
730 static void
731 info_tasks (int from_tty)
732 {
733   int taskno;
734   const int nb_tasks = VEC_length (ada_task_info_s, task_list);
735
736   printf_filtered (_("  ID       TID P-ID Pri State                  Name\n"));
737   
738   for (taskno = 1; taskno <= nb_tasks; taskno++)
739     short_task_info (taskno);
740 }
741
742 /* Print a detailed description of the Ada task whose ID is TASKNO_STR.  */
743
744 static void
745 info_task (char *taskno_str, int from_tty)
746 {
747   const int taskno = value_as_long (parse_and_eval (taskno_str));
748   struct ada_task_info *task_info;
749   int parent_taskno = 0;
750
751   if (taskno <= 0 || taskno > VEC_length (ada_task_info_s, task_list))
752     error (_("Task ID %d not known.  Use the \"info tasks\" command to\n"
753              "see the IDs of currently known tasks"), taskno);
754   task_info = VEC_index (ada_task_info_s, task_list, taskno - 1);
755
756   /* Print the Ada task ID.  */
757   printf_filtered (_("Ada Task: %s\n"), paddr_nz (task_info->task_id));
758
759   /* Print the name of the task.  */
760   if (task_info->name[0] != '\0')
761     printf_filtered (_("Name: %s\n"), task_info->name);
762   else
763     printf_filtered (_("<no name>\n"));
764
765   /* Print the TID and LWP.  */
766   printf_filtered (_("Thread: %#lx\n"), ptid_get_tid (task_info->ptid));
767   printf_filtered (_("LWP: %#lx\n"), ptid_get_lwp (task_info->ptid));
768
769   /* Print who is the parent (if any).  */
770   if (task_info->parent != 0)
771     parent_taskno = get_task_number_from_id (task_info->parent);
772   if (parent_taskno)
773     {
774       struct ada_task_info *parent =
775         VEC_index (ada_task_info_s, task_list, parent_taskno - 1);
776
777       printf_filtered (_("Parent: %d"), parent_taskno);
778       if (parent->name[0] != '\0')
779         printf_filtered (" (%s)", parent->name);
780       printf_filtered ("\n");
781     }
782   else
783     printf_filtered (_("No parent\n"));
784
785   /* Print the base priority.  */
786   printf_filtered (_("Base Priority: %d\n"), task_info->priority);
787
788   /* print the task current state.  */
789   {
790     int target_taskno = 0;
791
792     if (task_info->caller_task)
793       {
794         target_taskno = get_task_number_from_id (task_info->caller_task);
795         printf_filtered (_("State: Accepting rendezvous with %d"),
796                          target_taskno);
797       }
798     else if (task_info->state == Entry_Caller_Sleep && task_info->called_task)
799       {
800         target_taskno = get_task_number_from_id (task_info->called_task);
801         printf_filtered (_("State: Waiting on task %d's entry"),
802                          target_taskno);
803       }
804     else
805       printf_filtered (_("State: %s"), _(long_task_states[task_info->state]));
806
807     if (target_taskno)
808       {
809         struct ada_task_info *target_task_info =
810           VEC_index (ada_task_info_s, task_list, target_taskno - 1);
811
812         if (target_task_info->name[0] != '\0')
813           printf_filtered (" (%s)", target_task_info->name);
814       }
815
816     printf_filtered ("\n");
817   }
818 }
819
820 /* If ARG is empty or null, then print a list of all Ada tasks.
821    Otherwise, print detailed information about the task whose ID
822    is ARG.
823    
824    Does nothing if the program doesn't use Ada tasking.  */
825
826 static void
827 info_tasks_command (char *arg, int from_tty)
828 {
829   const int task_list_built = ada_build_task_list (1);
830
831   if (!task_list_built)
832     return;
833
834   if (arg == NULL || *arg == '\0')
835     info_tasks (from_tty);
836   else
837     info_task (arg, from_tty);
838 }
839
840 /* Print a message telling the user id of the current task.
841    This function assumes that tasking is in use in the inferior.  */
842
843 static void
844 display_current_task_id (void)
845 {
846   const int current_task = ada_get_task_number (inferior_ptid);
847
848   if (current_task == 0)
849     printf_filtered (_("[Current task is unknown]\n"));
850   else
851     printf_filtered (_("[Current task is %d]\n"), current_task);
852 }
853
854 /* Parse and evaluate TIDSTR into a task id, and try to switch to
855    that task.  Print an error message if the task switch failed.  */
856
857 static void
858 task_command_1 (char *taskno_str, int from_tty)
859 {
860   const int taskno = value_as_long (parse_and_eval (taskno_str));
861   struct ada_task_info *task_info;
862
863   if (taskno <= 0 || taskno > VEC_length (ada_task_info_s, task_list))
864     error (_("Task ID %d not known.  Use the \"info tasks\" command to\n"
865              "see the IDs of currently known tasks"), taskno);
866   task_info = VEC_index (ada_task_info_s, task_list, taskno - 1);
867
868   if (!ada_task_is_alive (task_info))
869     error (_("Cannot switch to task %d: Task is no longer running"), taskno);
870    
871   switch_to_thread (task_info->ptid);
872   ada_find_printable_frame (get_selected_frame (NULL));
873   printf_filtered (_("[Switching to task %d]\n"), taskno);
874   print_stack_frame (get_selected_frame (NULL),
875                      frame_relative_level (get_selected_frame (NULL)), 1);
876 }
877
878
879 /* Print the ID of the current task if TASKNO_STR is empty or NULL.
880    Otherwise, switch to the task indicated by TASKNO_STR.  */
881
882 static void
883 task_command (char *taskno_str, int from_tty)
884 {
885   const int task_list_built = ada_build_task_list (1);
886
887   if (!task_list_built)
888     return;
889
890   if (taskno_str == NULL || taskno_str[0] == '\0')
891     display_current_task_id ();
892   else
893     {
894       /* Task switching in core files doesn't work, either because:
895            1. Thread support is not implemented with core files
896            2. Thread support is implemented, but the thread IDs created
897               after having read the core file are not the same as the ones
898               that were used during the program life, before the crash.
899               As a consequence, there is no longer a way for the debugger
900               to find the associated thead ID of any given Ada task.
901          So, instead of attempting a task switch without giving the user
902          any clue as to what might have happened, just error-out with
903          a message explaining that this feature is not supported.  */
904       if (!target_has_execution)
905         error (_("\
906 Task switching not supported when debugging from core files\n\
907 (use thread support instead)"));
908       task_command_1 (taskno_str, from_tty);
909     }
910 }
911
912 /* Indicate that the task list may have changed, so invalidate the cache.  */
913
914 static void
915 ada_task_list_changed (void)
916 {
917   stale_task_list_p = 1;  
918 }
919
920 /* The 'normal_stop' observer notification callback.  */
921
922 static void
923 ada_normal_stop_observer (struct bpstats *unused_args, int unused_args2)
924 {
925   /* The inferior has been resumed, and just stopped. This means that
926      our task_list needs to be recomputed before it can be used again.  */
927   ada_task_list_changed ();
928 }
929
930 /* A routine to be called when the objfiles have changed.  */
931
932 static void
933 ada_new_objfile_observer (struct objfile *objfile)
934 {
935   /* Invalidate all cached data that were extracted from an objfile.  */
936
937   atcb_type = NULL;
938   atcb_common_type = NULL;
939   atcb_ll_type = NULL;
940   atcb_call_type = NULL;
941
942   ada_tasks_check_symbol_table = 1;
943 }
944
945 /* Provide a prototype to silence -Wmissing-prototypes.  */
946 extern initialize_file_ftype _initialize_tasks;
947
948 void
949 _initialize_tasks (void)
950 {
951   /* Attach various observers.  */
952   observer_attach_normal_stop (ada_normal_stop_observer);
953   observer_attach_new_objfile (ada_new_objfile_observer);
954
955   /* Some new commands provided by this module.  */
956   add_info ("tasks", info_tasks_command,
957             _("Provide information about all known Ada tasks"));
958   add_cmd ("task", class_run, task_command,
959            _("Use this command to switch between Ada tasks.\n\
960 Without argument, this command simply prints the current task ID"),
961            &cmdlist);
962 }
963