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