]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/ada-lang.c
gdb: move store/extract integer functions to extract-store-integer.{c,h}
[thirdparty/binutils-gdb.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20
21 #include <ctype.h>
22 #include "extract-store-integer.h"
23 #include "gdbsupport/gdb_regex.h"
24 #include "frame.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "gdbcmd.h"
28 #include "expression.h"
29 #include "parser-defs.h"
30 #include "language.h"
31 #include "varobj.h"
32 #include "inferior.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "breakpoint.h"
36 #include "gdbcore.h"
37 #include "hashtab.h"
38 #include "gdbsupport/gdb_obstack.h"
39 #include "ada-lang.h"
40 #include "completer.h"
41 #include "ui-out.h"
42 #include "block.h"
43 #include "infcall.h"
44 #include "annotate.h"
45 #include "valprint.h"
46 #include "source.h"
47 #include "observable.h"
48 #include "stack.h"
49 #include "typeprint.h"
50 #include "namespace.h"
51 #include "cli/cli-style.h"
52 #include "cli/cli-decode.h"
53
54 #include "value.h"
55 #include "mi/mi-common.h"
56 #include "arch-utils.h"
57 #include "cli/cli-utils.h"
58 #include "gdbsupport/function-view.h"
59 #include "gdbsupport/byte-vector.h"
60 #include "gdbsupport/selftest.h"
61 #include <algorithm>
62 #include "ada-exp.h"
63 #include "charset.h"
64 #include "ax-gdb.h"
65
66 static struct type *desc_base_type (struct type *);
67
68 static struct type *desc_bounds_type (struct type *);
69
70 static struct value *desc_bounds (struct value *);
71
72 static int fat_pntr_bounds_bitpos (struct type *);
73
74 static int fat_pntr_bounds_bitsize (struct type *);
75
76 static struct type *desc_data_target_type (struct type *);
77
78 static struct value *desc_data (struct value *);
79
80 static int fat_pntr_data_bitpos (struct type *);
81
82 static int fat_pntr_data_bitsize (struct type *);
83
84 static struct value *desc_one_bound (struct value *, int, int);
85
86 static int desc_bound_bitpos (struct type *, int, int);
87
88 static int desc_bound_bitsize (struct type *, int, int);
89
90 static struct type *desc_index_type (struct type *, int);
91
92 static int desc_arity (struct type *);
93
94 static int ada_args_match (struct symbol *, struct value **, int);
95
96 static struct value *make_array_descriptor (struct type *, struct value *);
97
98 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
99 const struct block *,
100 const lookup_name_info &lookup_name,
101 domain_search_flags, struct objfile *);
102
103 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
104 const struct block *,
105 const lookup_name_info &lookup_name,
106 domain_search_flags, int, int *);
107
108 static int is_nonfunction (const std::vector<struct block_symbol> &);
109
110 static void add_defn_to_vec (std::vector<struct block_symbol> &,
111 struct symbol *,
112 const struct block *);
113
114 static int possible_user_operator_p (enum exp_opcode, struct value **);
115
116 static const char *ada_decoded_op_name (enum exp_opcode);
117
118 static int numeric_type_p (struct type *);
119
120 static int integer_type_p (struct type *);
121
122 static int scalar_type_p (struct type *);
123
124 static int discrete_type_p (struct type *);
125
126 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
127 int, int);
128
129 static struct type *ada_find_parallel_type_with_name (struct type *,
130 const char *);
131
132 static int is_dynamic_field (struct type *, int);
133
134 static struct type *to_fixed_variant_branch_type (struct type *,
135 const gdb_byte *,
136 CORE_ADDR, struct value *);
137
138 static struct type *to_fixed_array_type (struct type *, struct value *, int);
139
140 static struct type *to_fixed_range_type (struct type *, struct value *);
141
142 static struct type *to_static_fixed_type (struct type *);
143 static struct type *static_unwrap_type (struct type *type);
144
145 static struct value *unwrap_value (struct value *);
146
147 static struct type *constrained_packed_array_type (struct type *, long *);
148
149 static struct type *decode_constrained_packed_array_type (struct type *);
150
151 static long decode_packed_array_bitsize (struct type *);
152
153 static struct value *decode_constrained_packed_array (struct value *);
154
155 static int ada_is_unconstrained_packed_array_type (struct type *);
156
157 static struct value *value_subscript_packed (struct value *, int,
158 struct value **);
159
160 static struct value *coerce_unspec_val_to_type (struct value *,
161 struct type *);
162
163 static int lesseq_defined_than (struct symbol *, struct symbol *);
164
165 static int equiv_types (struct type *, struct type *);
166
167 static int is_name_suffix (const char *);
168
169 static int advance_wild_match (const char **, const char *, char);
170
171 static bool wild_match (const char *name, const char *patn);
172
173 static struct value *ada_coerce_ref (struct value *);
174
175 static LONGEST pos_atr (struct value *);
176
177 static struct value *val_atr (struct type *, LONGEST);
178
179 static struct value *ada_search_struct_field (const char *, struct value *, int,
180 struct type *);
181
182 static int find_struct_field (const char *, struct type *, int,
183 struct type **, int *, int *, int *, int *);
184
185 static int ada_resolve_function (std::vector<struct block_symbol> &,
186 struct value **, int, const char *,
187 struct type *, bool);
188
189 static int ada_is_direct_array_type (struct type *);
190
191 static struct value *ada_index_struct_field (int, struct value *, int,
192 struct type *);
193
194 static struct type *ada_find_any_type (const char *name);
195
196 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
197 (const lookup_name_info &lookup_name);
198
199 static int symbols_are_identical_enums
200 (const std::vector<struct block_symbol> &syms);
201
202 static int ada_identical_enum_types_p (struct type *type1, struct type *type2);
203 \f
204
205 /* The character set used for source files. */
206 static const char *ada_source_charset;
207
208 /* The string "UTF-8". This is here so we can check for the UTF-8
209 charset using == rather than strcmp. */
210 static const char ada_utf8[] = "UTF-8";
211
212 /* Each entry in the UTF-32 case-folding table is of this form. */
213 struct utf8_entry
214 {
215 /* The start and end, inclusive, of this range of codepoints. */
216 uint32_t start, end;
217 /* The delta to apply to get the upper-case form. 0 if this is
218 already upper-case. */
219 int upper_delta;
220 /* The delta to apply to get the lower-case form. 0 if this is
221 already lower-case. */
222 int lower_delta;
223
224 bool operator< (uint32_t val) const
225 {
226 return end < val;
227 }
228 };
229
230 static const utf8_entry ada_case_fold[] =
231 {
232 #include "ada-casefold.h"
233 };
234
235 \f
236
237 static const char ada_completer_word_break_characters[] =
238 #ifdef VMS
239 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
240 #else
241 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
242 #endif
243
244 /* The name of the symbol to use to get the name of the main subprogram. */
245 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
246 = "__gnat_ada_main_program_name";
247
248 /* Limit on the number of warnings to raise per expression evaluation. */
249 static int warning_limit = 2;
250
251 /* Number of warning messages issued; reset to 0 by cleanups after
252 expression evaluation. */
253 static int warnings_issued = 0;
254
255 static const char * const known_runtime_file_name_patterns[] = {
256 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
257 };
258
259 static const char * const known_auxiliary_function_name_patterns[] = {
260 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
261 };
262
263 /* Maintenance-related settings for this module. */
264
265 static struct cmd_list_element *maint_set_ada_cmdlist;
266 static struct cmd_list_element *maint_show_ada_cmdlist;
267
268 /* The "maintenance ada set/show ignore-descriptive-type" value. */
269
270 static bool ada_ignore_descriptive_types_p = false;
271
272 /* Inferior-specific data. */
273
274 /* Per-inferior data for this module. */
275
276 struct ada_inferior_data
277 {
278 /* The ada__tags__type_specific_data type, which is used when decoding
279 tagged types. With older versions of GNAT, this type was directly
280 accessible through a component ("tsd") in the object tag. But this
281 is no longer the case, so we cache it for each inferior. */
282 struct type *tsd_type = nullptr;
283
284 /* The exception_support_info data. This data is used to determine
285 how to implement support for Ada exception catchpoints in a given
286 inferior. */
287 const struct exception_support_info *exception_info = nullptr;
288 };
289
290 /* Our key to this module's inferior data. */
291 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
292
293 /* Return our inferior data for the given inferior (INF).
294
295 This function always returns a valid pointer to an allocated
296 ada_inferior_data structure. If INF's inferior data has not
297 been previously set, this functions creates a new one with all
298 fields set to zero, sets INF's inferior to it, and then returns
299 a pointer to that newly allocated ada_inferior_data. */
300
301 static struct ada_inferior_data *
302 get_ada_inferior_data (struct inferior *inf)
303 {
304 struct ada_inferior_data *data;
305
306 data = ada_inferior_data.get (inf);
307 if (data == NULL)
308 data = ada_inferior_data.emplace (inf);
309
310 return data;
311 }
312
313 /* Perform all necessary cleanups regarding our module's inferior data
314 that is required after the inferior INF just exited. */
315
316 static void
317 ada_inferior_exit (struct inferior *inf)
318 {
319 ada_inferior_data.clear (inf);
320 }
321
322
323 /* program-space-specific data. */
324
325 /* The result of a symbol lookup to be stored in our symbol cache. */
326
327 struct cache_entry
328 {
329 /* The name used to perform the lookup. */
330 std::string name;
331 /* The namespace used during the lookup. */
332 domain_search_flags domain = 0;
333 /* The symbol returned by the lookup, or NULL if no matching symbol
334 was found. */
335 struct symbol *sym = nullptr;
336 /* The block where the symbol was found, or NULL if no matching
337 symbol was found. */
338 const struct block *block = nullptr;
339 };
340
341 /* The symbol cache uses this type when searching. */
342
343 struct cache_entry_search
344 {
345 const char *name;
346 domain_search_flags domain;
347
348 hashval_t hash () const
349 {
350 /* This must agree with hash_cache_entry, below. */
351 return htab_hash_string (name);
352 }
353 };
354
355 /* Hash function for cache_entry. */
356
357 static hashval_t
358 hash_cache_entry (const void *v)
359 {
360 const cache_entry *entry = (const cache_entry *) v;
361 return htab_hash_string (entry->name.c_str ());
362 }
363
364 /* Equality function for cache_entry. */
365
366 static int
367 eq_cache_entry (const void *a, const void *b)
368 {
369 const cache_entry *entrya = (const cache_entry *) a;
370 const cache_entry_search *entryb = (const cache_entry_search *) b;
371
372 return entrya->domain == entryb->domain && entrya->name == entryb->name;
373 }
374
375 /* Key to our per-program-space data. */
376 static const registry<program_space>::key<htab, htab_deleter>
377 ada_pspace_data_handle;
378
379 /* Return this module's data for the given program space (PSPACE).
380 If not is found, add a zero'ed one now.
381
382 This function always returns a valid object. */
383
384 static htab_t
385 get_ada_pspace_data (struct program_space *pspace)
386 {
387 htab_t data = ada_pspace_data_handle.get (pspace);
388 if (data == nullptr)
389 {
390 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
391 htab_delete_entry<cache_entry>,
392 xcalloc, xfree);
393 ada_pspace_data_handle.set (pspace, data);
394 }
395
396 return data;
397 }
398
399 /* Utilities */
400
401 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
402 all typedef layers have been peeled. Otherwise, return TYPE.
403
404 Normally, we really expect a typedef type to only have 1 typedef layer.
405 In other words, we really expect the target type of a typedef type to be
406 a non-typedef type. This is particularly true for Ada units, because
407 the language does not have a typedef vs not-typedef distinction.
408 In that respect, the Ada compiler has been trying to eliminate as many
409 typedef definitions in the debugging information, since they generally
410 do not bring any extra information (we still use typedef under certain
411 circumstances related mostly to the GNAT encoding).
412
413 Unfortunately, we have seen situations where the debugging information
414 generated by the compiler leads to such multiple typedef layers. For
415 instance, consider the following example with stabs:
416
417 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
418 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
419
420 This is an error in the debugging information which causes type
421 pck__float_array___XUP to be defined twice, and the second time,
422 it is defined as a typedef of a typedef.
423
424 This is on the fringe of legality as far as debugging information is
425 concerned, and certainly unexpected. But it is easy to handle these
426 situations correctly, so we can afford to be lenient in this case. */
427
428 static struct type *
429 ada_typedef_target_type (struct type *type)
430 {
431 while (type->code () == TYPE_CODE_TYPEDEF)
432 type = type->target_type ();
433 return type;
434 }
435
436 /* Given DECODED_NAME a string holding a symbol name in its
437 decoded form (ie using the Ada dotted notation), returns
438 its unqualified name. */
439
440 static const char *
441 ada_unqualified_name (const char *decoded_name)
442 {
443 const char *result;
444
445 /* If the decoded name starts with '<', it means that the encoded
446 name does not follow standard naming conventions, and thus that
447 it is not your typical Ada symbol name. Trying to unqualify it
448 is therefore pointless and possibly erroneous. */
449 if (decoded_name[0] == '<')
450 return decoded_name;
451
452 result = strrchr (decoded_name, '.');
453 if (result != NULL)
454 result++; /* Skip the dot... */
455 else
456 result = decoded_name;
457
458 return result;
459 }
460
461 /* Return a string starting with '<', followed by STR, and '>'. */
462
463 static std::string
464 add_angle_brackets (const char *str)
465 {
466 return string_printf ("<%s>", str);
467 }
468
469 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
470 suffix of FIELD_NAME beginning "___". */
471
472 static int
473 field_name_match (const char *field_name, const char *target)
474 {
475 int len = strlen (target);
476
477 return
478 (strncmp (field_name, target, len) == 0
479 && (field_name[len] == '\0'
480 || (startswith (field_name + len, "___")
481 && strcmp (field_name + strlen (field_name) - 6,
482 "___XVN") != 0)));
483 }
484
485
486 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
487 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
488 and return its index. This function also handles fields whose name
489 have ___ suffixes because the compiler sometimes alters their name
490 by adding such a suffix to represent fields with certain constraints.
491 If the field could not be found, return a negative number if
492 MAYBE_MISSING is set. Otherwise raise an error. */
493
494 int
495 ada_get_field_index (const struct type *type, const char *field_name,
496 int maybe_missing)
497 {
498 int fieldno;
499 struct type *struct_type = check_typedef ((struct type *) type);
500
501 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
502 if (field_name_match (struct_type->field (fieldno).name (), field_name))
503 return fieldno;
504
505 if (!maybe_missing)
506 error (_("Unable to find field %s in struct %s. Aborting"),
507 field_name, struct_type->name ());
508
509 return -1;
510 }
511
512 /* The length of the prefix of NAME prior to any "___" suffix. */
513
514 int
515 ada_name_prefix_len (const char *name)
516 {
517 if (name == NULL)
518 return 0;
519 else
520 {
521 const char *p = strstr (name, "___");
522
523 if (p == NULL)
524 return strlen (name);
525 else
526 return p - name;
527 }
528 }
529
530 /* Return non-zero if SUFFIX is a suffix of STR.
531 Return zero if STR is null. */
532
533 static int
534 is_suffix (const char *str, const char *suffix)
535 {
536 int len1, len2;
537
538 if (str == NULL)
539 return 0;
540 len1 = strlen (str);
541 len2 = strlen (suffix);
542 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
543 }
544
545 /* The contents of value VAL, treated as a value of type TYPE. The
546 result is an lval in memory if VAL is. */
547
548 static struct value *
549 coerce_unspec_val_to_type (struct value *val, struct type *type)
550 {
551 type = ada_check_typedef (type);
552 if (val->type () == type)
553 return val;
554 else
555 {
556 struct value *result;
557
558 if (val->optimized_out ())
559 result = value::allocate_optimized_out (type);
560 else if (val->lazy ()
561 /* Be careful not to make a lazy not_lval value. */
562 || (val->lval () != not_lval
563 && type->length () > val->type ()->length ()))
564 result = value::allocate_lazy (type);
565 else
566 {
567 result = value::allocate (type);
568 val->contents_copy (result, 0, 0, type->length ());
569 }
570 result->set_component_location (val);
571 result->set_bitsize (val->bitsize ());
572 result->set_bitpos (val->bitpos ());
573 if (result->lval () == lval_memory)
574 result->set_address (val->address ());
575 return result;
576 }
577 }
578
579 static const gdb_byte *
580 cond_offset_host (const gdb_byte *valaddr, long offset)
581 {
582 if (valaddr == NULL)
583 return NULL;
584 else
585 return valaddr + offset;
586 }
587
588 static CORE_ADDR
589 cond_offset_target (CORE_ADDR address, long offset)
590 {
591 if (address == 0)
592 return 0;
593 else
594 return address + offset;
595 }
596
597 /* Issue a warning (as for the definition of warning in utils.c, but
598 with exactly one argument rather than ...), unless the limit on the
599 number of warnings has passed during the evaluation of the current
600 expression. */
601
602 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
603 provided by "complaint". */
604 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
605
606 static void
607 lim_warning (const char *format, ...)
608 {
609 va_list args;
610
611 va_start (args, format);
612 warnings_issued += 1;
613 if (warnings_issued <= warning_limit)
614 vwarning (format, args);
615
616 va_end (args);
617 }
618
619 /* Maximum value of a SIZE-byte signed integer type. */
620 static LONGEST
621 max_of_size (int size)
622 {
623 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
624
625 return top_bit | (top_bit - 1);
626 }
627
628 /* Minimum value of a SIZE-byte signed integer type. */
629 static LONGEST
630 min_of_size (int size)
631 {
632 return -max_of_size (size) - 1;
633 }
634
635 /* Maximum value of a SIZE-byte unsigned integer type. */
636 static ULONGEST
637 umax_of_size (int size)
638 {
639 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
640
641 return top_bit | (top_bit - 1);
642 }
643
644 /* Maximum value of integral type T, as a signed quantity. */
645 static LONGEST
646 max_of_type (struct type *t)
647 {
648 if (t->is_unsigned ())
649 return (LONGEST) umax_of_size (t->length ());
650 else
651 return max_of_size (t->length ());
652 }
653
654 /* Minimum value of integral type T, as a signed quantity. */
655 static LONGEST
656 min_of_type (struct type *t)
657 {
658 if (t->is_unsigned ())
659 return 0;
660 else
661 return min_of_size (t->length ());
662 }
663
664 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
665 LONGEST
666 ada_discrete_type_high_bound (struct type *type)
667 {
668 type = resolve_dynamic_type (type, {}, 0);
669 switch (type->code ())
670 {
671 case TYPE_CODE_RANGE:
672 {
673 const dynamic_prop &high = type->bounds ()->high;
674
675 if (high.is_constant ())
676 return high.const_val ();
677 else
678 {
679 gdb_assert (!high.is_available ());
680
681 /* This happens when trying to evaluate a type's dynamic bound
682 without a live target. There is nothing relevant for us to
683 return here, so return 0. */
684 return 0;
685 }
686 }
687 case TYPE_CODE_ENUM:
688 return type->field (type->num_fields () - 1).loc_enumval ();
689 case TYPE_CODE_BOOL:
690 return 1;
691 case TYPE_CODE_CHAR:
692 case TYPE_CODE_INT:
693 return max_of_type (type);
694 default:
695 error (_("Unexpected type in ada_discrete_type_high_bound."));
696 }
697 }
698
699 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
700 LONGEST
701 ada_discrete_type_low_bound (struct type *type)
702 {
703 type = resolve_dynamic_type (type, {}, 0);
704 switch (type->code ())
705 {
706 case TYPE_CODE_RANGE:
707 {
708 const dynamic_prop &low = type->bounds ()->low;
709
710 if (low.is_constant ())
711 return low.const_val ();
712 else
713 {
714 gdb_assert (!low.is_available ());
715
716 /* This happens when trying to evaluate a type's dynamic bound
717 without a live target. There is nothing relevant for us to
718 return here, so return 0. */
719 return 0;
720 }
721 }
722 case TYPE_CODE_ENUM:
723 return type->field (0).loc_enumval ();
724 case TYPE_CODE_BOOL:
725 return 0;
726 case TYPE_CODE_CHAR:
727 case TYPE_CODE_INT:
728 return min_of_type (type);
729 default:
730 error (_("Unexpected type in ada_discrete_type_low_bound."));
731 }
732 }
733
734 /* The identity on non-range types. For range types, the underlying
735 non-range scalar type. */
736
737 static struct type *
738 get_base_type (struct type *type)
739 {
740 while (type != NULL && type->code () == TYPE_CODE_RANGE)
741 {
742 if (type == type->target_type () || type->target_type () == NULL)
743 return type;
744 type = type->target_type ();
745 }
746 return type;
747 }
748
749 /* Return a decoded version of the given VALUE. This means returning
750 a value whose type is obtained by applying all the GNAT-specific
751 encodings, making the resulting type a static but standard description
752 of the initial type. */
753
754 struct value *
755 ada_get_decoded_value (struct value *value)
756 {
757 struct type *type = ada_check_typedef (value->type ());
758
759 if (ada_is_array_descriptor_type (type)
760 || (ada_is_constrained_packed_array_type (type)
761 && type->code () != TYPE_CODE_PTR))
762 {
763 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
764 value = ada_coerce_to_simple_array_ptr (value);
765 else
766 value = ada_coerce_to_simple_array (value);
767 }
768 else
769 value = ada_to_fixed_value (value);
770
771 return value;
772 }
773
774 /* Same as ada_get_decoded_value, but with the given TYPE.
775 Because there is no associated actual value for this type,
776 the resulting type might be a best-effort approximation in
777 the case of dynamic types. */
778
779 struct type *
780 ada_get_decoded_type (struct type *type)
781 {
782 type = to_static_fixed_type (type);
783 if (ada_is_constrained_packed_array_type (type))
784 type = ada_coerce_to_simple_array_type (type);
785 return type;
786 }
787
788 \f
789
790 /* Language Selection */
791
792 /* If the main procedure is written in Ada, then return its name.
793 The result is good until the next call. Return NULL if the main
794 procedure doesn't appear to be in Ada. */
795
796 const char *
797 ada_main_name ()
798 {
799 struct bound_minimal_symbol msym;
800 static gdb::unique_xmalloc_ptr<char> main_program_name;
801
802 /* For Ada, the name of the main procedure is stored in a specific
803 string constant, generated by the binder. Look for that symbol,
804 extract its address, and then read that string. If we didn't find
805 that string, then most probably the main procedure is not written
806 in Ada. */
807 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
808
809 if (msym.minsym != NULL)
810 {
811 CORE_ADDR main_program_name_addr = msym.value_address ();
812 if (main_program_name_addr == 0)
813 error (_("Invalid address for Ada main program name."));
814
815 /* Force trust_readonly, because we always want to fetch this
816 string from the executable, not from inferior memory. If the
817 user changes the exec-file and invokes "start", we want to
818 pick the "main" from the new executable, not one that may
819 come from the still-live inferior. */
820 scoped_restore save_trust_readonly
821 = make_scoped_restore (&trust_readonly, true);
822 main_program_name = target_read_string (main_program_name_addr, 1024);
823 return main_program_name.get ();
824 }
825
826 /* The main procedure doesn't seem to be in Ada. */
827 return NULL;
828 }
829 \f
830 /* Symbols */
831
832 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
833 of NULLs. */
834
835 const struct ada_opname_map ada_opname_table[] = {
836 {"Oadd", "\"+\"", BINOP_ADD},
837 {"Osubtract", "\"-\"", BINOP_SUB},
838 {"Omultiply", "\"*\"", BINOP_MUL},
839 {"Odivide", "\"/\"", BINOP_DIV},
840 {"Omod", "\"mod\"", BINOP_MOD},
841 {"Orem", "\"rem\"", BINOP_REM},
842 {"Oexpon", "\"**\"", BINOP_EXP},
843 {"Olt", "\"<\"", BINOP_LESS},
844 {"Ole", "\"<=\"", BINOP_LEQ},
845 {"Ogt", "\">\"", BINOP_GTR},
846 {"Oge", "\">=\"", BINOP_GEQ},
847 {"Oeq", "\"=\"", BINOP_EQUAL},
848 {"One", "\"/=\"", BINOP_NOTEQUAL},
849 {"Oand", "\"and\"", BINOP_BITWISE_AND},
850 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
851 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
852 {"Oconcat", "\"&\"", BINOP_CONCAT},
853 {"Oabs", "\"abs\"", UNOP_ABS},
854 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
855 {"Oadd", "\"+\"", UNOP_PLUS},
856 {"Osubtract", "\"-\"", UNOP_NEG},
857 {NULL, NULL}
858 };
859
860 /* If STR is a decoded version of a compiler-provided suffix (like the
861 "[cold]" in "symbol[cold]"), return true. Otherwise, return
862 false. */
863
864 static bool
865 is_compiler_suffix (const char *str)
866 {
867 gdb_assert (*str == '[');
868 ++str;
869 while (*str != '\0' && isalpha (*str))
870 ++str;
871 /* We accept a missing "]" in order to support completion. */
872 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
873 }
874
875 /* Append a non-ASCII character to RESULT. */
876 static void
877 append_hex_encoded (std::string &result, uint32_t one_char)
878 {
879 if (one_char <= 0xff)
880 {
881 result.append ("U");
882 result.append (phex (one_char, 1));
883 }
884 else if (one_char <= 0xffff)
885 {
886 result.append ("W");
887 result.append (phex (one_char, 2));
888 }
889 else
890 {
891 result.append ("WW");
892 result.append (phex (one_char, 4));
893 }
894 }
895
896 /* Return a string that is a copy of the data in STORAGE, with
897 non-ASCII characters replaced by the appropriate hex encoding. A
898 template is used because, for UTF-8, we actually want to work with
899 UTF-32 codepoints. */
900 template<typename T>
901 std::string
902 copy_and_hex_encode (struct obstack *storage)
903 {
904 const T *chars = (T *) obstack_base (storage);
905 int num_chars = obstack_object_size (storage) / sizeof (T);
906 std::string result;
907 for (int i = 0; i < num_chars; ++i)
908 {
909 if (chars[i] <= 0x7f)
910 {
911 /* The host character set has to be a superset of ASCII, as
912 are all the other character sets we can use. */
913 result.push_back (chars[i]);
914 }
915 else
916 append_hex_encoded (result, chars[i]);
917 }
918 return result;
919 }
920
921 /* The "encoded" form of DECODED, according to GNAT conventions. If
922 THROW_ERRORS, throw an error if invalid operator name is found.
923 Otherwise, return the empty string in that case. */
924
925 static std::string
926 ada_encode_1 (const char *decoded, bool throw_errors)
927 {
928 if (decoded == NULL)
929 return {};
930
931 std::string encoding_buffer;
932 bool saw_non_ascii = false;
933 for (const char *p = decoded; *p != '\0'; p += 1)
934 {
935 if ((*p & 0x80) != 0)
936 saw_non_ascii = true;
937
938 if (*p == '.')
939 encoding_buffer.append ("__");
940 else if (*p == '[' && is_compiler_suffix (p))
941 {
942 encoding_buffer = encoding_buffer + "." + (p + 1);
943 if (encoding_buffer.back () == ']')
944 encoding_buffer.pop_back ();
945 break;
946 }
947 else if (*p == '"')
948 {
949 const struct ada_opname_map *mapping;
950
951 for (mapping = ada_opname_table;
952 mapping->encoded != NULL
953 && !startswith (p, mapping->decoded); mapping += 1)
954 ;
955 if (mapping->encoded == NULL)
956 {
957 if (throw_errors)
958 error (_("invalid Ada operator name: %s"), p);
959 else
960 return {};
961 }
962 encoding_buffer.append (mapping->encoded);
963 break;
964 }
965 else
966 encoding_buffer.push_back (*p);
967 }
968
969 /* If a non-ASCII character is seen, we must convert it to the
970 appropriate hex form. As this is more expensive, we keep track
971 of whether it is even necessary. */
972 if (saw_non_ascii)
973 {
974 auto_obstack storage;
975 bool is_utf8 = ada_source_charset == ada_utf8;
976 try
977 {
978 convert_between_encodings
979 (host_charset (),
980 is_utf8 ? HOST_UTF32 : ada_source_charset,
981 (const gdb_byte *) encoding_buffer.c_str (),
982 encoding_buffer.length (), 1,
983 &storage, translit_none);
984 }
985 catch (const gdb_exception &)
986 {
987 static bool warned = false;
988
989 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
990 might like to know why. */
991 if (!warned)
992 {
993 warned = true;
994 warning (_("charset conversion failure for '%s'.\n"
995 "You may have the wrong value for 'set ada source-charset'."),
996 encoding_buffer.c_str ());
997 }
998
999 /* We don't try to recover from errors. */
1000 return encoding_buffer;
1001 }
1002
1003 if (is_utf8)
1004 return copy_and_hex_encode<uint32_t> (&storage);
1005 return copy_and_hex_encode<gdb_byte> (&storage);
1006 }
1007
1008 return encoding_buffer;
1009 }
1010
1011 /* Find the entry for C in the case-folding table. Return nullptr if
1012 the entry does not cover C. */
1013 static const utf8_entry *
1014 find_case_fold_entry (uint32_t c)
1015 {
1016 auto iter = std::lower_bound (std::begin (ada_case_fold),
1017 std::end (ada_case_fold),
1018 c);
1019 if (iter == std::end (ada_case_fold)
1020 || c < iter->start
1021 || c > iter->end)
1022 return nullptr;
1023 return &*iter;
1024 }
1025
1026 /* Return NAME folded to lower case, or, if surrounded by single
1027 quotes, unfolded, but with the quotes stripped away. If
1028 THROW_ON_ERROR is true, encoding failures will throw an exception
1029 rather than emitting a warning. Result good to next call. */
1030
1031 static const char *
1032 ada_fold_name (std::string_view name, bool throw_on_error = false)
1033 {
1034 static std::string fold_storage;
1035
1036 if (!name.empty () && name[0] == '\'')
1037 fold_storage = name.substr (1, name.size () - 2);
1038 else
1039 {
1040 /* Why convert to UTF-32 and implement our own case-folding,
1041 rather than convert to wchar_t and use the platform's
1042 functions? I'm glad you asked.
1043
1044 The main problem is that GNAT implements an unusual rule for
1045 case folding. For ASCII letters, letters in single-byte
1046 encodings (such as ISO-8859-*), and Unicode letters that fit
1047 in a single byte (i.e., code point is <= 0xff), the letter is
1048 folded to lower case. Other Unicode letters are folded to
1049 upper case.
1050
1051 This rule means that the code must be able to examine the
1052 value of the character. And, some hosts do not use Unicode
1053 for wchar_t, so examining the value of such characters is
1054 forbidden. */
1055 auto_obstack storage;
1056 try
1057 {
1058 convert_between_encodings
1059 (host_charset (), HOST_UTF32,
1060 (const gdb_byte *) name.data (),
1061 name.length (), 1,
1062 &storage, translit_none);
1063 }
1064 catch (const gdb_exception &)
1065 {
1066 if (throw_on_error)
1067 throw;
1068
1069 static bool warned = false;
1070
1071 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1072 might like to know why. */
1073 if (!warned)
1074 {
1075 warned = true;
1076 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1077 "This normally should not happen, please file a bug report."),
1078 std::string (name).c_str (), host_charset ());
1079 }
1080
1081 /* We don't try to recover from errors; just return the
1082 original string. */
1083 fold_storage = name;
1084 return fold_storage.c_str ();
1085 }
1086
1087 bool is_utf8 = ada_source_charset == ada_utf8;
1088 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1089 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1090 for (int i = 0; i < num_chars; ++i)
1091 {
1092 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1093 if (entry != nullptr)
1094 {
1095 uint32_t low = chars[i] + entry->lower_delta;
1096 if (!is_utf8 || low <= 0xff)
1097 chars[i] = low;
1098 else
1099 chars[i] = chars[i] + entry->upper_delta;
1100 }
1101 }
1102
1103 /* Now convert back to ordinary characters. */
1104 auto_obstack reconverted;
1105 try
1106 {
1107 convert_between_encodings (HOST_UTF32,
1108 host_charset (),
1109 (const gdb_byte *) chars,
1110 num_chars * sizeof (uint32_t),
1111 sizeof (uint32_t),
1112 &reconverted,
1113 translit_none);
1114 obstack_1grow (&reconverted, '\0');
1115 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1116 }
1117 catch (const gdb_exception &)
1118 {
1119 if (throw_on_error)
1120 throw;
1121
1122 static bool warned = false;
1123
1124 /* Converting back from UTF-32 shouldn't normally fail, but
1125 there are some host encodings without upper/lower
1126 equivalence. */
1127 if (!warned)
1128 {
1129 warned = true;
1130 warning (_("could not convert the lower-cased variant of '%s'\n"
1131 "from UTF-32 to the host encoding (%s)."),
1132 std::string (name).c_str (), host_charset ());
1133 }
1134
1135 /* We don't try to recover from errors; just return the
1136 original string. */
1137 fold_storage = name;
1138 }
1139 }
1140
1141 return fold_storage.c_str ();
1142 }
1143
1144 /* The "encoded" form of DECODED, according to GNAT conventions. If
1145 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1146 with <...> quoting are not folded in any case. */
1147
1148 std::string
1149 ada_encode (const char *decoded, bool fold)
1150 {
1151 if (fold && decoded[0] != '<')
1152 decoded = ada_fold_name (decoded);
1153 return ada_encode_1 (decoded, true);
1154 }
1155
1156 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1157
1158 static int
1159 is_lower_alphanum (const char c)
1160 {
1161 return (isdigit (c) || (isalpha (c) && islower (c)));
1162 }
1163
1164 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1165 This function saves in LEN the length of that same symbol name but
1166 without either of these suffixes:
1167 . .{DIGIT}+
1168 . ${DIGIT}+
1169 . ___{DIGIT}+
1170 . __{DIGIT}+.
1171
1172 These are suffixes introduced by the compiler for entities such as
1173 nested subprogram for instance, in order to avoid name clashes.
1174 They do not serve any purpose for the debugger. */
1175
1176 static void
1177 ada_remove_trailing_digits (const char *encoded, int *len)
1178 {
1179 if (*len > 1 && isdigit (encoded[*len - 1]))
1180 {
1181 int i = *len - 2;
1182
1183 while (i > 0 && isdigit (encoded[i]))
1184 i--;
1185 if (i >= 0 && encoded[i] == '.')
1186 *len = i;
1187 else if (i >= 0 && encoded[i] == '$')
1188 *len = i;
1189 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1190 *len = i - 2;
1191 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1192 *len = i - 1;
1193 }
1194 }
1195
1196 /* Remove the suffix introduced by the compiler for protected object
1197 subprograms. */
1198
1199 static void
1200 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1201 {
1202 /* Remove trailing N. */
1203
1204 /* Protected entry subprograms are broken into two
1205 separate subprograms: The first one is unprotected, and has
1206 a 'N' suffix; the second is the protected version, and has
1207 the 'P' suffix. The second calls the first one after handling
1208 the protection. Since the P subprograms are internally generated,
1209 we leave these names undecoded, giving the user a clue that this
1210 entity is internal. */
1211
1212 if (*len > 1
1213 && encoded[*len - 1] == 'N'
1214 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1215 *len = *len - 1;
1216 }
1217
1218 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1219 then update *LEN to remove the suffix and return the offset of the
1220 character just past the ".". Otherwise, return -1. */
1221
1222 static int
1223 remove_compiler_suffix (const char *encoded, int *len)
1224 {
1225 int offset = *len - 1;
1226 while (offset > 0 && isalpha (encoded[offset]))
1227 --offset;
1228 if (offset > 0 && encoded[offset] == '.')
1229 {
1230 *len = offset;
1231 return offset + 1;
1232 }
1233 return -1;
1234 }
1235
1236 /* Convert an ASCII hex string to a number. Reads exactly N
1237 characters from STR. Returns true on success, false if one of the
1238 digits was not a hex digit. */
1239 static bool
1240 convert_hex (const char *str, int n, uint32_t *out)
1241 {
1242 uint32_t result = 0;
1243
1244 for (int i = 0; i < n; ++i)
1245 {
1246 if (!isxdigit (str[i]))
1247 return false;
1248 result <<= 4;
1249 result |= fromhex (str[i]);
1250 }
1251
1252 *out = result;
1253 return true;
1254 }
1255
1256 /* Convert a wide character from its ASCII hex representation in STR
1257 (consisting of exactly N characters) to the host encoding,
1258 appending the resulting bytes to OUT. If N==2 and the Ada source
1259 charset is not UTF-8, then hex refers to an encoding in the
1260 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1261 Return false and do not modify OUT on conversion failure. */
1262 static bool
1263 convert_from_hex_encoded (std::string &out, const char *str, int n)
1264 {
1265 uint32_t value;
1266
1267 if (!convert_hex (str, n, &value))
1268 return false;
1269 try
1270 {
1271 auto_obstack bytes;
1272 /* In the 'U' case, the hex digits encode the character in the
1273 Ada source charset. However, if the source charset is UTF-8,
1274 this really means it is a single-byte UTF-32 character. */
1275 if (n == 2 && ada_source_charset != ada_utf8)
1276 {
1277 gdb_byte one_char = (gdb_byte) value;
1278
1279 convert_between_encodings (ada_source_charset, host_charset (),
1280 &one_char,
1281 sizeof (one_char), sizeof (one_char),
1282 &bytes, translit_none);
1283 }
1284 else
1285 convert_between_encodings (HOST_UTF32, host_charset (),
1286 (const gdb_byte *) &value,
1287 sizeof (value), sizeof (value),
1288 &bytes, translit_none);
1289 obstack_1grow (&bytes, '\0');
1290 out.append ((const char *) obstack_base (&bytes));
1291 }
1292 catch (const gdb_exception &)
1293 {
1294 /* On failure, the caller will just let the encoded form
1295 through, which seems basically reasonable. */
1296 return false;
1297 }
1298
1299 return true;
1300 }
1301
1302 /* See ada-lang.h. */
1303
1304 std::string
1305 ada_decode (const char *encoded, bool wrap, bool operators, bool wide)
1306 {
1307 int i;
1308 int len0;
1309 const char *p;
1310 int at_start_name;
1311 std::string decoded;
1312 int suffix = -1;
1313
1314 /* With function descriptors on PPC64, the value of a symbol named
1315 ".FN", if it exists, is the entry point of the function "FN". */
1316 if (encoded[0] == '.')
1317 encoded += 1;
1318
1319 /* The name of the Ada main procedure starts with "_ada_".
1320 This prefix is not part of the decoded name, so skip this part
1321 if we see this prefix. */
1322 if (startswith (encoded, "_ada_"))
1323 encoded += 5;
1324 /* The "___ghost_" prefix is used for ghost entities. Normally
1325 these aren't preserved but when they are, it's useful to see
1326 them. */
1327 if (startswith (encoded, "___ghost_"))
1328 encoded += 9;
1329
1330 /* If the name starts with '_', then it is not a properly encoded
1331 name, so do not attempt to decode it. Similarly, if the name
1332 starts with '<', the name should not be decoded. */
1333 if (encoded[0] == '_' || encoded[0] == '<')
1334 goto Suppress;
1335
1336 len0 = strlen (encoded);
1337
1338 suffix = remove_compiler_suffix (encoded, &len0);
1339
1340 ada_remove_trailing_digits (encoded, &len0);
1341 ada_remove_po_subprogram_suffix (encoded, &len0);
1342
1343 /* Remove the ___X.* suffix if present. Do not forget to verify that
1344 the suffix is located before the current "end" of ENCODED. We want
1345 to avoid re-matching parts of ENCODED that have previously been
1346 marked as discarded (by decrementing LEN0). */
1347 p = strstr (encoded, "___");
1348 if (p != NULL && p - encoded < len0 - 3)
1349 {
1350 if (p[3] == 'X')
1351 len0 = p - encoded;
1352 else
1353 goto Suppress;
1354 }
1355
1356 /* Remove any trailing TKB suffix. It tells us that this symbol
1357 is for the body of a task, but that information does not actually
1358 appear in the decoded name. */
1359
1360 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1361 len0 -= 3;
1362
1363 /* Remove any trailing TB suffix. The TB suffix is slightly different
1364 from the TKB suffix because it is used for non-anonymous task
1365 bodies. */
1366
1367 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1368 len0 -= 2;
1369
1370 /* Remove trailing "B" suffixes. */
1371 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1372
1373 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1374 len0 -= 1;
1375
1376 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1377
1378 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1379 {
1380 i = len0 - 2;
1381 while ((i >= 0 && isdigit (encoded[i]))
1382 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1383 i -= 1;
1384 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1385 len0 = i - 1;
1386 else if (i >= 0 && encoded[i] == '$')
1387 len0 = i;
1388 }
1389
1390 /* The first few characters that are not alphabetic are not part
1391 of any encoding we use, so we can copy them over verbatim. */
1392
1393 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1394 decoded.push_back (encoded[i]);
1395
1396 at_start_name = 1;
1397 while (i < len0)
1398 {
1399 /* Is this a symbol function? */
1400 if (operators && at_start_name && encoded[i] == 'O')
1401 {
1402 int k;
1403
1404 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1405 {
1406 int op_len = strlen (ada_opname_table[k].encoded);
1407 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1408 op_len - 1) == 0)
1409 && !isalnum (encoded[i + op_len]))
1410 {
1411 decoded.append (ada_opname_table[k].decoded);
1412 at_start_name = 0;
1413 i += op_len;
1414 break;
1415 }
1416 }
1417 if (ada_opname_table[k].encoded != NULL)
1418 continue;
1419 }
1420 at_start_name = 0;
1421
1422 /* Replace "TK__" with "__", which will eventually be translated
1423 into "." (just below). */
1424
1425 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1426 i += 2;
1427
1428 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1429 be translated into "." (just below). These are internal names
1430 generated for anonymous blocks inside which our symbol is nested. */
1431
1432 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1433 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1434 && isdigit (encoded [i+4]))
1435 {
1436 int k = i + 5;
1437
1438 while (k < len0 && isdigit (encoded[k]))
1439 k++; /* Skip any extra digit. */
1440
1441 /* Double-check that the "__B_{DIGITS}+" sequence we found
1442 is indeed followed by "__". */
1443 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1444 i = k;
1445 }
1446
1447 /* Remove _E{DIGITS}+[sb] */
1448
1449 /* Just as for protected object subprograms, there are 2 categories
1450 of subprograms created by the compiler for each entry. The first
1451 one implements the actual entry code, and has a suffix following
1452 the convention above; the second one implements the barrier and
1453 uses the same convention as above, except that the 'E' is replaced
1454 by a 'B'.
1455
1456 Just as above, we do not decode the name of barrier functions
1457 to give the user a clue that the code he is debugging has been
1458 internally generated. */
1459
1460 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1461 && isdigit (encoded[i+2]))
1462 {
1463 int k = i + 3;
1464
1465 while (k < len0 && isdigit (encoded[k]))
1466 k++;
1467
1468 if (k < len0
1469 && (encoded[k] == 'b' || encoded[k] == 's'))
1470 {
1471 k++;
1472 /* Just as an extra precaution, make sure that if this
1473 suffix is followed by anything else, it is a '_'.
1474 Otherwise, we matched this sequence by accident. */
1475 if (k == len0
1476 || (k < len0 && encoded[k] == '_'))
1477 i = k;
1478 }
1479 }
1480
1481 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1482 the GNAT front-end in protected object subprograms. */
1483
1484 if (i < len0 + 3
1485 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1486 {
1487 /* Backtrack a bit up until we reach either the begining of
1488 the encoded name, or "__". Make sure that we only find
1489 digits or lowercase characters. */
1490 const char *ptr = encoded + i - 1;
1491
1492 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1493 ptr--;
1494 if (ptr < encoded
1495 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1496 i++;
1497 }
1498
1499 if (wide && i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1500 {
1501 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1502 {
1503 i += 3;
1504 continue;
1505 }
1506 }
1507 else if (wide && i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1508 {
1509 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1510 {
1511 i += 5;
1512 continue;
1513 }
1514 }
1515 else if (wide && i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1516 && isxdigit (encoded[i + 2]))
1517 {
1518 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1519 {
1520 i += 10;
1521 continue;
1522 }
1523 }
1524
1525 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1526 {
1527 /* This is a X[bn]* sequence not separated from the previous
1528 part of the name with a non-alpha-numeric character (in other
1529 words, immediately following an alpha-numeric character), then
1530 verify that it is placed at the end of the encoded name. If
1531 not, then the encoding is not valid and we should abort the
1532 decoding. Otherwise, just skip it, it is used in body-nested
1533 package names. */
1534 do
1535 i += 1;
1536 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1537 if (i < len0)
1538 goto Suppress;
1539 }
1540 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1541 {
1542 /* Replace '__' by '.'. */
1543 decoded.push_back ('.');
1544 at_start_name = 1;
1545 i += 2;
1546 }
1547 else
1548 {
1549 /* It's a character part of the decoded name, so just copy it
1550 over. */
1551 decoded.push_back (encoded[i]);
1552 i += 1;
1553 }
1554 }
1555
1556 /* Decoded names should never contain any uppercase character.
1557 Double-check this, and abort the decoding if we find one. */
1558
1559 if (operators)
1560 {
1561 for (i = 0; i < decoded.length(); ++i)
1562 if (isupper (decoded[i]) || decoded[i] == ' ')
1563 goto Suppress;
1564 }
1565
1566 /* If the compiler added a suffix, append it now. */
1567 if (suffix >= 0)
1568 decoded = decoded + "[" + &encoded[suffix] + "]";
1569
1570 return decoded;
1571
1572 Suppress:
1573 if (!wrap)
1574 return {};
1575
1576 if (encoded[0] == '<')
1577 decoded = encoded;
1578 else
1579 decoded = '<' + std::string(encoded) + '>';
1580 return decoded;
1581 }
1582
1583 #ifdef GDB_SELF_TEST
1584
1585 static void
1586 ada_decode_tests ()
1587 {
1588 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1589 result does not really matter very much. */
1590 SELF_CHECK (ada_decode ("44") == "44");
1591 }
1592
1593 #endif
1594
1595 /* Table for keeping permanent unique copies of decoded names. Once
1596 allocated, names in this table are never released. While this is a
1597 storage leak, it should not be significant unless there are massive
1598 changes in the set of decoded names in successive versions of a
1599 symbol table loaded during a single session. */
1600 static struct htab *decoded_names_store;
1601
1602 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1603 in the language-specific part of GSYMBOL, if it has not been
1604 previously computed. Tries to save the decoded name in the same
1605 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1606 in any case, the decoded symbol has a lifetime at least that of
1607 GSYMBOL).
1608 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1609 const, but nevertheless modified to a semantically equivalent form
1610 when a decoded name is cached in it. */
1611
1612 const char *
1613 ada_decode_symbol (const struct general_symbol_info *arg)
1614 {
1615 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1616 const char **resultp =
1617 &gsymbol->language_specific.demangled_name;
1618
1619 if (!gsymbol->ada_mangled)
1620 {
1621 std::string decoded = ada_decode (gsymbol->linkage_name ());
1622 struct obstack *obstack = gsymbol->language_specific.obstack;
1623
1624 gsymbol->ada_mangled = 1;
1625
1626 if (obstack != NULL)
1627 *resultp = obstack_strdup (obstack, decoded.c_str ());
1628 else
1629 {
1630 /* Sometimes, we can't find a corresponding objfile, in
1631 which case, we put the result on the heap. Since we only
1632 decode when needed, we hope this usually does not cause a
1633 significant memory leak (FIXME). */
1634
1635 char **slot = (char **) htab_find_slot (decoded_names_store,
1636 decoded.c_str (), INSERT);
1637
1638 if (*slot == NULL)
1639 *slot = xstrdup (decoded.c_str ());
1640 *resultp = *slot;
1641 }
1642 }
1643
1644 return *resultp;
1645 }
1646
1647 \f
1648
1649 /* Arrays */
1650
1651 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1652 generated by the GNAT compiler to describe the index type used
1653 for each dimension of an array, check whether it follows the latest
1654 known encoding. If not, fix it up to conform to the latest encoding.
1655 Otherwise, do nothing. This function also does nothing if
1656 INDEX_DESC_TYPE is NULL.
1657
1658 The GNAT encoding used to describe the array index type evolved a bit.
1659 Initially, the information would be provided through the name of each
1660 field of the structure type only, while the type of these fields was
1661 described as unspecified and irrelevant. The debugger was then expected
1662 to perform a global type lookup using the name of that field in order
1663 to get access to the full index type description. Because these global
1664 lookups can be very expensive, the encoding was later enhanced to make
1665 the global lookup unnecessary by defining the field type as being
1666 the full index type description.
1667
1668 The purpose of this routine is to allow us to support older versions
1669 of the compiler by detecting the use of the older encoding, and by
1670 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1671 we essentially replace each field's meaningless type by the associated
1672 index subtype). */
1673
1674 void
1675 ada_fixup_array_indexes_type (struct type *index_desc_type)
1676 {
1677 int i;
1678
1679 if (index_desc_type == NULL)
1680 return;
1681 gdb_assert (index_desc_type->num_fields () > 0);
1682
1683 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1684 to check one field only, no need to check them all). If not, return
1685 now.
1686
1687 If our INDEX_DESC_TYPE was generated using the older encoding,
1688 the field type should be a meaningless integer type whose name
1689 is not equal to the field name. */
1690 if (index_desc_type->field (0).type ()->name () != NULL
1691 && strcmp (index_desc_type->field (0).type ()->name (),
1692 index_desc_type->field (0).name ()) == 0)
1693 return;
1694
1695 /* Fixup each field of INDEX_DESC_TYPE. */
1696 for (i = 0; i < index_desc_type->num_fields (); i++)
1697 {
1698 const char *name = index_desc_type->field (i).name ();
1699 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1700
1701 if (raw_type)
1702 index_desc_type->field (i).set_type (raw_type);
1703 }
1704 }
1705
1706 /* The desc_* routines return primitive portions of array descriptors
1707 (fat pointers). */
1708
1709 /* The descriptor or array type, if any, indicated by TYPE; removes
1710 level of indirection, if needed. */
1711
1712 static struct type *
1713 desc_base_type (struct type *type)
1714 {
1715 if (type == NULL)
1716 return NULL;
1717 type = ada_check_typedef (type);
1718 if (type->code () == TYPE_CODE_TYPEDEF)
1719 type = ada_typedef_target_type (type);
1720
1721 if (type != NULL
1722 && (type->code () == TYPE_CODE_PTR
1723 || type->code () == TYPE_CODE_REF))
1724 return ada_check_typedef (type->target_type ());
1725 else
1726 return type;
1727 }
1728
1729 /* True iff TYPE indicates a "thin" array pointer type. */
1730
1731 static int
1732 is_thin_pntr (struct type *type)
1733 {
1734 return
1735 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1736 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1737 }
1738
1739 /* The descriptor type for thin pointer type TYPE. */
1740
1741 static struct type *
1742 thin_descriptor_type (struct type *type)
1743 {
1744 struct type *base_type = desc_base_type (type);
1745
1746 if (base_type == NULL)
1747 return NULL;
1748 if (is_suffix (ada_type_name (base_type), "___XVE"))
1749 return base_type;
1750 else
1751 {
1752 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1753
1754 if (alt_type == NULL)
1755 return base_type;
1756 else
1757 return alt_type;
1758 }
1759 }
1760
1761 /* A pointer to the array data for thin-pointer value VAL. */
1762
1763 static struct value *
1764 thin_data_pntr (struct value *val)
1765 {
1766 struct type *type = ada_check_typedef (val->type ());
1767 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1768
1769 data_type = lookup_pointer_type (data_type);
1770
1771 if (type->code () == TYPE_CODE_PTR)
1772 return value_cast (data_type, val->copy ());
1773 else
1774 return value_from_longest (data_type, val->address ());
1775 }
1776
1777 /* True iff TYPE indicates a "thick" array pointer type. */
1778
1779 static int
1780 is_thick_pntr (struct type *type)
1781 {
1782 type = desc_base_type (type);
1783 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1784 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1785 }
1786
1787 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1788 pointer to one, the type of its bounds data; otherwise, NULL. */
1789
1790 static struct type *
1791 desc_bounds_type (struct type *type)
1792 {
1793 struct type *r;
1794
1795 type = desc_base_type (type);
1796
1797 if (type == NULL)
1798 return NULL;
1799 else if (is_thin_pntr (type))
1800 {
1801 type = thin_descriptor_type (type);
1802 if (type == NULL)
1803 return NULL;
1804 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1805 if (r != NULL)
1806 return ada_check_typedef (r);
1807 }
1808 else if (type->code () == TYPE_CODE_STRUCT)
1809 {
1810 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1811 if (r != NULL)
1812 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1813 }
1814 return NULL;
1815 }
1816
1817 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1818 one, a pointer to its bounds data. Otherwise NULL. */
1819
1820 static struct value *
1821 desc_bounds (struct value *arr)
1822 {
1823 struct type *type = ada_check_typedef (arr->type ());
1824
1825 if (is_thin_pntr (type))
1826 {
1827 struct type *bounds_type =
1828 desc_bounds_type (thin_descriptor_type (type));
1829 LONGEST addr;
1830
1831 if (bounds_type == NULL)
1832 error (_("Bad GNAT array descriptor"));
1833
1834 /* NOTE: The following calculation is not really kosher, but
1835 since desc_type is an XVE-encoded type (and shouldn't be),
1836 the correct calculation is a real pain. FIXME (and fix GCC). */
1837 if (type->code () == TYPE_CODE_PTR)
1838 addr = value_as_long (arr);
1839 else
1840 addr = arr->address ();
1841
1842 return
1843 value_from_longest (lookup_pointer_type (bounds_type),
1844 addr - bounds_type->length ());
1845 }
1846
1847 else if (is_thick_pntr (type))
1848 {
1849 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1850 _("Bad GNAT array descriptor"));
1851 struct type *p_bounds_type = p_bounds->type ();
1852
1853 if (p_bounds_type
1854 && p_bounds_type->code () == TYPE_CODE_PTR)
1855 {
1856 struct type *target_type = p_bounds_type->target_type ();
1857
1858 if (target_type->is_stub ())
1859 p_bounds = value_cast (lookup_pointer_type
1860 (ada_check_typedef (target_type)),
1861 p_bounds);
1862 }
1863 else
1864 error (_("Bad GNAT array descriptor"));
1865
1866 return p_bounds;
1867 }
1868 else
1869 return NULL;
1870 }
1871
1872 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1873 position of the field containing the address of the bounds data. */
1874
1875 static int
1876 fat_pntr_bounds_bitpos (struct type *type)
1877 {
1878 return desc_base_type (type)->field (1).loc_bitpos ();
1879 }
1880
1881 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1882 size of the field containing the address of the bounds data. */
1883
1884 static int
1885 fat_pntr_bounds_bitsize (struct type *type)
1886 {
1887 type = desc_base_type (type);
1888
1889 if (type->field (1).bitsize () > 0)
1890 return type->field (1).bitsize ();
1891 else
1892 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1893 }
1894
1895 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1896 pointer to one, the type of its array data (a array-with-no-bounds type);
1897 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1898 data. */
1899
1900 static struct type *
1901 desc_data_target_type (struct type *type)
1902 {
1903 type = desc_base_type (type);
1904
1905 /* NOTE: The following is bogus; see comment in desc_bounds. */
1906 if (is_thin_pntr (type))
1907 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1908 else if (is_thick_pntr (type))
1909 {
1910 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1911
1912 if (data_type
1913 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1914 return ada_check_typedef (data_type->target_type ());
1915 }
1916
1917 return NULL;
1918 }
1919
1920 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1921 its array data. */
1922
1923 static struct value *
1924 desc_data (struct value *arr)
1925 {
1926 struct type *type = arr->type ();
1927
1928 if (is_thin_pntr (type))
1929 return thin_data_pntr (arr);
1930 else if (is_thick_pntr (type))
1931 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1932 _("Bad GNAT array descriptor"));
1933 else
1934 return NULL;
1935 }
1936
1937
1938 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1939 position of the field containing the address of the data. */
1940
1941 static int
1942 fat_pntr_data_bitpos (struct type *type)
1943 {
1944 return desc_base_type (type)->field (0).loc_bitpos ();
1945 }
1946
1947 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1948 size of the field containing the address of the data. */
1949
1950 static int
1951 fat_pntr_data_bitsize (struct type *type)
1952 {
1953 type = desc_base_type (type);
1954
1955 if (type->field (0).bitsize () > 0)
1956 return type->field (0).bitsize ();
1957 else
1958 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1959 }
1960
1961 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1962 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1963 bound, if WHICH is 1. The first bound is I=1. */
1964
1965 static struct value *
1966 desc_one_bound (struct value *bounds, int i, int which)
1967 {
1968 char bound_name[20];
1969 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1970 which ? 'U' : 'L', i - 1);
1971 return value_struct_elt (&bounds, {}, bound_name, NULL,
1972 _("Bad GNAT array descriptor bounds"));
1973 }
1974
1975 /* If BOUNDS is an array-bounds structure type, return the bit position
1976 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1977 bound, if WHICH is 1. The first bound is I=1. */
1978
1979 static int
1980 desc_bound_bitpos (struct type *type, int i, int which)
1981 {
1982 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1983 }
1984
1985 /* If BOUNDS is an array-bounds structure type, return the bit field size
1986 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1987 bound, if WHICH is 1. The first bound is I=1. */
1988
1989 static int
1990 desc_bound_bitsize (struct type *type, int i, int which)
1991 {
1992 type = desc_base_type (type);
1993
1994 if (type->field (2 * i + which - 2).bitsize () > 0)
1995 return type->field (2 * i + which - 2).bitsize ();
1996 else
1997 return 8 * type->field (2 * i + which - 2).type ()->length ();
1998 }
1999
2000 /* If TYPE is the type of an array-bounds structure, the type of its
2001 Ith bound (numbering from 1). Otherwise, NULL. */
2002
2003 static struct type *
2004 desc_index_type (struct type *type, int i)
2005 {
2006 type = desc_base_type (type);
2007
2008 if (type->code () == TYPE_CODE_STRUCT)
2009 {
2010 char bound_name[20];
2011 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2012 return lookup_struct_elt_type (type, bound_name, 1);
2013 }
2014 else
2015 return NULL;
2016 }
2017
2018 /* The number of index positions in the array-bounds type TYPE.
2019 Return 0 if TYPE is NULL. */
2020
2021 static int
2022 desc_arity (struct type *type)
2023 {
2024 type = desc_base_type (type);
2025
2026 if (type != NULL)
2027 return type->num_fields () / 2;
2028 return 0;
2029 }
2030
2031 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2032 an array descriptor type (representing an unconstrained array
2033 type). */
2034
2035 static int
2036 ada_is_direct_array_type (struct type *type)
2037 {
2038 if (type == NULL)
2039 return 0;
2040 type = ada_check_typedef (type);
2041 return (type->code () == TYPE_CODE_ARRAY
2042 || ada_is_array_descriptor_type (type));
2043 }
2044
2045 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2046 * to one. */
2047
2048 static int
2049 ada_is_array_type (struct type *type)
2050 {
2051 while (type != NULL
2052 && (type->code () == TYPE_CODE_PTR
2053 || type->code () == TYPE_CODE_REF))
2054 type = type->target_type ();
2055 return ada_is_direct_array_type (type);
2056 }
2057
2058 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2059
2060 int
2061 ada_is_simple_array_type (struct type *type)
2062 {
2063 if (type == NULL)
2064 return 0;
2065 type = ada_check_typedef (type);
2066 return (type->code () == TYPE_CODE_ARRAY
2067 || (type->code () == TYPE_CODE_PTR
2068 && (ada_check_typedef (type->target_type ())->code ()
2069 == TYPE_CODE_ARRAY)));
2070 }
2071
2072 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2073
2074 int
2075 ada_is_array_descriptor_type (struct type *type)
2076 {
2077 struct type *data_type = desc_data_target_type (type);
2078
2079 if (type == NULL)
2080 return 0;
2081 type = ada_check_typedef (type);
2082 return (data_type != NULL
2083 && data_type->code () == TYPE_CODE_ARRAY
2084 && desc_arity (desc_bounds_type (type)) > 0);
2085 }
2086
2087 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2088 (fat pointer) returns the type of the array data described---specifically,
2089 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2090 in from the descriptor; otherwise, they are left unspecified. If
2091 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2092 returns NULL. The result is simply the type of ARR if ARR is not
2093 a descriptor. */
2094
2095 static struct type *
2096 ada_type_of_array (struct value *arr, int bounds)
2097 {
2098 if (ada_is_constrained_packed_array_type (arr->type ()))
2099 return decode_constrained_packed_array_type (arr->type ());
2100
2101 if (!ada_is_array_descriptor_type (arr->type ()))
2102 return arr->type ();
2103
2104 if (!bounds)
2105 {
2106 struct type *array_type =
2107 ada_check_typedef (desc_data_target_type (arr->type ()));
2108
2109 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2110 array_type->field (0).set_bitsize
2111 (decode_packed_array_bitsize (arr->type ()));
2112
2113 return array_type;
2114 }
2115 else
2116 {
2117 struct type *elt_type;
2118 int arity;
2119 struct value *descriptor;
2120
2121 elt_type = ada_array_element_type (arr->type (), -1);
2122 arity = ada_array_arity (arr->type ());
2123
2124 if (elt_type == NULL || arity == 0)
2125 return ada_check_typedef (arr->type ());
2126
2127 descriptor = desc_bounds (arr);
2128 if (value_as_long (descriptor) == 0)
2129 return NULL;
2130 while (arity > 0)
2131 {
2132 type_allocator alloc (arr->type ());
2133 struct value *low = desc_one_bound (descriptor, arity, 0);
2134 struct value *high = desc_one_bound (descriptor, arity, 1);
2135
2136 arity -= 1;
2137 struct type *range_type
2138 = create_static_range_type (alloc, low->type (),
2139 longest_to_int (value_as_long (low)),
2140 longest_to_int (value_as_long (high)));
2141 elt_type = create_array_type (alloc, elt_type, range_type);
2142 INIT_GNAT_SPECIFIC (elt_type);
2143
2144 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2145 {
2146 /* We need to store the element packed bitsize, as well as
2147 recompute the array size, because it was previously
2148 computed based on the unpacked element size. */
2149 LONGEST lo = value_as_long (low);
2150 LONGEST hi = value_as_long (high);
2151
2152 elt_type->field (0).set_bitsize
2153 (decode_packed_array_bitsize (arr->type ()));
2154
2155 /* If the array has no element, then the size is already
2156 zero, and does not need to be recomputed. */
2157 if (lo < hi)
2158 {
2159 int array_bitsize =
2160 (hi - lo + 1) * elt_type->field (0).bitsize ();
2161
2162 elt_type->set_length ((array_bitsize + 7) / 8);
2163 }
2164 }
2165 }
2166
2167 return lookup_pointer_type (elt_type);
2168 }
2169 }
2170
2171 /* If ARR does not represent an array, returns ARR unchanged.
2172 Otherwise, returns either a standard GDB array with bounds set
2173 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2174 GDB array. Returns NULL if ARR is a null fat pointer. */
2175
2176 struct value *
2177 ada_coerce_to_simple_array_ptr (struct value *arr)
2178 {
2179 if (ada_is_array_descriptor_type (arr->type ()))
2180 {
2181 struct type *arrType = ada_type_of_array (arr, 1);
2182
2183 if (arrType == NULL)
2184 return NULL;
2185 return value_cast (arrType, desc_data (arr)->copy ());
2186 }
2187 else if (ada_is_constrained_packed_array_type (arr->type ()))
2188 return decode_constrained_packed_array (arr);
2189 else
2190 return arr;
2191 }
2192
2193 /* If ARR does not represent an array, returns ARR unchanged.
2194 Otherwise, returns a standard GDB array describing ARR (which may
2195 be ARR itself if it already is in the proper form). */
2196
2197 struct value *
2198 ada_coerce_to_simple_array (struct value *arr)
2199 {
2200 if (ada_is_array_descriptor_type (arr->type ()))
2201 {
2202 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2203
2204 if (arrVal == NULL)
2205 error (_("Bounds unavailable for null array pointer."));
2206 return value_ind (arrVal);
2207 }
2208 else if (ada_is_constrained_packed_array_type (arr->type ()))
2209 return decode_constrained_packed_array (arr);
2210 else
2211 return arr;
2212 }
2213
2214 /* If TYPE represents a GNAT array type, return it translated to an
2215 ordinary GDB array type (possibly with BITSIZE fields indicating
2216 packing). For other types, is the identity. */
2217
2218 struct type *
2219 ada_coerce_to_simple_array_type (struct type *type)
2220 {
2221 if (ada_is_constrained_packed_array_type (type))
2222 return decode_constrained_packed_array_type (type);
2223
2224 if (ada_is_array_descriptor_type (type))
2225 return ada_check_typedef (desc_data_target_type (type));
2226
2227 return type;
2228 }
2229
2230 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2231
2232 static int
2233 ada_is_gnat_encoded_packed_array_type (struct type *type)
2234 {
2235 if (type == NULL)
2236 return 0;
2237 type = desc_base_type (type);
2238 type = ada_check_typedef (type);
2239 return
2240 ada_type_name (type) != NULL
2241 && strstr (ada_type_name (type), "___XP") != NULL;
2242 }
2243
2244 /* Non-zero iff TYPE represents a standard GNAT constrained
2245 packed-array type. */
2246
2247 int
2248 ada_is_constrained_packed_array_type (struct type *type)
2249 {
2250 return ada_is_gnat_encoded_packed_array_type (type)
2251 && !ada_is_array_descriptor_type (type);
2252 }
2253
2254 /* Non-zero iff TYPE represents an array descriptor for a
2255 unconstrained packed-array type. */
2256
2257 static int
2258 ada_is_unconstrained_packed_array_type (struct type *type)
2259 {
2260 if (!ada_is_array_descriptor_type (type))
2261 return 0;
2262
2263 if (ada_is_gnat_encoded_packed_array_type (type))
2264 return 1;
2265
2266 /* If we saw GNAT encodings, then the above code is sufficient.
2267 However, with minimal encodings, we will just have a thick
2268 pointer instead. */
2269 if (is_thick_pntr (type))
2270 {
2271 type = desc_base_type (type);
2272 /* The structure's first field is a pointer to an array, so this
2273 fetches the array type. */
2274 type = type->field (0).type ()->target_type ();
2275 if (type->code () == TYPE_CODE_TYPEDEF)
2276 type = ada_typedef_target_type (type);
2277 /* Now we can see if the array elements are packed. */
2278 return type->field (0).bitsize () > 0;
2279 }
2280
2281 return 0;
2282 }
2283
2284 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2285 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2286
2287 static bool
2288 ada_is_any_packed_array_type (struct type *type)
2289 {
2290 return (ada_is_constrained_packed_array_type (type)
2291 || (type->code () == TYPE_CODE_ARRAY
2292 && type->field (0).bitsize () % 8 != 0));
2293 }
2294
2295 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2296 return the size of its elements in bits. */
2297
2298 static long
2299 decode_packed_array_bitsize (struct type *type)
2300 {
2301 const char *raw_name;
2302 const char *tail;
2303 long bits;
2304
2305 /* Access to arrays implemented as fat pointers are encoded as a typedef
2306 of the fat pointer type. We need the name of the fat pointer type
2307 to do the decoding, so strip the typedef layer. */
2308 if (type->code () == TYPE_CODE_TYPEDEF)
2309 type = ada_typedef_target_type (type);
2310
2311 raw_name = ada_type_name (ada_check_typedef (type));
2312 if (!raw_name)
2313 raw_name = ada_type_name (desc_base_type (type));
2314
2315 if (!raw_name)
2316 return 0;
2317
2318 tail = strstr (raw_name, "___XP");
2319 if (tail == nullptr)
2320 {
2321 gdb_assert (is_thick_pntr (type));
2322 /* The structure's first field is a pointer to an array, so this
2323 fetches the array type. */
2324 type = type->field (0).type ()->target_type ();
2325 /* Now we can see if the array elements are packed. */
2326 return type->field (0).bitsize ();
2327 }
2328
2329 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2330 {
2331 lim_warning
2332 (_("could not understand bit size information on packed array"));
2333 return 0;
2334 }
2335
2336 return bits;
2337 }
2338
2339 /* Given that TYPE is a standard GDB array type with all bounds filled
2340 in, and that the element size of its ultimate scalar constituents
2341 (that is, either its elements, or, if it is an array of arrays, its
2342 elements' elements, etc.) is *ELT_BITS, return an identical type,
2343 but with the bit sizes of its elements (and those of any
2344 constituent arrays) recorded in the BITSIZE components of its
2345 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2346 in bits.
2347
2348 Note that, for arrays whose index type has an XA encoding where
2349 a bound references a record discriminant, getting that discriminant,
2350 and therefore the actual value of that bound, is not possible
2351 because none of the given parameters gives us access to the record.
2352 This function assumes that it is OK in the context where it is being
2353 used to return an array whose bounds are still dynamic and where
2354 the length is arbitrary. */
2355
2356 static struct type *
2357 constrained_packed_array_type (struct type *type, long *elt_bits)
2358 {
2359 struct type *new_elt_type;
2360 struct type *new_type;
2361 struct type *index_type_desc;
2362 struct type *index_type;
2363 LONGEST low_bound, high_bound;
2364
2365 type = ada_check_typedef (type);
2366 if (type->code () != TYPE_CODE_ARRAY)
2367 return type;
2368
2369 index_type_desc = ada_find_parallel_type (type, "___XA");
2370 if (index_type_desc)
2371 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2372 NULL);
2373 else
2374 index_type = type->index_type ();
2375
2376 type_allocator alloc (type);
2377 new_elt_type =
2378 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2379 elt_bits);
2380 new_type = create_array_type (alloc, new_elt_type, index_type);
2381 new_type->field (0).set_bitsize (*elt_bits);
2382 new_type->set_name (ada_type_name (type));
2383
2384 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2385 && is_dynamic_type (check_typedef (index_type)))
2386 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2387 low_bound = high_bound = 0;
2388 if (high_bound < low_bound)
2389 {
2390 *elt_bits = 0;
2391 new_type->set_length (0);
2392 }
2393 else
2394 {
2395 *elt_bits *= (high_bound - low_bound + 1);
2396 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2397 }
2398
2399 new_type->set_is_fixed_instance (true);
2400 return new_type;
2401 }
2402
2403 /* The array type encoded by TYPE, where
2404 ada_is_constrained_packed_array_type (TYPE). */
2405
2406 static struct type *
2407 decode_constrained_packed_array_type (struct type *type)
2408 {
2409 const char *raw_name = ada_type_name (ada_check_typedef (type));
2410 char *name;
2411 const char *tail;
2412 struct type *shadow_type;
2413 long bits;
2414
2415 if (!raw_name)
2416 raw_name = ada_type_name (desc_base_type (type));
2417
2418 if (!raw_name)
2419 return NULL;
2420
2421 name = (char *) alloca (strlen (raw_name) + 1);
2422 tail = strstr (raw_name, "___XP");
2423 type = desc_base_type (type);
2424
2425 memcpy (name, raw_name, tail - raw_name);
2426 name[tail - raw_name] = '\000';
2427
2428 shadow_type = ada_find_parallel_type_with_name (type, name);
2429
2430 if (shadow_type == NULL)
2431 {
2432 lim_warning (_("could not find bounds information on packed array"));
2433 return NULL;
2434 }
2435 shadow_type = check_typedef (shadow_type);
2436
2437 if (shadow_type->code () != TYPE_CODE_ARRAY)
2438 {
2439 lim_warning (_("could not understand bounds "
2440 "information on packed array"));
2441 return NULL;
2442 }
2443
2444 bits = decode_packed_array_bitsize (type);
2445 return constrained_packed_array_type (shadow_type, &bits);
2446 }
2447
2448 /* Helper function for decode_constrained_packed_array. Set the field
2449 bitsize on a series of packed arrays. Returns the number of
2450 elements in TYPE. */
2451
2452 static LONGEST
2453 recursively_update_array_bitsize (struct type *type)
2454 {
2455 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2456
2457 LONGEST low, high;
2458 if (!get_discrete_bounds (type->index_type (), &low, &high)
2459 || low > high)
2460 return 0;
2461 LONGEST our_len = high - low + 1;
2462
2463 struct type *elt_type = type->target_type ();
2464 if (elt_type->code () == TYPE_CODE_ARRAY)
2465 {
2466 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2467 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
2468 type->field (0).set_bitsize (elt_bitsize);
2469
2470 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2471 / HOST_CHAR_BIT));
2472 }
2473
2474 return our_len;
2475 }
2476
2477 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2478 array, returns a simple array that denotes that array. Its type is a
2479 standard GDB array type except that the BITSIZEs of the array
2480 target types are set to the number of bits in each element, and the
2481 type length is set appropriately. */
2482
2483 static struct value *
2484 decode_constrained_packed_array (struct value *arr)
2485 {
2486 struct type *type;
2487
2488 /* If our value is a pointer, then dereference it. Likewise if
2489 the value is a reference. Make sure that this operation does not
2490 cause the target type to be fixed, as this would indirectly cause
2491 this array to be decoded. The rest of the routine assumes that
2492 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2493 and "value_ind" routines to perform the dereferencing, as opposed
2494 to using "ada_coerce_ref" or "ada_value_ind". */
2495 arr = coerce_ref (arr);
2496 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2497 arr = value_ind (arr);
2498
2499 type = decode_constrained_packed_array_type (arr->type ());
2500 if (type == NULL)
2501 {
2502 error (_("can't unpack array"));
2503 return NULL;
2504 }
2505
2506 /* Decoding the packed array type could not correctly set the field
2507 bitsizes for any dimension except the innermost, because the
2508 bounds may be variable and were not passed to that function. So,
2509 we further resolve the array bounds here and then update the
2510 sizes. */
2511 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2512 CORE_ADDR address = arr->address ();
2513 gdb::array_view<const gdb_byte> view
2514 = gdb::make_array_view (valaddr, type->length ());
2515 type = resolve_dynamic_type (type, view, address);
2516 recursively_update_array_bitsize (type);
2517
2518 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2519 && ada_is_modular_type (arr->type ()))
2520 {
2521 /* This is a (right-justified) modular type representing a packed
2522 array with no wrapper. In order to interpret the value through
2523 the (left-justified) packed array type we just built, we must
2524 first left-justify it. */
2525 int bit_size, bit_pos;
2526 ULONGEST mod;
2527
2528 mod = ada_modulus (arr->type ()) - 1;
2529 bit_size = 0;
2530 while (mod > 0)
2531 {
2532 bit_size += 1;
2533 mod >>= 1;
2534 }
2535 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2536 arr = ada_value_primitive_packed_val (arr, NULL,
2537 bit_pos / HOST_CHAR_BIT,
2538 bit_pos % HOST_CHAR_BIT,
2539 bit_size,
2540 type);
2541 }
2542
2543 return coerce_unspec_val_to_type (arr, type);
2544 }
2545
2546
2547 /* The value of the element of packed array ARR at the ARITY indices
2548 given in IND. ARR must be a simple array. */
2549
2550 static struct value *
2551 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2552 {
2553 int i;
2554 int bits, elt_off, bit_off;
2555 long elt_total_bit_offset;
2556 struct type *elt_type;
2557 struct value *v;
2558
2559 bits = 0;
2560 elt_total_bit_offset = 0;
2561 elt_type = ada_check_typedef (arr->type ());
2562 for (i = 0; i < arity; i += 1)
2563 {
2564 if (elt_type->code () != TYPE_CODE_ARRAY
2565 || elt_type->field (0).bitsize () == 0)
2566 error
2567 (_("attempt to do packed indexing of "
2568 "something other than a packed array"));
2569 else
2570 {
2571 struct type *range_type = elt_type->index_type ();
2572 LONGEST lowerbound, upperbound;
2573 LONGEST idx;
2574
2575 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2576 {
2577 lim_warning (_("don't know bounds of array"));
2578 lowerbound = upperbound = 0;
2579 }
2580
2581 idx = pos_atr (ind[i]);
2582 if (idx < lowerbound || idx > upperbound)
2583 lim_warning (_("packed array index %ld out of bounds"),
2584 (long) idx);
2585 bits = elt_type->field (0).bitsize ();
2586 elt_total_bit_offset += (idx - lowerbound) * bits;
2587 elt_type = ada_check_typedef (elt_type->target_type ());
2588 }
2589 }
2590 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2591 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2592
2593 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2594 bits, elt_type);
2595 return v;
2596 }
2597
2598 /* Non-zero iff TYPE includes negative integer values. */
2599
2600 static int
2601 has_negatives (struct type *type)
2602 {
2603 switch (type->code ())
2604 {
2605 default:
2606 return 0;
2607 case TYPE_CODE_INT:
2608 return !type->is_unsigned ();
2609 case TYPE_CODE_RANGE:
2610 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2611 }
2612 }
2613
2614 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2615 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2616 the unpacked buffer.
2617
2618 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2619 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2620
2621 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2622 zero otherwise.
2623
2624 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2625
2626 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2627
2628 static void
2629 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2630 gdb_byte *unpacked, int unpacked_len,
2631 int is_big_endian, int is_signed_type,
2632 int is_scalar)
2633 {
2634 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2635 int src_idx; /* Index into the source area */
2636 int src_bytes_left; /* Number of source bytes left to process. */
2637 int srcBitsLeft; /* Number of source bits left to move */
2638 int unusedLS; /* Number of bits in next significant
2639 byte of source that are unused */
2640
2641 int unpacked_idx; /* Index into the unpacked buffer */
2642 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2643
2644 unsigned long accum; /* Staging area for bits being transferred */
2645 int accumSize; /* Number of meaningful bits in accum */
2646 unsigned char sign;
2647
2648 /* Transmit bytes from least to most significant; delta is the direction
2649 the indices move. */
2650 int delta = is_big_endian ? -1 : 1;
2651
2652 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2653 bits from SRC. .*/
2654 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2655 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2656 bit_size, unpacked_len);
2657
2658 srcBitsLeft = bit_size;
2659 src_bytes_left = src_len;
2660 unpacked_bytes_left = unpacked_len;
2661 sign = 0;
2662
2663 if (is_big_endian)
2664 {
2665 src_idx = src_len - 1;
2666 if (is_signed_type
2667 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2668 sign = ~0;
2669
2670 unusedLS =
2671 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2672 % HOST_CHAR_BIT;
2673
2674 if (is_scalar)
2675 {
2676 accumSize = 0;
2677 unpacked_idx = unpacked_len - 1;
2678 }
2679 else
2680 {
2681 /* Non-scalar values must be aligned at a byte boundary... */
2682 accumSize =
2683 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2684 /* ... And are placed at the beginning (most-significant) bytes
2685 of the target. */
2686 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2687 unpacked_bytes_left = unpacked_idx + 1;
2688 }
2689 }
2690 else
2691 {
2692 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2693
2694 src_idx = unpacked_idx = 0;
2695 unusedLS = bit_offset;
2696 accumSize = 0;
2697
2698 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2699 sign = ~0;
2700 }
2701
2702 accum = 0;
2703 while (src_bytes_left > 0)
2704 {
2705 /* Mask for removing bits of the next source byte that are not
2706 part of the value. */
2707 unsigned int unusedMSMask =
2708 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2709 1;
2710 /* Sign-extend bits for this byte. */
2711 unsigned int signMask = sign & ~unusedMSMask;
2712
2713 accum |=
2714 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2715 accumSize += HOST_CHAR_BIT - unusedLS;
2716 if (accumSize >= HOST_CHAR_BIT)
2717 {
2718 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2719 accumSize -= HOST_CHAR_BIT;
2720 accum >>= HOST_CHAR_BIT;
2721 unpacked_bytes_left -= 1;
2722 unpacked_idx += delta;
2723 }
2724 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2725 unusedLS = 0;
2726 src_bytes_left -= 1;
2727 src_idx += delta;
2728 }
2729 while (unpacked_bytes_left > 0)
2730 {
2731 accum |= sign << accumSize;
2732 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2733 accumSize -= HOST_CHAR_BIT;
2734 if (accumSize < 0)
2735 accumSize = 0;
2736 accum >>= HOST_CHAR_BIT;
2737 unpacked_bytes_left -= 1;
2738 unpacked_idx += delta;
2739 }
2740 }
2741
2742 /* Create a new value of type TYPE from the contents of OBJ starting
2743 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2744 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2745 assigning through the result will set the field fetched from.
2746 VALADDR is ignored unless OBJ is NULL, in which case,
2747 VALADDR+OFFSET must address the start of storage containing the
2748 packed value. The value returned in this case is never an lval.
2749 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2750
2751 struct value *
2752 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2753 long offset, int bit_offset, int bit_size,
2754 struct type *type)
2755 {
2756 struct value *v;
2757 const gdb_byte *src; /* First byte containing data to unpack */
2758 gdb_byte *unpacked;
2759 const int is_scalar = is_scalar_type (type);
2760 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2761 gdb::byte_vector staging;
2762
2763 type = ada_check_typedef (type);
2764
2765 if (obj == NULL)
2766 src = valaddr + offset;
2767 else
2768 src = obj->contents ().data () + offset;
2769
2770 if (is_dynamic_type (type))
2771 {
2772 /* The length of TYPE might by dynamic, so we need to resolve
2773 TYPE in order to know its actual size, which we then use
2774 to create the contents buffer of the value we return.
2775 The difficulty is that the data containing our object is
2776 packed, and therefore maybe not at a byte boundary. So, what
2777 we do, is unpack the data into a byte-aligned buffer, and then
2778 use that buffer as our object's value for resolving the type. */
2779 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2780 staging.resize (staging_len);
2781
2782 ada_unpack_from_contents (src, bit_offset, bit_size,
2783 staging.data (), staging.size (),
2784 is_big_endian, has_negatives (type),
2785 is_scalar);
2786 type = resolve_dynamic_type (type, staging, 0);
2787 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2788 {
2789 /* This happens when the length of the object is dynamic,
2790 and is actually smaller than the space reserved for it.
2791 For instance, in an array of variant records, the bit_size
2792 we're given is the array stride, which is constant and
2793 normally equal to the maximum size of its element.
2794 But, in reality, each element only actually spans a portion
2795 of that stride. */
2796 bit_size = type->length () * HOST_CHAR_BIT;
2797 }
2798 }
2799
2800 if (obj == NULL)
2801 {
2802 v = value::allocate (type);
2803 src = valaddr + offset;
2804 }
2805 else if (obj->lval () == lval_memory && obj->lazy ())
2806 {
2807 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2808 gdb_byte *buf;
2809
2810 v = value_at (type, obj->address () + offset);
2811 buf = (gdb_byte *) alloca (src_len);
2812 read_memory (v->address (), buf, src_len);
2813 src = buf;
2814 }
2815 else
2816 {
2817 v = value::allocate (type);
2818 src = obj->contents ().data () + offset;
2819 }
2820
2821 if (obj != NULL)
2822 {
2823 long new_offset = offset;
2824
2825 v->set_component_location (obj);
2826 v->set_bitpos (bit_offset + obj->bitpos ());
2827 v->set_bitsize (bit_size);
2828 if (v->bitpos () >= HOST_CHAR_BIT)
2829 {
2830 ++new_offset;
2831 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2832 }
2833 v->set_offset (new_offset);
2834
2835 /* Also set the parent value. This is needed when trying to
2836 assign a new value (in inferior memory). */
2837 v->set_parent (obj);
2838 }
2839 else
2840 v->set_bitsize (bit_size);
2841 unpacked = v->contents_writeable ().data ();
2842
2843 if (bit_size == 0)
2844 {
2845 memset (unpacked, 0, type->length ());
2846 return v;
2847 }
2848
2849 if (staging.size () == type->length ())
2850 {
2851 /* Small short-cut: If we've unpacked the data into a buffer
2852 of the same size as TYPE's length, then we can reuse that,
2853 instead of doing the unpacking again. */
2854 memcpy (unpacked, staging.data (), staging.size ());
2855 }
2856 else
2857 ada_unpack_from_contents (src, bit_offset, bit_size,
2858 unpacked, type->length (),
2859 is_big_endian, has_negatives (type), is_scalar);
2860
2861 return v;
2862 }
2863
2864 /* Store the contents of FROMVAL into the location of TOVAL.
2865 Return a new value with the location of TOVAL and contents of
2866 FROMVAL. Handles assignment into packed fields that have
2867 floating-point or non-scalar types. */
2868
2869 static struct value *
2870 ada_value_assign (struct value *toval, struct value *fromval)
2871 {
2872 struct type *type = toval->type ();
2873 int bits = toval->bitsize ();
2874
2875 toval = ada_coerce_ref (toval);
2876 fromval = ada_coerce_ref (fromval);
2877
2878 if (ada_is_direct_array_type (toval->type ()))
2879 toval = ada_coerce_to_simple_array (toval);
2880 if (ada_is_direct_array_type (fromval->type ()))
2881 fromval = ada_coerce_to_simple_array (fromval);
2882
2883 if (!toval->deprecated_modifiable ())
2884 error (_("Left operand of assignment is not a modifiable lvalue."));
2885
2886 if (toval->lval () == lval_memory
2887 && bits > 0
2888 && (type->code () == TYPE_CODE_FLT
2889 || type->code () == TYPE_CODE_STRUCT))
2890 {
2891 int len = (toval->bitpos ()
2892 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2893 int from_size;
2894 gdb_byte *buffer = (gdb_byte *) alloca (len);
2895 struct value *val;
2896 CORE_ADDR to_addr = toval->address ();
2897
2898 if (type->code () == TYPE_CODE_FLT)
2899 fromval = value_cast (type, fromval);
2900
2901 read_memory (to_addr, buffer, len);
2902 from_size = fromval->bitsize ();
2903 if (from_size == 0)
2904 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2905
2906 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2907 ULONGEST from_offset = 0;
2908 if (is_big_endian && is_scalar_type (fromval->type ()))
2909 from_offset = from_size - bits;
2910 copy_bitwise (buffer, toval->bitpos (),
2911 fromval->contents ().data (), from_offset,
2912 bits, is_big_endian);
2913 write_memory_with_notification (to_addr, buffer, len);
2914
2915 val = toval->copy ();
2916 memcpy (val->contents_raw ().data (),
2917 fromval->contents ().data (),
2918 type->length ());
2919 val->deprecated_set_type (type);
2920
2921 return val;
2922 }
2923
2924 return value_assign (toval, fromval);
2925 }
2926
2927
2928 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2929 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2930 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2931 COMPONENT, and not the inferior's memory. The current contents
2932 of COMPONENT are ignored.
2933
2934 Although not part of the initial design, this function also works
2935 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2936 had a null address, and COMPONENT had an address which is equal to
2937 its offset inside CONTAINER. */
2938
2939 static void
2940 value_assign_to_component (struct value *container, struct value *component,
2941 struct value *val)
2942 {
2943 LONGEST offset_in_container =
2944 (LONGEST) (component->address () - container->address ());
2945 int bit_offset_in_container =
2946 component->bitpos () - container->bitpos ();
2947 int bits;
2948
2949 val = value_cast (component->type (), val);
2950
2951 if (component->bitsize () == 0)
2952 bits = TARGET_CHAR_BIT * component->type ()->length ();
2953 else
2954 bits = component->bitsize ();
2955
2956 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2957 {
2958 int src_offset;
2959
2960 if (is_scalar_type (check_typedef (component->type ())))
2961 src_offset
2962 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2963 else
2964 src_offset = 0;
2965 copy_bitwise ((container->contents_writeable ().data ()
2966 + offset_in_container),
2967 container->bitpos () + bit_offset_in_container,
2968 val->contents ().data (), src_offset, bits, 1);
2969 }
2970 else
2971 copy_bitwise ((container->contents_writeable ().data ()
2972 + offset_in_container),
2973 container->bitpos () + bit_offset_in_container,
2974 val->contents ().data (), 0, bits, 0);
2975 }
2976
2977 /* Determine if TYPE is an access to an unconstrained array. */
2978
2979 bool
2980 ada_is_access_to_unconstrained_array (struct type *type)
2981 {
2982 return (type->code () == TYPE_CODE_TYPEDEF
2983 && is_thick_pntr (ada_typedef_target_type (type)));
2984 }
2985
2986 /* The value of the element of array ARR at the ARITY indices given in IND.
2987 ARR may be either a simple array, GNAT array descriptor, or pointer
2988 thereto. */
2989
2990 struct value *
2991 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2992 {
2993 int k;
2994 struct value *elt;
2995 struct type *elt_type;
2996
2997 elt = ada_coerce_to_simple_array (arr);
2998
2999 elt_type = ada_check_typedef (elt->type ());
3000 if (elt_type->code () == TYPE_CODE_ARRAY
3001 && elt_type->field (0).bitsize () > 0)
3002 return value_subscript_packed (elt, arity, ind);
3003
3004 for (k = 0; k < arity; k += 1)
3005 {
3006 struct type *saved_elt_type = elt_type->target_type ();
3007
3008 if (elt_type->code () != TYPE_CODE_ARRAY)
3009 error (_("too many subscripts (%d expected)"), k);
3010
3011 elt = value_subscript (elt, pos_atr (ind[k]));
3012
3013 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3014 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3015 {
3016 /* The element is a typedef to an unconstrained array,
3017 except that the value_subscript call stripped the
3018 typedef layer. The typedef layer is GNAT's way to
3019 specify that the element is, at the source level, an
3020 access to the unconstrained array, rather than the
3021 unconstrained array. So, we need to restore that
3022 typedef layer, which we can do by forcing the element's
3023 type back to its original type. Otherwise, the returned
3024 value is going to be printed as the array, rather
3025 than as an access. Another symptom of the same issue
3026 would be that an expression trying to dereference the
3027 element would also be improperly rejected. */
3028 elt->deprecated_set_type (saved_elt_type);
3029 }
3030
3031 elt_type = ada_check_typedef (elt->type ());
3032 }
3033
3034 return elt;
3035 }
3036
3037 /* Assuming ARR is a pointer to a GDB array, the value of the element
3038 of *ARR at the ARITY indices given in IND.
3039 Does not read the entire array into memory.
3040
3041 Note: Unlike what one would expect, this function is used instead of
3042 ada_value_subscript for basically all non-packed array types. The reason
3043 for this is that a side effect of doing our own pointer arithmetics instead
3044 of relying on value_subscript is that there is no implicit typedef peeling.
3045 This is important for arrays of array accesses, where it allows us to
3046 preserve the fact that the array's element is an array access, where the
3047 access part os encoded in a typedef layer. */
3048
3049 static struct value *
3050 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3051 {
3052 int k;
3053 struct value *array_ind = ada_value_ind (arr);
3054 struct type *type
3055 = check_typedef (array_ind->enclosing_type ());
3056
3057 if (type->code () == TYPE_CODE_ARRAY
3058 && type->field (0).bitsize () > 0)
3059 return value_subscript_packed (array_ind, arity, ind);
3060
3061 for (k = 0; k < arity; k += 1)
3062 {
3063 LONGEST lwb, upb;
3064
3065 if (type->code () != TYPE_CODE_ARRAY)
3066 error (_("too many subscripts (%d expected)"), k);
3067 arr = value_cast (lookup_pointer_type (type->target_type ()),
3068 arr->copy ());
3069 get_discrete_bounds (type->index_type (), &lwb, &upb);
3070 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3071 type = type->target_type ();
3072 }
3073
3074 return value_ind (arr);
3075 }
3076
3077 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3078 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3079 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3080 this array is LOW, as per Ada rules. */
3081 static struct value *
3082 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3083 int low, int high)
3084 {
3085 struct type *type0 = ada_check_typedef (type);
3086 struct type *base_index_type = type0->index_type ()->target_type ();
3087 type_allocator alloc (base_index_type);
3088 struct type *index_type
3089 = create_static_range_type (alloc, base_index_type, low, high);
3090 struct type *slice_type = create_array_type_with_stride
3091 (alloc, type0->target_type (), index_type,
3092 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3093 type0->field (0).bitsize ());
3094 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3095 std::optional<LONGEST> base_low_pos, low_pos;
3096 CORE_ADDR base;
3097
3098 low_pos = discrete_position (base_index_type, low);
3099 base_low_pos = discrete_position (base_index_type, base_low);
3100
3101 if (!low_pos.has_value () || !base_low_pos.has_value ())
3102 {
3103 warning (_("unable to get positions in slice, use bounds instead"));
3104 low_pos = low;
3105 base_low_pos = base_low;
3106 }
3107
3108 ULONGEST stride = slice_type->field (0).bitsize () / 8;
3109 if (stride == 0)
3110 stride = type0->target_type ()->length ();
3111
3112 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3113 return value_at_lazy (slice_type, base);
3114 }
3115
3116
3117 static struct value *
3118 ada_value_slice (struct value *array, int low, int high)
3119 {
3120 struct type *type = ada_check_typedef (array->type ());
3121 struct type *base_index_type = type->index_type ()->target_type ();
3122 type_allocator alloc (type->index_type ());
3123 struct type *index_type
3124 = create_static_range_type (alloc, type->index_type (), low, high);
3125 struct type *slice_type = create_array_type_with_stride
3126 (alloc, type->target_type (), index_type,
3127 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3128 type->field (0).bitsize ());
3129 std::optional<LONGEST> low_pos, high_pos;
3130
3131
3132 low_pos = discrete_position (base_index_type, low);
3133 high_pos = discrete_position (base_index_type, high);
3134
3135 if (!low_pos.has_value () || !high_pos.has_value ())
3136 {
3137 warning (_("unable to get positions in slice, use bounds instead"));
3138 low_pos = low;
3139 high_pos = high;
3140 }
3141
3142 return value_cast (slice_type,
3143 value_slice (array, low, *high_pos - *low_pos + 1));
3144 }
3145
3146 /* If type is a record type in the form of a standard GNAT array
3147 descriptor, returns the number of dimensions for type. If arr is a
3148 simple array, returns the number of "array of"s that prefix its
3149 type designation. Otherwise, returns 0. */
3150
3151 int
3152 ada_array_arity (struct type *type)
3153 {
3154 int arity;
3155
3156 if (type == NULL)
3157 return 0;
3158
3159 type = desc_base_type (type);
3160
3161 arity = 0;
3162 if (type->code () == TYPE_CODE_STRUCT)
3163 return desc_arity (desc_bounds_type (type));
3164 else
3165 while (type->code () == TYPE_CODE_ARRAY)
3166 {
3167 arity += 1;
3168 type = ada_check_typedef (type->target_type ());
3169 }
3170
3171 return arity;
3172 }
3173
3174 /* If TYPE is a record type in the form of a standard GNAT array
3175 descriptor or a simple array type, returns the element type for
3176 TYPE after indexing by NINDICES indices, or by all indices if
3177 NINDICES is -1. Otherwise, returns NULL. */
3178
3179 struct type *
3180 ada_array_element_type (struct type *type, int nindices)
3181 {
3182 type = desc_base_type (type);
3183
3184 if (type->code () == TYPE_CODE_STRUCT)
3185 {
3186 int k;
3187 struct type *p_array_type;
3188
3189 p_array_type = desc_data_target_type (type);
3190
3191 k = ada_array_arity (type);
3192 if (k == 0)
3193 return NULL;
3194
3195 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3196 if (nindices >= 0 && k > nindices)
3197 k = nindices;
3198 while (k > 0 && p_array_type != NULL)
3199 {
3200 p_array_type = ada_check_typedef (p_array_type->target_type ());
3201 k -= 1;
3202 }
3203 return p_array_type;
3204 }
3205 else if (type->code () == TYPE_CODE_ARRAY)
3206 {
3207 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3208 {
3209 type = type->target_type ();
3210 /* A multi-dimensional array is represented using a sequence
3211 of array types. If one of these types has a name, then
3212 it is not another dimension of the outer array, but
3213 rather the element type of the outermost array. */
3214 if (type->name () != nullptr)
3215 break;
3216 nindices -= 1;
3217 }
3218 return type;
3219 }
3220
3221 return NULL;
3222 }
3223
3224 /* See ada-lang.h. */
3225
3226 struct type *
3227 ada_index_type (struct type *type, int n, const char *name)
3228 {
3229 struct type *result_type;
3230
3231 type = desc_base_type (type);
3232
3233 if (n < 0 || n > ada_array_arity (type))
3234 error (_("invalid dimension number to '%s"), name);
3235
3236 if (ada_is_simple_array_type (type))
3237 {
3238 int i;
3239
3240 for (i = 1; i < n; i += 1)
3241 {
3242 type = ada_check_typedef (type);
3243 type = type->target_type ();
3244 }
3245 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3246 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3247 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3248 perhaps stabsread.c would make more sense. */
3249 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3250 result_type = NULL;
3251 }
3252 else
3253 {
3254 result_type = desc_index_type (desc_bounds_type (type), n);
3255 if (result_type == NULL)
3256 error (_("attempt to take bound of something that is not an array"));
3257 }
3258
3259 return result_type;
3260 }
3261
3262 /* Given that arr is an array type, returns the lower bound of the
3263 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3264 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3265 array-descriptor type. It works for other arrays with bounds supplied
3266 by run-time quantities other than discriminants. */
3267
3268 static LONGEST
3269 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3270 {
3271 struct type *type, *index_type_desc, *index_type;
3272 int i;
3273
3274 gdb_assert (which == 0 || which == 1);
3275
3276 if (ada_is_constrained_packed_array_type (arr_type))
3277 arr_type = decode_constrained_packed_array_type (arr_type);
3278
3279 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3280 return - which;
3281
3282 if (arr_type->code () == TYPE_CODE_PTR)
3283 type = arr_type->target_type ();
3284 else
3285 type = arr_type;
3286
3287 if (type->is_fixed_instance ())
3288 {
3289 /* The array has already been fixed, so we do not need to
3290 check the parallel ___XA type again. That encoding has
3291 already been applied, so ignore it now. */
3292 index_type_desc = NULL;
3293 }
3294 else
3295 {
3296 index_type_desc = ada_find_parallel_type (type, "___XA");
3297 ada_fixup_array_indexes_type (index_type_desc);
3298 }
3299
3300 if (index_type_desc != NULL)
3301 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3302 NULL);
3303 else
3304 {
3305 struct type *elt_type = check_typedef (type);
3306
3307 for (i = 1; i < n; i++)
3308 elt_type = check_typedef (elt_type->target_type ());
3309
3310 index_type = elt_type->index_type ();
3311 }
3312
3313 return (which == 0
3314 ? ada_discrete_type_low_bound (index_type)
3315 : ada_discrete_type_high_bound (index_type));
3316 }
3317
3318 /* Given that arr is an array value, returns the lower bound of the
3319 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3320 WHICH is 1. This routine will also work for arrays with bounds
3321 supplied by run-time quantities other than discriminants. */
3322
3323 static LONGEST
3324 ada_array_bound (struct value *arr, int n, int which)
3325 {
3326 struct type *arr_type;
3327
3328 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3329 arr = value_ind (arr);
3330 arr_type = arr->enclosing_type ();
3331
3332 if (ada_is_constrained_packed_array_type (arr_type))
3333 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3334 else if (ada_is_simple_array_type (arr_type))
3335 return ada_array_bound_from_type (arr_type, n, which);
3336 else
3337 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3338 }
3339
3340 /* Given that arr is an array value, returns the length of the
3341 nth index. This routine will also work for arrays with bounds
3342 supplied by run-time quantities other than discriminants.
3343 Does not work for arrays indexed by enumeration types with representation
3344 clauses at the moment. */
3345
3346 static LONGEST
3347 ada_array_length (struct value *arr, int n)
3348 {
3349 struct type *arr_type, *index_type;
3350 int low, high;
3351
3352 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3353 arr = value_ind (arr);
3354 arr_type = arr->enclosing_type ();
3355
3356 if (ada_is_constrained_packed_array_type (arr_type))
3357 return ada_array_length (decode_constrained_packed_array (arr), n);
3358
3359 if (ada_is_simple_array_type (arr_type))
3360 {
3361 low = ada_array_bound_from_type (arr_type, n, 0);
3362 high = ada_array_bound_from_type (arr_type, n, 1);
3363 }
3364 else
3365 {
3366 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3367 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3368 }
3369
3370 arr_type = check_typedef (arr_type);
3371 index_type = ada_index_type (arr_type, n, "length");
3372 if (index_type != NULL)
3373 {
3374 struct type *base_type;
3375 if (index_type->code () == TYPE_CODE_RANGE)
3376 base_type = index_type->target_type ();
3377 else
3378 base_type = index_type;
3379
3380 low = pos_atr (value_from_longest (base_type, low));
3381 high = pos_atr (value_from_longest (base_type, high));
3382 }
3383 return high - low + 1;
3384 }
3385
3386 /* An array whose type is that of ARR_TYPE (an array type), with
3387 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3388 less than LOW, then LOW-1 is used. */
3389
3390 static struct value *
3391 empty_array (struct type *arr_type, int low, int high)
3392 {
3393 struct type *arr_type0 = ada_check_typedef (arr_type);
3394 type_allocator alloc (arr_type0->index_type ()->target_type ());
3395 struct type *index_type
3396 = create_static_range_type
3397 (alloc, arr_type0->index_type ()->target_type (), low,
3398 high < low ? low - 1 : high);
3399 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3400
3401 return value::allocate (create_array_type (alloc, elt_type, index_type));
3402 }
3403 \f
3404
3405 /* Name resolution */
3406
3407 /* The "decoded" name for the user-definable Ada operator corresponding
3408 to OP. */
3409
3410 static const char *
3411 ada_decoded_op_name (enum exp_opcode op)
3412 {
3413 int i;
3414
3415 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3416 {
3417 if (ada_opname_table[i].op == op)
3418 return ada_opname_table[i].decoded;
3419 }
3420 error (_("Could not find operator name for opcode"));
3421 }
3422
3423 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3424 in a listing of choices during disambiguation (see sort_choices, below).
3425 The idea is that overloadings of a subprogram name from the
3426 same package should sort in their source order. We settle for ordering
3427 such symbols by their trailing number (__N or $N). */
3428
3429 static int
3430 encoded_ordered_before (const char *N0, const char *N1)
3431 {
3432 if (N1 == NULL)
3433 return 0;
3434 else if (N0 == NULL)
3435 return 1;
3436 else
3437 {
3438 int k0, k1;
3439
3440 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3441 ;
3442 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3443 ;
3444 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3445 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3446 {
3447 int n0, n1;
3448
3449 n0 = k0;
3450 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3451 n0 -= 1;
3452 n1 = k1;
3453 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3454 n1 -= 1;
3455 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3456 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3457 }
3458 return (strcmp (N0, N1) < 0);
3459 }
3460 }
3461
3462 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3463 encoded names. */
3464
3465 static void
3466 sort_choices (struct block_symbol syms[], int nsyms)
3467 {
3468 int i;
3469
3470 for (i = 1; i < nsyms; i += 1)
3471 {
3472 struct block_symbol sym = syms[i];
3473 int j;
3474
3475 for (j = i - 1; j >= 0; j -= 1)
3476 {
3477 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3478 sym.symbol->linkage_name ()))
3479 break;
3480 syms[j + 1] = syms[j];
3481 }
3482 syms[j + 1] = sym;
3483 }
3484 }
3485
3486 /* Whether GDB should display formals and return types for functions in the
3487 overloads selection menu. */
3488 static bool print_signatures = true;
3489
3490 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3491 all but functions, the signature is just the name of the symbol. For
3492 functions, this is the name of the function, the list of types for formals
3493 and the return type (if any). */
3494
3495 static void
3496 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3497 const struct type_print_options *flags)
3498 {
3499 struct type *type = sym->type ();
3500
3501 gdb_printf (stream, "%s", sym->print_name ());
3502 if (!print_signatures
3503 || type == NULL
3504 || type->code () != TYPE_CODE_FUNC)
3505 return;
3506
3507 if (type->num_fields () > 0)
3508 {
3509 int i;
3510
3511 gdb_printf (stream, " (");
3512 for (i = 0; i < type->num_fields (); ++i)
3513 {
3514 if (i > 0)
3515 gdb_printf (stream, "; ");
3516 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3517 flags);
3518 }
3519 gdb_printf (stream, ")");
3520 }
3521 if (type->target_type () != NULL
3522 && type->target_type ()->code () != TYPE_CODE_VOID)
3523 {
3524 gdb_printf (stream, " return ");
3525 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3526 }
3527 }
3528
3529 /* Read and validate a set of numeric choices from the user in the
3530 range 0 .. N_CHOICES-1. Place the results in increasing
3531 order in CHOICES[0 .. N-1], and return N.
3532
3533 The user types choices as a sequence of numbers on one line
3534 separated by blanks, encoding them as follows:
3535
3536 + A choice of 0 means to cancel the selection, throwing an error.
3537 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3538 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3539
3540 The user is not allowed to choose more than MAX_RESULTS values.
3541
3542 ANNOTATION_SUFFIX, if present, is used to annotate the input
3543 prompts (for use with the -f switch). */
3544
3545 static int
3546 get_selections (int *choices, int n_choices, int max_results,
3547 int is_all_choice, const char *annotation_suffix)
3548 {
3549 const char *args;
3550 const char *prompt;
3551 int n_chosen;
3552 int first_choice = is_all_choice ? 2 : 1;
3553
3554 prompt = getenv ("PS2");
3555 if (prompt == NULL)
3556 prompt = "> ";
3557
3558 std::string buffer;
3559 args = command_line_input (buffer, prompt, annotation_suffix);
3560
3561 if (args == NULL)
3562 error_no_arg (_("one or more choice numbers"));
3563
3564 n_chosen = 0;
3565
3566 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3567 order, as given in args. Choices are validated. */
3568 while (1)
3569 {
3570 char *args2;
3571 int choice, j;
3572
3573 args = skip_spaces (args);
3574 if (*args == '\0' && n_chosen == 0)
3575 error_no_arg (_("one or more choice numbers"));
3576 else if (*args == '\0')
3577 break;
3578
3579 choice = strtol (args, &args2, 10);
3580 if (args == args2 || choice < 0
3581 || choice > n_choices + first_choice - 1)
3582 error (_("Argument must be choice number"));
3583 args = args2;
3584
3585 if (choice == 0)
3586 error (_("cancelled"));
3587
3588 if (choice < first_choice)
3589 {
3590 n_chosen = n_choices;
3591 for (j = 0; j < n_choices; j += 1)
3592 choices[j] = j;
3593 break;
3594 }
3595 choice -= first_choice;
3596
3597 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3598 {
3599 }
3600
3601 if (j < 0 || choice != choices[j])
3602 {
3603 int k;
3604
3605 for (k = n_chosen - 1; k > j; k -= 1)
3606 choices[k + 1] = choices[k];
3607 choices[j + 1] = choice;
3608 n_chosen += 1;
3609 }
3610 }
3611
3612 if (n_chosen > max_results)
3613 error (_("Select no more than %d of the above"), max_results);
3614
3615 return n_chosen;
3616 }
3617
3618 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3619 by asking the user (if necessary), returning the number selected,
3620 and setting the first elements of SYMS items. Error if no symbols
3621 selected. */
3622
3623 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3624 to be re-integrated one of these days. */
3625
3626 static int
3627 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3628 {
3629 int i;
3630 int *chosen = XALLOCAVEC (int , nsyms);
3631 int n_chosen;
3632 int first_choice = (max_results == 1) ? 1 : 2;
3633 const char *select_mode = multiple_symbols_select_mode ();
3634
3635 if (max_results < 1)
3636 error (_("Request to select 0 symbols!"));
3637 if (nsyms <= 1)
3638 return nsyms;
3639
3640 if (select_mode == multiple_symbols_cancel)
3641 error (_("\
3642 canceled because the command is ambiguous\n\
3643 See set/show multiple-symbol."));
3644
3645 /* If select_mode is "all", then return all possible symbols.
3646 Only do that if more than one symbol can be selected, of course.
3647 Otherwise, display the menu as usual. */
3648 if (select_mode == multiple_symbols_all && max_results > 1)
3649 return nsyms;
3650
3651 gdb_printf (_("[0] cancel\n"));
3652 if (max_results > 1)
3653 gdb_printf (_("[1] all\n"));
3654
3655 sort_choices (syms, nsyms);
3656
3657 for (i = 0; i < nsyms; i += 1)
3658 {
3659 if (syms[i].symbol == NULL)
3660 continue;
3661
3662 if (syms[i].symbol->aclass () == LOC_BLOCK)
3663 {
3664 struct symtab_and_line sal =
3665 find_function_start_sal (syms[i].symbol, 1);
3666
3667 gdb_printf ("[%d] ", i + first_choice);
3668 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3669 &type_print_raw_options);
3670 if (sal.symtab == NULL)
3671 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3672 metadata_style.style ().ptr (), nullptr, sal.line);
3673 else
3674 gdb_printf
3675 (_(" at %ps:%d\n"),
3676 styled_string (file_name_style.style (),
3677 symtab_to_filename_for_display (sal.symtab)),
3678 sal.line);
3679 continue;
3680 }
3681 else
3682 {
3683 int is_enumeral =
3684 (syms[i].symbol->aclass () == LOC_CONST
3685 && syms[i].symbol->type () != NULL
3686 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3687 struct symtab *symtab = NULL;
3688
3689 if (syms[i].symbol->is_objfile_owned ())
3690 symtab = syms[i].symbol->symtab ();
3691
3692 if (syms[i].symbol->line () != 0 && symtab != NULL)
3693 {
3694 gdb_printf ("[%d] ", i + first_choice);
3695 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3696 &type_print_raw_options);
3697 gdb_printf (_(" at %s:%d\n"),
3698 symtab_to_filename_for_display (symtab),
3699 syms[i].symbol->line ());
3700 }
3701 else if (is_enumeral
3702 && syms[i].symbol->type ()->name () != NULL)
3703 {
3704 gdb_printf (("[%d] "), i + first_choice);
3705 ada_print_type (syms[i].symbol->type (), NULL,
3706 gdb_stdout, -1, 0, &type_print_raw_options);
3707 gdb_printf (_("'(%s) (enumeral)\n"),
3708 syms[i].symbol->print_name ());
3709 }
3710 else
3711 {
3712 gdb_printf ("[%d] ", i + first_choice);
3713 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3714 &type_print_raw_options);
3715
3716 if (symtab != NULL)
3717 gdb_printf (is_enumeral
3718 ? _(" in %s (enumeral)\n")
3719 : _(" at %s:?\n"),
3720 symtab_to_filename_for_display (symtab));
3721 else
3722 gdb_printf (is_enumeral
3723 ? _(" (enumeral)\n")
3724 : _(" at ?\n"));
3725 }
3726 }
3727 }
3728
3729 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3730 "overload-choice");
3731
3732 for (i = 0; i < n_chosen; i += 1)
3733 syms[i] = syms[chosen[i]];
3734
3735 return n_chosen;
3736 }
3737
3738 /* See ada-lang.h. */
3739
3740 block_symbol
3741 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3742 int nargs, value *argvec[])
3743 {
3744 if (possible_user_operator_p (op, argvec))
3745 {
3746 std::vector<struct block_symbol> candidates
3747 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3748 NULL, SEARCH_VFT);
3749
3750 int i = ada_resolve_function (candidates, argvec,
3751 nargs, ada_decoded_op_name (op), NULL,
3752 parse_completion);
3753 if (i >= 0)
3754 return candidates[i];
3755 }
3756 return {};
3757 }
3758
3759 /* See ada-lang.h. */
3760
3761 block_symbol
3762 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3763 struct type *context_type,
3764 bool parse_completion,
3765 int nargs, value *argvec[],
3766 innermost_block_tracker *tracker)
3767 {
3768 std::vector<struct block_symbol> candidates
3769 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3770
3771 int i;
3772 if (candidates.size () == 1)
3773 i = 0;
3774 else
3775 {
3776 i = ada_resolve_function
3777 (candidates,
3778 argvec, nargs,
3779 sym->linkage_name (),
3780 context_type, parse_completion);
3781 if (i < 0)
3782 error (_("Could not find a match for %s"), sym->print_name ());
3783 }
3784
3785 tracker->update (candidates[i]);
3786 return candidates[i];
3787 }
3788
3789 /* Resolve a mention of a name where the context type is an
3790 enumeration type. */
3791
3792 static int
3793 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3794 const char *name, struct type *context_type,
3795 bool parse_completion)
3796 {
3797 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3798 context_type = ada_check_typedef (context_type);
3799
3800 /* We already know the name matches, so we're just looking for
3801 an element of the correct enum type. */
3802 struct type *type1 = context_type;
3803 for (int i = 0; i < syms.size (); ++i)
3804 {
3805 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3806 if (type1 == type2)
3807 return i;
3808 }
3809
3810 for (int i = 0; i < syms.size (); ++i)
3811 {
3812 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3813 if (type1->num_fields () != type2->num_fields ())
3814 continue;
3815 if (strcmp (type1->name (), type2->name ()) != 0)
3816 continue;
3817 if (ada_identical_enum_types_p (type1, type2))
3818 return i;
3819 }
3820
3821 error (_("No name '%s' in enumeration type '%s'"), name,
3822 ada_type_name (context_type));
3823 }
3824
3825 /* See ada-lang.h. */
3826
3827 block_symbol
3828 ada_resolve_variable (struct symbol *sym, const struct block *block,
3829 struct type *context_type,
3830 bool parse_completion,
3831 int deprocedure_p,
3832 innermost_block_tracker *tracker)
3833 {
3834 std::vector<struct block_symbol> candidates
3835 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3836
3837 if (std::any_of (candidates.begin (),
3838 candidates.end (),
3839 [] (block_symbol &bsym)
3840 {
3841 switch (bsym.symbol->aclass ())
3842 {
3843 case LOC_REGISTER:
3844 case LOC_ARG:
3845 case LOC_REF_ARG:
3846 case LOC_REGPARM_ADDR:
3847 case LOC_LOCAL:
3848 case LOC_COMPUTED:
3849 return true;
3850 default:
3851 return false;
3852 }
3853 }))
3854 {
3855 /* Types tend to get re-introduced locally, so if there
3856 are any local symbols that are not types, first filter
3857 out all types. */
3858 candidates.erase
3859 (std::remove_if
3860 (candidates.begin (),
3861 candidates.end (),
3862 [] (block_symbol &bsym)
3863 {
3864 return bsym.symbol->aclass () == LOC_TYPEDEF;
3865 }),
3866 candidates.end ());
3867 }
3868
3869 /* Filter out artificial symbols. */
3870 candidates.erase
3871 (std::remove_if
3872 (candidates.begin (),
3873 candidates.end (),
3874 [] (block_symbol &bsym)
3875 {
3876 return bsym.symbol->is_artificial ();
3877 }),
3878 candidates.end ());
3879
3880 int i;
3881 if (candidates.empty ())
3882 error (_("No definition found for %s"), sym->print_name ());
3883 else if (candidates.size () == 1)
3884 i = 0;
3885 else if (context_type != nullptr
3886 && context_type->code () == TYPE_CODE_ENUM)
3887 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3888 parse_completion);
3889 else if (context_type == nullptr
3890 && symbols_are_identical_enums (candidates))
3891 {
3892 /* If all the remaining symbols are identical enumerals, then
3893 just keep the first one and discard the rest.
3894
3895 Unlike what we did previously, we do not discard any entry
3896 unless they are ALL identical. This is because the symbol
3897 comparison is not a strict comparison, but rather a practical
3898 comparison. If all symbols are considered identical, then
3899 we can just go ahead and use the first one and discard the rest.
3900 But if we cannot reduce the list to a single element, we have
3901 to ask the user to disambiguate anyways. And if we have to
3902 present a multiple-choice menu, it's less confusing if the list
3903 isn't missing some choices that were identical and yet distinct. */
3904 candidates.resize (1);
3905 i = 0;
3906 }
3907 else if (deprocedure_p && !is_nonfunction (candidates))
3908 {
3909 i = ada_resolve_function
3910 (candidates, NULL, 0,
3911 sym->linkage_name (),
3912 context_type, parse_completion);
3913 if (i < 0)
3914 error (_("Could not find a match for %s"), sym->print_name ());
3915 }
3916 else
3917 {
3918 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3919 user_select_syms (candidates.data (), candidates.size (), 1);
3920 i = 0;
3921 }
3922
3923 tracker->update (candidates[i]);
3924 return candidates[i];
3925 }
3926
3927 static bool ada_type_match (struct type *ftype, struct type *atype);
3928
3929 /* Helper for ada_type_match that checks that two array types are
3930 compatible. As with that function, FTYPE is the formal type and
3931 ATYPE is the actual type. */
3932
3933 static bool
3934 ada_type_match_arrays (struct type *ftype, struct type *atype)
3935 {
3936 if (ftype->code () != TYPE_CODE_ARRAY
3937 && !ada_is_array_descriptor_type (ftype))
3938 return false;
3939 if (atype->code () != TYPE_CODE_ARRAY
3940 && !ada_is_array_descriptor_type (atype))
3941 return false;
3942
3943 if (ada_array_arity (ftype) != ada_array_arity (atype))
3944 return false;
3945
3946 struct type *f_elt_type = ada_array_element_type (ftype, -1);
3947 struct type *a_elt_type = ada_array_element_type (atype, -1);
3948 return ada_type_match (f_elt_type, a_elt_type);
3949 }
3950
3951 /* Return non-zero if formal type FTYPE matches actual type ATYPE.
3952 The term "match" here is rather loose. The match is heuristic and
3953 liberal -- while it tries to reject matches that are obviously
3954 incorrect, it may still let through some that do not strictly
3955 correspond to Ada rules. */
3956
3957 static bool
3958 ada_type_match (struct type *ftype, struct type *atype)
3959 {
3960 ftype = ada_check_typedef (ftype);
3961 atype = ada_check_typedef (atype);
3962
3963 if (ftype->code () == TYPE_CODE_REF)
3964 ftype = ftype->target_type ();
3965 if (atype->code () == TYPE_CODE_REF)
3966 atype = atype->target_type ();
3967
3968 switch (ftype->code ())
3969 {
3970 default:
3971 return ftype->code () == atype->code ();
3972 case TYPE_CODE_PTR:
3973 if (atype->code () != TYPE_CODE_PTR)
3974 return false;
3975 atype = atype->target_type ();
3976 /* This can only happen if the actual argument is 'null'. */
3977 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3978 return true;
3979 return ada_type_match (ftype->target_type (), atype);
3980 case TYPE_CODE_INT:
3981 case TYPE_CODE_ENUM:
3982 case TYPE_CODE_RANGE:
3983 switch (atype->code ())
3984 {
3985 case TYPE_CODE_INT:
3986 case TYPE_CODE_ENUM:
3987 case TYPE_CODE_RANGE:
3988 return true;
3989 default:
3990 return false;
3991 }
3992
3993 case TYPE_CODE_STRUCT:
3994 if (!ada_is_array_descriptor_type (ftype))
3995 return (atype->code () == TYPE_CODE_STRUCT
3996 && !ada_is_array_descriptor_type (atype));
3997
3998 [[fallthrough]];
3999 case TYPE_CODE_ARRAY:
4000 return ada_type_match_arrays (ftype, atype);
4001
4002 case TYPE_CODE_UNION:
4003 case TYPE_CODE_FLT:
4004 return (atype->code () == ftype->code ());
4005 }
4006 }
4007
4008 /* Return non-zero if the formals of FUNC "sufficiently match" the
4009 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
4010 may also be an enumeral, in which case it is treated as a 0-
4011 argument function. */
4012
4013 static int
4014 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
4015 {
4016 int i;
4017 struct type *func_type = func->type ();
4018
4019 if (func->aclass () == LOC_CONST
4020 && func_type->code () == TYPE_CODE_ENUM)
4021 return (n_actuals == 0);
4022 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
4023 return 0;
4024
4025 if (func_type->num_fields () != n_actuals)
4026 return 0;
4027
4028 for (i = 0; i < n_actuals; i += 1)
4029 {
4030 if (actuals[i] == NULL)
4031 return 0;
4032 else
4033 {
4034 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
4035 struct type *atype = ada_check_typedef (actuals[i]->type ());
4036
4037 if (!ada_type_match (ftype, atype))
4038 return 0;
4039 }
4040 }
4041 return 1;
4042 }
4043
4044 /* False iff function type FUNC_TYPE definitely does not produce a value
4045 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4046 FUNC_TYPE is not a valid function type with a non-null return type
4047 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4048
4049 static int
4050 return_match (struct type *func_type, struct type *context_type)
4051 {
4052 struct type *return_type;
4053
4054 if (func_type == NULL)
4055 return 1;
4056
4057 if (func_type->code () == TYPE_CODE_FUNC)
4058 return_type = get_base_type (func_type->target_type ());
4059 else
4060 return_type = get_base_type (func_type);
4061 if (return_type == NULL)
4062 return 1;
4063
4064 context_type = get_base_type (context_type);
4065
4066 if (return_type->code () == TYPE_CODE_ENUM)
4067 return context_type == NULL || return_type == context_type;
4068 else if (context_type == NULL)
4069 return return_type->code () != TYPE_CODE_VOID;
4070 else
4071 return return_type->code () == context_type->code ();
4072 }
4073
4074
4075 /* Returns the index in SYMS that contains the symbol for the
4076 function (if any) that matches the types of the NARGS arguments in
4077 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4078 that returns that type, then eliminate matches that don't. If
4079 CONTEXT_TYPE is void and there is at least one match that does not
4080 return void, eliminate all matches that do.
4081
4082 Asks the user if there is more than one match remaining. Returns -1
4083 if there is no such symbol or none is selected. NAME is used
4084 solely for messages. May re-arrange and modify SYMS in
4085 the process; the index returned is for the modified vector. */
4086
4087 static int
4088 ada_resolve_function (std::vector<struct block_symbol> &syms,
4089 struct value **args, int nargs,
4090 const char *name, struct type *context_type,
4091 bool parse_completion)
4092 {
4093 int fallback;
4094 int k;
4095 int m; /* Number of hits */
4096
4097 m = 0;
4098 /* In the first pass of the loop, we only accept functions matching
4099 context_type. If none are found, we add a second pass of the loop
4100 where every function is accepted. */
4101 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4102 {
4103 for (k = 0; k < syms.size (); k += 1)
4104 {
4105 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4106
4107 if (ada_args_match (syms[k].symbol, args, nargs)
4108 && (fallback || return_match (type, context_type)))
4109 {
4110 syms[m] = syms[k];
4111 m += 1;
4112 }
4113 }
4114 }
4115
4116 /* If we got multiple matches, ask the user which one to use. Don't do this
4117 interactive thing during completion, though, as the purpose of the
4118 completion is providing a list of all possible matches. Prompting the
4119 user to filter it down would be completely unexpected in this case. */
4120 if (m == 0)
4121 return -1;
4122 else if (m > 1 && !parse_completion)
4123 {
4124 gdb_printf (_("Multiple matches for %s\n"), name);
4125 user_select_syms (syms.data (), m, 1);
4126 return 0;
4127 }
4128 return 0;
4129 }
4130
4131 /* Type-class predicates */
4132
4133 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4134 or FLOAT). */
4135
4136 static int
4137 numeric_type_p (struct type *type)
4138 {
4139 if (type == NULL)
4140 return 0;
4141 else
4142 {
4143 switch (type->code ())
4144 {
4145 case TYPE_CODE_INT:
4146 case TYPE_CODE_FLT:
4147 case TYPE_CODE_FIXED_POINT:
4148 return 1;
4149 case TYPE_CODE_RANGE:
4150 return (type == type->target_type ()
4151 || numeric_type_p (type->target_type ()));
4152 default:
4153 return 0;
4154 }
4155 }
4156 }
4157
4158 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4159
4160 static int
4161 integer_type_p (struct type *type)
4162 {
4163 if (type == NULL)
4164 return 0;
4165 else
4166 {
4167 switch (type->code ())
4168 {
4169 case TYPE_CODE_INT:
4170 return 1;
4171 case TYPE_CODE_RANGE:
4172 return (type == type->target_type ()
4173 || integer_type_p (type->target_type ()));
4174 default:
4175 return 0;
4176 }
4177 }
4178 }
4179
4180 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4181
4182 static int
4183 scalar_type_p (struct type *type)
4184 {
4185 if (type == NULL)
4186 return 0;
4187 else
4188 {
4189 switch (type->code ())
4190 {
4191 case TYPE_CODE_INT:
4192 case TYPE_CODE_RANGE:
4193 case TYPE_CODE_ENUM:
4194 case TYPE_CODE_FLT:
4195 case TYPE_CODE_FIXED_POINT:
4196 return 1;
4197 default:
4198 return 0;
4199 }
4200 }
4201 }
4202
4203 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4204 This essentially means one of (INT, RANGE, ENUM) -- but note that
4205 "enum" includes character and boolean as well. */
4206
4207 static int
4208 discrete_type_p (struct type *type)
4209 {
4210 if (type == NULL)
4211 return 0;
4212 else
4213 {
4214 switch (type->code ())
4215 {
4216 case TYPE_CODE_INT:
4217 case TYPE_CODE_RANGE:
4218 case TYPE_CODE_ENUM:
4219 case TYPE_CODE_BOOL:
4220 case TYPE_CODE_CHAR:
4221 return 1;
4222 default:
4223 return 0;
4224 }
4225 }
4226 }
4227
4228 /* Returns non-zero if OP with operands in the vector ARGS could be
4229 a user-defined function. Errs on the side of pre-defined operators
4230 (i.e., result 0). */
4231
4232 static int
4233 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4234 {
4235 struct type *type0 =
4236 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4237 struct type *type1 =
4238 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4239
4240 if (type0 == NULL)
4241 return 0;
4242
4243 switch (op)
4244 {
4245 default:
4246 return 0;
4247
4248 case BINOP_ADD:
4249 case BINOP_SUB:
4250 case BINOP_MUL:
4251 case BINOP_DIV:
4252 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4253
4254 case BINOP_REM:
4255 case BINOP_MOD:
4256 case BINOP_BITWISE_AND:
4257 case BINOP_BITWISE_IOR:
4258 case BINOP_BITWISE_XOR:
4259 return (!(integer_type_p (type0) && integer_type_p (type1)));
4260
4261 case BINOP_EQUAL:
4262 case BINOP_NOTEQUAL:
4263 case BINOP_LESS:
4264 case BINOP_GTR:
4265 case BINOP_LEQ:
4266 case BINOP_GEQ:
4267 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4268
4269 case BINOP_CONCAT:
4270 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4271
4272 case BINOP_EXP:
4273 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4274
4275 case UNOP_NEG:
4276 case UNOP_PLUS:
4277 case UNOP_LOGICAL_NOT:
4278 case UNOP_ABS:
4279 return (!numeric_type_p (type0));
4280
4281 }
4282 }
4283 \f
4284 /* Renaming */
4285
4286 /* NOTES:
4287
4288 1. In the following, we assume that a renaming type's name may
4289 have an ___XD suffix. It would be nice if this went away at some
4290 point.
4291 2. We handle both the (old) purely type-based representation of
4292 renamings and the (new) variable-based encoding. At some point,
4293 it is devoutly to be hoped that the former goes away
4294 (FIXME: hilfinger-2007-07-09).
4295 3. Subprogram renamings are not implemented, although the XRS
4296 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4297
4298 /* If SYM encodes a renaming,
4299
4300 <renaming> renames <renamed entity>,
4301
4302 sets *LEN to the length of the renamed entity's name,
4303 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4304 the string describing the subcomponent selected from the renamed
4305 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4306 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4307 are undefined). Otherwise, returns a value indicating the category
4308 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4309 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4310 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4311 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4312 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4313 may be NULL, in which case they are not assigned.
4314
4315 [Currently, however, GCC does not generate subprogram renamings.] */
4316
4317 enum ada_renaming_category
4318 ada_parse_renaming (struct symbol *sym,
4319 const char **renamed_entity, int *len,
4320 const char **renaming_expr)
4321 {
4322 enum ada_renaming_category kind;
4323 const char *info;
4324 const char *suffix;
4325
4326 if (sym == NULL)
4327 return ADA_NOT_RENAMING;
4328 switch (sym->aclass ())
4329 {
4330 default:
4331 return ADA_NOT_RENAMING;
4332 case LOC_LOCAL:
4333 case LOC_STATIC:
4334 case LOC_COMPUTED:
4335 case LOC_OPTIMIZED_OUT:
4336 info = strstr (sym->linkage_name (), "___XR");
4337 if (info == NULL)
4338 return ADA_NOT_RENAMING;
4339 switch (info[5])
4340 {
4341 case '_':
4342 kind = ADA_OBJECT_RENAMING;
4343 info += 6;
4344 break;
4345 case 'E':
4346 kind = ADA_EXCEPTION_RENAMING;
4347 info += 7;
4348 break;
4349 case 'P':
4350 kind = ADA_PACKAGE_RENAMING;
4351 info += 7;
4352 break;
4353 case 'S':
4354 kind = ADA_SUBPROGRAM_RENAMING;
4355 info += 7;
4356 break;
4357 default:
4358 return ADA_NOT_RENAMING;
4359 }
4360 }
4361
4362 if (renamed_entity != NULL)
4363 *renamed_entity = info;
4364 suffix = strstr (info, "___XE");
4365 if (suffix == NULL || suffix == info)
4366 return ADA_NOT_RENAMING;
4367 if (len != NULL)
4368 *len = strlen (info) - strlen (suffix);
4369 suffix += 5;
4370 if (renaming_expr != NULL)
4371 *renaming_expr = suffix;
4372 return kind;
4373 }
4374
4375 /* Compute the value of the given RENAMING_SYM, which is expected to
4376 be a symbol encoding a renaming expression. BLOCK is the block
4377 used to evaluate the renaming. */
4378
4379 static struct value *
4380 ada_read_renaming_var_value (struct symbol *renaming_sym,
4381 const struct block *block)
4382 {
4383 const char *sym_name;
4384
4385 sym_name = renaming_sym->linkage_name ();
4386 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4387 return expr->evaluate ();
4388 }
4389 \f
4390
4391 /* Evaluation: Function Calls */
4392
4393 /* Return an lvalue containing the value VAL. This is the identity on
4394 lvalues, and otherwise has the side-effect of allocating memory
4395 in the inferior where a copy of the value contents is copied. */
4396
4397 static struct value *
4398 ensure_lval (struct value *val)
4399 {
4400 if (val->lval () == not_lval
4401 || val->lval () == lval_internalvar)
4402 {
4403 int len = ada_check_typedef (val->type ())->length ();
4404 const CORE_ADDR addr =
4405 value_as_long (value_allocate_space_in_inferior (len));
4406
4407 val->set_lval (lval_memory);
4408 val->set_address (addr);
4409 write_memory (addr, val->contents ().data (), len);
4410 }
4411
4412 return val;
4413 }
4414
4415 /* Given ARG, a value of type (pointer or reference to a)*
4416 structure/union, extract the component named NAME from the ultimate
4417 target structure/union and return it as a value with its
4418 appropriate type.
4419
4420 The routine searches for NAME among all members of the structure itself
4421 and (recursively) among all members of any wrapper members
4422 (e.g., '_parent').
4423
4424 If NO_ERR, then simply return NULL in case of error, rather than
4425 calling error. */
4426
4427 static struct value *
4428 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4429 {
4430 struct type *t, *t1;
4431 struct value *v;
4432 int check_tag;
4433
4434 v = NULL;
4435 t1 = t = ada_check_typedef (arg->type ());
4436 if (t->code () == TYPE_CODE_REF)
4437 {
4438 t1 = t->target_type ();
4439 if (t1 == NULL)
4440 goto BadValue;
4441 t1 = ada_check_typedef (t1);
4442 if (t1->code () == TYPE_CODE_PTR)
4443 {
4444 arg = coerce_ref (arg);
4445 t = t1;
4446 }
4447 }
4448
4449 while (t->code () == TYPE_CODE_PTR)
4450 {
4451 t1 = t->target_type ();
4452 if (t1 == NULL)
4453 goto BadValue;
4454 t1 = ada_check_typedef (t1);
4455 if (t1->code () == TYPE_CODE_PTR)
4456 {
4457 arg = value_ind (arg);
4458 t = t1;
4459 }
4460 else
4461 break;
4462 }
4463
4464 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4465 goto BadValue;
4466
4467 if (t1 == t)
4468 v = ada_search_struct_field (name, arg, 0, t);
4469 else
4470 {
4471 int bit_offset, bit_size, byte_offset;
4472 struct type *field_type;
4473 CORE_ADDR address;
4474
4475 if (t->code () == TYPE_CODE_PTR)
4476 address = ada_value_ind (arg)->address ();
4477 else
4478 address = ada_coerce_ref (arg)->address ();
4479
4480 /* Check to see if this is a tagged type. We also need to handle
4481 the case where the type is a reference to a tagged type, but
4482 we have to be careful to exclude pointers to tagged types.
4483 The latter should be shown as usual (as a pointer), whereas
4484 a reference should mostly be transparent to the user. */
4485
4486 if (ada_is_tagged_type (t1, 0)
4487 || (t1->code () == TYPE_CODE_REF
4488 && ada_is_tagged_type (t1->target_type (), 0)))
4489 {
4490 /* We first try to find the searched field in the current type.
4491 If not found then let's look in the fixed type. */
4492
4493 if (!find_struct_field (name, t1, 0,
4494 nullptr, nullptr, nullptr,
4495 nullptr, nullptr))
4496 check_tag = 1;
4497 else
4498 check_tag = 0;
4499 }
4500 else
4501 check_tag = 0;
4502
4503 /* Convert to fixed type in all cases, so that we have proper
4504 offsets to each field in unconstrained record types. */
4505 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4506 address, NULL, check_tag);
4507
4508 /* Resolve the dynamic type as well. */
4509 arg = value_from_contents_and_address (t1, nullptr, address);
4510 t1 = arg->type ();
4511
4512 if (find_struct_field (name, t1, 0,
4513 &field_type, &byte_offset, &bit_offset,
4514 &bit_size, NULL))
4515 {
4516 if (bit_size != 0)
4517 {
4518 if (t->code () == TYPE_CODE_REF)
4519 arg = ada_coerce_ref (arg);
4520 else
4521 arg = ada_value_ind (arg);
4522 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4523 bit_offset, bit_size,
4524 field_type);
4525 }
4526 else
4527 v = value_at_lazy (field_type, address + byte_offset);
4528 }
4529 }
4530
4531 if (v != NULL || no_err)
4532 return v;
4533 else
4534 error (_("There is no member named %s."), name);
4535
4536 BadValue:
4537 if (no_err)
4538 return NULL;
4539 else
4540 error (_("Attempt to extract a component of "
4541 "a value that is not a record."));
4542 }
4543
4544 /* Return the value ACTUAL, converted to be an appropriate value for a
4545 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4546 allocating any necessary descriptors (fat pointers), or copies of
4547 values not residing in memory, updating it as needed. */
4548
4549 struct value *
4550 ada_convert_actual (struct value *actual, struct type *formal_type0)
4551 {
4552 struct type *actual_type = ada_check_typedef (actual->type ());
4553 struct type *formal_type = ada_check_typedef (formal_type0);
4554 struct type *formal_target =
4555 formal_type->code () == TYPE_CODE_PTR
4556 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4557 struct type *actual_target =
4558 actual_type->code () == TYPE_CODE_PTR
4559 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4560
4561 if (ada_is_array_descriptor_type (formal_target)
4562 && actual_target->code () == TYPE_CODE_ARRAY)
4563 return make_array_descriptor (formal_type, actual);
4564 else if (formal_type->code () == TYPE_CODE_PTR
4565 || formal_type->code () == TYPE_CODE_REF)
4566 {
4567 struct value *result;
4568
4569 if (formal_target->code () == TYPE_CODE_ARRAY
4570 && ada_is_array_descriptor_type (actual_target))
4571 result = desc_data (actual);
4572 else if (formal_type->code () != TYPE_CODE_PTR)
4573 {
4574 if (actual->lval () != lval_memory)
4575 {
4576 struct value *val;
4577
4578 actual_type = ada_check_typedef (actual->type ());
4579 val = value::allocate (actual_type);
4580 copy (actual->contents (), val->contents_raw ());
4581 actual = ensure_lval (val);
4582 }
4583 result = value_addr (actual);
4584 }
4585 else
4586 return actual;
4587 return value_cast_pointers (formal_type, result, 0);
4588 }
4589 else if (actual_type->code () == TYPE_CODE_PTR)
4590 return ada_value_ind (actual);
4591 else if (ada_is_aligner_type (formal_type))
4592 {
4593 /* We need to turn this parameter into an aligner type
4594 as well. */
4595 struct value *aligner = value::allocate (formal_type);
4596 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4597
4598 value_assign_to_component (aligner, component, actual);
4599 return aligner;
4600 }
4601
4602 return actual;
4603 }
4604
4605 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4606 type TYPE. This is usually an inefficient no-op except on some targets
4607 (such as AVR) where the representation of a pointer and an address
4608 differs. */
4609
4610 static CORE_ADDR
4611 value_pointer (struct value *value, struct type *type)
4612 {
4613 unsigned len = type->length ();
4614 gdb_byte *buf = (gdb_byte *) alloca (len);
4615 CORE_ADDR addr;
4616
4617 addr = value->address ();
4618 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4619 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4620 return addr;
4621 }
4622
4623
4624 /* Push a descriptor of type TYPE for array value ARR on the stack at
4625 *SP, updating *SP to reflect the new descriptor. Return either
4626 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4627 to-descriptor type rather than a descriptor type), a struct value *
4628 representing a pointer to this descriptor. */
4629
4630 static struct value *
4631 make_array_descriptor (struct type *type, struct value *arr)
4632 {
4633 struct type *bounds_type = desc_bounds_type (type);
4634 struct type *desc_type = desc_base_type (type);
4635 struct value *descriptor = value::allocate (desc_type);
4636 struct value *bounds = value::allocate (bounds_type);
4637 int i;
4638
4639 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4640 i > 0; i -= 1)
4641 {
4642 modify_field (bounds->type (),
4643 bounds->contents_writeable ().data (),
4644 ada_array_bound (arr, i, 0),
4645 desc_bound_bitpos (bounds_type, i, 0),
4646 desc_bound_bitsize (bounds_type, i, 0));
4647 modify_field (bounds->type (),
4648 bounds->contents_writeable ().data (),
4649 ada_array_bound (arr, i, 1),
4650 desc_bound_bitpos (bounds_type, i, 1),
4651 desc_bound_bitsize (bounds_type, i, 1));
4652 }
4653
4654 bounds = ensure_lval (bounds);
4655
4656 modify_field (descriptor->type (),
4657 descriptor->contents_writeable ().data (),
4658 value_pointer (ensure_lval (arr),
4659 desc_type->field (0).type ()),
4660 fat_pntr_data_bitpos (desc_type),
4661 fat_pntr_data_bitsize (desc_type));
4662
4663 modify_field (descriptor->type (),
4664 descriptor->contents_writeable ().data (),
4665 value_pointer (bounds,
4666 desc_type->field (1).type ()),
4667 fat_pntr_bounds_bitpos (desc_type),
4668 fat_pntr_bounds_bitsize (desc_type));
4669
4670 descriptor = ensure_lval (descriptor);
4671
4672 if (type->code () == TYPE_CODE_PTR)
4673 return value_addr (descriptor);
4674 else
4675 return descriptor;
4676 }
4677 \f
4678 /* Symbol Cache Module */
4679
4680 /* Performance measurements made as of 2010-01-15 indicate that
4681 this cache does bring some noticeable improvements. Depending
4682 on the type of entity being printed, the cache can make it as much
4683 as an order of magnitude faster than without it.
4684
4685 The descriptive type DWARF extension has significantly reduced
4686 the need for this cache, at least when DWARF is being used. However,
4687 even in this case, some expensive name-based symbol searches are still
4688 sometimes necessary - to find an XVZ variable, mostly. */
4689
4690 /* Clear all entries from the symbol cache. */
4691
4692 static void
4693 ada_clear_symbol_cache (program_space *pspace)
4694 {
4695 ada_pspace_data_handle.clear (pspace);
4696 }
4697
4698 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4699 Return 1 if found, 0 otherwise.
4700
4701 If an entry was found and SYM is not NULL, set *SYM to the entry's
4702 SYM. Same principle for BLOCK if not NULL. */
4703
4704 static int
4705 lookup_cached_symbol (const char *name, domain_search_flags domain,
4706 struct symbol **sym, const struct block **block)
4707 {
4708 htab_t tab = get_ada_pspace_data (current_program_space);
4709 cache_entry_search search;
4710 search.name = name;
4711 search.domain = domain;
4712
4713 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4714 search.hash ());
4715 if (e == nullptr)
4716 return 0;
4717 if (sym != nullptr)
4718 *sym = e->sym;
4719 if (block != nullptr)
4720 *block = e->block;
4721 return 1;
4722 }
4723
4724 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4725 in domain DOMAIN, save this result in our symbol cache. */
4726
4727 static void
4728 cache_symbol (const char *name, domain_search_flags domain,
4729 struct symbol *sym, const struct block *block)
4730 {
4731 /* Symbols for builtin types don't have a block.
4732 For now don't cache such symbols. */
4733 if (sym != NULL && !sym->is_objfile_owned ())
4734 return;
4735
4736 /* If the symbol is a local symbol, then do not cache it, as a search
4737 for that symbol depends on the context. To determine whether
4738 the symbol is local or not, we check the block where we found it
4739 against the global and static blocks of its associated symtab. */
4740 if (sym != nullptr)
4741 {
4742 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4743
4744 if (bv.global_block () != block && bv.static_block () != block)
4745 return;
4746 }
4747
4748 htab_t tab = get_ada_pspace_data (current_program_space);
4749 cache_entry_search search;
4750 search.name = name;
4751 search.domain = domain;
4752
4753 void **slot = htab_find_slot_with_hash (tab, &search,
4754 search.hash (), INSERT);
4755
4756 cache_entry *e = new cache_entry;
4757 e->name = name;
4758 e->domain = domain;
4759 e->sym = sym;
4760 e->block = block;
4761
4762 *slot = e;
4763 }
4764 \f
4765 /* Symbol Lookup */
4766
4767 /* Return the symbol name match type that should be used used when
4768 searching for all symbols matching LOOKUP_NAME.
4769
4770 LOOKUP_NAME is expected to be a symbol name after transformation
4771 for Ada lookups. */
4772
4773 static symbol_name_match_type
4774 name_match_type_from_name (const char *lookup_name)
4775 {
4776 return (strstr (lookup_name, "__") == NULL
4777 ? symbol_name_match_type::WILD
4778 : symbol_name_match_type::FULL);
4779 }
4780
4781 /* Return the result of a standard (literal, C-like) lookup of NAME in
4782 given DOMAIN, visible from lexical block BLOCK. */
4783
4784 static struct symbol *
4785 standard_lookup (const char *name, const struct block *block,
4786 domain_search_flags domain)
4787 {
4788 /* Initialize it just to avoid a GCC false warning. */
4789 struct block_symbol sym = {};
4790
4791 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4792 return sym.symbol;
4793 ada_lookup_encoded_symbol (name, block, domain, &sym);
4794 cache_symbol (name, domain, sym.symbol, sym.block);
4795 return sym.symbol;
4796 }
4797
4798
4799 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4800 in the symbol fields of SYMS. We treat enumerals as functions,
4801 since they contend in overloading in the same way. */
4802 static int
4803 is_nonfunction (const std::vector<struct block_symbol> &syms)
4804 {
4805 for (const block_symbol &sym : syms)
4806 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4807 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4808 || sym.symbol->aclass () != LOC_CONST))
4809 return 1;
4810
4811 return 0;
4812 }
4813
4814 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4815 struct types. Otherwise, they may not. */
4816
4817 static int
4818 equiv_types (struct type *type0, struct type *type1)
4819 {
4820 if (type0 == type1)
4821 return 1;
4822 if (type0 == NULL || type1 == NULL
4823 || type0->code () != type1->code ())
4824 return 0;
4825 if ((type0->code () == TYPE_CODE_STRUCT
4826 || type0->code () == TYPE_CODE_ENUM)
4827 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4828 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4829 return 1;
4830
4831 return 0;
4832 }
4833
4834 /* True iff SYM0 represents the same entity as SYM1, or one that is
4835 no more defined than that of SYM1. */
4836
4837 static int
4838 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4839 {
4840 if (sym0 == sym1)
4841 return 1;
4842 if (sym0->domain () != sym1->domain ()
4843 || sym0->aclass () != sym1->aclass ())
4844 return 0;
4845
4846 switch (sym0->aclass ())
4847 {
4848 case LOC_UNDEF:
4849 return 1;
4850 case LOC_TYPEDEF:
4851 {
4852 struct type *type0 = sym0->type ();
4853 struct type *type1 = sym1->type ();
4854 const char *name0 = sym0->linkage_name ();
4855 const char *name1 = sym1->linkage_name ();
4856 int len0 = strlen (name0);
4857
4858 return
4859 type0->code () == type1->code ()
4860 && (equiv_types (type0, type1)
4861 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4862 && startswith (name1 + len0, "___XV")));
4863 }
4864 case LOC_CONST:
4865 return sym0->value_longest () == sym1->value_longest ()
4866 && equiv_types (sym0->type (), sym1->type ());
4867
4868 case LOC_STATIC:
4869 {
4870 const char *name0 = sym0->linkage_name ();
4871 const char *name1 = sym1->linkage_name ();
4872 return (strcmp (name0, name1) == 0
4873 && sym0->value_address () == sym1->value_address ());
4874 }
4875
4876 default:
4877 return 0;
4878 }
4879 }
4880
4881 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4882 records in RESULT. Do nothing if SYM is a duplicate. */
4883
4884 static void
4885 add_defn_to_vec (std::vector<struct block_symbol> &result,
4886 struct symbol *sym,
4887 const struct block *block)
4888 {
4889 /* Do not try to complete stub types, as the debugger is probably
4890 already scanning all symbols matching a certain name at the
4891 time when this function is called. Trying to replace the stub
4892 type by its associated full type will cause us to restart a scan
4893 which may lead to an infinite recursion. Instead, the client
4894 collecting the matching symbols will end up collecting several
4895 matches, with at least one of them complete. It can then filter
4896 out the stub ones if needed. */
4897
4898 for (int i = result.size () - 1; i >= 0; i -= 1)
4899 {
4900 if (lesseq_defined_than (sym, result[i].symbol))
4901 return;
4902 else if (lesseq_defined_than (result[i].symbol, sym))
4903 {
4904 result[i].symbol = sym;
4905 result[i].block = block;
4906 return;
4907 }
4908 }
4909
4910 struct block_symbol info;
4911 info.symbol = sym;
4912 info.block = block;
4913 result.push_back (info);
4914 }
4915
4916 /* Return a bound minimal symbol matching NAME according to Ada
4917 decoding rules. Returns an invalid symbol if there is no such
4918 minimal symbol. Names prefixed with "standard__" are handled
4919 specially: "standard__" is first stripped off, and only static and
4920 global symbols are searched. */
4921
4922 struct bound_minimal_symbol
4923 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4924 {
4925 struct bound_minimal_symbol result;
4926
4927 symbol_name_match_type match_type = name_match_type_from_name (name);
4928 lookup_name_info lookup_name (name, match_type);
4929
4930 symbol_name_matcher_ftype *match_name
4931 = ada_get_symbol_name_matcher (lookup_name);
4932
4933 gdbarch_iterate_over_objfiles_in_search_order
4934 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
4935 [&result, lookup_name, match_name] (struct objfile *obj)
4936 {
4937 for (minimal_symbol *msymbol : obj->msymbols ())
4938 {
4939 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4940 && msymbol->type () != mst_solib_trampoline)
4941 {
4942 result.minsym = msymbol;
4943 result.objfile = obj;
4944 return 1;
4945 }
4946 }
4947
4948 return 0;
4949 }, objfile);
4950
4951 return result;
4952 }
4953
4954 /* True if TYPE is definitely an artificial type supplied to a symbol
4955 for which no debugging information was given in the symbol file. */
4956
4957 static int
4958 is_nondebugging_type (struct type *type)
4959 {
4960 const char *name = ada_type_name (type);
4961
4962 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4963 }
4964
4965 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4966 that are deemed "identical" for practical purposes.
4967
4968 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4969 types and that their number of enumerals is identical (in other
4970 words, type1->num_fields () == type2->num_fields ()). */
4971
4972 static int
4973 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4974 {
4975 int i;
4976
4977 /* The heuristic we use here is fairly conservative. We consider
4978 that 2 enumerate types are identical if they have the same
4979 number of enumerals and that all enumerals have the same
4980 underlying value and name. */
4981
4982 /* All enums in the type should have an identical underlying value. */
4983 for (i = 0; i < type1->num_fields (); i++)
4984 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4985 return 0;
4986
4987 /* All enumerals should also have the same name (modulo any numerical
4988 suffix). */
4989 for (i = 0; i < type1->num_fields (); i++)
4990 {
4991 const char *name_1 = type1->field (i).name ();
4992 const char *name_2 = type2->field (i).name ();
4993 int len_1 = strlen (name_1);
4994 int len_2 = strlen (name_2);
4995
4996 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4997 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4998 if (len_1 != len_2
4999 || strncmp (type1->field (i).name (),
5000 type2->field (i).name (),
5001 len_1) != 0)
5002 return 0;
5003 }
5004
5005 return 1;
5006 }
5007
5008 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
5009 that are deemed "identical" for practical purposes. Sometimes,
5010 enumerals are not strictly identical, but their types are so similar
5011 that they can be considered identical.
5012
5013 For instance, consider the following code:
5014
5015 type Color is (Black, Red, Green, Blue, White);
5016 type RGB_Color is new Color range Red .. Blue;
5017
5018 Type RGB_Color is a subrange of an implicit type which is a copy
5019 of type Color. If we call that implicit type RGB_ColorB ("B" is
5020 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5021 As a result, when an expression references any of the enumeral
5022 by name (Eg. "print green"), the expression is technically
5023 ambiguous and the user should be asked to disambiguate. But
5024 doing so would only hinder the user, since it wouldn't matter
5025 what choice he makes, the outcome would always be the same.
5026 So, for practical purposes, we consider them as the same. */
5027
5028 static int
5029 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5030 {
5031 int i;
5032
5033 /* Before performing a thorough comparison check of each type,
5034 we perform a series of inexpensive checks. We expect that these
5035 checks will quickly fail in the vast majority of cases, and thus
5036 help prevent the unnecessary use of a more expensive comparison.
5037 Said comparison also expects us to make some of these checks
5038 (see ada_identical_enum_types_p). */
5039
5040 /* Quick check: All symbols should have an enum type. */
5041 for (i = 0; i < syms.size (); i++)
5042 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5043 return 0;
5044
5045 /* Quick check: They should all have the same value. */
5046 for (i = 1; i < syms.size (); i++)
5047 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5048 return 0;
5049
5050 /* Quick check: They should all have the same number of enumerals. */
5051 for (i = 1; i < syms.size (); i++)
5052 if (syms[i].symbol->type ()->num_fields ()
5053 != syms[0].symbol->type ()->num_fields ())
5054 return 0;
5055
5056 /* All the sanity checks passed, so we might have a set of
5057 identical enumeration types. Perform a more complete
5058 comparison of the type of each symbol. */
5059 for (i = 1; i < syms.size (); i++)
5060 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5061 syms[0].symbol->type ()))
5062 return 0;
5063
5064 return 1;
5065 }
5066
5067 /* Remove any non-debugging symbols in SYMS that definitely
5068 duplicate other symbols in the list (The only case I know of where
5069 this happens is when object files containing stabs-in-ecoff are
5070 linked with files containing ordinary ecoff debugging symbols (or no
5071 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5072
5073 static void
5074 remove_extra_symbols (std::vector<struct block_symbol> &syms)
5075 {
5076 int i, j;
5077
5078 /* We should never be called with less than 2 symbols, as there
5079 cannot be any extra symbol in that case. But it's easy to
5080 handle, since we have nothing to do in that case. */
5081 if (syms.size () < 2)
5082 return;
5083
5084 i = 0;
5085 while (i < syms.size ())
5086 {
5087 bool remove_p = false;
5088
5089 /* If two symbols have the same name and one of them is a stub type,
5090 the get rid of the stub. */
5091
5092 if (syms[i].symbol->type ()->is_stub ()
5093 && syms[i].symbol->linkage_name () != NULL)
5094 {
5095 for (j = 0; !remove_p && j < syms.size (); j++)
5096 {
5097 if (j != i
5098 && !syms[j].symbol->type ()->is_stub ()
5099 && syms[j].symbol->linkage_name () != NULL
5100 && strcmp (syms[i].symbol->linkage_name (),
5101 syms[j].symbol->linkage_name ()) == 0)
5102 remove_p = true;
5103 }
5104 }
5105
5106 /* Two symbols with the same name, same class and same address
5107 should be identical. */
5108
5109 else if (syms[i].symbol->linkage_name () != NULL
5110 && syms[i].symbol->aclass () == LOC_STATIC
5111 && is_nondebugging_type (syms[i].symbol->type ()))
5112 {
5113 for (j = 0; !remove_p && j < syms.size (); j += 1)
5114 {
5115 if (i != j
5116 && syms[j].symbol->linkage_name () != NULL
5117 && strcmp (syms[i].symbol->linkage_name (),
5118 syms[j].symbol->linkage_name ()) == 0
5119 && (syms[i].symbol->aclass ()
5120 == syms[j].symbol->aclass ())
5121 && syms[i].symbol->value_address ()
5122 == syms[j].symbol->value_address ())
5123 remove_p = true;
5124 }
5125 }
5126
5127 /* Two functions with the same block are identical. */
5128
5129 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5130 {
5131 for (j = 0; !remove_p && j < syms.size (); j += 1)
5132 {
5133 if (i != j
5134 && syms[j].symbol->aclass () == LOC_BLOCK
5135 && (syms[i].symbol->value_block ()
5136 == syms[j].symbol->value_block ()))
5137 remove_p = true;
5138 }
5139 }
5140
5141 if (remove_p)
5142 syms.erase (syms.begin () + i);
5143 else
5144 i += 1;
5145 }
5146 }
5147
5148 /* Given a type that corresponds to a renaming entity, use the type name
5149 to extract the scope (package name or function name, fully qualified,
5150 and following the GNAT encoding convention) where this renaming has been
5151 defined. */
5152
5153 static std::string
5154 xget_renaming_scope (struct type *renaming_type)
5155 {
5156 /* The renaming types adhere to the following convention:
5157 <scope>__<rename>___<XR extension>.
5158 So, to extract the scope, we search for the "___XR" extension,
5159 and then backtrack until we find the first "__". */
5160
5161 const char *name = renaming_type->name ();
5162 const char *suffix = strstr (name, "___XR");
5163 const char *last;
5164
5165 /* Now, backtrack a bit until we find the first "__". Start looking
5166 at suffix - 3, as the <rename> part is at least one character long. */
5167
5168 for (last = suffix - 3; last > name; last--)
5169 if (last[0] == '_' && last[1] == '_')
5170 break;
5171
5172 /* Make a copy of scope and return it. */
5173 return std::string (name, last);
5174 }
5175
5176 /* Return nonzero if NAME corresponds to a package name. */
5177
5178 static int
5179 is_package_name (const char *name)
5180 {
5181 /* Here, We take advantage of the fact that no symbols are generated
5182 for packages, while symbols are generated for each function.
5183 So the condition for NAME represent a package becomes equivalent
5184 to NAME not existing in our list of symbols. There is only one
5185 small complication with library-level functions (see below). */
5186
5187 /* If it is a function that has not been defined at library level,
5188 then we should be able to look it up in the symbols. */
5189 if (standard_lookup (name, NULL, SEARCH_VFT) != NULL)
5190 return 0;
5191
5192 /* Library-level function names start with "_ada_". See if function
5193 "_ada_" followed by NAME can be found. */
5194
5195 /* Do a quick check that NAME does not contain "__", since library-level
5196 functions names cannot contain "__" in them. */
5197 if (strstr (name, "__") != NULL)
5198 return 0;
5199
5200 std::string fun_name = string_printf ("_ada_%s", name);
5201
5202 return (standard_lookup (fun_name.c_str (), NULL, SEARCH_VFT) == NULL);
5203 }
5204
5205 /* Return nonzero if SYM corresponds to a renaming entity that is
5206 not visible from FUNCTION_NAME. */
5207
5208 static int
5209 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5210 {
5211 if (sym->aclass () != LOC_TYPEDEF)
5212 return 0;
5213
5214 std::string scope = xget_renaming_scope (sym->type ());
5215
5216 /* If the rename has been defined in a package, then it is visible. */
5217 if (is_package_name (scope.c_str ()))
5218 return 0;
5219
5220 /* Check that the rename is in the current function scope by checking
5221 that its name starts with SCOPE. */
5222
5223 /* If the function name starts with "_ada_", it means that it is
5224 a library-level function. Strip this prefix before doing the
5225 comparison, as the encoding for the renaming does not contain
5226 this prefix. */
5227 if (startswith (function_name, "_ada_"))
5228 function_name += 5;
5229
5230 return !startswith (function_name, scope.c_str ());
5231 }
5232
5233 /* Remove entries from SYMS that corresponds to a renaming entity that
5234 is not visible from the function associated with CURRENT_BLOCK or
5235 that is superfluous due to the presence of more specific renaming
5236 information. Places surviving symbols in the initial entries of
5237 SYMS.
5238
5239 Rationale:
5240 First, in cases where an object renaming is implemented as a
5241 reference variable, GNAT may produce both the actual reference
5242 variable and the renaming encoding. In this case, we discard the
5243 latter.
5244
5245 Second, GNAT emits a type following a specified encoding for each renaming
5246 entity. Unfortunately, STABS currently does not support the definition
5247 of types that are local to a given lexical block, so all renamings types
5248 are emitted at library level. As a consequence, if an application
5249 contains two renaming entities using the same name, and a user tries to
5250 print the value of one of these entities, the result of the ada symbol
5251 lookup will also contain the wrong renaming type.
5252
5253 This function partially covers for this limitation by attempting to
5254 remove from the SYMS list renaming symbols that should be visible
5255 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5256 method with the current information available. The implementation
5257 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5258
5259 - When the user tries to print a rename in a function while there
5260 is another rename entity defined in a package: Normally, the
5261 rename in the function has precedence over the rename in the
5262 package, so the latter should be removed from the list. This is
5263 currently not the case.
5264
5265 - This function will incorrectly remove valid renames if
5266 the CURRENT_BLOCK corresponds to a function which symbol name
5267 has been changed by an "Export" pragma. As a consequence,
5268 the user will be unable to print such rename entities. */
5269
5270 static void
5271 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5272 const struct block *current_block)
5273 {
5274 struct symbol *current_function;
5275 const char *current_function_name;
5276 int i;
5277 int is_new_style_renaming;
5278
5279 /* If there is both a renaming foo___XR... encoded as a variable and
5280 a simple variable foo in the same block, discard the latter.
5281 First, zero out such symbols, then compress. */
5282 is_new_style_renaming = 0;
5283 for (i = 0; i < syms->size (); i += 1)
5284 {
5285 struct symbol *sym = (*syms)[i].symbol;
5286 const struct block *block = (*syms)[i].block;
5287 const char *name;
5288 const char *suffix;
5289
5290 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5291 continue;
5292 name = sym->linkage_name ();
5293 suffix = strstr (name, "___XR");
5294
5295 if (suffix != NULL)
5296 {
5297 int name_len = suffix - name;
5298 int j;
5299
5300 is_new_style_renaming = 1;
5301 for (j = 0; j < syms->size (); j += 1)
5302 if (i != j && (*syms)[j].symbol != NULL
5303 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5304 name_len) == 0
5305 && block == (*syms)[j].block)
5306 (*syms)[j].symbol = NULL;
5307 }
5308 }
5309 if (is_new_style_renaming)
5310 {
5311 int j, k;
5312
5313 for (j = k = 0; j < syms->size (); j += 1)
5314 if ((*syms)[j].symbol != NULL)
5315 {
5316 (*syms)[k] = (*syms)[j];
5317 k += 1;
5318 }
5319 syms->resize (k);
5320 return;
5321 }
5322
5323 /* Extract the function name associated to CURRENT_BLOCK.
5324 Abort if unable to do so. */
5325
5326 if (current_block == NULL)
5327 return;
5328
5329 current_function = current_block->linkage_function ();
5330 if (current_function == NULL)
5331 return;
5332
5333 current_function_name = current_function->linkage_name ();
5334 if (current_function_name == NULL)
5335 return;
5336
5337 /* Check each of the symbols, and remove it from the list if it is
5338 a type corresponding to a renaming that is out of the scope of
5339 the current block. */
5340
5341 i = 0;
5342 while (i < syms->size ())
5343 {
5344 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5345 == ADA_OBJECT_RENAMING
5346 && old_renaming_is_invisible ((*syms)[i].symbol,
5347 current_function_name))
5348 syms->erase (syms->begin () + i);
5349 else
5350 i += 1;
5351 }
5352 }
5353
5354 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5355 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5356
5357 Note: This function assumes that RESULT is empty. */
5358
5359 static void
5360 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5361 const lookup_name_info &lookup_name,
5362 const struct block *block, domain_search_flags domain)
5363 {
5364 while (block != NULL)
5365 {
5366 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5367
5368 /* If we found a non-function match, assume that's the one. We
5369 only check this when finding a function boundary, so that we
5370 can accumulate all results from intervening blocks first. */
5371 if (block->function () != nullptr && is_nonfunction (result))
5372 return;
5373
5374 block = block->superblock ();
5375 }
5376 }
5377
5378 /* An object of this type is used as the callback argument when
5379 calling the map_matching_symbols method. */
5380
5381 struct match_data
5382 {
5383 explicit match_data (std::vector<struct block_symbol> *rp)
5384 : resultp (rp)
5385 {
5386 }
5387 DISABLE_COPY_AND_ASSIGN (match_data);
5388
5389 bool operator() (struct block_symbol *bsym);
5390
5391 struct objfile *objfile = nullptr;
5392 std::vector<struct block_symbol> *resultp;
5393 struct symbol *arg_sym = nullptr;
5394 bool found_sym = false;
5395 };
5396
5397 /* A callback for add_nonlocal_symbols that adds symbol, found in
5398 BSYM, to a list of symbols. */
5399
5400 bool
5401 match_data::operator() (struct block_symbol *bsym)
5402 {
5403 const struct block *block = bsym->block;
5404 struct symbol *sym = bsym->symbol;
5405
5406 if (sym == NULL)
5407 {
5408 if (!found_sym && arg_sym != NULL)
5409 add_defn_to_vec (*resultp, arg_sym, block);
5410 found_sym = false;
5411 arg_sym = NULL;
5412 }
5413 else
5414 {
5415 if (sym->aclass () == LOC_UNRESOLVED)
5416 return true;
5417 else if (sym->is_argument ())
5418 arg_sym = sym;
5419 else
5420 {
5421 found_sym = true;
5422 add_defn_to_vec (*resultp, sym, block);
5423 }
5424 }
5425 return true;
5426 }
5427
5428 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5429 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5430 symbols to RESULT. Return whether we found such symbols. */
5431
5432 static int
5433 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5434 const struct block *block,
5435 const lookup_name_info &lookup_name,
5436 domain_search_flags domain)
5437 {
5438 struct using_direct *renaming;
5439 int defns_mark = result.size ();
5440
5441 symbol_name_matcher_ftype *name_match
5442 = ada_get_symbol_name_matcher (lookup_name);
5443
5444 for (renaming = block->get_using ();
5445 renaming != NULL;
5446 renaming = renaming->next)
5447 {
5448 const char *r_name;
5449
5450 /* Avoid infinite recursions: skip this renaming if we are actually
5451 already traversing it.
5452
5453 Currently, symbol lookup in Ada don't use the namespace machinery from
5454 C++/Fortran support: skip namespace imports that use them. */
5455 if (renaming->searched
5456 || (renaming->import_src != NULL
5457 && renaming->import_src[0] != '\0')
5458 || (renaming->import_dest != NULL
5459 && renaming->import_dest[0] != '\0'))
5460 continue;
5461 renaming->searched = 1;
5462
5463 /* TODO: here, we perform another name-based symbol lookup, which can
5464 pull its own multiple overloads. In theory, we should be able to do
5465 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5466 not a simple name. But in order to do this, we would need to enhance
5467 the DWARF reader to associate a symbol to this renaming, instead of a
5468 name. So, for now, we do something simpler: re-use the C++/Fortran
5469 namespace machinery. */
5470 r_name = (renaming->alias != NULL
5471 ? renaming->alias
5472 : renaming->declaration);
5473 if (name_match (r_name, lookup_name, NULL))
5474 {
5475 lookup_name_info decl_lookup_name (renaming->declaration,
5476 lookup_name.match_type ());
5477 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5478 1, NULL);
5479 }
5480 renaming->searched = 0;
5481 }
5482 return result.size () != defns_mark;
5483 }
5484
5485 /* Convenience function to get at the Ada encoded lookup name for
5486 LOOKUP_NAME, as a C string. */
5487
5488 static const char *
5489 ada_lookup_name (const lookup_name_info &lookup_name)
5490 {
5491 return lookup_name.ada ().lookup_name ().c_str ();
5492 }
5493
5494 /* A helper for add_nonlocal_symbols. Expand all necessary symtabs
5495 for OBJFILE, then walk the objfile's symtabs and update the
5496 results. */
5497
5498 static void
5499 map_matching_symbols (struct objfile *objfile,
5500 const lookup_name_info &lookup_name,
5501 domain_search_flags domain,
5502 int global,
5503 match_data &data)
5504 {
5505 data.objfile = objfile;
5506 objfile->expand_symtabs_matching (nullptr, &lookup_name,
5507 nullptr, nullptr,
5508 global
5509 ? SEARCH_GLOBAL_BLOCK
5510 : SEARCH_STATIC_BLOCK,
5511 domain);
5512
5513 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5514 for (compunit_symtab *symtab : objfile->compunits ())
5515 {
5516 const struct block *block
5517 = symtab->blockvector ()->block (block_kind);
5518 if (!iterate_over_symbols_terminated (block, lookup_name,
5519 domain, data))
5520 break;
5521 }
5522 }
5523
5524 /* Add to RESULT all non-local symbols whose name and domain match
5525 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5526 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5527 symbols otherwise. */
5528
5529 static void
5530 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5531 const lookup_name_info &lookup_name,
5532 domain_search_flags domain, int global)
5533 {
5534 struct match_data data (&result);
5535
5536 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5537
5538 for (objfile *objfile : current_program_space->objfiles ())
5539 {
5540 map_matching_symbols (objfile, lookup_name, domain, global, data);
5541
5542 for (compunit_symtab *cu : objfile->compunits ())
5543 {
5544 const struct block *global_block
5545 = cu->blockvector ()->global_block ();
5546
5547 if (ada_add_block_renamings (result, global_block, lookup_name,
5548 domain))
5549 data.found_sym = true;
5550 }
5551 }
5552
5553 if (result.empty () && global && !is_wild_match)
5554 {
5555 const char *name = ada_lookup_name (lookup_name);
5556 std::string bracket_name = std::string ("<_ada_") + name + '>';
5557 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5558
5559 for (objfile *objfile : current_program_space->objfiles ())
5560 map_matching_symbols (objfile, name1, domain, global, data);
5561 }
5562 }
5563
5564 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5565 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5566 returning the number of matches. Add these to RESULT.
5567
5568 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5569 symbol match within the nest of blocks whose innermost member is BLOCK,
5570 is the one match returned (no other matches in that or
5571 enclosing blocks is returned). If there are any matches in or
5572 surrounding BLOCK, then these alone are returned.
5573
5574 Names prefixed with "standard__" are handled specially:
5575 "standard__" is first stripped off (by the lookup_name
5576 constructor), and only static and global symbols are searched.
5577
5578 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5579 to lookup global symbols. */
5580
5581 static void
5582 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5583 const struct block *block,
5584 const lookup_name_info &lookup_name,
5585 domain_search_flags domain,
5586 int full_search,
5587 int *made_global_lookup_p)
5588 {
5589 struct symbol *sym;
5590
5591 if (made_global_lookup_p)
5592 *made_global_lookup_p = 0;
5593
5594 /* Special case: If the user specifies a symbol name inside package
5595 Standard, do a non-wild matching of the symbol name without
5596 the "standard__" prefix. This was primarily introduced in order
5597 to allow the user to specifically access the standard exceptions
5598 using, for instance, Standard.Constraint_Error when Constraint_Error
5599 is ambiguous (due to the user defining its own Constraint_Error
5600 entity inside its program). */
5601 if (lookup_name.ada ().standard_p ())
5602 block = NULL;
5603
5604 /* Check the non-global symbols. If we have ANY match, then we're done. */
5605
5606 if (block != NULL)
5607 {
5608 if (full_search)
5609 ada_add_local_symbols (result, lookup_name, block, domain);
5610 else
5611 {
5612 /* In the !full_search case we're are being called by
5613 iterate_over_symbols, and we don't want to search
5614 superblocks. */
5615 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5616 }
5617 if (!result.empty () || !full_search)
5618 return;
5619 }
5620
5621 /* No non-global symbols found. Check our cache to see if we have
5622 already performed this search before. If we have, then return
5623 the same result. */
5624
5625 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5626 domain, &sym, &block))
5627 {
5628 if (sym != NULL)
5629 add_defn_to_vec (result, sym, block);
5630 return;
5631 }
5632
5633 if (made_global_lookup_p)
5634 *made_global_lookup_p = 1;
5635
5636 /* Search symbols from all global blocks. */
5637
5638 add_nonlocal_symbols (result, lookup_name, domain, 1);
5639
5640 /* Now add symbols from all per-file blocks if we've gotten no hits
5641 (not strictly correct, but perhaps better than an error). */
5642
5643 if (result.empty ())
5644 add_nonlocal_symbols (result, lookup_name, domain, 0);
5645 }
5646
5647 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5648 is non-zero, enclosing scope and in global scopes.
5649
5650 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5651 blocks and symbol tables (if any) in which they were found.
5652
5653 When full_search is non-zero, any non-function/non-enumeral
5654 symbol match within the nest of blocks whose innermost member is BLOCK,
5655 is the one match returned (no other matches in that or
5656 enclosing blocks is returned). If there are any matches in or
5657 surrounding BLOCK, then these alone are returned.
5658
5659 Names prefixed with "standard__" are handled specially: "standard__"
5660 is first stripped off, and only static and global symbols are searched. */
5661
5662 static std::vector<struct block_symbol>
5663 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5664 const struct block *block,
5665 domain_search_flags domain,
5666 int full_search)
5667 {
5668 int syms_from_global_search;
5669 std::vector<struct block_symbol> results;
5670
5671 ada_add_all_symbols (results, block, lookup_name,
5672 domain, full_search, &syms_from_global_search);
5673
5674 remove_extra_symbols (results);
5675
5676 if (results.empty () && full_search && syms_from_global_search)
5677 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5678
5679 if (results.size () == 1 && full_search && syms_from_global_search)
5680 cache_symbol (ada_lookup_name (lookup_name), domain,
5681 results[0].symbol, results[0].block);
5682
5683 remove_irrelevant_renamings (&results, block);
5684 return results;
5685 }
5686
5687 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5688 in global scopes, returning (SYM,BLOCK) tuples.
5689
5690 See ada_lookup_symbol_list_worker for further details. */
5691
5692 std::vector<struct block_symbol>
5693 ada_lookup_symbol_list (const char *name, const struct block *block,
5694 domain_search_flags domain)
5695 {
5696 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5697 lookup_name_info lookup_name (name, name_match_type);
5698
5699 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5700 }
5701
5702 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5703 to 1, but choosing the first symbol found if there are multiple
5704 choices.
5705
5706 The result is stored in *INFO, which must be non-NULL.
5707 If no match is found, INFO->SYM is set to NULL. */
5708
5709 void
5710 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5711 domain_search_flags domain,
5712 struct block_symbol *info)
5713 {
5714 /* Since we already have an encoded name, wrap it in '<>' to force a
5715 verbatim match. Otherwise, if the name happens to not look like
5716 an encoded name (because it doesn't include a "__"),
5717 ada_lookup_name_info would re-encode/fold it again, and that
5718 would e.g., incorrectly lowercase object renaming names like
5719 "R28b" -> "r28b". */
5720 std::string verbatim = add_angle_brackets (name);
5721
5722 gdb_assert (info != NULL);
5723 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5724 }
5725
5726 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5727 scope and in global scopes, or NULL if none. NAME is folded and
5728 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5729 choosing the first symbol if there are multiple choices. */
5730
5731 struct block_symbol
5732 ada_lookup_symbol (const char *name, const struct block *block0,
5733 domain_search_flags domain)
5734 {
5735 std::vector<struct block_symbol> candidates
5736 = ada_lookup_symbol_list (name, block0, domain);
5737
5738 if (candidates.empty ())
5739 return {};
5740
5741 return candidates[0];
5742 }
5743
5744
5745 /* True iff STR is a possible encoded suffix of a normal Ada name
5746 that is to be ignored for matching purposes. Suffixes of parallel
5747 names (e.g., XVE) are not included here. Currently, the possible suffixes
5748 are given by any of the regular expressions:
5749
5750 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5751 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5752 TKB [subprogram suffix for task bodies]
5753 _E[0-9]+[bs]$ [protected object entry suffixes]
5754 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5755
5756 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5757 match is performed. This sequence is used to differentiate homonyms,
5758 is an optional part of a valid name suffix. */
5759
5760 static int
5761 is_name_suffix (const char *str)
5762 {
5763 int k;
5764 const char *matching;
5765 const int len = strlen (str);
5766
5767 /* Skip optional leading __[0-9]+. */
5768
5769 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5770 {
5771 str += 3;
5772 while (isdigit (str[0]))
5773 str += 1;
5774 }
5775
5776 /* [.$][0-9]+ */
5777
5778 if (str[0] == '.' || str[0] == '$')
5779 {
5780 matching = str + 1;
5781 while (isdigit (matching[0]))
5782 matching += 1;
5783 if (matching[0] == '\0')
5784 return 1;
5785 }
5786
5787 /* ___[0-9]+ */
5788
5789 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5790 {
5791 matching = str + 3;
5792 while (isdigit (matching[0]))
5793 matching += 1;
5794 if (matching[0] == '\0')
5795 return 1;
5796 }
5797
5798 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5799
5800 if (strcmp (str, "TKB") == 0)
5801 return 1;
5802
5803 #if 0
5804 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5805 with a N at the end. Unfortunately, the compiler uses the same
5806 convention for other internal types it creates. So treating
5807 all entity names that end with an "N" as a name suffix causes
5808 some regressions. For instance, consider the case of an enumerated
5809 type. To support the 'Image attribute, it creates an array whose
5810 name ends with N.
5811 Having a single character like this as a suffix carrying some
5812 information is a bit risky. Perhaps we should change the encoding
5813 to be something like "_N" instead. In the meantime, do not do
5814 the following check. */
5815 /* Protected Object Subprograms */
5816 if (len == 1 && str [0] == 'N')
5817 return 1;
5818 #endif
5819
5820 /* _E[0-9]+[bs]$ */
5821 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5822 {
5823 matching = str + 3;
5824 while (isdigit (matching[0]))
5825 matching += 1;
5826 if ((matching[0] == 'b' || matching[0] == 's')
5827 && matching [1] == '\0')
5828 return 1;
5829 }
5830
5831 /* ??? We should not modify STR directly, as we are doing below. This
5832 is fine in this case, but may become problematic later if we find
5833 that this alternative did not work, and want to try matching
5834 another one from the begining of STR. Since we modified it, we
5835 won't be able to find the begining of the string anymore! */
5836 if (str[0] == 'X')
5837 {
5838 str += 1;
5839 while (str[0] != '_' && str[0] != '\0')
5840 {
5841 if (str[0] != 'n' && str[0] != 'b')
5842 return 0;
5843 str += 1;
5844 }
5845 }
5846
5847 if (str[0] == '\000')
5848 return 1;
5849
5850 if (str[0] == '_')
5851 {
5852 if (str[1] != '_' || str[2] == '\000')
5853 return 0;
5854 if (str[2] == '_')
5855 {
5856 if (strcmp (str + 3, "JM") == 0)
5857 return 1;
5858 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5859 the LJM suffix in favor of the JM one. But we will
5860 still accept LJM as a valid suffix for a reasonable
5861 amount of time, just to allow ourselves to debug programs
5862 compiled using an older version of GNAT. */
5863 if (strcmp (str + 3, "LJM") == 0)
5864 return 1;
5865 if (str[3] != 'X')
5866 return 0;
5867 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5868 || str[4] == 'U' || str[4] == 'P')
5869 return 1;
5870 if (str[4] == 'R' && str[5] != 'T')
5871 return 1;
5872 return 0;
5873 }
5874 if (!isdigit (str[2]))
5875 return 0;
5876 for (k = 3; str[k] != '\0'; k += 1)
5877 if (!isdigit (str[k]) && str[k] != '_')
5878 return 0;
5879 return 1;
5880 }
5881 if (str[0] == '$' && isdigit (str[1]))
5882 {
5883 for (k = 2; str[k] != '\0'; k += 1)
5884 if (!isdigit (str[k]) && str[k] != '_')
5885 return 0;
5886 return 1;
5887 }
5888 return 0;
5889 }
5890
5891 /* Return non-zero if the string starting at NAME and ending before
5892 NAME_END contains no capital letters. */
5893
5894 static int
5895 is_valid_name_for_wild_match (const char *name0)
5896 {
5897 std::string decoded_name = ada_decode (name0);
5898 int i;
5899
5900 /* If the decoded name starts with an angle bracket, it means that
5901 NAME0 does not follow the GNAT encoding format. It should then
5902 not be allowed as a possible wild match. */
5903 if (decoded_name[0] == '<')
5904 return 0;
5905
5906 for (i=0; decoded_name[i] != '\0'; i++)
5907 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5908 return 0;
5909
5910 return 1;
5911 }
5912
5913 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5914 character which could start a simple name. Assumes that *NAMEP points
5915 somewhere inside the string beginning at NAME0. */
5916
5917 static int
5918 advance_wild_match (const char **namep, const char *name0, char target0)
5919 {
5920 const char *name = *namep;
5921
5922 while (1)
5923 {
5924 char t0, t1;
5925
5926 t0 = *name;
5927 if (t0 == '_')
5928 {
5929 t1 = name[1];
5930 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5931 {
5932 name += 1;
5933 if (name == name0 + 5 && startswith (name0, "_ada"))
5934 break;
5935 else
5936 name += 1;
5937 }
5938 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5939 || name[2] == target0))
5940 {
5941 name += 2;
5942 break;
5943 }
5944 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5945 {
5946 /* Names like "pkg__B_N__name", where N is a number, are
5947 block-local. We can handle these by simply skipping
5948 the "B_" here. */
5949 name += 4;
5950 }
5951 else
5952 return 0;
5953 }
5954 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5955 name += 1;
5956 else
5957 return 0;
5958 }
5959
5960 *namep = name;
5961 return 1;
5962 }
5963
5964 /* Return true iff NAME encodes a name of the form prefix.PATN.
5965 Ignores any informational suffixes of NAME (i.e., for which
5966 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5967 simple name. */
5968
5969 static bool
5970 wild_match (const char *name, const char *patn)
5971 {
5972 const char *p;
5973 const char *name0 = name;
5974
5975 if (startswith (name, "___ghost_"))
5976 name += 9;
5977
5978 while (1)
5979 {
5980 const char *match = name;
5981
5982 if (*name == *patn)
5983 {
5984 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5985 if (*p != *name)
5986 break;
5987 if (*p == '\0' && is_name_suffix (name))
5988 return match == name0 || is_valid_name_for_wild_match (name0);
5989
5990 if (name[-1] == '_')
5991 name -= 1;
5992 }
5993 if (!advance_wild_match (&name, name0, *patn))
5994 return false;
5995 }
5996 }
5997
5998 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
5999 necessary). OBJFILE is the section containing BLOCK. */
6000
6001 static void
6002 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6003 const struct block *block,
6004 const lookup_name_info &lookup_name,
6005 domain_search_flags domain, struct objfile *objfile)
6006 {
6007 /* A matching argument symbol, if any. */
6008 struct symbol *arg_sym;
6009 /* Set true when we find a matching non-argument symbol. */
6010 bool found_sym;
6011
6012 arg_sym = NULL;
6013 found_sym = false;
6014 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
6015 {
6016 if (sym->matches (domain))
6017 {
6018 if (sym->aclass () != LOC_UNRESOLVED)
6019 {
6020 if (sym->is_argument ())
6021 arg_sym = sym;
6022 else
6023 {
6024 found_sym = true;
6025 add_defn_to_vec (result, sym, block);
6026 }
6027 }
6028 }
6029 }
6030
6031 /* Handle renamings. */
6032
6033 if (ada_add_block_renamings (result, block, lookup_name, domain))
6034 found_sym = true;
6035
6036 if (!found_sym && arg_sym != NULL)
6037 {
6038 add_defn_to_vec (result, arg_sym, block);
6039 }
6040
6041 if (!lookup_name.ada ().wild_match_p ())
6042 {
6043 arg_sym = NULL;
6044 found_sym = false;
6045 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6046 const char *name = ada_lookup_name.c_str ();
6047 size_t name_len = ada_lookup_name.size ();
6048
6049 for (struct symbol *sym : block_iterator_range (block))
6050 {
6051 if (sym->matches (domain))
6052 {
6053 int cmp;
6054
6055 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6056 if (cmp == 0)
6057 {
6058 cmp = !startswith (sym->linkage_name (), "_ada_");
6059 if (cmp == 0)
6060 cmp = strncmp (name, sym->linkage_name () + 5,
6061 name_len);
6062 }
6063
6064 if (cmp == 0
6065 && is_name_suffix (sym->linkage_name () + name_len + 5))
6066 {
6067 if (sym->aclass () != LOC_UNRESOLVED)
6068 {
6069 if (sym->is_argument ())
6070 arg_sym = sym;
6071 else
6072 {
6073 found_sym = true;
6074 add_defn_to_vec (result, sym, block);
6075 }
6076 }
6077 }
6078 }
6079 }
6080
6081 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6082 They aren't parameters, right? */
6083 if (!found_sym && arg_sym != NULL)
6084 {
6085 add_defn_to_vec (result, arg_sym, block);
6086 }
6087 }
6088 }
6089 \f
6090
6091 /* Symbol Completion */
6092
6093 /* See symtab.h. */
6094
6095 bool
6096 ada_lookup_name_info::matches
6097 (const char *sym_name,
6098 symbol_name_match_type match_type,
6099 completion_match_result *comp_match_res) const
6100 {
6101 bool match = false;
6102 const char *text = m_encoded_name.c_str ();
6103 size_t text_len = m_encoded_name.size ();
6104
6105 /* First, test against the fully qualified name of the symbol. */
6106
6107 if (strncmp (sym_name, text, text_len) == 0)
6108 match = true;
6109
6110 std::string decoded_name = ada_decode (sym_name);
6111 if (match && !m_encoded_p)
6112 {
6113 /* One needed check before declaring a positive match is to verify
6114 that iff we are doing a verbatim match, the decoded version
6115 of the symbol name starts with '<'. Otherwise, this symbol name
6116 is not a suitable completion. */
6117
6118 bool has_angle_bracket = (decoded_name[0] == '<');
6119 match = (has_angle_bracket == m_verbatim_p);
6120 }
6121
6122 if (match && !m_verbatim_p)
6123 {
6124 /* When doing non-verbatim match, another check that needs to
6125 be done is to verify that the potentially matching symbol name
6126 does not include capital letters, because the ada-mode would
6127 not be able to understand these symbol names without the
6128 angle bracket notation. */
6129 const char *tmp;
6130
6131 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6132 if (*tmp != '\0')
6133 match = false;
6134 }
6135
6136 /* Second: Try wild matching... */
6137
6138 if (!match && m_wild_match_p)
6139 {
6140 /* Since we are doing wild matching, this means that TEXT
6141 may represent an unqualified symbol name. We therefore must
6142 also compare TEXT against the unqualified name of the symbol. */
6143 sym_name = ada_unqualified_name (decoded_name.c_str ());
6144
6145 if (strncmp (sym_name, text, text_len) == 0)
6146 match = true;
6147 }
6148
6149 /* Finally: If we found a match, prepare the result to return. */
6150
6151 if (!match)
6152 return false;
6153
6154 if (comp_match_res != NULL)
6155 {
6156 std::string &match_str = comp_match_res->match.storage ();
6157
6158 if (!m_encoded_p)
6159 match_str = ada_decode (sym_name);
6160 else
6161 {
6162 if (m_verbatim_p)
6163 match_str = add_angle_brackets (sym_name);
6164 else
6165 match_str = sym_name;
6166
6167 }
6168
6169 comp_match_res->set_match (match_str.c_str ());
6170 }
6171
6172 return true;
6173 }
6174
6175 /* Field Access */
6176
6177 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6178 for tagged types. */
6179
6180 static int
6181 ada_is_dispatch_table_ptr_type (struct type *type)
6182 {
6183 const char *name;
6184
6185 if (type->code () != TYPE_CODE_PTR)
6186 return 0;
6187
6188 name = type->target_type ()->name ();
6189 if (name == NULL)
6190 return 0;
6191
6192 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6193 }
6194
6195 /* Return non-zero if TYPE is an interface tag. */
6196
6197 static int
6198 ada_is_interface_tag (struct type *type)
6199 {
6200 const char *name = type->name ();
6201
6202 if (name == NULL)
6203 return 0;
6204
6205 return (strcmp (name, "ada__tags__interface_tag") == 0);
6206 }
6207
6208 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6209 to be invisible to users. */
6210
6211 int
6212 ada_is_ignored_field (struct type *type, int field_num)
6213 {
6214 if (field_num < 0 || field_num > type->num_fields ())
6215 return 1;
6216
6217 /* Check the name of that field. */
6218 {
6219 const char *name = type->field (field_num).name ();
6220
6221 /* Anonymous field names should not be printed.
6222 brobecker/2007-02-20: I don't think this can actually happen
6223 but we don't want to print the value of anonymous fields anyway. */
6224 if (name == NULL)
6225 return 1;
6226
6227 /* Normally, fields whose name start with an underscore ("_")
6228 are fields that have been internally generated by the compiler,
6229 and thus should not be printed. The "_parent" field is special,
6230 however: This is a field internally generated by the compiler
6231 for tagged types, and it contains the components inherited from
6232 the parent type. This field should not be printed as is, but
6233 should not be ignored either. */
6234 if (name[0] == '_' && !startswith (name, "_parent"))
6235 return 1;
6236
6237 /* The compiler doesn't document this, but sometimes it emits
6238 a field whose name starts with a capital letter, like 'V148s'.
6239 These aren't marked as artificial in any way, but we know they
6240 should be ignored. However, wrapper fields should not be
6241 ignored. */
6242 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6243 {
6244 /* Wrapper field. */
6245 }
6246 else if (isupper (name[0]))
6247 return 1;
6248 }
6249
6250 /* If this is the dispatch table of a tagged type or an interface tag,
6251 then ignore. */
6252 if (ada_is_tagged_type (type, 1)
6253 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6254 || ada_is_interface_tag (type->field (field_num).type ())))
6255 return 1;
6256
6257 /* Not a special field, so it should not be ignored. */
6258 return 0;
6259 }
6260
6261 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6262 pointer or reference type whose ultimate target has a tag field. */
6263
6264 int
6265 ada_is_tagged_type (struct type *type, int refok)
6266 {
6267 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6268 }
6269
6270 /* True iff TYPE represents the type of X'Tag */
6271
6272 int
6273 ada_is_tag_type (struct type *type)
6274 {
6275 type = ada_check_typedef (type);
6276
6277 if (type == NULL || type->code () != TYPE_CODE_PTR)
6278 return 0;
6279 else
6280 {
6281 const char *name = ada_type_name (type->target_type ());
6282
6283 return (name != NULL
6284 && strcmp (name, "ada__tags__dispatch_table") == 0);
6285 }
6286 }
6287
6288 /* The type of the tag on VAL. */
6289
6290 static struct type *
6291 ada_tag_type (struct value *val)
6292 {
6293 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6294 }
6295
6296 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6297 retired at Ada 05). */
6298
6299 static int
6300 is_ada95_tag (struct value *tag)
6301 {
6302 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6303 }
6304
6305 /* The value of the tag on VAL. */
6306
6307 static struct value *
6308 ada_value_tag (struct value *val)
6309 {
6310 return ada_value_struct_elt (val, "_tag", 0);
6311 }
6312
6313 /* The value of the tag on the object of type TYPE whose contents are
6314 saved at VALADDR, if it is non-null, or is at memory address
6315 ADDRESS. */
6316
6317 static struct value *
6318 value_tag_from_contents_and_address (struct type *type,
6319 const gdb_byte *valaddr,
6320 CORE_ADDR address)
6321 {
6322 int tag_byte_offset;
6323 struct type *tag_type;
6324
6325 gdb::array_view<const gdb_byte> contents;
6326 if (valaddr != nullptr)
6327 contents = gdb::make_array_view (valaddr, type->length ());
6328 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6329 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6330 NULL, NULL, NULL))
6331 {
6332 const gdb_byte *valaddr1 = ((valaddr == NULL)
6333 ? NULL
6334 : valaddr + tag_byte_offset);
6335 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6336
6337 return value_from_contents_and_address (tag_type, valaddr1, address1);
6338 }
6339 return NULL;
6340 }
6341
6342 static struct type *
6343 type_from_tag (struct value *tag)
6344 {
6345 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6346
6347 if (type_name != NULL)
6348 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6349 return NULL;
6350 }
6351
6352 /* Given a value OBJ of a tagged type, return a value of this
6353 type at the base address of the object. The base address, as
6354 defined in Ada.Tags, it is the address of the primary tag of
6355 the object, and therefore where the field values of its full
6356 view can be fetched. */
6357
6358 struct value *
6359 ada_tag_value_at_base_address (struct value *obj)
6360 {
6361 struct value *val;
6362 LONGEST offset_to_top = 0;
6363 struct type *ptr_type, *obj_type;
6364 struct value *tag;
6365 CORE_ADDR base_address;
6366
6367 obj_type = obj->type ();
6368
6369 /* It is the responsibility of the caller to deref pointers. */
6370
6371 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6372 return obj;
6373
6374 tag = ada_value_tag (obj);
6375 if (!tag)
6376 return obj;
6377
6378 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6379
6380 if (is_ada95_tag (tag))
6381 return obj;
6382
6383 struct type *offset_type
6384 = language_lookup_primitive_type (language_def (language_ada),
6385 current_inferior ()->arch (),
6386 "storage_offset");
6387 ptr_type = lookup_pointer_type (offset_type);
6388 val = value_cast (ptr_type, tag);
6389 if (!val)
6390 return obj;
6391
6392 /* It is perfectly possible that an exception be raised while
6393 trying to determine the base address, just like for the tag;
6394 see ada_tag_name for more details. We do not print the error
6395 message for the same reason. */
6396
6397 try
6398 {
6399 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6400 }
6401
6402 catch (const gdb_exception_error &e)
6403 {
6404 return obj;
6405 }
6406
6407 /* If offset is null, nothing to do. */
6408
6409 if (offset_to_top == 0)
6410 return obj;
6411
6412 /* -1 is a special case in Ada.Tags; however, what should be done
6413 is not quite clear from the documentation. So do nothing for
6414 now. */
6415
6416 if (offset_to_top == -1)
6417 return obj;
6418
6419 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6420 top is used. In this situation the offset is stored just after
6421 the tag, in the object itself. */
6422 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6423 if (offset_to_top == last)
6424 {
6425 struct value *tem = value_addr (tag);
6426 tem = value_ptradd (tem, 1);
6427 tem = value_cast (ptr_type, tem);
6428 offset_to_top = value_as_long (value_ind (tem));
6429 }
6430
6431 if (offset_to_top > 0)
6432 {
6433 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6434 from the base address. This was however incompatible with
6435 C++ dispatch table: C++ uses a *negative* value to *add*
6436 to the base address. Ada's convention has therefore been
6437 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6438 use the same convention. Here, we support both cases by
6439 checking the sign of OFFSET_TO_TOP. */
6440 offset_to_top = -offset_to_top;
6441 }
6442
6443 base_address = obj->address () + offset_to_top;
6444 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6445
6446 /* Make sure that we have a proper tag at the new address.
6447 Otherwise, offset_to_top is bogus (which can happen when
6448 the object is not initialized yet). */
6449
6450 if (!tag)
6451 return obj;
6452
6453 obj_type = type_from_tag (tag);
6454
6455 if (!obj_type)
6456 return obj;
6457
6458 return value_from_contents_and_address (obj_type, NULL, base_address);
6459 }
6460
6461 /* Return the "ada__tags__type_specific_data" type. */
6462
6463 static struct type *
6464 ada_get_tsd_type (struct inferior *inf)
6465 {
6466 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6467
6468 if (data->tsd_type == 0)
6469 data->tsd_type
6470 = lookup_transparent_type ("<ada__tags__type_specific_data>",
6471 SEARCH_TYPE_DOMAIN);
6472 return data->tsd_type;
6473 }
6474
6475 /* Return the TSD (type-specific data) associated to the given TAG.
6476 TAG is assumed to be the tag of a tagged-type entity.
6477
6478 May return NULL if we are unable to get the TSD. */
6479
6480 static struct value *
6481 ada_get_tsd_from_tag (struct value *tag)
6482 {
6483 struct value *val;
6484 struct type *type;
6485
6486 /* First option: The TSD is simply stored as a field of our TAG.
6487 Only older versions of GNAT would use this format, but we have
6488 to test it first, because there are no visible markers for
6489 the current approach except the absence of that field. */
6490
6491 val = ada_value_struct_elt (tag, "tsd", 1);
6492 if (val)
6493 return val;
6494
6495 /* Try the second representation for the dispatch table (in which
6496 there is no explicit 'tsd' field in the referent of the tag pointer,
6497 and instead the tsd pointer is stored just before the dispatch
6498 table. */
6499
6500 type = ada_get_tsd_type (current_inferior());
6501 if (type == NULL)
6502 return NULL;
6503 type = lookup_pointer_type (lookup_pointer_type (type));
6504 val = value_cast (type, tag);
6505 if (val == NULL)
6506 return NULL;
6507 return value_ind (value_ptradd (val, -1));
6508 }
6509
6510 /* Given the TSD of a tag (type-specific data), return a string
6511 containing the name of the associated type.
6512
6513 May return NULL if we are unable to determine the tag name. */
6514
6515 static gdb::unique_xmalloc_ptr<char>
6516 ada_tag_name_from_tsd (struct value *tsd)
6517 {
6518 struct value *val;
6519
6520 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6521 if (val == NULL)
6522 return NULL;
6523 gdb::unique_xmalloc_ptr<char> buffer
6524 = target_read_string (value_as_address (val), INT_MAX);
6525 if (buffer == nullptr)
6526 return nullptr;
6527
6528 try
6529 {
6530 /* Let this throw an exception on error. If the data is
6531 uninitialized, we'd rather not have the user see a
6532 warning. */
6533 const char *folded = ada_fold_name (buffer.get (), true);
6534 return make_unique_xstrdup (folded);
6535 }
6536 catch (const gdb_exception &)
6537 {
6538 return nullptr;
6539 }
6540 }
6541
6542 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6543 a C string.
6544
6545 Return NULL if the TAG is not an Ada tag, or if we were unable to
6546 determine the name of that tag. */
6547
6548 gdb::unique_xmalloc_ptr<char>
6549 ada_tag_name (struct value *tag)
6550 {
6551 gdb::unique_xmalloc_ptr<char> name;
6552
6553 if (!ada_is_tag_type (tag->type ()))
6554 return NULL;
6555
6556 /* It is perfectly possible that an exception be raised while trying
6557 to determine the TAG's name, even under normal circumstances:
6558 The associated variable may be uninitialized or corrupted, for
6559 instance. We do not let any exception propagate past this point.
6560 instead we return NULL.
6561
6562 We also do not print the error message either (which often is very
6563 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6564 the caller print a more meaningful message if necessary. */
6565 try
6566 {
6567 struct value *tsd = ada_get_tsd_from_tag (tag);
6568
6569 if (tsd != NULL)
6570 name = ada_tag_name_from_tsd (tsd);
6571 }
6572 catch (const gdb_exception_error &e)
6573 {
6574 }
6575
6576 return name;
6577 }
6578
6579 /* The parent type of TYPE, or NULL if none. */
6580
6581 struct type *
6582 ada_parent_type (struct type *type)
6583 {
6584 int i;
6585
6586 type = ada_check_typedef (type);
6587
6588 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6589 return NULL;
6590
6591 for (i = 0; i < type->num_fields (); i += 1)
6592 if (ada_is_parent_field (type, i))
6593 {
6594 struct type *parent_type = type->field (i).type ();
6595
6596 /* If the _parent field is a pointer, then dereference it. */
6597 if (parent_type->code () == TYPE_CODE_PTR)
6598 parent_type = parent_type->target_type ();
6599 /* If there is a parallel XVS type, get the actual base type. */
6600 parent_type = ada_get_base_type (parent_type);
6601
6602 return ada_check_typedef (parent_type);
6603 }
6604
6605 return NULL;
6606 }
6607
6608 /* True iff field number FIELD_NUM of structure type TYPE contains the
6609 parent-type (inherited) fields of a derived type. Assumes TYPE is
6610 a structure type with at least FIELD_NUM+1 fields. */
6611
6612 int
6613 ada_is_parent_field (struct type *type, int field_num)
6614 {
6615 const char *name = ada_check_typedef (type)->field (field_num).name ();
6616
6617 return (name != NULL
6618 && (startswith (name, "PARENT")
6619 || startswith (name, "_parent")));
6620 }
6621
6622 /* True iff field number FIELD_NUM of structure type TYPE is a
6623 transparent wrapper field (which should be silently traversed when doing
6624 field selection and flattened when printing). Assumes TYPE is a
6625 structure type with at least FIELD_NUM+1 fields. Such fields are always
6626 structures. */
6627
6628 int
6629 ada_is_wrapper_field (struct type *type, int field_num)
6630 {
6631 const char *name = type->field (field_num).name ();
6632
6633 if (name != NULL && strcmp (name, "RETVAL") == 0)
6634 {
6635 /* This happens in functions with "out" or "in out" parameters
6636 which are passed by copy. For such functions, GNAT describes
6637 the function's return type as being a struct where the return
6638 value is in a field called RETVAL, and where the other "out"
6639 or "in out" parameters are fields of that struct. This is not
6640 a wrapper. */
6641 return 0;
6642 }
6643
6644 return (name != NULL
6645 && (startswith (name, "PARENT")
6646 || strcmp (name, "REP") == 0
6647 || startswith (name, "_parent")
6648 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6649 }
6650
6651 /* True iff field number FIELD_NUM of structure or union type TYPE
6652 is a variant wrapper. Assumes TYPE is a structure type with at least
6653 FIELD_NUM+1 fields. */
6654
6655 int
6656 ada_is_variant_part (struct type *type, int field_num)
6657 {
6658 /* Only Ada types are eligible. */
6659 if (!ADA_TYPE_P (type))
6660 return 0;
6661
6662 struct type *field_type = type->field (field_num).type ();
6663
6664 return (field_type->code () == TYPE_CODE_UNION
6665 || (is_dynamic_field (type, field_num)
6666 && (field_type->target_type ()->code ()
6667 == TYPE_CODE_UNION)));
6668 }
6669
6670 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6671 whose discriminants are contained in the record type OUTER_TYPE,
6672 returns the type of the controlling discriminant for the variant.
6673 May return NULL if the type could not be found. */
6674
6675 struct type *
6676 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6677 {
6678 const char *name = ada_variant_discrim_name (var_type);
6679
6680 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6681 }
6682
6683 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6684 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6685 represents a 'when others' clause; otherwise 0. */
6686
6687 static int
6688 ada_is_others_clause (struct type *type, int field_num)
6689 {
6690 const char *name = type->field (field_num).name ();
6691
6692 return (name != NULL && name[0] == 'O');
6693 }
6694
6695 /* Assuming that TYPE0 is the type of the variant part of a record,
6696 returns the name of the discriminant controlling the variant.
6697 The value is valid until the next call to ada_variant_discrim_name. */
6698
6699 const char *
6700 ada_variant_discrim_name (struct type *type0)
6701 {
6702 static std::string result;
6703 struct type *type;
6704 const char *name;
6705 const char *discrim_end;
6706 const char *discrim_start;
6707
6708 if (type0->code () == TYPE_CODE_PTR)
6709 type = type0->target_type ();
6710 else
6711 type = type0;
6712
6713 name = ada_type_name (type);
6714
6715 if (name == NULL || name[0] == '\000')
6716 return "";
6717
6718 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6719 discrim_end -= 1)
6720 {
6721 if (startswith (discrim_end, "___XVN"))
6722 break;
6723 }
6724 if (discrim_end == name)
6725 return "";
6726
6727 for (discrim_start = discrim_end; discrim_start != name + 3;
6728 discrim_start -= 1)
6729 {
6730 if (discrim_start == name + 1)
6731 return "";
6732 if ((discrim_start > name + 3
6733 && startswith (discrim_start - 3, "___"))
6734 || discrim_start[-1] == '.')
6735 break;
6736 }
6737
6738 result = std::string (discrim_start, discrim_end - discrim_start);
6739 return result.c_str ();
6740 }
6741
6742 /* Scan STR for a subtype-encoded number, beginning at position K.
6743 Put the position of the character just past the number scanned in
6744 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6745 Return 1 if there was a valid number at the given position, and 0
6746 otherwise. A "subtype-encoded" number consists of the absolute value
6747 in decimal, followed by the letter 'm' to indicate a negative number.
6748 Assumes 0m does not occur. */
6749
6750 int
6751 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6752 {
6753 ULONGEST RU;
6754
6755 if (!isdigit (str[k]))
6756 return 0;
6757
6758 /* Do it the hard way so as not to make any assumption about
6759 the relationship of unsigned long (%lu scan format code) and
6760 LONGEST. */
6761 RU = 0;
6762 while (isdigit (str[k]))
6763 {
6764 RU = RU * 10 + (str[k] - '0');
6765 k += 1;
6766 }
6767
6768 if (str[k] == 'm')
6769 {
6770 if (R != NULL)
6771 *R = (-(LONGEST) (RU - 1)) - 1;
6772 k += 1;
6773 }
6774 else if (R != NULL)
6775 *R = (LONGEST) RU;
6776
6777 /* NOTE on the above: Technically, C does not say what the results of
6778 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6779 number representable as a LONGEST (although either would probably work
6780 in most implementations). When RU>0, the locution in the then branch
6781 above is always equivalent to the negative of RU. */
6782
6783 if (new_k != NULL)
6784 *new_k = k;
6785 return 1;
6786 }
6787
6788 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6789 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6790 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6791
6792 static int
6793 ada_in_variant (LONGEST val, struct type *type, int field_num)
6794 {
6795 const char *name = type->field (field_num).name ();
6796 int p;
6797
6798 p = 0;
6799 while (1)
6800 {
6801 switch (name[p])
6802 {
6803 case '\0':
6804 return 0;
6805 case 'S':
6806 {
6807 LONGEST W;
6808
6809 if (!ada_scan_number (name, p + 1, &W, &p))
6810 return 0;
6811 if (val == W)
6812 return 1;
6813 break;
6814 }
6815 case 'R':
6816 {
6817 LONGEST L, U;
6818
6819 if (!ada_scan_number (name, p + 1, &L, &p)
6820 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6821 return 0;
6822 if (val >= L && val <= U)
6823 return 1;
6824 break;
6825 }
6826 case 'O':
6827 return 1;
6828 default:
6829 return 0;
6830 }
6831 }
6832 }
6833
6834 /* FIXME: Lots of redundancy below. Try to consolidate. */
6835
6836 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6837 ARG_TYPE, extract and return the value of one of its (non-static)
6838 fields. FIELDNO says which field. Differs from value_primitive_field
6839 only in that it can handle packed values of arbitrary type. */
6840
6841 struct value *
6842 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6843 struct type *arg_type)
6844 {
6845 struct type *type;
6846
6847 arg_type = ada_check_typedef (arg_type);
6848 type = arg_type->field (fieldno).type ();
6849
6850 /* Handle packed fields. It might be that the field is not packed
6851 relative to its containing structure, but the structure itself is
6852 packed; in this case we must take the bit-field path. */
6853 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
6854 {
6855 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6856 int bit_size = arg_type->field (fieldno).bitsize ();
6857
6858 return ada_value_primitive_packed_val (arg1,
6859 arg1->contents ().data (),
6860 offset + bit_pos / 8,
6861 bit_pos % 8, bit_size, type);
6862 }
6863 else
6864 return arg1->primitive_field (offset, fieldno, arg_type);
6865 }
6866
6867 /* Find field with name NAME in object of type TYPE. If found,
6868 set the following for each argument that is non-null:
6869 - *FIELD_TYPE_P to the field's type;
6870 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6871 an object of that type;
6872 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6873 - *BIT_SIZE_P to its size in bits if the field is packed, and
6874 0 otherwise;
6875 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6876 fields up to but not including the desired field, or by the total
6877 number of fields if not found. A NULL value of NAME never
6878 matches; the function just counts visible fields in this case.
6879
6880 Notice that we need to handle when a tagged record hierarchy
6881 has some components with the same name, like in this scenario:
6882
6883 type Top_T is tagged record
6884 N : Integer := 1;
6885 U : Integer := 974;
6886 A : Integer := 48;
6887 end record;
6888
6889 type Middle_T is new Top.Top_T with record
6890 N : Character := 'a';
6891 C : Integer := 3;
6892 end record;
6893
6894 type Bottom_T is new Middle.Middle_T with record
6895 N : Float := 4.0;
6896 C : Character := '5';
6897 X : Integer := 6;
6898 A : Character := 'J';
6899 end record;
6900
6901 Let's say we now have a variable declared and initialized as follow:
6902
6903 TC : Top_A := new Bottom_T;
6904
6905 And then we use this variable to call this function
6906
6907 procedure Assign (Obj: in out Top_T; TV : Integer);
6908
6909 as follow:
6910
6911 Assign (Top_T (B), 12);
6912
6913 Now, we're in the debugger, and we're inside that procedure
6914 then and we want to print the value of obj.c:
6915
6916 Usually, the tagged record or one of the parent type owns the
6917 component to print and there's no issue but in this particular
6918 case, what does it mean to ask for Obj.C? Since the actual
6919 type for object is type Bottom_T, it could mean two things: type
6920 component C from the Middle_T view, but also component C from
6921 Bottom_T. So in that "undefined" case, when the component is
6922 not found in the non-resolved type (which includes all the
6923 components of the parent type), then resolve it and see if we
6924 get better luck once expanded.
6925
6926 In the case of homonyms in the derived tagged type, we don't
6927 guaranty anything, and pick the one that's easiest for us
6928 to program.
6929
6930 Returns 1 if found, 0 otherwise. */
6931
6932 static int
6933 find_struct_field (const char *name, struct type *type, int offset,
6934 struct type **field_type_p,
6935 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6936 int *index_p)
6937 {
6938 int i;
6939 int parent_offset = -1;
6940
6941 type = ada_check_typedef (type);
6942
6943 if (field_type_p != NULL)
6944 *field_type_p = NULL;
6945 if (byte_offset_p != NULL)
6946 *byte_offset_p = 0;
6947 if (bit_offset_p != NULL)
6948 *bit_offset_p = 0;
6949 if (bit_size_p != NULL)
6950 *bit_size_p = 0;
6951
6952 for (i = 0; i < type->num_fields (); i += 1)
6953 {
6954 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6955 type. However, we only need the values to be correct when
6956 the caller asks for them. */
6957 int bit_pos = 0, fld_offset = 0;
6958 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6959 {
6960 bit_pos = type->field (i).loc_bitpos ();
6961 fld_offset = offset + bit_pos / 8;
6962 }
6963
6964 const char *t_field_name = type->field (i).name ();
6965
6966 if (t_field_name == NULL)
6967 continue;
6968
6969 else if (ada_is_parent_field (type, i))
6970 {
6971 /* This is a field pointing us to the parent type of a tagged
6972 type. As hinted in this function's documentation, we give
6973 preference to fields in the current record first, so what
6974 we do here is just record the index of this field before
6975 we skip it. If it turns out we couldn't find our field
6976 in the current record, then we'll get back to it and search
6977 inside it whether the field might exist in the parent. */
6978
6979 parent_offset = i;
6980 continue;
6981 }
6982
6983 else if (name != NULL && field_name_match (t_field_name, name))
6984 {
6985 int bit_size = type->field (i).bitsize ();
6986
6987 if (field_type_p != NULL)
6988 *field_type_p = type->field (i).type ();
6989 if (byte_offset_p != NULL)
6990 *byte_offset_p = fld_offset;
6991 if (bit_offset_p != NULL)
6992 *bit_offset_p = bit_pos % 8;
6993 if (bit_size_p != NULL)
6994 *bit_size_p = bit_size;
6995 return 1;
6996 }
6997 else if (ada_is_wrapper_field (type, i))
6998 {
6999 if (find_struct_field (name, type->field (i).type (), fld_offset,
7000 field_type_p, byte_offset_p, bit_offset_p,
7001 bit_size_p, index_p))
7002 return 1;
7003 }
7004 else if (ada_is_variant_part (type, i))
7005 {
7006 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7007 fixed type?? */
7008 int j;
7009 struct type *field_type
7010 = ada_check_typedef (type->field (i).type ());
7011
7012 for (j = 0; j < field_type->num_fields (); j += 1)
7013 {
7014 if (find_struct_field (name, field_type->field (j).type (),
7015 fld_offset
7016 + field_type->field (j).loc_bitpos () / 8,
7017 field_type_p, byte_offset_p,
7018 bit_offset_p, bit_size_p, index_p))
7019 return 1;
7020 }
7021 }
7022 else if (index_p != NULL)
7023 *index_p += 1;
7024 }
7025
7026 /* Field not found so far. If this is a tagged type which
7027 has a parent, try finding that field in the parent now. */
7028
7029 if (parent_offset != -1)
7030 {
7031 /* As above, only compute the offset when truly needed. */
7032 int fld_offset = offset;
7033 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7034 {
7035 int bit_pos = type->field (parent_offset).loc_bitpos ();
7036 fld_offset += bit_pos / 8;
7037 }
7038
7039 if (find_struct_field (name, type->field (parent_offset).type (),
7040 fld_offset, field_type_p, byte_offset_p,
7041 bit_offset_p, bit_size_p, index_p))
7042 return 1;
7043 }
7044
7045 return 0;
7046 }
7047
7048 /* Number of user-visible fields in record type TYPE. */
7049
7050 static int
7051 num_visible_fields (struct type *type)
7052 {
7053 int n;
7054
7055 n = 0;
7056 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7057 return n;
7058 }
7059
7060 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7061 and search in it assuming it has (class) type TYPE.
7062 If found, return value, else return NULL.
7063
7064 Searches recursively through wrapper fields (e.g., '_parent').
7065
7066 In the case of homonyms in the tagged types, please refer to the
7067 long explanation in find_struct_field's function documentation. */
7068
7069 static struct value *
7070 ada_search_struct_field (const char *name, struct value *arg, int offset,
7071 struct type *type)
7072 {
7073 int i;
7074 int parent_offset = -1;
7075
7076 type = ada_check_typedef (type);
7077 for (i = 0; i < type->num_fields (); i += 1)
7078 {
7079 const char *t_field_name = type->field (i).name ();
7080
7081 if (t_field_name == NULL)
7082 continue;
7083
7084 else if (ada_is_parent_field (type, i))
7085 {
7086 /* This is a field pointing us to the parent type of a tagged
7087 type. As hinted in this function's documentation, we give
7088 preference to fields in the current record first, so what
7089 we do here is just record the index of this field before
7090 we skip it. If it turns out we couldn't find our field
7091 in the current record, then we'll get back to it and search
7092 inside it whether the field might exist in the parent. */
7093
7094 parent_offset = i;
7095 continue;
7096 }
7097
7098 else if (field_name_match (t_field_name, name))
7099 return ada_value_primitive_field (arg, offset, i, type);
7100
7101 else if (ada_is_wrapper_field (type, i))
7102 {
7103 struct value *v = /* Do not let indent join lines here. */
7104 ada_search_struct_field (name, arg,
7105 offset + type->field (i).loc_bitpos () / 8,
7106 type->field (i).type ());
7107
7108 if (v != NULL)
7109 return v;
7110 }
7111
7112 else if (ada_is_variant_part (type, i))
7113 {
7114 /* PNH: Do we ever get here? See find_struct_field. */
7115 int j;
7116 struct type *field_type = ada_check_typedef (type->field (i).type ());
7117 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7118
7119 for (j = 0; j < field_type->num_fields (); j += 1)
7120 {
7121 struct value *v = ada_search_struct_field /* Force line
7122 break. */
7123 (name, arg,
7124 var_offset + field_type->field (j).loc_bitpos () / 8,
7125 field_type->field (j).type ());
7126
7127 if (v != NULL)
7128 return v;
7129 }
7130 }
7131 }
7132
7133 /* Field not found so far. If this is a tagged type which
7134 has a parent, try finding that field in the parent now. */
7135
7136 if (parent_offset != -1)
7137 {
7138 struct value *v = ada_search_struct_field (
7139 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7140 type->field (parent_offset).type ());
7141
7142 if (v != NULL)
7143 return v;
7144 }
7145
7146 return NULL;
7147 }
7148
7149 static struct value *ada_index_struct_field_1 (int *, struct value *,
7150 int, struct type *);
7151
7152
7153 /* Return field #INDEX in ARG, where the index is that returned by
7154 * find_struct_field through its INDEX_P argument. Adjust the address
7155 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7156 * If found, return value, else return NULL. */
7157
7158 static struct value *
7159 ada_index_struct_field (int index, struct value *arg, int offset,
7160 struct type *type)
7161 {
7162 return ada_index_struct_field_1 (&index, arg, offset, type);
7163 }
7164
7165
7166 /* Auxiliary function for ada_index_struct_field. Like
7167 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7168 * *INDEX_P. */
7169
7170 static struct value *
7171 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7172 struct type *type)
7173 {
7174 int i;
7175 type = ada_check_typedef (type);
7176
7177 for (i = 0; i < type->num_fields (); i += 1)
7178 {
7179 if (type->field (i).name () == NULL)
7180 continue;
7181 else if (ada_is_wrapper_field (type, i))
7182 {
7183 struct value *v = /* Do not let indent join lines here. */
7184 ada_index_struct_field_1 (index_p, arg,
7185 offset + type->field (i).loc_bitpos () / 8,
7186 type->field (i).type ());
7187
7188 if (v != NULL)
7189 return v;
7190 }
7191
7192 else if (ada_is_variant_part (type, i))
7193 {
7194 /* PNH: Do we ever get here? See ada_search_struct_field,
7195 find_struct_field. */
7196 error (_("Cannot assign this kind of variant record"));
7197 }
7198 else if (*index_p == 0)
7199 return ada_value_primitive_field (arg, offset, i, type);
7200 else
7201 *index_p -= 1;
7202 }
7203 return NULL;
7204 }
7205
7206 /* Return a string representation of type TYPE. */
7207
7208 static std::string
7209 type_as_string (struct type *type)
7210 {
7211 string_file tmp_stream;
7212
7213 type_print (type, "", &tmp_stream, -1);
7214
7215 return tmp_stream.release ();
7216 }
7217
7218 /* Given a type TYPE, look up the type of the component of type named NAME.
7219
7220 Matches any field whose name has NAME as a prefix, possibly
7221 followed by "___".
7222
7223 TYPE can be either a struct or union. If REFOK, TYPE may also
7224 be a (pointer or reference)+ to a struct or union, and the
7225 ultimate target type will be searched.
7226
7227 Looks recursively into variant clauses and parent types.
7228
7229 In the case of homonyms in the tagged types, please refer to the
7230 long explanation in find_struct_field's function documentation.
7231
7232 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7233 TYPE is not a type of the right kind. */
7234
7235 static struct type *
7236 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7237 int noerr)
7238 {
7239 if (name == NULL)
7240 goto BadName;
7241
7242 if (refok && type != NULL)
7243 while (1)
7244 {
7245 type = ada_check_typedef (type);
7246 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7247 break;
7248 type = type->target_type ();
7249 }
7250
7251 if (type == NULL
7252 || (type->code () != TYPE_CODE_STRUCT
7253 && type->code () != TYPE_CODE_UNION))
7254 {
7255 if (noerr)
7256 return NULL;
7257
7258 error (_("Type %s is not a structure or union type"),
7259 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7260 }
7261
7262 type = to_static_fixed_type (type);
7263
7264 struct type *result;
7265 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7266 nullptr);
7267 if (result != nullptr)
7268 return result;
7269
7270 BadName:
7271 if (!noerr)
7272 {
7273 const char *name_str = name != NULL ? name : _("<null>");
7274
7275 error (_("Type %s has no component named %s"),
7276 type_as_string (type).c_str (), name_str);
7277 }
7278
7279 return NULL;
7280 }
7281
7282 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7283 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7284 represents an unchecked union (that is, the variant part of a
7285 record that is named in an Unchecked_Union pragma). */
7286
7287 static int
7288 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7289 {
7290 const char *discrim_name = ada_variant_discrim_name (var_type);
7291
7292 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7293 }
7294
7295
7296 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7297 within OUTER, determine which variant clause (field number in VAR_TYPE,
7298 numbering from 0) is applicable. Returns -1 if none are. */
7299
7300 int
7301 ada_which_variant_applies (struct type *var_type, struct value *outer)
7302 {
7303 int others_clause;
7304 int i;
7305 const char *discrim_name = ada_variant_discrim_name (var_type);
7306 struct value *discrim;
7307 LONGEST discrim_val;
7308
7309 /* Using plain value_from_contents_and_address here causes problems
7310 because we will end up trying to resolve a type that is currently
7311 being constructed. */
7312 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7313 if (discrim == NULL)
7314 return -1;
7315 discrim_val = value_as_long (discrim);
7316
7317 others_clause = -1;
7318 for (i = 0; i < var_type->num_fields (); i += 1)
7319 {
7320 if (ada_is_others_clause (var_type, i))
7321 others_clause = i;
7322 else if (ada_in_variant (discrim_val, var_type, i))
7323 return i;
7324 }
7325
7326 return others_clause;
7327 }
7328 \f
7329
7330
7331 /* Dynamic-Sized Records */
7332
7333 /* Strategy: The type ostensibly attached to a value with dynamic size
7334 (i.e., a size that is not statically recorded in the debugging
7335 data) does not accurately reflect the size or layout of the value.
7336 Our strategy is to convert these values to values with accurate,
7337 conventional types that are constructed on the fly. */
7338
7339 /* There is a subtle and tricky problem here. In general, we cannot
7340 determine the size of dynamic records without its data. However,
7341 the 'struct value' data structure, which GDB uses to represent
7342 quantities in the inferior process (the target), requires the size
7343 of the type at the time of its allocation in order to reserve space
7344 for GDB's internal copy of the data. That's why the
7345 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7346 rather than struct value*s.
7347
7348 However, GDB's internal history variables ($1, $2, etc.) are
7349 struct value*s containing internal copies of the data that are not, in
7350 general, the same as the data at their corresponding addresses in
7351 the target. Fortunately, the types we give to these values are all
7352 conventional, fixed-size types (as per the strategy described
7353 above), so that we don't usually have to perform the
7354 'to_fixed_xxx_type' conversions to look at their values.
7355 Unfortunately, there is one exception: if one of the internal
7356 history variables is an array whose elements are unconstrained
7357 records, then we will need to create distinct fixed types for each
7358 element selected. */
7359
7360 /* The upshot of all of this is that many routines take a (type, host
7361 address, target address) triple as arguments to represent a value.
7362 The host address, if non-null, is supposed to contain an internal
7363 copy of the relevant data; otherwise, the program is to consult the
7364 target at the target address. */
7365
7366 /* Assuming that VAL0 represents a pointer value, the result of
7367 dereferencing it. Differs from value_ind in its treatment of
7368 dynamic-sized types. */
7369
7370 struct value *
7371 ada_value_ind (struct value *val0)
7372 {
7373 struct value *val = value_ind (val0);
7374
7375 if (ada_is_tagged_type (val->type (), 0))
7376 val = ada_tag_value_at_base_address (val);
7377
7378 return ada_to_fixed_value (val);
7379 }
7380
7381 /* The value resulting from dereferencing any "reference to"
7382 qualifiers on VAL0. */
7383
7384 static struct value *
7385 ada_coerce_ref (struct value *val0)
7386 {
7387 if (val0->type ()->code () == TYPE_CODE_REF)
7388 {
7389 struct value *val = val0;
7390
7391 val = coerce_ref (val);
7392
7393 if (ada_is_tagged_type (val->type (), 0))
7394 val = ada_tag_value_at_base_address (val);
7395
7396 return ada_to_fixed_value (val);
7397 }
7398 else
7399 return val0;
7400 }
7401
7402 /* Return the bit alignment required for field #F of template type TYPE. */
7403
7404 static unsigned int
7405 field_alignment (struct type *type, int f)
7406 {
7407 const char *name = type->field (f).name ();
7408 int len;
7409 int align_offset;
7410
7411 /* The field name should never be null, unless the debugging information
7412 is somehow malformed. In this case, we assume the field does not
7413 require any alignment. */
7414 if (name == NULL)
7415 return 1;
7416
7417 len = strlen (name);
7418
7419 if (!isdigit (name[len - 1]))
7420 return 1;
7421
7422 if (isdigit (name[len - 2]))
7423 align_offset = len - 2;
7424 else
7425 align_offset = len - 1;
7426
7427 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7428 return TARGET_CHAR_BIT;
7429
7430 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7431 }
7432
7433 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7434
7435 static struct symbol *
7436 ada_find_any_type_symbol (const char *name)
7437 {
7438 return standard_lookup (name, get_selected_block (nullptr),
7439 SEARCH_TYPE_DOMAIN);
7440 }
7441
7442 /* Find a type named NAME. Ignores ambiguity. This routine will look
7443 solely for types defined by debug info, it will not search the GDB
7444 primitive types. */
7445
7446 static struct type *
7447 ada_find_any_type (const char *name)
7448 {
7449 struct symbol *sym = ada_find_any_type_symbol (name);
7450
7451 if (sym != NULL)
7452 return sym->type ();
7453
7454 return NULL;
7455 }
7456
7457 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7458 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7459 symbol, in which case it is returned. Otherwise, this looks for
7460 symbols whose name is that of NAME_SYM suffixed with "___XR".
7461 Return symbol if found, and NULL otherwise. */
7462
7463 static bool
7464 ada_is_renaming_symbol (struct symbol *name_sym)
7465 {
7466 const char *name = name_sym->linkage_name ();
7467 return strstr (name, "___XR") != NULL;
7468 }
7469
7470 /* Because of GNAT encoding conventions, several GDB symbols may match a
7471 given type name. If the type denoted by TYPE0 is to be preferred to
7472 that of TYPE1 for purposes of type printing, return non-zero;
7473 otherwise return 0. */
7474
7475 int
7476 ada_prefer_type (struct type *type0, struct type *type1)
7477 {
7478 if (type1 == NULL)
7479 return 1;
7480 else if (type0 == NULL)
7481 return 0;
7482 else if (type1->code () == TYPE_CODE_VOID)
7483 return 1;
7484 else if (type0->code () == TYPE_CODE_VOID)
7485 return 0;
7486 else if (type1->name () == NULL && type0->name () != NULL)
7487 return 1;
7488 else if (ada_is_constrained_packed_array_type (type0))
7489 return 1;
7490 else if (ada_is_array_descriptor_type (type0)
7491 && !ada_is_array_descriptor_type (type1))
7492 return 1;
7493 else
7494 {
7495 const char *type0_name = type0->name ();
7496 const char *type1_name = type1->name ();
7497
7498 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7499 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7500 return 1;
7501 }
7502 return 0;
7503 }
7504
7505 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7506 null. */
7507
7508 const char *
7509 ada_type_name (struct type *type)
7510 {
7511 if (type == NULL)
7512 return NULL;
7513 return type->name ();
7514 }
7515
7516 /* Search the list of "descriptive" types associated to TYPE for a type
7517 whose name is NAME. */
7518
7519 static struct type *
7520 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7521 {
7522 struct type *result, *tmp;
7523
7524 if (ada_ignore_descriptive_types_p)
7525 return NULL;
7526
7527 /* If there no descriptive-type info, then there is no parallel type
7528 to be found. */
7529 if (!HAVE_GNAT_AUX_INFO (type))
7530 return NULL;
7531
7532 result = TYPE_DESCRIPTIVE_TYPE (type);
7533 while (result != NULL)
7534 {
7535 const char *result_name = ada_type_name (result);
7536
7537 if (result_name == NULL)
7538 {
7539 warning (_("unexpected null name on descriptive type"));
7540 return NULL;
7541 }
7542
7543 /* If the names match, stop. */
7544 if (strcmp (result_name, name) == 0)
7545 break;
7546
7547 /* Otherwise, look at the next item on the list, if any. */
7548 if (HAVE_GNAT_AUX_INFO (result))
7549 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7550 else
7551 tmp = NULL;
7552
7553 /* If not found either, try after having resolved the typedef. */
7554 if (tmp != NULL)
7555 result = tmp;
7556 else
7557 {
7558 result = check_typedef (result);
7559 if (HAVE_GNAT_AUX_INFO (result))
7560 result = TYPE_DESCRIPTIVE_TYPE (result);
7561 else
7562 result = NULL;
7563 }
7564 }
7565
7566 /* If we didn't find a match, see whether this is a packed array. With
7567 older compilers, the descriptive type information is either absent or
7568 irrelevant when it comes to packed arrays so the above lookup fails.
7569 Fall back to using a parallel lookup by name in this case. */
7570 if (result == NULL && ada_is_constrained_packed_array_type (type))
7571 return ada_find_any_type (name);
7572
7573 return result;
7574 }
7575
7576 /* Find a parallel type to TYPE with the specified NAME, using the
7577 descriptive type taken from the debugging information, if available,
7578 and otherwise using the (slower) name-based method. */
7579
7580 static struct type *
7581 ada_find_parallel_type_with_name (struct type *type, const char *name)
7582 {
7583 struct type *result = NULL;
7584
7585 if (HAVE_GNAT_AUX_INFO (type))
7586 result = find_parallel_type_by_descriptive_type (type, name);
7587 else
7588 result = ada_find_any_type (name);
7589
7590 return result;
7591 }
7592
7593 /* Same as above, but specify the name of the parallel type by appending
7594 SUFFIX to the name of TYPE. */
7595
7596 struct type *
7597 ada_find_parallel_type (struct type *type, const char *suffix)
7598 {
7599 char *name;
7600 const char *type_name = ada_type_name (type);
7601 int len;
7602
7603 if (type_name == NULL)
7604 return NULL;
7605
7606 len = strlen (type_name);
7607
7608 name = (char *) alloca (len + strlen (suffix) + 1);
7609
7610 strcpy (name, type_name);
7611 strcpy (name + len, suffix);
7612
7613 return ada_find_parallel_type_with_name (type, name);
7614 }
7615
7616 /* If TYPE is a variable-size record type, return the corresponding template
7617 type describing its fields. Otherwise, return NULL. */
7618
7619 static struct type *
7620 dynamic_template_type (struct type *type)
7621 {
7622 type = ada_check_typedef (type);
7623
7624 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7625 || ada_type_name (type) == NULL)
7626 return NULL;
7627 else
7628 {
7629 int len = strlen (ada_type_name (type));
7630
7631 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7632 return type;
7633 else
7634 return ada_find_parallel_type (type, "___XVE");
7635 }
7636 }
7637
7638 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7639 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7640
7641 static int
7642 is_dynamic_field (struct type *templ_type, int field_num)
7643 {
7644 const char *name = templ_type->field (field_num).name ();
7645
7646 return name != NULL
7647 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7648 && strstr (name, "___XVL") != NULL;
7649 }
7650
7651 /* The index of the variant field of TYPE, or -1 if TYPE does not
7652 represent a variant record type. */
7653
7654 static int
7655 variant_field_index (struct type *type)
7656 {
7657 int f;
7658
7659 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7660 return -1;
7661
7662 for (f = 0; f < type->num_fields (); f += 1)
7663 {
7664 if (ada_is_variant_part (type, f))
7665 return f;
7666 }
7667 return -1;
7668 }
7669
7670 /* A record type with no fields. */
7671
7672 static struct type *
7673 empty_record (struct type *templ)
7674 {
7675 struct type *type = type_allocator (templ).new_type ();
7676
7677 type->set_code (TYPE_CODE_STRUCT);
7678 INIT_NONE_SPECIFIC (type);
7679 type->set_name ("<empty>");
7680 type->set_length (0);
7681 return type;
7682 }
7683
7684 /* An ordinary record type (with fixed-length fields) that describes
7685 the value of type TYPE at VALADDR or ADDRESS (see comments at
7686 the beginning of this section) VAL according to GNAT conventions.
7687 DVAL0 should describe the (portion of a) record that contains any
7688 necessary discriminants. It should be NULL if VAL->type () is
7689 an outer-level type (i.e., as opposed to a branch of a variant.) A
7690 variant field (unless unchecked) is replaced by a particular branch
7691 of the variant.
7692
7693 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7694 length are not statically known are discarded. As a consequence,
7695 VALADDR, ADDRESS and DVAL0 are ignored.
7696
7697 NOTE: Limitations: For now, we assume that dynamic fields and
7698 variants occupy whole numbers of bytes. However, they need not be
7699 byte-aligned. */
7700
7701 struct type *
7702 ada_template_to_fixed_record_type_1 (struct type *type,
7703 const gdb_byte *valaddr,
7704 CORE_ADDR address, struct value *dval0,
7705 int keep_dynamic_fields)
7706 {
7707 struct value *dval;
7708 struct type *rtype;
7709 int nfields, bit_len;
7710 int variant_field;
7711 long off;
7712 int fld_bit_len;
7713 int f;
7714
7715 scoped_value_mark mark;
7716
7717 /* Compute the number of fields in this record type that are going
7718 to be processed: unless keep_dynamic_fields, this includes only
7719 fields whose position and length are static will be processed. */
7720 if (keep_dynamic_fields)
7721 nfields = type->num_fields ();
7722 else
7723 {
7724 nfields = 0;
7725 while (nfields < type->num_fields ()
7726 && !ada_is_variant_part (type, nfields)
7727 && !is_dynamic_field (type, nfields))
7728 nfields++;
7729 }
7730
7731 rtype = type_allocator (type).new_type ();
7732 rtype->set_code (TYPE_CODE_STRUCT);
7733 INIT_NONE_SPECIFIC (rtype);
7734 rtype->alloc_fields (nfields);
7735 rtype->set_name (ada_type_name (type));
7736 rtype->set_is_fixed_instance (true);
7737
7738 off = 0;
7739 bit_len = 0;
7740 variant_field = -1;
7741
7742 for (f = 0; f < nfields; f += 1)
7743 {
7744 off = align_up (off, field_alignment (type, f))
7745 + type->field (f).loc_bitpos ();
7746 rtype->field (f).set_loc_bitpos (off);
7747 rtype->field (f).set_bitsize (0);
7748
7749 if (ada_is_variant_part (type, f))
7750 {
7751 variant_field = f;
7752 fld_bit_len = 0;
7753 }
7754 else if (is_dynamic_field (type, f))
7755 {
7756 const gdb_byte *field_valaddr = valaddr;
7757 CORE_ADDR field_address = address;
7758 struct type *field_type = type->field (f).type ()->target_type ();
7759
7760 if (dval0 == NULL)
7761 {
7762 /* Using plain value_from_contents_and_address here
7763 causes problems because we will end up trying to
7764 resolve a type that is currently being
7765 constructed. */
7766 dval = value_from_contents_and_address_unresolved (rtype,
7767 valaddr,
7768 address);
7769 rtype = dval->type ();
7770 }
7771 else
7772 dval = dval0;
7773
7774 /* If the type referenced by this field is an aligner type, we need
7775 to unwrap that aligner type, because its size might not be set.
7776 Keeping the aligner type would cause us to compute the wrong
7777 size for this field, impacting the offset of the all the fields
7778 that follow this one. */
7779 if (ada_is_aligner_type (field_type))
7780 {
7781 long field_offset = type->field (f).loc_bitpos ();
7782
7783 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7784 field_address = cond_offset_target (field_address, field_offset);
7785 field_type = ada_aligned_type (field_type);
7786 }
7787
7788 field_valaddr = cond_offset_host (field_valaddr,
7789 off / TARGET_CHAR_BIT);
7790 field_address = cond_offset_target (field_address,
7791 off / TARGET_CHAR_BIT);
7792
7793 /* Get the fixed type of the field. Note that, in this case,
7794 we do not want to get the real type out of the tag: if
7795 the current field is the parent part of a tagged record,
7796 we will get the tag of the object. Clearly wrong: the real
7797 type of the parent is not the real type of the child. We
7798 would end up in an infinite loop. */
7799 field_type = ada_get_base_type (field_type);
7800 field_type = ada_to_fixed_type (field_type, field_valaddr,
7801 field_address, dval, 0);
7802
7803 rtype->field (f).set_type (field_type);
7804 rtype->field (f).set_name (type->field (f).name ());
7805 /* The multiplication can potentially overflow. But because
7806 the field length has been size-checked just above, and
7807 assuming that the maximum size is a reasonable value,
7808 an overflow should not happen in practice. So rather than
7809 adding overflow recovery code to this already complex code,
7810 we just assume that it's not going to happen. */
7811 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7812 }
7813 else
7814 {
7815 /* Note: If this field's type is a typedef, it is important
7816 to preserve the typedef layer.
7817
7818 Otherwise, we might be transforming a typedef to a fat
7819 pointer (encoding a pointer to an unconstrained array),
7820 into a basic fat pointer (encoding an unconstrained
7821 array). As both types are implemented using the same
7822 structure, the typedef is the only clue which allows us
7823 to distinguish between the two options. Stripping it
7824 would prevent us from printing this field appropriately. */
7825 rtype->field (f).set_type (type->field (f).type ());
7826 rtype->field (f).set_name (type->field (f).name ());
7827 if (type->field (f).bitsize () > 0)
7828 {
7829 fld_bit_len = type->field (f).bitsize ();
7830 rtype->field (f).set_bitsize (fld_bit_len);
7831 }
7832 else
7833 {
7834 struct type *field_type = type->field (f).type ();
7835
7836 /* We need to be careful of typedefs when computing
7837 the length of our field. If this is a typedef,
7838 get the length of the target type, not the length
7839 of the typedef. */
7840 if (field_type->code () == TYPE_CODE_TYPEDEF)
7841 field_type = ada_typedef_target_type (field_type);
7842
7843 fld_bit_len =
7844 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7845 }
7846 }
7847 if (off + fld_bit_len > bit_len)
7848 bit_len = off + fld_bit_len;
7849 off += fld_bit_len;
7850 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7851 }
7852
7853 /* We handle the variant part, if any, at the end because of certain
7854 odd cases in which it is re-ordered so as NOT to be the last field of
7855 the record. This can happen in the presence of representation
7856 clauses. */
7857 if (variant_field >= 0)
7858 {
7859 struct type *branch_type;
7860
7861 off = rtype->field (variant_field).loc_bitpos ();
7862
7863 if (dval0 == NULL)
7864 {
7865 /* Using plain value_from_contents_and_address here causes
7866 problems because we will end up trying to resolve a type
7867 that is currently being constructed. */
7868 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7869 address);
7870 rtype = dval->type ();
7871 }
7872 else
7873 dval = dval0;
7874
7875 branch_type =
7876 to_fixed_variant_branch_type
7877 (type->field (variant_field).type (),
7878 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7879 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7880 if (branch_type == NULL)
7881 {
7882 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7883 rtype->field (f - 1) = rtype->field (f);
7884 rtype->set_num_fields (rtype->num_fields () - 1);
7885 }
7886 else
7887 {
7888 rtype->field (variant_field).set_type (branch_type);
7889 rtype->field (variant_field).set_name ("S");
7890 fld_bit_len =
7891 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
7892 if (off + fld_bit_len > bit_len)
7893 bit_len = off + fld_bit_len;
7894
7895 rtype->set_length
7896 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7897 }
7898 }
7899
7900 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7901 should contain the alignment of that record, which should be a strictly
7902 positive value. If null or negative, then something is wrong, most
7903 probably in the debug info. In that case, we don't round up the size
7904 of the resulting type. If this record is not part of another structure,
7905 the current RTYPE length might be good enough for our purposes. */
7906 if (type->length () <= 0)
7907 {
7908 if (rtype->name ())
7909 warning (_("Invalid type size for `%s' detected: %s."),
7910 rtype->name (), pulongest (type->length ()));
7911 else
7912 warning (_("Invalid type size for <unnamed> detected: %s."),
7913 pulongest (type->length ()));
7914 }
7915 else
7916 rtype->set_length (align_up (rtype->length (), type->length ()));
7917
7918 return rtype;
7919 }
7920
7921 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7922 of 1. */
7923
7924 static struct type *
7925 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7926 CORE_ADDR address, struct value *dval0)
7927 {
7928 return ada_template_to_fixed_record_type_1 (type, valaddr,
7929 address, dval0, 1);
7930 }
7931
7932 /* An ordinary record type in which ___XVL-convention fields and
7933 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7934 static approximations, containing all possible fields. Uses
7935 no runtime values. Useless for use in values, but that's OK,
7936 since the results are used only for type determinations. Works on both
7937 structs and unions. Representation note: to save space, we memorize
7938 the result of this function in the type::target_type of the
7939 template type. */
7940
7941 static struct type *
7942 template_to_static_fixed_type (struct type *type0)
7943 {
7944 struct type *type;
7945 int nfields;
7946 int f;
7947
7948 /* No need no do anything if the input type is already fixed. */
7949 if (type0->is_fixed_instance ())
7950 return type0;
7951
7952 /* Likewise if we already have computed the static approximation. */
7953 if (type0->target_type () != NULL)
7954 return type0->target_type ();
7955
7956 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
7957 type = type0;
7958 nfields = type0->num_fields ();
7959
7960 /* Whether or not we cloned TYPE0, cache the result so that we don't do
7961 recompute all over next time. */
7962 type0->set_target_type (type);
7963
7964 for (f = 0; f < nfields; f += 1)
7965 {
7966 struct type *field_type = type0->field (f).type ();
7967 struct type *new_type;
7968
7969 if (is_dynamic_field (type0, f))
7970 {
7971 field_type = ada_check_typedef (field_type);
7972 new_type = to_static_fixed_type (field_type->target_type ());
7973 }
7974 else
7975 new_type = static_unwrap_type (field_type);
7976
7977 if (new_type != field_type)
7978 {
7979 /* Clone TYPE0 only the first time we get a new field type. */
7980 if (type == type0)
7981 {
7982 type = type_allocator (type0).new_type ();
7983 type0->set_target_type (type);
7984 type->set_code (type0->code ());
7985 INIT_NONE_SPECIFIC (type);
7986
7987 type->copy_fields (type0);
7988
7989 type->set_name (ada_type_name (type0));
7990 type->set_is_fixed_instance (true);
7991 type->set_length (0);
7992 }
7993 type->field (f).set_type (new_type);
7994 type->field (f).set_name (type0->field (f).name ());
7995 }
7996 }
7997
7998 return type;
7999 }
8000
8001 /* Given an object of type TYPE whose contents are at VALADDR and
8002 whose address in memory is ADDRESS, returns a revision of TYPE,
8003 which should be a non-dynamic-sized record, in which the variant
8004 part, if any, is replaced with the appropriate branch. Looks
8005 for discriminant values in DVAL0, which can be NULL if the record
8006 contains the necessary discriminant values. */
8007
8008 static struct type *
8009 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8010 CORE_ADDR address, struct value *dval0)
8011 {
8012 struct value *dval;
8013 struct type *rtype;
8014 struct type *branch_type;
8015 int nfields = type->num_fields ();
8016 int variant_field = variant_field_index (type);
8017
8018 if (variant_field == -1)
8019 return type;
8020
8021 scoped_value_mark mark;
8022 if (dval0 == NULL)
8023 {
8024 dval = value_from_contents_and_address (type, valaddr, address);
8025 type = dval->type ();
8026 }
8027 else
8028 dval = dval0;
8029
8030 rtype = type_allocator (type).new_type ();
8031 rtype->set_code (TYPE_CODE_STRUCT);
8032 INIT_NONE_SPECIFIC (rtype);
8033 rtype->copy_fields (type);
8034
8035 rtype->set_name (ada_type_name (type));
8036 rtype->set_is_fixed_instance (true);
8037 rtype->set_length (type->length ());
8038
8039 branch_type = to_fixed_variant_branch_type
8040 (type->field (variant_field).type (),
8041 cond_offset_host (valaddr,
8042 type->field (variant_field).loc_bitpos ()
8043 / TARGET_CHAR_BIT),
8044 cond_offset_target (address,
8045 type->field (variant_field).loc_bitpos ()
8046 / TARGET_CHAR_BIT), dval);
8047 if (branch_type == NULL)
8048 {
8049 int f;
8050
8051 for (f = variant_field + 1; f < nfields; f += 1)
8052 rtype->field (f - 1) = rtype->field (f);
8053 rtype->set_num_fields (rtype->num_fields () - 1);
8054 }
8055 else
8056 {
8057 rtype->field (variant_field).set_type (branch_type);
8058 rtype->field (variant_field).set_name ("S");
8059 rtype->field (variant_field).set_bitsize (0);
8060 rtype->set_length (rtype->length () + branch_type->length ());
8061 }
8062
8063 rtype->set_length (rtype->length ()
8064 - type->field (variant_field).type ()->length ());
8065
8066 return rtype;
8067 }
8068
8069 /* An ordinary record type (with fixed-length fields) that describes
8070 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8071 beginning of this section]. Any necessary discriminants' values
8072 should be in DVAL, a record value; it may be NULL if the object
8073 at ADDR itself contains any necessary discriminant values.
8074 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8075 values from the record are needed. Except in the case that DVAL,
8076 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8077 unchecked) is replaced by a particular branch of the variant.
8078
8079 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8080 is questionable and may be removed. It can arise during the
8081 processing of an unconstrained-array-of-record type where all the
8082 variant branches have exactly the same size. This is because in
8083 such cases, the compiler does not bother to use the XVS convention
8084 when encoding the record. I am currently dubious of this
8085 shortcut and suspect the compiler should be altered. FIXME. */
8086
8087 static struct type *
8088 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8089 CORE_ADDR address, struct value *dval)
8090 {
8091 struct type *templ_type;
8092
8093 if (type0->is_fixed_instance ())
8094 return type0;
8095
8096 templ_type = dynamic_template_type (type0);
8097
8098 if (templ_type != NULL)
8099 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8100 else if (variant_field_index (type0) >= 0)
8101 {
8102 if (dval == NULL && valaddr == NULL && address == 0)
8103 return type0;
8104 return to_record_with_fixed_variant_part (type0, valaddr, address,
8105 dval);
8106 }
8107 else
8108 {
8109 type0->set_is_fixed_instance (true);
8110 return type0;
8111 }
8112
8113 }
8114
8115 /* An ordinary record type (with fixed-length fields) that describes
8116 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8117 union type. Any necessary discriminants' values should be in DVAL,
8118 a record value. That is, this routine selects the appropriate
8119 branch of the union at ADDR according to the discriminant value
8120 indicated in the union's type name. Returns VAR_TYPE0 itself if
8121 it represents a variant subject to a pragma Unchecked_Union. */
8122
8123 static struct type *
8124 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8125 CORE_ADDR address, struct value *dval)
8126 {
8127 int which;
8128 struct type *templ_type;
8129 struct type *var_type;
8130
8131 if (var_type0->code () == TYPE_CODE_PTR)
8132 var_type = var_type0->target_type ();
8133 else
8134 var_type = var_type0;
8135
8136 templ_type = ada_find_parallel_type (var_type, "___XVU");
8137
8138 if (templ_type != NULL)
8139 var_type = templ_type;
8140
8141 if (is_unchecked_variant (var_type, dval->type ()))
8142 return var_type0;
8143 which = ada_which_variant_applies (var_type, dval);
8144
8145 if (which < 0)
8146 return empty_record (var_type);
8147 else if (is_dynamic_field (var_type, which))
8148 return to_fixed_record_type
8149 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8150 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8151 return
8152 to_fixed_record_type
8153 (var_type->field (which).type (), valaddr, address, dval);
8154 else
8155 return var_type->field (which).type ();
8156 }
8157
8158 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8159 ENCODING_TYPE, a type following the GNAT conventions for discrete
8160 type encodings, only carries redundant information. */
8161
8162 static int
8163 ada_is_redundant_range_encoding (struct type *range_type,
8164 struct type *encoding_type)
8165 {
8166 const char *bounds_str;
8167 int n;
8168 LONGEST lo, hi;
8169
8170 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8171
8172 if (get_base_type (range_type)->code ()
8173 != get_base_type (encoding_type)->code ())
8174 {
8175 /* The compiler probably used a simple base type to describe
8176 the range type instead of the range's actual base type,
8177 expecting us to get the real base type from the encoding
8178 anyway. In this situation, the encoding cannot be ignored
8179 as redundant. */
8180 return 0;
8181 }
8182
8183 if (is_dynamic_type (range_type))
8184 return 0;
8185
8186 if (encoding_type->name () == NULL)
8187 return 0;
8188
8189 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8190 if (bounds_str == NULL)
8191 return 0;
8192
8193 n = 8; /* Skip "___XDLU_". */
8194 if (!ada_scan_number (bounds_str, n, &lo, &n))
8195 return 0;
8196 if (range_type->bounds ()->low.const_val () != lo)
8197 return 0;
8198
8199 n += 2; /* Skip the "__" separator between the two bounds. */
8200 if (!ada_scan_number (bounds_str, n, &hi, &n))
8201 return 0;
8202 if (range_type->bounds ()->high.const_val () != hi)
8203 return 0;
8204
8205 return 1;
8206 }
8207
8208 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8209 a type following the GNAT encoding for describing array type
8210 indices, only carries redundant information. */
8211
8212 static int
8213 ada_is_redundant_index_type_desc (struct type *array_type,
8214 struct type *desc_type)
8215 {
8216 struct type *this_layer = check_typedef (array_type);
8217 int i;
8218
8219 for (i = 0; i < desc_type->num_fields (); i++)
8220 {
8221 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8222 desc_type->field (i).type ()))
8223 return 0;
8224 this_layer = check_typedef (this_layer->target_type ());
8225 }
8226
8227 return 1;
8228 }
8229
8230 /* Assuming that TYPE0 is an array type describing the type of a value
8231 at ADDR, and that DVAL describes a record containing any
8232 discriminants used in TYPE0, returns a type for the value that
8233 contains no dynamic components (that is, no components whose sizes
8234 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8235 true, gives an error message if the resulting type's size is over
8236 varsize_limit. */
8237
8238 static struct type *
8239 to_fixed_array_type (struct type *type0, struct value *dval,
8240 int ignore_too_big)
8241 {
8242 struct type *index_type_desc;
8243 struct type *result;
8244 int constrained_packed_array_p;
8245 static const char *xa_suffix = "___XA";
8246
8247 type0 = ada_check_typedef (type0);
8248 if (type0->is_fixed_instance ())
8249 return type0;
8250
8251 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8252 if (constrained_packed_array_p)
8253 {
8254 type0 = decode_constrained_packed_array_type (type0);
8255 if (type0 == nullptr)
8256 error (_("could not decode constrained packed array type"));
8257 }
8258
8259 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8260
8261 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8262 encoding suffixed with 'P' may still be generated. If so,
8263 it should be used to find the XA type. */
8264
8265 if (index_type_desc == NULL)
8266 {
8267 const char *type_name = ada_type_name (type0);
8268
8269 if (type_name != NULL)
8270 {
8271 const int len = strlen (type_name);
8272 char *name = (char *) alloca (len + strlen (xa_suffix));
8273
8274 if (type_name[len - 1] == 'P')
8275 {
8276 strcpy (name, type_name);
8277 strcpy (name + len - 1, xa_suffix);
8278 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8279 }
8280 }
8281 }
8282
8283 ada_fixup_array_indexes_type (index_type_desc);
8284 if (index_type_desc != NULL
8285 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8286 {
8287 /* Ignore this ___XA parallel type, as it does not bring any
8288 useful information. This allows us to avoid creating fixed
8289 versions of the array's index types, which would be identical
8290 to the original ones. This, in turn, can also help avoid
8291 the creation of fixed versions of the array itself. */
8292 index_type_desc = NULL;
8293 }
8294
8295 if (index_type_desc == NULL)
8296 {
8297 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8298
8299 /* NOTE: elt_type---the fixed version of elt_type0---should never
8300 depend on the contents of the array in properly constructed
8301 debugging data. */
8302 /* Create a fixed version of the array element type.
8303 We're not providing the address of an element here,
8304 and thus the actual object value cannot be inspected to do
8305 the conversion. This should not be a problem, since arrays of
8306 unconstrained objects are not allowed. In particular, all
8307 the elements of an array of a tagged type should all be of
8308 the same type specified in the debugging info. No need to
8309 consult the object tag. */
8310 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8311
8312 /* Make sure we always create a new array type when dealing with
8313 packed array types, since we're going to fix-up the array
8314 type length and element bitsize a little further down. */
8315 if (elt_type0 == elt_type && !constrained_packed_array_p)
8316 result = type0;
8317 else
8318 {
8319 type_allocator alloc (type0);
8320 result = create_array_type (alloc, elt_type, type0->index_type ());
8321 }
8322 }
8323 else
8324 {
8325 int i;
8326 struct type *elt_type0;
8327
8328 elt_type0 = type0;
8329 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8330 elt_type0 = elt_type0->target_type ();
8331
8332 /* NOTE: result---the fixed version of elt_type0---should never
8333 depend on the contents of the array in properly constructed
8334 debugging data. */
8335 /* Create a fixed version of the array element type.
8336 We're not providing the address of an element here,
8337 and thus the actual object value cannot be inspected to do
8338 the conversion. This should not be a problem, since arrays of
8339 unconstrained objects are not allowed. In particular, all
8340 the elements of an array of a tagged type should all be of
8341 the same type specified in the debugging info. No need to
8342 consult the object tag. */
8343 result =
8344 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8345
8346 elt_type0 = type0;
8347 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8348 {
8349 struct type *range_type =
8350 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8351
8352 type_allocator alloc (elt_type0);
8353 result = create_array_type (alloc, result, range_type);
8354 elt_type0 = elt_type0->target_type ();
8355 }
8356 }
8357
8358 /* We want to preserve the type name. This can be useful when
8359 trying to get the type name of a value that has already been
8360 printed (for instance, if the user did "print VAR; whatis $". */
8361 result->set_name (type0->name ());
8362
8363 if (constrained_packed_array_p)
8364 {
8365 /* So far, the resulting type has been created as if the original
8366 type was a regular (non-packed) array type. As a result, the
8367 bitsize of the array elements needs to be set again, and the array
8368 length needs to be recomputed based on that bitsize. */
8369 int len = result->length () / result->target_type ()->length ();
8370 int elt_bitsize = type0->field (0).bitsize ();
8371
8372 result->field (0).set_bitsize (elt_bitsize);
8373 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8374 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8375 result->set_length (result->length () + 1);
8376 }
8377
8378 result->set_is_fixed_instance (true);
8379 return result;
8380 }
8381
8382
8383 /* A standard type (containing no dynamically sized components)
8384 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8385 DVAL describes a record containing any discriminants used in TYPE0,
8386 and may be NULL if there are none, or if the object of type TYPE at
8387 ADDRESS or in VALADDR contains these discriminants.
8388
8389 If CHECK_TAG is not null, in the case of tagged types, this function
8390 attempts to locate the object's tag and use it to compute the actual
8391 type. However, when ADDRESS is null, we cannot use it to determine the
8392 location of the tag, and therefore compute the tagged type's actual type.
8393 So we return the tagged type without consulting the tag. */
8394
8395 static struct type *
8396 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8397 CORE_ADDR address, struct value *dval, int check_tag)
8398 {
8399 type = ada_check_typedef (type);
8400
8401 /* Only un-fixed types need to be handled here. */
8402 if (!HAVE_GNAT_AUX_INFO (type))
8403 return type;
8404
8405 switch (type->code ())
8406 {
8407 default:
8408 return type;
8409 case TYPE_CODE_STRUCT:
8410 {
8411 struct type *static_type = to_static_fixed_type (type);
8412 struct type *fixed_record_type =
8413 to_fixed_record_type (type, valaddr, address, NULL);
8414
8415 /* If STATIC_TYPE is a tagged type and we know the object's address,
8416 then we can determine its tag, and compute the object's actual
8417 type from there. Note that we have to use the fixed record
8418 type (the parent part of the record may have dynamic fields
8419 and the way the location of _tag is expressed may depend on
8420 them). */
8421
8422 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8423 {
8424 struct value *tag =
8425 value_tag_from_contents_and_address
8426 (fixed_record_type,
8427 valaddr,
8428 address);
8429 struct type *real_type = type_from_tag (tag);
8430 struct value *obj =
8431 value_from_contents_and_address (fixed_record_type,
8432 valaddr,
8433 address);
8434 fixed_record_type = obj->type ();
8435 if (real_type != NULL)
8436 return to_fixed_record_type
8437 (real_type, NULL,
8438 ada_tag_value_at_base_address (obj)->address (), NULL);
8439 }
8440
8441 /* Check to see if there is a parallel ___XVZ variable.
8442 If there is, then it provides the actual size of our type. */
8443 else if (ada_type_name (fixed_record_type) != NULL)
8444 {
8445 const char *name = ada_type_name (fixed_record_type);
8446 char *xvz_name
8447 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8448 bool xvz_found = false;
8449 LONGEST size;
8450
8451 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8452 try
8453 {
8454 xvz_found = get_int_var_value (xvz_name, size);
8455 }
8456 catch (const gdb_exception_error &except)
8457 {
8458 /* We found the variable, but somehow failed to read
8459 its value. Rethrow the same error, but with a little
8460 bit more information, to help the user understand
8461 what went wrong (Eg: the variable might have been
8462 optimized out). */
8463 throw_error (except.error,
8464 _("unable to read value of %s (%s)"),
8465 xvz_name, except.what ());
8466 }
8467
8468 if (xvz_found && fixed_record_type->length () != size)
8469 {
8470 fixed_record_type = copy_type (fixed_record_type);
8471 fixed_record_type->set_length (size);
8472
8473 /* The FIXED_RECORD_TYPE may have be a stub. We have
8474 observed this when the debugging info is STABS, and
8475 apparently it is something that is hard to fix.
8476
8477 In practice, we don't need the actual type definition
8478 at all, because the presence of the XVZ variable allows us
8479 to assume that there must be a XVS type as well, which we
8480 should be able to use later, when we need the actual type
8481 definition.
8482
8483 In the meantime, pretend that the "fixed" type we are
8484 returning is NOT a stub, because this can cause trouble
8485 when using this type to create new types targeting it.
8486 Indeed, the associated creation routines often check
8487 whether the target type is a stub and will try to replace
8488 it, thus using a type with the wrong size. This, in turn,
8489 might cause the new type to have the wrong size too.
8490 Consider the case of an array, for instance, where the size
8491 of the array is computed from the number of elements in
8492 our array multiplied by the size of its element. */
8493 fixed_record_type->set_is_stub (false);
8494 }
8495 }
8496 return fixed_record_type;
8497 }
8498 case TYPE_CODE_ARRAY:
8499 return to_fixed_array_type (type, dval, 1);
8500 case TYPE_CODE_UNION:
8501 if (dval == NULL)
8502 return type;
8503 else
8504 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8505 }
8506 }
8507
8508 /* The same as ada_to_fixed_type_1, except that it preserves the type
8509 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8510
8511 The typedef layer needs be preserved in order to differentiate between
8512 arrays and array pointers when both types are implemented using the same
8513 fat pointer. In the array pointer case, the pointer is encoded as
8514 a typedef of the pointer type. For instance, considering:
8515
8516 type String_Access is access String;
8517 S1 : String_Access := null;
8518
8519 To the debugger, S1 is defined as a typedef of type String. But
8520 to the user, it is a pointer. So if the user tries to print S1,
8521 we should not dereference the array, but print the array address
8522 instead.
8523
8524 If we didn't preserve the typedef layer, we would lose the fact that
8525 the type is to be presented as a pointer (needs de-reference before
8526 being printed). And we would also use the source-level type name. */
8527
8528 struct type *
8529 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8530 CORE_ADDR address, struct value *dval, int check_tag)
8531
8532 {
8533 struct type *fixed_type =
8534 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8535
8536 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8537 then preserve the typedef layer.
8538
8539 Implementation note: We can only check the main-type portion of
8540 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8541 from TYPE now returns a type that has the same instance flags
8542 as TYPE. For instance, if TYPE is a "typedef const", and its
8543 target type is a "struct", then the typedef elimination will return
8544 a "const" version of the target type. See check_typedef for more
8545 details about how the typedef layer elimination is done.
8546
8547 brobecker/2010-11-19: It seems to me that the only case where it is
8548 useful to preserve the typedef layer is when dealing with fat pointers.
8549 Perhaps, we could add a check for that and preserve the typedef layer
8550 only in that situation. But this seems unnecessary so far, probably
8551 because we call check_typedef/ada_check_typedef pretty much everywhere.
8552 */
8553 if (type->code () == TYPE_CODE_TYPEDEF
8554 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8555 == TYPE_MAIN_TYPE (fixed_type)))
8556 return type;
8557
8558 return fixed_type;
8559 }
8560
8561 /* A standard (static-sized) type corresponding as well as possible to
8562 TYPE0, but based on no runtime data. */
8563
8564 static struct type *
8565 to_static_fixed_type (struct type *type0)
8566 {
8567 struct type *type;
8568
8569 if (type0 == NULL)
8570 return NULL;
8571
8572 if (type0->is_fixed_instance ())
8573 return type0;
8574
8575 type0 = ada_check_typedef (type0);
8576
8577 switch (type0->code ())
8578 {
8579 default:
8580 return type0;
8581 case TYPE_CODE_STRUCT:
8582 type = dynamic_template_type (type0);
8583 if (type != NULL)
8584 return template_to_static_fixed_type (type);
8585 else
8586 return template_to_static_fixed_type (type0);
8587 case TYPE_CODE_UNION:
8588 type = ada_find_parallel_type (type0, "___XVU");
8589 if (type != NULL)
8590 return template_to_static_fixed_type (type);
8591 else
8592 return template_to_static_fixed_type (type0);
8593 }
8594 }
8595
8596 /* A static approximation of TYPE with all type wrappers removed. */
8597
8598 static struct type *
8599 static_unwrap_type (struct type *type)
8600 {
8601 if (ada_is_aligner_type (type))
8602 {
8603 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8604 if (ada_type_name (type1) == NULL)
8605 type1->set_name (ada_type_name (type));
8606
8607 return static_unwrap_type (type1);
8608 }
8609 else
8610 {
8611 struct type *raw_real_type = ada_get_base_type (type);
8612
8613 if (raw_real_type == type)
8614 return type;
8615 else
8616 return to_static_fixed_type (raw_real_type);
8617 }
8618 }
8619
8620 /* In some cases, incomplete and private types require
8621 cross-references that are not resolved as records (for example,
8622 type Foo;
8623 type FooP is access Foo;
8624 V: FooP;
8625 type Foo is array ...;
8626 ). In these cases, since there is no mechanism for producing
8627 cross-references to such types, we instead substitute for FooP a
8628 stub enumeration type that is nowhere resolved, and whose tag is
8629 the name of the actual type. Call these types "non-record stubs". */
8630
8631 /* A type equivalent to TYPE that is not a non-record stub, if one
8632 exists, otherwise TYPE. */
8633
8634 struct type *
8635 ada_check_typedef (struct type *type)
8636 {
8637 if (type == NULL)
8638 return NULL;
8639
8640 /* If our type is an access to an unconstrained array, which is encoded
8641 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8642 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8643 what allows us to distinguish between fat pointers that represent
8644 array types, and fat pointers that represent array access types
8645 (in both cases, the compiler implements them as fat pointers). */
8646 if (ada_is_access_to_unconstrained_array (type))
8647 return type;
8648
8649 type = check_typedef (type);
8650 if (type == NULL || type->code () != TYPE_CODE_ENUM
8651 || !type->is_stub ()
8652 || type->name () == NULL)
8653 return type;
8654 else
8655 {
8656 const char *name = type->name ();
8657 struct type *type1 = ada_find_any_type (name);
8658
8659 if (type1 == NULL)
8660 return type;
8661
8662 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8663 stubs pointing to arrays, as we don't create symbols for array
8664 types, only for the typedef-to-array types). If that's the case,
8665 strip the typedef layer. */
8666 if (type1->code () == TYPE_CODE_TYPEDEF)
8667 type1 = ada_check_typedef (type1);
8668
8669 return type1;
8670 }
8671 }
8672
8673 /* A value representing the data at VALADDR/ADDRESS as described by
8674 type TYPE0, but with a standard (static-sized) type that correctly
8675 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8676 type, then return VAL0 [this feature is simply to avoid redundant
8677 creation of struct values]. */
8678
8679 static struct value *
8680 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8681 struct value *val0)
8682 {
8683 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8684
8685 if (type == type0 && val0 != NULL)
8686 return val0;
8687
8688 if (val0->lval () != lval_memory)
8689 {
8690 /* Our value does not live in memory; it could be a convenience
8691 variable, for instance. Create a not_lval value using val0's
8692 contents. */
8693 return value_from_contents (type, val0->contents ().data ());
8694 }
8695
8696 return value_from_contents_and_address (type, 0, address);
8697 }
8698
8699 /* A value representing VAL, but with a standard (static-sized) type
8700 that correctly describes it. Does not necessarily create a new
8701 value. */
8702
8703 struct value *
8704 ada_to_fixed_value (struct value *val)
8705 {
8706 val = unwrap_value (val);
8707 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8708 return val;
8709 }
8710 \f
8711
8712 /* Attributes */
8713
8714 /* Evaluate the 'POS attribute applied to ARG. */
8715
8716 static LONGEST
8717 pos_atr (struct value *arg)
8718 {
8719 struct value *val = coerce_ref (arg);
8720 struct type *type = val->type ();
8721
8722 if (!discrete_type_p (type))
8723 error (_("'POS only defined on discrete types"));
8724
8725 std::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8726 if (!result.has_value ())
8727 error (_("enumeration value is invalid: can't find 'POS"));
8728
8729 return *result;
8730 }
8731
8732 struct value *
8733 ada_pos_atr (struct type *expect_type,
8734 struct expression *exp,
8735 enum noside noside, enum exp_opcode op,
8736 struct value *arg)
8737 {
8738 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8739 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8740 return value::zero (type, not_lval);
8741 return value_from_longest (type, pos_atr (arg));
8742 }
8743
8744 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8745
8746 static struct value *
8747 val_atr (struct type *type, LONGEST val)
8748 {
8749 gdb_assert (discrete_type_p (type));
8750 if (type->code () == TYPE_CODE_RANGE)
8751 type = type->target_type ();
8752 if (type->code () == TYPE_CODE_ENUM)
8753 {
8754 if (val < 0 || val >= type->num_fields ())
8755 error (_("argument to 'VAL out of range"));
8756 val = type->field (val).loc_enumval ();
8757 }
8758 return value_from_longest (type, val);
8759 }
8760
8761 struct value *
8762 ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8763 struct value *arg)
8764 {
8765 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8766 return value::zero (type, not_lval);
8767
8768 if (!discrete_type_p (type))
8769 error (_("'VAL only defined on discrete types"));
8770 if (!integer_type_p (arg->type ()))
8771 error (_("'VAL requires integral argument"));
8772
8773 return val_atr (type, value_as_long (arg));
8774 }
8775
8776 /* Implementation of the enum_rep attribute. */
8777 struct value *
8778 ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8779 struct value *arg)
8780 {
8781 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8782 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8783 return value::zero (inttype, not_lval);
8784
8785 if (type->code () == TYPE_CODE_RANGE)
8786 type = type->target_type ();
8787 if (type->code () != TYPE_CODE_ENUM)
8788 error (_("'Enum_Rep only defined on enum types"));
8789 if (!types_equal (type, arg->type ()))
8790 error (_("'Enum_Rep requires argument to have same type as enum"));
8791
8792 return value_cast (inttype, arg);
8793 }
8794
8795 /* Implementation of the enum_val attribute. */
8796 struct value *
8797 ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8798 struct value *arg)
8799 {
8800 struct type *original_type = type;
8801 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8802 return value::zero (original_type, not_lval);
8803
8804 if (type->code () == TYPE_CODE_RANGE)
8805 type = type->target_type ();
8806 if (type->code () != TYPE_CODE_ENUM)
8807 error (_("'Enum_Val only defined on enum types"));
8808 if (!integer_type_p (arg->type ()))
8809 error (_("'Enum_Val requires integral argument"));
8810
8811 LONGEST value = value_as_long (arg);
8812 for (int i = 0; i < type->num_fields (); ++i)
8813 {
8814 if (type->field (i).loc_enumval () == value)
8815 return value_from_longest (original_type, value);
8816 }
8817
8818 error (_("value %s not found in enum"), plongest (value));
8819 }
8820
8821 \f
8822
8823 /* Evaluation */
8824
8825 /* True if TYPE appears to be an Ada character type.
8826 [At the moment, this is true only for Character and Wide_Character;
8827 It is a heuristic test that could stand improvement]. */
8828
8829 bool
8830 ada_is_character_type (struct type *type)
8831 {
8832 const char *name;
8833
8834 /* If the type code says it's a character, then assume it really is,
8835 and don't check any further. */
8836 if (type->code () == TYPE_CODE_CHAR)
8837 return true;
8838
8839 /* Otherwise, assume it's a character type iff it is a discrete type
8840 with a known character type name. */
8841 name = ada_type_name (type);
8842 return (name != NULL
8843 && (type->code () == TYPE_CODE_INT
8844 || type->code () == TYPE_CODE_RANGE)
8845 && (strcmp (name, "character") == 0
8846 || strcmp (name, "wide_character") == 0
8847 || strcmp (name, "wide_wide_character") == 0
8848 || strcmp (name, "unsigned char") == 0));
8849 }
8850
8851 /* True if TYPE appears to be an Ada string type. */
8852
8853 bool
8854 ada_is_string_type (struct type *type)
8855 {
8856 type = ada_check_typedef (type);
8857 if (type != NULL
8858 && type->code () != TYPE_CODE_PTR
8859 && (ada_is_simple_array_type (type)
8860 || ada_is_array_descriptor_type (type))
8861 && ada_array_arity (type) == 1)
8862 {
8863 struct type *elttype = ada_array_element_type (type, 1);
8864
8865 return ada_is_character_type (elttype);
8866 }
8867 else
8868 return false;
8869 }
8870
8871 /* The compiler sometimes provides a parallel XVS type for a given
8872 PAD type. Normally, it is safe to follow the PAD type directly,
8873 but older versions of the compiler have a bug that causes the offset
8874 of its "F" field to be wrong. Following that field in that case
8875 would lead to incorrect results, but this can be worked around
8876 by ignoring the PAD type and using the associated XVS type instead.
8877
8878 Set to True if the debugger should trust the contents of PAD types.
8879 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8880 static bool trust_pad_over_xvs = true;
8881
8882 /* True if TYPE is a struct type introduced by the compiler to force the
8883 alignment of a value. Such types have a single field with a
8884 distinctive name. */
8885
8886 int
8887 ada_is_aligner_type (struct type *type)
8888 {
8889 type = ada_check_typedef (type);
8890
8891 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8892 return 0;
8893
8894 return (type->code () == TYPE_CODE_STRUCT
8895 && type->num_fields () == 1
8896 && strcmp (type->field (0).name (), "F") == 0);
8897 }
8898
8899 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8900 the parallel type. */
8901
8902 struct type *
8903 ada_get_base_type (struct type *raw_type)
8904 {
8905 struct type *real_type_namer;
8906 struct type *raw_real_type;
8907
8908 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8909 return raw_type;
8910
8911 if (ada_is_aligner_type (raw_type))
8912 /* The encoding specifies that we should always use the aligner type.
8913 So, even if this aligner type has an associated XVS type, we should
8914 simply ignore it.
8915
8916 According to the compiler gurus, an XVS type parallel to an aligner
8917 type may exist because of a stabs limitation. In stabs, aligner
8918 types are empty because the field has a variable-sized type, and
8919 thus cannot actually be used as an aligner type. As a result,
8920 we need the associated parallel XVS type to decode the type.
8921 Since the policy in the compiler is to not change the internal
8922 representation based on the debugging info format, we sometimes
8923 end up having a redundant XVS type parallel to the aligner type. */
8924 return raw_type;
8925
8926 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8927 if (real_type_namer == NULL
8928 || real_type_namer->code () != TYPE_CODE_STRUCT
8929 || real_type_namer->num_fields () != 1)
8930 return raw_type;
8931
8932 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8933 {
8934 /* This is an older encoding form where the base type needs to be
8935 looked up by name. We prefer the newer encoding because it is
8936 more efficient. */
8937 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
8938 if (raw_real_type == NULL)
8939 return raw_type;
8940 else
8941 return raw_real_type;
8942 }
8943
8944 /* The field in our XVS type is a reference to the base type. */
8945 return real_type_namer->field (0).type ()->target_type ();
8946 }
8947
8948 /* The type of value designated by TYPE, with all aligners removed. */
8949
8950 struct type *
8951 ada_aligned_type (struct type *type)
8952 {
8953 if (ada_is_aligner_type (type))
8954 return ada_aligned_type (type->field (0).type ());
8955 else
8956 return ada_get_base_type (type);
8957 }
8958
8959
8960 /* The address of the aligned value in an object at address VALADDR
8961 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
8962
8963 const gdb_byte *
8964 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8965 {
8966 if (ada_is_aligner_type (type))
8967 return ada_aligned_value_addr
8968 (type->field (0).type (),
8969 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
8970 else
8971 return valaddr;
8972 }
8973
8974
8975
8976 /* The printed representation of an enumeration literal with encoded
8977 name NAME. The value is good to the next call of ada_enum_name. */
8978 const char *
8979 ada_enum_name (const char *name)
8980 {
8981 static std::string storage;
8982 const char *tmp;
8983
8984 /* First, unqualify the enumeration name:
8985 1. Search for the last '.' character. If we find one, then skip
8986 all the preceding characters, the unqualified name starts
8987 right after that dot.
8988 2. Otherwise, we may be debugging on a target where the compiler
8989 translates dots into "__". Search forward for double underscores,
8990 but stop searching when we hit an overloading suffix, which is
8991 of the form "__" followed by digits. */
8992
8993 tmp = strrchr (name, '.');
8994 if (tmp != NULL)
8995 name = tmp + 1;
8996 else
8997 {
8998 while ((tmp = strstr (name, "__")) != NULL)
8999 {
9000 if (isdigit (tmp[2]))
9001 break;
9002 else
9003 name = tmp + 2;
9004 }
9005 }
9006
9007 if (name[0] == 'Q')
9008 {
9009 int v;
9010
9011 if (name[1] == 'U' || name[1] == 'W')
9012 {
9013 int offset = 2;
9014 if (name[1] == 'W' && name[2] == 'W')
9015 {
9016 /* Also handle the QWW case. */
9017 ++offset;
9018 }
9019 if (sscanf (name + offset, "%x", &v) != 1)
9020 return name;
9021 }
9022 else if (((name[1] >= '0' && name[1] <= '9')
9023 || (name[1] >= 'a' && name[1] <= 'z'))
9024 && name[2] == '\0')
9025 {
9026 storage = string_printf ("'%c'", name[1]);
9027 return storage.c_str ();
9028 }
9029 else
9030 return name;
9031
9032 if (isascii (v) && isprint (v))
9033 storage = string_printf ("'%c'", v);
9034 else if (name[1] == 'U')
9035 storage = string_printf ("'[\"%02x\"]'", v);
9036 else if (name[2] != 'W')
9037 storage = string_printf ("'[\"%04x\"]'", v);
9038 else
9039 storage = string_printf ("'[\"%06x\"]'", v);
9040
9041 return storage.c_str ();
9042 }
9043 else
9044 {
9045 tmp = strstr (name, "__");
9046 if (tmp == NULL)
9047 tmp = strstr (name, "$");
9048 if (tmp != NULL)
9049 {
9050 storage = std::string (name, tmp - name);
9051 return storage.c_str ();
9052 }
9053
9054 return name;
9055 }
9056 }
9057
9058 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9059 there is no parallel type, return nullptr. */
9060
9061 static struct type *
9062 find_base_type (struct type *type)
9063 {
9064 struct type *raw_real_type
9065 = ada_check_typedef (ada_get_base_type (type));
9066
9067 /* No parallel XVS or XVE type. */
9068 if (type == raw_real_type
9069 && ada_find_parallel_type (type, "___XVE") == nullptr)
9070 return nullptr;
9071
9072 return raw_real_type;
9073 }
9074
9075 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9076 value it wraps. */
9077
9078 static struct value *
9079 unwrap_value (struct value *val)
9080 {
9081 struct type *type = ada_check_typedef (val->type ());
9082
9083 if (ada_is_aligner_type (type))
9084 {
9085 struct value *v = ada_value_struct_elt (val, "F", 0);
9086 struct type *val_type = ada_check_typedef (v->type ());
9087
9088 if (ada_type_name (val_type) == NULL)
9089 val_type->set_name (ada_type_name (type));
9090
9091 return unwrap_value (v);
9092 }
9093 else
9094 {
9095 struct type *raw_real_type = find_base_type (type);
9096 if (raw_real_type == nullptr)
9097 return val;
9098
9099 return
9100 coerce_unspec_val_to_type
9101 (val, ada_to_fixed_type (raw_real_type, 0,
9102 val->address (),
9103 NULL, 1));
9104 }
9105 }
9106
9107 /* Given two array types T1 and T2, return nonzero iff both arrays
9108 contain the same number of elements. */
9109
9110 static int
9111 ada_same_array_size_p (struct type *t1, struct type *t2)
9112 {
9113 LONGEST lo1, hi1, lo2, hi2;
9114
9115 /* Get the array bounds in order to verify that the size of
9116 the two arrays match. */
9117 if (!get_array_bounds (t1, &lo1, &hi1)
9118 || !get_array_bounds (t2, &lo2, &hi2))
9119 error (_("unable to determine array bounds"));
9120
9121 /* To make things easier for size comparison, normalize a bit
9122 the case of empty arrays by making sure that the difference
9123 between upper bound and lower bound is always -1. */
9124 if (lo1 > hi1)
9125 hi1 = lo1 - 1;
9126 if (lo2 > hi2)
9127 hi2 = lo2 - 1;
9128
9129 return (hi1 - lo1 == hi2 - lo2);
9130 }
9131
9132 /* Assuming that VAL is an array of integrals, and TYPE represents
9133 an array with the same number of elements, but with wider integral
9134 elements, return an array "casted" to TYPE. In practice, this
9135 means that the returned array is built by casting each element
9136 of the original array into TYPE's (wider) element type. */
9137
9138 static struct value *
9139 ada_promote_array_of_integrals (struct type *type, struct value *val)
9140 {
9141 struct type *elt_type = type->target_type ();
9142 LONGEST lo, hi;
9143 LONGEST i;
9144
9145 /* Verify that both val and type are arrays of scalars, and
9146 that the size of val's elements is smaller than the size
9147 of type's element. */
9148 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9149 gdb_assert (is_integral_type (type->target_type ()));
9150 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9151 gdb_assert (is_integral_type (val->type ()->target_type ()));
9152 gdb_assert (type->target_type ()->length ()
9153 > val->type ()->target_type ()->length ());
9154
9155 if (!get_array_bounds (type, &lo, &hi))
9156 error (_("unable to determine array bounds"));
9157
9158 value *res = value::allocate (type);
9159 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9160
9161 /* Promote each array element. */
9162 for (i = 0; i < hi - lo + 1; i++)
9163 {
9164 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9165 int elt_len = elt_type->length ();
9166
9167 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9168 }
9169
9170 return res;
9171 }
9172
9173 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9174 return the converted value. */
9175
9176 static struct value *
9177 coerce_for_assign (struct type *type, struct value *val)
9178 {
9179 struct type *type2 = val->type ();
9180
9181 if (type == type2)
9182 return val;
9183
9184 type2 = ada_check_typedef (type2);
9185 type = ada_check_typedef (type);
9186
9187 if (type2->code () == TYPE_CODE_PTR
9188 && type->code () == TYPE_CODE_ARRAY)
9189 {
9190 val = ada_value_ind (val);
9191 type2 = val->type ();
9192 }
9193
9194 if (type2->code () == TYPE_CODE_ARRAY
9195 && type->code () == TYPE_CODE_ARRAY)
9196 {
9197 if (!ada_same_array_size_p (type, type2))
9198 error (_("cannot assign arrays of different length"));
9199
9200 if (is_integral_type (type->target_type ())
9201 && is_integral_type (type2->target_type ())
9202 && type2->target_type ()->length () < type->target_type ()->length ())
9203 {
9204 /* Allow implicit promotion of the array elements to
9205 a wider type. */
9206 return ada_promote_array_of_integrals (type, val);
9207 }
9208
9209 if (type2->target_type ()->length () != type->target_type ()->length ())
9210 error (_("Incompatible types in assignment"));
9211 val->deprecated_set_type (type);
9212 }
9213 return val;
9214 }
9215
9216 static struct value *
9217 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9218 {
9219 struct type *type1, *type2;
9220
9221 arg1 = coerce_ref (arg1);
9222 arg2 = coerce_ref (arg2);
9223 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9224 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9225
9226 if (type1->code () != TYPE_CODE_INT
9227 || type2->code () != TYPE_CODE_INT)
9228 return value_binop (arg1, arg2, op);
9229
9230 switch (op)
9231 {
9232 case BINOP_MOD:
9233 case BINOP_DIV:
9234 case BINOP_REM:
9235 break;
9236 default:
9237 return value_binop (arg1, arg2, op);
9238 }
9239
9240 gdb_mpz v2 = value_as_mpz (arg2);
9241 if (v2.sgn () == 0)
9242 {
9243 const char *name;
9244 if (op == BINOP_MOD)
9245 name = "mod";
9246 else if (op == BINOP_DIV)
9247 name = "/";
9248 else
9249 {
9250 gdb_assert (op == BINOP_REM);
9251 name = "rem";
9252 }
9253
9254 error (_("second operand of %s must not be zero."), name);
9255 }
9256
9257 if (type1->is_unsigned () || op == BINOP_MOD)
9258 return value_binop (arg1, arg2, op);
9259
9260 gdb_mpz v1 = value_as_mpz (arg1);
9261 gdb_mpz v;
9262 switch (op)
9263 {
9264 case BINOP_DIV:
9265 v = v1 / v2;
9266 break;
9267 case BINOP_REM:
9268 v = v1 % v2;
9269 if (v * v1 < 0)
9270 v -= v2;
9271 break;
9272 default:
9273 /* Should not reach this point. */
9274 gdb_assert_not_reached ("invalid operator");
9275 }
9276
9277 return value_from_mpz (type1, v);
9278 }
9279
9280 static int
9281 ada_value_equal (struct value *arg1, struct value *arg2)
9282 {
9283 if (ada_is_direct_array_type (arg1->type ())
9284 || ada_is_direct_array_type (arg2->type ()))
9285 {
9286 struct type *arg1_type, *arg2_type;
9287
9288 /* Automatically dereference any array reference before
9289 we attempt to perform the comparison. */
9290 arg1 = ada_coerce_ref (arg1);
9291 arg2 = ada_coerce_ref (arg2);
9292
9293 arg1 = ada_coerce_to_simple_array (arg1);
9294 arg2 = ada_coerce_to_simple_array (arg2);
9295
9296 arg1_type = ada_check_typedef (arg1->type ());
9297 arg2_type = ada_check_typedef (arg2->type ());
9298
9299 if (arg1_type->code () != TYPE_CODE_ARRAY
9300 || arg2_type->code () != TYPE_CODE_ARRAY)
9301 error (_("Attempt to compare array with non-array"));
9302 /* FIXME: The following works only for types whose
9303 representations use all bits (no padding or undefined bits)
9304 and do not have user-defined equality. */
9305 return (arg1_type->length () == arg2_type->length ()
9306 && memcmp (arg1->contents ().data (),
9307 arg2->contents ().data (),
9308 arg1_type->length ()) == 0);
9309 }
9310 return value_equal (arg1, arg2);
9311 }
9312
9313 namespace expr
9314 {
9315
9316 bool
9317 check_objfile (const std::unique_ptr<ada_component> &comp,
9318 struct objfile *objfile)
9319 {
9320 return comp->uses_objfile (objfile);
9321 }
9322
9323 /* See ada-exp.h. */
9324
9325 void
9326 aggregate_assigner::assign (LONGEST index, operation_up &arg)
9327 {
9328 scoped_value_mark mark;
9329
9330 struct value *elt;
9331 struct type *lhs_type = check_typedef (lhs->type ());
9332
9333 if (lhs_type->code () == TYPE_CODE_ARRAY)
9334 {
9335 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9336 struct value *index_val = value_from_longest (index_type, index);
9337
9338 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9339 }
9340 else
9341 {
9342 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9343 elt = ada_to_fixed_value (elt);
9344 }
9345
9346 scoped_restore save_index = make_scoped_restore (&m_current_index, index);
9347
9348 ada_aggregate_operation *ag_op
9349 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9350 if (ag_op != nullptr)
9351 ag_op->assign_aggregate (container, elt, exp);
9352 else
9353 value_assign_to_component (container, elt,
9354 arg->evaluate (nullptr, exp,
9355 EVAL_NORMAL));
9356 }
9357
9358 /* See ada-exp.h. */
9359
9360 value *
9361 aggregate_assigner::current_value () const
9362 {
9363 /* Note that using an integer type here is incorrect -- the type
9364 should be the array's index type. Unfortunately, though, this
9365 isn't currently available during parsing and type resolution. */
9366 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9367 return value_from_longest (index_type, m_current_index);
9368 }
9369
9370 bool
9371 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9372 {
9373 if (m_base != nullptr && m_base->uses_objfile (objfile))
9374 return true;
9375 for (const auto &item : m_components)
9376 if (item->uses_objfile (objfile))
9377 return true;
9378 return false;
9379 }
9380
9381 void
9382 ada_aggregate_component::dump (ui_file *stream, int depth)
9383 {
9384 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9385 if (m_base != nullptr)
9386 {
9387 gdb_printf (stream, _("%*swith delta\n"), depth + 1, "");
9388 m_base->dump (stream, depth + 2);
9389 }
9390 for (const auto &item : m_components)
9391 item->dump (stream, depth + 1);
9392 }
9393
9394 void
9395 ada_aggregate_component::assign (aggregate_assigner &assigner)
9396 {
9397 if (m_base != nullptr)
9398 {
9399 value *base = m_base->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9400 if (ada_is_direct_array_type (base->type ()))
9401 base = ada_coerce_to_simple_array (base);
9402 if (!types_deeply_equal (assigner.container->type (), base->type ()))
9403 error (_("Type mismatch in delta aggregate"));
9404 value_assign_to_component (assigner.container, assigner.container,
9405 base);
9406 }
9407
9408 for (auto &item : m_components)
9409 item->assign (assigner);
9410 }
9411
9412 /* See ada-exp.h. */
9413
9414 ada_aggregate_component::ada_aggregate_component
9415 (operation_up &&base, std::vector<ada_component_up> &&components)
9416 : m_base (std::move (base)),
9417 m_components (std::move (components))
9418 {
9419 for (const auto &component : m_components)
9420 if (dynamic_cast<const ada_others_component *> (component.get ())
9421 != nullptr)
9422 {
9423 /* It's invalid and nonsensical to have 'others => ...' with a
9424 delta aggregate. It was simpler to enforce this
9425 restriction here as opposed to in the parser. */
9426 error (_("'others' invalid in delta aggregate"));
9427 }
9428 }
9429
9430 /* See ada-exp.h. */
9431
9432 value *
9433 ada_aggregate_operation::assign_aggregate (struct value *container,
9434 struct value *lhs,
9435 struct expression *exp)
9436 {
9437 struct type *lhs_type;
9438 aggregate_assigner assigner;
9439
9440 container = ada_coerce_ref (container);
9441 if (ada_is_direct_array_type (container->type ()))
9442 container = ada_coerce_to_simple_array (container);
9443 lhs = ada_coerce_ref (lhs);
9444 if (!lhs->deprecated_modifiable ())
9445 error (_("Left operand of assignment is not a modifiable lvalue."));
9446
9447 lhs_type = check_typedef (lhs->type ());
9448 if (ada_is_direct_array_type (lhs_type))
9449 {
9450 lhs = ada_coerce_to_simple_array (lhs);
9451 lhs_type = check_typedef (lhs->type ());
9452 assigner.low = lhs_type->bounds ()->low.const_val ();
9453 assigner.high = lhs_type->bounds ()->high.const_val ();
9454 }
9455 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9456 {
9457 assigner.low = 0;
9458 assigner.high = num_visible_fields (lhs_type) - 1;
9459 }
9460 else
9461 error (_("Left-hand side must be array or record."));
9462
9463 assigner.indices.push_back (assigner.low - 1);
9464 assigner.indices.push_back (assigner.low - 1);
9465 assigner.indices.push_back (assigner.high + 1);
9466 assigner.indices.push_back (assigner.high + 1);
9467
9468 assigner.container = container;
9469 assigner.lhs = lhs;
9470 assigner.exp = exp;
9471
9472 std::get<0> (m_storage)->assign (assigner);
9473
9474 return container;
9475 }
9476
9477 bool
9478 ada_positional_component::uses_objfile (struct objfile *objfile)
9479 {
9480 return m_op->uses_objfile (objfile);
9481 }
9482
9483 void
9484 ada_positional_component::dump (ui_file *stream, int depth)
9485 {
9486 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9487 depth, "", m_index);
9488 m_op->dump (stream, depth + 1);
9489 }
9490
9491 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9492 construct, given that the positions are relative to lower bound
9493 LOW, where HIGH is the upper bound. Record the position in
9494 INDICES. CONTAINER is as for assign_aggregate. */
9495 void
9496 ada_positional_component::assign (aggregate_assigner &assigner)
9497 {
9498 LONGEST ind = m_index + assigner.low;
9499
9500 if (ind - 1 == assigner.high)
9501 warning (_("Extra components in aggregate ignored."));
9502 if (ind <= assigner.high)
9503 {
9504 assigner.add_interval (ind, ind);
9505 assigner.assign (ind, m_op);
9506 }
9507 }
9508
9509 bool
9510 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9511 {
9512 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9513 }
9514
9515 void
9516 ada_discrete_range_association::dump (ui_file *stream, int depth)
9517 {
9518 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9519 m_low->dump (stream, depth + 1);
9520 m_high->dump (stream, depth + 1);
9521 }
9522
9523 void
9524 ada_discrete_range_association::assign (aggregate_assigner &assigner,
9525 operation_up &op)
9526 {
9527 LONGEST lower = value_as_long (m_low->evaluate (nullptr, assigner.exp,
9528 EVAL_NORMAL));
9529 LONGEST upper = value_as_long (m_high->evaluate (nullptr, assigner.exp,
9530 EVAL_NORMAL));
9531
9532 if (lower <= upper && (lower < assigner.low || upper > assigner.high))
9533 error (_("Index in component association out of bounds."));
9534
9535 assigner.add_interval (lower, upper);
9536 while (lower <= upper)
9537 {
9538 assigner.assign (lower, op);
9539 lower += 1;
9540 }
9541 }
9542
9543 bool
9544 ada_name_association::uses_objfile (struct objfile *objfile)
9545 {
9546 return m_val->uses_objfile (objfile);
9547 }
9548
9549 void
9550 ada_name_association::dump (ui_file *stream, int depth)
9551 {
9552 gdb_printf (stream, _("%*sName:\n"), depth, "");
9553 m_val->dump (stream, depth + 1);
9554 }
9555
9556 void
9557 ada_name_association::assign (aggregate_assigner &assigner,
9558 operation_up &op)
9559 {
9560 int index;
9561
9562 if (ada_is_direct_array_type (assigner.lhs->type ()))
9563 {
9564 value *tem = m_val->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9565 index = longest_to_int (value_as_long (tem));
9566 }
9567 else
9568 {
9569 ada_string_operation *strop
9570 = dynamic_cast<ada_string_operation *> (m_val.get ());
9571
9572 const char *name;
9573 if (strop != nullptr)
9574 name = strop->get_name ();
9575 else
9576 {
9577 ada_var_value_operation *vvo
9578 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9579 if (vvo == nullptr)
9580 error (_("Invalid record component association."));
9581 name = vvo->get_symbol ()->natural_name ();
9582 /* In this scenario, the user wrote (name => expr), but
9583 write_name_assoc found some fully-qualified name and
9584 substituted it. This happens because, at parse time, the
9585 meaning of the expression isn't known; but here we know
9586 that just the base name was supplied and it refers to the
9587 name of a field. */
9588 name = ada_unqualified_name (name);
9589 }
9590
9591 index = 0;
9592 if (! find_struct_field (name, assigner.lhs->type (), 0,
9593 NULL, NULL, NULL, NULL, &index))
9594 error (_("Unknown component name: %s."), name);
9595 }
9596
9597 assigner.add_interval (index, index);
9598 assigner.assign (index, op);
9599 }
9600
9601 bool
9602 ada_choices_component::uses_objfile (struct objfile *objfile)
9603 {
9604 if (m_op->uses_objfile (objfile))
9605 return true;
9606 for (const auto &item : m_assocs)
9607 if (item->uses_objfile (objfile))
9608 return true;
9609 return false;
9610 }
9611
9612 void
9613 ada_choices_component::dump (ui_file *stream, int depth)
9614 {
9615 if (m_name.empty ())
9616 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9617 else
9618 {
9619 gdb_printf (stream, _("%*sIterated choices:\n"), depth, "");
9620 gdb_printf (stream, _("%*sName: %s\n"), depth + 1, "", m_name.c_str ());
9621 }
9622 m_op->dump (stream, depth + 1);
9623
9624 for (const auto &item : m_assocs)
9625 item->dump (stream, depth + 1);
9626 }
9627
9628 /* Assign into the components of LHS indexed by the OP_CHOICES
9629 construct at *POS, updating *POS past the construct, given that
9630 the allowable indices are LOW..HIGH. Record the indices assigned
9631 to in INDICES. CONTAINER is as for assign_aggregate. */
9632 void
9633 ada_choices_component::assign (aggregate_assigner &assigner)
9634 {
9635 scoped_restore save_index = make_scoped_restore (&m_assigner, &assigner);
9636 for (auto &item : m_assocs)
9637 item->assign (assigner, m_op);
9638 }
9639
9640 void
9641 ada_index_var_operation::dump (struct ui_file *stream, int depth) const
9642 {
9643 gdb_printf (stream, _("%*sIndex variable: %s\n"), depth, "",
9644 m_var->name ().c_str ());
9645 }
9646
9647 value *
9648 ada_index_var_operation::evaluate (struct type *expect_type,
9649 struct expression *exp,
9650 enum noside noside)
9651 {
9652 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9653 {
9654 /* Note that using an integer type here is incorrect -- the type
9655 should be the array's index type. Unfortunately, though,
9656 this isn't currently available during parsing and type
9657 resolution. */
9658 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9659 return value::zero (index_type, not_lval);
9660 }
9661
9662 return m_var->current_value ();
9663 }
9664
9665 bool
9666 ada_others_component::uses_objfile (struct objfile *objfile)
9667 {
9668 return m_op->uses_objfile (objfile);
9669 }
9670
9671 void
9672 ada_others_component::dump (ui_file *stream, int depth)
9673 {
9674 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9675 m_op->dump (stream, depth + 1);
9676 }
9677
9678 /* Assign the value of the expression in the OP_OTHERS construct in
9679 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9680 have not been previously assigned. The index intervals already assigned
9681 are in INDICES. CONTAINER is as for assign_aggregate. */
9682 void
9683 ada_others_component::assign (aggregate_assigner &assigner)
9684 {
9685 int num_indices = assigner.indices.size ();
9686 for (int i = 0; i < num_indices - 2; i += 2)
9687 {
9688 for (LONGEST ind = assigner.indices[i + 1] + 1;
9689 ind < assigner.indices[i + 2];
9690 ind += 1)
9691 assigner.assign (ind, m_op);
9692 }
9693 }
9694
9695 struct value *
9696 ada_assign_operation::evaluate (struct type *expect_type,
9697 struct expression *exp,
9698 enum noside noside)
9699 {
9700 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9701 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
9702
9703 ada_aggregate_operation *ag_op
9704 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9705 if (ag_op != nullptr)
9706 {
9707 if (noside != EVAL_NORMAL)
9708 return arg1;
9709
9710 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9711 return ada_value_assign (arg1, arg1);
9712 }
9713 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9714 except if the lhs of our assignment is a convenience variable.
9715 In the case of assigning to a convenience variable, the lhs
9716 should be exactly the result of the evaluation of the rhs. */
9717 struct type *type = arg1->type ();
9718 if (arg1->lval () == lval_internalvar)
9719 type = NULL;
9720 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9721 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9722 return arg1;
9723 if (arg1->lval () == lval_internalvar)
9724 {
9725 /* Nothing. */
9726 }
9727 else
9728 arg2 = coerce_for_assign (arg1->type (), arg2);
9729 return ada_value_assign (arg1, arg2);
9730 }
9731
9732 /* See ada-exp.h. */
9733
9734 void
9735 aggregate_assigner::add_interval (LONGEST from, LONGEST to)
9736 {
9737 int i, j;
9738
9739 int size = indices.size ();
9740 for (i = 0; i < size; i += 2) {
9741 if (to >= indices[i] && from <= indices[i + 1])
9742 {
9743 int kh;
9744
9745 for (kh = i + 2; kh < size; kh += 2)
9746 if (to < indices[kh])
9747 break;
9748 if (from < indices[i])
9749 indices[i] = from;
9750 indices[i + 1] = indices[kh - 1];
9751 if (to > indices[i + 1])
9752 indices[i + 1] = to;
9753 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9754 indices.resize (kh - i - 2);
9755 return;
9756 }
9757 else if (to < indices[i])
9758 break;
9759 }
9760
9761 indices.resize (indices.size () + 2);
9762 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9763 indices[j] = indices[j - 2];
9764 indices[i] = from;
9765 indices[i + 1] = to;
9766 }
9767
9768 } /* namespace expr */
9769
9770 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9771 is different. */
9772
9773 static struct value *
9774 ada_value_cast (struct type *type, struct value *arg2)
9775 {
9776 if (type == ada_check_typedef (arg2->type ()))
9777 return arg2;
9778
9779 return value_cast (type, arg2);
9780 }
9781
9782 /* Evaluating Ada expressions, and printing their result.
9783 ------------------------------------------------------
9784
9785 1. Introduction:
9786 ----------------
9787
9788 We usually evaluate an Ada expression in order to print its value.
9789 We also evaluate an expression in order to print its type, which
9790 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9791 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9792 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9793 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9794 similar.
9795
9796 Evaluating expressions is a little more complicated for Ada entities
9797 than it is for entities in languages such as C. The main reason for
9798 this is that Ada provides types whose definition might be dynamic.
9799 One example of such types is variant records. Or another example
9800 would be an array whose bounds can only be known at run time.
9801
9802 The following description is a general guide as to what should be
9803 done (and what should NOT be done) in order to evaluate an expression
9804 involving such types, and when. This does not cover how the semantic
9805 information is encoded by GNAT as this is covered separatly. For the
9806 document used as the reference for the GNAT encoding, see exp_dbug.ads
9807 in the GNAT sources.
9808
9809 Ideally, we should embed each part of this description next to its
9810 associated code. Unfortunately, the amount of code is so vast right
9811 now that it's hard to see whether the code handling a particular
9812 situation might be duplicated or not. One day, when the code is
9813 cleaned up, this guide might become redundant with the comments
9814 inserted in the code, and we might want to remove it.
9815
9816 2. ``Fixing'' an Entity, the Simple Case:
9817 -----------------------------------------
9818
9819 When evaluating Ada expressions, the tricky issue is that they may
9820 reference entities whose type contents and size are not statically
9821 known. Consider for instance a variant record:
9822
9823 type Rec (Empty : Boolean := True) is record
9824 case Empty is
9825 when True => null;
9826 when False => Value : Integer;
9827 end case;
9828 end record;
9829 Yes : Rec := (Empty => False, Value => 1);
9830 No : Rec := (empty => True);
9831
9832 The size and contents of that record depends on the value of the
9833 discriminant (Rec.Empty). At this point, neither the debugging
9834 information nor the associated type structure in GDB are able to
9835 express such dynamic types. So what the debugger does is to create
9836 "fixed" versions of the type that applies to the specific object.
9837 We also informally refer to this operation as "fixing" an object,
9838 which means creating its associated fixed type.
9839
9840 Example: when printing the value of variable "Yes" above, its fixed
9841 type would look like this:
9842
9843 type Rec is record
9844 Empty : Boolean;
9845 Value : Integer;
9846 end record;
9847
9848 On the other hand, if we printed the value of "No", its fixed type
9849 would become:
9850
9851 type Rec is record
9852 Empty : Boolean;
9853 end record;
9854
9855 Things become a little more complicated when trying to fix an entity
9856 with a dynamic type that directly contains another dynamic type,
9857 such as an array of variant records, for instance. There are
9858 two possible cases: Arrays, and records.
9859
9860 3. ``Fixing'' Arrays:
9861 ---------------------
9862
9863 The type structure in GDB describes an array in terms of its bounds,
9864 and the type of its elements. By design, all elements in the array
9865 have the same type and we cannot represent an array of variant elements
9866 using the current type structure in GDB. When fixing an array,
9867 we cannot fix the array element, as we would potentially need one
9868 fixed type per element of the array. As a result, the best we can do
9869 when fixing an array is to produce an array whose bounds and size
9870 are correct (allowing us to read it from memory), but without having
9871 touched its element type. Fixing each element will be done later,
9872 when (if) necessary.
9873
9874 Arrays are a little simpler to handle than records, because the same
9875 amount of memory is allocated for each element of the array, even if
9876 the amount of space actually used by each element differs from element
9877 to element. Consider for instance the following array of type Rec:
9878
9879 type Rec_Array is array (1 .. 2) of Rec;
9880
9881 The actual amount of memory occupied by each element might be different
9882 from element to element, depending on the value of their discriminant.
9883 But the amount of space reserved for each element in the array remains
9884 fixed regardless. So we simply need to compute that size using
9885 the debugging information available, from which we can then determine
9886 the array size (we multiply the number of elements of the array by
9887 the size of each element).
9888
9889 The simplest case is when we have an array of a constrained element
9890 type. For instance, consider the following type declarations:
9891
9892 type Bounded_String (Max_Size : Integer) is
9893 Length : Integer;
9894 Buffer : String (1 .. Max_Size);
9895 end record;
9896 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9897
9898 In this case, the compiler describes the array as an array of
9899 variable-size elements (identified by its XVS suffix) for which
9900 the size can be read in the parallel XVZ variable.
9901
9902 In the case of an array of an unconstrained element type, the compiler
9903 wraps the array element inside a private PAD type. This type should not
9904 be shown to the user, and must be "unwrap"'ed before printing. Note
9905 that we also use the adjective "aligner" in our code to designate
9906 these wrapper types.
9907
9908 In some cases, the size allocated for each element is statically
9909 known. In that case, the PAD type already has the correct size,
9910 and the array element should remain unfixed.
9911
9912 But there are cases when this size is not statically known.
9913 For instance, assuming that "Five" is an integer variable:
9914
9915 type Dynamic is array (1 .. Five) of Integer;
9916 type Wrapper (Has_Length : Boolean := False) is record
9917 Data : Dynamic;
9918 case Has_Length is
9919 when True => Length : Integer;
9920 when False => null;
9921 end case;
9922 end record;
9923 type Wrapper_Array is array (1 .. 2) of Wrapper;
9924
9925 Hello : Wrapper_Array := (others => (Has_Length => True,
9926 Data => (others => 17),
9927 Length => 1));
9928
9929
9930 The debugging info would describe variable Hello as being an
9931 array of a PAD type. The size of that PAD type is not statically
9932 known, but can be determined using a parallel XVZ variable.
9933 In that case, a copy of the PAD type with the correct size should
9934 be used for the fixed array.
9935
9936 3. ``Fixing'' record type objects:
9937 ----------------------------------
9938
9939 Things are slightly different from arrays in the case of dynamic
9940 record types. In this case, in order to compute the associated
9941 fixed type, we need to determine the size and offset of each of
9942 its components. This, in turn, requires us to compute the fixed
9943 type of each of these components.
9944
9945 Consider for instance the example:
9946
9947 type Bounded_String (Max_Size : Natural) is record
9948 Str : String (1 .. Max_Size);
9949 Length : Natural;
9950 end record;
9951 My_String : Bounded_String (Max_Size => 10);
9952
9953 In that case, the position of field "Length" depends on the size
9954 of field Str, which itself depends on the value of the Max_Size
9955 discriminant. In order to fix the type of variable My_String,
9956 we need to fix the type of field Str. Therefore, fixing a variant
9957 record requires us to fix each of its components.
9958
9959 However, if a component does not have a dynamic size, the component
9960 should not be fixed. In particular, fields that use a PAD type
9961 should not fixed. Here is an example where this might happen
9962 (assuming type Rec above):
9963
9964 type Container (Big : Boolean) is record
9965 First : Rec;
9966 After : Integer;
9967 case Big is
9968 when True => Another : Integer;
9969 when False => null;
9970 end case;
9971 end record;
9972 My_Container : Container := (Big => False,
9973 First => (Empty => True),
9974 After => 42);
9975
9976 In that example, the compiler creates a PAD type for component First,
9977 whose size is constant, and then positions the component After just
9978 right after it. The offset of component After is therefore constant
9979 in this case.
9980
9981 The debugger computes the position of each field based on an algorithm
9982 that uses, among other things, the actual position and size of the field
9983 preceding it. Let's now imagine that the user is trying to print
9984 the value of My_Container. If the type fixing was recursive, we would
9985 end up computing the offset of field After based on the size of the
9986 fixed version of field First. And since in our example First has
9987 only one actual field, the size of the fixed type is actually smaller
9988 than the amount of space allocated to that field, and thus we would
9989 compute the wrong offset of field After.
9990
9991 To make things more complicated, we need to watch out for dynamic
9992 components of variant records (identified by the ___XVL suffix in
9993 the component name). Even if the target type is a PAD type, the size
9994 of that type might not be statically known. So the PAD type needs
9995 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9996 we might end up with the wrong size for our component. This can be
9997 observed with the following type declarations:
9998
9999 type Octal is new Integer range 0 .. 7;
10000 type Octal_Array is array (Positive range <>) of Octal;
10001 pragma Pack (Octal_Array);
10002
10003 type Octal_Buffer (Size : Positive) is record
10004 Buffer : Octal_Array (1 .. Size);
10005 Length : Integer;
10006 end record;
10007
10008 In that case, Buffer is a PAD type whose size is unset and needs
10009 to be computed by fixing the unwrapped type.
10010
10011 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10012 ----------------------------------------------------------
10013
10014 Lastly, when should the sub-elements of an entity that remained unfixed
10015 thus far, be actually fixed?
10016
10017 The answer is: Only when referencing that element. For instance
10018 when selecting one component of a record, this specific component
10019 should be fixed at that point in time. Or when printing the value
10020 of a record, each component should be fixed before its value gets
10021 printed. Similarly for arrays, the element of the array should be
10022 fixed when printing each element of the array, or when extracting
10023 one element out of that array. On the other hand, fixing should
10024 not be performed on the elements when taking a slice of an array!
10025
10026 Note that one of the side effects of miscomputing the offset and
10027 size of each field is that we end up also miscomputing the size
10028 of the containing type. This can have adverse results when computing
10029 the value of an entity. GDB fetches the value of an entity based
10030 on the size of its type, and thus a wrong size causes GDB to fetch
10031 the wrong amount of memory. In the case where the computed size is
10032 too small, GDB fetches too little data to print the value of our
10033 entity. Results in this case are unpredictable, as we usually read
10034 past the buffer containing the data =:-o. */
10035
10036 /* A helper function for TERNOP_IN_RANGE. */
10037
10038 static value *
10039 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10040 enum noside noside,
10041 value *arg1, value *arg2, value *arg3)
10042 {
10043 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10044 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10045 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10046 return
10047 value_from_longest (type,
10048 (value_less (arg1, arg3)
10049 || value_equal (arg1, arg3))
10050 && (value_less (arg2, arg1)
10051 || value_equal (arg2, arg1)));
10052 }
10053
10054 /* A helper function for UNOP_NEG. */
10055
10056 value *
10057 ada_unop_neg (struct type *expect_type,
10058 struct expression *exp,
10059 enum noside noside, enum exp_opcode op,
10060 struct value *arg1)
10061 {
10062 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10063 return value_neg (arg1);
10064 }
10065
10066 /* A helper function for UNOP_IN_RANGE. */
10067
10068 value *
10069 ada_unop_in_range (struct type *expect_type,
10070 struct expression *exp,
10071 enum noside noside, enum exp_opcode op,
10072 struct value *arg1, struct type *type)
10073 {
10074 struct value *arg2, *arg3;
10075 switch (type->code ())
10076 {
10077 default:
10078 lim_warning (_("Membership test incompletely implemented; "
10079 "always returns true"));
10080 type = language_bool_type (exp->language_defn, exp->gdbarch);
10081 return value_from_longest (type, 1);
10082
10083 case TYPE_CODE_RANGE:
10084 arg2 = value_from_longest (type,
10085 type->bounds ()->low.const_val ());
10086 arg3 = value_from_longest (type,
10087 type->bounds ()->high.const_val ());
10088 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10089 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10090 type = language_bool_type (exp->language_defn, exp->gdbarch);
10091 return
10092 value_from_longest (type,
10093 (value_less (arg1, arg3)
10094 || value_equal (arg1, arg3))
10095 && (value_less (arg2, arg1)
10096 || value_equal (arg2, arg1)));
10097 }
10098 }
10099
10100 /* A helper function for OP_ATR_TAG. */
10101
10102 value *
10103 ada_atr_tag (struct type *expect_type,
10104 struct expression *exp,
10105 enum noside noside, enum exp_opcode op,
10106 struct value *arg1)
10107 {
10108 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10109 return value::zero (ada_tag_type (arg1), not_lval);
10110
10111 return ada_value_tag (arg1);
10112 }
10113
10114 /* A helper function for OP_ATR_SIZE. */
10115
10116 value *
10117 ada_atr_size (struct type *expect_type,
10118 struct expression *exp,
10119 enum noside noside, enum exp_opcode op,
10120 struct value *arg1)
10121 {
10122 struct type *type = arg1->type ();
10123
10124 /* If the argument is a reference, then dereference its type, since
10125 the user is really asking for the size of the actual object,
10126 not the size of the pointer. */
10127 if (type->code () == TYPE_CODE_REF)
10128 type = type->target_type ();
10129
10130 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10131 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10132 else
10133 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10134 TARGET_CHAR_BIT * type->length ());
10135 }
10136
10137 /* A helper function for UNOP_ABS. */
10138
10139 value *
10140 ada_abs (struct type *expect_type,
10141 struct expression *exp,
10142 enum noside noside, enum exp_opcode op,
10143 struct value *arg1)
10144 {
10145 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10146 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10147 return value_neg (arg1);
10148 else
10149 return arg1;
10150 }
10151
10152 /* A helper function for BINOP_MUL. */
10153
10154 value *
10155 ada_mult_binop (struct type *expect_type,
10156 struct expression *exp,
10157 enum noside noside, enum exp_opcode op,
10158 struct value *arg1, struct value *arg2)
10159 {
10160 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10161 {
10162 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10163 return value::zero (arg1->type (), not_lval);
10164 }
10165 else
10166 {
10167 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10168 return ada_value_binop (arg1, arg2, op);
10169 }
10170 }
10171
10172 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10173
10174 value *
10175 ada_equal_binop (struct type *expect_type,
10176 struct expression *exp,
10177 enum noside noside, enum exp_opcode op,
10178 struct value *arg1, struct value *arg2)
10179 {
10180 int tem;
10181 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10182 tem = 0;
10183 else
10184 {
10185 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10186 tem = ada_value_equal (arg1, arg2);
10187 }
10188 if (op == BINOP_NOTEQUAL)
10189 tem = !tem;
10190 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10191 return value_from_longest (type, tem);
10192 }
10193
10194 /* A helper function for TERNOP_SLICE. */
10195
10196 value *
10197 ada_ternop_slice (struct expression *exp,
10198 enum noside noside,
10199 struct value *array, struct value *low_bound_val,
10200 struct value *high_bound_val)
10201 {
10202 LONGEST low_bound;
10203 LONGEST high_bound;
10204
10205 low_bound_val = coerce_ref (low_bound_val);
10206 high_bound_val = coerce_ref (high_bound_val);
10207 low_bound = value_as_long (low_bound_val);
10208 high_bound = value_as_long (high_bound_val);
10209
10210 /* If this is a reference to an aligner type, then remove all
10211 the aligners. */
10212 if (array->type ()->code () == TYPE_CODE_REF
10213 && ada_is_aligner_type (array->type ()->target_type ()))
10214 array->type ()->set_target_type
10215 (ada_aligned_type (array->type ()->target_type ()));
10216
10217 if (ada_is_any_packed_array_type (array->type ()))
10218 error (_("cannot slice a packed array"));
10219
10220 /* If this is a reference to an array or an array lvalue,
10221 convert to a pointer. */
10222 if (array->type ()->code () == TYPE_CODE_REF
10223 || (array->type ()->code () == TYPE_CODE_ARRAY
10224 && array->lval () == lval_memory))
10225 array = value_addr (array);
10226
10227 if (noside == EVAL_AVOID_SIDE_EFFECTS
10228 && ada_is_array_descriptor_type (ada_check_typedef
10229 (array->type ())))
10230 return empty_array (ada_type_of_array (array, 0), low_bound,
10231 high_bound);
10232
10233 array = ada_coerce_to_simple_array_ptr (array);
10234
10235 /* If we have more than one level of pointer indirection,
10236 dereference the value until we get only one level. */
10237 while (array->type ()->code () == TYPE_CODE_PTR
10238 && (array->type ()->target_type ()->code ()
10239 == TYPE_CODE_PTR))
10240 array = value_ind (array);
10241
10242 /* Make sure we really do have an array type before going further,
10243 to avoid a SEGV when trying to get the index type or the target
10244 type later down the road if the debug info generated by
10245 the compiler is incorrect or incomplete. */
10246 if (!ada_is_simple_array_type (array->type ()))
10247 error (_("cannot take slice of non-array"));
10248
10249 if (ada_check_typedef (array->type ())->code ()
10250 == TYPE_CODE_PTR)
10251 {
10252 struct type *type0 = ada_check_typedef (array->type ());
10253
10254 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10255 return empty_array (type0->target_type (), low_bound, high_bound);
10256 else
10257 {
10258 struct type *arr_type0 =
10259 to_fixed_array_type (type0->target_type (), NULL, 1);
10260
10261 return ada_value_slice_from_ptr (array, arr_type0,
10262 longest_to_int (low_bound),
10263 longest_to_int (high_bound));
10264 }
10265 }
10266 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10267 return array;
10268 else if (high_bound < low_bound)
10269 return empty_array (array->type (), low_bound, high_bound);
10270 else
10271 return ada_value_slice (array, longest_to_int (low_bound),
10272 longest_to_int (high_bound));
10273 }
10274
10275 /* A helper function for BINOP_IN_BOUNDS. */
10276
10277 value *
10278 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10279 struct value *arg1, struct value *arg2, int n)
10280 {
10281 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10282 {
10283 struct type *type = language_bool_type (exp->language_defn,
10284 exp->gdbarch);
10285 return value::zero (type, not_lval);
10286 }
10287
10288 struct type *type = ada_index_type (arg2->type (), n, "range");
10289 if (!type)
10290 type = arg1->type ();
10291
10292 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10293 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10294
10295 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10296 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10297 type = language_bool_type (exp->language_defn, exp->gdbarch);
10298 return value_from_longest (type,
10299 (value_less (arg1, arg3)
10300 || value_equal (arg1, arg3))
10301 && (value_less (arg2, arg1)
10302 || value_equal (arg2, arg1)));
10303 }
10304
10305 /* A helper function for some attribute operations. */
10306
10307 static value *
10308 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10309 struct value *arg1, struct type *type_arg, int tem)
10310 {
10311 const char *attr_name = nullptr;
10312 if (op == OP_ATR_FIRST)
10313 attr_name = "first";
10314 else if (op == OP_ATR_LAST)
10315 attr_name = "last";
10316
10317 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10318 {
10319 if (type_arg == NULL)
10320 type_arg = arg1->type ();
10321
10322 if (ada_is_constrained_packed_array_type (type_arg))
10323 type_arg = decode_constrained_packed_array_type (type_arg);
10324
10325 if (!discrete_type_p (type_arg))
10326 {
10327 switch (op)
10328 {
10329 default: /* Should never happen. */
10330 error (_("unexpected attribute encountered"));
10331 case OP_ATR_FIRST:
10332 case OP_ATR_LAST:
10333 type_arg = ada_index_type (type_arg, tem,
10334 attr_name);
10335 break;
10336 case OP_ATR_LENGTH:
10337 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10338 break;
10339 }
10340 }
10341
10342 return value::zero (type_arg, not_lval);
10343 }
10344 else if (type_arg == NULL)
10345 {
10346 arg1 = ada_coerce_ref (arg1);
10347
10348 if (ada_is_constrained_packed_array_type (arg1->type ()))
10349 arg1 = ada_coerce_to_simple_array (arg1);
10350
10351 struct type *type;
10352 if (op == OP_ATR_LENGTH)
10353 type = builtin_type (exp->gdbarch)->builtin_int;
10354 else
10355 {
10356 type = ada_index_type (arg1->type (), tem,
10357 attr_name);
10358 if (type == NULL)
10359 type = builtin_type (exp->gdbarch)->builtin_int;
10360 }
10361
10362 switch (op)
10363 {
10364 default: /* Should never happen. */
10365 error (_("unexpected attribute encountered"));
10366 case OP_ATR_FIRST:
10367 return value_from_longest
10368 (type, ada_array_bound (arg1, tem, 0));
10369 case OP_ATR_LAST:
10370 return value_from_longest
10371 (type, ada_array_bound (arg1, tem, 1));
10372 case OP_ATR_LENGTH:
10373 return value_from_longest
10374 (type, ada_array_length (arg1, tem));
10375 }
10376 }
10377 else if (discrete_type_p (type_arg))
10378 {
10379 struct type *range_type;
10380 const char *name = ada_type_name (type_arg);
10381
10382 range_type = NULL;
10383 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10384 range_type = to_fixed_range_type (type_arg, NULL);
10385 if (range_type == NULL)
10386 range_type = type_arg;
10387 switch (op)
10388 {
10389 default:
10390 error (_("unexpected attribute encountered"));
10391 case OP_ATR_FIRST:
10392 return value_from_longest
10393 (range_type, ada_discrete_type_low_bound (range_type));
10394 case OP_ATR_LAST:
10395 return value_from_longest
10396 (range_type, ada_discrete_type_high_bound (range_type));
10397 case OP_ATR_LENGTH:
10398 error (_("the 'length attribute applies only to array types"));
10399 }
10400 }
10401 else if (type_arg->code () == TYPE_CODE_FLT)
10402 error (_("unimplemented type attribute"));
10403 else
10404 {
10405 LONGEST low, high;
10406
10407 if (ada_is_constrained_packed_array_type (type_arg))
10408 type_arg = decode_constrained_packed_array_type (type_arg);
10409
10410 struct type *type;
10411 if (op == OP_ATR_LENGTH)
10412 type = builtin_type (exp->gdbarch)->builtin_int;
10413 else
10414 {
10415 type = ada_index_type (type_arg, tem, attr_name);
10416 if (type == NULL)
10417 type = builtin_type (exp->gdbarch)->builtin_int;
10418 }
10419
10420 switch (op)
10421 {
10422 default:
10423 error (_("unexpected attribute encountered"));
10424 case OP_ATR_FIRST:
10425 low = ada_array_bound_from_type (type_arg, tem, 0);
10426 return value_from_longest (type, low);
10427 case OP_ATR_LAST:
10428 high = ada_array_bound_from_type (type_arg, tem, 1);
10429 return value_from_longest (type, high);
10430 case OP_ATR_LENGTH:
10431 low = ada_array_bound_from_type (type_arg, tem, 0);
10432 high = ada_array_bound_from_type (type_arg, tem, 1);
10433 return value_from_longest (type, high - low + 1);
10434 }
10435 }
10436 }
10437
10438 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10439
10440 struct value *
10441 ada_binop_minmax (struct type *expect_type,
10442 struct expression *exp,
10443 enum noside noside, enum exp_opcode op,
10444 struct value *arg1, struct value *arg2)
10445 {
10446 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10447 return value::zero (arg1->type (), not_lval);
10448 else
10449 {
10450 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10451 return value_binop (arg1, arg2, op);
10452 }
10453 }
10454
10455 /* A helper function for BINOP_EXP. */
10456
10457 struct value *
10458 ada_binop_exp (struct type *expect_type,
10459 struct expression *exp,
10460 enum noside noside, enum exp_opcode op,
10461 struct value *arg1, struct value *arg2)
10462 {
10463 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10464 return value::zero (arg1->type (), not_lval);
10465 else
10466 {
10467 /* For integer exponentiation operations,
10468 only promote the first argument. */
10469 if (is_integral_type (arg2->type ()))
10470 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10471 else
10472 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10473
10474 return value_binop (arg1, arg2, op);
10475 }
10476 }
10477
10478 namespace expr
10479 {
10480
10481 /* See ada-exp.h. */
10482
10483 operation_up
10484 ada_resolvable::replace (operation_up &&owner,
10485 struct expression *exp,
10486 bool deprocedure_p,
10487 bool parse_completion,
10488 innermost_block_tracker *tracker,
10489 struct type *context_type)
10490 {
10491 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10492 return (make_operation<ada_funcall_operation>
10493 (std::move (owner),
10494 std::vector<operation_up> ()));
10495 return std::move (owner);
10496 }
10497
10498 /* Convert the character literal whose value would be VAL to the
10499 appropriate value of type TYPE, if there is a translation.
10500 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10501 the literal 'A' (VAL == 65), returns 0. */
10502
10503 static LONGEST
10504 convert_char_literal (struct type *type, LONGEST val)
10505 {
10506 char name[12];
10507 int f;
10508
10509 if (type == NULL)
10510 return val;
10511 type = check_typedef (type);
10512 if (type->code () != TYPE_CODE_ENUM)
10513 return val;
10514
10515 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10516 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10517 else if (val >= 0 && val < 256)
10518 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10519 else if (val >= 0 && val < 0x10000)
10520 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10521 else
10522 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10523 size_t len = strlen (name);
10524 for (f = 0; f < type->num_fields (); f += 1)
10525 {
10526 /* Check the suffix because an enum constant in a package will
10527 have a name like "pkg__QUxx". This is safe enough because we
10528 already have the correct type, and because mangling means
10529 there can't be clashes. */
10530 const char *ename = type->field (f).name ();
10531 size_t elen = strlen (ename);
10532
10533 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10534 return type->field (f).loc_enumval ();
10535 }
10536 return val;
10537 }
10538
10539 value *
10540 ada_char_operation::evaluate (struct type *expect_type,
10541 struct expression *exp,
10542 enum noside noside)
10543 {
10544 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10545 if (expect_type != nullptr)
10546 result = ada_value_cast (expect_type, result);
10547 return result;
10548 }
10549
10550 /* See ada-exp.h. */
10551
10552 operation_up
10553 ada_char_operation::replace (operation_up &&owner,
10554 struct expression *exp,
10555 bool deprocedure_p,
10556 bool parse_completion,
10557 innermost_block_tracker *tracker,
10558 struct type *context_type)
10559 {
10560 operation_up result = std::move (owner);
10561
10562 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10563 {
10564 LONGEST val = as_longest ();
10565 gdb_assert (result.get () == this);
10566 std::get<0> (m_storage) = context_type;
10567 std::get<1> (m_storage) = convert_char_literal (context_type, val);
10568 }
10569
10570 return result;
10571 }
10572
10573 value *
10574 ada_wrapped_operation::evaluate (struct type *expect_type,
10575 struct expression *exp,
10576 enum noside noside)
10577 {
10578 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10579 if (noside == EVAL_NORMAL)
10580 result = unwrap_value (result);
10581
10582 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10583 then we need to perform the conversion manually, because
10584 evaluate_subexp_standard doesn't do it. This conversion is
10585 necessary in Ada because the different kinds of float/fixed
10586 types in Ada have different representations.
10587
10588 Similarly, we need to perform the conversion from OP_LONG
10589 ourselves. */
10590 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10591 result = ada_value_cast (expect_type, result);
10592
10593 return result;
10594 }
10595
10596 void
10597 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10598 struct agent_expr *ax,
10599 struct axs_value *value,
10600 struct type *cast_type)
10601 {
10602 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10603
10604 struct type *type = value->type;
10605 if (ada_is_aligner_type (type))
10606 error (_("Aligner types cannot be handled in agent expressions"));
10607 else if (find_base_type (type) != nullptr)
10608 error (_("Dynamic types cannot be handled in agent expressions"));
10609 }
10610
10611 value *
10612 ada_string_operation::evaluate (struct type *expect_type,
10613 struct expression *exp,
10614 enum noside noside)
10615 {
10616 struct type *char_type;
10617 if (expect_type != nullptr && ada_is_string_type (expect_type))
10618 char_type = ada_array_element_type (expect_type, 1);
10619 else
10620 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10621
10622 const std::string &str = std::get<0> (m_storage);
10623 const char *encoding;
10624 switch (char_type->length ())
10625 {
10626 case 1:
10627 {
10628 /* Simply copy over the data -- this isn't perhaps strictly
10629 correct according to the encodings, but it is gdb's
10630 historical behavior. */
10631 struct type *stringtype
10632 = lookup_array_range_type (char_type, 1, str.length ());
10633 struct value *val = value::allocate (stringtype);
10634 memcpy (val->contents_raw ().data (), str.c_str (),
10635 str.length ());
10636 return val;
10637 }
10638
10639 case 2:
10640 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10641 encoding = "UTF-16BE";
10642 else
10643 encoding = "UTF-16LE";
10644 break;
10645
10646 case 4:
10647 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10648 encoding = "UTF-32BE";
10649 else
10650 encoding = "UTF-32LE";
10651 break;
10652
10653 default:
10654 error (_("unexpected character type size %s"),
10655 pulongest (char_type->length ()));
10656 }
10657
10658 auto_obstack converted;
10659 convert_between_encodings (host_charset (), encoding,
10660 (const gdb_byte *) str.c_str (),
10661 str.length (), 1,
10662 &converted, translit_none);
10663
10664 struct type *stringtype
10665 = lookup_array_range_type (char_type, 1,
10666 obstack_object_size (&converted)
10667 / char_type->length ());
10668 struct value *val = value::allocate (stringtype);
10669 memcpy (val->contents_raw ().data (),
10670 obstack_base (&converted),
10671 obstack_object_size (&converted));
10672 return val;
10673 }
10674
10675 value *
10676 ada_concat_operation::evaluate (struct type *expect_type,
10677 struct expression *exp,
10678 enum noside noside)
10679 {
10680 /* If one side is a literal, evaluate the other side first so that
10681 the expected type can be set properly. */
10682 const operation_up &lhs_expr = std::get<0> (m_storage);
10683 const operation_up &rhs_expr = std::get<1> (m_storage);
10684
10685 value *lhs, *rhs;
10686 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10687 {
10688 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10689 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10690 }
10691 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10692 {
10693 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10694 struct type *rhs_type = check_typedef (rhs->type ());
10695 struct type *elt_type = nullptr;
10696 if (rhs_type->code () == TYPE_CODE_ARRAY)
10697 elt_type = rhs_type->target_type ();
10698 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10699 }
10700 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10701 {
10702 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10703 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10704 }
10705 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10706 {
10707 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10708 struct type *lhs_type = check_typedef (lhs->type ());
10709 struct type *elt_type = nullptr;
10710 if (lhs_type->code () == TYPE_CODE_ARRAY)
10711 elt_type = lhs_type->target_type ();
10712 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10713 }
10714 else
10715 return concat_operation::evaluate (expect_type, exp, noside);
10716
10717 return value_concat (lhs, rhs);
10718 }
10719
10720 value *
10721 ada_qual_operation::evaluate (struct type *expect_type,
10722 struct expression *exp,
10723 enum noside noside)
10724 {
10725 struct type *type = std::get<1> (m_storage);
10726 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10727 }
10728
10729 value *
10730 ada_ternop_range_operation::evaluate (struct type *expect_type,
10731 struct expression *exp,
10732 enum noside noside)
10733 {
10734 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10735 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10736 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10737 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10738 }
10739
10740 value *
10741 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10742 struct expression *exp,
10743 enum noside noside)
10744 {
10745 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10746 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10747
10748 auto do_op = [this] (LONGEST x, LONGEST y)
10749 {
10750 if (std::get<0> (m_storage) == BINOP_ADD)
10751 return x + y;
10752 return x - y;
10753 };
10754
10755 if (arg1->type ()->code () == TYPE_CODE_PTR)
10756 return (value_from_longest
10757 (arg1->type (),
10758 do_op (value_as_long (arg1), value_as_long (arg2))));
10759 if (arg2->type ()->code () == TYPE_CODE_PTR)
10760 return (value_from_longest
10761 (arg2->type (),
10762 do_op (value_as_long (arg1), value_as_long (arg2))));
10763 /* Preserve the original type for use by the range case below.
10764 We cannot cast the result to a reference type, so if ARG1 is
10765 a reference type, find its underlying type. */
10766 struct type *type = arg1->type ();
10767 while (type->code () == TYPE_CODE_REF)
10768 type = type->target_type ();
10769 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10770 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10771 /* We need to special-case the result with a range.
10772 This is done for the benefit of "ptype". gdb's Ada support
10773 historically used the LHS to set the result type here, so
10774 preserve this behavior. */
10775 if (type->code () == TYPE_CODE_RANGE)
10776 arg1 = value_cast (type, arg1);
10777 return arg1;
10778 }
10779
10780 value *
10781 ada_unop_atr_operation::evaluate (struct type *expect_type,
10782 struct expression *exp,
10783 enum noside noside)
10784 {
10785 struct type *type_arg = nullptr;
10786 value *val = nullptr;
10787
10788 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10789 {
10790 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10791 EVAL_AVOID_SIDE_EFFECTS);
10792 type_arg = tem->type ();
10793 }
10794 else
10795 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10796
10797 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10798 val, type_arg, std::get<2> (m_storage));
10799 }
10800
10801 value *
10802 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10803 struct expression *exp,
10804 enum noside noside)
10805 {
10806 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10807 return value::zero (expect_type, not_lval);
10808
10809 const bound_minimal_symbol &b = std::get<0> (m_storage);
10810 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10811
10812 val = ada_value_cast (expect_type, val);
10813
10814 /* Follow the Ada language semantics that do not allow taking
10815 an address of the result of a cast (view conversion in Ada). */
10816 if (val->lval () == lval_memory)
10817 {
10818 if (val->lazy ())
10819 val->fetch_lazy ();
10820 val->set_lval (not_lval);
10821 }
10822 return val;
10823 }
10824
10825 value *
10826 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10827 struct expression *exp,
10828 enum noside noside)
10829 {
10830 value *val = evaluate_var_value (noside,
10831 std::get<0> (m_storage).block,
10832 std::get<0> (m_storage).symbol);
10833
10834 val = ada_value_cast (expect_type, val);
10835
10836 /* Follow the Ada language semantics that do not allow taking
10837 an address of the result of a cast (view conversion in Ada). */
10838 if (val->lval () == lval_memory)
10839 {
10840 if (val->lazy ())
10841 val->fetch_lazy ();
10842 val->set_lval (not_lval);
10843 }
10844 return val;
10845 }
10846
10847 value *
10848 ada_var_value_operation::evaluate (struct type *expect_type,
10849 struct expression *exp,
10850 enum noside noside)
10851 {
10852 symbol *sym = std::get<0> (m_storage).symbol;
10853
10854 if (sym->domain () == UNDEF_DOMAIN)
10855 /* Only encountered when an unresolved symbol occurs in a
10856 context other than a function call, in which case, it is
10857 invalid. */
10858 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10859 sym->print_name ());
10860
10861 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10862 {
10863 struct type *type = static_unwrap_type (sym->type ());
10864 /* Check to see if this is a tagged type. We also need to handle
10865 the case where the type is a reference to a tagged type, but
10866 we have to be careful to exclude pointers to tagged types.
10867 The latter should be shown as usual (as a pointer), whereas
10868 a reference should mostly be transparent to the user. */
10869 if (ada_is_tagged_type (type, 0)
10870 || (type->code () == TYPE_CODE_REF
10871 && ada_is_tagged_type (type->target_type (), 0)))
10872 {
10873 /* Tagged types are a little special in the fact that the real
10874 type is dynamic and can only be determined by inspecting the
10875 object's tag. This means that we need to get the object's
10876 value first (EVAL_NORMAL) and then extract the actual object
10877 type from its tag.
10878
10879 Note that we cannot skip the final step where we extract
10880 the object type from its tag, because the EVAL_NORMAL phase
10881 results in dynamic components being resolved into fixed ones.
10882 This can cause problems when trying to print the type
10883 description of tagged types whose parent has a dynamic size:
10884 We use the type name of the "_parent" component in order
10885 to print the name of the ancestor type in the type description.
10886 If that component had a dynamic size, the resolution into
10887 a fixed type would result in the loss of that type name,
10888 thus preventing us from printing the name of the ancestor
10889 type in the type description. */
10890 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10891
10892 if (type->code () != TYPE_CODE_REF)
10893 {
10894 struct type *actual_type;
10895
10896 actual_type = type_from_tag (ada_value_tag (arg1));
10897 if (actual_type == NULL)
10898 /* If, for some reason, we were unable to determine
10899 the actual type from the tag, then use the static
10900 approximation that we just computed as a fallback.
10901 This can happen if the debugging information is
10902 incomplete, for instance. */
10903 actual_type = type;
10904 return value::zero (actual_type, not_lval);
10905 }
10906 else
10907 {
10908 /* In the case of a ref, ada_coerce_ref takes care
10909 of determining the actual type. But the evaluation
10910 should return a ref as it should be valid to ask
10911 for its address; so rebuild a ref after coerce. */
10912 arg1 = ada_coerce_ref (arg1);
10913 return value_ref (arg1, TYPE_CODE_REF);
10914 }
10915 }
10916
10917 /* Records and unions for which GNAT encodings have been
10918 generated need to be statically fixed as well.
10919 Otherwise, non-static fixing produces a type where
10920 all dynamic properties are removed, which prevents "ptype"
10921 from being able to completely describe the type.
10922 For instance, a case statement in a variant record would be
10923 replaced by the relevant components based on the actual
10924 value of the discriminants. */
10925 if ((type->code () == TYPE_CODE_STRUCT
10926 && dynamic_template_type (type) != NULL)
10927 || (type->code () == TYPE_CODE_UNION
10928 && ada_find_parallel_type (type, "___XVU") != NULL))
10929 return value::zero (to_static_fixed_type (type), not_lval);
10930 }
10931
10932 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10933 return ada_to_fixed_value (arg1);
10934 }
10935
10936 bool
10937 ada_var_value_operation::resolve (struct expression *exp,
10938 bool deprocedure_p,
10939 bool parse_completion,
10940 innermost_block_tracker *tracker,
10941 struct type *context_type)
10942 {
10943 symbol *sym = std::get<0> (m_storage).symbol;
10944 if (sym->domain () == UNDEF_DOMAIN)
10945 {
10946 block_symbol resolved
10947 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10948 context_type, parse_completion,
10949 deprocedure_p, tracker);
10950 std::get<0> (m_storage) = resolved;
10951 }
10952
10953 if (deprocedure_p
10954 && (std::get<0> (m_storage).symbol->type ()->code ()
10955 == TYPE_CODE_FUNC))
10956 return true;
10957
10958 return false;
10959 }
10960
10961 void
10962 ada_var_value_operation::do_generate_ax (struct expression *exp,
10963 struct agent_expr *ax,
10964 struct axs_value *value,
10965 struct type *cast_type)
10966 {
10967 symbol *sym = std::get<0> (m_storage).symbol;
10968
10969 if (sym->domain () == UNDEF_DOMAIN)
10970 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10971 sym->print_name ());
10972
10973 struct type *type = static_unwrap_type (sym->type ());
10974 if (ada_is_tagged_type (type, 0)
10975 || (type->code () == TYPE_CODE_REF
10976 && ada_is_tagged_type (type->target_type (), 0)))
10977 error (_("Tagged types cannot be handled in agent expressions"));
10978
10979 if ((type->code () == TYPE_CODE_STRUCT
10980 && dynamic_template_type (type) != NULL)
10981 || (type->code () == TYPE_CODE_UNION
10982 && ada_find_parallel_type (type, "___XVU") != NULL))
10983 error (_("Dynamic types cannot be handled in agent expressions"));
10984
10985 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10986 }
10987
10988 value *
10989 ada_unop_ind_operation::evaluate (struct type *expect_type,
10990 struct expression *exp,
10991 enum noside noside)
10992 {
10993 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10994
10995 struct type *type = ada_check_typedef (arg1->type ());
10996 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10997 {
10998 if (ada_is_array_descriptor_type (type))
10999 {
11000 /* GDB allows dereferencing GNAT array descriptors.
11001 However, for 'ptype' we don't want to try to
11002 "dereference" a thick pointer here -- that will end up
11003 giving us an array with (1 .. 0) for bounds, which is
11004 less clear than (<>). */
11005 struct type *arrType = ada_type_of_array (arg1, 0);
11006
11007 if (arrType == NULL)
11008 error (_("Attempt to dereference null array pointer."));
11009 if (is_thick_pntr (type))
11010 return arg1;
11011 return value_at_lazy (arrType, 0);
11012 }
11013 else if (type->code () == TYPE_CODE_PTR
11014 || type->code () == TYPE_CODE_REF
11015 /* In C you can dereference an array to get the 1st elt. */
11016 || type->code () == TYPE_CODE_ARRAY)
11017 {
11018 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11019 only be determined by inspecting the object's tag.
11020 This means that we need to evaluate completely the
11021 expression in order to get its type. */
11022
11023 if ((type->code () == TYPE_CODE_REF
11024 || type->code () == TYPE_CODE_PTR)
11025 && ada_is_tagged_type (type->target_type (), 0))
11026 {
11027 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11028 EVAL_NORMAL);
11029 type = ada_value_ind (arg1)->type ();
11030 }
11031 else
11032 {
11033 type = to_static_fixed_type
11034 (ada_aligned_type
11035 (ada_check_typedef (type->target_type ())));
11036 }
11037 return value::zero (type, lval_memory);
11038 }
11039 else if (type->code () == TYPE_CODE_INT)
11040 {
11041 /* GDB allows dereferencing an int. */
11042 if (expect_type == NULL)
11043 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11044 lval_memory);
11045 else
11046 {
11047 expect_type =
11048 to_static_fixed_type (ada_aligned_type (expect_type));
11049 return value::zero (expect_type, lval_memory);
11050 }
11051 }
11052 else
11053 error (_("Attempt to take contents of a non-pointer value."));
11054 }
11055 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11056 type = ada_check_typedef (arg1->type ());
11057
11058 if (type->code () == TYPE_CODE_INT)
11059 /* GDB allows dereferencing an int. If we were given
11060 the expect_type, then use that as the target type.
11061 Otherwise, assume that the target type is an int. */
11062 {
11063 if (expect_type != NULL)
11064 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11065 arg1));
11066 else
11067 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11068 value_as_address (arg1));
11069 }
11070
11071 if (ada_is_array_descriptor_type (type))
11072 /* GDB allows dereferencing GNAT array descriptors. */
11073 return ada_coerce_to_simple_array (arg1);
11074 else
11075 return ada_value_ind (arg1);
11076 }
11077
11078 value *
11079 ada_structop_operation::evaluate (struct type *expect_type,
11080 struct expression *exp,
11081 enum noside noside)
11082 {
11083 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11084 const char *str = std::get<1> (m_storage).c_str ();
11085 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11086 {
11087 struct type *type;
11088 struct type *type1 = arg1->type ();
11089
11090 if (ada_is_tagged_type (type1, 1))
11091 {
11092 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11093
11094 /* If the field is not found, check if it exists in the
11095 extension of this object's type. This means that we
11096 need to evaluate completely the expression. */
11097
11098 if (type == NULL)
11099 {
11100 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11101 EVAL_NORMAL);
11102 arg1 = ada_value_struct_elt (arg1, str, 0);
11103 arg1 = unwrap_value (arg1);
11104 type = ada_to_fixed_value (arg1)->type ();
11105 }
11106 }
11107 else
11108 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11109
11110 return value::zero (ada_aligned_type (type), lval_memory);
11111 }
11112 else
11113 {
11114 arg1 = ada_value_struct_elt (arg1, str, 0);
11115 arg1 = unwrap_value (arg1);
11116 return ada_to_fixed_value (arg1);
11117 }
11118 }
11119
11120 value *
11121 ada_funcall_operation::evaluate (struct type *expect_type,
11122 struct expression *exp,
11123 enum noside noside)
11124 {
11125 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11126 int nargs = args_up.size ();
11127 std::vector<value *> argvec (nargs);
11128 operation_up &callee_op = std::get<0> (m_storage);
11129
11130 ada_var_value_operation *avv
11131 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11132 if (avv != nullptr
11133 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11134 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11135 avv->get_symbol ()->print_name ());
11136
11137 value *callee = callee_op->evaluate (nullptr, exp, noside);
11138 for (int i = 0; i < args_up.size (); ++i)
11139 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11140
11141 if (ada_is_constrained_packed_array_type
11142 (desc_base_type (callee->type ())))
11143 callee = ada_coerce_to_simple_array (callee);
11144 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11145 && callee->type ()->field (0).bitsize () != 0)
11146 /* This is a packed array that has already been fixed, and
11147 therefore already coerced to a simple array. Nothing further
11148 to do. */
11149 ;
11150 else if (callee->type ()->code () == TYPE_CODE_REF)
11151 {
11152 /* Make sure we dereference references so that all the code below
11153 feels like it's really handling the referenced value. Wrapping
11154 types (for alignment) may be there, so make sure we strip them as
11155 well. */
11156 callee = ada_to_fixed_value (coerce_ref (callee));
11157 }
11158 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11159 && callee->lval () == lval_memory)
11160 callee = value_addr (callee);
11161
11162 struct type *type = ada_check_typedef (callee->type ());
11163
11164 /* Ada allows us to implicitly dereference arrays when subscripting
11165 them. So, if this is an array typedef (encoding use for array
11166 access types encoded as fat pointers), strip it now. */
11167 if (type->code () == TYPE_CODE_TYPEDEF)
11168 type = ada_typedef_target_type (type);
11169
11170 if (type->code () == TYPE_CODE_PTR)
11171 {
11172 switch (ada_check_typedef (type->target_type ())->code ())
11173 {
11174 case TYPE_CODE_FUNC:
11175 type = ada_check_typedef (type->target_type ());
11176 break;
11177 case TYPE_CODE_ARRAY:
11178 break;
11179 case TYPE_CODE_STRUCT:
11180 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11181 callee = ada_value_ind (callee);
11182 type = ada_check_typedef (type->target_type ());
11183 break;
11184 default:
11185 error (_("cannot subscript or call something of type `%s'"),
11186 ada_type_name (callee->type ()));
11187 break;
11188 }
11189 }
11190
11191 switch (type->code ())
11192 {
11193 case TYPE_CODE_FUNC:
11194 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11195 {
11196 if (type->target_type () == NULL)
11197 error_call_unknown_return_type (NULL);
11198 return value::allocate (type->target_type ());
11199 }
11200 return call_function_by_hand (callee, expect_type, argvec);
11201 case TYPE_CODE_INTERNAL_FUNCTION:
11202 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11203 /* We don't know anything about what the internal
11204 function might return, but we have to return
11205 something. */
11206 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11207 not_lval);
11208 else
11209 return call_internal_function (exp->gdbarch, exp->language_defn,
11210 callee, nargs,
11211 argvec.data ());
11212
11213 case TYPE_CODE_STRUCT:
11214 {
11215 int arity;
11216
11217 arity = ada_array_arity (type);
11218 type = ada_array_element_type (type, nargs);
11219 if (type == NULL)
11220 error (_("cannot subscript or call a record"));
11221 if (arity != nargs)
11222 error (_("wrong number of subscripts; expecting %d"), arity);
11223 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11224 return value::zero (ada_aligned_type (type), lval_memory);
11225 return
11226 unwrap_value (ada_value_subscript
11227 (callee, nargs, argvec.data ()));
11228 }
11229 case TYPE_CODE_ARRAY:
11230 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11231 {
11232 type = ada_array_element_type (type, nargs);
11233 if (type == NULL)
11234 error (_("element type of array unknown"));
11235 else
11236 return value::zero (ada_aligned_type (type), lval_memory);
11237 }
11238 return
11239 unwrap_value (ada_value_subscript
11240 (ada_coerce_to_simple_array (callee),
11241 nargs, argvec.data ()));
11242 case TYPE_CODE_PTR: /* Pointer to array */
11243 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11244 {
11245 type = to_fixed_array_type (type->target_type (), NULL, 1);
11246 type = ada_array_element_type (type, nargs);
11247 if (type == NULL)
11248 error (_("element type of array unknown"));
11249 else
11250 return value::zero (ada_aligned_type (type), lval_memory);
11251 }
11252 return
11253 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11254 argvec.data ()));
11255
11256 default:
11257 error (_("Attempt to index or call something other than an "
11258 "array or function"));
11259 }
11260 }
11261
11262 bool
11263 ada_funcall_operation::resolve (struct expression *exp,
11264 bool deprocedure_p,
11265 bool parse_completion,
11266 innermost_block_tracker *tracker,
11267 struct type *context_type)
11268 {
11269 operation_up &callee_op = std::get<0> (m_storage);
11270
11271 ada_var_value_operation *avv
11272 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11273 if (avv == nullptr)
11274 return false;
11275
11276 symbol *sym = avv->get_symbol ();
11277 if (sym->domain () != UNDEF_DOMAIN)
11278 return false;
11279
11280 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11281 int nargs = args_up.size ();
11282 std::vector<value *> argvec (nargs);
11283
11284 for (int i = 0; i < args_up.size (); ++i)
11285 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11286
11287 const block *block = avv->get_block ();
11288 block_symbol resolved
11289 = ada_resolve_funcall (sym, block,
11290 context_type, parse_completion,
11291 nargs, argvec.data (),
11292 tracker);
11293
11294 std::get<0> (m_storage)
11295 = make_operation<ada_var_value_operation> (resolved);
11296 return false;
11297 }
11298
11299 bool
11300 ada_ternop_slice_operation::resolve (struct expression *exp,
11301 bool deprocedure_p,
11302 bool parse_completion,
11303 innermost_block_tracker *tracker,
11304 struct type *context_type)
11305 {
11306 /* Historically this check was done during resolution, so we
11307 continue that here. */
11308 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11309 EVAL_AVOID_SIDE_EFFECTS);
11310 if (ada_is_any_packed_array_type (v->type ()))
11311 error (_("cannot slice a packed array"));
11312 return false;
11313 }
11314
11315 }
11316
11317 \f
11318
11319 /* Return non-zero iff TYPE represents a System.Address type. */
11320
11321 int
11322 ada_is_system_address_type (struct type *type)
11323 {
11324 return (type->name () && strcmp (type->name (), "system__address") == 0);
11325 }
11326
11327 \f
11328
11329 /* Range types */
11330
11331 /* Scan STR beginning at position K for a discriminant name, and
11332 return the value of that discriminant field of DVAL in *PX. If
11333 PNEW_K is not null, put the position of the character beyond the
11334 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11335 not alter *PX and *PNEW_K if unsuccessful. */
11336
11337 static int
11338 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11339 int *pnew_k)
11340 {
11341 static std::string storage;
11342 const char *pstart, *pend, *bound;
11343 struct value *bound_val;
11344
11345 if (dval == NULL || str == NULL || str[k] == '\0')
11346 return 0;
11347
11348 pstart = str + k;
11349 pend = strstr (pstart, "__");
11350 if (pend == NULL)
11351 {
11352 bound = pstart;
11353 k += strlen (bound);
11354 }
11355 else
11356 {
11357 int len = pend - pstart;
11358
11359 /* Strip __ and beyond. */
11360 storage = std::string (pstart, len);
11361 bound = storage.c_str ();
11362 k = pend - str;
11363 }
11364
11365 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11366 if (bound_val == NULL)
11367 return 0;
11368
11369 *px = value_as_long (bound_val);
11370 if (pnew_k != NULL)
11371 *pnew_k = k;
11372 return 1;
11373 }
11374
11375 /* Value of variable named NAME. Only exact matches are considered.
11376 If no such variable found, then if ERR_MSG is null, returns 0, and
11377 otherwise causes an error with message ERR_MSG. */
11378
11379 static struct value *
11380 get_var_value (const char *name, const char *err_msg)
11381 {
11382 std::string quoted_name = add_angle_brackets (name);
11383
11384 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11385
11386 std::vector<struct block_symbol> syms
11387 = ada_lookup_symbol_list_worker (lookup_name,
11388 get_selected_block (0),
11389 SEARCH_VFT, 1);
11390
11391 if (syms.size () != 1)
11392 {
11393 if (err_msg == NULL)
11394 return 0;
11395 else
11396 error (("%s"), err_msg);
11397 }
11398
11399 return value_of_variable (syms[0].symbol, syms[0].block);
11400 }
11401
11402 /* Value of integer variable named NAME in the current environment.
11403 If no such variable is found, returns false. Otherwise, sets VALUE
11404 to the variable's value and returns true. */
11405
11406 bool
11407 get_int_var_value (const char *name, LONGEST &value)
11408 {
11409 struct value *var_val = get_var_value (name, 0);
11410
11411 if (var_val == 0)
11412 return false;
11413
11414 value = value_as_long (var_val);
11415 return true;
11416 }
11417
11418
11419 /* Return a range type whose base type is that of the range type named
11420 NAME in the current environment, and whose bounds are calculated
11421 from NAME according to the GNAT range encoding conventions.
11422 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11423 corresponding range type from debug information; fall back to using it
11424 if symbol lookup fails. If a new type must be created, allocate it
11425 like ORIG_TYPE was. The bounds information, in general, is encoded
11426 in NAME, the base type given in the named range type. */
11427
11428 static struct type *
11429 to_fixed_range_type (struct type *raw_type, struct value *dval)
11430 {
11431 const char *name;
11432 struct type *base_type;
11433 const char *subtype_info;
11434
11435 gdb_assert (raw_type != NULL);
11436 gdb_assert (raw_type->name () != NULL);
11437
11438 if (raw_type->code () == TYPE_CODE_RANGE)
11439 base_type = raw_type->target_type ();
11440 else
11441 base_type = raw_type;
11442
11443 name = raw_type->name ();
11444 subtype_info = strstr (name, "___XD");
11445 if (subtype_info == NULL)
11446 {
11447 LONGEST L = ada_discrete_type_low_bound (raw_type);
11448 LONGEST U = ada_discrete_type_high_bound (raw_type);
11449
11450 if (L < INT_MIN || U > INT_MAX)
11451 return raw_type;
11452 else
11453 {
11454 type_allocator alloc (raw_type);
11455 return create_static_range_type (alloc, raw_type, L, U);
11456 }
11457 }
11458 else
11459 {
11460 int prefix_len = subtype_info - name;
11461 LONGEST L, U;
11462 struct type *type;
11463 const char *bounds_str;
11464 int n;
11465
11466 subtype_info += 5;
11467 bounds_str = strchr (subtype_info, '_');
11468 n = 1;
11469
11470 if (*subtype_info == 'L')
11471 {
11472 if (!ada_scan_number (bounds_str, n, &L, &n)
11473 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11474 return raw_type;
11475 if (bounds_str[n] == '_')
11476 n += 2;
11477 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11478 n += 1;
11479 subtype_info += 1;
11480 }
11481 else
11482 {
11483 std::string name_buf = std::string (name, prefix_len) + "___L";
11484 if (!get_int_var_value (name_buf.c_str (), L))
11485 {
11486 lim_warning (_("Unknown lower bound, using 1."));
11487 L = 1;
11488 }
11489 }
11490
11491 if (*subtype_info == 'U')
11492 {
11493 if (!ada_scan_number (bounds_str, n, &U, &n)
11494 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11495 return raw_type;
11496 }
11497 else
11498 {
11499 std::string name_buf = std::string (name, prefix_len) + "___U";
11500 if (!get_int_var_value (name_buf.c_str (), U))
11501 {
11502 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11503 U = L;
11504 }
11505 }
11506
11507 type_allocator alloc (raw_type);
11508 type = create_static_range_type (alloc, base_type, L, U);
11509 /* create_static_range_type alters the resulting type's length
11510 to match the size of the base_type, which is not what we want.
11511 Set it back to the original range type's length. */
11512 type->set_length (raw_type->length ());
11513 type->set_name (name);
11514 return type;
11515 }
11516 }
11517
11518 /* True iff NAME is the name of a range type. */
11519
11520 int
11521 ada_is_range_type_name (const char *name)
11522 {
11523 return (name != NULL && strstr (name, "___XD"));
11524 }
11525 \f
11526
11527 /* Modular types */
11528
11529 /* True iff TYPE is an Ada modular type. */
11530
11531 int
11532 ada_is_modular_type (struct type *type)
11533 {
11534 struct type *subranged_type = get_base_type (type);
11535
11536 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11537 && subranged_type->code () == TYPE_CODE_INT
11538 && subranged_type->is_unsigned ());
11539 }
11540
11541 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11542
11543 ULONGEST
11544 ada_modulus (struct type *type)
11545 {
11546 const dynamic_prop &high = type->bounds ()->high;
11547
11548 if (high.is_constant ())
11549 return (ULONGEST) high.const_val () + 1;
11550
11551 /* If TYPE is unresolved, the high bound might be a location list. Return
11552 0, for lack of a better value to return. */
11553 return 0;
11554 }
11555 \f
11556
11557 /* Ada exception catchpoint support:
11558 ---------------------------------
11559
11560 We support 3 kinds of exception catchpoints:
11561 . catchpoints on Ada exceptions
11562 . catchpoints on unhandled Ada exceptions
11563 . catchpoints on failed assertions
11564
11565 Exceptions raised during failed assertions, or unhandled exceptions
11566 could perfectly be caught with the general catchpoint on Ada exceptions.
11567 However, we can easily differentiate these two special cases, and having
11568 the option to distinguish these two cases from the rest can be useful
11569 to zero-in on certain situations.
11570
11571 Exception catchpoints are a specialized form of breakpoint,
11572 since they rely on inserting breakpoints inside known routines
11573 of the GNAT runtime. The implementation therefore uses a standard
11574 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11575 of breakpoint_ops.
11576
11577 Support in the runtime for exception catchpoints have been changed
11578 a few times already, and these changes affect the implementation
11579 of these catchpoints. In order to be able to support several
11580 variants of the runtime, we use a sniffer that will determine
11581 the runtime variant used by the program being debugged. */
11582
11583 /* Ada's standard exceptions.
11584
11585 The Ada 83 standard also defined Numeric_Error. But there so many
11586 situations where it was unclear from the Ada 83 Reference Manual
11587 (RM) whether Constraint_Error or Numeric_Error should be raised,
11588 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11589 Interpretation saying that anytime the RM says that Numeric_Error
11590 should be raised, the implementation may raise Constraint_Error.
11591 Ada 95 went one step further and pretty much removed Numeric_Error
11592 from the list of standard exceptions (it made it a renaming of
11593 Constraint_Error, to help preserve compatibility when compiling
11594 an Ada83 compiler). As such, we do not include Numeric_Error from
11595 this list of standard exceptions. */
11596
11597 static const char * const standard_exc[] = {
11598 "constraint_error",
11599 "program_error",
11600 "storage_error",
11601 "tasking_error"
11602 };
11603
11604 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11605
11606 /* A structure that describes how to support exception catchpoints
11607 for a given executable. */
11608
11609 struct exception_support_info
11610 {
11611 /* The name of the symbol to break on in order to insert
11612 a catchpoint on exceptions. */
11613 const char *catch_exception_sym;
11614
11615 /* The name of the symbol to break on in order to insert
11616 a catchpoint on unhandled exceptions. */
11617 const char *catch_exception_unhandled_sym;
11618
11619 /* The name of the symbol to break on in order to insert
11620 a catchpoint on failed assertions. */
11621 const char *catch_assert_sym;
11622
11623 /* The name of the symbol to break on in order to insert
11624 a catchpoint on exception handling. */
11625 const char *catch_handlers_sym;
11626
11627 /* Assuming that the inferior just triggered an unhandled exception
11628 catchpoint, this function is responsible for returning the address
11629 in inferior memory where the name of that exception is stored.
11630 Return zero if the address could not be computed. */
11631 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11632 };
11633
11634 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11635 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11636
11637 /* The following exception support info structure describes how to
11638 implement exception catchpoints with the latest version of the
11639 Ada runtime (as of 2019-08-??). */
11640
11641 static const struct exception_support_info default_exception_support_info =
11642 {
11643 "__gnat_debug_raise_exception", /* catch_exception_sym */
11644 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11645 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11646 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11647 ada_unhandled_exception_name_addr
11648 };
11649
11650 /* The following exception support info structure describes how to
11651 implement exception catchpoints with an earlier version of the
11652 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11653
11654 static const struct exception_support_info exception_support_info_v0 =
11655 {
11656 "__gnat_debug_raise_exception", /* catch_exception_sym */
11657 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11658 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11659 "__gnat_begin_handler", /* catch_handlers_sym */
11660 ada_unhandled_exception_name_addr
11661 };
11662
11663 /* The following exception support info structure describes how to
11664 implement exception catchpoints with a slightly older version
11665 of the Ada runtime. */
11666
11667 static const struct exception_support_info exception_support_info_fallback =
11668 {
11669 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11670 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11671 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11672 "__gnat_begin_handler", /* catch_handlers_sym */
11673 ada_unhandled_exception_name_addr_from_raise
11674 };
11675
11676 /* Return nonzero if we can detect the exception support routines
11677 described in EINFO.
11678
11679 This function errors out if an abnormal situation is detected
11680 (for instance, if we find the exception support routines, but
11681 that support is found to be incomplete). */
11682
11683 static int
11684 ada_has_this_exception_support (const struct exception_support_info *einfo)
11685 {
11686 struct symbol *sym;
11687
11688 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11689 that should be compiled with debugging information. As a result, we
11690 expect to find that symbol in the symtabs. */
11691
11692 sym = standard_lookup (einfo->catch_exception_sym, NULL, SEARCH_VFT);
11693 if (sym == NULL)
11694 {
11695 /* Perhaps we did not find our symbol because the Ada runtime was
11696 compiled without debugging info, or simply stripped of it.
11697 It happens on some GNU/Linux distributions for instance, where
11698 users have to install a separate debug package in order to get
11699 the runtime's debugging info. In that situation, let the user
11700 know why we cannot insert an Ada exception catchpoint.
11701
11702 Note: Just for the purpose of inserting our Ada exception
11703 catchpoint, we could rely purely on the associated minimal symbol.
11704 But we would be operating in degraded mode anyway, since we are
11705 still lacking the debugging info needed later on to extract
11706 the name of the exception being raised (this name is printed in
11707 the catchpoint message, and is also used when trying to catch
11708 a specific exception). We do not handle this case for now. */
11709 struct bound_minimal_symbol msym
11710 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11711
11712 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11713 error (_("Your Ada runtime appears to be missing some debugging "
11714 "information.\nCannot insert Ada exception catchpoint "
11715 "in this configuration."));
11716
11717 return 0;
11718 }
11719
11720 /* Make sure that the symbol we found corresponds to a function. */
11721
11722 if (sym->aclass () != LOC_BLOCK)
11723 error (_("Symbol \"%s\" is not a function (class = %d)"),
11724 sym->linkage_name (), sym->aclass ());
11725
11726 sym = standard_lookup (einfo->catch_handlers_sym, NULL, SEARCH_VFT);
11727 if (sym == NULL)
11728 {
11729 struct bound_minimal_symbol msym
11730 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11731
11732 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11733 error (_("Your Ada runtime appears to be missing some debugging "
11734 "information.\nCannot insert Ada exception catchpoint "
11735 "in this configuration."));
11736
11737 return 0;
11738 }
11739
11740 /* Make sure that the symbol we found corresponds to a function. */
11741
11742 if (sym->aclass () != LOC_BLOCK)
11743 error (_("Symbol \"%s\" is not a function (class = %d)"),
11744 sym->linkage_name (), sym->aclass ());
11745
11746 return 1;
11747 }
11748
11749 /* Inspect the Ada runtime and determine which exception info structure
11750 should be used to provide support for exception catchpoints.
11751
11752 This function will always set the per-inferior exception_info,
11753 or raise an error. */
11754
11755 static void
11756 ada_exception_support_info_sniffer (void)
11757 {
11758 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11759
11760 /* If the exception info is already known, then no need to recompute it. */
11761 if (data->exception_info != NULL)
11762 return;
11763
11764 /* Check the latest (default) exception support info. */
11765 if (ada_has_this_exception_support (&default_exception_support_info))
11766 {
11767 data->exception_info = &default_exception_support_info;
11768 return;
11769 }
11770
11771 /* Try the v0 exception suport info. */
11772 if (ada_has_this_exception_support (&exception_support_info_v0))
11773 {
11774 data->exception_info = &exception_support_info_v0;
11775 return;
11776 }
11777
11778 /* Try our fallback exception suport info. */
11779 if (ada_has_this_exception_support (&exception_support_info_fallback))
11780 {
11781 data->exception_info = &exception_support_info_fallback;
11782 return;
11783 }
11784
11785 throw_error (NOT_FOUND_ERROR,
11786 _("Could not find Ada runtime exception support"));
11787 }
11788
11789 /* True iff FRAME is very likely to be that of a function that is
11790 part of the runtime system. This is all very heuristic, but is
11791 intended to be used as advice as to what frames are uninteresting
11792 to most users. */
11793
11794 static int
11795 is_known_support_routine (const frame_info_ptr &frame)
11796 {
11797 enum language func_lang;
11798 int i;
11799 const char *fullname;
11800
11801 /* If this code does not have any debugging information (no symtab),
11802 This cannot be any user code. */
11803
11804 symtab_and_line sal = find_frame_sal (frame);
11805 if (sal.symtab == NULL)
11806 return 1;
11807
11808 /* If there is a symtab, but the associated source file cannot be
11809 located, then assume this is not user code: Selecting a frame
11810 for which we cannot display the code would not be very helpful
11811 for the user. This should also take care of case such as VxWorks
11812 where the kernel has some debugging info provided for a few units. */
11813
11814 fullname = symtab_to_fullname (sal.symtab);
11815 if (access (fullname, R_OK) != 0)
11816 return 1;
11817
11818 /* Check the unit filename against the Ada runtime file naming.
11819 We also check the name of the objfile against the name of some
11820 known system libraries that sometimes come with debugging info
11821 too. */
11822
11823 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11824 {
11825 re_comp (known_runtime_file_name_patterns[i]);
11826 if (re_exec (lbasename (sal.symtab->filename)))
11827 return 1;
11828 if (sal.symtab->compunit ()->objfile () != NULL
11829 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11830 return 1;
11831 }
11832
11833 /* Check whether the function is a GNAT-generated entity. */
11834
11835 gdb::unique_xmalloc_ptr<char> func_name
11836 = find_frame_funname (frame, &func_lang, NULL);
11837 if (func_name == NULL)
11838 return 1;
11839
11840 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11841 {
11842 re_comp (known_auxiliary_function_name_patterns[i]);
11843 if (re_exec (func_name.get ()))
11844 return 1;
11845 }
11846
11847 return 0;
11848 }
11849
11850 /* Find the first frame that contains debugging information and that is not
11851 part of the Ada run-time, starting from FI and moving upward. */
11852
11853 void
11854 ada_find_printable_frame (const frame_info_ptr &initial_fi)
11855 {
11856 for (frame_info_ptr fi = initial_fi; fi != nullptr; fi = get_prev_frame (fi))
11857 {
11858 if (!is_known_support_routine (fi))
11859 {
11860 select_frame (fi);
11861 break;
11862 }
11863 }
11864
11865 }
11866
11867 /* Assuming that the inferior just triggered an unhandled exception
11868 catchpoint, return the address in inferior memory where the name
11869 of the exception is stored.
11870
11871 Return zero if the address could not be computed. */
11872
11873 static CORE_ADDR
11874 ada_unhandled_exception_name_addr (void)
11875 {
11876 return parse_and_eval_address ("e.full_name");
11877 }
11878
11879 /* Same as ada_unhandled_exception_name_addr, except that this function
11880 should be used when the inferior uses an older version of the runtime,
11881 where the exception name needs to be extracted from a specific frame
11882 several frames up in the callstack. */
11883
11884 static CORE_ADDR
11885 ada_unhandled_exception_name_addr_from_raise (void)
11886 {
11887 int frame_level;
11888 frame_info_ptr fi;
11889 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11890
11891 /* To determine the name of this exception, we need to select
11892 the frame corresponding to RAISE_SYM_NAME. This frame is
11893 at least 3 levels up, so we simply skip the first 3 frames
11894 without checking the name of their associated function. */
11895 fi = get_current_frame ();
11896 for (frame_level = 0; frame_level < 3; frame_level += 1)
11897 if (fi != NULL)
11898 fi = get_prev_frame (fi);
11899
11900 while (fi != NULL)
11901 {
11902 enum language func_lang;
11903
11904 gdb::unique_xmalloc_ptr<char> func_name
11905 = find_frame_funname (fi, &func_lang, NULL);
11906 if (func_name != NULL)
11907 {
11908 if (strcmp (func_name.get (),
11909 data->exception_info->catch_exception_sym) == 0)
11910 break; /* We found the frame we were looking for... */
11911 }
11912 fi = get_prev_frame (fi);
11913 }
11914
11915 if (fi == NULL)
11916 return 0;
11917
11918 select_frame (fi);
11919 return parse_and_eval_address ("id.full_name");
11920 }
11921
11922 /* Assuming the inferior just triggered an Ada exception catchpoint
11923 (of any type), return the address in inferior memory where the name
11924 of the exception is stored, if applicable.
11925
11926 Assumes the selected frame is the current frame.
11927
11928 Return zero if the address could not be computed, or if not relevant. */
11929
11930 static CORE_ADDR
11931 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11932 {
11933 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11934
11935 switch (ex)
11936 {
11937 case ada_catch_exception:
11938 return (parse_and_eval_address ("e.full_name"));
11939 break;
11940
11941 case ada_catch_exception_unhandled:
11942 return data->exception_info->unhandled_exception_name_addr ();
11943 break;
11944
11945 case ada_catch_handlers:
11946 return 0; /* The runtimes does not provide access to the exception
11947 name. */
11948 break;
11949
11950 case ada_catch_assert:
11951 return 0; /* Exception name is not relevant in this case. */
11952 break;
11953
11954 default:
11955 internal_error (_("unexpected catchpoint type"));
11956 break;
11957 }
11958
11959 return 0; /* Should never be reached. */
11960 }
11961
11962 /* Assuming the inferior is stopped at an exception catchpoint,
11963 return the message which was associated to the exception, if
11964 available. Return NULL if the message could not be retrieved.
11965
11966 Note: The exception message can be associated to an exception
11967 either through the use of the Raise_Exception function, or
11968 more simply (Ada 2005 and later), via:
11969
11970 raise Exception_Name with "exception message";
11971
11972 */
11973
11974 static gdb::unique_xmalloc_ptr<char>
11975 ada_exception_message_1 (void)
11976 {
11977 struct value *e_msg_val;
11978 int e_msg_len;
11979
11980 /* For runtimes that support this feature, the exception message
11981 is passed as an unbounded string argument called "message". */
11982 e_msg_val = parse_and_eval ("message");
11983 if (e_msg_val == NULL)
11984 return NULL; /* Exception message not supported. */
11985
11986 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11987 gdb_assert (e_msg_val != NULL);
11988 e_msg_len = e_msg_val->type ()->length ();
11989
11990 /* If the message string is empty, then treat it as if there was
11991 no exception message. */
11992 if (e_msg_len <= 0)
11993 return NULL;
11994
11995 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11996 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
11997 e_msg_len);
11998 e_msg.get ()[e_msg_len] = '\0';
11999
12000 return e_msg;
12001 }
12002
12003 /* Same as ada_exception_message_1, except that all exceptions are
12004 contained here (returning NULL instead). */
12005
12006 static gdb::unique_xmalloc_ptr<char>
12007 ada_exception_message (void)
12008 {
12009 gdb::unique_xmalloc_ptr<char> e_msg;
12010
12011 try
12012 {
12013 e_msg = ada_exception_message_1 ();
12014 }
12015 catch (const gdb_exception_error &e)
12016 {
12017 e_msg.reset (nullptr);
12018 }
12019
12020 return e_msg;
12021 }
12022
12023 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12024 any error that ada_exception_name_addr_1 might cause to be thrown.
12025 When an error is intercepted, a warning with the error message is printed,
12026 and zero is returned. */
12027
12028 static CORE_ADDR
12029 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12030 {
12031 CORE_ADDR result = 0;
12032
12033 try
12034 {
12035 result = ada_exception_name_addr_1 (ex);
12036 }
12037
12038 catch (const gdb_exception_error &e)
12039 {
12040 warning (_("failed to get exception name: %s"), e.what ());
12041 return 0;
12042 }
12043
12044 return result;
12045 }
12046
12047 static std::string ada_exception_catchpoint_cond_string
12048 (const char *excep_string,
12049 enum ada_exception_catchpoint_kind ex);
12050
12051 /* Ada catchpoints.
12052
12053 In the case of catchpoints on Ada exceptions, the catchpoint will
12054 stop the target on every exception the program throws. When a user
12055 specifies the name of a specific exception, we translate this
12056 request into a condition expression (in text form), and then parse
12057 it into an expression stored in each of the catchpoint's locations.
12058 We then use this condition to check whether the exception that was
12059 raised is the one the user is interested in. If not, then the
12060 target is resumed again. We store the name of the requested
12061 exception, in order to be able to re-set the condition expression
12062 when symbols change. */
12063
12064 /* An instance of this type is used to represent an Ada catchpoint. */
12065
12066 struct ada_catchpoint : public code_breakpoint
12067 {
12068 ada_catchpoint (struct gdbarch *gdbarch_,
12069 enum ada_exception_catchpoint_kind kind,
12070 const char *cond_string,
12071 bool tempflag,
12072 bool enabled,
12073 bool from_tty,
12074 std::string &&excep_string_)
12075 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
12076 m_excep_string (std::move (excep_string_)),
12077 m_kind (kind)
12078 {
12079 /* Unlike most code_breakpoint types, Ada catchpoints are
12080 pspace-specific. */
12081 pspace = current_program_space;
12082 enable_state = enabled ? bp_enabled : bp_disabled;
12083 language = language_ada;
12084
12085 re_set ();
12086 }
12087
12088 struct bp_location *allocate_location () override;
12089 void re_set () override;
12090 void check_status (struct bpstat *bs) override;
12091 enum print_stop_action print_it (const bpstat *bs) const override;
12092 bool print_one (const bp_location **) const override;
12093 void print_mention () const override;
12094 void print_recreate (struct ui_file *fp) const override;
12095
12096 private:
12097
12098 /* A helper function for check_status. Returns true if we should
12099 stop for this breakpoint hit. If the user specified a specific
12100 exception, we only want to cause a stop if the program thrown
12101 that exception. */
12102 bool should_stop_exception (const struct bp_location *bl) const;
12103
12104 /* The name of the specific exception the user specified. */
12105 std::string m_excep_string;
12106
12107 /* What kind of catchpoint this is. */
12108 enum ada_exception_catchpoint_kind m_kind;
12109 };
12110
12111 /* An instance of this type is used to represent an Ada catchpoint
12112 breakpoint location. */
12113
12114 class ada_catchpoint_location : public bp_location
12115 {
12116 public:
12117 explicit ada_catchpoint_location (ada_catchpoint *owner)
12118 : bp_location (owner, bp_loc_software_breakpoint)
12119 {}
12120
12121 /* The condition that checks whether the exception that was raised
12122 is the specific exception the user specified on catchpoint
12123 creation. */
12124 expression_up excep_cond_expr;
12125 };
12126
12127 static struct symtab_and_line ada_exception_sal
12128 (enum ada_exception_catchpoint_kind ex);
12129
12130 /* Implement the RE_SET method in the structure for all exception
12131 catchpoint kinds. */
12132
12133 void
12134 ada_catchpoint::re_set ()
12135 {
12136 std::vector<symtab_and_line> sals;
12137 try
12138 {
12139 struct symtab_and_line sal = ada_exception_sal (m_kind);
12140 sals.push_back (sal);
12141 }
12142 catch (const gdb_exception_error &ex)
12143 {
12144 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12145 if (ex.error != NOT_FOUND_ERROR)
12146 throw;
12147 }
12148
12149 update_breakpoint_locations (this, pspace, sals, {});
12150
12151 /* Reparse the exception conditional expressions. One for each
12152 location. */
12153
12154 /* Nothing to do if there's no specific exception to catch. */
12155 if (m_excep_string.empty ())
12156 return;
12157
12158 /* Same if there are no locations... */
12159 if (!has_locations ())
12160 return;
12161
12162 /* Compute the condition expression in text form, from the specific
12163 exception we want to catch. */
12164 std::string cond_string
12165 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
12166
12167 /* Iterate over all the catchpoint's locations, and parse an
12168 expression for each. */
12169 for (bp_location &bl : locations ())
12170 {
12171 ada_catchpoint_location &ada_loc
12172 = static_cast<ada_catchpoint_location &> (bl);
12173 expression_up exp;
12174
12175 if (!bl.shlib_disabled)
12176 {
12177 const char *s;
12178
12179 s = cond_string.c_str ();
12180 try
12181 {
12182 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
12183 }
12184 catch (const gdb_exception_error &e)
12185 {
12186 warning (_("failed to reevaluate internal exception condition "
12187 "for catchpoint %d: %s"),
12188 number, e.what ());
12189 }
12190 }
12191
12192 ada_loc.excep_cond_expr = std::move (exp);
12193 }
12194 }
12195
12196 /* Implement the ALLOCATE_LOCATION method in the structure for all
12197 exception catchpoint kinds. */
12198
12199 struct bp_location *
12200 ada_catchpoint::allocate_location ()
12201 {
12202 return new ada_catchpoint_location (this);
12203 }
12204
12205 /* See declaration. */
12206
12207 bool
12208 ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
12209 {
12210 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
12211 const struct ada_catchpoint_location *ada_loc
12212 = (const struct ada_catchpoint_location *) bl;
12213 bool stop;
12214
12215 struct internalvar *var = lookup_internalvar ("_ada_exception");
12216 if (c->m_kind == ada_catch_assert)
12217 clear_internalvar (var);
12218 else
12219 {
12220 try
12221 {
12222 const char *expr;
12223
12224 if (c->m_kind == ada_catch_handlers)
12225 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12226 ".all.occurrence.id");
12227 else
12228 expr = "e";
12229
12230 struct value *exc = parse_and_eval (expr);
12231 set_internalvar (var, exc);
12232 }
12233 catch (const gdb_exception_error &ex)
12234 {
12235 clear_internalvar (var);
12236 }
12237 }
12238
12239 /* With no specific exception, should always stop. */
12240 if (c->m_excep_string.empty ())
12241 return true;
12242
12243 if (ada_loc->excep_cond_expr == NULL)
12244 {
12245 /* We will have a NULL expression if back when we were creating
12246 the expressions, this location's had failed to parse. */
12247 return true;
12248 }
12249
12250 stop = true;
12251 try
12252 {
12253 scoped_value_mark mark;
12254 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
12255 }
12256 catch (const gdb_exception_error &ex)
12257 {
12258 exception_fprintf (gdb_stderr, ex,
12259 _("Error in testing exception condition:\n"));
12260 }
12261
12262 return stop;
12263 }
12264
12265 /* Implement the CHECK_STATUS method in the structure for all
12266 exception catchpoint kinds. */
12267
12268 void
12269 ada_catchpoint::check_status (bpstat *bs)
12270 {
12271 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12272 }
12273
12274 /* Implement the PRINT_IT method in the structure for all exception
12275 catchpoint kinds. */
12276
12277 enum print_stop_action
12278 ada_catchpoint::print_it (const bpstat *bs) const
12279 {
12280 struct ui_out *uiout = current_uiout;
12281
12282 annotate_catchpoint (number);
12283
12284 if (uiout->is_mi_like_p ())
12285 {
12286 uiout->field_string ("reason",
12287 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12288 uiout->field_string ("disp", bpdisp_text (disposition));
12289 }
12290
12291 uiout->text (disposition == disp_del
12292 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12293 print_num_locno (bs, uiout);
12294 uiout->text (", ");
12295
12296 /* ada_exception_name_addr relies on the selected frame being the
12297 current frame. Need to do this here because this function may be
12298 called more than once when printing a stop, and below, we'll
12299 select the first frame past the Ada run-time (see
12300 ada_find_printable_frame). */
12301 select_frame (get_current_frame ());
12302
12303 switch (m_kind)
12304 {
12305 case ada_catch_exception:
12306 case ada_catch_exception_unhandled:
12307 case ada_catch_handlers:
12308 {
12309 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12310 char exception_name[256];
12311
12312 if (addr != 0)
12313 {
12314 read_memory (addr, (gdb_byte *) exception_name,
12315 sizeof (exception_name) - 1);
12316 exception_name [sizeof (exception_name) - 1] = '\0';
12317 }
12318 else
12319 {
12320 /* For some reason, we were unable to read the exception
12321 name. This could happen if the Runtime was compiled
12322 without debugging info, for instance. In that case,
12323 just replace the exception name by the generic string
12324 "exception" - it will read as "an exception" in the
12325 notification we are about to print. */
12326 memcpy (exception_name, "exception", sizeof ("exception"));
12327 }
12328 /* In the case of unhandled exception breakpoints, we print
12329 the exception name as "unhandled EXCEPTION_NAME", to make
12330 it clearer to the user which kind of catchpoint just got
12331 hit. We used ui_out_text to make sure that this extra
12332 info does not pollute the exception name in the MI case. */
12333 if (m_kind == ada_catch_exception_unhandled)
12334 uiout->text ("unhandled ");
12335 uiout->field_string ("exception-name", exception_name);
12336 }
12337 break;
12338 case ada_catch_assert:
12339 /* In this case, the name of the exception is not really
12340 important. Just print "failed assertion" to make it clearer
12341 that his program just hit an assertion-failure catchpoint.
12342 We used ui_out_text because this info does not belong in
12343 the MI output. */
12344 uiout->text ("failed assertion");
12345 break;
12346 }
12347
12348 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12349 if (exception_message != NULL)
12350 {
12351 uiout->text (" (");
12352 uiout->field_string ("exception-message", exception_message.get ());
12353 uiout->text (")");
12354 }
12355
12356 uiout->text (" at ");
12357 ada_find_printable_frame (get_current_frame ());
12358
12359 return PRINT_SRC_AND_LOC;
12360 }
12361
12362 /* Implement the PRINT_ONE method in the structure for all exception
12363 catchpoint kinds. */
12364
12365 bool
12366 ada_catchpoint::print_one (const bp_location **last_loc) const
12367 {
12368 struct ui_out *uiout = current_uiout;
12369 struct value_print_options opts;
12370
12371 get_user_print_options (&opts);
12372
12373 if (opts.addressprint)
12374 uiout->field_skip ("addr");
12375
12376 annotate_field (5);
12377 switch (m_kind)
12378 {
12379 case ada_catch_exception:
12380 if (!m_excep_string.empty ())
12381 {
12382 std::string msg = string_printf (_("`%s' Ada exception"),
12383 m_excep_string.c_str ());
12384
12385 uiout->field_string ("what", msg);
12386 }
12387 else
12388 uiout->field_string ("what", "all Ada exceptions");
12389
12390 break;
12391
12392 case ada_catch_exception_unhandled:
12393 uiout->field_string ("what", "unhandled Ada exceptions");
12394 break;
12395
12396 case ada_catch_handlers:
12397 if (!m_excep_string.empty ())
12398 {
12399 uiout->field_fmt ("what",
12400 _("`%s' Ada exception handlers"),
12401 m_excep_string.c_str ());
12402 }
12403 else
12404 uiout->field_string ("what", "all Ada exceptions handlers");
12405 break;
12406
12407 case ada_catch_assert:
12408 uiout->field_string ("what", "failed Ada assertions");
12409 break;
12410
12411 default:
12412 internal_error (_("unexpected catchpoint type"));
12413 break;
12414 }
12415
12416 return true;
12417 }
12418
12419 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12420 for all exception catchpoint kinds. */
12421
12422 void
12423 ada_catchpoint::print_mention () const
12424 {
12425 struct ui_out *uiout = current_uiout;
12426
12427 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12428 : _("Catchpoint "));
12429 uiout->field_signed ("bkptno", number);
12430 uiout->text (": ");
12431
12432 switch (m_kind)
12433 {
12434 case ada_catch_exception:
12435 if (!m_excep_string.empty ())
12436 {
12437 std::string info = string_printf (_("`%s' Ada exception"),
12438 m_excep_string.c_str ());
12439 uiout->text (info);
12440 }
12441 else
12442 uiout->text (_("all Ada exceptions"));
12443 break;
12444
12445 case ada_catch_exception_unhandled:
12446 uiout->text (_("unhandled Ada exceptions"));
12447 break;
12448
12449 case ada_catch_handlers:
12450 if (!m_excep_string.empty ())
12451 {
12452 std::string info
12453 = string_printf (_("`%s' Ada exception handlers"),
12454 m_excep_string.c_str ());
12455 uiout->text (info);
12456 }
12457 else
12458 uiout->text (_("all Ada exceptions handlers"));
12459 break;
12460
12461 case ada_catch_assert:
12462 uiout->text (_("failed Ada assertions"));
12463 break;
12464
12465 default:
12466 internal_error (_("unexpected catchpoint type"));
12467 break;
12468 }
12469 }
12470
12471 /* Implement the PRINT_RECREATE method in the structure for all
12472 exception catchpoint kinds. */
12473
12474 void
12475 ada_catchpoint::print_recreate (struct ui_file *fp) const
12476 {
12477 switch (m_kind)
12478 {
12479 case ada_catch_exception:
12480 gdb_printf (fp, "catch exception");
12481 if (!m_excep_string.empty ())
12482 gdb_printf (fp, " %s", m_excep_string.c_str ());
12483 break;
12484
12485 case ada_catch_exception_unhandled:
12486 gdb_printf (fp, "catch exception unhandled");
12487 break;
12488
12489 case ada_catch_handlers:
12490 gdb_printf (fp, "catch handlers");
12491 break;
12492
12493 case ada_catch_assert:
12494 gdb_printf (fp, "catch assert");
12495 break;
12496
12497 default:
12498 internal_error (_("unexpected catchpoint type"));
12499 }
12500 print_recreate_thread (fp);
12501 }
12502
12503 /* See ada-lang.h. */
12504
12505 bool
12506 is_ada_exception_catchpoint (breakpoint *bp)
12507 {
12508 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12509 }
12510
12511 /* Split the arguments specified in a "catch exception" command.
12512 Set EX to the appropriate catchpoint type.
12513 Set EXCEP_STRING to the name of the specific exception if
12514 specified by the user.
12515 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12516 "catch handlers" command. False otherwise.
12517 If a condition is found at the end of the arguments, the condition
12518 expression is stored in COND_STRING (memory must be deallocated
12519 after use). Otherwise COND_STRING is set to NULL. */
12520
12521 static void
12522 catch_ada_exception_command_split (const char *args,
12523 bool is_catch_handlers_cmd,
12524 enum ada_exception_catchpoint_kind *ex,
12525 std::string *excep_string,
12526 std::string *cond_string)
12527 {
12528 std::string exception_name;
12529
12530 exception_name = extract_arg (&args);
12531 if (exception_name == "if")
12532 {
12533 /* This is not an exception name; this is the start of a condition
12534 expression for a catchpoint on all exceptions. So, "un-get"
12535 this token, and set exception_name to NULL. */
12536 exception_name.clear ();
12537 args -= 2;
12538 }
12539
12540 /* Check to see if we have a condition. */
12541
12542 args = skip_spaces (args);
12543 if (startswith (args, "if")
12544 && (isspace (args[2]) || args[2] == '\0'))
12545 {
12546 args += 2;
12547 args = skip_spaces (args);
12548
12549 if (args[0] == '\0')
12550 error (_("Condition missing after `if' keyword"));
12551 *cond_string = args;
12552
12553 args += strlen (args);
12554 }
12555
12556 /* Check that we do not have any more arguments. Anything else
12557 is unexpected. */
12558
12559 if (args[0] != '\0')
12560 error (_("Junk at end of expression"));
12561
12562 if (is_catch_handlers_cmd)
12563 {
12564 /* Catch handling of exceptions. */
12565 *ex = ada_catch_handlers;
12566 *excep_string = exception_name;
12567 }
12568 else if (exception_name.empty ())
12569 {
12570 /* Catch all exceptions. */
12571 *ex = ada_catch_exception;
12572 excep_string->clear ();
12573 }
12574 else if (exception_name == "unhandled")
12575 {
12576 /* Catch unhandled exceptions. */
12577 *ex = ada_catch_exception_unhandled;
12578 excep_string->clear ();
12579 }
12580 else
12581 {
12582 /* Catch a specific exception. */
12583 *ex = ada_catch_exception;
12584 *excep_string = exception_name;
12585 }
12586 }
12587
12588 /* Return the name of the symbol on which we should break in order to
12589 implement a catchpoint of the EX kind. */
12590
12591 static const char *
12592 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12593 {
12594 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12595
12596 gdb_assert (data->exception_info != NULL);
12597
12598 switch (ex)
12599 {
12600 case ada_catch_exception:
12601 return (data->exception_info->catch_exception_sym);
12602 break;
12603 case ada_catch_exception_unhandled:
12604 return (data->exception_info->catch_exception_unhandled_sym);
12605 break;
12606 case ada_catch_assert:
12607 return (data->exception_info->catch_assert_sym);
12608 break;
12609 case ada_catch_handlers:
12610 return (data->exception_info->catch_handlers_sym);
12611 break;
12612 default:
12613 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12614 }
12615 }
12616
12617 /* Return the condition that will be used to match the current exception
12618 being raised with the exception that the user wants to catch. This
12619 assumes that this condition is used when the inferior just triggered
12620 an exception catchpoint.
12621 EX: the type of catchpoints used for catching Ada exceptions. */
12622
12623 static std::string
12624 ada_exception_catchpoint_cond_string (const char *excep_string,
12625 enum ada_exception_catchpoint_kind ex)
12626 {
12627 bool is_standard_exc = false;
12628 std::string result;
12629
12630 if (ex == ada_catch_handlers)
12631 {
12632 /* For exception handlers catchpoints, the condition string does
12633 not use the same parameter as for the other exceptions. */
12634 result = ("long_integer (GNAT_GCC_exception_Access"
12635 "(gcc_exception).all.occurrence.id)");
12636 }
12637 else
12638 result = "long_integer (e)";
12639
12640 /* The standard exceptions are a special case. They are defined in
12641 runtime units that have been compiled without debugging info; if
12642 EXCEP_STRING is the not-fully-qualified name of a standard
12643 exception (e.g. "constraint_error") then, during the evaluation
12644 of the condition expression, the symbol lookup on this name would
12645 *not* return this standard exception. The catchpoint condition
12646 may then be set only on user-defined exceptions which have the
12647 same not-fully-qualified name (e.g. my_package.constraint_error).
12648
12649 To avoid this unexcepted behavior, these standard exceptions are
12650 systematically prefixed by "standard". This means that "catch
12651 exception constraint_error" is rewritten into "catch exception
12652 standard.constraint_error".
12653
12654 If an exception named constraint_error is defined in another package of
12655 the inferior program, then the only way to specify this exception as a
12656 breakpoint condition is to use its fully-qualified named:
12657 e.g. my_package.constraint_error. */
12658
12659 for (const char *name : standard_exc)
12660 {
12661 if (strcmp (name, excep_string) == 0)
12662 {
12663 is_standard_exc = true;
12664 break;
12665 }
12666 }
12667
12668 result += " = ";
12669
12670 if (is_standard_exc)
12671 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12672 else
12673 string_appendf (result, "long_integer (&%s)", excep_string);
12674
12675 return result;
12676 }
12677
12678 /* Return the symtab_and_line that should be used to insert an
12679 exception catchpoint of the TYPE kind. */
12680
12681 static struct symtab_and_line
12682 ada_exception_sal (enum ada_exception_catchpoint_kind ex)
12683 {
12684 const char *sym_name;
12685 struct symbol *sym;
12686
12687 /* First, find out which exception support info to use. */
12688 ada_exception_support_info_sniffer ();
12689
12690 /* Then lookup the function on which we will break in order to catch
12691 the Ada exceptions requested by the user. */
12692 sym_name = ada_exception_sym_name (ex);
12693 sym = standard_lookup (sym_name, NULL, SEARCH_VFT);
12694
12695 if (sym == NULL)
12696 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12697 sym_name);
12698
12699 if (sym->aclass () != LOC_BLOCK)
12700 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12701
12702 return find_function_start_sal (sym, 1);
12703 }
12704
12705 /* Create an Ada exception catchpoint.
12706
12707 EX_KIND is the kind of exception catchpoint to be created.
12708
12709 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12710 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12711 of the exception to which this catchpoint applies.
12712
12713 COND_STRING, if not empty, is the catchpoint condition.
12714
12715 TEMPFLAG, if nonzero, means that the underlying breakpoint
12716 should be temporary.
12717
12718 FROM_TTY is the usual argument passed to all commands implementations. */
12719
12720 void
12721 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12722 enum ada_exception_catchpoint_kind ex_kind,
12723 std::string &&excep_string,
12724 const std::string &cond_string,
12725 int tempflag,
12726 int enabled,
12727 int from_tty)
12728 {
12729 std::unique_ptr<ada_catchpoint> c
12730 (new ada_catchpoint (gdbarch, ex_kind,
12731 cond_string.empty () ? nullptr : cond_string.c_str (),
12732 tempflag, enabled, from_tty,
12733 std::move (excep_string)));
12734 install_breakpoint (0, std::move (c), 1);
12735 }
12736
12737 /* Implement the "catch exception" command. */
12738
12739 static void
12740 catch_ada_exception_command (const char *arg_entry, int from_tty,
12741 struct cmd_list_element *command)
12742 {
12743 const char *arg = arg_entry;
12744 struct gdbarch *gdbarch = get_current_arch ();
12745 int tempflag;
12746 enum ada_exception_catchpoint_kind ex_kind;
12747 std::string excep_string;
12748 std::string cond_string;
12749
12750 tempflag = command->context () == CATCH_TEMPORARY;
12751
12752 if (!arg)
12753 arg = "";
12754 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12755 &cond_string);
12756 create_ada_exception_catchpoint (gdbarch, ex_kind,
12757 std::move (excep_string), cond_string,
12758 tempflag, 1 /* enabled */,
12759 from_tty);
12760 }
12761
12762 /* Implement the "catch handlers" command. */
12763
12764 static void
12765 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12766 struct cmd_list_element *command)
12767 {
12768 const char *arg = arg_entry;
12769 struct gdbarch *gdbarch = get_current_arch ();
12770 int tempflag;
12771 enum ada_exception_catchpoint_kind ex_kind;
12772 std::string excep_string;
12773 std::string cond_string;
12774
12775 tempflag = command->context () == CATCH_TEMPORARY;
12776
12777 if (!arg)
12778 arg = "";
12779 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12780 &cond_string);
12781 create_ada_exception_catchpoint (gdbarch, ex_kind,
12782 std::move (excep_string), cond_string,
12783 tempflag, 1 /* enabled */,
12784 from_tty);
12785 }
12786
12787 /* Completion function for the Ada "catch" commands. */
12788
12789 static void
12790 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12791 const char *text, const char *word)
12792 {
12793 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12794
12795 for (const ada_exc_info &info : exceptions)
12796 {
12797 if (startswith (info.name, word))
12798 tracker.add_completion (make_unique_xstrdup (info.name));
12799 }
12800 }
12801
12802 /* Split the arguments specified in a "catch assert" command.
12803
12804 ARGS contains the command's arguments (or the empty string if
12805 no arguments were passed).
12806
12807 If ARGS contains a condition, set COND_STRING to that condition
12808 (the memory needs to be deallocated after use). */
12809
12810 static void
12811 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12812 {
12813 args = skip_spaces (args);
12814
12815 /* Check whether a condition was provided. */
12816 if (startswith (args, "if")
12817 && (isspace (args[2]) || args[2] == '\0'))
12818 {
12819 args += 2;
12820 args = skip_spaces (args);
12821 if (args[0] == '\0')
12822 error (_("condition missing after `if' keyword"));
12823 cond_string.assign (args);
12824 }
12825
12826 /* Otherwise, there should be no other argument at the end of
12827 the command. */
12828 else if (args[0] != '\0')
12829 error (_("Junk at end of arguments."));
12830 }
12831
12832 /* Implement the "catch assert" command. */
12833
12834 static void
12835 catch_assert_command (const char *arg_entry, int from_tty,
12836 struct cmd_list_element *command)
12837 {
12838 const char *arg = arg_entry;
12839 struct gdbarch *gdbarch = get_current_arch ();
12840 int tempflag;
12841 std::string cond_string;
12842
12843 tempflag = command->context () == CATCH_TEMPORARY;
12844
12845 if (!arg)
12846 arg = "";
12847 catch_ada_assert_command_split (arg, cond_string);
12848 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12849 {}, cond_string,
12850 tempflag, 1 /* enabled */,
12851 from_tty);
12852 }
12853
12854 /* Return non-zero if the symbol SYM is an Ada exception object. */
12855
12856 static int
12857 ada_is_exception_sym (struct symbol *sym)
12858 {
12859 const char *type_name = sym->type ()->name ();
12860
12861 return (sym->aclass () != LOC_TYPEDEF
12862 && sym->aclass () != LOC_BLOCK
12863 && sym->aclass () != LOC_CONST
12864 && sym->aclass () != LOC_UNRESOLVED
12865 && type_name != NULL && strcmp (type_name, "exception") == 0);
12866 }
12867
12868 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12869 Ada exception object. This matches all exceptions except the ones
12870 defined by the Ada language. */
12871
12872 static int
12873 ada_is_non_standard_exception_sym (struct symbol *sym)
12874 {
12875 if (!ada_is_exception_sym (sym))
12876 return 0;
12877
12878 for (const char *name : standard_exc)
12879 if (strcmp (sym->linkage_name (), name) == 0)
12880 return 0; /* A standard exception. */
12881
12882 /* Numeric_Error is also a standard exception, so exclude it.
12883 See the STANDARD_EXC description for more details as to why
12884 this exception is not listed in that array. */
12885 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12886 return 0;
12887
12888 return 1;
12889 }
12890
12891 /* A helper function for std::sort, comparing two struct ada_exc_info
12892 objects.
12893
12894 The comparison is determined first by exception name, and then
12895 by exception address. */
12896
12897 bool
12898 ada_exc_info::operator< (const ada_exc_info &other) const
12899 {
12900 int result;
12901
12902 result = strcmp (name, other.name);
12903 if (result < 0)
12904 return true;
12905 if (result == 0 && addr < other.addr)
12906 return true;
12907 return false;
12908 }
12909
12910 bool
12911 ada_exc_info::operator== (const ada_exc_info &other) const
12912 {
12913 return addr == other.addr && strcmp (name, other.name) == 0;
12914 }
12915
12916 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12917 routine, but keeping the first SKIP elements untouched.
12918
12919 All duplicates are also removed. */
12920
12921 static void
12922 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12923 int skip)
12924 {
12925 std::sort (exceptions->begin () + skip, exceptions->end ());
12926 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12927 exceptions->end ());
12928 }
12929
12930 /* Add all exceptions defined by the Ada standard whose name match
12931 a regular expression.
12932
12933 If PREG is not NULL, then this regexp_t object is used to
12934 perform the symbol name matching. Otherwise, no name-based
12935 filtering is performed.
12936
12937 EXCEPTIONS is a vector of exceptions to which matching exceptions
12938 gets pushed. */
12939
12940 static void
12941 ada_add_standard_exceptions (compiled_regex *preg,
12942 std::vector<ada_exc_info> *exceptions)
12943 {
12944 for (const char *name : standard_exc)
12945 {
12946 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12947 {
12948 symbol_name_match_type match_type = name_match_type_from_name (name);
12949 lookup_name_info lookup_name (name, match_type);
12950
12951 symbol_name_matcher_ftype *match_name
12952 = ada_get_symbol_name_matcher (lookup_name);
12953
12954 /* Iterate over all objfiles irrespective of scope or linker
12955 namespaces so we get all exceptions anywhere in the
12956 progspace. */
12957 for (objfile *objfile : current_program_space->objfiles ())
12958 {
12959 for (minimal_symbol *msymbol : objfile->msymbols ())
12960 {
12961 if (match_name (msymbol->linkage_name (), lookup_name,
12962 nullptr)
12963 && msymbol->type () != mst_solib_trampoline)
12964 {
12965 ada_exc_info info
12966 = {name, msymbol->value_address (objfile)};
12967
12968 exceptions->push_back (info);
12969 }
12970 }
12971 }
12972 }
12973 }
12974 }
12975
12976 /* Add all Ada exceptions defined locally and accessible from the given
12977 FRAME.
12978
12979 If PREG is not NULL, then this regexp_t object is used to
12980 perform the symbol name matching. Otherwise, no name-based
12981 filtering is performed.
12982
12983 EXCEPTIONS is a vector of exceptions to which matching exceptions
12984 gets pushed. */
12985
12986 static void
12987 ada_add_exceptions_from_frame (compiled_regex *preg,
12988 const frame_info_ptr &frame,
12989 std::vector<ada_exc_info> *exceptions)
12990 {
12991 const struct block *block = get_frame_block (frame, 0);
12992
12993 while (block != 0)
12994 {
12995 for (struct symbol *sym : block_iterator_range (block))
12996 {
12997 switch (sym->aclass ())
12998 {
12999 case LOC_TYPEDEF:
13000 case LOC_BLOCK:
13001 case LOC_CONST:
13002 break;
13003 default:
13004 if (ada_is_exception_sym (sym))
13005 {
13006 struct ada_exc_info info = {sym->print_name (),
13007 sym->value_address ()};
13008
13009 exceptions->push_back (info);
13010 }
13011 }
13012 }
13013 if (block->function () != NULL)
13014 break;
13015 block = block->superblock ();
13016 }
13017 }
13018
13019 /* Return true if NAME matches PREG or if PREG is NULL. */
13020
13021 static bool
13022 name_matches_regex (const char *name, compiled_regex *preg)
13023 {
13024 return (preg == NULL
13025 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13026 }
13027
13028 /* Add all exceptions defined globally whose name name match
13029 a regular expression, excluding standard exceptions.
13030
13031 The reason we exclude standard exceptions is that they need
13032 to be handled separately: Standard exceptions are defined inside
13033 a runtime unit which is normally not compiled with debugging info,
13034 and thus usually do not show up in our symbol search. However,
13035 if the unit was in fact built with debugging info, we need to
13036 exclude them because they would duplicate the entry we found
13037 during the special loop that specifically searches for those
13038 standard exceptions.
13039
13040 If PREG is not NULL, then this regexp_t object is used to
13041 perform the symbol name matching. Otherwise, no name-based
13042 filtering is performed.
13043
13044 EXCEPTIONS is a vector of exceptions to which matching exceptions
13045 gets pushed. */
13046
13047 static void
13048 ada_add_global_exceptions (compiled_regex *preg,
13049 std::vector<ada_exc_info> *exceptions)
13050 {
13051 /* In Ada, the symbol "search name" is a linkage name, whereas the
13052 regular expression used to do the matching refers to the natural
13053 name. So match against the decoded name. */
13054 expand_symtabs_matching (NULL,
13055 lookup_name_info::match_any (),
13056 [&] (const char *search_name)
13057 {
13058 std::string decoded = ada_decode (search_name);
13059 return name_matches_regex (decoded.c_str (), preg);
13060 },
13061 NULL,
13062 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13063 SEARCH_VAR_DOMAIN);
13064
13065 /* Iterate over all objfiles irrespective of scope or linker namespaces
13066 so we get all exceptions anywhere in the progspace. */
13067 for (objfile *objfile : current_program_space->objfiles ())
13068 {
13069 for (compunit_symtab *s : objfile->compunits ())
13070 {
13071 const struct blockvector *bv = s->blockvector ();
13072 int i;
13073
13074 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13075 {
13076 const struct block *b = bv->block (i);
13077
13078 for (struct symbol *sym : block_iterator_range (b))
13079 if (ada_is_non_standard_exception_sym (sym)
13080 && name_matches_regex (sym->natural_name (), preg))
13081 {
13082 struct ada_exc_info info
13083 = {sym->print_name (), sym->value_address ()};
13084
13085 exceptions->push_back (info);
13086 }
13087 }
13088 }
13089 }
13090 }
13091
13092 /* Implements ada_exceptions_list with the regular expression passed
13093 as a regex_t, rather than a string.
13094
13095 If not NULL, PREG is used to filter out exceptions whose names
13096 do not match. Otherwise, all exceptions are listed. */
13097
13098 static std::vector<ada_exc_info>
13099 ada_exceptions_list_1 (compiled_regex *preg)
13100 {
13101 std::vector<ada_exc_info> result;
13102 int prev_len;
13103
13104 /* First, list the known standard exceptions. These exceptions
13105 need to be handled separately, as they are usually defined in
13106 runtime units that have been compiled without debugging info. */
13107
13108 ada_add_standard_exceptions (preg, &result);
13109
13110 /* Next, find all exceptions whose scope is local and accessible
13111 from the currently selected frame. */
13112
13113 if (has_stack_frames ())
13114 {
13115 prev_len = result.size ();
13116 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13117 &result);
13118 if (result.size () > prev_len)
13119 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13120 }
13121
13122 /* Add all exceptions whose scope is global. */
13123
13124 prev_len = result.size ();
13125 ada_add_global_exceptions (preg, &result);
13126 if (result.size () > prev_len)
13127 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13128
13129 return result;
13130 }
13131
13132 /* Return a vector of ada_exc_info.
13133
13134 If REGEXP is NULL, all exceptions are included in the result.
13135 Otherwise, it should contain a valid regular expression,
13136 and only the exceptions whose names match that regular expression
13137 are included in the result.
13138
13139 The exceptions are sorted in the following order:
13140 - Standard exceptions (defined by the Ada language), in
13141 alphabetical order;
13142 - Exceptions only visible from the current frame, in
13143 alphabetical order;
13144 - Exceptions whose scope is global, in alphabetical order. */
13145
13146 std::vector<ada_exc_info>
13147 ada_exceptions_list (const char *regexp)
13148 {
13149 if (regexp == NULL)
13150 return ada_exceptions_list_1 (NULL);
13151
13152 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13153 return ada_exceptions_list_1 (&reg);
13154 }
13155
13156 /* Implement the "info exceptions" command. */
13157
13158 static void
13159 info_exceptions_command (const char *regexp, int from_tty)
13160 {
13161 struct gdbarch *gdbarch = get_current_arch ();
13162
13163 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13164
13165 if (regexp != NULL)
13166 gdb_printf
13167 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13168 else
13169 gdb_printf (_("All defined Ada exceptions:\n"));
13170
13171 for (const ada_exc_info &info : exceptions)
13172 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13173 }
13174
13175 \f
13176 /* Language vector */
13177
13178 /* symbol_name_matcher_ftype adapter for wild_match. */
13179
13180 static bool
13181 do_wild_match (const char *symbol_search_name,
13182 const lookup_name_info &lookup_name,
13183 completion_match_result *comp_match_res)
13184 {
13185 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13186 }
13187
13188 /* symbol_name_matcher_ftype adapter for full_match. */
13189
13190 static bool
13191 do_full_match (const char *symbol_search_name,
13192 const lookup_name_info &lookup_name,
13193 completion_match_result *comp_match_res)
13194 {
13195 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13196
13197 /* If both symbols start with "_ada_", just let the loop below
13198 handle the comparison. However, if only the symbol name starts
13199 with "_ada_", skip the prefix and let the match proceed as
13200 usual. */
13201 if (startswith (symbol_search_name, "_ada_")
13202 && !startswith (lname, "_ada"))
13203 symbol_search_name += 5;
13204 /* Likewise for ghost entities. */
13205 if (startswith (symbol_search_name, "___ghost_")
13206 && !startswith (lname, "___ghost_"))
13207 symbol_search_name += 9;
13208
13209 int uscore_count = 0;
13210 while (*lname != '\0')
13211 {
13212 if (*symbol_search_name != *lname)
13213 {
13214 if (*symbol_search_name == 'B' && uscore_count == 2
13215 && symbol_search_name[1] == '_')
13216 {
13217 symbol_search_name += 2;
13218 while (isdigit (*symbol_search_name))
13219 ++symbol_search_name;
13220 if (symbol_search_name[0] == '_'
13221 && symbol_search_name[1] == '_')
13222 {
13223 symbol_search_name += 2;
13224 continue;
13225 }
13226 }
13227 return false;
13228 }
13229
13230 if (*symbol_search_name == '_')
13231 ++uscore_count;
13232 else
13233 uscore_count = 0;
13234
13235 ++symbol_search_name;
13236 ++lname;
13237 }
13238
13239 return is_name_suffix (symbol_search_name);
13240 }
13241
13242 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13243
13244 static bool
13245 do_exact_match (const char *symbol_search_name,
13246 const lookup_name_info &lookup_name,
13247 completion_match_result *comp_match_res)
13248 {
13249 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13250 }
13251
13252 /* Build the Ada lookup name for LOOKUP_NAME. */
13253
13254 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13255 {
13256 std::string_view user_name = lookup_name.name ();
13257
13258 if (!user_name.empty () && user_name[0] == '<')
13259 {
13260 if (user_name.back () == '>')
13261 m_encoded_name = user_name.substr (1, user_name.size () - 2);
13262 else
13263 m_encoded_name = user_name.substr (1, user_name.size () - 1);
13264 m_encoded_p = true;
13265 m_verbatim_p = true;
13266 m_wild_match_p = false;
13267 m_standard_p = false;
13268 }
13269 else
13270 {
13271 m_verbatim_p = false;
13272
13273 m_encoded_p = user_name.find ("__") != std::string_view::npos;
13274
13275 if (!m_encoded_p)
13276 {
13277 const char *folded = ada_fold_name (user_name);
13278 m_encoded_name = ada_encode_1 (folded, false);
13279 if (m_encoded_name.empty ())
13280 m_encoded_name = user_name;
13281 }
13282 else
13283 m_encoded_name = user_name;
13284
13285 /* Handle the 'package Standard' special case. See description
13286 of m_standard_p. */
13287 if (startswith (m_encoded_name.c_str (), "standard__"))
13288 {
13289 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13290 m_standard_p = true;
13291 }
13292 else
13293 m_standard_p = false;
13294
13295 m_decoded_name = ada_decode (m_encoded_name.c_str (), true, false, false);
13296
13297 /* If the name contains a ".", then the user is entering a fully
13298 qualified entity name, and the match must not be done in wild
13299 mode. Similarly, if the user wants to complete what looks
13300 like an encoded name, the match must not be done in wild
13301 mode. Also, in the standard__ special case always do
13302 non-wild matching. */
13303 m_wild_match_p
13304 = (lookup_name.match_type () != symbol_name_match_type::FULL
13305 && !m_encoded_p
13306 && !m_standard_p
13307 && user_name.find ('.') == std::string::npos);
13308 }
13309 }
13310
13311 /* symbol_name_matcher_ftype method for Ada. This only handles
13312 completion mode. */
13313
13314 static bool
13315 ada_symbol_name_matches (const char *symbol_search_name,
13316 const lookup_name_info &lookup_name,
13317 completion_match_result *comp_match_res)
13318 {
13319 return lookup_name.ada ().matches (symbol_search_name,
13320 lookup_name.match_type (),
13321 comp_match_res);
13322 }
13323
13324 /* A name matcher that matches the symbol name exactly, with
13325 strcmp. */
13326
13327 static bool
13328 literal_symbol_name_matcher (const char *symbol_search_name,
13329 const lookup_name_info &lookup_name,
13330 completion_match_result *comp_match_res)
13331 {
13332 std::string_view name_view = lookup_name.name ();
13333
13334 if (lookup_name.completion_mode ()
13335 ? (strncmp (symbol_search_name, name_view.data (),
13336 name_view.size ()) == 0)
13337 : symbol_search_name == name_view)
13338 {
13339 if (comp_match_res != NULL)
13340 comp_match_res->set_match (symbol_search_name);
13341 return true;
13342 }
13343 else
13344 return false;
13345 }
13346
13347 /* Implement the "get_symbol_name_matcher" language_defn method for
13348 Ada. */
13349
13350 static symbol_name_matcher_ftype *
13351 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13352 {
13353 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13354 return literal_symbol_name_matcher;
13355
13356 if (lookup_name.completion_mode ())
13357 return ada_symbol_name_matches;
13358 else
13359 {
13360 if (lookup_name.ada ().wild_match_p ())
13361 return do_wild_match;
13362 else if (lookup_name.ada ().verbatim_p ())
13363 return do_exact_match;
13364 else
13365 return do_full_match;
13366 }
13367 }
13368
13369 /* Class representing the Ada language. */
13370
13371 class ada_language : public language_defn
13372 {
13373 public:
13374 ada_language ()
13375 : language_defn (language_ada)
13376 { /* Nothing. */ }
13377
13378 /* See language.h. */
13379
13380 const char *name () const override
13381 { return "ada"; }
13382
13383 /* See language.h. */
13384
13385 const char *natural_name () const override
13386 { return "Ada"; }
13387
13388 /* See language.h. */
13389
13390 const std::vector<const char *> &filename_extensions () const override
13391 {
13392 static const std::vector<const char *> extensions
13393 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13394 return extensions;
13395 }
13396
13397 /* Print an array element index using the Ada syntax. */
13398
13399 void print_array_index (struct type *index_type,
13400 LONGEST index,
13401 struct ui_file *stream,
13402 const value_print_options *options) const override
13403 {
13404 struct value *index_value = val_atr (index_type, index);
13405
13406 value_print (index_value, stream, options);
13407 gdb_printf (stream, " => ");
13408 }
13409
13410 /* Implement the "read_var_value" language_defn method for Ada. */
13411
13412 struct value *read_var_value (struct symbol *var,
13413 const struct block *var_block,
13414 const frame_info_ptr &frame) const override
13415 {
13416 /* The only case where default_read_var_value is not sufficient
13417 is when VAR is a renaming... */
13418 if (frame != nullptr)
13419 {
13420 const struct block *frame_block = get_frame_block (frame, NULL);
13421 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13422 return ada_read_renaming_var_value (var, frame_block);
13423 }
13424
13425 /* This is a typical case where we expect the default_read_var_value
13426 function to work. */
13427 return language_defn::read_var_value (var, var_block, frame);
13428 }
13429
13430 /* See language.h. */
13431 bool symbol_printing_suppressed (struct symbol *symbol) const override
13432 {
13433 return symbol->is_artificial ();
13434 }
13435
13436 /* See language.h. */
13437 struct value *value_string (struct gdbarch *gdbarch,
13438 const char *ptr, ssize_t len) const override
13439 {
13440 struct type *type = language_string_char_type (this, gdbarch);
13441 value *val = ::value_string (ptr, len, type);
13442 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13443 strings that are arrays of characters, so fix the type now. */
13444 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13445 val->type ()->set_code (TYPE_CODE_ARRAY);
13446 return val;
13447 }
13448
13449 /* See language.h. */
13450 void language_arch_info (struct gdbarch *gdbarch,
13451 struct language_arch_info *lai) const override
13452 {
13453 const struct builtin_type *builtin = builtin_type (gdbarch);
13454
13455 /* Helper function to allow shorter lines below. */
13456 auto add = [&] (struct type *t)
13457 {
13458 lai->add_primitive_type (t);
13459 };
13460
13461 type_allocator alloc (gdbarch);
13462 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13463 0, "integer"));
13464 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13465 0, "long_integer"));
13466 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13467 0, "short_integer"));
13468 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13469 1, "character");
13470 lai->set_string_char_type (char_type);
13471 add (char_type);
13472 add (init_character_type (alloc, 16, 1, "wide_character"));
13473 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13474 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13475 "float", gdbarch_float_format (gdbarch)));
13476 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13477 "long_float", gdbarch_double_format (gdbarch)));
13478 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13479 0, "long_long_integer"));
13480 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13481 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
13482 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13483 "long_long_float",
13484 gdbarch_long_double_format (gdbarch)));
13485 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13486 0, "natural"));
13487 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13488 0, "positive"));
13489 add (builtin->builtin_void);
13490
13491 struct type *system_addr_ptr
13492 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13493 "void"));
13494 system_addr_ptr->set_name ("system__address");
13495 add (system_addr_ptr);
13496
13497 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13498 type. This is a signed integral type whose size is the same as
13499 the size of addresses. */
13500 unsigned int addr_length = system_addr_ptr->length ();
13501 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13502 "storage_offset"));
13503
13504 lai->set_bool_type (builtin->builtin_bool);
13505 }
13506
13507 /* See language.h. */
13508
13509 bool iterate_over_symbols
13510 (const struct block *block, const lookup_name_info &name,
13511 domain_search_flags domain,
13512 gdb::function_view<symbol_found_callback_ftype> callback) const override
13513 {
13514 std::vector<struct block_symbol> results
13515 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13516 for (block_symbol &sym : results)
13517 {
13518 if (!callback (&sym))
13519 return false;
13520 }
13521
13522 return true;
13523 }
13524
13525 /* See language.h. */
13526 bool sniff_from_mangled_name
13527 (const char *mangled,
13528 gdb::unique_xmalloc_ptr<char> *out) const override
13529 {
13530 std::string demangled = ada_decode (mangled);
13531
13532 *out = NULL;
13533
13534 if (demangled != mangled && demangled[0] != '<')
13535 {
13536 /* Set the gsymbol language to Ada, but still return 0.
13537 Two reasons for that:
13538
13539 1. For Ada, we prefer computing the symbol's decoded name
13540 on the fly rather than pre-compute it, in order to save
13541 memory (Ada projects are typically very large).
13542
13543 2. There are some areas in the definition of the GNAT
13544 encoding where, with a bit of bad luck, we might be able
13545 to decode a non-Ada symbol, generating an incorrect
13546 demangled name (Eg: names ending with "TB" for instance
13547 are identified as task bodies and so stripped from
13548 the decoded name returned).
13549
13550 Returning true, here, but not setting *DEMANGLED, helps us get
13551 a little bit of the best of both worlds. Because we're last,
13552 we should not affect any of the other languages that were
13553 able to demangle the symbol before us; we get to correctly
13554 tag Ada symbols as such; and even if we incorrectly tagged a
13555 non-Ada symbol, which should be rare, any routing through the
13556 Ada language should be transparent (Ada tries to behave much
13557 like C/C++ with non-Ada symbols). */
13558 return true;
13559 }
13560
13561 return false;
13562 }
13563
13564 /* See language.h. */
13565
13566 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13567 int options) const override
13568 {
13569 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13570 }
13571
13572 /* See language.h. */
13573
13574 void print_type (struct type *type, const char *varstring,
13575 struct ui_file *stream, int show, int level,
13576 const struct type_print_options *flags) const override
13577 {
13578 ada_print_type (type, varstring, stream, show, level, flags);
13579 }
13580
13581 /* See language.h. */
13582
13583 const char *word_break_characters (void) const override
13584 {
13585 return ada_completer_word_break_characters;
13586 }
13587
13588 /* See language.h. */
13589
13590 void collect_symbol_completion_matches (completion_tracker &tracker,
13591 complete_symbol_mode mode,
13592 symbol_name_match_type name_match_type,
13593 const char *text, const char *word,
13594 enum type_code code) const override
13595 {
13596 const struct block *b, *surrounding_static_block = 0;
13597
13598 gdb_assert (code == TYPE_CODE_UNDEF);
13599
13600 lookup_name_info lookup_name (text, name_match_type, true);
13601
13602 /* First, look at the partial symtab symbols. */
13603 expand_symtabs_matching (NULL,
13604 lookup_name,
13605 NULL,
13606 NULL,
13607 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13608 SEARCH_ALL_DOMAINS);
13609
13610 /* At this point scan through the misc symbol vectors and add each
13611 symbol you find to the list. Eventually we want to ignore
13612 anything that isn't a text symbol (everything else will be
13613 handled by the psymtab code above). */
13614
13615 for (objfile *objfile : current_program_space->objfiles ())
13616 {
13617 for (minimal_symbol *msymbol : objfile->msymbols ())
13618 {
13619 QUIT;
13620
13621 if (completion_skip_symbol (mode, msymbol))
13622 continue;
13623
13624 language symbol_language = msymbol->language ();
13625
13626 /* Ada minimal symbols won't have their language set to Ada. If
13627 we let completion_list_add_name compare using the
13628 default/C-like matcher, then when completing e.g., symbols in a
13629 package named "pck", we'd match internal Ada symbols like
13630 "pckS", which are invalid in an Ada expression, unless you wrap
13631 them in '<' '>' to request a verbatim match.
13632
13633 Unfortunately, some Ada encoded names successfully demangle as
13634 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13635 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13636 with the wrong language set. Paper over that issue here. */
13637 if (symbol_language == language_unknown
13638 || symbol_language == language_cplus)
13639 symbol_language = language_ada;
13640
13641 completion_list_add_name (tracker,
13642 symbol_language,
13643 msymbol->linkage_name (),
13644 lookup_name, text, word);
13645 }
13646 }
13647
13648 /* Search upwards from currently selected frame (so that we can
13649 complete on local vars. */
13650
13651 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13652 {
13653 if (!b->superblock ())
13654 surrounding_static_block = b; /* For elmin of dups */
13655
13656 for (struct symbol *sym : block_iterator_range (b))
13657 {
13658 if (completion_skip_symbol (mode, sym))
13659 continue;
13660
13661 completion_list_add_name (tracker,
13662 sym->language (),
13663 sym->linkage_name (),
13664 lookup_name, text, word);
13665 }
13666 }
13667
13668 /* Go through the symtabs and check the externs and statics for
13669 symbols which match. */
13670
13671 for (objfile *objfile : current_program_space->objfiles ())
13672 {
13673 for (compunit_symtab *s : objfile->compunits ())
13674 {
13675 QUIT;
13676 b = s->blockvector ()->global_block ();
13677 for (struct symbol *sym : block_iterator_range (b))
13678 {
13679 if (completion_skip_symbol (mode, sym))
13680 continue;
13681
13682 completion_list_add_name (tracker,
13683 sym->language (),
13684 sym->linkage_name (),
13685 lookup_name, text, word);
13686 }
13687 }
13688 }
13689
13690 for (objfile *objfile : current_program_space->objfiles ())
13691 {
13692 for (compunit_symtab *s : objfile->compunits ())
13693 {
13694 QUIT;
13695 b = s->blockvector ()->static_block ();
13696 /* Don't do this block twice. */
13697 if (b == surrounding_static_block)
13698 continue;
13699 for (struct symbol *sym : block_iterator_range (b))
13700 {
13701 if (completion_skip_symbol (mode, sym))
13702 continue;
13703
13704 completion_list_add_name (tracker,
13705 sym->language (),
13706 sym->linkage_name (),
13707 lookup_name, text, word);
13708 }
13709 }
13710 }
13711 }
13712
13713 /* See language.h. */
13714
13715 gdb::unique_xmalloc_ptr<char> watch_location_expression
13716 (struct type *type, CORE_ADDR addr) const override
13717 {
13718 type = check_typedef (check_typedef (type)->target_type ());
13719 std::string name = type_to_string (type);
13720 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13721 }
13722
13723 /* See language.h. */
13724
13725 void value_print (struct value *val, struct ui_file *stream,
13726 const struct value_print_options *options) const override
13727 {
13728 return ada_value_print (val, stream, options);
13729 }
13730
13731 /* See language.h. */
13732
13733 void value_print_inner
13734 (struct value *val, struct ui_file *stream, int recurse,
13735 const struct value_print_options *options) const override
13736 {
13737 return ada_value_print_inner (val, stream, recurse, options);
13738 }
13739
13740 /* See language.h. */
13741
13742 struct block_symbol lookup_symbol_nonlocal
13743 (const char *name, const struct block *block,
13744 const domain_search_flags domain) const override
13745 {
13746 struct block_symbol sym;
13747
13748 sym = ada_lookup_symbol (name,
13749 (block == nullptr
13750 ? nullptr
13751 : block->static_block ()),
13752 domain);
13753 if (sym.symbol != NULL)
13754 return sym;
13755
13756 /* If we haven't found a match at this point, try the primitive
13757 types. In other languages, this search is performed before
13758 searching for global symbols in order to short-circuit that
13759 global-symbol search if it happens that the name corresponds
13760 to a primitive type. But we cannot do the same in Ada, because
13761 it is perfectly legitimate for a program to declare a type which
13762 has the same name as a standard type. If looking up a type in
13763 that situation, we have traditionally ignored the primitive type
13764 in favor of user-defined types. This is why, unlike most other
13765 languages, we search the primitive types this late and only after
13766 having searched the global symbols without success. */
13767
13768 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
13769 {
13770 struct gdbarch *gdbarch;
13771
13772 if (block == NULL)
13773 gdbarch = current_inferior ()->arch ();
13774 else
13775 gdbarch = block->gdbarch ();
13776 sym.symbol
13777 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13778 if (sym.symbol != NULL)
13779 return sym;
13780 }
13781
13782 return {};
13783 }
13784
13785 /* See language.h. */
13786
13787 int parser (struct parser_state *ps) const override
13788 {
13789 warnings_issued = 0;
13790 return ada_parse (ps);
13791 }
13792
13793 /* See language.h. */
13794
13795 void emitchar (int ch, struct type *chtype,
13796 struct ui_file *stream, int quoter) const override
13797 {
13798 ada_emit_char (ch, chtype, stream, quoter, 1);
13799 }
13800
13801 /* See language.h. */
13802
13803 void printchar (int ch, struct type *chtype,
13804 struct ui_file *stream) const override
13805 {
13806 ada_printchar (ch, chtype, stream);
13807 }
13808
13809 /* See language.h. */
13810
13811 void printstr (struct ui_file *stream, struct type *elttype,
13812 const gdb_byte *string, unsigned int length,
13813 const char *encoding, int force_ellipses,
13814 const struct value_print_options *options) const override
13815 {
13816 ada_printstr (stream, elttype, string, length, encoding,
13817 force_ellipses, options);
13818 }
13819
13820 /* See language.h. */
13821
13822 void print_typedef (struct type *type, struct symbol *new_symbol,
13823 struct ui_file *stream) const override
13824 {
13825 ada_print_typedef (type, new_symbol, stream);
13826 }
13827
13828 /* See language.h. */
13829
13830 bool is_string_type_p (struct type *type) const override
13831 {
13832 return ada_is_string_type (type);
13833 }
13834
13835 /* See language.h. */
13836
13837 bool is_array_like (struct type *type) const override
13838 {
13839 return (ada_is_constrained_packed_array_type (type)
13840 || ada_is_array_descriptor_type (type));
13841 }
13842
13843 /* See language.h. */
13844
13845 struct value *to_array (struct value *val) const override
13846 { return ada_coerce_to_simple_array (val); }
13847
13848 /* See language.h. */
13849
13850 const char *struct_too_deep_ellipsis () const override
13851 { return "(...)"; }
13852
13853 /* See language.h. */
13854
13855 bool c_style_arrays_p () const override
13856 { return false; }
13857
13858 /* See language.h. */
13859
13860 bool store_sym_names_in_linkage_form_p () const override
13861 { return true; }
13862
13863 /* See language.h. */
13864
13865 const struct lang_varobj_ops *varobj_ops () const override
13866 { return &ada_varobj_ops; }
13867
13868 protected:
13869 /* See language.h. */
13870
13871 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13872 (const lookup_name_info &lookup_name) const override
13873 {
13874 return ada_get_symbol_name_matcher (lookup_name);
13875 }
13876 };
13877
13878 /* Single instance of the Ada language class. */
13879
13880 static ada_language ada_language_defn;
13881
13882 /* Command-list for the "set/show ada" prefix command. */
13883 static struct cmd_list_element *set_ada_list;
13884 static struct cmd_list_element *show_ada_list;
13885
13886 /* This module's 'new_objfile' observer. */
13887
13888 static void
13889 ada_new_objfile_observer (struct objfile *objfile)
13890 {
13891 ada_clear_symbol_cache (objfile->pspace);
13892 }
13893
13894 /* This module's 'free_objfile' observer. */
13895
13896 static void
13897 ada_free_objfile_observer (struct objfile *objfile)
13898 {
13899 ada_clear_symbol_cache (objfile->pspace);
13900 }
13901
13902 /* Charsets known to GNAT. */
13903 static const char * const gnat_source_charsets[] =
13904 {
13905 /* Note that code below assumes that the default comes first.
13906 Latin-1 is the default here, because that is also GNAT's
13907 default. */
13908 "ISO-8859-1",
13909 "ISO-8859-2",
13910 "ISO-8859-3",
13911 "ISO-8859-4",
13912 "ISO-8859-5",
13913 "ISO-8859-15",
13914 "CP437",
13915 "CP850",
13916 /* Note that this value is special-cased in the encoder and
13917 decoder. */
13918 ada_utf8,
13919 nullptr
13920 };
13921
13922 void _initialize_ada_language ();
13923 void
13924 _initialize_ada_language ()
13925 {
13926 add_setshow_prefix_cmd
13927 ("ada", no_class,
13928 _("Prefix command for changing Ada-specific settings."),
13929 _("Generic command for showing Ada-specific settings."),
13930 &set_ada_list, &show_ada_list,
13931 &setlist, &showlist);
13932
13933 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13934 &trust_pad_over_xvs, _("\
13935 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13936 Show whether an optimization trusting PAD types over XVS types is activated."),
13937 _("\
13938 This is related to the encoding used by the GNAT compiler. The debugger\n\
13939 should normally trust the contents of PAD types, but certain older versions\n\
13940 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13941 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13942 work around this bug. It is always safe to turn this option \"off\", but\n\
13943 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13944 this option to \"off\" unless necessary."),
13945 NULL, NULL, &set_ada_list, &show_ada_list);
13946
13947 add_setshow_boolean_cmd ("print-signatures", class_vars,
13948 &print_signatures, _("\
13949 Enable or disable the output of formal and return types for functions in the \
13950 overloads selection menu."), _("\
13951 Show whether the output of formal and return types for functions in the \
13952 overloads selection menu is activated."),
13953 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13954
13955 ada_source_charset = gnat_source_charsets[0];
13956 add_setshow_enum_cmd ("source-charset", class_files,
13957 gnat_source_charsets,
13958 &ada_source_charset, _("\
13959 Set the Ada source character set."), _("\
13960 Show the Ada source character set."), _("\
13961 The character set used for Ada source files.\n\
13962 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13963 nullptr, nullptr,
13964 &set_ada_list, &show_ada_list);
13965
13966 add_catch_command ("exception", _("\
13967 Catch Ada exceptions, when raised.\n\
13968 Usage: catch exception [ARG] [if CONDITION]\n\
13969 Without any argument, stop when any Ada exception is raised.\n\
13970 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13971 being raised does not have a handler (and will therefore lead to the task's\n\
13972 termination).\n\
13973 Otherwise, the catchpoint only stops when the name of the exception being\n\
13974 raised is the same as ARG.\n\
13975 CONDITION is a boolean expression that is evaluated to see whether the\n\
13976 exception should cause a stop."),
13977 catch_ada_exception_command,
13978 catch_ada_completer,
13979 CATCH_PERMANENT,
13980 CATCH_TEMPORARY);
13981
13982 add_catch_command ("handlers", _("\
13983 Catch Ada exceptions, when handled.\n\
13984 Usage: catch handlers [ARG] [if CONDITION]\n\
13985 Without any argument, stop when any Ada exception is handled.\n\
13986 With an argument, catch only exceptions with the given name.\n\
13987 CONDITION is a boolean expression that is evaluated to see whether the\n\
13988 exception should cause a stop."),
13989 catch_ada_handlers_command,
13990 catch_ada_completer,
13991 CATCH_PERMANENT,
13992 CATCH_TEMPORARY);
13993 add_catch_command ("assert", _("\
13994 Catch failed Ada assertions, when raised.\n\
13995 Usage: catch assert [if CONDITION]\n\
13996 CONDITION is a boolean expression that is evaluated to see whether the\n\
13997 exception should cause a stop."),
13998 catch_assert_command,
13999 NULL,
14000 CATCH_PERMANENT,
14001 CATCH_TEMPORARY);
14002
14003 add_info ("exceptions", info_exceptions_command,
14004 _("\
14005 List all Ada exception names.\n\
14006 Usage: info exceptions [REGEXP]\n\
14007 If a regular expression is passed as an argument, only those matching\n\
14008 the regular expression are listed."));
14009
14010 add_setshow_prefix_cmd ("ada", class_maintenance,
14011 _("Set Ada maintenance-related variables."),
14012 _("Show Ada maintenance-related variables."),
14013 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14014 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14015
14016 add_setshow_boolean_cmd
14017 ("ignore-descriptive-types", class_maintenance,
14018 &ada_ignore_descriptive_types_p,
14019 _("Set whether descriptive types generated by GNAT should be ignored."),
14020 _("Show whether descriptive types generated by GNAT should be ignored."),
14021 _("\
14022 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14023 DWARF attribute."),
14024 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14025
14026 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14027 htab_eq_string,
14028 NULL, xcalloc, xfree);
14029
14030 /* The ada-lang observers. */
14031 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14032 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14033 "ada-lang");
14034 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14035 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14036
14037 #ifdef GDB_SELF_TEST
14038 selftests::register_test ("ada-decode", ada_decode_tests);
14039 #endif
14040 }