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