1 /* Copyright (C) 1992-2021 Free Software Foundation, Inc.
2 
3    This file is part of GDB.
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17 
18 #include "defs.h"
19 #include "observable.h"
20 #include "gdbcmd.h"
21 #include "target.h"
22 #include "ada-lang.h"
23 #include "gdbcore.h"
24 #include "inferior.h"
25 #include "gdbthread.h"
26 #include "progspace.h"
27 #include "objfiles.h"
28 #include "cli/cli-style.h"
29 
30 static int ada_build_task_list ();
31 
32 /* The name of the array in the GNAT runtime where the Ada Task Control
33    Block of each task is stored.  */
34 #define KNOWN_TASKS_NAME "system__tasking__debug__known_tasks"
35 
36 /* The maximum number of tasks known to the Ada runtime.  */
37 static const int MAX_NUMBER_OF_KNOWN_TASKS = 1000;
38 
39 /* The name of the variable in the GNAT runtime where the head of a task
40    chain is saved.  This is an alternate mechanism to find the list of known
41    tasks.  */
42 #define KNOWN_TASKS_LIST "system__tasking__debug__first_task"
43 
44 enum task_states
45 {
46   Unactivated,
47   Runnable,
48   Terminated,
49   Activator_Sleep,
50   Acceptor_Sleep,
51   Entry_Caller_Sleep,
52   Async_Select_Sleep,
53   Delay_Sleep,
54   Master_Completion_Sleep,
55   Master_Phase_2_Sleep,
56   Interrupt_Server_Idle_Sleep,
57   Interrupt_Server_Blocked_Interrupt_Sleep,
58   Timer_Server_Sleep,
59   AST_Server_Sleep,
60   Asynchronous_Hold,
61   Interrupt_Server_Blocked_On_Event_Flag,
62   Activating,
63   Acceptor_Delay_Sleep
64 };
65 
66 /* A short description corresponding to each possible task state.  */
67 static const char * const task_states[] = {
68   N_("Unactivated"),
69   N_("Runnable"),
70   N_("Terminated"),
71   N_("Child Activation Wait"),
72   N_("Accept or Select Term"),
73   N_("Waiting on entry call"),
74   N_("Async Select Wait"),
75   N_("Delay Sleep"),
76   N_("Child Termination Wait"),
77   N_("Wait Child in Term Alt"),
78   "",
79   "",
80   "",
81   "",
82   N_("Asynchronous Hold"),
83   "",
84   N_("Activating"),
85   N_("Selective Wait")
86 };
87 
88 /* A longer description corresponding to each possible task state.  */
89 static const char * const long_task_states[] = {
90   N_("Unactivated"),
91   N_("Runnable"),
92   N_("Terminated"),
93   N_("Waiting for child activation"),
94   N_("Blocked in accept or select with terminate"),
95   N_("Waiting on entry call"),
96   N_("Asynchronous Selective Wait"),
97   N_("Delay Sleep"),
98   N_("Waiting for children termination"),
99   N_("Waiting for children in terminate alternative"),
100   "",
101   "",
102   "",
103   "",
104   N_("Asynchronous Hold"),
105   "",
106   N_("Activating"),
107   N_("Blocked in selective wait statement")
108 };
109 
110 /* The index of certain important fields in the Ada Task Control Block
111    record and sub-records.  */
112 
113 struct atcb_fieldnos
114 {
115   /* Fields in record Ada_Task_Control_Block.  */
116   int common;
117   int entry_calls;
118   int atc_nesting_level;
119 
120   /* Fields in record Common_ATCB.  */
121   int state;
122   int parent;
123   int priority;
124   int image;
125   int image_len;     /* This field may be missing.  */
126   int activation_link;
127   int call;
128   int ll;
129   int base_cpu;
130 
131   /* Fields in Task_Primitives.Private_Data.  */
132   int ll_thread;
133   int ll_lwp;        /* This field may be missing.  */
134 
135   /* Fields in Common_ATCB.Call.all.  */
136   int call_self;
137 };
138 
139 /* This module's per-program-space data.  */
140 
141 struct ada_tasks_pspace_data
142 {
143   /* Nonzero if the data has been initialized.  If set to zero,
144      it means that the data has either not been initialized, or
145      has potentially become stale.  */
146   int initialized_p = 0;
147 
148   /* The ATCB record type.  */
149   struct type *atcb_type = nullptr;
150 
151   /* The ATCB "Common" component type.  */
152   struct type *atcb_common_type = nullptr;
153 
154   /* The type of the "ll" field, from the atcb_common_type.  */
155   struct type *atcb_ll_type = nullptr;
156 
157   /* The type of the "call" field, from the atcb_common_type.  */
158   struct type *atcb_call_type = nullptr;
159 
160   /* The index of various fields in the ATCB record and sub-records.  */
161   struct atcb_fieldnos atcb_fieldno {};
162 
163   /* On some systems, gdbserver applies an offset to the CPU that is
164      reported.  */
165   unsigned int cpu_id_offset = 0;
166 };
167 
168 /* Key to our per-program-space data.  */
169 static const struct program_space_key<ada_tasks_pspace_data>
170   ada_tasks_pspace_data_handle;
171 
172 /* The kind of data structure used by the runtime to store the list
173    of Ada tasks.  */
174 
175 enum ada_known_tasks_kind
176 {
177   /* Use this value when we haven't determined which kind of structure
178      is being used, or when we need to recompute it.
179 
180      We set the value of this enumerate to zero on purpose: This allows
181      us to use this enumerate in a structure where setting all fields
182      to zero will result in this kind being set to unknown.  */
183   ADA_TASKS_UNKNOWN = 0,
184 
185   /* This value means that we did not find any task list.  Unless
186      there is a bug somewhere, this means that the inferior does not
187      use tasking.  */
188   ADA_TASKS_NOT_FOUND,
189 
190   /* This value means that the task list is stored as an array.
191      This is the usual method, as it causes very little overhead.
192      But this method is not always used, as it does use a certain
193      amount of memory, which might be scarse in certain environments.  */
194   ADA_TASKS_ARRAY,
195 
196   /* This value means that the task list is stored as a linked list.
197      This has more runtime overhead than the array approach, but
198      also require less memory when the number of tasks is small.  */
199   ADA_TASKS_LIST,
200 };
201 
202 /* This module's per-inferior data.  */
203 
204 struct ada_tasks_inferior_data
205 {
206   /* The type of data structure used by the runtime to store
207      the list of Ada tasks.  The value of this field influences
208      the interpretation of the known_tasks_addr field below:
209        - ADA_TASKS_UNKNOWN: The value of known_tasks_addr hasn't
210 	 been determined yet;
211        - ADA_TASKS_NOT_FOUND: The program probably does not use tasking
212 	 and the known_tasks_addr is irrelevant;
213        - ADA_TASKS_ARRAY: The known_tasks is an array;
214        - ADA_TASKS_LIST: The known_tasks is a list.  */
215   enum ada_known_tasks_kind known_tasks_kind = ADA_TASKS_UNKNOWN;
216 
217   /* The address of the known_tasks structure.  This is where
218      the runtime stores the information for all Ada tasks.
219      The interpretation of this field depends on KNOWN_TASKS_KIND
220      above.  */
221   CORE_ADDR known_tasks_addr = 0;
222 
223   /* Type of elements of the known task.  Usually a pointer.  */
224   struct type *known_tasks_element = nullptr;
225 
226   /* Number of elements in the known tasks array.  */
227   unsigned int known_tasks_length = 0;
228 
229   /* When nonzero, this flag indicates that the task_list field
230      below is up to date.  When set to zero, the list has either
231      not been initialized, or has potentially become stale.  */
232   bool task_list_valid_p = false;
233 
234   /* The list of Ada tasks.
235 
236      Note: To each task we associate a number that the user can use to
237      reference it - this number is printed beside each task in the tasks
238      info listing displayed by "info tasks".  This number is equal to
239      its index in the vector + 1.  Reciprocally, to compute the index
240      of a task in the vector, we need to substract 1 from its number.  */
241   std::vector<ada_task_info> task_list;
242 };
243 
244 /* Key to our per-inferior data.  */
245 static const struct inferior_key<ada_tasks_inferior_data>
246   ada_tasks_inferior_data_handle;
247 
248 /* Return a string with TASKNO followed by the task name if TASK_INFO
249    contains a name.  */
250 
251 static std::string
252 task_to_str (int taskno, const ada_task_info *task_info)
253 {
254   if (task_info->name[0] == '\0')
255     return string_printf ("%d", taskno);
256   else
257     return string_printf ("%d \"%s\"", taskno, task_info->name);
258 }
259 
260 /* Return the ada-tasks module's data for the given program space (PSPACE).
261    If none is found, add a zero'ed one now.
262 
263    This function always returns a valid object.  */
264 
265 static struct ada_tasks_pspace_data *
266 get_ada_tasks_pspace_data (struct program_space *pspace)
267 {
268   struct ada_tasks_pspace_data *data;
269 
270   data = ada_tasks_pspace_data_handle.get (pspace);
271   if (data == NULL)
272     data = ada_tasks_pspace_data_handle.emplace (pspace);
273 
274   return data;
275 }
276 
277 /* Return the ada-tasks module's data for the given inferior (INF).
278    If none is found, add a zero'ed one now.
279 
280    This function always returns a valid object.
281 
282    Note that we could use an observer of the inferior-created event
283    to make sure that the ada-tasks per-inferior data always exists.
284    But we prefered this approach, as it avoids this entirely as long
285    as the user does not use any of the tasking features.  This is
286    quite possible, particularly in the case where the inferior does
287    not use tasking.  */
288 
289 static struct ada_tasks_inferior_data *
290 get_ada_tasks_inferior_data (struct inferior *inf)
291 {
292   struct ada_tasks_inferior_data *data;
293 
294   data = ada_tasks_inferior_data_handle.get (inf);
295   if (data == NULL)
296     data = ada_tasks_inferior_data_handle.emplace (inf);
297 
298   return data;
299 }
300 
301 /* Return the task number of the task whose thread is THREAD, or zero
302    if the task could not be found.  */
303 
304 int
305 ada_get_task_number (thread_info *thread)
306 {
307   struct inferior *inf = thread->inf;
308   struct ada_tasks_inferior_data *data;
309 
310   gdb_assert (inf != NULL);
311   data = get_ada_tasks_inferior_data (inf);
312 
313   for (int i = 0; i < data->task_list.size (); i++)
314     if (data->task_list[i].ptid == thread->ptid)
315       return i + 1;
316 
317   return 0;  /* No matching task found.  */
318 }
319 
320 /* Return the task number of the task running in inferior INF which
321    matches TASK_ID , or zero if the task could not be found.  */
322 
323 static int
324 get_task_number_from_id (CORE_ADDR task_id, struct inferior *inf)
325 {
326   struct ada_tasks_inferior_data *data = get_ada_tasks_inferior_data (inf);
327 
328   for (int i = 0; i < data->task_list.size (); i++)
329     {
330       if (data->task_list[i].task_id == task_id)
331 	return i + 1;
332     }
333 
334   /* Task not found.  Return 0.  */
335   return 0;
336 }
337 
338 /* Return non-zero if TASK_NUM is a valid task number.  */
339 
340 int
341 valid_task_id (int task_num)
342 {
343   struct ada_tasks_inferior_data *data;
344 
345   ada_build_task_list ();
346   data = get_ada_tasks_inferior_data (current_inferior ());
347   return task_num > 0 && task_num <= data->task_list.size ();
348 }
349 
350 /* Return non-zero iff the task STATE corresponds to a non-terminated
351    task state.  */
352 
353 static int
354 ada_task_is_alive (const struct ada_task_info *task_info)
355 {
356   return (task_info->state != Terminated);
357 }
358 
359 /* Search through the list of known tasks for the one whose ptid is
360    PTID, and return it.  Return NULL if the task was not found.  */
361 
362 struct ada_task_info *
363 ada_get_task_info_from_ptid (ptid_t ptid)
364 {
365   struct ada_tasks_inferior_data *data;
366 
367   ada_build_task_list ();
368   data = get_ada_tasks_inferior_data (current_inferior ());
369 
370   for (ada_task_info &task : data->task_list)
371     {
372       if (task.ptid == ptid)
373 	return &task;
374     }
375 
376   return NULL;
377 }
378 
379 /* Call the ITERATOR function once for each Ada task that hasn't been
380    terminated yet.  */
381 
382 void
383 iterate_over_live_ada_tasks (ada_task_list_iterator_ftype iterator)
384 {
385   struct ada_tasks_inferior_data *data;
386 
387   ada_build_task_list ();
388   data = get_ada_tasks_inferior_data (current_inferior ());
389 
390   for (ada_task_info &task : data->task_list)
391     {
392       if (!ada_task_is_alive (&task))
393 	continue;
394       iterator (&task);
395     }
396 }
397 
398 /* Extract the contents of the value as a string whose length is LENGTH,
399    and store the result in DEST.  */
400 
401 static void
402 value_as_string (char *dest, struct value *val, int length)
403 {
404   memcpy (dest, value_contents (val), length);
405   dest[length] = '\0';
406 }
407 
408 /* Extract the string image from the fat string corresponding to VAL,
409    and store it in DEST.  If the string length is greater than MAX_LEN,
410    then truncate the result to the first MAX_LEN characters of the fat
411    string.  */
412 
413 static void
414 read_fat_string_value (char *dest, struct value *val, int max_len)
415 {
416   struct value *array_val;
417   struct value *bounds_val;
418   int len;
419 
420   /* The following variables are made static to avoid recomputing them
421      each time this function is called.  */
422   static int initialize_fieldnos = 1;
423   static int array_fieldno;
424   static int bounds_fieldno;
425   static int upper_bound_fieldno;
426 
427   /* Get the index of the fields that we will need to read in order
428      to extract the string from the fat string.  */
429   if (initialize_fieldnos)
430     {
431       struct type *type = value_type (val);
432       struct type *bounds_type;
433 
434       array_fieldno = ada_get_field_index (type, "P_ARRAY", 0);
435       bounds_fieldno = ada_get_field_index (type, "P_BOUNDS", 0);
436 
437       bounds_type = type->field (bounds_fieldno).type ();
438       if (bounds_type->code () == TYPE_CODE_PTR)
439 	bounds_type = TYPE_TARGET_TYPE (bounds_type);
440       if (bounds_type->code () != TYPE_CODE_STRUCT)
441 	error (_("Unknown task name format. Aborting"));
442       upper_bound_fieldno = ada_get_field_index (bounds_type, "UB0", 0);
443 
444       initialize_fieldnos = 0;
445     }
446 
447   /* Get the size of the task image by checking the value of the bounds.
448      The lower bound is always 1, so we only need to read the upper bound.  */
449   bounds_val = value_ind (value_field (val, bounds_fieldno));
450   len = value_as_long (value_field (bounds_val, upper_bound_fieldno));
451 
452   /* Make sure that we do not read more than max_len characters...  */
453   if (len > max_len)
454     len = max_len;
455 
456   /* Extract LEN characters from the fat string.  */
457   array_val = value_ind (value_field (val, array_fieldno));
458   read_memory (value_address (array_val), (gdb_byte *) dest, len);
459 
460   /* Add the NUL character to close the string.  */
461   dest[len] = '\0';
462 }
463 
464 /* Get, from the debugging information, the type description of all types
465    related to the Ada Task Control Block that are needed in order to
466    read the list of known tasks in the Ada runtime.  If all of the info
467    needed to do so is found, then save that info in the module's per-
468    program-space data, and return NULL.  Otherwise, if any information
469    cannot be found, leave the per-program-space data untouched, and
470    return an error message explaining what was missing (that error
471    message does NOT need to be deallocated).  */
472 
473 const char *
474 ada_get_tcb_types_info (void)
475 {
476   struct type *type;
477   struct type *common_type;
478   struct type *ll_type;
479   struct type *call_type;
480   struct atcb_fieldnos fieldnos;
481   struct ada_tasks_pspace_data *pspace_data;
482 
483   const char *atcb_name = "system__tasking__ada_task_control_block___XVE";
484   const char *atcb_name_fixed = "system__tasking__ada_task_control_block";
485   const char *common_atcb_name = "system__tasking__common_atcb";
486   const char *private_data_name = "system__task_primitives__private_data";
487   const char *entry_call_record_name = "system__tasking__entry_call_record";
488 
489   /* ATCB symbols may be found in several compilation units.  As we
490      are only interested in one instance, use standard (literal,
491      C-like) lookups to get the first match.  */
492 
493   struct symbol *atcb_sym =
494     lookup_symbol_in_language (atcb_name, NULL, STRUCT_DOMAIN,
495 			       language_c, NULL).symbol;
496   const struct symbol *common_atcb_sym =
497     lookup_symbol_in_language (common_atcb_name, NULL, STRUCT_DOMAIN,
498 			       language_c, NULL).symbol;
499   const struct symbol *private_data_sym =
500     lookup_symbol_in_language (private_data_name, NULL, STRUCT_DOMAIN,
501 			       language_c, NULL).symbol;
502   const struct symbol *entry_call_record_sym =
503     lookup_symbol_in_language (entry_call_record_name, NULL, STRUCT_DOMAIN,
504 			       language_c, NULL).symbol;
505 
506   if (atcb_sym == NULL || atcb_sym->type == NULL)
507     {
508       /* In Ravenscar run-time libs, the  ATCB does not have a dynamic
509 	 size, so the symbol name differs.  */
510       atcb_sym = lookup_symbol_in_language (atcb_name_fixed, NULL,
511 					    STRUCT_DOMAIN, language_c,
512 					    NULL).symbol;
513 
514       if (atcb_sym == NULL || atcb_sym->type == NULL)
515 	return _("Cannot find Ada_Task_Control_Block type");
516 
517       type = atcb_sym->type;
518     }
519   else
520     {
521       /* Get a static representation of the type record
522 	 Ada_Task_Control_Block.  */
523       type = atcb_sym->type;
524       type = ada_template_to_fixed_record_type_1 (type, NULL, 0, NULL, 0);
525     }
526 
527   if (common_atcb_sym == NULL || common_atcb_sym->type == NULL)
528     return _("Cannot find Common_ATCB type");
529   if (private_data_sym == NULL || private_data_sym->type == NULL)
530     return _("Cannot find Private_Data type");
531   if (entry_call_record_sym == NULL || entry_call_record_sym->type == NULL)
532     return _("Cannot find Entry_Call_Record type");
533 
534   /* Get the type for Ada_Task_Control_Block.Common.  */
535   common_type = common_atcb_sym->type;
536 
537   /* Get the type for Ada_Task_Control_Bloc.Common.Call.LL.  */
538   ll_type = private_data_sym->type;
539 
540   /* Get the type for Common_ATCB.Call.all.  */
541   call_type = entry_call_record_sym->type;
542 
543   /* Get the field indices.  */
544   fieldnos.common = ada_get_field_index (type, "common", 0);
545   fieldnos.entry_calls = ada_get_field_index (type, "entry_calls", 1);
546   fieldnos.atc_nesting_level =
547     ada_get_field_index (type, "atc_nesting_level", 1);
548   fieldnos.state = ada_get_field_index (common_type, "state", 0);
549   fieldnos.parent = ada_get_field_index (common_type, "parent", 1);
550   fieldnos.priority = ada_get_field_index (common_type, "base_priority", 0);
551   fieldnos.image = ada_get_field_index (common_type, "task_image", 1);
552   fieldnos.image_len = ada_get_field_index (common_type, "task_image_len", 1);
553   fieldnos.activation_link = ada_get_field_index (common_type,
554 						  "activation_link", 1);
555   fieldnos.call = ada_get_field_index (common_type, "call", 1);
556   fieldnos.ll = ada_get_field_index (common_type, "ll", 0);
557   fieldnos.base_cpu = ada_get_field_index (common_type, "base_cpu", 0);
558   fieldnos.ll_thread = ada_get_field_index (ll_type, "thread", 0);
559   fieldnos.ll_lwp = ada_get_field_index (ll_type, "lwp", 1);
560   fieldnos.call_self = ada_get_field_index (call_type, "self", 0);
561 
562   /* On certain platforms such as x86-windows, the "lwp" field has been
563      named "thread_id".  This field will likely be renamed in the future,
564      but we need to support both possibilities to avoid an unnecessary
565      dependency on a recent compiler.  We therefore try locating the
566      "thread_id" field in place of the "lwp" field if we did not find
567      the latter.  */
568   if (fieldnos.ll_lwp < 0)
569     fieldnos.ll_lwp = ada_get_field_index (ll_type, "thread_id", 1);
570 
571   /* Check for the CPU offset.  */
572   bound_minimal_symbol first_id_sym
573     = lookup_bound_minimal_symbol ("__gnat_gdb_cpu_first_id");
574   unsigned int first_id = 0;
575   if (first_id_sym.minsym != nullptr)
576     {
577       CORE_ADDR addr = BMSYMBOL_VALUE_ADDRESS (first_id_sym);
578       /* This symbol always has type uint32_t.  */
579       struct type *u32type = builtin_type (target_gdbarch ())->builtin_uint32;
580       first_id = value_as_long (value_at (u32type, addr));
581     }
582 
583   /* Set all the out parameters all at once, now that we are certain
584      that there are no potential error() anymore.  */
585   pspace_data = get_ada_tasks_pspace_data (current_program_space);
586   pspace_data->initialized_p = 1;
587   pspace_data->atcb_type = type;
588   pspace_data->atcb_common_type = common_type;
589   pspace_data->atcb_ll_type = ll_type;
590   pspace_data->atcb_call_type = call_type;
591   pspace_data->atcb_fieldno = fieldnos;
592   pspace_data->cpu_id_offset = first_id;
593   return NULL;
594 }
595 
596 /* Build the PTID of the task from its COMMON_VALUE, which is the "Common"
597    component of its ATCB record.  This PTID needs to match the PTID used
598    by the thread layer.  */
599 
600 static ptid_t
601 ptid_from_atcb_common (struct value *common_value)
602 {
603   long thread = 0;
604   CORE_ADDR lwp = 0;
605   struct value *ll_value;
606   ptid_t ptid;
607   const struct ada_tasks_pspace_data *pspace_data
608     = get_ada_tasks_pspace_data (current_program_space);
609 
610   ll_value = value_field (common_value, pspace_data->atcb_fieldno.ll);
611 
612   if (pspace_data->atcb_fieldno.ll_lwp >= 0)
613     lwp = value_as_address (value_field (ll_value,
614 					 pspace_data->atcb_fieldno.ll_lwp));
615   thread = value_as_long (value_field (ll_value,
616 				       pspace_data->atcb_fieldno.ll_thread));
617 
618   ptid = target_get_ada_task_ptid (lwp, thread);
619 
620   return ptid;
621 }
622 
623 /* Read the ATCB data of a given task given its TASK_ID (which is in practice
624    the address of its associated ATCB record), and store the result inside
625    TASK_INFO.  */
626 
627 static void
628 read_atcb (CORE_ADDR task_id, struct ada_task_info *task_info)
629 {
630   struct value *tcb_value;
631   struct value *common_value;
632   struct value *atc_nesting_level_value;
633   struct value *entry_calls_value;
634   struct value *entry_calls_value_element;
635   int called_task_fieldno = -1;
636   static const char ravenscar_task_name[] = "Ravenscar task";
637   const struct ada_tasks_pspace_data *pspace_data
638     = get_ada_tasks_pspace_data (current_program_space);
639 
640   /* Clear the whole structure to start with, so that everything
641      is always initialized the same.  */
642   memset (task_info, 0, sizeof (struct ada_task_info));
643 
644   if (!pspace_data->initialized_p)
645     {
646       const char *err_msg = ada_get_tcb_types_info ();
647 
648       if (err_msg != NULL)
649 	error (_("%s. Aborting"), err_msg);
650     }
651 
652   tcb_value = value_from_contents_and_address (pspace_data->atcb_type,
653 					       NULL, task_id);
654   common_value = value_field (tcb_value, pspace_data->atcb_fieldno.common);
655 
656   /* Fill in the task_id.  */
657 
658   task_info->task_id = task_id;
659 
660   /* Compute the name of the task.
661 
662      Depending on the GNAT version used, the task image is either a fat
663      string, or a thin array of characters.  Older versions of GNAT used
664      to use fat strings, and therefore did not need an extra field in
665      the ATCB to store the string length.  For efficiency reasons, newer
666      versions of GNAT replaced the fat string by a static buffer, but this
667      also required the addition of a new field named "Image_Len" containing
668      the length of the task name.  The method used to extract the task name
669      is selected depending on the existence of this field.
670 
671      In some run-time libs (e.g. Ravenscar), the name is not in the ATCB;
672      we may want to get it from the first user frame of the stack.  For now,
673      we just give a dummy name.  */
674 
675   if (pspace_data->atcb_fieldno.image_len == -1)
676     {
677       if (pspace_data->atcb_fieldno.image >= 0)
678 	read_fat_string_value (task_info->name,
679 			       value_field (common_value,
680 					    pspace_data->atcb_fieldno.image),
681 			       sizeof (task_info->name) - 1);
682       else
683 	{
684 	  struct bound_minimal_symbol msym;
685 
686 	  msym = lookup_minimal_symbol_by_pc (task_id);
687 	  if (msym.minsym)
688 	    {
689 	      const char *full_name = msym.minsym->linkage_name ();
690 	      const char *task_name = full_name;
691 	      const char *p;
692 
693 	      /* Strip the prefix.  */
694 	      for (p = full_name; *p; p++)
695 		if (p[0] == '_' && p[1] == '_')
696 		  task_name = p + 2;
697 
698 	      /* Copy the task name.  */
699 	      strncpy (task_info->name, task_name,
700 		       sizeof (task_info->name) - 1);
701 	      task_info->name[sizeof (task_info->name) - 1] = 0;
702 	    }
703 	  else
704 	    {
705 	      /* No symbol found.  Use a default name.  */
706 	      strcpy (task_info->name, ravenscar_task_name);
707 	    }
708 	}
709     }
710   else
711     {
712       int len = value_as_long
713 		  (value_field (common_value,
714 				pspace_data->atcb_fieldno.image_len));
715 
716       value_as_string (task_info->name,
717 		       value_field (common_value,
718 				    pspace_data->atcb_fieldno.image),
719 		       len);
720     }
721 
722   /* Compute the task state and priority.  */
723 
724   task_info->state =
725     value_as_long (value_field (common_value,
726 				pspace_data->atcb_fieldno.state));
727   task_info->priority =
728     value_as_long (value_field (common_value,
729 				pspace_data->atcb_fieldno.priority));
730 
731   /* If the ATCB contains some information about the parent task,
732      then compute it as well.  Otherwise, zero.  */
733 
734   if (pspace_data->atcb_fieldno.parent >= 0)
735     task_info->parent =
736       value_as_address (value_field (common_value,
737 				     pspace_data->atcb_fieldno.parent));
738 
739   /* If the task is in an entry call waiting for another task,
740      then determine which task it is.  */
741 
742   if (task_info->state == Entry_Caller_Sleep
743       && pspace_data->atcb_fieldno.atc_nesting_level > 0
744       && pspace_data->atcb_fieldno.entry_calls > 0)
745     {
746       /* Let My_ATCB be the Ada task control block of a task calling the
747 	 entry of another task; then the Task_Id of the called task is
748 	 in My_ATCB.Entry_Calls (My_ATCB.ATC_Nesting_Level).Called_Task.  */
749       atc_nesting_level_value =
750 	value_field (tcb_value, pspace_data->atcb_fieldno.atc_nesting_level);
751       entry_calls_value =
752 	ada_coerce_to_simple_array_ptr
753 	  (value_field (tcb_value, pspace_data->atcb_fieldno.entry_calls));
754       entry_calls_value_element =
755 	value_subscript (entry_calls_value,
756 			 value_as_long (atc_nesting_level_value));
757       called_task_fieldno =
758 	ada_get_field_index (value_type (entry_calls_value_element),
759 			     "called_task", 0);
760       task_info->called_task =
761 	value_as_address (value_field (entry_calls_value_element,
762 				       called_task_fieldno));
763     }
764 
765   /* If the ATCB contains some information about RV callers, then
766      compute the "caller_task".  Otherwise, leave it as zero.  */
767 
768   if (pspace_data->atcb_fieldno.call >= 0)
769     {
770       /* Get the ID of the caller task from Common_ATCB.Call.all.Self.
771 	 If Common_ATCB.Call is null, then there is no caller.  */
772       const CORE_ADDR call =
773 	value_as_address (value_field (common_value,
774 				       pspace_data->atcb_fieldno.call));
775       struct value *call_val;
776 
777       if (call != 0)
778 	{
779 	  call_val =
780 	    value_from_contents_and_address (pspace_data->atcb_call_type,
781 					     NULL, call);
782 	  task_info->caller_task =
783 	    value_as_address
784 	      (value_field (call_val, pspace_data->atcb_fieldno.call_self));
785 	}
786     }
787 
788   task_info->base_cpu
789     = (pspace_data->cpu_id_offset
790       + value_as_long (value_field (common_value,
791 				    pspace_data->atcb_fieldno.base_cpu)));
792 
793   /* And finally, compute the task ptid.  Note that there is not point
794      in computing it if the task is no longer alive, in which case
795      it is good enough to set its ptid to the null_ptid.  */
796   if (ada_task_is_alive (task_info))
797     task_info->ptid = ptid_from_atcb_common (common_value);
798   else
799     task_info->ptid = null_ptid;
800 }
801 
802 /* Read the ATCB info of the given task (identified by TASK_ID), and
803    add the result to the given inferior's TASK_LIST.  */
804 
805 static void
806 add_ada_task (CORE_ADDR task_id, struct inferior *inf)
807 {
808   struct ada_task_info task_info;
809   struct ada_tasks_inferior_data *data = get_ada_tasks_inferior_data (inf);
810 
811   read_atcb (task_id, &task_info);
812   data->task_list.push_back (task_info);
813 }
814 
815 /* Read the Known_Tasks array from the inferior memory, and store
816    it in the current inferior's TASK_LIST.  Return true upon success.  */
817 
818 static bool
819 read_known_tasks_array (struct ada_tasks_inferior_data *data)
820 {
821   const int target_ptr_byte = TYPE_LENGTH (data->known_tasks_element);
822   const int known_tasks_size = target_ptr_byte * data->known_tasks_length;
823   gdb_byte *known_tasks = (gdb_byte *) alloca (known_tasks_size);
824   int i;
825 
826   /* Build a new list by reading the ATCBs from the Known_Tasks array
827      in the Ada runtime.  */
828   read_memory (data->known_tasks_addr, known_tasks, known_tasks_size);
829   for (i = 0; i < data->known_tasks_length; i++)
830     {
831       CORE_ADDR task_id =
832 	extract_typed_address (known_tasks + i * target_ptr_byte,
833 			       data->known_tasks_element);
834 
835       if (task_id != 0)
836 	add_ada_task (task_id, current_inferior ());
837     }
838 
839   return true;
840 }
841 
842 /* Read the known tasks from the inferior memory, and store it in
843    the current inferior's TASK_LIST.  Return true upon success.  */
844 
845 static bool
846 read_known_tasks_list (struct ada_tasks_inferior_data *data)
847 {
848   const int target_ptr_byte = TYPE_LENGTH (data->known_tasks_element);
849   gdb_byte *known_tasks = (gdb_byte *) alloca (target_ptr_byte);
850   CORE_ADDR task_id;
851   const struct ada_tasks_pspace_data *pspace_data
852     = get_ada_tasks_pspace_data (current_program_space);
853 
854   /* Sanity check.  */
855   if (pspace_data->atcb_fieldno.activation_link < 0)
856     return false;
857 
858   /* Build a new list by reading the ATCBs.  Read head of the list.  */
859   read_memory (data->known_tasks_addr, known_tasks, target_ptr_byte);
860   task_id = extract_typed_address (known_tasks, data->known_tasks_element);
861   while (task_id != 0)
862     {
863       struct value *tcb_value;
864       struct value *common_value;
865 
866       add_ada_task (task_id, current_inferior ());
867 
868       /* Read the chain.  */
869       tcb_value = value_from_contents_and_address (pspace_data->atcb_type,
870 						   NULL, task_id);
871       common_value = value_field (tcb_value, pspace_data->atcb_fieldno.common);
872       task_id = value_as_address
873 		  (value_field (common_value,
874 				pspace_data->atcb_fieldno.activation_link));
875     }
876 
877   return true;
878 }
879 
880 /* Set all fields of the current inferior ada-tasks data pointed by DATA.
881    Do nothing if those fields are already set and still up to date.  */
882 
883 static void
884 ada_tasks_inferior_data_sniffer (struct ada_tasks_inferior_data *data)
885 {
886   struct bound_minimal_symbol msym;
887   struct symbol *sym;
888 
889   /* Return now if already set.  */
890   if (data->known_tasks_kind != ADA_TASKS_UNKNOWN)
891     return;
892 
893   /* Try array.  */
894 
895   msym = lookup_minimal_symbol (KNOWN_TASKS_NAME, NULL, NULL);
896   if (msym.minsym != NULL)
897     {
898       data->known_tasks_kind = ADA_TASKS_ARRAY;
899       data->known_tasks_addr = BMSYMBOL_VALUE_ADDRESS (msym);
900 
901       /* Try to get pointer type and array length from the symtab.  */
902       sym = lookup_symbol_in_language (KNOWN_TASKS_NAME, NULL, VAR_DOMAIN,
903 				       language_c, NULL).symbol;
904       if (sym != NULL)
905 	{
906 	  /* Validate.  */
907 	  struct type *type = check_typedef (SYMBOL_TYPE (sym));
908 	  struct type *eltype = NULL;
909 	  struct type *idxtype = NULL;
910 
911 	  if (type->code () == TYPE_CODE_ARRAY)
912 	    eltype = check_typedef (TYPE_TARGET_TYPE (type));
913 	  if (eltype != NULL
914 	      && eltype->code () == TYPE_CODE_PTR)
915 	    idxtype = check_typedef (type->index_type ());
916 	  if (idxtype != NULL
917 	      && idxtype->bounds ()->low.kind () != PROP_UNDEFINED
918 	      && idxtype->bounds ()->high.kind () != PROP_UNDEFINED)
919 	    {
920 	      data->known_tasks_element = eltype;
921 	      data->known_tasks_length =
922 		(idxtype->bounds ()->high.const_val ()
923 		 - idxtype->bounds ()->low.const_val () + 1);
924 	      return;
925 	    }
926 	}
927 
928       /* Fallback to default values.  The runtime may have been stripped (as
929 	 in some distributions), but it is likely that the executable still
930 	 contains debug information on the task type (due to implicit with of
931 	 Ada.Tasking).  */
932       data->known_tasks_element =
933 	builtin_type (target_gdbarch ())->builtin_data_ptr;
934       data->known_tasks_length = MAX_NUMBER_OF_KNOWN_TASKS;
935       return;
936     }
937 
938 
939   /* Try list.  */
940 
941   msym = lookup_minimal_symbol (KNOWN_TASKS_LIST, NULL, NULL);
942   if (msym.minsym != NULL)
943     {
944       data->known_tasks_kind = ADA_TASKS_LIST;
945       data->known_tasks_addr = BMSYMBOL_VALUE_ADDRESS (msym);
946       data->known_tasks_length = 1;
947 
948       sym = lookup_symbol_in_language (KNOWN_TASKS_LIST, NULL, VAR_DOMAIN,
949 				       language_c, NULL).symbol;
950       if (sym != NULL && SYMBOL_VALUE_ADDRESS (sym) != 0)
951 	{
952 	  /* Validate.  */
953 	  struct type *type = check_typedef (SYMBOL_TYPE (sym));
954 
955 	  if (type->code () == TYPE_CODE_PTR)
956 	    {
957 	      data->known_tasks_element = type;
958 	      return;
959 	    }
960 	}
961 
962       /* Fallback to default values.  */
963       data->known_tasks_element =
964 	builtin_type (target_gdbarch ())->builtin_data_ptr;
965       data->known_tasks_length = 1;
966       return;
967     }
968 
969   /* Can't find tasks.  */
970 
971   data->known_tasks_kind = ADA_TASKS_NOT_FOUND;
972   data->known_tasks_addr = 0;
973 }
974 
975 /* Read the known tasks from the current inferior's memory, and store it
976    in the current inferior's data TASK_LIST.  */
977 
978 static void
979 read_known_tasks ()
980 {
981   struct ada_tasks_inferior_data *data =
982     get_ada_tasks_inferior_data (current_inferior ());
983 
984   /* Step 1: Clear the current list, if necessary.  */
985   data->task_list.clear ();
986 
987   /* Step 2: do the real work.
988      If the application does not use task, then no more needs to be done.
989      It is important to have the task list cleared (see above) before we
990      return, as we don't want a stale task list to be used...  This can
991      happen for instance when debugging a non-multitasking program after
992      having debugged a multitasking one.  */
993   ada_tasks_inferior_data_sniffer (data);
994   gdb_assert (data->known_tasks_kind != ADA_TASKS_UNKNOWN);
995 
996   /* Step 3: Set task_list_valid_p, to avoid re-reading the Known_Tasks
997      array unless needed.  */
998   switch (data->known_tasks_kind)
999     {
1000     case ADA_TASKS_NOT_FOUND: /* Tasking not in use in inferior.  */
1001       break;
1002     case ADA_TASKS_ARRAY:
1003       data->task_list_valid_p = read_known_tasks_array (data);
1004       break;
1005     case ADA_TASKS_LIST:
1006       data->task_list_valid_p = read_known_tasks_list (data);
1007       break;
1008     }
1009 }
1010 
1011 /* Build the task_list by reading the Known_Tasks array from
1012    the inferior, and return the number of tasks in that list
1013    (zero means that the program is not using tasking at all).  */
1014 
1015 static int
1016 ada_build_task_list ()
1017 {
1018   struct ada_tasks_inferior_data *data;
1019 
1020   if (!target_has_stack ())
1021     error (_("Cannot inspect Ada tasks when program is not running"));
1022 
1023   data = get_ada_tasks_inferior_data (current_inferior ());
1024   if (!data->task_list_valid_p)
1025     read_known_tasks ();
1026 
1027   return data->task_list.size ();
1028 }
1029 
1030 /* Print a table providing a short description of all Ada tasks
1031    running inside inferior INF.  If ARG_STR is set, it will be
1032    interpreted as a task number, and the table will be limited to
1033    that task only.  */
1034 
1035 void
1036 print_ada_task_info (struct ui_out *uiout,
1037 		     const char *arg_str,
1038 		     struct inferior *inf)
1039 {
1040   struct ada_tasks_inferior_data *data;
1041   int taskno, nb_tasks;
1042   int taskno_arg = 0;
1043   int nb_columns;
1044 
1045   if (ada_build_task_list () == 0)
1046     {
1047       uiout->message (_("Your application does not use any Ada tasks.\n"));
1048       return;
1049     }
1050 
1051   if (arg_str != NULL && arg_str[0] != '\0')
1052     taskno_arg = value_as_long (parse_and_eval (arg_str));
1053 
1054   if (uiout->is_mi_like_p ())
1055     /* In GDB/MI mode, we want to provide the thread ID corresponding
1056        to each task.  This allows clients to quickly find the thread
1057        associated to any task, which is helpful for commands that
1058        take a --thread argument.  However, in order to be able to
1059        provide that thread ID, the thread list must be up to date
1060        first.  */
1061     target_update_thread_list ();
1062 
1063   data = get_ada_tasks_inferior_data (inf);
1064 
1065   /* Compute the number of tasks that are going to be displayed
1066      in the output.  If an argument was given, there will be
1067      at most 1 entry.  Otherwise, there will be as many entries
1068      as we have tasks.  */
1069   if (taskno_arg)
1070     {
1071       if (taskno_arg > 0 && taskno_arg <= data->task_list.size ())
1072 	nb_tasks = 1;
1073       else
1074 	nb_tasks = 0;
1075     }
1076   else
1077     nb_tasks = data->task_list.size ();
1078 
1079   nb_columns = uiout->is_mi_like_p () ? 8 : 7;
1080   ui_out_emit_table table_emitter (uiout, nb_columns, nb_tasks, "tasks");
1081   uiout->table_header (1, ui_left, "current", "");
1082   uiout->table_header (3, ui_right, "id", "ID");
1083   {
1084     size_t tid_width = 9;
1085     /* Grown below in case the largest entry is bigger.  */
1086 
1087     if (!uiout->is_mi_like_p ())
1088       {
1089 	for (taskno = 1; taskno <= data->task_list.size (); taskno++)
1090 	  {
1091 	    const struct ada_task_info *const task_info
1092 	      = &data->task_list[taskno - 1];
1093 
1094 	    gdb_assert (task_info != NULL);
1095 
1096 	    tid_width = std::max (tid_width,
1097 				  1 + strlen (phex_nz (task_info->task_id,
1098 						       sizeof (CORE_ADDR))));
1099 	  }
1100       }
1101     uiout->table_header (tid_width, ui_right, "task-id", "TID");
1102   }
1103   /* The following column is provided in GDB/MI mode only because
1104      it is only really useful in that mode, and also because it
1105      allows us to keep the CLI output shorter and more compact.  */
1106   if (uiout->is_mi_like_p ())
1107     uiout->table_header (4, ui_right, "thread-id", "");
1108   uiout->table_header (4, ui_right, "parent-id", "P-ID");
1109   uiout->table_header (3, ui_right, "priority", "Pri");
1110   uiout->table_header (22, ui_left, "state", "State");
1111   /* Use ui_noalign for the last column, to prevent the CLI uiout
1112      from printing an extra space at the end of each row.  This
1113      is a bit of a hack, but does get the job done.  */
1114   uiout->table_header (1, ui_noalign, "name", "Name");
1115   uiout->table_body ();
1116 
1117   for (taskno = 1; taskno <= data->task_list.size (); taskno++)
1118     {
1119       const struct ada_task_info *const task_info =
1120 	&data->task_list[taskno - 1];
1121       int parent_id;
1122 
1123       gdb_assert (task_info != NULL);
1124 
1125       /* If the user asked for the output to be restricted
1126 	 to one task only, and this is not the task, skip
1127 	 to the next one.  */
1128       if (taskno_arg && taskno != taskno_arg)
1129 	continue;
1130 
1131       ui_out_emit_tuple tuple_emitter (uiout, NULL);
1132 
1133       /* Print a star if this task is the current task (or the task
1134 	 currently selected).  */
1135       if (task_info->ptid == inferior_ptid)
1136 	uiout->field_string ("current", "*");
1137       else
1138 	uiout->field_skip ("current");
1139 
1140       /* Print the task number.  */
1141       uiout->field_signed ("id", taskno);
1142 
1143       /* Print the Task ID.  */
1144       uiout->field_string ("task-id", phex_nz (task_info->task_id,
1145 					       sizeof (CORE_ADDR)));
1146 
1147       /* Print the associated Thread ID.  */
1148       if (uiout->is_mi_like_p ())
1149 	{
1150 	  thread_info *thread = (ada_task_is_alive (task_info)
1151 				 ? find_thread_ptid (inf, task_info->ptid)
1152 				 : nullptr);
1153 
1154 	  if (thread != NULL)
1155 	    uiout->field_signed ("thread-id", thread->global_num);
1156 	  else
1157 	    {
1158 	      /* This can happen if the thread is no longer alive.  */
1159 	      uiout->field_skip ("thread-id");
1160 	    }
1161 	}
1162 
1163       /* Print the ID of the parent task.  */
1164       parent_id = get_task_number_from_id (task_info->parent, inf);
1165       if (parent_id)
1166 	uiout->field_signed ("parent-id", parent_id);
1167       else
1168 	uiout->field_skip ("parent-id");
1169 
1170       /* Print the base priority of the task.  */
1171       uiout->field_signed ("priority", task_info->priority);
1172 
1173       /* Print the task current state.  */
1174       if (task_info->caller_task)
1175 	uiout->field_fmt ("state",
1176 			  _("Accepting RV with %-4d"),
1177 			  get_task_number_from_id (task_info->caller_task,
1178 						   inf));
1179       else if (task_info->called_task)
1180 	uiout->field_fmt ("state",
1181 			  _("Waiting on RV with %-3d"),
1182 			  get_task_number_from_id (task_info->called_task,
1183 						   inf));
1184       else
1185 	uiout->field_string ("state", task_states[task_info->state]);
1186 
1187       /* Finally, print the task name, without quotes around it, as mi like
1188 	 is not expecting quotes, and in non mi-like no need for quotes
1189 	 as there is a specific column for the name.  */
1190       uiout->field_fmt ("name",
1191 			(task_info->name[0] != '\0'
1192 			 ? ui_file_style ()
1193 			 : metadata_style.style ()),
1194 			"%s",
1195 			(task_info->name[0] != '\0'
1196 			 ? task_info->name
1197 			 : _("<no name>")));
1198 
1199       uiout->text ("\n");
1200     }
1201 }
1202 
1203 /* Print a detailed description of the Ada task whose ID is TASKNO_STR
1204    for the given inferior (INF).  */
1205 
1206 static void
1207 info_task (struct ui_out *uiout, const char *taskno_str, struct inferior *inf)
1208 {
1209   const int taskno = value_as_long (parse_and_eval (taskno_str));
1210   struct ada_task_info *task_info;
1211   int parent_taskno = 0;
1212   struct ada_tasks_inferior_data *data = get_ada_tasks_inferior_data (inf);
1213 
1214   if (ada_build_task_list () == 0)
1215     {
1216       uiout->message (_("Your application does not use any Ada tasks.\n"));
1217       return;
1218     }
1219 
1220   if (taskno <= 0 || taskno > data->task_list.size ())
1221     error (_("Task ID %d not known.  Use the \"info tasks\" command to\n"
1222 	     "see the IDs of currently known tasks"), taskno);
1223   task_info = &data->task_list[taskno - 1];
1224 
1225   /* Print the Ada task ID.  */
1226   printf_filtered (_("Ada Task: %s\n"),
1227 		   paddress (target_gdbarch (), task_info->task_id));
1228 
1229   /* Print the name of the task.  */
1230   if (task_info->name[0] != '\0')
1231     printf_filtered (_("Name: %s\n"), task_info->name);
1232   else
1233     fprintf_styled (gdb_stdout, metadata_style.style (), _("<no name>\n"));
1234 
1235   /* Print the TID and LWP.  */
1236   printf_filtered (_("Thread: %#lx\n"), task_info->ptid.tid ());
1237   printf_filtered (_("LWP: %#lx\n"), task_info->ptid.lwp ());
1238 
1239   /* If set, print the base CPU.  */
1240   if (task_info->base_cpu != 0)
1241     printf_filtered (_("Base CPU: %d\n"), task_info->base_cpu);
1242 
1243   /* Print who is the parent (if any).  */
1244   if (task_info->parent != 0)
1245     parent_taskno = get_task_number_from_id (task_info->parent, inf);
1246   if (parent_taskno)
1247     {
1248       struct ada_task_info *parent = &data->task_list[parent_taskno - 1];
1249 
1250       printf_filtered (_("Parent: %d"), parent_taskno);
1251       if (parent->name[0] != '\0')
1252 	printf_filtered (" (%s)", parent->name);
1253       printf_filtered ("\n");
1254     }
1255   else
1256     printf_filtered (_("No parent\n"));
1257 
1258   /* Print the base priority.  */
1259   printf_filtered (_("Base Priority: %d\n"), task_info->priority);
1260 
1261   /* print the task current state.  */
1262   {
1263     int target_taskno = 0;
1264 
1265     if (task_info->caller_task)
1266       {
1267 	target_taskno = get_task_number_from_id (task_info->caller_task, inf);
1268 	printf_filtered (_("State: Accepting rendezvous with %d"),
1269 			 target_taskno);
1270       }
1271     else if (task_info->called_task)
1272       {
1273 	target_taskno = get_task_number_from_id (task_info->called_task, inf);
1274 	printf_filtered (_("State: Waiting on task %d's entry"),
1275 			 target_taskno);
1276       }
1277     else
1278       printf_filtered (_("State: %s"), _(long_task_states[task_info->state]));
1279 
1280     if (target_taskno)
1281       {
1282 	ada_task_info *target_task_info = &data->task_list[target_taskno - 1];
1283 
1284 	if (target_task_info->name[0] != '\0')
1285 	  printf_filtered (" (%s)", target_task_info->name);
1286       }
1287 
1288     printf_filtered ("\n");
1289   }
1290 }
1291 
1292 /* If ARG is empty or null, then print a list of all Ada tasks.
1293    Otherwise, print detailed information about the task whose ID
1294    is ARG.
1295 
1296    Does nothing if the program doesn't use Ada tasking.  */
1297 
1298 static void
1299 info_tasks_command (const char *arg, int from_tty)
1300 {
1301   struct ui_out *uiout = current_uiout;
1302 
1303   if (arg == NULL || *arg == '\0')
1304     print_ada_task_info (uiout, NULL, current_inferior ());
1305   else
1306     info_task (uiout, arg, current_inferior ());
1307 }
1308 
1309 /* Print a message telling the user id of the current task.
1310    This function assumes that tasking is in use in the inferior.  */
1311 
1312 static void
1313 display_current_task_id (void)
1314 {
1315   const int current_task = ada_get_task_number (inferior_thread ());
1316 
1317   if (current_task == 0)
1318     printf_filtered (_("[Current task is unknown]\n"));
1319   else
1320     {
1321       struct ada_tasks_inferior_data *data
1322 	= get_ada_tasks_inferior_data (current_inferior ());
1323       struct ada_task_info *task_info = &data->task_list[current_task - 1];
1324 
1325       printf_filtered (_("[Current task is %s]\n"),
1326 		       task_to_str (current_task, task_info).c_str ());
1327     }
1328 }
1329 
1330 /* Parse and evaluate TIDSTR into a task id, and try to switch to
1331    that task.  Print an error message if the task switch failed.  */
1332 
1333 static void
1334 task_command_1 (const char *taskno_str, int from_tty, struct inferior *inf)
1335 {
1336   const int taskno = value_as_long (parse_and_eval (taskno_str));
1337   struct ada_task_info *task_info;
1338   struct ada_tasks_inferior_data *data = get_ada_tasks_inferior_data (inf);
1339 
1340   if (taskno <= 0 || taskno > data->task_list.size ())
1341     error (_("Task ID %d not known.  Use the \"info tasks\" command to\n"
1342 	     "see the IDs of currently known tasks"), taskno);
1343   task_info = &data->task_list[taskno - 1];
1344 
1345   if (!ada_task_is_alive (task_info))
1346     error (_("Cannot switch to task %s: Task is no longer running"),
1347 	   task_to_str (taskno, task_info).c_str ());
1348 
1349   /* On some platforms, the thread list is not updated until the user
1350      performs a thread-related operation (by using the "info threads"
1351      command, for instance).  So this thread list may not be up to date
1352      when the user attempts this task switch.  Since we cannot switch
1353      to the thread associated to our task if GDB does not know about
1354      that thread, we need to make sure that any new threads gets added
1355      to the thread list.  */
1356   target_update_thread_list ();
1357 
1358   /* Verify that the ptid of the task we want to switch to is valid
1359      (in other words, a ptid that GDB knows about).  Otherwise, we will
1360      cause an assertion failure later on, when we try to determine
1361      the ptid associated thread_info data.  We should normally never
1362      encounter such an error, but the wrong ptid can actually easily be
1363      computed if target_get_ada_task_ptid has not been implemented for
1364      our target (yet).  Rather than cause an assertion error in that case,
1365      it's nicer for the user to just refuse to perform the task switch.  */
1366   thread_info *tp = find_thread_ptid (inf, task_info->ptid);
1367   if (tp == NULL)
1368     error (_("Unable to compute thread ID for task %s.\n"
1369 	     "Cannot switch to this task."),
1370 	   task_to_str (taskno, task_info).c_str ());
1371 
1372   switch_to_thread (tp);
1373   ada_find_printable_frame (get_selected_frame (NULL));
1374   printf_filtered (_("[Switching to task %s]\n"),
1375 		   task_to_str (taskno, task_info).c_str ());
1376   print_stack_frame (get_selected_frame (NULL),
1377 		     frame_relative_level (get_selected_frame (NULL)),
1378 		     SRC_AND_LOC, 1);
1379 }
1380 
1381 
1382 /* Print the ID of the current task if TASKNO_STR is empty or NULL.
1383    Otherwise, switch to the task indicated by TASKNO_STR.  */
1384 
1385 static void
1386 task_command (const char *taskno_str, int from_tty)
1387 {
1388   struct ui_out *uiout = current_uiout;
1389 
1390   if (ada_build_task_list () == 0)
1391     {
1392       uiout->message (_("Your application does not use any Ada tasks.\n"));
1393       return;
1394     }
1395 
1396   if (taskno_str == NULL || taskno_str[0] == '\0')
1397     display_current_task_id ();
1398   else
1399     task_command_1 (taskno_str, from_tty, current_inferior ());
1400 }
1401 
1402 /* Indicate that the given inferior's task list may have changed,
1403    so invalidate the cache.  */
1404 
1405 static void
1406 ada_task_list_changed (struct inferior *inf)
1407 {
1408   struct ada_tasks_inferior_data *data = get_ada_tasks_inferior_data (inf);
1409 
1410   data->task_list_valid_p = false;
1411 }
1412 
1413 /* Invalidate the per-program-space data.  */
1414 
1415 static void
1416 ada_tasks_invalidate_pspace_data (struct program_space *pspace)
1417 {
1418   get_ada_tasks_pspace_data (pspace)->initialized_p = 0;
1419 }
1420 
1421 /* Invalidate the per-inferior data.  */
1422 
1423 static void
1424 ada_tasks_invalidate_inferior_data (struct inferior *inf)
1425 {
1426   struct ada_tasks_inferior_data *data = get_ada_tasks_inferior_data (inf);
1427 
1428   data->known_tasks_kind = ADA_TASKS_UNKNOWN;
1429   data->task_list_valid_p = false;
1430 }
1431 
1432 /* The 'normal_stop' observer notification callback.  */
1433 
1434 static void
1435 ada_tasks_normal_stop_observer (struct bpstats *unused_args, int unused_args2)
1436 {
1437   /* The inferior has been resumed, and just stopped. This means that
1438      our task_list needs to be recomputed before it can be used again.  */
1439   ada_task_list_changed (current_inferior ());
1440 }
1441 
1442 /* A routine to be called when the objfiles have changed.  */
1443 
1444 static void
1445 ada_tasks_new_objfile_observer (struct objfile *objfile)
1446 {
1447   struct inferior *inf;
1448 
1449   /* Invalidate the relevant data in our program-space data.  */
1450 
1451   if (objfile == NULL)
1452     {
1453       /* All objfiles are being cleared, so we should clear all
1454 	 our caches for all program spaces.  */
1455       for (struct program_space *pspace : program_spaces)
1456 	ada_tasks_invalidate_pspace_data (pspace);
1457     }
1458   else
1459     {
1460       /* The associated program-space data might have changed after
1461 	 this objfile was added.  Invalidate all cached data.  */
1462       ada_tasks_invalidate_pspace_data (objfile->pspace);
1463     }
1464 
1465   /* Invalidate the per-inferior cache for all inferiors using
1466      this objfile (or, in other words, for all inferiors who have
1467      the same program-space as the objfile's program space).
1468      If all objfiles are being cleared (OBJFILE is NULL), then
1469      clear the caches for all inferiors.  */
1470 
1471   for (inf = inferior_list; inf != NULL; inf = inf->next)
1472     if (objfile == NULL || inf->pspace == objfile->pspace)
1473       ada_tasks_invalidate_inferior_data (inf);
1474 }
1475 
1476 void _initialize_tasks ();
1477 void
1478 _initialize_tasks ()
1479 {
1480   /* Attach various observers.  */
1481   gdb::observers::normal_stop.attach (ada_tasks_normal_stop_observer,
1482 				      "ada-tasks");
1483   gdb::observers::new_objfile.attach (ada_tasks_new_objfile_observer,
1484 				      "ada-tasks");
1485 
1486   /* Some new commands provided by this module.  */
1487   add_info ("tasks", info_tasks_command,
1488 	    _("Provide information about all known Ada tasks."));
1489   add_cmd ("task", class_run, task_command,
1490 	   _("Use this command to switch between Ada tasks.\n\
1491 Without argument, this command simply prints the current task ID."),
1492 	   &cmdlist);
1493 }
1494