gdb, testsuite: Fix return value in gdb.base/foll-fork.exp
[binutils-gdb.git] / gdb / ada-lang.c
blob0b430428fb473687fa2750ae3483fef435d4bd14
1 /* Ada language support routines for GDB, the GNU debugger.
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
21 #include <ctype.h>
22 #include "event-top.h"
23 #include "extract-store-integer.h"
24 #include "gdbsupport/gdb_regex.h"
25 #include "frame.h"
26 #include "symtab.h"
27 #include "gdbtypes.h"
28 #include "cli/cli-cmds.h"
29 #include "expression.h"
30 #include "parser-defs.h"
31 #include "language.h"
32 #include "varobj.h"
33 #include "inferior.h"
34 #include "symfile.h"
35 #include "objfiles.h"
36 #include "breakpoint.h"
37 #include "gdbcore.h"
38 #include "hashtab.h"
39 #include "gdbsupport/gdb_obstack.h"
40 #include "ada-lang.h"
41 #include "completer.h"
42 #include "ui-out.h"
43 #include "block.h"
44 #include "infcall.h"
45 #include "annotate.h"
46 #include "valprint.h"
47 #include "source.h"
48 #include "observable.h"
49 #include "stack.h"
50 #include "typeprint.h"
51 #include "namespace.h"
52 #include "cli/cli-style.h"
53 #include "cli/cli-decode.h"
55 #include "value.h"
56 #include "mi/mi-common.h"
57 #include "arch-utils.h"
58 #include "cli/cli-utils.h"
59 #include "gdbsupport/function-view.h"
60 #include "gdbsupport/byte-vector.h"
61 #include "gdbsupport/selftest.h"
62 #include <algorithm>
63 #include "ada-exp.h"
64 #include "charset.h"
65 #include "ax-gdb.h"
67 static struct type *desc_base_type (struct type *);
69 static struct type *desc_bounds_type (struct type *);
71 static struct value *desc_bounds (struct value *);
73 static int fat_pntr_bounds_bitpos (struct type *);
75 static int fat_pntr_bounds_bitsize (struct type *);
77 static struct type *desc_data_target_type (struct type *);
79 static struct value *desc_data (struct value *);
81 static int fat_pntr_data_bitpos (struct type *);
83 static int fat_pntr_data_bitsize (struct type *);
85 static struct value *desc_one_bound (struct value *, int, int);
87 static int desc_bound_bitpos (struct type *, int, int);
89 static int desc_bound_bitsize (struct type *, int, int);
91 static struct type *desc_index_type (struct type *, int);
93 static int desc_arity (struct type *);
95 static int ada_args_match (struct symbol *, struct value **, int);
97 static struct value *make_array_descriptor (struct type *, struct value *);
99 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
100 const struct block *,
101 const lookup_name_info &lookup_name,
102 domain_search_flags, struct objfile *);
104 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
106 const lookup_name_info &lookup_name,
107 domain_search_flags, int, int *);
109 static int is_nonfunction (const std::vector<struct block_symbol> &);
111 static void add_defn_to_vec (std::vector<struct block_symbol> &,
112 struct symbol *,
113 const struct block *);
115 static int possible_user_operator_p (enum exp_opcode, struct value **);
117 static const char *ada_decoded_op_name (enum exp_opcode);
119 static int numeric_type_p (struct type *);
121 static int integer_type_p (struct type *);
123 static int scalar_type_p (struct type *);
125 static int discrete_type_p (struct type *);
127 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
128 int, int);
130 static struct type *ada_find_parallel_type_with_name (struct type *,
131 const char *);
133 static int is_dynamic_field (struct type *, int);
135 static struct type *to_fixed_variant_branch_type (struct type *,
136 const gdb_byte *,
137 CORE_ADDR, struct value *);
139 static struct type *to_fixed_array_type (struct type *, struct value *, int);
141 static struct type *to_fixed_range_type (struct type *, struct value *);
143 static struct type *to_static_fixed_type (struct type *);
144 static struct type *static_unwrap_type (struct type *type);
146 static struct value *unwrap_value (struct value *);
148 static struct type *constrained_packed_array_type (struct type *, long *);
150 static struct type *decode_constrained_packed_array_type (struct type *);
152 static long decode_packed_array_bitsize (struct type *);
154 static struct value *decode_constrained_packed_array (struct value *);
156 static int ada_is_unconstrained_packed_array_type (struct type *);
158 static struct value *value_subscript_packed (struct value *, int,
159 struct value **);
161 static struct value *coerce_unspec_val_to_type (struct value *,
162 struct type *);
164 static int lesseq_defined_than (struct symbol *, struct symbol *);
166 static int equiv_types (struct type *, struct type *);
168 static int is_name_suffix (const char *);
170 static int advance_wild_match (const char **, const char *, char);
172 static bool wild_match (const char *name, const char *patn);
174 static struct value *ada_coerce_ref (struct value *);
176 static LONGEST pos_atr (struct value *);
178 static struct value *val_atr (struct type *, LONGEST);
180 static struct value *ada_search_struct_field (const char *, struct value *, int,
181 struct type *);
183 static int find_struct_field (const char *, struct type *, int,
184 struct type **, int *, int *, int *, int *);
186 static int ada_resolve_function (std::vector<struct block_symbol> &,
187 struct value **, int, const char *,
188 struct type *, bool);
190 static int ada_is_direct_array_type (struct type *);
192 static struct value *ada_index_struct_field (int, struct value *, int,
193 struct type *);
195 static struct type *ada_find_any_type (const char *name);
197 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
198 (const lookup_name_info &lookup_name);
200 static int symbols_are_identical_enums
201 (const std::vector<struct block_symbol> &syms);
203 static int ada_identical_enum_types_p (struct type *type1, struct type *type2);
206 /* The character set used for source files. */
207 static const char *ada_source_charset;
209 /* The string "UTF-8". This is here so we can check for the UTF-8
210 charset using == rather than strcmp. */
211 static const char ada_utf8[] = "UTF-8";
213 /* Each entry in the UTF-32 case-folding table is of this form. */
214 struct utf8_entry
216 /* The start and end, inclusive, of this range of codepoints. */
217 uint32_t start, end;
218 /* The delta to apply to get the upper-case form. 0 if this is
219 already upper-case. */
220 int upper_delta;
221 /* The delta to apply to get the lower-case form. 0 if this is
222 already lower-case. */
223 int lower_delta;
225 bool operator< (uint32_t val) const
227 return end < val;
231 static const utf8_entry ada_case_fold[] =
233 #include "ada-casefold.h"
238 static const char ada_completer_word_break_characters[] =
239 #ifdef VMS
240 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
241 #else
242 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
243 #endif
245 /* The name of the symbol to use to get the name of the main subprogram. */
246 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
247 = "__gnat_ada_main_program_name";
249 /* Limit on the number of warnings to raise per expression evaluation. */
250 static int warning_limit = 2;
252 /* Number of warning messages issued; reset to 0 by cleanups after
253 expression evaluation. */
254 static int warnings_issued = 0;
256 static const char * const known_runtime_file_name_patterns[] = {
257 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
260 static const char * const known_auxiliary_function_name_patterns[] = {
261 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
264 /* Maintenance-related settings for this module. */
266 static struct cmd_list_element *maint_set_ada_cmdlist;
267 static struct cmd_list_element *maint_show_ada_cmdlist;
269 /* The "maintenance ada set/show ignore-descriptive-type" value. */
271 static bool ada_ignore_descriptive_types_p = false;
273 /* Inferior-specific data. */
275 /* Per-inferior data for this module. */
277 struct ada_inferior_data
279 /* The ada__tags__type_specific_data type, which is used when decoding
280 tagged types. With older versions of GNAT, this type was directly
281 accessible through a component ("tsd") in the object tag. But this
282 is no longer the case, so we cache it for each inferior. */
283 struct type *tsd_type = nullptr;
285 /* The exception_support_info data. This data is used to determine
286 how to implement support for Ada exception catchpoints in a given
287 inferior. */
288 const struct exception_support_info *exception_info = nullptr;
291 /* Our key to this module's inferior data. */
292 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
294 /* Return our inferior data for the given inferior (INF).
296 This function always returns a valid pointer to an allocated
297 ada_inferior_data structure. If INF's inferior data has not
298 been previously set, this functions creates a new one with all
299 fields set to zero, sets INF's inferior to it, and then returns
300 a pointer to that newly allocated ada_inferior_data. */
302 static struct ada_inferior_data *
303 get_ada_inferior_data (struct inferior *inf)
305 struct ada_inferior_data *data;
307 data = ada_inferior_data.get (inf);
308 if (data == NULL)
309 data = ada_inferior_data.emplace (inf);
311 return data;
314 /* Perform all necessary cleanups regarding our module's inferior data
315 that is required after the inferior INF just exited. */
317 static void
318 ada_inferior_exit (struct inferior *inf)
320 ada_inferior_data.clear (inf);
324 /* program-space-specific data. */
326 /* The result of a symbol lookup to be stored in our symbol cache. */
328 struct cache_entry
330 /* The name used to perform the lookup. */
331 std::string name;
332 /* The namespace used during the lookup. */
333 domain_search_flags domain = 0;
334 /* The symbol returned by the lookup, or NULL if no matching symbol
335 was found. */
336 struct symbol *sym = nullptr;
337 /* The block where the symbol was found, or NULL if no matching
338 symbol was found. */
339 const struct block *block = nullptr;
342 /* The symbol cache uses this type when searching. */
344 struct cache_entry_search
346 const char *name;
347 domain_search_flags domain;
349 hashval_t hash () const
351 /* This must agree with hash_cache_entry, below. */
352 return htab_hash_string (name);
356 /* Hash function for cache_entry. */
358 static hashval_t
359 hash_cache_entry (const void *v)
361 const cache_entry *entry = (const cache_entry *) v;
362 return htab_hash_string (entry->name.c_str ());
365 /* Equality function for cache_entry. */
367 static int
368 eq_cache_entry (const void *a, const void *b)
370 const cache_entry *entrya = (const cache_entry *) a;
371 const cache_entry_search *entryb = (const cache_entry_search *) b;
373 return entrya->domain == entryb->domain && entrya->name == entryb->name;
376 /* Key to our per-program-space data. */
377 static const registry<program_space>::key<htab, htab_deleter>
378 ada_pspace_data_handle;
380 /* Return this module's data for the given program space (PSPACE).
381 If not is found, add a zero'ed one now.
383 This function always returns a valid object. */
385 static htab_t
386 get_ada_pspace_data (struct program_space *pspace)
388 htab_t data = ada_pspace_data_handle.get (pspace);
389 if (data == nullptr)
391 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
392 htab_delete_entry<cache_entry>,
393 xcalloc, xfree);
394 ada_pspace_data_handle.set (pspace, data);
397 return data;
400 /* Utilities */
402 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
403 all typedef layers have been peeled. Otherwise, return TYPE.
405 Normally, we really expect a typedef type to only have 1 typedef layer.
406 In other words, we really expect the target type of a typedef type to be
407 a non-typedef type. This is particularly true for Ada units, because
408 the language does not have a typedef vs not-typedef distinction.
409 In that respect, the Ada compiler has been trying to eliminate as many
410 typedef definitions in the debugging information, since they generally
411 do not bring any extra information (we still use typedef under certain
412 circumstances related mostly to the GNAT encoding).
414 Unfortunately, we have seen situations where the debugging information
415 generated by the compiler leads to such multiple typedef layers. For
416 instance, consider the following example with stabs:
418 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
419 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
421 This is an error in the debugging information which causes type
422 pck__float_array___XUP to be defined twice, and the second time,
423 it is defined as a typedef of a typedef.
425 This is on the fringe of legality as far as debugging information is
426 concerned, and certainly unexpected. But it is easy to handle these
427 situations correctly, so we can afford to be lenient in this case. */
429 static struct type *
430 ada_typedef_target_type (struct type *type)
432 while (type->code () == TYPE_CODE_TYPEDEF)
433 type = type->target_type ();
434 return type;
437 /* Given DECODED_NAME a string holding a symbol name in its
438 decoded form (ie using the Ada dotted notation), returns
439 its unqualified name. */
441 static const char *
442 ada_unqualified_name (const char *decoded_name)
444 const char *result;
446 /* If the decoded name starts with '<', it means that the encoded
447 name does not follow standard naming conventions, and thus that
448 it is not your typical Ada symbol name. Trying to unqualify it
449 is therefore pointless and possibly erroneous. */
450 if (decoded_name[0] == '<')
451 return decoded_name;
453 result = strrchr (decoded_name, '.');
454 if (result != NULL)
455 result++; /* Skip the dot... */
456 else
457 result = decoded_name;
459 return result;
462 /* Return a string starting with '<', followed by STR, and '>'. */
464 static std::string
465 add_angle_brackets (const char *str)
467 return string_printf ("<%s>", str);
470 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
471 suffix of FIELD_NAME beginning "___". */
473 static int
474 field_name_match (const char *field_name, const char *target)
476 int len = strlen (target);
478 return
479 (strncmp (field_name, target, len) == 0
480 && (field_name[len] == '\0'
481 || (startswith (field_name + len, "___")
482 && strcmp (field_name + strlen (field_name) - 6,
483 "___XVN") != 0)));
487 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
488 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
489 and return its index. This function also handles fields whose name
490 have ___ suffixes because the compiler sometimes alters their name
491 by adding such a suffix to represent fields with certain constraints.
492 If the field could not be found, return a negative number if
493 MAYBE_MISSING is set. Otherwise raise an error. */
496 ada_get_field_index (const struct type *type, const char *field_name,
497 int maybe_missing)
499 int fieldno;
500 struct type *struct_type = check_typedef ((struct type *) type);
502 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
503 if (field_name_match (struct_type->field (fieldno).name (), field_name))
504 return fieldno;
506 if (!maybe_missing)
507 error (_("Unable to find field %s in struct %s. Aborting"),
508 field_name, struct_type->name ());
510 return -1;
513 /* The length of the prefix of NAME prior to any "___" suffix. */
516 ada_name_prefix_len (const char *name)
518 if (name == NULL)
519 return 0;
520 else
522 const char *p = strstr (name, "___");
524 if (p == NULL)
525 return strlen (name);
526 else
527 return p - name;
531 /* Return non-zero if SUFFIX is a suffix of STR.
532 Return zero if STR is null. */
534 static int
535 is_suffix (const char *str, const char *suffix)
537 int len1, len2;
539 if (str == NULL)
540 return 0;
541 len1 = strlen (str);
542 len2 = strlen (suffix);
543 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
546 /* The contents of value VAL, treated as a value of type TYPE. The
547 result is an lval in memory if VAL is. */
549 static struct value *
550 coerce_unspec_val_to_type (struct value *val, struct type *type)
552 type = ada_check_typedef (type);
553 if (val->type () == type)
554 return val;
555 else
557 struct value *result;
559 if (val->optimized_out ())
560 result = value::allocate_optimized_out (type);
561 else if (val->lazy ()
562 /* Be careful not to make a lazy not_lval value. */
563 || (val->lval () != not_lval
564 && type->length () > val->type ()->length ()))
565 result = value::allocate_lazy (type);
566 else
568 result = value::allocate (type);
569 val->contents_copy (result, 0, 0, type->length ());
571 result->set_component_location (val);
572 result->set_bitsize (val->bitsize ());
573 result->set_bitpos (val->bitpos ());
574 if (result->lval () == lval_memory)
575 result->set_address (val->address ());
576 return result;
580 static const gdb_byte *
581 cond_offset_host (const gdb_byte *valaddr, long offset)
583 if (valaddr == NULL)
584 return NULL;
585 else
586 return valaddr + offset;
589 static CORE_ADDR
590 cond_offset_target (CORE_ADDR address, long offset)
592 if (address == 0)
593 return 0;
594 else
595 return address + offset;
598 /* Issue a warning (as for the definition of warning in utils.c, but
599 with exactly one argument rather than ...), unless the limit on the
600 number of warnings has passed during the evaluation of the current
601 expression. */
603 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
604 provided by "complaint". */
605 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
607 static void
608 lim_warning (const char *format, ...)
610 va_list args;
612 va_start (args, format);
613 warnings_issued += 1;
614 if (warnings_issued <= warning_limit)
615 vwarning (format, args);
617 va_end (args);
620 /* Maximum value of a SIZE-byte signed integer type. */
621 static LONGEST
622 max_of_size (int size)
624 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
626 return top_bit | (top_bit - 1);
629 /* Minimum value of a SIZE-byte signed integer type. */
630 static LONGEST
631 min_of_size (int size)
633 return -max_of_size (size) - 1;
636 /* Maximum value of a SIZE-byte unsigned integer type. */
637 static ULONGEST
638 umax_of_size (int size)
640 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
642 return top_bit | (top_bit - 1);
645 /* Maximum value of integral type T, as a signed quantity. */
646 static LONGEST
647 max_of_type (struct type *t)
649 if (t->is_unsigned ())
650 return (LONGEST) umax_of_size (t->length ());
651 else
652 return max_of_size (t->length ());
655 /* Minimum value of integral type T, as a signed quantity. */
656 static LONGEST
657 min_of_type (struct type *t)
659 if (t->is_unsigned ())
660 return 0;
661 else
662 return min_of_size (t->length ());
665 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
666 LONGEST
667 ada_discrete_type_high_bound (struct type *type)
669 type = resolve_dynamic_type (type, {}, 0);
670 switch (type->code ())
672 case TYPE_CODE_RANGE:
674 const dynamic_prop &high = type->bounds ()->high;
676 if (high.is_constant ())
677 return high.const_val ();
678 else
680 gdb_assert (!high.is_available ());
682 /* This happens when trying to evaluate a type's dynamic bound
683 without a live target. There is nothing relevant for us to
684 return here, so return 0. */
685 return 0;
688 case TYPE_CODE_ENUM:
689 return type->field (type->num_fields () - 1).loc_enumval ();
690 case TYPE_CODE_BOOL:
691 return 1;
692 case TYPE_CODE_CHAR:
693 case TYPE_CODE_INT:
694 return max_of_type (type);
695 default:
696 error (_("Unexpected type in ada_discrete_type_high_bound."));
700 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
701 LONGEST
702 ada_discrete_type_low_bound (struct type *type)
704 type = resolve_dynamic_type (type, {}, 0);
705 switch (type->code ())
707 case TYPE_CODE_RANGE:
709 const dynamic_prop &low = type->bounds ()->low;
711 if (low.is_constant ())
712 return low.const_val ();
713 else
715 gdb_assert (!low.is_available ());
717 /* This happens when trying to evaluate a type's dynamic bound
718 without a live target. There is nothing relevant for us to
719 return here, so return 0. */
720 return 0;
723 case TYPE_CODE_ENUM:
724 return type->field (0).loc_enumval ();
725 case TYPE_CODE_BOOL:
726 return 0;
727 case TYPE_CODE_CHAR:
728 case TYPE_CODE_INT:
729 return min_of_type (type);
730 default:
731 error (_("Unexpected type in ada_discrete_type_low_bound."));
735 /* The identity on non-range types. For range types, the underlying
736 non-range scalar type. */
738 static struct type *
739 get_base_type (struct type *type)
741 while (type != NULL && type->code () == TYPE_CODE_RANGE)
743 if (type == type->target_type () || type->target_type () == NULL)
744 return type;
745 type = type->target_type ();
747 return type;
750 /* Return a decoded version of the given VALUE. This means returning
751 a value whose type is obtained by applying all the GNAT-specific
752 encodings, making the resulting type a static but standard description
753 of the initial type. */
755 struct value *
756 ada_get_decoded_value (struct value *value)
758 struct type *type = ada_check_typedef (value->type ());
760 if (ada_is_array_descriptor_type (type)
761 || (ada_is_constrained_packed_array_type (type)
762 && type->code () != TYPE_CODE_PTR))
764 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
765 value = ada_coerce_to_simple_array_ptr (value);
766 else
767 value = ada_coerce_to_simple_array (value);
769 else
770 value = ada_to_fixed_value (value);
772 return value;
775 /* Same as ada_get_decoded_value, but with the given TYPE.
776 Because there is no associated actual value for this type,
777 the resulting type might be a best-effort approximation in
778 the case of dynamic types. */
780 struct type *
781 ada_get_decoded_type (struct type *type)
783 type = to_static_fixed_type (type);
784 if (ada_is_constrained_packed_array_type (type))
785 type = ada_coerce_to_simple_array_type (type);
786 return type;
791 /* Language Selection */
793 /* If the main procedure is written in Ada, then return its name.
794 The result is good until the next call. Return NULL if the main
795 procedure doesn't appear to be in Ada. */
797 const char *
798 ada_main_name ()
800 struct bound_minimal_symbol msym;
801 static gdb::unique_xmalloc_ptr<char> main_program_name;
803 /* For Ada, the name of the main procedure is stored in a specific
804 string constant, generated by the binder. Look for that symbol,
805 extract its address, and then read that string. If we didn't find
806 that string, then most probably the main procedure is not written
807 in Ada. */
808 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
810 if (msym.minsym != NULL)
812 CORE_ADDR main_program_name_addr = msym.value_address ();
813 if (main_program_name_addr == 0)
814 error (_("Invalid address for Ada main program name."));
816 /* Force trust_readonly, because we always want to fetch this
817 string from the executable, not from inferior memory. If the
818 user changes the exec-file and invokes "start", we want to
819 pick the "main" from the new executable, not one that may
820 come from the still-live inferior. */
821 scoped_restore save_trust_readonly
822 = make_scoped_restore (&trust_readonly, true);
823 main_program_name = target_read_string (main_program_name_addr, 1024);
824 return main_program_name.get ();
827 /* The main procedure doesn't seem to be in Ada. */
828 return NULL;
831 /* Symbols */
833 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
834 of NULLs. */
836 const struct ada_opname_map ada_opname_table[] = {
837 {"Oadd", "\"+\"", BINOP_ADD},
838 {"Osubtract", "\"-\"", BINOP_SUB},
839 {"Omultiply", "\"*\"", BINOP_MUL},
840 {"Odivide", "\"/\"", BINOP_DIV},
841 {"Omod", "\"mod\"", BINOP_MOD},
842 {"Orem", "\"rem\"", BINOP_REM},
843 {"Oexpon", "\"**\"", BINOP_EXP},
844 {"Olt", "\"<\"", BINOP_LESS},
845 {"Ole", "\"<=\"", BINOP_LEQ},
846 {"Ogt", "\">\"", BINOP_GTR},
847 {"Oge", "\">=\"", BINOP_GEQ},
848 {"Oeq", "\"=\"", BINOP_EQUAL},
849 {"One", "\"/=\"", BINOP_NOTEQUAL},
850 {"Oand", "\"and\"", BINOP_BITWISE_AND},
851 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
852 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
853 {"Oconcat", "\"&\"", BINOP_CONCAT},
854 {"Oabs", "\"abs\"", UNOP_ABS},
855 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
856 {"Oadd", "\"+\"", UNOP_PLUS},
857 {"Osubtract", "\"-\"", UNOP_NEG},
858 {NULL, NULL}
861 /* If STR is a decoded version of a compiler-provided suffix (like the
862 "[cold]" in "symbol[cold]"), return true. Otherwise, return
863 false. */
865 static bool
866 is_compiler_suffix (const char *str)
868 gdb_assert (*str == '[');
869 ++str;
870 while (*str != '\0' && isalpha (*str))
871 ++str;
872 /* We accept a missing "]" in order to support completion. */
873 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
876 /* Append a non-ASCII character to RESULT. */
877 static void
878 append_hex_encoded (std::string &result, uint32_t one_char)
880 if (one_char <= 0xff)
882 result.append ("U");
883 result.append (phex (one_char, 1));
885 else if (one_char <= 0xffff)
887 result.append ("W");
888 result.append (phex (one_char, 2));
890 else
892 result.append ("WW");
893 result.append (phex (one_char, 4));
897 /* Return a string that is a copy of the data in STORAGE, with
898 non-ASCII characters replaced by the appropriate hex encoding. A
899 template is used because, for UTF-8, we actually want to work with
900 UTF-32 codepoints. */
901 template<typename T>
902 std::string
903 copy_and_hex_encode (struct obstack *storage)
905 const T *chars = (T *) obstack_base (storage);
906 int num_chars = obstack_object_size (storage) / sizeof (T);
907 std::string result;
908 for (int i = 0; i < num_chars; ++i)
910 if (chars[i] <= 0x7f)
912 /* The host character set has to be a superset of ASCII, as
913 are all the other character sets we can use. */
914 result.push_back (chars[i]);
916 else
917 append_hex_encoded (result, chars[i]);
919 return result;
922 /* The "encoded" form of DECODED, according to GNAT conventions. If
923 THROW_ERRORS, throw an error if invalid operator name is found.
924 Otherwise, return the empty string in that case. */
926 static std::string
927 ada_encode_1 (const char *decoded, bool throw_errors)
929 if (decoded == NULL)
930 return {};
932 std::string encoding_buffer;
933 bool saw_non_ascii = false;
934 for (const char *p = decoded; *p != '\0'; p += 1)
936 if ((*p & 0x80) != 0)
937 saw_non_ascii = true;
939 if (*p == '.')
940 encoding_buffer.append ("__");
941 else if (*p == '[' && is_compiler_suffix (p))
943 encoding_buffer = encoding_buffer + "." + (p + 1);
944 if (encoding_buffer.back () == ']')
945 encoding_buffer.pop_back ();
946 break;
948 else if (*p == '"')
950 const struct ada_opname_map *mapping;
952 for (mapping = ada_opname_table;
953 mapping->encoded != NULL
954 && !startswith (p, mapping->decoded); mapping += 1)
956 if (mapping->encoded == NULL)
958 if (throw_errors)
959 error (_("invalid Ada operator name: %s"), p);
960 else
961 return {};
963 encoding_buffer.append (mapping->encoded);
964 break;
966 else
967 encoding_buffer.push_back (*p);
970 /* If a non-ASCII character is seen, we must convert it to the
971 appropriate hex form. As this is more expensive, we keep track
972 of whether it is even necessary. */
973 if (saw_non_ascii)
975 auto_obstack storage;
976 bool is_utf8 = ada_source_charset == ada_utf8;
979 convert_between_encodings
980 (host_charset (),
981 is_utf8 ? HOST_UTF32 : ada_source_charset,
982 (const gdb_byte *) encoding_buffer.c_str (),
983 encoding_buffer.length (), 1,
984 &storage, translit_none);
986 catch (const gdb_exception &)
988 static bool warned = false;
990 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
991 might like to know why. */
992 if (!warned)
994 warned = true;
995 warning (_("charset conversion failure for '%s'.\n"
996 "You may have the wrong value for 'set ada source-charset'."),
997 encoding_buffer.c_str ());
1000 /* We don't try to recover from errors. */
1001 return encoding_buffer;
1004 if (is_utf8)
1005 return copy_and_hex_encode<uint32_t> (&storage);
1006 return copy_and_hex_encode<gdb_byte> (&storage);
1009 return encoding_buffer;
1012 /* Find the entry for C in the case-folding table. Return nullptr if
1013 the entry does not cover C. */
1014 static const utf8_entry *
1015 find_case_fold_entry (uint32_t c)
1017 auto iter = std::lower_bound (std::begin (ada_case_fold),
1018 std::end (ada_case_fold),
1020 if (iter == std::end (ada_case_fold)
1021 || c < iter->start
1022 || c > iter->end)
1023 return nullptr;
1024 return &*iter;
1027 /* Return NAME folded to lower case, or, if surrounded by single
1028 quotes, unfolded, but with the quotes stripped away. If
1029 THROW_ON_ERROR is true, encoding failures will throw an exception
1030 rather than emitting a warning. Result good to next call. */
1032 static const char *
1033 ada_fold_name (std::string_view name, bool throw_on_error = false)
1035 static std::string fold_storage;
1037 if (!name.empty () && name[0] == '\'')
1038 fold_storage = name.substr (1, name.size () - 2);
1039 else
1041 /* Why convert to UTF-32 and implement our own case-folding,
1042 rather than convert to wchar_t and use the platform's
1043 functions? I'm glad you asked.
1045 The main problem is that GNAT implements an unusual rule for
1046 case folding. For ASCII letters, letters in single-byte
1047 encodings (such as ISO-8859-*), and Unicode letters that fit
1048 in a single byte (i.e., code point is <= 0xff), the letter is
1049 folded to lower case. Other Unicode letters are folded to
1050 upper case.
1052 This rule means that the code must be able to examine the
1053 value of the character. And, some hosts do not use Unicode
1054 for wchar_t, so examining the value of such characters is
1055 forbidden. */
1056 auto_obstack storage;
1059 convert_between_encodings
1060 (host_charset (), HOST_UTF32,
1061 (const gdb_byte *) name.data (),
1062 name.length (), 1,
1063 &storage, translit_none);
1065 catch (const gdb_exception &)
1067 if (throw_on_error)
1068 throw;
1070 static bool warned = false;
1072 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1073 might like to know why. */
1074 if (!warned)
1076 warned = true;
1077 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1078 "This normally should not happen, please file a bug report."),
1079 std::string (name).c_str (), host_charset ());
1082 /* We don't try to recover from errors; just return the
1083 original string. */
1084 fold_storage = name;
1085 return fold_storage.c_str ();
1088 bool is_utf8 = ada_source_charset == ada_utf8;
1089 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1090 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1091 for (int i = 0; i < num_chars; ++i)
1093 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1094 if (entry != nullptr)
1096 uint32_t low = chars[i] + entry->lower_delta;
1097 if (!is_utf8 || low <= 0xff)
1098 chars[i] = low;
1099 else
1100 chars[i] = chars[i] + entry->upper_delta;
1104 /* Now convert back to ordinary characters. */
1105 auto_obstack reconverted;
1108 convert_between_encodings (HOST_UTF32,
1109 host_charset (),
1110 (const gdb_byte *) chars,
1111 num_chars * sizeof (uint32_t),
1112 sizeof (uint32_t),
1113 &reconverted,
1114 translit_none);
1115 obstack_1grow (&reconverted, '\0');
1116 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1118 catch (const gdb_exception &)
1120 if (throw_on_error)
1121 throw;
1123 static bool warned = false;
1125 /* Converting back from UTF-32 shouldn't normally fail, but
1126 there are some host encodings without upper/lower
1127 equivalence. */
1128 if (!warned)
1130 warned = true;
1131 warning (_("could not convert the lower-cased variant of '%s'\n"
1132 "from UTF-32 to the host encoding (%s)."),
1133 std::string (name).c_str (), host_charset ());
1136 /* We don't try to recover from errors; just return the
1137 original string. */
1138 fold_storage = name;
1142 return fold_storage.c_str ();
1145 /* The "encoded" form of DECODED, according to GNAT conventions. If
1146 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1147 with <...> quoting are not folded in any case. */
1149 std::string
1150 ada_encode (const char *decoded, bool fold)
1152 if (fold && decoded[0] != '<')
1153 decoded = ada_fold_name (decoded);
1154 return ada_encode_1 (decoded, true);
1157 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1159 static int
1160 is_lower_alphanum (const char c)
1162 return (isdigit (c) || (isalpha (c) && islower (c)));
1165 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1166 This function saves in LEN the length of that same symbol name but
1167 without either of these suffixes:
1168 . .{DIGIT}+
1169 . ${DIGIT}+
1170 . ___{DIGIT}+
1171 . __{DIGIT}+.
1173 These are suffixes introduced by the compiler for entities such as
1174 nested subprogram for instance, in order to avoid name clashes.
1175 They do not serve any purpose for the debugger. */
1177 static void
1178 ada_remove_trailing_digits (const char *encoded, int *len)
1180 if (*len > 1 && isdigit (encoded[*len - 1]))
1182 int i = *len - 2;
1184 while (i > 0 && isdigit (encoded[i]))
1185 i--;
1186 if (i >= 0 && encoded[i] == '.')
1187 *len = i;
1188 else if (i >= 0 && encoded[i] == '$')
1189 *len = i;
1190 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1191 *len = i - 2;
1192 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1193 *len = i - 1;
1197 /* Remove the suffix introduced by the compiler for protected object
1198 subprograms. */
1200 static void
1201 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1203 /* Remove trailing N. */
1205 /* Protected entry subprograms are broken into two
1206 separate subprograms: The first one is unprotected, and has
1207 a 'N' suffix; the second is the protected version, and has
1208 the 'P' suffix. The second calls the first one after handling
1209 the protection. Since the P subprograms are internally generated,
1210 we leave these names undecoded, giving the user a clue that this
1211 entity is internal. */
1213 if (*len > 1
1214 && encoded[*len - 1] == 'N'
1215 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1216 *len = *len - 1;
1219 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1220 then update *LEN to remove the suffix and return the offset of the
1221 character just past the ".". Otherwise, return -1. */
1223 static int
1224 remove_compiler_suffix (const char *encoded, int *len)
1226 int offset = *len - 1;
1227 while (offset > 0 && isalpha (encoded[offset]))
1228 --offset;
1229 if (offset > 0 && encoded[offset] == '.')
1231 *len = offset;
1232 return offset + 1;
1234 return -1;
1237 /* Convert an ASCII hex string to a number. Reads exactly N
1238 characters from STR. Returns true on success, false if one of the
1239 digits was not a hex digit. */
1240 static bool
1241 convert_hex (const char *str, int n, uint32_t *out)
1243 uint32_t result = 0;
1245 for (int i = 0; i < n; ++i)
1247 if (!isxdigit (str[i]))
1248 return false;
1249 result <<= 4;
1250 result |= fromhex (str[i]);
1253 *out = result;
1254 return true;
1257 /* Convert a wide character from its ASCII hex representation in STR
1258 (consisting of exactly N characters) to the host encoding,
1259 appending the resulting bytes to OUT. If N==2 and the Ada source
1260 charset is not UTF-8, then hex refers to an encoding in the
1261 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1262 Return false and do not modify OUT on conversion failure. */
1263 static bool
1264 convert_from_hex_encoded (std::string &out, const char *str, int n)
1266 uint32_t value;
1268 if (!convert_hex (str, n, &value))
1269 return false;
1272 auto_obstack bytes;
1273 /* In the 'U' case, the hex digits encode the character in the
1274 Ada source charset. However, if the source charset is UTF-8,
1275 this really means it is a single-byte UTF-32 character. */
1276 if (n == 2 && ada_source_charset != ada_utf8)
1278 gdb_byte one_char = (gdb_byte) value;
1280 convert_between_encodings (ada_source_charset, host_charset (),
1281 &one_char,
1282 sizeof (one_char), sizeof (one_char),
1283 &bytes, translit_none);
1285 else
1286 convert_between_encodings (HOST_UTF32, host_charset (),
1287 (const gdb_byte *) &value,
1288 sizeof (value), sizeof (value),
1289 &bytes, translit_none);
1290 obstack_1grow (&bytes, '\0');
1291 out.append ((const char *) obstack_base (&bytes));
1293 catch (const gdb_exception &)
1295 /* On failure, the caller will just let the encoded form
1296 through, which seems basically reasonable. */
1297 return false;
1300 return true;
1303 /* See ada-lang.h. */
1305 std::string
1306 ada_decode (const char *encoded, bool wrap, bool operators, bool wide)
1308 int i;
1309 int len0;
1310 const char *p;
1311 int at_start_name;
1312 std::string decoded;
1313 int suffix = -1;
1315 /* With function descriptors on PPC64, the value of a symbol named
1316 ".FN", if it exists, is the entry point of the function "FN". */
1317 if (encoded[0] == '.')
1318 encoded += 1;
1320 /* The name of the Ada main procedure starts with "_ada_".
1321 This prefix is not part of the decoded name, so skip this part
1322 if we see this prefix. */
1323 if (startswith (encoded, "_ada_"))
1324 encoded += 5;
1325 /* The "___ghost_" prefix is used for ghost entities. Normally
1326 these aren't preserved but when they are, it's useful to see
1327 them. */
1328 if (startswith (encoded, "___ghost_"))
1329 encoded += 9;
1331 /* If the name starts with '_', then it is not a properly encoded
1332 name, so do not attempt to decode it. Similarly, if the name
1333 starts with '<', the name should not be decoded. */
1334 if (encoded[0] == '_' || encoded[0] == '<')
1335 goto Suppress;
1337 len0 = strlen (encoded);
1339 suffix = remove_compiler_suffix (encoded, &len0);
1341 ada_remove_trailing_digits (encoded, &len0);
1342 ada_remove_po_subprogram_suffix (encoded, &len0);
1344 /* Remove the ___X.* suffix if present. Do not forget to verify that
1345 the suffix is located before the current "end" of ENCODED. We want
1346 to avoid re-matching parts of ENCODED that have previously been
1347 marked as discarded (by decrementing LEN0). */
1348 p = strstr (encoded, "___");
1349 if (p != NULL && p - encoded < len0 - 3)
1351 if (p[3] == 'X')
1352 len0 = p - encoded;
1353 else
1354 goto Suppress;
1357 /* Remove any trailing TKB suffix. It tells us that this symbol
1358 is for the body of a task, but that information does not actually
1359 appear in the decoded name. */
1361 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1362 len0 -= 3;
1364 /* Remove any trailing TB suffix. The TB suffix is slightly different
1365 from the TKB suffix because it is used for non-anonymous task
1366 bodies. */
1368 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1369 len0 -= 2;
1371 /* Remove trailing "B" suffixes. */
1372 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1374 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1375 len0 -= 1;
1377 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1379 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1381 i = len0 - 2;
1382 while ((i >= 0 && isdigit (encoded[i]))
1383 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1384 i -= 1;
1385 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1386 len0 = i - 1;
1387 else if (i >= 0 && encoded[i] == '$')
1388 len0 = i;
1391 /* The first few characters that are not alphabetic are not part
1392 of any encoding we use, so we can copy them over verbatim. */
1394 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1395 decoded.push_back (encoded[i]);
1397 at_start_name = 1;
1398 while (i < len0)
1400 /* Is this a symbol function? */
1401 if (operators && at_start_name && encoded[i] == 'O')
1403 int k;
1405 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1407 int op_len = strlen (ada_opname_table[k].encoded);
1408 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1409 op_len - 1) == 0)
1410 && !isalnum (encoded[i + op_len]))
1412 decoded.append (ada_opname_table[k].decoded);
1413 at_start_name = 0;
1414 i += op_len;
1415 break;
1418 if (ada_opname_table[k].encoded != NULL)
1419 continue;
1421 at_start_name = 0;
1423 /* Replace "TK__" with "__", which will eventually be translated
1424 into "." (just below). */
1426 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1427 i += 2;
1429 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1430 be translated into "." (just below). These are internal names
1431 generated for anonymous blocks inside which our symbol is nested. */
1433 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1434 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1435 && isdigit (encoded [i+4]))
1437 int k = i + 5;
1439 while (k < len0 && isdigit (encoded[k]))
1440 k++; /* Skip any extra digit. */
1442 /* Double-check that the "__B_{DIGITS}+" sequence we found
1443 is indeed followed by "__". */
1444 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1445 i = k;
1448 /* Remove _E{DIGITS}+[sb] */
1450 /* Just as for protected object subprograms, there are 2 categories
1451 of subprograms created by the compiler for each entry. The first
1452 one implements the actual entry code, and has a suffix following
1453 the convention above; the second one implements the barrier and
1454 uses the same convention as above, except that the 'E' is replaced
1455 by a 'B'.
1457 Just as above, we do not decode the name of barrier functions
1458 to give the user a clue that the code he is debugging has been
1459 internally generated. */
1461 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1462 && isdigit (encoded[i+2]))
1464 int k = i + 3;
1466 while (k < len0 && isdigit (encoded[k]))
1467 k++;
1469 if (k < len0
1470 && (encoded[k] == 'b' || encoded[k] == 's'))
1472 k++;
1473 /* Just as an extra precaution, make sure that if this
1474 suffix is followed by anything else, it is a '_'.
1475 Otherwise, we matched this sequence by accident. */
1476 if (k == len0
1477 || (k < len0 && encoded[k] == '_'))
1478 i = k;
1482 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1483 the GNAT front-end in protected object subprograms. */
1485 if (i < len0 + 3
1486 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1488 /* Backtrack a bit up until we reach either the begining of
1489 the encoded name, or "__". Make sure that we only find
1490 digits or lowercase characters. */
1491 const char *ptr = encoded + i - 1;
1493 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1494 ptr--;
1495 if (ptr < encoded
1496 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1497 i++;
1500 if (wide && i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1502 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1504 i += 3;
1505 continue;
1508 else if (wide && i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1510 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1512 i += 5;
1513 continue;
1516 else if (wide && i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1517 && isxdigit (encoded[i + 2]))
1519 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1521 i += 10;
1522 continue;
1526 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1528 /* This is a X[bn]* sequence not separated from the previous
1529 part of the name with a non-alpha-numeric character (in other
1530 words, immediately following an alpha-numeric character), then
1531 verify that it is placed at the end of the encoded name. If
1532 not, then the encoding is not valid and we should abort the
1533 decoding. Otherwise, just skip it, it is used in body-nested
1534 package names. */
1536 i += 1;
1537 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1538 if (i < len0)
1539 goto Suppress;
1541 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1543 /* Replace '__' by '.'. */
1544 decoded.push_back ('.');
1545 at_start_name = 1;
1546 i += 2;
1548 else
1550 /* It's a character part of the decoded name, so just copy it
1551 over. */
1552 decoded.push_back (encoded[i]);
1553 i += 1;
1557 /* Decoded names should never contain any uppercase character.
1558 Double-check this, and abort the decoding if we find one. */
1560 if (operators)
1562 for (i = 0; i < decoded.length(); ++i)
1563 if (isupper (decoded[i]) || decoded[i] == ' ')
1564 goto Suppress;
1567 /* If the compiler added a suffix, append it now. */
1568 if (suffix >= 0)
1569 decoded = decoded + "[" + &encoded[suffix] + "]";
1571 return decoded;
1573 Suppress:
1574 if (!wrap)
1575 return {};
1577 if (encoded[0] == '<')
1578 decoded = encoded;
1579 else
1580 decoded = '<' + std::string(encoded) + '>';
1581 return decoded;
1584 #ifdef GDB_SELF_TEST
1586 static void
1587 ada_decode_tests ()
1589 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1590 result does not really matter very much. */
1591 SELF_CHECK (ada_decode ("44") == "44");
1594 #endif
1596 /* Table for keeping permanent unique copies of decoded names. Once
1597 allocated, names in this table are never released. While this is a
1598 storage leak, it should not be significant unless there are massive
1599 changes in the set of decoded names in successive versions of a
1600 symbol table loaded during a single session. */
1601 static struct htab *decoded_names_store;
1603 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1604 in the language-specific part of GSYMBOL, if it has not been
1605 previously computed. Tries to save the decoded name in the same
1606 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1607 in any case, the decoded symbol has a lifetime at least that of
1608 GSYMBOL).
1609 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1610 const, but nevertheless modified to a semantically equivalent form
1611 when a decoded name is cached in it. */
1613 const char *
1614 ada_decode_symbol (const struct general_symbol_info *arg)
1616 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1617 const char **resultp =
1618 &gsymbol->language_specific.demangled_name;
1620 if (!gsymbol->ada_mangled)
1622 std::string decoded = ada_decode (gsymbol->linkage_name ());
1623 struct obstack *obstack = gsymbol->language_specific.obstack;
1625 gsymbol->ada_mangled = 1;
1627 if (obstack != NULL)
1628 *resultp = obstack_strdup (obstack, decoded.c_str ());
1629 else
1631 /* Sometimes, we can't find a corresponding objfile, in
1632 which case, we put the result on the heap. Since we only
1633 decode when needed, we hope this usually does not cause a
1634 significant memory leak (FIXME). */
1636 char **slot = (char **) htab_find_slot (decoded_names_store,
1637 decoded.c_str (), INSERT);
1639 if (*slot == NULL)
1640 *slot = xstrdup (decoded.c_str ());
1641 *resultp = *slot;
1645 return *resultp;
1650 /* Arrays */
1652 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1653 generated by the GNAT compiler to describe the index type used
1654 for each dimension of an array, check whether it follows the latest
1655 known encoding. If not, fix it up to conform to the latest encoding.
1656 Otherwise, do nothing. This function also does nothing if
1657 INDEX_DESC_TYPE is NULL.
1659 The GNAT encoding used to describe the array index type evolved a bit.
1660 Initially, the information would be provided through the name of each
1661 field of the structure type only, while the type of these fields was
1662 described as unspecified and irrelevant. The debugger was then expected
1663 to perform a global type lookup using the name of that field in order
1664 to get access to the full index type description. Because these global
1665 lookups can be very expensive, the encoding was later enhanced to make
1666 the global lookup unnecessary by defining the field type as being
1667 the full index type description.
1669 The purpose of this routine is to allow us to support older versions
1670 of the compiler by detecting the use of the older encoding, and by
1671 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1672 we essentially replace each field's meaningless type by the associated
1673 index subtype). */
1675 void
1676 ada_fixup_array_indexes_type (struct type *index_desc_type)
1678 int i;
1680 if (index_desc_type == NULL)
1681 return;
1682 gdb_assert (index_desc_type->num_fields () > 0);
1684 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1685 to check one field only, no need to check them all). If not, return
1686 now.
1688 If our INDEX_DESC_TYPE was generated using the older encoding,
1689 the field type should be a meaningless integer type whose name
1690 is not equal to the field name. */
1691 if (index_desc_type->field (0).type ()->name () != NULL
1692 && strcmp (index_desc_type->field (0).type ()->name (),
1693 index_desc_type->field (0).name ()) == 0)
1694 return;
1696 /* Fixup each field of INDEX_DESC_TYPE. */
1697 for (i = 0; i < index_desc_type->num_fields (); i++)
1699 const char *name = index_desc_type->field (i).name ();
1700 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1702 if (raw_type)
1703 index_desc_type->field (i).set_type (raw_type);
1707 /* The desc_* routines return primitive portions of array descriptors
1708 (fat pointers). */
1710 /* The descriptor or array type, if any, indicated by TYPE; removes
1711 level of indirection, if needed. */
1713 static struct type *
1714 desc_base_type (struct type *type)
1716 if (type == NULL)
1717 return NULL;
1718 type = ada_check_typedef (type);
1719 if (type->code () == TYPE_CODE_TYPEDEF)
1720 type = ada_typedef_target_type (type);
1722 if (type != NULL
1723 && (type->code () == TYPE_CODE_PTR
1724 || type->code () == TYPE_CODE_REF))
1725 return ada_check_typedef (type->target_type ());
1726 else
1727 return type;
1730 /* True iff TYPE indicates a "thin" array pointer type. */
1732 static int
1733 is_thin_pntr (struct type *type)
1735 return
1736 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1737 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1740 /* The descriptor type for thin pointer type TYPE. */
1742 static struct type *
1743 thin_descriptor_type (struct type *type)
1745 struct type *base_type = desc_base_type (type);
1747 if (base_type == NULL)
1748 return NULL;
1749 if (is_suffix (ada_type_name (base_type), "___XVE"))
1750 return base_type;
1751 else
1753 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1755 if (alt_type == NULL)
1756 return base_type;
1757 else
1758 return alt_type;
1762 /* A pointer to the array data for thin-pointer value VAL. */
1764 static struct value *
1765 thin_data_pntr (struct value *val)
1767 struct type *type = ada_check_typedef (val->type ());
1768 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1770 data_type = lookup_pointer_type (data_type);
1772 if (type->code () == TYPE_CODE_PTR)
1773 return value_cast (data_type, val->copy ());
1774 else
1775 return value_from_longest (data_type, val->address ());
1778 /* True iff TYPE indicates a "thick" array pointer type. */
1780 static int
1781 is_thick_pntr (struct type *type)
1783 type = desc_base_type (type);
1784 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1785 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1788 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1789 pointer to one, the type of its bounds data; otherwise, NULL. */
1791 static struct type *
1792 desc_bounds_type (struct type *type)
1794 struct type *r;
1796 type = desc_base_type (type);
1798 if (type == NULL)
1799 return NULL;
1800 else if (is_thin_pntr (type))
1802 type = thin_descriptor_type (type);
1803 if (type == NULL)
1804 return NULL;
1805 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1806 if (r != NULL)
1807 return ada_check_typedef (r);
1809 else if (type->code () == TYPE_CODE_STRUCT)
1811 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1812 if (r != NULL)
1813 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1815 return NULL;
1818 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1819 one, a pointer to its bounds data. Otherwise NULL. */
1821 static struct value *
1822 desc_bounds (struct value *arr)
1824 struct type *type = ada_check_typedef (arr->type ());
1826 if (is_thin_pntr (type))
1828 struct type *bounds_type =
1829 desc_bounds_type (thin_descriptor_type (type));
1830 LONGEST addr;
1832 if (bounds_type == NULL)
1833 error (_("Bad GNAT array descriptor"));
1835 /* NOTE: The following calculation is not really kosher, but
1836 since desc_type is an XVE-encoded type (and shouldn't be),
1837 the correct calculation is a real pain. FIXME (and fix GCC). */
1838 if (type->code () == TYPE_CODE_PTR)
1839 addr = value_as_long (arr);
1840 else
1841 addr = arr->address ();
1843 return
1844 value_from_longest (lookup_pointer_type (bounds_type),
1845 addr - bounds_type->length ());
1848 else if (is_thick_pntr (type))
1850 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1851 _("Bad GNAT array descriptor"));
1852 struct type *p_bounds_type = p_bounds->type ();
1854 if (p_bounds_type
1855 && p_bounds_type->code () == TYPE_CODE_PTR)
1857 struct type *target_type = p_bounds_type->target_type ();
1859 if (target_type->is_stub ())
1860 p_bounds = value_cast (lookup_pointer_type
1861 (ada_check_typedef (target_type)),
1862 p_bounds);
1864 else
1865 error (_("Bad GNAT array descriptor"));
1867 return p_bounds;
1869 else
1870 return NULL;
1873 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1874 position of the field containing the address of the bounds data. */
1876 static int
1877 fat_pntr_bounds_bitpos (struct type *type)
1879 return desc_base_type (type)->field (1).loc_bitpos ();
1882 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1883 size of the field containing the address of the bounds data. */
1885 static int
1886 fat_pntr_bounds_bitsize (struct type *type)
1888 type = desc_base_type (type);
1890 if (type->field (1).bitsize () > 0)
1891 return type->field (1).bitsize ();
1892 else
1893 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1896 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1897 pointer to one, the type of its array data (a array-with-no-bounds type);
1898 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1899 data. */
1901 static struct type *
1902 desc_data_target_type (struct type *type)
1904 type = desc_base_type (type);
1906 /* NOTE: The following is bogus; see comment in desc_bounds. */
1907 if (is_thin_pntr (type))
1908 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1909 else if (is_thick_pntr (type))
1911 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1913 if (data_type
1914 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1915 return ada_check_typedef (data_type->target_type ());
1918 return NULL;
1921 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1922 its array data. */
1924 static struct value *
1925 desc_data (struct value *arr)
1927 struct type *type = arr->type ();
1929 if (is_thin_pntr (type))
1930 return thin_data_pntr (arr);
1931 else if (is_thick_pntr (type))
1932 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1933 _("Bad GNAT array descriptor"));
1934 else
1935 return NULL;
1939 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1940 position of the field containing the address of the data. */
1942 static int
1943 fat_pntr_data_bitpos (struct type *type)
1945 return desc_base_type (type)->field (0).loc_bitpos ();
1948 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1949 size of the field containing the address of the data. */
1951 static int
1952 fat_pntr_data_bitsize (struct type *type)
1954 type = desc_base_type (type);
1956 if (type->field (0).bitsize () > 0)
1957 return type->field (0).bitsize ();
1958 else
1959 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1962 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1963 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1964 bound, if WHICH is 1. The first bound is I=1. */
1966 static struct value *
1967 desc_one_bound (struct value *bounds, int i, int which)
1969 char bound_name[20];
1970 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1971 which ? 'U' : 'L', i - 1);
1972 return value_struct_elt (&bounds, {}, bound_name, NULL,
1973 _("Bad GNAT array descriptor bounds"));
1976 /* If BOUNDS is an array-bounds structure type, return the bit position
1977 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1978 bound, if WHICH is 1. The first bound is I=1. */
1980 static int
1981 desc_bound_bitpos (struct type *type, int i, int which)
1983 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1986 /* If BOUNDS is an array-bounds structure type, return the bit field size
1987 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1988 bound, if WHICH is 1. The first bound is I=1. */
1990 static int
1991 desc_bound_bitsize (struct type *type, int i, int which)
1993 type = desc_base_type (type);
1995 if (type->field (2 * i + which - 2).bitsize () > 0)
1996 return type->field (2 * i + which - 2).bitsize ();
1997 else
1998 return 8 * type->field (2 * i + which - 2).type ()->length ();
2001 /* If TYPE is the type of an array-bounds structure, the type of its
2002 Ith bound (numbering from 1). Otherwise, NULL. */
2004 static struct type *
2005 desc_index_type (struct type *type, int i)
2007 type = desc_base_type (type);
2009 if (type->code () == TYPE_CODE_STRUCT)
2011 char bound_name[20];
2012 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2013 return lookup_struct_elt_type (type, bound_name, 1);
2015 else
2016 return NULL;
2019 /* The number of index positions in the array-bounds type TYPE.
2020 Return 0 if TYPE is NULL. */
2022 static int
2023 desc_arity (struct type *type)
2025 type = desc_base_type (type);
2027 if (type != NULL)
2028 return type->num_fields () / 2;
2029 return 0;
2032 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2033 an array descriptor type (representing an unconstrained array
2034 type). */
2036 static int
2037 ada_is_direct_array_type (struct type *type)
2039 if (type == NULL)
2040 return 0;
2041 type = ada_check_typedef (type);
2042 return (type->code () == TYPE_CODE_ARRAY
2043 || ada_is_array_descriptor_type (type));
2046 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2047 * to one. */
2049 static int
2050 ada_is_array_type (struct type *type)
2052 while (type != NULL
2053 && (type->code () == TYPE_CODE_PTR
2054 || type->code () == TYPE_CODE_REF))
2055 type = type->target_type ();
2056 return ada_is_direct_array_type (type);
2059 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2062 ada_is_simple_array_type (struct type *type)
2064 if (type == NULL)
2065 return 0;
2066 type = ada_check_typedef (type);
2067 return (type->code () == TYPE_CODE_ARRAY
2068 || (type->code () == TYPE_CODE_PTR
2069 && (ada_check_typedef (type->target_type ())->code ()
2070 == TYPE_CODE_ARRAY)));
2073 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2076 ada_is_array_descriptor_type (struct type *type)
2078 struct type *data_type = desc_data_target_type (type);
2080 if (type == NULL)
2081 return 0;
2082 type = ada_check_typedef (type);
2083 return (data_type != NULL
2084 && data_type->code () == TYPE_CODE_ARRAY
2085 && desc_arity (desc_bounds_type (type)) > 0);
2088 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2089 (fat pointer) returns the type of the array data described---specifically,
2090 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2091 in from the descriptor; otherwise, they are left unspecified. If
2092 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2093 returns NULL. The result is simply the type of ARR if ARR is not
2094 a descriptor. */
2096 static struct type *
2097 ada_type_of_array (struct value *arr, int bounds)
2099 if (ada_is_constrained_packed_array_type (arr->type ()))
2100 return decode_constrained_packed_array_type (arr->type ());
2102 if (!ada_is_array_descriptor_type (arr->type ()))
2103 return arr->type ();
2105 if (!bounds)
2107 struct type *array_type =
2108 ada_check_typedef (desc_data_target_type (arr->type ()));
2110 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2111 array_type->field (0).set_bitsize
2112 (decode_packed_array_bitsize (arr->type ()));
2114 return array_type;
2116 else
2118 struct type *elt_type;
2119 int arity;
2120 struct value *descriptor;
2122 elt_type = ada_array_element_type (arr->type (), -1);
2123 arity = ada_array_arity (arr->type ());
2125 if (elt_type == NULL || arity == 0)
2126 return ada_check_typedef (arr->type ());
2128 descriptor = desc_bounds (arr);
2129 if (value_as_long (descriptor) == 0)
2130 return NULL;
2131 while (arity > 0)
2133 type_allocator alloc (arr->type ());
2134 struct value *low = desc_one_bound (descriptor, arity, 0);
2135 struct value *high = desc_one_bound (descriptor, arity, 1);
2137 arity -= 1;
2138 struct type *range_type
2139 = create_static_range_type (alloc, low->type (),
2140 longest_to_int (value_as_long (low)),
2141 longest_to_int (value_as_long (high)));
2142 elt_type = create_array_type (alloc, elt_type, range_type);
2143 INIT_GNAT_SPECIFIC (elt_type);
2145 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2147 /* We need to store the element packed bitsize, as well as
2148 recompute the array size, because it was previously
2149 computed based on the unpacked element size. */
2150 LONGEST lo = value_as_long (low);
2151 LONGEST hi = value_as_long (high);
2153 elt_type->field (0).set_bitsize
2154 (decode_packed_array_bitsize (arr->type ()));
2156 /* If the array has no element, then the size is already
2157 zero, and does not need to be recomputed. */
2158 if (lo < hi)
2160 int array_bitsize =
2161 (hi - lo + 1) * elt_type->field (0).bitsize ();
2163 elt_type->set_length ((array_bitsize + 7) / 8);
2168 return lookup_pointer_type (elt_type);
2172 /* If ARR does not represent an array, returns ARR unchanged.
2173 Otherwise, returns either a standard GDB array with bounds set
2174 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2175 GDB array. Returns NULL if ARR is a null fat pointer. */
2177 struct value *
2178 ada_coerce_to_simple_array_ptr (struct value *arr)
2180 if (ada_is_array_descriptor_type (arr->type ()))
2182 struct type *arrType = ada_type_of_array (arr, 1);
2184 if (arrType == NULL)
2185 return NULL;
2186 return value_cast (arrType, desc_data (arr)->copy ());
2188 else if (ada_is_constrained_packed_array_type (arr->type ()))
2189 return decode_constrained_packed_array (arr);
2190 else
2191 return arr;
2194 /* If ARR does not represent an array, returns ARR unchanged.
2195 Otherwise, returns a standard GDB array describing ARR (which may
2196 be ARR itself if it already is in the proper form). */
2198 struct value *
2199 ada_coerce_to_simple_array (struct value *arr)
2201 if (ada_is_array_descriptor_type (arr->type ()))
2203 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2205 if (arrVal == NULL)
2206 error (_("Bounds unavailable for null array pointer."));
2207 return value_ind (arrVal);
2209 else if (ada_is_constrained_packed_array_type (arr->type ()))
2210 return decode_constrained_packed_array (arr);
2211 else
2212 return arr;
2215 /* If TYPE represents a GNAT array type, return it translated to an
2216 ordinary GDB array type (possibly with BITSIZE fields indicating
2217 packing). For other types, is the identity. */
2219 struct type *
2220 ada_coerce_to_simple_array_type (struct type *type)
2222 if (ada_is_constrained_packed_array_type (type))
2223 return decode_constrained_packed_array_type (type);
2225 if (ada_is_array_descriptor_type (type))
2226 return ada_check_typedef (desc_data_target_type (type));
2228 return type;
2231 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2233 static int
2234 ada_is_gnat_encoded_packed_array_type (struct type *type)
2236 if (type == NULL)
2237 return 0;
2238 type = desc_base_type (type);
2239 type = ada_check_typedef (type);
2240 return
2241 ada_type_name (type) != NULL
2242 && strstr (ada_type_name (type), "___XP") != NULL;
2245 /* Non-zero iff TYPE represents a standard GNAT constrained
2246 packed-array type. */
2249 ada_is_constrained_packed_array_type (struct type *type)
2251 return ada_is_gnat_encoded_packed_array_type (type)
2252 && !ada_is_array_descriptor_type (type);
2255 /* Non-zero iff TYPE represents an array descriptor for a
2256 unconstrained packed-array type. */
2258 static int
2259 ada_is_unconstrained_packed_array_type (struct type *type)
2261 if (!ada_is_array_descriptor_type (type))
2262 return 0;
2264 if (ada_is_gnat_encoded_packed_array_type (type))
2265 return 1;
2267 /* If we saw GNAT encodings, then the above code is sufficient.
2268 However, with minimal encodings, we will just have a thick
2269 pointer instead. */
2270 if (is_thick_pntr (type))
2272 type = desc_base_type (type);
2273 /* The structure's first field is a pointer to an array, so this
2274 fetches the array type. */
2275 type = type->field (0).type ()->target_type ();
2276 if (type->code () == TYPE_CODE_TYPEDEF)
2277 type = ada_typedef_target_type (type);
2278 /* Now we can see if the array elements are packed. */
2279 return type->field (0).bitsize () > 0;
2282 return 0;
2285 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2286 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2288 static bool
2289 ada_is_any_packed_array_type (struct type *type)
2291 return (ada_is_constrained_packed_array_type (type)
2292 || (type->code () == TYPE_CODE_ARRAY
2293 && type->field (0).bitsize () % 8 != 0));
2296 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2297 return the size of its elements in bits. */
2299 static long
2300 decode_packed_array_bitsize (struct type *type)
2302 const char *raw_name;
2303 const char *tail;
2304 long bits;
2306 /* Access to arrays implemented as fat pointers are encoded as a typedef
2307 of the fat pointer type. We need the name of the fat pointer type
2308 to do the decoding, so strip the typedef layer. */
2309 if (type->code () == TYPE_CODE_TYPEDEF)
2310 type = ada_typedef_target_type (type);
2312 raw_name = ada_type_name (ada_check_typedef (type));
2313 if (!raw_name)
2314 raw_name = ada_type_name (desc_base_type (type));
2316 if (!raw_name)
2317 return 0;
2319 tail = strstr (raw_name, "___XP");
2320 if (tail == nullptr)
2322 gdb_assert (is_thick_pntr (type));
2323 /* The structure's first field is a pointer to an array, so this
2324 fetches the array type. */
2325 type = type->field (0).type ()->target_type ();
2326 /* Now we can see if the array elements are packed. */
2327 return type->field (0).bitsize ();
2330 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2332 lim_warning
2333 (_("could not understand bit size information on packed array"));
2334 return 0;
2337 return bits;
2340 /* Given that TYPE is a standard GDB array type with all bounds filled
2341 in, and that the element size of its ultimate scalar constituents
2342 (that is, either its elements, or, if it is an array of arrays, its
2343 elements' elements, etc.) is *ELT_BITS, return an identical type,
2344 but with the bit sizes of its elements (and those of any
2345 constituent arrays) recorded in the BITSIZE components of its
2346 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2347 in bits.
2349 Note that, for arrays whose index type has an XA encoding where
2350 a bound references a record discriminant, getting that discriminant,
2351 and therefore the actual value of that bound, is not possible
2352 because none of the given parameters gives us access to the record.
2353 This function assumes that it is OK in the context where it is being
2354 used to return an array whose bounds are still dynamic and where
2355 the length is arbitrary. */
2357 static struct type *
2358 constrained_packed_array_type (struct type *type, long *elt_bits)
2360 struct type *new_elt_type;
2361 struct type *new_type;
2362 struct type *index_type_desc;
2363 struct type *index_type;
2364 LONGEST low_bound, high_bound;
2366 type = ada_check_typedef (type);
2367 if (type->code () != TYPE_CODE_ARRAY)
2368 return type;
2370 index_type_desc = ada_find_parallel_type (type, "___XA");
2371 if (index_type_desc)
2372 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2373 NULL);
2374 else
2375 index_type = type->index_type ();
2377 type_allocator alloc (type);
2378 new_elt_type =
2379 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2380 elt_bits);
2381 new_type = create_array_type (alloc, new_elt_type, index_type);
2382 new_type->field (0).set_bitsize (*elt_bits);
2383 new_type->set_name (ada_type_name (type));
2385 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2386 && is_dynamic_type (check_typedef (index_type)))
2387 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2388 low_bound = high_bound = 0;
2389 if (high_bound < low_bound)
2391 *elt_bits = 0;
2392 new_type->set_length (0);
2394 else
2396 *elt_bits *= (high_bound - low_bound + 1);
2397 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2400 new_type->set_is_fixed_instance (true);
2401 return new_type;
2404 /* The array type encoded by TYPE, where
2405 ada_is_constrained_packed_array_type (TYPE). */
2407 static struct type *
2408 decode_constrained_packed_array_type (struct type *type)
2410 const char *raw_name = ada_type_name (ada_check_typedef (type));
2411 char *name;
2412 const char *tail;
2413 struct type *shadow_type;
2414 long bits;
2416 if (!raw_name)
2417 raw_name = ada_type_name (desc_base_type (type));
2419 if (!raw_name)
2420 return NULL;
2422 name = (char *) alloca (strlen (raw_name) + 1);
2423 tail = strstr (raw_name, "___XP");
2424 type = desc_base_type (type);
2426 memcpy (name, raw_name, tail - raw_name);
2427 name[tail - raw_name] = '\000';
2429 shadow_type = ada_find_parallel_type_with_name (type, name);
2431 if (shadow_type == NULL)
2433 lim_warning (_("could not find bounds information on packed array"));
2434 return NULL;
2436 shadow_type = check_typedef (shadow_type);
2438 if (shadow_type->code () != TYPE_CODE_ARRAY)
2440 lim_warning (_("could not understand bounds "
2441 "information on packed array"));
2442 return NULL;
2445 bits = decode_packed_array_bitsize (type);
2446 return constrained_packed_array_type (shadow_type, &bits);
2449 /* Helper function for decode_constrained_packed_array. Set the field
2450 bitsize on a series of packed arrays. Returns the number of
2451 elements in TYPE. */
2453 static LONGEST
2454 recursively_update_array_bitsize (struct type *type)
2456 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2458 LONGEST low, high;
2459 if (!get_discrete_bounds (type->index_type (), &low, &high)
2460 || low > high)
2461 return 0;
2462 LONGEST our_len = high - low + 1;
2464 struct type *elt_type = type->target_type ();
2465 if (elt_type->code () == TYPE_CODE_ARRAY)
2467 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2468 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
2469 type->field (0).set_bitsize (elt_bitsize);
2471 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2472 / HOST_CHAR_BIT));
2475 return our_len;
2478 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2479 array, returns a simple array that denotes that array. Its type is a
2480 standard GDB array type except that the BITSIZEs of the array
2481 target types are set to the number of bits in each element, and the
2482 type length is set appropriately. */
2484 static struct value *
2485 decode_constrained_packed_array (struct value *arr)
2487 struct type *type;
2489 /* If our value is a pointer, then dereference it. Likewise if
2490 the value is a reference. Make sure that this operation does not
2491 cause the target type to be fixed, as this would indirectly cause
2492 this array to be decoded. The rest of the routine assumes that
2493 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2494 and "value_ind" routines to perform the dereferencing, as opposed
2495 to using "ada_coerce_ref" or "ada_value_ind". */
2496 arr = coerce_ref (arr);
2497 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2498 arr = value_ind (arr);
2500 type = decode_constrained_packed_array_type (arr->type ());
2501 if (type == NULL)
2503 error (_("can't unpack array"));
2504 return NULL;
2507 /* Decoding the packed array type could not correctly set the field
2508 bitsizes for any dimension except the innermost, because the
2509 bounds may be variable and were not passed to that function. So,
2510 we further resolve the array bounds here and then update the
2511 sizes. */
2512 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2513 CORE_ADDR address = arr->address ();
2514 gdb::array_view<const gdb_byte> view
2515 = gdb::make_array_view (valaddr, type->length ());
2516 type = resolve_dynamic_type (type, view, address);
2517 recursively_update_array_bitsize (type);
2519 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2520 && ada_is_modular_type (arr->type ()))
2522 /* This is a (right-justified) modular type representing a packed
2523 array with no wrapper. In order to interpret the value through
2524 the (left-justified) packed array type we just built, we must
2525 first left-justify it. */
2526 int bit_size, bit_pos;
2527 ULONGEST mod;
2529 mod = ada_modulus (arr->type ()) - 1;
2530 bit_size = 0;
2531 while (mod > 0)
2533 bit_size += 1;
2534 mod >>= 1;
2536 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2537 arr = ada_value_primitive_packed_val (arr, NULL,
2538 bit_pos / HOST_CHAR_BIT,
2539 bit_pos % HOST_CHAR_BIT,
2540 bit_size,
2541 type);
2544 return coerce_unspec_val_to_type (arr, type);
2548 /* The value of the element of packed array ARR at the ARITY indices
2549 given in IND. ARR must be a simple array. */
2551 static struct value *
2552 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2554 int i;
2555 int bits, elt_off, bit_off;
2556 long elt_total_bit_offset;
2557 struct type *elt_type;
2558 struct value *v;
2560 bits = 0;
2561 elt_total_bit_offset = 0;
2562 elt_type = ada_check_typedef (arr->type ());
2563 for (i = 0; i < arity; i += 1)
2565 if (elt_type->code () != TYPE_CODE_ARRAY
2566 || elt_type->field (0).bitsize () == 0)
2567 error
2568 (_("attempt to do packed indexing of "
2569 "something other than a packed array"));
2570 else
2572 struct type *range_type = elt_type->index_type ();
2573 LONGEST lowerbound, upperbound;
2574 LONGEST idx;
2576 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2578 lim_warning (_("don't know bounds of array"));
2579 lowerbound = upperbound = 0;
2582 idx = pos_atr (ind[i]);
2583 if (idx < lowerbound || idx > upperbound)
2584 lim_warning (_("packed array index %ld out of bounds"),
2585 (long) idx);
2586 bits = elt_type->field (0).bitsize ();
2587 elt_total_bit_offset += (idx - lowerbound) * bits;
2588 elt_type = ada_check_typedef (elt_type->target_type ());
2591 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2592 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2594 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2595 bits, elt_type);
2596 return v;
2599 /* Non-zero iff TYPE includes negative integer values. */
2601 static int
2602 has_negatives (struct type *type)
2604 switch (type->code ())
2606 default:
2607 return 0;
2608 case TYPE_CODE_INT:
2609 return !type->is_unsigned ();
2610 case TYPE_CODE_RANGE:
2611 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2615 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2616 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2617 the unpacked buffer.
2619 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2620 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2622 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2623 zero otherwise.
2625 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2627 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2629 static void
2630 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2631 gdb_byte *unpacked, int unpacked_len,
2632 int is_big_endian, int is_signed_type,
2633 int is_scalar)
2635 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2636 int src_idx; /* Index into the source area */
2637 int src_bytes_left; /* Number of source bytes left to process. */
2638 int srcBitsLeft; /* Number of source bits left to move */
2639 int unusedLS; /* Number of bits in next significant
2640 byte of source that are unused */
2642 int unpacked_idx; /* Index into the unpacked buffer */
2643 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2645 unsigned long accum; /* Staging area for bits being transferred */
2646 int accumSize; /* Number of meaningful bits in accum */
2647 unsigned char sign;
2649 /* Transmit bytes from least to most significant; delta is the direction
2650 the indices move. */
2651 int delta = is_big_endian ? -1 : 1;
2653 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2654 bits from SRC. .*/
2655 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2656 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2657 bit_size, unpacked_len);
2659 srcBitsLeft = bit_size;
2660 src_bytes_left = src_len;
2661 unpacked_bytes_left = unpacked_len;
2662 sign = 0;
2664 if (is_big_endian)
2666 src_idx = src_len - 1;
2667 if (is_signed_type
2668 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2669 sign = ~0;
2671 unusedLS =
2672 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2673 % HOST_CHAR_BIT;
2675 if (is_scalar)
2677 accumSize = 0;
2678 unpacked_idx = unpacked_len - 1;
2680 else
2682 /* Non-scalar values must be aligned at a byte boundary... */
2683 accumSize =
2684 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2685 /* ... And are placed at the beginning (most-significant) bytes
2686 of the target. */
2687 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2688 unpacked_bytes_left = unpacked_idx + 1;
2691 else
2693 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2695 src_idx = unpacked_idx = 0;
2696 unusedLS = bit_offset;
2697 accumSize = 0;
2699 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2700 sign = ~0;
2703 accum = 0;
2704 while (src_bytes_left > 0)
2706 /* Mask for removing bits of the next source byte that are not
2707 part of the value. */
2708 unsigned int unusedMSMask =
2709 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2711 /* Sign-extend bits for this byte. */
2712 unsigned int signMask = sign & ~unusedMSMask;
2714 accum |=
2715 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2716 accumSize += HOST_CHAR_BIT - unusedLS;
2717 if (accumSize >= HOST_CHAR_BIT)
2719 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2720 accumSize -= HOST_CHAR_BIT;
2721 accum >>= HOST_CHAR_BIT;
2722 unpacked_bytes_left -= 1;
2723 unpacked_idx += delta;
2725 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2726 unusedLS = 0;
2727 src_bytes_left -= 1;
2728 src_idx += delta;
2730 while (unpacked_bytes_left > 0)
2732 accum |= sign << accumSize;
2733 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2734 accumSize -= HOST_CHAR_BIT;
2735 if (accumSize < 0)
2736 accumSize = 0;
2737 accum >>= HOST_CHAR_BIT;
2738 unpacked_bytes_left -= 1;
2739 unpacked_idx += delta;
2743 /* Create a new value of type TYPE from the contents of OBJ starting
2744 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2745 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2746 assigning through the result will set the field fetched from.
2747 VALADDR is ignored unless OBJ is NULL, in which case,
2748 VALADDR+OFFSET must address the start of storage containing the
2749 packed value. The value returned in this case is never an lval.
2750 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2752 struct value *
2753 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2754 long offset, int bit_offset, int bit_size,
2755 struct type *type)
2757 struct value *v;
2758 const gdb_byte *src; /* First byte containing data to unpack */
2759 gdb_byte *unpacked;
2760 const int is_scalar = is_scalar_type (type);
2761 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2762 gdb::byte_vector staging;
2764 type = ada_check_typedef (type);
2766 if (obj == NULL)
2767 src = valaddr + offset;
2768 else
2769 src = obj->contents ().data () + offset;
2771 if (is_dynamic_type (type))
2773 /* The length of TYPE might by dynamic, so we need to resolve
2774 TYPE in order to know its actual size, which we then use
2775 to create the contents buffer of the value we return.
2776 The difficulty is that the data containing our object is
2777 packed, and therefore maybe not at a byte boundary. So, what
2778 we do, is unpack the data into a byte-aligned buffer, and then
2779 use that buffer as our object's value for resolving the type. */
2780 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2781 staging.resize (staging_len);
2783 ada_unpack_from_contents (src, bit_offset, bit_size,
2784 staging.data (), staging.size (),
2785 is_big_endian, has_negatives (type),
2786 is_scalar);
2787 type = resolve_dynamic_type (type, staging, 0);
2788 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2790 /* This happens when the length of the object is dynamic,
2791 and is actually smaller than the space reserved for it.
2792 For instance, in an array of variant records, the bit_size
2793 we're given is the array stride, which is constant and
2794 normally equal to the maximum size of its element.
2795 But, in reality, each element only actually spans a portion
2796 of that stride. */
2797 bit_size = type->length () * HOST_CHAR_BIT;
2801 if (obj == NULL)
2803 v = value::allocate (type);
2804 src = valaddr + offset;
2806 else if (obj->lval () == lval_memory && obj->lazy ())
2808 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2809 gdb_byte *buf;
2811 v = value_at (type, obj->address () + offset);
2812 buf = (gdb_byte *) alloca (src_len);
2813 read_memory (v->address (), buf, src_len);
2814 src = buf;
2816 else
2818 v = value::allocate (type);
2819 src = obj->contents ().data () + offset;
2822 if (obj != NULL)
2824 long new_offset = offset;
2826 v->set_component_location (obj);
2827 v->set_bitpos (bit_offset + obj->bitpos ());
2828 v->set_bitsize (bit_size);
2829 if (v->bitpos () >= HOST_CHAR_BIT)
2831 ++new_offset;
2832 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2834 v->set_offset (new_offset);
2836 /* Also set the parent value. This is needed when trying to
2837 assign a new value (in inferior memory). */
2838 v->set_parent (obj);
2840 else
2841 v->set_bitsize (bit_size);
2842 unpacked = v->contents_writeable ().data ();
2844 if (bit_size == 0)
2846 memset (unpacked, 0, type->length ());
2847 return v;
2850 if (staging.size () == type->length ())
2852 /* Small short-cut: If we've unpacked the data into a buffer
2853 of the same size as TYPE's length, then we can reuse that,
2854 instead of doing the unpacking again. */
2855 memcpy (unpacked, staging.data (), staging.size ());
2857 else
2858 ada_unpack_from_contents (src, bit_offset, bit_size,
2859 unpacked, type->length (),
2860 is_big_endian, has_negatives (type), is_scalar);
2862 return v;
2865 /* Store the contents of FROMVAL into the location of TOVAL.
2866 Return a new value with the location of TOVAL and contents of
2867 FROMVAL. Handles assignment into packed fields that have
2868 floating-point or non-scalar types. */
2870 static struct value *
2871 ada_value_assign (struct value *toval, struct value *fromval)
2873 struct type *type = toval->type ();
2874 int bits = toval->bitsize ();
2876 toval = ada_coerce_ref (toval);
2877 fromval = ada_coerce_ref (fromval);
2879 if (ada_is_direct_array_type (toval->type ()))
2880 toval = ada_coerce_to_simple_array (toval);
2881 if (ada_is_direct_array_type (fromval->type ()))
2882 fromval = ada_coerce_to_simple_array (fromval);
2884 if (!toval->deprecated_modifiable ())
2885 error (_("Left operand of assignment is not a modifiable lvalue."));
2887 if (toval->lval () == lval_memory
2888 && bits > 0
2889 && (type->code () == TYPE_CODE_FLT
2890 || type->code () == TYPE_CODE_STRUCT))
2892 int len = (toval->bitpos ()
2893 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2894 int from_size;
2895 gdb_byte *buffer = (gdb_byte *) alloca (len);
2896 struct value *val;
2897 CORE_ADDR to_addr = toval->address ();
2899 if (type->code () == TYPE_CODE_FLT)
2900 fromval = value_cast (type, fromval);
2902 read_memory (to_addr, buffer, len);
2903 from_size = fromval->bitsize ();
2904 if (from_size == 0)
2905 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2907 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2908 ULONGEST from_offset = 0;
2909 if (is_big_endian && is_scalar_type (fromval->type ()))
2910 from_offset = from_size - bits;
2911 copy_bitwise (buffer, toval->bitpos (),
2912 fromval->contents ().data (), from_offset,
2913 bits, is_big_endian);
2914 write_memory_with_notification (to_addr, buffer, len);
2916 val = toval->copy ();
2917 memcpy (val->contents_raw ().data (),
2918 fromval->contents ().data (),
2919 type->length ());
2920 val->deprecated_set_type (type);
2922 return val;
2925 return value_assign (toval, fromval);
2929 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2930 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2931 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2932 COMPONENT, and not the inferior's memory. The current contents
2933 of COMPONENT are ignored.
2935 Although not part of the initial design, this function also works
2936 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2937 had a null address, and COMPONENT had an address which is equal to
2938 its offset inside CONTAINER. */
2940 static void
2941 value_assign_to_component (struct value *container, struct value *component,
2942 struct value *val)
2944 LONGEST offset_in_container =
2945 (LONGEST) (component->address () - container->address ());
2946 int bit_offset_in_container =
2947 component->bitpos () - container->bitpos ();
2948 int bits;
2950 val = value_cast (component->type (), val);
2952 if (component->bitsize () == 0)
2953 bits = TARGET_CHAR_BIT * component->type ()->length ();
2954 else
2955 bits = component->bitsize ();
2957 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2959 int src_offset;
2961 if (is_scalar_type (check_typedef (component->type ())))
2962 src_offset
2963 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2964 else
2965 src_offset = 0;
2966 copy_bitwise ((container->contents_writeable ().data ()
2967 + offset_in_container),
2968 container->bitpos () + bit_offset_in_container,
2969 val->contents ().data (), src_offset, bits, 1);
2971 else
2972 copy_bitwise ((container->contents_writeable ().data ()
2973 + offset_in_container),
2974 container->bitpos () + bit_offset_in_container,
2975 val->contents ().data (), 0, bits, 0);
2978 /* Determine if TYPE is an access to an unconstrained array. */
2980 bool
2981 ada_is_access_to_unconstrained_array (struct type *type)
2983 return (type->code () == TYPE_CODE_TYPEDEF
2984 && is_thick_pntr (ada_typedef_target_type (type)));
2987 /* The value of the element of array ARR at the ARITY indices given in IND.
2988 ARR may be either a simple array, GNAT array descriptor, or pointer
2989 thereto. */
2991 struct value *
2992 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2994 int k;
2995 struct value *elt;
2996 struct type *elt_type;
2998 elt = ada_coerce_to_simple_array (arr);
3000 elt_type = ada_check_typedef (elt->type ());
3001 if (elt_type->code () == TYPE_CODE_ARRAY
3002 && elt_type->field (0).bitsize () > 0)
3003 return value_subscript_packed (elt, arity, ind);
3005 for (k = 0; k < arity; k += 1)
3007 struct type *saved_elt_type = elt_type->target_type ();
3009 if (elt_type->code () != TYPE_CODE_ARRAY)
3010 error (_("too many subscripts (%d expected)"), k);
3012 elt = value_subscript (elt, pos_atr (ind[k]));
3014 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3015 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3017 /* The element is a typedef to an unconstrained array,
3018 except that the value_subscript call stripped the
3019 typedef layer. The typedef layer is GNAT's way to
3020 specify that the element is, at the source level, an
3021 access to the unconstrained array, rather than the
3022 unconstrained array. So, we need to restore that
3023 typedef layer, which we can do by forcing the element's
3024 type back to its original type. Otherwise, the returned
3025 value is going to be printed as the array, rather
3026 than as an access. Another symptom of the same issue
3027 would be that an expression trying to dereference the
3028 element would also be improperly rejected. */
3029 elt->deprecated_set_type (saved_elt_type);
3032 elt_type = ada_check_typedef (elt->type ());
3035 return elt;
3038 /* Assuming ARR is a pointer to a GDB array, the value of the element
3039 of *ARR at the ARITY indices given in IND.
3040 Does not read the entire array into memory.
3042 Note: Unlike what one would expect, this function is used instead of
3043 ada_value_subscript for basically all non-packed array types. The reason
3044 for this is that a side effect of doing our own pointer arithmetics instead
3045 of relying on value_subscript is that there is no implicit typedef peeling.
3046 This is important for arrays of array accesses, where it allows us to
3047 preserve the fact that the array's element is an array access, where the
3048 access part os encoded in a typedef layer. */
3050 static struct value *
3051 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3053 int k;
3054 struct value *array_ind = ada_value_ind (arr);
3055 struct type *type
3056 = check_typedef (array_ind->enclosing_type ());
3058 if (type->code () == TYPE_CODE_ARRAY
3059 && type->field (0).bitsize () > 0)
3060 return value_subscript_packed (array_ind, arity, ind);
3062 for (k = 0; k < arity; k += 1)
3064 LONGEST lwb, upb;
3066 if (type->code () != TYPE_CODE_ARRAY)
3067 error (_("too many subscripts (%d expected)"), k);
3068 arr = value_cast (lookup_pointer_type (type->target_type ()),
3069 arr->copy ());
3070 get_discrete_bounds (type->index_type (), &lwb, &upb);
3071 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3072 type = type->target_type ();
3075 return value_ind (arr);
3078 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3079 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3080 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3081 this array is LOW, as per Ada rules. */
3082 static struct value *
3083 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3084 int low, int high)
3086 struct type *type0 = ada_check_typedef (type);
3087 struct type *base_index_type = type0->index_type ()->target_type ();
3088 type_allocator alloc (base_index_type);
3089 struct type *index_type
3090 = create_static_range_type (alloc, base_index_type, low, high);
3091 struct type *slice_type = create_array_type_with_stride
3092 (alloc, type0->target_type (), index_type,
3093 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3094 type0->field (0).bitsize ());
3095 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3096 std::optional<LONGEST> base_low_pos, low_pos;
3097 CORE_ADDR base;
3099 low_pos = discrete_position (base_index_type, low);
3100 base_low_pos = discrete_position (base_index_type, base_low);
3102 if (!low_pos.has_value () || !base_low_pos.has_value ())
3104 warning (_("unable to get positions in slice, use bounds instead"));
3105 low_pos = low;
3106 base_low_pos = base_low;
3109 ULONGEST stride = slice_type->field (0).bitsize () / 8;
3110 if (stride == 0)
3111 stride = type0->target_type ()->length ();
3113 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3114 return value_at_lazy (slice_type, base);
3118 static struct value *
3119 ada_value_slice (struct value *array, int low, int high)
3121 struct type *type = ada_check_typedef (array->type ());
3122 struct type *base_index_type = type->index_type ()->target_type ();
3123 type_allocator alloc (type->index_type ());
3124 struct type *index_type
3125 = create_static_range_type (alloc, type->index_type (), low, high);
3126 struct type *slice_type = create_array_type_with_stride
3127 (alloc, type->target_type (), index_type,
3128 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3129 type->field (0).bitsize ());
3130 std::optional<LONGEST> low_pos, high_pos;
3133 low_pos = discrete_position (base_index_type, low);
3134 high_pos = discrete_position (base_index_type, high);
3136 if (!low_pos.has_value () || !high_pos.has_value ())
3138 warning (_("unable to get positions in slice, use bounds instead"));
3139 low_pos = low;
3140 high_pos = high;
3143 return value_cast (slice_type,
3144 value_slice (array, low, *high_pos - *low_pos + 1));
3147 /* If type is a record type in the form of a standard GNAT array
3148 descriptor, returns the number of dimensions for type. If arr is a
3149 simple array, returns the number of "array of"s that prefix its
3150 type designation. Otherwise, returns 0. */
3153 ada_array_arity (struct type *type)
3155 int arity;
3157 if (type == NULL)
3158 return 0;
3160 type = desc_base_type (type);
3162 arity = 0;
3163 if (type->code () == TYPE_CODE_STRUCT)
3164 return desc_arity (desc_bounds_type (type));
3165 else
3166 while (type->code () == TYPE_CODE_ARRAY)
3168 arity += 1;
3169 type = ada_check_typedef (type->target_type ());
3172 return arity;
3175 /* If TYPE is a record type in the form of a standard GNAT array
3176 descriptor or a simple array type, returns the element type for
3177 TYPE after indexing by NINDICES indices, or by all indices if
3178 NINDICES is -1. Otherwise, returns NULL. */
3180 struct type *
3181 ada_array_element_type (struct type *type, int nindices)
3183 type = desc_base_type (type);
3185 if (type->code () == TYPE_CODE_STRUCT)
3187 int k;
3188 struct type *p_array_type;
3190 p_array_type = desc_data_target_type (type);
3192 k = ada_array_arity (type);
3193 if (k == 0)
3194 return NULL;
3196 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3197 if (nindices >= 0 && k > nindices)
3198 k = nindices;
3199 while (k > 0 && p_array_type != NULL)
3201 p_array_type = ada_check_typedef (p_array_type->target_type ());
3202 k -= 1;
3204 return p_array_type;
3206 else if (type->code () == TYPE_CODE_ARRAY)
3208 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3210 type = type->target_type ();
3211 /* A multi-dimensional array is represented using a sequence
3212 of array types. If one of these types has a name, then
3213 it is not another dimension of the outer array, but
3214 rather the element type of the outermost array. */
3215 if (type->name () != nullptr)
3216 break;
3217 nindices -= 1;
3219 return type;
3222 return NULL;
3225 /* See ada-lang.h. */
3227 struct type *
3228 ada_index_type (struct type *type, int n, const char *name)
3230 struct type *result_type;
3232 type = desc_base_type (type);
3234 if (n < 0 || n > ada_array_arity (type))
3235 error (_("invalid dimension number to '%s"), name);
3237 if (ada_is_simple_array_type (type))
3239 int i;
3241 for (i = 1; i < n; i += 1)
3243 type = ada_check_typedef (type);
3244 type = type->target_type ();
3246 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3247 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3248 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3249 perhaps stabsread.c would make more sense. */
3250 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3251 result_type = NULL;
3253 else
3255 result_type = desc_index_type (desc_bounds_type (type), n);
3256 if (result_type == NULL)
3257 error (_("attempt to take bound of something that is not an array"));
3260 return result_type;
3263 /* Given that arr is an array type, returns the lower bound of the
3264 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3265 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3266 array-descriptor type. It works for other arrays with bounds supplied
3267 by run-time quantities other than discriminants. */
3269 static LONGEST
3270 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3272 struct type *type, *index_type_desc, *index_type;
3273 int i;
3275 gdb_assert (which == 0 || which == 1);
3277 if (ada_is_constrained_packed_array_type (arr_type))
3278 arr_type = decode_constrained_packed_array_type (arr_type);
3280 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3281 return - which;
3283 if (arr_type->code () == TYPE_CODE_PTR)
3284 type = arr_type->target_type ();
3285 else
3286 type = arr_type;
3288 if (type->is_fixed_instance ())
3290 /* The array has already been fixed, so we do not need to
3291 check the parallel ___XA type again. That encoding has
3292 already been applied, so ignore it now. */
3293 index_type_desc = NULL;
3295 else
3297 index_type_desc = ada_find_parallel_type (type, "___XA");
3298 ada_fixup_array_indexes_type (index_type_desc);
3301 if (index_type_desc != NULL)
3302 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3303 NULL);
3304 else
3306 struct type *elt_type = check_typedef (type);
3308 for (i = 1; i < n; i++)
3309 elt_type = check_typedef (elt_type->target_type ());
3311 index_type = elt_type->index_type ();
3314 return (which == 0
3315 ? ada_discrete_type_low_bound (index_type)
3316 : ada_discrete_type_high_bound (index_type));
3319 /* Given that arr is an array value, returns the lower bound of the
3320 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3321 WHICH is 1. This routine will also work for arrays with bounds
3322 supplied by run-time quantities other than discriminants. */
3324 static LONGEST
3325 ada_array_bound (struct value *arr, int n, int which)
3327 struct type *arr_type;
3329 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3330 arr = value_ind (arr);
3331 arr_type = arr->enclosing_type ();
3333 if (ada_is_constrained_packed_array_type (arr_type))
3334 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3335 else if (ada_is_simple_array_type (arr_type))
3336 return ada_array_bound_from_type (arr_type, n, which);
3337 else
3338 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3341 /* Given that arr is an array value, returns the length of the
3342 nth index. This routine will also work for arrays with bounds
3343 supplied by run-time quantities other than discriminants.
3344 Does not work for arrays indexed by enumeration types with representation
3345 clauses at the moment. */
3347 static LONGEST
3348 ada_array_length (struct value *arr, int n)
3350 struct type *arr_type, *index_type;
3351 int low, high;
3353 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3354 arr = value_ind (arr);
3355 arr_type = arr->enclosing_type ();
3357 if (ada_is_constrained_packed_array_type (arr_type))
3358 return ada_array_length (decode_constrained_packed_array (arr), n);
3360 if (ada_is_simple_array_type (arr_type))
3362 low = ada_array_bound_from_type (arr_type, n, 0);
3363 high = ada_array_bound_from_type (arr_type, n, 1);
3365 else
3367 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3368 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3371 arr_type = check_typedef (arr_type);
3372 index_type = ada_index_type (arr_type, n, "length");
3373 if (index_type != NULL)
3375 struct type *base_type;
3376 if (index_type->code () == TYPE_CODE_RANGE)
3377 base_type = index_type->target_type ();
3378 else
3379 base_type = index_type;
3381 low = pos_atr (value_from_longest (base_type, low));
3382 high = pos_atr (value_from_longest (base_type, high));
3384 return high - low + 1;
3387 /* An array whose type is that of ARR_TYPE (an array type), with
3388 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3389 less than LOW, then LOW-1 is used. */
3391 static struct value *
3392 empty_array (struct type *arr_type, int low, int high)
3394 struct type *arr_type0 = ada_check_typedef (arr_type);
3395 type_allocator alloc (arr_type0->index_type ()->target_type ());
3396 struct type *index_type
3397 = create_static_range_type
3398 (alloc, arr_type0->index_type ()->target_type (), low,
3399 high < low ? low - 1 : high);
3400 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3402 return value::allocate (create_array_type (alloc, elt_type, index_type));
3406 /* Name resolution */
3408 /* The "decoded" name for the user-definable Ada operator corresponding
3409 to OP. */
3411 static const char *
3412 ada_decoded_op_name (enum exp_opcode op)
3414 int i;
3416 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3418 if (ada_opname_table[i].op == op)
3419 return ada_opname_table[i].decoded;
3421 error (_("Could not find operator name for opcode"));
3424 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3425 in a listing of choices during disambiguation (see sort_choices, below).
3426 The idea is that overloadings of a subprogram name from the
3427 same package should sort in their source order. We settle for ordering
3428 such symbols by their trailing number (__N or $N). */
3430 static int
3431 encoded_ordered_before (const char *N0, const char *N1)
3433 if (N1 == NULL)
3434 return 0;
3435 else if (N0 == NULL)
3436 return 1;
3437 else
3439 int k0, k1;
3441 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3443 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3445 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3446 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3448 int n0, n1;
3450 n0 = k0;
3451 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3452 n0 -= 1;
3453 n1 = k1;
3454 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3455 n1 -= 1;
3456 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3457 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3459 return (strcmp (N0, N1) < 0);
3463 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3464 encoded names. */
3466 static void
3467 sort_choices (struct block_symbol syms[], int nsyms)
3469 int i;
3471 for (i = 1; i < nsyms; i += 1)
3473 struct block_symbol sym = syms[i];
3474 int j;
3476 for (j = i - 1; j >= 0; j -= 1)
3478 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3479 sym.symbol->linkage_name ()))
3480 break;
3481 syms[j + 1] = syms[j];
3483 syms[j + 1] = sym;
3487 /* Whether GDB should display formals and return types for functions in the
3488 overloads selection menu. */
3489 static bool print_signatures = true;
3491 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3492 all but functions, the signature is just the name of the symbol. For
3493 functions, this is the name of the function, the list of types for formals
3494 and the return type (if any). */
3496 static void
3497 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3498 const struct type_print_options *flags)
3500 struct type *type = sym->type ();
3502 gdb_printf (stream, "%s", sym->print_name ());
3503 if (!print_signatures
3504 || type == NULL
3505 || type->code () != TYPE_CODE_FUNC)
3506 return;
3508 if (type->num_fields () > 0)
3510 int i;
3512 gdb_printf (stream, " (");
3513 for (i = 0; i < type->num_fields (); ++i)
3515 if (i > 0)
3516 gdb_printf (stream, "; ");
3517 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3518 flags);
3520 gdb_printf (stream, ")");
3522 if (type->target_type () != NULL
3523 && type->target_type ()->code () != TYPE_CODE_VOID)
3525 gdb_printf (stream, " return ");
3526 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3530 /* Read and validate a set of numeric choices from the user in the
3531 range 0 .. N_CHOICES-1. Place the results in increasing
3532 order in CHOICES[0 .. N-1], and return N.
3534 The user types choices as a sequence of numbers on one line
3535 separated by blanks, encoding them as follows:
3537 + A choice of 0 means to cancel the selection, throwing an error.
3538 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3539 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3541 The user is not allowed to choose more than MAX_RESULTS values.
3543 ANNOTATION_SUFFIX, if present, is used to annotate the input
3544 prompts (for use with the -f switch). */
3546 static int
3547 get_selections (int *choices, int n_choices, int max_results,
3548 int is_all_choice, const char *annotation_suffix)
3550 const char *args;
3551 const char *prompt;
3552 int n_chosen;
3553 int first_choice = is_all_choice ? 2 : 1;
3555 prompt = getenv ("PS2");
3556 if (prompt == NULL)
3557 prompt = "> ";
3559 std::string buffer;
3560 args = command_line_input (buffer, prompt, annotation_suffix);
3562 if (args == NULL)
3563 error_no_arg (_("one or more choice numbers"));
3565 n_chosen = 0;
3567 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3568 order, as given in args. Choices are validated. */
3569 while (1)
3571 char *args2;
3572 int choice, j;
3574 args = skip_spaces (args);
3575 if (*args == '\0' && n_chosen == 0)
3576 error_no_arg (_("one or more choice numbers"));
3577 else if (*args == '\0')
3578 break;
3580 choice = strtol (args, &args2, 10);
3581 if (args == args2 || choice < 0
3582 || choice > n_choices + first_choice - 1)
3583 error (_("Argument must be choice number"));
3584 args = args2;
3586 if (choice == 0)
3587 error (_("cancelled"));
3589 if (choice < first_choice)
3591 n_chosen = n_choices;
3592 for (j = 0; j < n_choices; j += 1)
3593 choices[j] = j;
3594 break;
3596 choice -= first_choice;
3598 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3602 if (j < 0 || choice != choices[j])
3604 int k;
3606 for (k = n_chosen - 1; k > j; k -= 1)
3607 choices[k + 1] = choices[k];
3608 choices[j + 1] = choice;
3609 n_chosen += 1;
3613 if (n_chosen > max_results)
3614 error (_("Select no more than %d of the above"), max_results);
3616 return n_chosen;
3619 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3620 by asking the user (if necessary), returning the number selected,
3621 and setting the first elements of SYMS items. Error if no symbols
3622 selected. */
3624 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3625 to be re-integrated one of these days. */
3627 static int
3628 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3630 int i;
3631 int *chosen = XALLOCAVEC (int , nsyms);
3632 int n_chosen;
3633 int first_choice = (max_results == 1) ? 1 : 2;
3634 const char *select_mode = multiple_symbols_select_mode ();
3636 if (max_results < 1)
3637 error (_("Request to select 0 symbols!"));
3638 if (nsyms <= 1)
3639 return nsyms;
3641 if (select_mode == multiple_symbols_cancel)
3642 error (_("\
3643 canceled because the command is ambiguous\n\
3644 See set/show multiple-symbol."));
3646 /* If select_mode is "all", then return all possible symbols.
3647 Only do that if more than one symbol can be selected, of course.
3648 Otherwise, display the menu as usual. */
3649 if (select_mode == multiple_symbols_all && max_results > 1)
3650 return nsyms;
3652 gdb_printf (_("[0] cancel\n"));
3653 if (max_results > 1)
3654 gdb_printf (_("[1] all\n"));
3656 sort_choices (syms, nsyms);
3658 for (i = 0; i < nsyms; i += 1)
3660 if (syms[i].symbol == NULL)
3661 continue;
3663 if (syms[i].symbol->aclass () == LOC_BLOCK)
3665 struct symtab_and_line sal =
3666 find_function_start_sal (syms[i].symbol, 1);
3668 gdb_printf ("[%d] ", i + first_choice);
3669 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3670 &type_print_raw_options);
3671 if (sal.symtab == NULL)
3672 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3673 metadata_style.style ().ptr (), nullptr, sal.line);
3674 else
3675 gdb_printf
3676 (_(" at %ps:%d\n"),
3677 styled_string (file_name_style.style (),
3678 symtab_to_filename_for_display (sal.symtab)),
3679 sal.line);
3680 continue;
3682 else
3684 int is_enumeral =
3685 (syms[i].symbol->aclass () == LOC_CONST
3686 && syms[i].symbol->type () != NULL
3687 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3688 struct symtab *symtab = NULL;
3690 if (syms[i].symbol->is_objfile_owned ())
3691 symtab = syms[i].symbol->symtab ();
3693 if (syms[i].symbol->line () != 0 && symtab != NULL)
3695 gdb_printf ("[%d] ", i + first_choice);
3696 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3697 &type_print_raw_options);
3698 gdb_printf (_(" at %s:%d\n"),
3699 symtab_to_filename_for_display (symtab),
3700 syms[i].symbol->line ());
3702 else if (is_enumeral
3703 && syms[i].symbol->type ()->name () != NULL)
3705 gdb_printf (("[%d] "), i + first_choice);
3706 ada_print_type (syms[i].symbol->type (), NULL,
3707 gdb_stdout, -1, 0, &type_print_raw_options);
3708 gdb_printf (_("'(%s) (enumeral)\n"),
3709 syms[i].symbol->print_name ());
3711 else
3713 gdb_printf ("[%d] ", i + first_choice);
3714 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3715 &type_print_raw_options);
3717 if (symtab != NULL)
3718 gdb_printf (is_enumeral
3719 ? _(" in %s (enumeral)\n")
3720 : _(" at %s:?\n"),
3721 symtab_to_filename_for_display (symtab));
3722 else
3723 gdb_printf (is_enumeral
3724 ? _(" (enumeral)\n")
3725 : _(" at ?\n"));
3730 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3731 "overload-choice");
3733 for (i = 0; i < n_chosen; i += 1)
3734 syms[i] = syms[chosen[i]];
3736 return n_chosen;
3739 /* See ada-lang.h. */
3741 block_symbol
3742 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3743 int nargs, value *argvec[])
3745 if (possible_user_operator_p (op, argvec))
3747 std::vector<struct block_symbol> candidates
3748 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3749 NULL, SEARCH_VFT);
3751 int i = ada_resolve_function (candidates, argvec,
3752 nargs, ada_decoded_op_name (op), NULL,
3753 parse_completion);
3754 if (i >= 0)
3755 return candidates[i];
3757 return {};
3760 /* See ada-lang.h. */
3762 block_symbol
3763 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3764 struct type *context_type,
3765 bool parse_completion,
3766 int nargs, value *argvec[],
3767 innermost_block_tracker *tracker)
3769 std::vector<struct block_symbol> candidates
3770 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3772 int i;
3773 if (candidates.size () == 1)
3774 i = 0;
3775 else
3777 i = ada_resolve_function
3778 (candidates,
3779 argvec, nargs,
3780 sym->linkage_name (),
3781 context_type, parse_completion);
3782 if (i < 0)
3783 error (_("Could not find a match for %s"), sym->print_name ());
3786 tracker->update (candidates[i]);
3787 return candidates[i];
3790 /* Resolve a mention of a name where the context type is an
3791 enumeration type. */
3793 static int
3794 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3795 const char *name, struct type *context_type,
3796 bool parse_completion)
3798 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3799 context_type = ada_check_typedef (context_type);
3801 /* We already know the name matches, so we're just looking for
3802 an element of the correct enum type. */
3803 struct type *type1 = context_type;
3804 for (int i = 0; i < syms.size (); ++i)
3806 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3807 if (type1 == type2)
3808 return i;
3811 for (int i = 0; i < syms.size (); ++i)
3813 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3814 if (type1->num_fields () != type2->num_fields ())
3815 continue;
3816 if (strcmp (type1->name (), type2->name ()) != 0)
3817 continue;
3818 if (ada_identical_enum_types_p (type1, type2))
3819 return i;
3822 error (_("No name '%s' in enumeration type '%s'"), name,
3823 ada_type_name (context_type));
3826 /* See ada-lang.h. */
3828 block_symbol
3829 ada_resolve_variable (struct symbol *sym, const struct block *block,
3830 struct type *context_type,
3831 bool parse_completion,
3832 int deprocedure_p,
3833 innermost_block_tracker *tracker)
3835 std::vector<struct block_symbol> candidates
3836 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3838 if (std::any_of (candidates.begin (),
3839 candidates.end (),
3840 [] (block_symbol &bsym)
3842 switch (bsym.symbol->aclass ())
3844 case LOC_REGISTER:
3845 case LOC_ARG:
3846 case LOC_REF_ARG:
3847 case LOC_REGPARM_ADDR:
3848 case LOC_LOCAL:
3849 case LOC_COMPUTED:
3850 return true;
3851 default:
3852 return false;
3856 /* Types tend to get re-introduced locally, so if there
3857 are any local symbols that are not types, first filter
3858 out all types. */
3859 candidates.erase
3860 (std::remove_if
3861 (candidates.begin (),
3862 candidates.end (),
3863 [] (block_symbol &bsym)
3865 return bsym.symbol->aclass () == LOC_TYPEDEF;
3867 candidates.end ());
3870 /* Filter out artificial symbols. */
3871 candidates.erase
3872 (std::remove_if
3873 (candidates.begin (),
3874 candidates.end (),
3875 [] (block_symbol &bsym)
3877 return bsym.symbol->is_artificial ();
3879 candidates.end ());
3881 int i;
3882 if (candidates.empty ())
3883 error (_("No definition found for %s"), sym->print_name ());
3884 else if (candidates.size () == 1)
3885 i = 0;
3886 else if (context_type != nullptr
3887 && context_type->code () == TYPE_CODE_ENUM)
3888 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3889 parse_completion);
3890 else if (context_type == nullptr
3891 && symbols_are_identical_enums (candidates))
3893 /* If all the remaining symbols are identical enumerals, then
3894 just keep the first one and discard the rest.
3896 Unlike what we did previously, we do not discard any entry
3897 unless they are ALL identical. This is because the symbol
3898 comparison is not a strict comparison, but rather a practical
3899 comparison. If all symbols are considered identical, then
3900 we can just go ahead and use the first one and discard the rest.
3901 But if we cannot reduce the list to a single element, we have
3902 to ask the user to disambiguate anyways. And if we have to
3903 present a multiple-choice menu, it's less confusing if the list
3904 isn't missing some choices that were identical and yet distinct. */
3905 candidates.resize (1);
3906 i = 0;
3908 else if (deprocedure_p && !is_nonfunction (candidates))
3910 i = ada_resolve_function
3911 (candidates, NULL, 0,
3912 sym->linkage_name (),
3913 context_type, parse_completion);
3914 if (i < 0)
3915 error (_("Could not find a match for %s"), sym->print_name ());
3917 else
3919 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3920 user_select_syms (candidates.data (), candidates.size (), 1);
3921 i = 0;
3924 tracker->update (candidates[i]);
3925 return candidates[i];
3928 static bool ada_type_match (struct type *ftype, struct type *atype);
3930 /* Helper for ada_type_match that checks that two array types are
3931 compatible. As with that function, FTYPE is the formal type and
3932 ATYPE is the actual type. */
3934 static bool
3935 ada_type_match_arrays (struct type *ftype, struct type *atype)
3937 if (ftype->code () != TYPE_CODE_ARRAY
3938 && !ada_is_array_descriptor_type (ftype))
3939 return false;
3940 if (atype->code () != TYPE_CODE_ARRAY
3941 && !ada_is_array_descriptor_type (atype))
3942 return false;
3944 if (ada_array_arity (ftype) != ada_array_arity (atype))
3945 return false;
3947 struct type *f_elt_type = ada_array_element_type (ftype, -1);
3948 struct type *a_elt_type = ada_array_element_type (atype, -1);
3949 return ada_type_match (f_elt_type, a_elt_type);
3952 /* Return non-zero if formal type FTYPE matches actual type ATYPE.
3953 The term "match" here is rather loose. The match is heuristic and
3954 liberal -- while it tries to reject matches that are obviously
3955 incorrect, it may still let through some that do not strictly
3956 correspond to Ada rules. */
3958 static bool
3959 ada_type_match (struct type *ftype, struct type *atype)
3961 ftype = ada_check_typedef (ftype);
3962 atype = ada_check_typedef (atype);
3964 if (ftype->code () == TYPE_CODE_REF)
3965 ftype = ftype->target_type ();
3966 if (atype->code () == TYPE_CODE_REF)
3967 atype = atype->target_type ();
3969 switch (ftype->code ())
3971 default:
3972 return ftype->code () == atype->code ();
3973 case TYPE_CODE_PTR:
3974 if (atype->code () != TYPE_CODE_PTR)
3975 return false;
3976 atype = atype->target_type ();
3977 /* This can only happen if the actual argument is 'null'. */
3978 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3979 return true;
3980 return ada_type_match (ftype->target_type (), atype);
3981 case TYPE_CODE_INT:
3982 case TYPE_CODE_ENUM:
3983 case TYPE_CODE_RANGE:
3984 switch (atype->code ())
3986 case TYPE_CODE_INT:
3987 case TYPE_CODE_ENUM:
3988 case TYPE_CODE_RANGE:
3989 return true;
3990 default:
3991 return false;
3994 case TYPE_CODE_STRUCT:
3995 if (!ada_is_array_descriptor_type (ftype))
3996 return (atype->code () == TYPE_CODE_STRUCT
3997 && !ada_is_array_descriptor_type (atype));
3999 [[fallthrough]];
4000 case TYPE_CODE_ARRAY:
4001 return ada_type_match_arrays (ftype, atype);
4003 case TYPE_CODE_UNION:
4004 case TYPE_CODE_FLT:
4005 return (atype->code () == ftype->code ());
4009 /* Return non-zero if the formals of FUNC "sufficiently match" the
4010 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
4011 may also be an enumeral, in which case it is treated as a 0-
4012 argument function. */
4014 static int
4015 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
4017 int i;
4018 struct type *func_type = func->type ();
4020 if (func->aclass () == LOC_CONST
4021 && func_type->code () == TYPE_CODE_ENUM)
4022 return (n_actuals == 0);
4023 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
4024 return 0;
4026 if (func_type->num_fields () != n_actuals)
4027 return 0;
4029 for (i = 0; i < n_actuals; i += 1)
4031 if (actuals[i] == NULL)
4032 return 0;
4033 else
4035 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
4036 struct type *atype = ada_check_typedef (actuals[i]->type ());
4038 if (!ada_type_match (ftype, atype))
4039 return 0;
4042 return 1;
4045 /* False iff function type FUNC_TYPE definitely does not produce a value
4046 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4047 FUNC_TYPE is not a valid function type with a non-null return type
4048 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4050 static int
4051 return_match (struct type *func_type, struct type *context_type)
4053 struct type *return_type;
4055 if (func_type == NULL)
4056 return 1;
4058 if (func_type->code () == TYPE_CODE_FUNC)
4059 return_type = get_base_type (func_type->target_type ());
4060 else
4061 return_type = get_base_type (func_type);
4062 if (return_type == NULL)
4063 return 1;
4065 context_type = get_base_type (context_type);
4067 if (return_type->code () == TYPE_CODE_ENUM)
4068 return context_type == NULL || return_type == context_type;
4069 else if (context_type == NULL)
4070 return return_type->code () != TYPE_CODE_VOID;
4071 else
4072 return return_type->code () == context_type->code ();
4076 /* Returns the index in SYMS that contains the symbol for the
4077 function (if any) that matches the types of the NARGS arguments in
4078 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4079 that returns that type, then eliminate matches that don't. If
4080 CONTEXT_TYPE is void and there is at least one match that does not
4081 return void, eliminate all matches that do.
4083 Asks the user if there is more than one match remaining. Returns -1
4084 if there is no such symbol or none is selected. NAME is used
4085 solely for messages. May re-arrange and modify SYMS in
4086 the process; the index returned is for the modified vector. */
4088 static int
4089 ada_resolve_function (std::vector<struct block_symbol> &syms,
4090 struct value **args, int nargs,
4091 const char *name, struct type *context_type,
4092 bool parse_completion)
4094 int fallback;
4095 int k;
4096 int m; /* Number of hits */
4098 m = 0;
4099 /* In the first pass of the loop, we only accept functions matching
4100 context_type. If none are found, we add a second pass of the loop
4101 where every function is accepted. */
4102 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4104 for (k = 0; k < syms.size (); k += 1)
4106 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4108 if (ada_args_match (syms[k].symbol, args, nargs)
4109 && (fallback || return_match (type, context_type)))
4111 syms[m] = syms[k];
4112 m += 1;
4117 /* If we got multiple matches, ask the user which one to use. Don't do this
4118 interactive thing during completion, though, as the purpose of the
4119 completion is providing a list of all possible matches. Prompting the
4120 user to filter it down would be completely unexpected in this case. */
4121 if (m == 0)
4122 return -1;
4123 else if (m > 1 && !parse_completion)
4125 gdb_printf (_("Multiple matches for %s\n"), name);
4126 user_select_syms (syms.data (), m, 1);
4127 return 0;
4129 return 0;
4132 /* Type-class predicates */
4134 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4135 or FLOAT). */
4137 static int
4138 numeric_type_p (struct type *type)
4140 if (type == NULL)
4141 return 0;
4142 else
4144 switch (type->code ())
4146 case TYPE_CODE_INT:
4147 case TYPE_CODE_FLT:
4148 case TYPE_CODE_FIXED_POINT:
4149 return 1;
4150 case TYPE_CODE_RANGE:
4151 return (type == type->target_type ()
4152 || numeric_type_p (type->target_type ()));
4153 default:
4154 return 0;
4159 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4161 static int
4162 integer_type_p (struct type *type)
4164 if (type == NULL)
4165 return 0;
4166 else
4168 switch (type->code ())
4170 case TYPE_CODE_INT:
4171 return 1;
4172 case TYPE_CODE_RANGE:
4173 return (type == type->target_type ()
4174 || integer_type_p (type->target_type ()));
4175 default:
4176 return 0;
4181 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4183 static int
4184 scalar_type_p (struct type *type)
4186 if (type == NULL)
4187 return 0;
4188 else
4190 switch (type->code ())
4192 case TYPE_CODE_INT:
4193 case TYPE_CODE_RANGE:
4194 case TYPE_CODE_ENUM:
4195 case TYPE_CODE_FLT:
4196 case TYPE_CODE_FIXED_POINT:
4197 return 1;
4198 default:
4199 return 0;
4204 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4205 This essentially means one of (INT, RANGE, ENUM) -- but note that
4206 "enum" includes character and boolean as well. */
4208 static int
4209 discrete_type_p (struct type *type)
4211 if (type == NULL)
4212 return 0;
4213 else
4215 switch (type->code ())
4217 case TYPE_CODE_INT:
4218 case TYPE_CODE_RANGE:
4219 case TYPE_CODE_ENUM:
4220 case TYPE_CODE_BOOL:
4221 case TYPE_CODE_CHAR:
4222 return 1;
4223 default:
4224 return 0;
4229 /* Returns non-zero if OP with operands in the vector ARGS could be
4230 a user-defined function. Errs on the side of pre-defined operators
4231 (i.e., result 0). */
4233 static int
4234 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4236 struct type *type0 =
4237 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4238 struct type *type1 =
4239 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4241 if (type0 == NULL)
4242 return 0;
4244 switch (op)
4246 default:
4247 return 0;
4249 case BINOP_ADD:
4250 case BINOP_SUB:
4251 case BINOP_MUL:
4252 case BINOP_DIV:
4253 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4255 case BINOP_REM:
4256 case BINOP_MOD:
4257 case BINOP_BITWISE_AND:
4258 case BINOP_BITWISE_IOR:
4259 case BINOP_BITWISE_XOR:
4260 return (!(integer_type_p (type0) && integer_type_p (type1)));
4262 case BINOP_EQUAL:
4263 case BINOP_NOTEQUAL:
4264 case BINOP_LESS:
4265 case BINOP_GTR:
4266 case BINOP_LEQ:
4267 case BINOP_GEQ:
4268 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4270 case BINOP_CONCAT:
4271 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4273 case BINOP_EXP:
4274 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4276 case UNOP_NEG:
4277 case UNOP_PLUS:
4278 case UNOP_LOGICAL_NOT:
4279 case UNOP_ABS:
4280 return (!numeric_type_p (type0));
4285 /* Renaming */
4287 /* NOTES:
4289 1. In the following, we assume that a renaming type's name may
4290 have an ___XD suffix. It would be nice if this went away at some
4291 point.
4292 2. We handle both the (old) purely type-based representation of
4293 renamings and the (new) variable-based encoding. At some point,
4294 it is devoutly to be hoped that the former goes away
4295 (FIXME: hilfinger-2007-07-09).
4296 3. Subprogram renamings are not implemented, although the XRS
4297 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4299 /* If SYM encodes a renaming,
4301 <renaming> renames <renamed entity>,
4303 sets *LEN to the length of the renamed entity's name,
4304 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4305 the string describing the subcomponent selected from the renamed
4306 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4307 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4308 are undefined). Otherwise, returns a value indicating the category
4309 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4310 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4311 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4312 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4313 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4314 may be NULL, in which case they are not assigned.
4316 [Currently, however, GCC does not generate subprogram renamings.] */
4318 enum ada_renaming_category
4319 ada_parse_renaming (struct symbol *sym,
4320 const char **renamed_entity, int *len,
4321 const char **renaming_expr)
4323 enum ada_renaming_category kind;
4324 const char *info;
4325 const char *suffix;
4327 if (sym == NULL)
4328 return ADA_NOT_RENAMING;
4329 switch (sym->aclass ())
4331 default:
4332 return ADA_NOT_RENAMING;
4333 case LOC_LOCAL:
4334 case LOC_STATIC:
4335 case LOC_COMPUTED:
4336 case LOC_OPTIMIZED_OUT:
4337 info = strstr (sym->linkage_name (), "___XR");
4338 if (info == NULL)
4339 return ADA_NOT_RENAMING;
4340 switch (info[5])
4342 case '_':
4343 kind = ADA_OBJECT_RENAMING;
4344 info += 6;
4345 break;
4346 case 'E':
4347 kind = ADA_EXCEPTION_RENAMING;
4348 info += 7;
4349 break;
4350 case 'P':
4351 kind = ADA_PACKAGE_RENAMING;
4352 info += 7;
4353 break;
4354 case 'S':
4355 kind = ADA_SUBPROGRAM_RENAMING;
4356 info += 7;
4357 break;
4358 default:
4359 return ADA_NOT_RENAMING;
4363 if (renamed_entity != NULL)
4364 *renamed_entity = info;
4365 suffix = strstr (info, "___XE");
4366 if (suffix == NULL || suffix == info)
4367 return ADA_NOT_RENAMING;
4368 if (len != NULL)
4369 *len = strlen (info) - strlen (suffix);
4370 suffix += 5;
4371 if (renaming_expr != NULL)
4372 *renaming_expr = suffix;
4373 return kind;
4376 /* Compute the value of the given RENAMING_SYM, which is expected to
4377 be a symbol encoding a renaming expression. BLOCK is the block
4378 used to evaluate the renaming. */
4380 static struct value *
4381 ada_read_renaming_var_value (struct symbol *renaming_sym,
4382 const struct block *block)
4384 const char *sym_name;
4386 sym_name = renaming_sym->linkage_name ();
4387 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4388 return expr->evaluate ();
4392 /* Evaluation: Function Calls */
4394 /* Return an lvalue containing the value VAL. This is the identity on
4395 lvalues, and otherwise has the side-effect of allocating memory
4396 in the inferior where a copy of the value contents is copied. */
4398 static struct value *
4399 ensure_lval (struct value *val)
4401 if (val->lval () == not_lval
4402 || val->lval () == lval_internalvar)
4404 int len = ada_check_typedef (val->type ())->length ();
4405 const CORE_ADDR addr =
4406 value_as_long (value_allocate_space_in_inferior (len));
4408 val->set_lval (lval_memory);
4409 val->set_address (addr);
4410 write_memory (addr, val->contents ().data (), len);
4413 return val;
4416 /* Given ARG, a value of type (pointer or reference to a)*
4417 structure/union, extract the component named NAME from the ultimate
4418 target structure/union and return it as a value with its
4419 appropriate type.
4421 The routine searches for NAME among all members of the structure itself
4422 and (recursively) among all members of any wrapper members
4423 (e.g., '_parent').
4425 If NO_ERR, then simply return NULL in case of error, rather than
4426 calling error. */
4428 static struct value *
4429 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4431 struct type *t, *t1;
4432 struct value *v;
4433 int check_tag;
4435 v = NULL;
4436 t1 = t = ada_check_typedef (arg->type ());
4437 if (t->code () == TYPE_CODE_REF)
4439 t1 = t->target_type ();
4440 if (t1 == NULL)
4441 goto BadValue;
4442 t1 = ada_check_typedef (t1);
4443 if (t1->code () == TYPE_CODE_PTR)
4445 arg = coerce_ref (arg);
4446 t = t1;
4450 while (t->code () == TYPE_CODE_PTR)
4452 t1 = t->target_type ();
4453 if (t1 == NULL)
4454 goto BadValue;
4455 t1 = ada_check_typedef (t1);
4456 if (t1->code () == TYPE_CODE_PTR)
4458 arg = value_ind (arg);
4459 t = t1;
4461 else
4462 break;
4465 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4466 goto BadValue;
4468 if (t1 == t)
4469 v = ada_search_struct_field (name, arg, 0, t);
4470 else
4472 int bit_offset, bit_size, byte_offset;
4473 struct type *field_type;
4474 CORE_ADDR address;
4476 if (t->code () == TYPE_CODE_PTR)
4477 address = ada_value_ind (arg)->address ();
4478 else
4479 address = ada_coerce_ref (arg)->address ();
4481 /* Check to see if this is a tagged type. We also need to handle
4482 the case where the type is a reference to a tagged type, but
4483 we have to be careful to exclude pointers to tagged types.
4484 The latter should be shown as usual (as a pointer), whereas
4485 a reference should mostly be transparent to the user. */
4487 if (ada_is_tagged_type (t1, 0)
4488 || (t1->code () == TYPE_CODE_REF
4489 && ada_is_tagged_type (t1->target_type (), 0)))
4491 /* We first try to find the searched field in the current type.
4492 If not found then let's look in the fixed type. */
4494 if (!find_struct_field (name, t1, 0,
4495 nullptr, nullptr, nullptr,
4496 nullptr, nullptr))
4497 check_tag = 1;
4498 else
4499 check_tag = 0;
4501 else
4502 check_tag = 0;
4504 /* Convert to fixed type in all cases, so that we have proper
4505 offsets to each field in unconstrained record types. */
4506 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4507 address, NULL, check_tag);
4509 /* Resolve the dynamic type as well. */
4510 arg = value_from_contents_and_address (t1, nullptr, address);
4511 t1 = arg->type ();
4513 if (find_struct_field (name, t1, 0,
4514 &field_type, &byte_offset, &bit_offset,
4515 &bit_size, NULL))
4517 if (bit_size != 0)
4519 if (t->code () == TYPE_CODE_REF)
4520 arg = ada_coerce_ref (arg);
4521 else
4522 arg = ada_value_ind (arg);
4523 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4524 bit_offset, bit_size,
4525 field_type);
4527 else
4528 v = value_at_lazy (field_type, address + byte_offset);
4532 if (v != NULL || no_err)
4533 return v;
4534 else
4535 error (_("There is no member named %s."), name);
4537 BadValue:
4538 if (no_err)
4539 return NULL;
4540 else
4541 error (_("Attempt to extract a component of "
4542 "a value that is not a record."));
4545 /* Return the value ACTUAL, converted to be an appropriate value for a
4546 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4547 allocating any necessary descriptors (fat pointers), or copies of
4548 values not residing in memory, updating it as needed. */
4550 struct value *
4551 ada_convert_actual (struct value *actual, struct type *formal_type0)
4553 struct type *actual_type = ada_check_typedef (actual->type ());
4554 struct type *formal_type = ada_check_typedef (formal_type0);
4555 struct type *formal_target =
4556 formal_type->code () == TYPE_CODE_PTR
4557 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4558 struct type *actual_target =
4559 actual_type->code () == TYPE_CODE_PTR
4560 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4562 if (ada_is_array_descriptor_type (formal_target)
4563 && actual_target->code () == TYPE_CODE_ARRAY)
4564 return make_array_descriptor (formal_type, actual);
4565 else if (formal_type->code () == TYPE_CODE_PTR
4566 || formal_type->code () == TYPE_CODE_REF)
4568 struct value *result;
4570 if (formal_target->code () == TYPE_CODE_ARRAY
4571 && ada_is_array_descriptor_type (actual_target))
4572 result = desc_data (actual);
4573 else if (formal_type->code () != TYPE_CODE_PTR)
4575 if (actual->lval () != lval_memory)
4577 struct value *val;
4579 actual_type = ada_check_typedef (actual->type ());
4580 val = value::allocate (actual_type);
4581 copy (actual->contents (), val->contents_raw ());
4582 actual = ensure_lval (val);
4584 result = value_addr (actual);
4586 else
4587 return actual;
4588 return value_cast_pointers (formal_type, result, 0);
4590 else if (actual_type->code () == TYPE_CODE_PTR)
4591 return ada_value_ind (actual);
4592 else if (ada_is_aligner_type (formal_type))
4594 /* We need to turn this parameter into an aligner type
4595 as well. */
4596 struct value *aligner = value::allocate (formal_type);
4597 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4599 value_assign_to_component (aligner, component, actual);
4600 return aligner;
4603 return actual;
4606 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4607 type TYPE. This is usually an inefficient no-op except on some targets
4608 (such as AVR) where the representation of a pointer and an address
4609 differs. */
4611 static CORE_ADDR
4612 value_pointer (struct value *value, struct type *type)
4614 unsigned len = type->length ();
4615 gdb_byte *buf = (gdb_byte *) alloca (len);
4616 CORE_ADDR addr;
4618 addr = value->address ();
4619 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4620 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4621 return addr;
4625 /* Push a descriptor of type TYPE for array value ARR on the stack at
4626 *SP, updating *SP to reflect the new descriptor. Return either
4627 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4628 to-descriptor type rather than a descriptor type), a struct value *
4629 representing a pointer to this descriptor. */
4631 static struct value *
4632 make_array_descriptor (struct type *type, struct value *arr)
4634 struct type *bounds_type = desc_bounds_type (type);
4635 struct type *desc_type = desc_base_type (type);
4636 struct value *descriptor = value::allocate (desc_type);
4637 struct value *bounds = value::allocate (bounds_type);
4638 int i;
4640 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4641 i > 0; i -= 1)
4643 modify_field (bounds->type (),
4644 bounds->contents_writeable ().data (),
4645 ada_array_bound (arr, i, 0),
4646 desc_bound_bitpos (bounds_type, i, 0),
4647 desc_bound_bitsize (bounds_type, i, 0));
4648 modify_field (bounds->type (),
4649 bounds->contents_writeable ().data (),
4650 ada_array_bound (arr, i, 1),
4651 desc_bound_bitpos (bounds_type, i, 1),
4652 desc_bound_bitsize (bounds_type, i, 1));
4655 bounds = ensure_lval (bounds);
4657 modify_field (descriptor->type (),
4658 descriptor->contents_writeable ().data (),
4659 value_pointer (ensure_lval (arr),
4660 desc_type->field (0).type ()),
4661 fat_pntr_data_bitpos (desc_type),
4662 fat_pntr_data_bitsize (desc_type));
4664 modify_field (descriptor->type (),
4665 descriptor->contents_writeable ().data (),
4666 value_pointer (bounds,
4667 desc_type->field (1).type ()),
4668 fat_pntr_bounds_bitpos (desc_type),
4669 fat_pntr_bounds_bitsize (desc_type));
4671 descriptor = ensure_lval (descriptor);
4673 if (type->code () == TYPE_CODE_PTR)
4674 return value_addr (descriptor);
4675 else
4676 return descriptor;
4679 /* Symbol Cache Module */
4681 /* Performance measurements made as of 2010-01-15 indicate that
4682 this cache does bring some noticeable improvements. Depending
4683 on the type of entity being printed, the cache can make it as much
4684 as an order of magnitude faster than without it.
4686 The descriptive type DWARF extension has significantly reduced
4687 the need for this cache, at least when DWARF is being used. However,
4688 even in this case, some expensive name-based symbol searches are still
4689 sometimes necessary - to find an XVZ variable, mostly. */
4691 /* Clear all entries from the symbol cache. */
4693 static void
4694 ada_clear_symbol_cache (program_space *pspace)
4696 ada_pspace_data_handle.clear (pspace);
4699 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4700 Return 1 if found, 0 otherwise.
4702 If an entry was found and SYM is not NULL, set *SYM to the entry's
4703 SYM. Same principle for BLOCK if not NULL. */
4705 static int
4706 lookup_cached_symbol (const char *name, domain_search_flags domain,
4707 struct symbol **sym, const struct block **block)
4709 htab_t tab = get_ada_pspace_data (current_program_space);
4710 cache_entry_search search;
4711 search.name = name;
4712 search.domain = domain;
4714 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4715 search.hash ());
4716 if (e == nullptr)
4717 return 0;
4718 if (sym != nullptr)
4719 *sym = e->sym;
4720 if (block != nullptr)
4721 *block = e->block;
4722 return 1;
4725 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4726 in domain DOMAIN, save this result in our symbol cache. */
4728 static void
4729 cache_symbol (const char *name, domain_search_flags domain,
4730 struct symbol *sym, const struct block *block)
4732 /* Symbols for builtin types don't have a block.
4733 For now don't cache such symbols. */
4734 if (sym != NULL && !sym->is_objfile_owned ())
4735 return;
4737 /* If the symbol is a local symbol, then do not cache it, as a search
4738 for that symbol depends on the context. To determine whether
4739 the symbol is local or not, we check the block where we found it
4740 against the global and static blocks of its associated symtab. */
4741 if (sym != nullptr)
4743 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4745 if (bv.global_block () != block && bv.static_block () != block)
4746 return;
4749 htab_t tab = get_ada_pspace_data (current_program_space);
4750 cache_entry_search search;
4751 search.name = name;
4752 search.domain = domain;
4754 void **slot = htab_find_slot_with_hash (tab, &search,
4755 search.hash (), INSERT);
4757 cache_entry *e = new cache_entry;
4758 e->name = name;
4759 e->domain = domain;
4760 e->sym = sym;
4761 e->block = block;
4763 *slot = e;
4766 /* Symbol Lookup */
4768 /* Return the symbol name match type that should be used used when
4769 searching for all symbols matching LOOKUP_NAME.
4771 LOOKUP_NAME is expected to be a symbol name after transformation
4772 for Ada lookups. */
4774 static symbol_name_match_type
4775 name_match_type_from_name (const char *lookup_name)
4777 return (strstr (lookup_name, "__") == NULL
4778 ? symbol_name_match_type::WILD
4779 : symbol_name_match_type::FULL);
4782 /* Return the result of a standard (literal, C-like) lookup of NAME in
4783 given DOMAIN, visible from lexical block BLOCK. */
4785 static struct symbol *
4786 standard_lookup (const char *name, const struct block *block,
4787 domain_search_flags domain)
4789 /* Initialize it just to avoid a GCC false warning. */
4790 struct block_symbol sym = {};
4792 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4793 return sym.symbol;
4794 ada_lookup_encoded_symbol (name, block, domain, &sym);
4795 cache_symbol (name, domain, sym.symbol, sym.block);
4796 return sym.symbol;
4800 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4801 in the symbol fields of SYMS. We treat enumerals as functions,
4802 since they contend in overloading in the same way. */
4803 static int
4804 is_nonfunction (const std::vector<struct block_symbol> &syms)
4806 for (const block_symbol &sym : syms)
4807 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4808 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4809 || sym.symbol->aclass () != LOC_CONST))
4810 return 1;
4812 return 0;
4815 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4816 struct types. Otherwise, they may not. */
4818 static int
4819 equiv_types (struct type *type0, struct type *type1)
4821 if (type0 == type1)
4822 return 1;
4823 if (type0 == NULL || type1 == NULL
4824 || type0->code () != type1->code ())
4825 return 0;
4826 if ((type0->code () == TYPE_CODE_STRUCT
4827 || type0->code () == TYPE_CODE_ENUM)
4828 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4829 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4830 return 1;
4832 return 0;
4835 /* True iff SYM0 represents the same entity as SYM1, or one that is
4836 no more defined than that of SYM1. */
4838 static int
4839 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4841 if (sym0 == sym1)
4842 return 1;
4843 if (sym0->domain () != sym1->domain ()
4844 || sym0->aclass () != sym1->aclass ())
4845 return 0;
4847 switch (sym0->aclass ())
4849 case LOC_UNDEF:
4850 return 1;
4851 case LOC_TYPEDEF:
4853 struct type *type0 = sym0->type ();
4854 struct type *type1 = sym1->type ();
4855 const char *name0 = sym0->linkage_name ();
4856 const char *name1 = sym1->linkage_name ();
4857 int len0 = strlen (name0);
4859 return
4860 type0->code () == type1->code ()
4861 && (equiv_types (type0, type1)
4862 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4863 && startswith (name1 + len0, "___XV")));
4865 case LOC_CONST:
4866 return sym0->value_longest () == sym1->value_longest ()
4867 && equiv_types (sym0->type (), sym1->type ());
4869 case LOC_STATIC:
4871 const char *name0 = sym0->linkage_name ();
4872 const char *name1 = sym1->linkage_name ();
4873 return (strcmp (name0, name1) == 0
4874 && sym0->value_address () == sym1->value_address ());
4877 default:
4878 return 0;
4882 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4883 records in RESULT. Do nothing if SYM is a duplicate. */
4885 static void
4886 add_defn_to_vec (std::vector<struct block_symbol> &result,
4887 struct symbol *sym,
4888 const struct block *block)
4890 /* Do not try to complete stub types, as the debugger is probably
4891 already scanning all symbols matching a certain name at the
4892 time when this function is called. Trying to replace the stub
4893 type by its associated full type will cause us to restart a scan
4894 which may lead to an infinite recursion. Instead, the client
4895 collecting the matching symbols will end up collecting several
4896 matches, with at least one of them complete. It can then filter
4897 out the stub ones if needed. */
4899 for (int i = result.size () - 1; i >= 0; i -= 1)
4901 if (lesseq_defined_than (sym, result[i].symbol))
4902 return;
4903 else if (lesseq_defined_than (result[i].symbol, sym))
4905 result[i].symbol = sym;
4906 result[i].block = block;
4907 return;
4911 struct block_symbol info;
4912 info.symbol = sym;
4913 info.block = block;
4914 result.push_back (info);
4917 /* Return a bound minimal symbol matching NAME according to Ada
4918 decoding rules. Returns an invalid symbol if there is no such
4919 minimal symbol. Names prefixed with "standard__" are handled
4920 specially: "standard__" is first stripped off, and only static and
4921 global symbols are searched. */
4923 struct bound_minimal_symbol
4924 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4926 struct bound_minimal_symbol result;
4928 symbol_name_match_type match_type = name_match_type_from_name (name);
4929 lookup_name_info lookup_name (name, match_type);
4931 symbol_name_matcher_ftype *match_name
4932 = ada_get_symbol_name_matcher (lookup_name);
4934 gdbarch_iterate_over_objfiles_in_search_order
4935 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
4936 [&result, lookup_name, match_name] (struct objfile *obj)
4938 for (minimal_symbol *msymbol : obj->msymbols ())
4940 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4941 && msymbol->type () != mst_solib_trampoline)
4943 result.minsym = msymbol;
4944 result.objfile = obj;
4945 return 1;
4949 return 0;
4950 }, objfile);
4952 return result;
4955 /* True if TYPE is definitely an artificial type supplied to a symbol
4956 for which no debugging information was given in the symbol file. */
4958 static int
4959 is_nondebugging_type (struct type *type)
4961 const char *name = ada_type_name (type);
4963 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4966 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4967 that are deemed "identical" for practical purposes.
4969 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4970 types and that their number of enumerals is identical (in other
4971 words, type1->num_fields () == type2->num_fields ()). */
4973 static int
4974 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4976 int i;
4978 /* The heuristic we use here is fairly conservative. We consider
4979 that 2 enumerate types are identical if they have the same
4980 number of enumerals and that all enumerals have the same
4981 underlying value and name. */
4983 /* All enums in the type should have an identical underlying value. */
4984 for (i = 0; i < type1->num_fields (); i++)
4985 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4986 return 0;
4988 /* All enumerals should also have the same name (modulo any numerical
4989 suffix). */
4990 for (i = 0; i < type1->num_fields (); i++)
4992 const char *name_1 = type1->field (i).name ();
4993 const char *name_2 = type2->field (i).name ();
4994 int len_1 = strlen (name_1);
4995 int len_2 = strlen (name_2);
4997 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4998 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4999 if (len_1 != len_2
5000 || strncmp (type1->field (i).name (),
5001 type2->field (i).name (),
5002 len_1) != 0)
5003 return 0;
5006 return 1;
5009 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
5010 that are deemed "identical" for practical purposes. Sometimes,
5011 enumerals are not strictly identical, but their types are so similar
5012 that they can be considered identical.
5014 For instance, consider the following code:
5016 type Color is (Black, Red, Green, Blue, White);
5017 type RGB_Color is new Color range Red .. Blue;
5019 Type RGB_Color is a subrange of an implicit type which is a copy
5020 of type Color. If we call that implicit type RGB_ColorB ("B" is
5021 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5022 As a result, when an expression references any of the enumeral
5023 by name (Eg. "print green"), the expression is technically
5024 ambiguous and the user should be asked to disambiguate. But
5025 doing so would only hinder the user, since it wouldn't matter
5026 what choice he makes, the outcome would always be the same.
5027 So, for practical purposes, we consider them as the same. */
5029 static int
5030 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5032 int i;
5034 /* Before performing a thorough comparison check of each type,
5035 we perform a series of inexpensive checks. We expect that these
5036 checks will quickly fail in the vast majority of cases, and thus
5037 help prevent the unnecessary use of a more expensive comparison.
5038 Said comparison also expects us to make some of these checks
5039 (see ada_identical_enum_types_p). */
5041 /* Quick check: All symbols should have an enum type. */
5042 for (i = 0; i < syms.size (); i++)
5043 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5044 return 0;
5046 /* Quick check: They should all have the same value. */
5047 for (i = 1; i < syms.size (); i++)
5048 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5049 return 0;
5051 /* Quick check: They should all have the same number of enumerals. */
5052 for (i = 1; i < syms.size (); i++)
5053 if (syms[i].symbol->type ()->num_fields ()
5054 != syms[0].symbol->type ()->num_fields ())
5055 return 0;
5057 /* All the sanity checks passed, so we might have a set of
5058 identical enumeration types. Perform a more complete
5059 comparison of the type of each symbol. */
5060 for (i = 1; i < syms.size (); i++)
5061 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5062 syms[0].symbol->type ()))
5063 return 0;
5065 return 1;
5068 /* Remove any non-debugging symbols in SYMS that definitely
5069 duplicate other symbols in the list (The only case I know of where
5070 this happens is when object files containing stabs-in-ecoff are
5071 linked with files containing ordinary ecoff debugging symbols (or no
5072 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5074 static void
5075 remove_extra_symbols (std::vector<struct block_symbol> &syms)
5077 int i, j;
5079 /* We should never be called with less than 2 symbols, as there
5080 cannot be any extra symbol in that case. But it's easy to
5081 handle, since we have nothing to do in that case. */
5082 if (syms.size () < 2)
5083 return;
5085 i = 0;
5086 while (i < syms.size ())
5088 bool remove_p = false;
5090 /* If two symbols have the same name and one of them is a stub type,
5091 the get rid of the stub. */
5093 if (syms[i].symbol->type ()->is_stub ()
5094 && syms[i].symbol->linkage_name () != NULL)
5096 for (j = 0; !remove_p && j < syms.size (); j++)
5098 if (j != i
5099 && !syms[j].symbol->type ()->is_stub ()
5100 && syms[j].symbol->linkage_name () != NULL
5101 && strcmp (syms[i].symbol->linkage_name (),
5102 syms[j].symbol->linkage_name ()) == 0)
5103 remove_p = true;
5107 /* Two symbols with the same name, same class and same address
5108 should be identical. */
5110 else if (syms[i].symbol->linkage_name () != NULL
5111 && syms[i].symbol->aclass () == LOC_STATIC
5112 && is_nondebugging_type (syms[i].symbol->type ()))
5114 for (j = 0; !remove_p && j < syms.size (); j += 1)
5116 if (i != j
5117 && syms[j].symbol->linkage_name () != NULL
5118 && strcmp (syms[i].symbol->linkage_name (),
5119 syms[j].symbol->linkage_name ()) == 0
5120 && (syms[i].symbol->aclass ()
5121 == syms[j].symbol->aclass ())
5122 && syms[i].symbol->value_address ()
5123 == syms[j].symbol->value_address ())
5124 remove_p = true;
5128 /* Two functions with the same block are identical. */
5130 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5132 for (j = 0; !remove_p && j < syms.size (); j += 1)
5134 if (i != j
5135 && syms[j].symbol->aclass () == LOC_BLOCK
5136 && (syms[i].symbol->value_block ()
5137 == syms[j].symbol->value_block ()))
5138 remove_p = true;
5142 if (remove_p)
5143 syms.erase (syms.begin () + i);
5144 else
5145 i += 1;
5149 /* Given a type that corresponds to a renaming entity, use the type name
5150 to extract the scope (package name or function name, fully qualified,
5151 and following the GNAT encoding convention) where this renaming has been
5152 defined. */
5154 static std::string
5155 xget_renaming_scope (struct type *renaming_type)
5157 /* The renaming types adhere to the following convention:
5158 <scope>__<rename>___<XR extension>.
5159 So, to extract the scope, we search for the "___XR" extension,
5160 and then backtrack until we find the first "__". */
5162 const char *name = renaming_type->name ();
5163 const char *suffix = strstr (name, "___XR");
5164 const char *last;
5166 /* Now, backtrack a bit until we find the first "__". Start looking
5167 at suffix - 3, as the <rename> part is at least one character long. */
5169 for (last = suffix - 3; last > name; last--)
5170 if (last[0] == '_' && last[1] == '_')
5171 break;
5173 /* Make a copy of scope and return it. */
5174 return std::string (name, last);
5177 /* Return nonzero if NAME corresponds to a package name. */
5179 static int
5180 is_package_name (const char *name)
5182 /* Here, We take advantage of the fact that no symbols are generated
5183 for packages, while symbols are generated for each function.
5184 So the condition for NAME represent a package becomes equivalent
5185 to NAME not existing in our list of symbols. There is only one
5186 small complication with library-level functions (see below). */
5188 /* If it is a function that has not been defined at library level,
5189 then we should be able to look it up in the symbols. */
5190 if (standard_lookup (name, NULL, SEARCH_VFT) != NULL)
5191 return 0;
5193 /* Library-level function names start with "_ada_". See if function
5194 "_ada_" followed by NAME can be found. */
5196 /* Do a quick check that NAME does not contain "__", since library-level
5197 functions names cannot contain "__" in them. */
5198 if (strstr (name, "__") != NULL)
5199 return 0;
5201 std::string fun_name = string_printf ("_ada_%s", name);
5203 return (standard_lookup (fun_name.c_str (), NULL, SEARCH_VFT) == NULL);
5206 /* Return nonzero if SYM corresponds to a renaming entity that is
5207 not visible from FUNCTION_NAME. */
5209 static int
5210 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5212 if (sym->aclass () != LOC_TYPEDEF)
5213 return 0;
5215 std::string scope = xget_renaming_scope (sym->type ());
5217 /* If the rename has been defined in a package, then it is visible. */
5218 if (is_package_name (scope.c_str ()))
5219 return 0;
5221 /* Check that the rename is in the current function scope by checking
5222 that its name starts with SCOPE. */
5224 /* If the function name starts with "_ada_", it means that it is
5225 a library-level function. Strip this prefix before doing the
5226 comparison, as the encoding for the renaming does not contain
5227 this prefix. */
5228 if (startswith (function_name, "_ada_"))
5229 function_name += 5;
5231 return !startswith (function_name, scope.c_str ());
5234 /* Remove entries from SYMS that corresponds to a renaming entity that
5235 is not visible from the function associated with CURRENT_BLOCK or
5236 that is superfluous due to the presence of more specific renaming
5237 information. Places surviving symbols in the initial entries of
5238 SYMS.
5240 Rationale:
5241 First, in cases where an object renaming is implemented as a
5242 reference variable, GNAT may produce both the actual reference
5243 variable and the renaming encoding. In this case, we discard the
5244 latter.
5246 Second, GNAT emits a type following a specified encoding for each renaming
5247 entity. Unfortunately, STABS currently does not support the definition
5248 of types that are local to a given lexical block, so all renamings types
5249 are emitted at library level. As a consequence, if an application
5250 contains two renaming entities using the same name, and a user tries to
5251 print the value of one of these entities, the result of the ada symbol
5252 lookup will also contain the wrong renaming type.
5254 This function partially covers for this limitation by attempting to
5255 remove from the SYMS list renaming symbols that should be visible
5256 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5257 method with the current information available. The implementation
5258 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5260 - When the user tries to print a rename in a function while there
5261 is another rename entity defined in a package: Normally, the
5262 rename in the function has precedence over the rename in the
5263 package, so the latter should be removed from the list. This is
5264 currently not the case.
5266 - This function will incorrectly remove valid renames if
5267 the CURRENT_BLOCK corresponds to a function which symbol name
5268 has been changed by an "Export" pragma. As a consequence,
5269 the user will be unable to print such rename entities. */
5271 static void
5272 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5273 const struct block *current_block)
5275 struct symbol *current_function;
5276 const char *current_function_name;
5277 int i;
5278 int is_new_style_renaming;
5280 /* If there is both a renaming foo___XR... encoded as a variable and
5281 a simple variable foo in the same block, discard the latter.
5282 First, zero out such symbols, then compress. */
5283 is_new_style_renaming = 0;
5284 for (i = 0; i < syms->size (); i += 1)
5286 struct symbol *sym = (*syms)[i].symbol;
5287 const struct block *block = (*syms)[i].block;
5288 const char *name;
5289 const char *suffix;
5291 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5292 continue;
5293 name = sym->linkage_name ();
5294 suffix = strstr (name, "___XR");
5296 if (suffix != NULL)
5298 int name_len = suffix - name;
5299 int j;
5301 is_new_style_renaming = 1;
5302 for (j = 0; j < syms->size (); j += 1)
5303 if (i != j && (*syms)[j].symbol != NULL
5304 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5305 name_len) == 0
5306 && block == (*syms)[j].block)
5307 (*syms)[j].symbol = NULL;
5310 if (is_new_style_renaming)
5312 int j, k;
5314 for (j = k = 0; j < syms->size (); j += 1)
5315 if ((*syms)[j].symbol != NULL)
5317 (*syms)[k] = (*syms)[j];
5318 k += 1;
5320 syms->resize (k);
5321 return;
5324 /* Extract the function name associated to CURRENT_BLOCK.
5325 Abort if unable to do so. */
5327 if (current_block == NULL)
5328 return;
5330 current_function = current_block->linkage_function ();
5331 if (current_function == NULL)
5332 return;
5334 current_function_name = current_function->linkage_name ();
5335 if (current_function_name == NULL)
5336 return;
5338 /* Check each of the symbols, and remove it from the list if it is
5339 a type corresponding to a renaming that is out of the scope of
5340 the current block. */
5342 i = 0;
5343 while (i < syms->size ())
5345 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5346 == ADA_OBJECT_RENAMING
5347 && old_renaming_is_invisible ((*syms)[i].symbol,
5348 current_function_name))
5349 syms->erase (syms->begin () + i);
5350 else
5351 i += 1;
5355 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5356 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5358 Note: This function assumes that RESULT is empty. */
5360 static void
5361 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5362 const lookup_name_info &lookup_name,
5363 const struct block *block, domain_search_flags domain)
5365 while (block != NULL)
5367 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5369 /* If we found a non-function match, assume that's the one. We
5370 only check this when finding a function boundary, so that we
5371 can accumulate all results from intervening blocks first. */
5372 if (block->function () != nullptr && is_nonfunction (result))
5373 return;
5375 block = block->superblock ();
5379 /* An object of this type is used as the callback argument when
5380 calling the map_matching_symbols method. */
5382 struct match_data
5384 explicit match_data (std::vector<struct block_symbol> *rp)
5385 : resultp (rp)
5388 DISABLE_COPY_AND_ASSIGN (match_data);
5390 bool operator() (struct block_symbol *bsym);
5392 struct objfile *objfile = nullptr;
5393 std::vector<struct block_symbol> *resultp;
5394 struct symbol *arg_sym = nullptr;
5395 bool found_sym = false;
5398 /* A callback for add_nonlocal_symbols that adds symbol, found in
5399 BSYM, to a list of symbols. */
5401 bool
5402 match_data::operator() (struct block_symbol *bsym)
5404 const struct block *block = bsym->block;
5405 struct symbol *sym = bsym->symbol;
5407 if (sym == NULL)
5409 if (!found_sym && arg_sym != NULL)
5410 add_defn_to_vec (*resultp, arg_sym, block);
5411 found_sym = false;
5412 arg_sym = NULL;
5414 else
5416 if (sym->aclass () == LOC_UNRESOLVED)
5417 return true;
5418 else if (sym->is_argument ())
5419 arg_sym = sym;
5420 else
5422 found_sym = true;
5423 add_defn_to_vec (*resultp, sym, block);
5426 return true;
5429 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5430 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5431 symbols to RESULT. Return whether we found such symbols. */
5433 static int
5434 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5435 const struct block *block,
5436 const lookup_name_info &lookup_name,
5437 domain_search_flags domain)
5439 struct using_direct *renaming;
5440 int defns_mark = result.size ();
5442 symbol_name_matcher_ftype *name_match
5443 = ada_get_symbol_name_matcher (lookup_name);
5445 for (renaming = block->get_using ();
5446 renaming != NULL;
5447 renaming = renaming->next)
5449 const char *r_name;
5451 /* Avoid infinite recursions: skip this renaming if we are actually
5452 already traversing it.
5454 Currently, symbol lookup in Ada don't use the namespace machinery from
5455 C++/Fortran support: skip namespace imports that use them. */
5456 if (renaming->searched
5457 || (renaming->import_src != NULL
5458 && renaming->import_src[0] != '\0')
5459 || (renaming->import_dest != NULL
5460 && renaming->import_dest[0] != '\0'))
5461 continue;
5462 renaming->searched = 1;
5464 /* TODO: here, we perform another name-based symbol lookup, which can
5465 pull its own multiple overloads. In theory, we should be able to do
5466 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5467 not a simple name. But in order to do this, we would need to enhance
5468 the DWARF reader to associate a symbol to this renaming, instead of a
5469 name. So, for now, we do something simpler: re-use the C++/Fortran
5470 namespace machinery. */
5471 r_name = (renaming->alias != NULL
5472 ? renaming->alias
5473 : renaming->declaration);
5474 if (name_match (r_name, lookup_name, NULL))
5476 lookup_name_info decl_lookup_name (renaming->declaration,
5477 lookup_name.match_type ());
5478 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5479 1, NULL);
5481 renaming->searched = 0;
5483 return result.size () != defns_mark;
5486 /* Convenience function to get at the Ada encoded lookup name for
5487 LOOKUP_NAME, as a C string. */
5489 static const char *
5490 ada_lookup_name (const lookup_name_info &lookup_name)
5492 return lookup_name.ada ().lookup_name ().c_str ();
5495 /* A helper for add_nonlocal_symbols. Expand all necessary symtabs
5496 for OBJFILE, then walk the objfile's symtabs and update the
5497 results. */
5499 static void
5500 map_matching_symbols (struct objfile *objfile,
5501 const lookup_name_info &lookup_name,
5502 domain_search_flags domain,
5503 int global,
5504 match_data &data)
5506 data.objfile = objfile;
5507 objfile->expand_symtabs_matching (nullptr, &lookup_name,
5508 nullptr, nullptr,
5509 global
5510 ? SEARCH_GLOBAL_BLOCK
5511 : SEARCH_STATIC_BLOCK,
5512 domain);
5514 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5515 for (compunit_symtab *symtab : objfile->compunits ())
5517 const struct block *block
5518 = symtab->blockvector ()->block (block_kind);
5519 if (!iterate_over_symbols_terminated (block, lookup_name,
5520 domain, data))
5521 break;
5525 /* Add to RESULT all non-local symbols whose name and domain match
5526 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5527 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5528 symbols otherwise. */
5530 static void
5531 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5532 const lookup_name_info &lookup_name,
5533 domain_search_flags domain, int global)
5535 struct match_data data (&result);
5537 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5539 for (objfile *objfile : current_program_space->objfiles ())
5541 map_matching_symbols (objfile, lookup_name, domain, global, data);
5543 for (compunit_symtab *cu : objfile->compunits ())
5545 const struct block *global_block
5546 = cu->blockvector ()->global_block ();
5548 if (ada_add_block_renamings (result, global_block, lookup_name,
5549 domain))
5550 data.found_sym = true;
5554 if (result.empty () && global && !is_wild_match)
5556 const char *name = ada_lookup_name (lookup_name);
5557 std::string bracket_name = std::string ("<_ada_") + name + '>';
5558 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5560 for (objfile *objfile : current_program_space->objfiles ())
5561 map_matching_symbols (objfile, name1, domain, global, data);
5565 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5566 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5567 returning the number of matches. Add these to RESULT.
5569 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5570 symbol match within the nest of blocks whose innermost member is BLOCK,
5571 is the one match returned (no other matches in that or
5572 enclosing blocks is returned). If there are any matches in or
5573 surrounding BLOCK, then these alone are returned.
5575 Names prefixed with "standard__" are handled specially:
5576 "standard__" is first stripped off (by the lookup_name
5577 constructor), and only static and global symbols are searched.
5579 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5580 to lookup global symbols. */
5582 static void
5583 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5584 const struct block *block,
5585 const lookup_name_info &lookup_name,
5586 domain_search_flags domain,
5587 int full_search,
5588 int *made_global_lookup_p)
5590 struct symbol *sym;
5592 if (made_global_lookup_p)
5593 *made_global_lookup_p = 0;
5595 /* Special case: If the user specifies a symbol name inside package
5596 Standard, do a non-wild matching of the symbol name without
5597 the "standard__" prefix. This was primarily introduced in order
5598 to allow the user to specifically access the standard exceptions
5599 using, for instance, Standard.Constraint_Error when Constraint_Error
5600 is ambiguous (due to the user defining its own Constraint_Error
5601 entity inside its program). */
5602 if (lookup_name.ada ().standard_p ())
5603 block = NULL;
5605 /* Check the non-global symbols. If we have ANY match, then we're done. */
5607 if (block != NULL)
5609 if (full_search)
5610 ada_add_local_symbols (result, lookup_name, block, domain);
5611 else
5613 /* In the !full_search case we're are being called by
5614 iterate_over_symbols, and we don't want to search
5615 superblocks. */
5616 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5618 if (!result.empty () || !full_search)
5619 return;
5622 /* No non-global symbols found. Check our cache to see if we have
5623 already performed this search before. If we have, then return
5624 the same result. */
5626 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5627 domain, &sym, &block))
5629 if (sym != NULL)
5630 add_defn_to_vec (result, sym, block);
5631 return;
5634 if (made_global_lookup_p)
5635 *made_global_lookup_p = 1;
5637 /* Search symbols from all global blocks. */
5639 add_nonlocal_symbols (result, lookup_name, domain, 1);
5641 /* Now add symbols from all per-file blocks if we've gotten no hits
5642 (not strictly correct, but perhaps better than an error). */
5644 if (result.empty ())
5645 add_nonlocal_symbols (result, lookup_name, domain, 0);
5648 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5649 is non-zero, enclosing scope and in global scopes.
5651 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5652 blocks and symbol tables (if any) in which they were found.
5654 When full_search is non-zero, any non-function/non-enumeral
5655 symbol match within the nest of blocks whose innermost member is BLOCK,
5656 is the one match returned (no other matches in that or
5657 enclosing blocks is returned). If there are any matches in or
5658 surrounding BLOCK, then these alone are returned.
5660 Names prefixed with "standard__" are handled specially: "standard__"
5661 is first stripped off, and only static and global symbols are searched. */
5663 static std::vector<struct block_symbol>
5664 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5665 const struct block *block,
5666 domain_search_flags domain,
5667 int full_search)
5669 int syms_from_global_search;
5670 std::vector<struct block_symbol> results;
5672 ada_add_all_symbols (results, block, lookup_name,
5673 domain, full_search, &syms_from_global_search);
5675 remove_extra_symbols (results);
5677 if (results.empty () && full_search && syms_from_global_search)
5678 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5680 if (results.size () == 1 && full_search && syms_from_global_search)
5681 cache_symbol (ada_lookup_name (lookup_name), domain,
5682 results[0].symbol, results[0].block);
5684 remove_irrelevant_renamings (&results, block);
5685 return results;
5688 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5689 in global scopes, returning (SYM,BLOCK) tuples.
5691 See ada_lookup_symbol_list_worker for further details. */
5693 std::vector<struct block_symbol>
5694 ada_lookup_symbol_list (const char *name, const struct block *block,
5695 domain_search_flags domain)
5697 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5698 lookup_name_info lookup_name (name, name_match_type);
5700 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5703 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5704 to 1, but choosing the first symbol found if there are multiple
5705 choices.
5707 The result is stored in *INFO, which must be non-NULL.
5708 If no match is found, INFO->SYM is set to NULL. */
5710 void
5711 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5712 domain_search_flags domain,
5713 struct block_symbol *info)
5715 /* Since we already have an encoded name, wrap it in '<>' to force a
5716 verbatim match. Otherwise, if the name happens to not look like
5717 an encoded name (because it doesn't include a "__"),
5718 ada_lookup_name_info would re-encode/fold it again, and that
5719 would e.g., incorrectly lowercase object renaming names like
5720 "R28b" -> "r28b". */
5721 std::string verbatim = add_angle_brackets (name);
5723 gdb_assert (info != NULL);
5724 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5727 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5728 scope and in global scopes, or NULL if none. NAME is folded and
5729 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5730 choosing the first symbol if there are multiple choices. */
5732 struct block_symbol
5733 ada_lookup_symbol (const char *name, const struct block *block0,
5734 domain_search_flags domain)
5736 std::vector<struct block_symbol> candidates
5737 = ada_lookup_symbol_list (name, block0, domain);
5739 if (candidates.empty ())
5740 return {};
5742 return candidates[0];
5746 /* True iff STR is a possible encoded suffix of a normal Ada name
5747 that is to be ignored for matching purposes. Suffixes of parallel
5748 names (e.g., XVE) are not included here. Currently, the possible suffixes
5749 are given by any of the regular expressions:
5751 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5752 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5753 TKB [subprogram suffix for task bodies]
5754 _E[0-9]+[bs]$ [protected object entry suffixes]
5755 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5757 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5758 match is performed. This sequence is used to differentiate homonyms,
5759 is an optional part of a valid name suffix. */
5761 static int
5762 is_name_suffix (const char *str)
5764 int k;
5765 const char *matching;
5766 const int len = strlen (str);
5768 /* Skip optional leading __[0-9]+. */
5770 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5772 str += 3;
5773 while (isdigit (str[0]))
5774 str += 1;
5777 /* [.$][0-9]+ */
5779 if (str[0] == '.' || str[0] == '$')
5781 matching = str + 1;
5782 while (isdigit (matching[0]))
5783 matching += 1;
5784 if (matching[0] == '\0')
5785 return 1;
5788 /* ___[0-9]+ */
5790 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5792 matching = str + 3;
5793 while (isdigit (matching[0]))
5794 matching += 1;
5795 if (matching[0] == '\0')
5796 return 1;
5799 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5801 if (strcmp (str, "TKB") == 0)
5802 return 1;
5804 #if 0
5805 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5806 with a N at the end. Unfortunately, the compiler uses the same
5807 convention for other internal types it creates. So treating
5808 all entity names that end with an "N" as a name suffix causes
5809 some regressions. For instance, consider the case of an enumerated
5810 type. To support the 'Image attribute, it creates an array whose
5811 name ends with N.
5812 Having a single character like this as a suffix carrying some
5813 information is a bit risky. Perhaps we should change the encoding
5814 to be something like "_N" instead. In the meantime, do not do
5815 the following check. */
5816 /* Protected Object Subprograms */
5817 if (len == 1 && str [0] == 'N')
5818 return 1;
5819 #endif
5821 /* _E[0-9]+[bs]$ */
5822 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5824 matching = str + 3;
5825 while (isdigit (matching[0]))
5826 matching += 1;
5827 if ((matching[0] == 'b' || matching[0] == 's')
5828 && matching [1] == '\0')
5829 return 1;
5832 /* ??? We should not modify STR directly, as we are doing below. This
5833 is fine in this case, but may become problematic later if we find
5834 that this alternative did not work, and want to try matching
5835 another one from the begining of STR. Since we modified it, we
5836 won't be able to find the begining of the string anymore! */
5837 if (str[0] == 'X')
5839 str += 1;
5840 while (str[0] != '_' && str[0] != '\0')
5842 if (str[0] != 'n' && str[0] != 'b')
5843 return 0;
5844 str += 1;
5848 if (str[0] == '\000')
5849 return 1;
5851 if (str[0] == '_')
5853 if (str[1] != '_' || str[2] == '\000')
5854 return 0;
5855 if (str[2] == '_')
5857 if (strcmp (str + 3, "JM") == 0)
5858 return 1;
5859 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5860 the LJM suffix in favor of the JM one. But we will
5861 still accept LJM as a valid suffix for a reasonable
5862 amount of time, just to allow ourselves to debug programs
5863 compiled using an older version of GNAT. */
5864 if (strcmp (str + 3, "LJM") == 0)
5865 return 1;
5866 if (str[3] != 'X')
5867 return 0;
5868 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5869 || str[4] == 'U' || str[4] == 'P')
5870 return 1;
5871 if (str[4] == 'R' && str[5] != 'T')
5872 return 1;
5873 return 0;
5875 if (!isdigit (str[2]))
5876 return 0;
5877 for (k = 3; str[k] != '\0'; k += 1)
5878 if (!isdigit (str[k]) && str[k] != '_')
5879 return 0;
5880 return 1;
5882 if (str[0] == '$' && isdigit (str[1]))
5884 for (k = 2; str[k] != '\0'; k += 1)
5885 if (!isdigit (str[k]) && str[k] != '_')
5886 return 0;
5887 return 1;
5889 return 0;
5892 /* Return non-zero if the string starting at NAME and ending before
5893 NAME_END contains no capital letters. */
5895 static int
5896 is_valid_name_for_wild_match (const char *name0)
5898 std::string decoded_name = ada_decode (name0);
5899 int i;
5901 /* If the decoded name starts with an angle bracket, it means that
5902 NAME0 does not follow the GNAT encoding format. It should then
5903 not be allowed as a possible wild match. */
5904 if (decoded_name[0] == '<')
5905 return 0;
5907 for (i=0; decoded_name[i] != '\0'; i++)
5908 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5909 return 0;
5911 return 1;
5914 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5915 character which could start a simple name. Assumes that *NAMEP points
5916 somewhere inside the string beginning at NAME0. */
5918 static int
5919 advance_wild_match (const char **namep, const char *name0, char target0)
5921 const char *name = *namep;
5923 while (1)
5925 char t0, t1;
5927 t0 = *name;
5928 if (t0 == '_')
5930 t1 = name[1];
5931 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5933 name += 1;
5934 if (name == name0 + 5 && startswith (name0, "_ada"))
5935 break;
5936 else
5937 name += 1;
5939 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5940 || name[2] == target0))
5942 name += 2;
5943 break;
5945 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5947 /* Names like "pkg__B_N__name", where N is a number, are
5948 block-local. We can handle these by simply skipping
5949 the "B_" here. */
5950 name += 4;
5952 else
5953 return 0;
5955 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5956 name += 1;
5957 else
5958 return 0;
5961 *namep = name;
5962 return 1;
5965 /* Return true iff NAME encodes a name of the form prefix.PATN.
5966 Ignores any informational suffixes of NAME (i.e., for which
5967 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5968 simple name. */
5970 static bool
5971 wild_match (const char *name, const char *patn)
5973 const char *p;
5974 const char *name0 = name;
5976 if (startswith (name, "___ghost_"))
5977 name += 9;
5979 while (1)
5981 const char *match = name;
5983 if (*name == *patn)
5985 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5986 if (*p != *name)
5987 break;
5988 if (*p == '\0' && is_name_suffix (name))
5989 return match == name0 || is_valid_name_for_wild_match (name0);
5991 if (name[-1] == '_')
5992 name -= 1;
5994 if (!advance_wild_match (&name, name0, *patn))
5995 return false;
5999 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6000 necessary). OBJFILE is the section containing BLOCK. */
6002 static void
6003 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6004 const struct block *block,
6005 const lookup_name_info &lookup_name,
6006 domain_search_flags domain, struct objfile *objfile)
6008 /* A matching argument symbol, if any. */
6009 struct symbol *arg_sym;
6010 /* Set true when we find a matching non-argument symbol. */
6011 bool found_sym;
6013 arg_sym = NULL;
6014 found_sym = false;
6015 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
6017 if (sym->matches (domain))
6019 if (sym->aclass () != LOC_UNRESOLVED)
6021 if (sym->is_argument ())
6022 arg_sym = sym;
6023 else
6025 found_sym = true;
6026 add_defn_to_vec (result, sym, block);
6032 /* Handle renamings. */
6034 if (ada_add_block_renamings (result, block, lookup_name, domain))
6035 found_sym = true;
6037 if (!found_sym && arg_sym != NULL)
6039 add_defn_to_vec (result, arg_sym, block);
6042 if (!lookup_name.ada ().wild_match_p ())
6044 arg_sym = NULL;
6045 found_sym = false;
6046 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6047 const char *name = ada_lookup_name.c_str ();
6048 size_t name_len = ada_lookup_name.size ();
6050 for (struct symbol *sym : block_iterator_range (block))
6052 if (sym->matches (domain))
6054 int cmp;
6056 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6057 if (cmp == 0)
6059 cmp = !startswith (sym->linkage_name (), "_ada_");
6060 if (cmp == 0)
6061 cmp = strncmp (name, sym->linkage_name () + 5,
6062 name_len);
6065 if (cmp == 0
6066 && is_name_suffix (sym->linkage_name () + name_len + 5))
6068 if (sym->aclass () != LOC_UNRESOLVED)
6070 if (sym->is_argument ())
6071 arg_sym = sym;
6072 else
6074 found_sym = true;
6075 add_defn_to_vec (result, sym, block);
6082 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6083 They aren't parameters, right? */
6084 if (!found_sym && arg_sym != NULL)
6086 add_defn_to_vec (result, arg_sym, block);
6092 /* Symbol Completion */
6094 /* See symtab.h. */
6096 bool
6097 ada_lookup_name_info::matches
6098 (const char *sym_name,
6099 symbol_name_match_type match_type,
6100 completion_match_result *comp_match_res) const
6102 bool match = false;
6103 const char *text = m_encoded_name.c_str ();
6104 size_t text_len = m_encoded_name.size ();
6106 /* First, test against the fully qualified name of the symbol. */
6108 if (strncmp (sym_name, text, text_len) == 0)
6109 match = true;
6111 std::string decoded_name = ada_decode (sym_name);
6112 if (match && !m_encoded_p)
6114 /* One needed check before declaring a positive match is to verify
6115 that iff we are doing a verbatim match, the decoded version
6116 of the symbol name starts with '<'. Otherwise, this symbol name
6117 is not a suitable completion. */
6119 bool has_angle_bracket = (decoded_name[0] == '<');
6120 match = (has_angle_bracket == m_verbatim_p);
6123 if (match && !m_verbatim_p)
6125 /* When doing non-verbatim match, another check that needs to
6126 be done is to verify that the potentially matching symbol name
6127 does not include capital letters, because the ada-mode would
6128 not be able to understand these symbol names without the
6129 angle bracket notation. */
6130 const char *tmp;
6132 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6133 if (*tmp != '\0')
6134 match = false;
6137 /* Second: Try wild matching... */
6139 if (!match && m_wild_match_p)
6141 /* Since we are doing wild matching, this means that TEXT
6142 may represent an unqualified symbol name. We therefore must
6143 also compare TEXT against the unqualified name of the symbol. */
6144 sym_name = ada_unqualified_name (decoded_name.c_str ());
6146 if (strncmp (sym_name, text, text_len) == 0)
6147 match = true;
6150 /* Finally: If we found a match, prepare the result to return. */
6152 if (!match)
6153 return false;
6155 if (comp_match_res != NULL)
6157 std::string &match_str = comp_match_res->match.storage ();
6159 if (!m_encoded_p)
6160 match_str = ada_decode (sym_name);
6161 else
6163 if (m_verbatim_p)
6164 match_str = add_angle_brackets (sym_name);
6165 else
6166 match_str = sym_name;
6170 comp_match_res->set_match (match_str.c_str ());
6173 return true;
6176 /* Field Access */
6178 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6179 for tagged types. */
6181 static int
6182 ada_is_dispatch_table_ptr_type (struct type *type)
6184 const char *name;
6186 if (type->code () != TYPE_CODE_PTR)
6187 return 0;
6189 name = type->target_type ()->name ();
6190 if (name == NULL)
6191 return 0;
6193 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6196 /* Return non-zero if TYPE is an interface tag. */
6198 static int
6199 ada_is_interface_tag (struct type *type)
6201 const char *name = type->name ();
6203 if (name == NULL)
6204 return 0;
6206 return (strcmp (name, "ada__tags__interface_tag") == 0);
6209 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6210 to be invisible to users. */
6213 ada_is_ignored_field (struct type *type, int field_num)
6215 if (field_num < 0 || field_num > type->num_fields ())
6216 return 1;
6218 /* Check the name of that field. */
6220 const char *name = type->field (field_num).name ();
6222 /* Anonymous field names should not be printed.
6223 brobecker/2007-02-20: I don't think this can actually happen
6224 but we don't want to print the value of anonymous fields anyway. */
6225 if (name == NULL)
6226 return 1;
6228 /* Normally, fields whose name start with an underscore ("_")
6229 are fields that have been internally generated by the compiler,
6230 and thus should not be printed. The "_parent" field is special,
6231 however: This is a field internally generated by the compiler
6232 for tagged types, and it contains the components inherited from
6233 the parent type. This field should not be printed as is, but
6234 should not be ignored either. */
6235 if (name[0] == '_' && !startswith (name, "_parent"))
6236 return 1;
6238 /* The compiler doesn't document this, but sometimes it emits
6239 a field whose name starts with a capital letter, like 'V148s'.
6240 These aren't marked as artificial in any way, but we know they
6241 should be ignored. However, wrapper fields should not be
6242 ignored. */
6243 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6245 /* Wrapper field. */
6247 else if (isupper (name[0]))
6248 return 1;
6251 /* If this is the dispatch table of a tagged type or an interface tag,
6252 then ignore. */
6253 if (ada_is_tagged_type (type, 1)
6254 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6255 || ada_is_interface_tag (type->field (field_num).type ())))
6256 return 1;
6258 /* Not a special field, so it should not be ignored. */
6259 return 0;
6262 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6263 pointer or reference type whose ultimate target has a tag field. */
6266 ada_is_tagged_type (struct type *type, int refok)
6268 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6271 /* True iff TYPE represents the type of X'Tag */
6274 ada_is_tag_type (struct type *type)
6276 type = ada_check_typedef (type);
6278 if (type == NULL || type->code () != TYPE_CODE_PTR)
6279 return 0;
6280 else
6282 const char *name = ada_type_name (type->target_type ());
6284 return (name != NULL
6285 && strcmp (name, "ada__tags__dispatch_table") == 0);
6289 /* The type of the tag on VAL. */
6291 static struct type *
6292 ada_tag_type (struct value *val)
6294 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6297 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6298 retired at Ada 05). */
6300 static int
6301 is_ada95_tag (struct value *tag)
6303 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6306 /* The value of the tag on VAL. */
6308 static struct value *
6309 ada_value_tag (struct value *val)
6311 return ada_value_struct_elt (val, "_tag", 0);
6314 /* The value of the tag on the object of type TYPE whose contents are
6315 saved at VALADDR, if it is non-null, or is at memory address
6316 ADDRESS. */
6318 static struct value *
6319 value_tag_from_contents_and_address (struct type *type,
6320 const gdb_byte *valaddr,
6321 CORE_ADDR address)
6323 int tag_byte_offset;
6324 struct type *tag_type;
6326 gdb::array_view<const gdb_byte> contents;
6327 if (valaddr != nullptr)
6328 contents = gdb::make_array_view (valaddr, type->length ());
6329 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6330 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6331 NULL, NULL, NULL))
6333 const gdb_byte *valaddr1 = ((valaddr == NULL)
6334 ? NULL
6335 : valaddr + tag_byte_offset);
6336 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6338 return value_from_contents_and_address (tag_type, valaddr1, address1);
6340 return NULL;
6343 static struct type *
6344 type_from_tag (struct value *tag)
6346 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6348 if (type_name != NULL)
6349 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6350 return NULL;
6353 /* Given a value OBJ of a tagged type, return a value of this
6354 type at the base address of the object. The base address, as
6355 defined in Ada.Tags, it is the address of the primary tag of
6356 the object, and therefore where the field values of its full
6357 view can be fetched. */
6359 struct value *
6360 ada_tag_value_at_base_address (struct value *obj)
6362 struct value *val;
6363 LONGEST offset_to_top = 0;
6364 struct type *ptr_type, *obj_type;
6365 struct value *tag;
6366 CORE_ADDR base_address;
6368 obj_type = obj->type ();
6370 /* It is the responsibility of the caller to deref pointers. */
6372 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6373 return obj;
6375 tag = ada_value_tag (obj);
6376 if (!tag)
6377 return obj;
6379 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6381 if (is_ada95_tag (tag))
6382 return obj;
6384 struct type *offset_type
6385 = language_lookup_primitive_type (language_def (language_ada),
6386 current_inferior ()->arch (),
6387 "storage_offset");
6388 ptr_type = lookup_pointer_type (offset_type);
6389 val = value_cast (ptr_type, tag);
6390 if (!val)
6391 return obj;
6393 /* It is perfectly possible that an exception be raised while
6394 trying to determine the base address, just like for the tag;
6395 see ada_tag_name for more details. We do not print the error
6396 message for the same reason. */
6400 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6403 catch (const gdb_exception_error &e)
6405 return obj;
6408 /* If offset is null, nothing to do. */
6410 if (offset_to_top == 0)
6411 return obj;
6413 /* -1 is a special case in Ada.Tags; however, what should be done
6414 is not quite clear from the documentation. So do nothing for
6415 now. */
6417 if (offset_to_top == -1)
6418 return obj;
6420 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6421 top is used. In this situation the offset is stored just after
6422 the tag, in the object itself. */
6423 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6424 if (offset_to_top == last)
6426 struct value *tem = value_addr (tag);
6427 tem = value_ptradd (tem, 1);
6428 tem = value_cast (ptr_type, tem);
6429 offset_to_top = value_as_long (value_ind (tem));
6432 if (offset_to_top > 0)
6434 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6435 from the base address. This was however incompatible with
6436 C++ dispatch table: C++ uses a *negative* value to *add*
6437 to the base address. Ada's convention has therefore been
6438 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6439 use the same convention. Here, we support both cases by
6440 checking the sign of OFFSET_TO_TOP. */
6441 offset_to_top = -offset_to_top;
6444 base_address = obj->address () + offset_to_top;
6445 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6447 /* Make sure that we have a proper tag at the new address.
6448 Otherwise, offset_to_top is bogus (which can happen when
6449 the object is not initialized yet). */
6451 if (!tag)
6452 return obj;
6454 obj_type = type_from_tag (tag);
6456 if (!obj_type)
6457 return obj;
6459 return value_from_contents_and_address (obj_type, NULL, base_address);
6462 /* Return the "ada__tags__type_specific_data" type. */
6464 static struct type *
6465 ada_get_tsd_type (struct inferior *inf)
6467 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6469 if (data->tsd_type == 0)
6470 data->tsd_type
6471 = lookup_transparent_type ("<ada__tags__type_specific_data>",
6472 SEARCH_TYPE_DOMAIN);
6473 return data->tsd_type;
6476 /* Return the TSD (type-specific data) associated to the given TAG.
6477 TAG is assumed to be the tag of a tagged-type entity.
6479 May return NULL if we are unable to get the TSD. */
6481 static struct value *
6482 ada_get_tsd_from_tag (struct value *tag)
6484 struct value *val;
6485 struct type *type;
6487 /* First option: The TSD is simply stored as a field of our TAG.
6488 Only older versions of GNAT would use this format, but we have
6489 to test it first, because there are no visible markers for
6490 the current approach except the absence of that field. */
6492 val = ada_value_struct_elt (tag, "tsd", 1);
6493 if (val)
6494 return val;
6496 /* Try the second representation for the dispatch table (in which
6497 there is no explicit 'tsd' field in the referent of the tag pointer,
6498 and instead the tsd pointer is stored just before the dispatch
6499 table. */
6501 type = ada_get_tsd_type (current_inferior());
6502 if (type == NULL)
6503 return NULL;
6504 type = lookup_pointer_type (lookup_pointer_type (type));
6505 val = value_cast (type, tag);
6506 if (val == NULL)
6507 return NULL;
6508 return value_ind (value_ptradd (val, -1));
6511 /* Given the TSD of a tag (type-specific data), return a string
6512 containing the name of the associated type.
6514 May return NULL if we are unable to determine the tag name. */
6516 static gdb::unique_xmalloc_ptr<char>
6517 ada_tag_name_from_tsd (struct value *tsd)
6519 struct value *val;
6521 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6522 if (val == NULL)
6523 return NULL;
6524 gdb::unique_xmalloc_ptr<char> buffer
6525 = target_read_string (value_as_address (val), INT_MAX);
6526 if (buffer == nullptr)
6527 return nullptr;
6531 /* Let this throw an exception on error. If the data is
6532 uninitialized, we'd rather not have the user see a
6533 warning. */
6534 const char *folded = ada_fold_name (buffer.get (), true);
6535 return make_unique_xstrdup (folded);
6537 catch (const gdb_exception &)
6539 return nullptr;
6543 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6544 a C string.
6546 Return NULL if the TAG is not an Ada tag, or if we were unable to
6547 determine the name of that tag. */
6549 gdb::unique_xmalloc_ptr<char>
6550 ada_tag_name (struct value *tag)
6552 gdb::unique_xmalloc_ptr<char> name;
6554 if (!ada_is_tag_type (tag->type ()))
6555 return NULL;
6557 /* It is perfectly possible that an exception be raised while trying
6558 to determine the TAG's name, even under normal circumstances:
6559 The associated variable may be uninitialized or corrupted, for
6560 instance. We do not let any exception propagate past this point.
6561 instead we return NULL.
6563 We also do not print the error message either (which often is very
6564 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6565 the caller print a more meaningful message if necessary. */
6568 struct value *tsd = ada_get_tsd_from_tag (tag);
6570 if (tsd != NULL)
6571 name = ada_tag_name_from_tsd (tsd);
6573 catch (const gdb_exception_error &e)
6577 return name;
6580 /* The parent type of TYPE, or NULL if none. */
6582 struct type *
6583 ada_parent_type (struct type *type)
6585 int i;
6587 type = ada_check_typedef (type);
6589 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6590 return NULL;
6592 for (i = 0; i < type->num_fields (); i += 1)
6593 if (ada_is_parent_field (type, i))
6595 struct type *parent_type = type->field (i).type ();
6597 /* If the _parent field is a pointer, then dereference it. */
6598 if (parent_type->code () == TYPE_CODE_PTR)
6599 parent_type = parent_type->target_type ();
6600 /* If there is a parallel XVS type, get the actual base type. */
6601 parent_type = ada_get_base_type (parent_type);
6603 return ada_check_typedef (parent_type);
6606 return NULL;
6609 /* True iff field number FIELD_NUM of structure type TYPE contains the
6610 parent-type (inherited) fields of a derived type. Assumes TYPE is
6611 a structure type with at least FIELD_NUM+1 fields. */
6614 ada_is_parent_field (struct type *type, int field_num)
6616 const char *name = ada_check_typedef (type)->field (field_num).name ();
6618 return (name != NULL
6619 && (startswith (name, "PARENT")
6620 || startswith (name, "_parent")));
6623 /* True iff field number FIELD_NUM of structure type TYPE is a
6624 transparent wrapper field (which should be silently traversed when doing
6625 field selection and flattened when printing). Assumes TYPE is a
6626 structure type with at least FIELD_NUM+1 fields. Such fields are always
6627 structures. */
6630 ada_is_wrapper_field (struct type *type, int field_num)
6632 const char *name = type->field (field_num).name ();
6634 if (name != NULL && strcmp (name, "RETVAL") == 0)
6636 /* This happens in functions with "out" or "in out" parameters
6637 which are passed by copy. For such functions, GNAT describes
6638 the function's return type as being a struct where the return
6639 value is in a field called RETVAL, and where the other "out"
6640 or "in out" parameters are fields of that struct. This is not
6641 a wrapper. */
6642 return 0;
6645 return (name != NULL
6646 && (startswith (name, "PARENT")
6647 || strcmp (name, "REP") == 0
6648 || startswith (name, "_parent")
6649 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6652 /* True iff field number FIELD_NUM of structure or union type TYPE
6653 is a variant wrapper. Assumes TYPE is a structure type with at least
6654 FIELD_NUM+1 fields. */
6657 ada_is_variant_part (struct type *type, int field_num)
6659 /* Only Ada types are eligible. */
6660 if (!ADA_TYPE_P (type))
6661 return 0;
6663 struct type *field_type = type->field (field_num).type ();
6665 return (field_type->code () == TYPE_CODE_UNION
6666 || (is_dynamic_field (type, field_num)
6667 && (field_type->target_type ()->code ()
6668 == TYPE_CODE_UNION)));
6671 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6672 whose discriminants are contained in the record type OUTER_TYPE,
6673 returns the type of the controlling discriminant for the variant.
6674 May return NULL if the type could not be found. */
6676 struct type *
6677 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6679 const char *name = ada_variant_discrim_name (var_type);
6681 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6684 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6685 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6686 represents a 'when others' clause; otherwise 0. */
6688 static int
6689 ada_is_others_clause (struct type *type, int field_num)
6691 const char *name = type->field (field_num).name ();
6693 return (name != NULL && name[0] == 'O');
6696 /* Assuming that TYPE0 is the type of the variant part of a record,
6697 returns the name of the discriminant controlling the variant.
6698 The value is valid until the next call to ada_variant_discrim_name. */
6700 const char *
6701 ada_variant_discrim_name (struct type *type0)
6703 static std::string result;
6704 struct type *type;
6705 const char *name;
6706 const char *discrim_end;
6707 const char *discrim_start;
6709 if (type0->code () == TYPE_CODE_PTR)
6710 type = type0->target_type ();
6711 else
6712 type = type0;
6714 name = ada_type_name (type);
6716 if (name == NULL || name[0] == '\000')
6717 return "";
6719 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6720 discrim_end -= 1)
6722 if (startswith (discrim_end, "___XVN"))
6723 break;
6725 if (discrim_end == name)
6726 return "";
6728 for (discrim_start = discrim_end; discrim_start != name + 3;
6729 discrim_start -= 1)
6731 if (discrim_start == name + 1)
6732 return "";
6733 if ((discrim_start > name + 3
6734 && startswith (discrim_start - 3, "___"))
6735 || discrim_start[-1] == '.')
6736 break;
6739 result = std::string (discrim_start, discrim_end - discrim_start);
6740 return result.c_str ();
6743 /* Scan STR for a subtype-encoded number, beginning at position K.
6744 Put the position of the character just past the number scanned in
6745 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6746 Return 1 if there was a valid number at the given position, and 0
6747 otherwise. A "subtype-encoded" number consists of the absolute value
6748 in decimal, followed by the letter 'm' to indicate a negative number.
6749 Assumes 0m does not occur. */
6752 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6754 ULONGEST RU;
6756 if (!isdigit (str[k]))
6757 return 0;
6759 /* Do it the hard way so as not to make any assumption about
6760 the relationship of unsigned long (%lu scan format code) and
6761 LONGEST. */
6762 RU = 0;
6763 while (isdigit (str[k]))
6765 RU = RU * 10 + (str[k] - '0');
6766 k += 1;
6769 if (str[k] == 'm')
6771 if (R != NULL)
6772 *R = (-(LONGEST) (RU - 1)) - 1;
6773 k += 1;
6775 else if (R != NULL)
6776 *R = (LONGEST) RU;
6778 /* NOTE on the above: Technically, C does not say what the results of
6779 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6780 number representable as a LONGEST (although either would probably work
6781 in most implementations). When RU>0, the locution in the then branch
6782 above is always equivalent to the negative of RU. */
6784 if (new_k != NULL)
6785 *new_k = k;
6786 return 1;
6789 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6790 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6791 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6793 static int
6794 ada_in_variant (LONGEST val, struct type *type, int field_num)
6796 const char *name = type->field (field_num).name ();
6797 int p;
6799 p = 0;
6800 while (1)
6802 switch (name[p])
6804 case '\0':
6805 return 0;
6806 case 'S':
6808 LONGEST W;
6810 if (!ada_scan_number (name, p + 1, &W, &p))
6811 return 0;
6812 if (val == W)
6813 return 1;
6814 break;
6816 case 'R':
6818 LONGEST L, U;
6820 if (!ada_scan_number (name, p + 1, &L, &p)
6821 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6822 return 0;
6823 if (val >= L && val <= U)
6824 return 1;
6825 break;
6827 case 'O':
6828 return 1;
6829 default:
6830 return 0;
6835 /* FIXME: Lots of redundancy below. Try to consolidate. */
6837 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6838 ARG_TYPE, extract and return the value of one of its (non-static)
6839 fields. FIELDNO says which field. Differs from value_primitive_field
6840 only in that it can handle packed values of arbitrary type. */
6842 struct value *
6843 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6844 struct type *arg_type)
6846 struct type *type;
6848 arg_type = ada_check_typedef (arg_type);
6849 type = arg_type->field (fieldno).type ();
6851 /* Handle packed fields. It might be that the field is not packed
6852 relative to its containing structure, but the structure itself is
6853 packed; in this case we must take the bit-field path. */
6854 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
6856 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6857 int bit_size = arg_type->field (fieldno).bitsize ();
6859 return ada_value_primitive_packed_val (arg1,
6860 arg1->contents ().data (),
6861 offset + bit_pos / 8,
6862 bit_pos % 8, bit_size, type);
6864 else
6865 return arg1->primitive_field (offset, fieldno, arg_type);
6868 /* Find field with name NAME in object of type TYPE. If found,
6869 set the following for each argument that is non-null:
6870 - *FIELD_TYPE_P to the field's type;
6871 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6872 an object of that type;
6873 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6874 - *BIT_SIZE_P to its size in bits if the field is packed, and
6875 0 otherwise;
6876 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6877 fields up to but not including the desired field, or by the total
6878 number of fields if not found. A NULL value of NAME never
6879 matches; the function just counts visible fields in this case.
6881 Notice that we need to handle when a tagged record hierarchy
6882 has some components with the same name, like in this scenario:
6884 type Top_T is tagged record
6885 N : Integer := 1;
6886 U : Integer := 974;
6887 A : Integer := 48;
6888 end record;
6890 type Middle_T is new Top.Top_T with record
6891 N : Character := 'a';
6892 C : Integer := 3;
6893 end record;
6895 type Bottom_T is new Middle.Middle_T with record
6896 N : Float := 4.0;
6897 C : Character := '5';
6898 X : Integer := 6;
6899 A : Character := 'J';
6900 end record;
6902 Let's say we now have a variable declared and initialized as follow:
6904 TC : Top_A := new Bottom_T;
6906 And then we use this variable to call this function
6908 procedure Assign (Obj: in out Top_T; TV : Integer);
6910 as follow:
6912 Assign (Top_T (B), 12);
6914 Now, we're in the debugger, and we're inside that procedure
6915 then and we want to print the value of obj.c:
6917 Usually, the tagged record or one of the parent type owns the
6918 component to print and there's no issue but in this particular
6919 case, what does it mean to ask for Obj.C? Since the actual
6920 type for object is type Bottom_T, it could mean two things: type
6921 component C from the Middle_T view, but also component C from
6922 Bottom_T. So in that "undefined" case, when the component is
6923 not found in the non-resolved type (which includes all the
6924 components of the parent type), then resolve it and see if we
6925 get better luck once expanded.
6927 In the case of homonyms in the derived tagged type, we don't
6928 guaranty anything, and pick the one that's easiest for us
6929 to program.
6931 Returns 1 if found, 0 otherwise. */
6933 static int
6934 find_struct_field (const char *name, struct type *type, int offset,
6935 struct type **field_type_p,
6936 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6937 int *index_p)
6939 int i;
6940 int parent_offset = -1;
6942 type = ada_check_typedef (type);
6944 if (field_type_p != NULL)
6945 *field_type_p = NULL;
6946 if (byte_offset_p != NULL)
6947 *byte_offset_p = 0;
6948 if (bit_offset_p != NULL)
6949 *bit_offset_p = 0;
6950 if (bit_size_p != NULL)
6951 *bit_size_p = 0;
6953 for (i = 0; i < type->num_fields (); i += 1)
6955 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6956 type. However, we only need the values to be correct when
6957 the caller asks for them. */
6958 int bit_pos = 0, fld_offset = 0;
6959 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6961 bit_pos = type->field (i).loc_bitpos ();
6962 fld_offset = offset + bit_pos / 8;
6965 const char *t_field_name = type->field (i).name ();
6967 if (t_field_name == NULL)
6968 continue;
6970 else if (ada_is_parent_field (type, i))
6972 /* This is a field pointing us to the parent type of a tagged
6973 type. As hinted in this function's documentation, we give
6974 preference to fields in the current record first, so what
6975 we do here is just record the index of this field before
6976 we skip it. If it turns out we couldn't find our field
6977 in the current record, then we'll get back to it and search
6978 inside it whether the field might exist in the parent. */
6980 parent_offset = i;
6981 continue;
6984 else if (name != NULL && field_name_match (t_field_name, name))
6986 int bit_size = type->field (i).bitsize ();
6988 if (field_type_p != NULL)
6989 *field_type_p = type->field (i).type ();
6990 if (byte_offset_p != NULL)
6991 *byte_offset_p = fld_offset;
6992 if (bit_offset_p != NULL)
6993 *bit_offset_p = bit_pos % 8;
6994 if (bit_size_p != NULL)
6995 *bit_size_p = bit_size;
6996 return 1;
6998 else if (ada_is_wrapper_field (type, i))
7000 if (find_struct_field (name, type->field (i).type (), fld_offset,
7001 field_type_p, byte_offset_p, bit_offset_p,
7002 bit_size_p, index_p))
7003 return 1;
7005 else if (ada_is_variant_part (type, i))
7007 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7008 fixed type?? */
7009 int j;
7010 struct type *field_type
7011 = ada_check_typedef (type->field (i).type ());
7013 for (j = 0; j < field_type->num_fields (); j += 1)
7015 if (find_struct_field (name, field_type->field (j).type (),
7016 fld_offset
7017 + field_type->field (j).loc_bitpos () / 8,
7018 field_type_p, byte_offset_p,
7019 bit_offset_p, bit_size_p, index_p))
7020 return 1;
7023 else if (index_p != NULL)
7024 *index_p += 1;
7027 /* Field not found so far. If this is a tagged type which
7028 has a parent, try finding that field in the parent now. */
7030 if (parent_offset != -1)
7032 /* As above, only compute the offset when truly needed. */
7033 int fld_offset = offset;
7034 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7036 int bit_pos = type->field (parent_offset).loc_bitpos ();
7037 fld_offset += bit_pos / 8;
7040 if (find_struct_field (name, type->field (parent_offset).type (),
7041 fld_offset, field_type_p, byte_offset_p,
7042 bit_offset_p, bit_size_p, index_p))
7043 return 1;
7046 return 0;
7049 /* Number of user-visible fields in record type TYPE. */
7051 static int
7052 num_visible_fields (struct type *type)
7054 int n;
7056 n = 0;
7057 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7058 return n;
7061 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7062 and search in it assuming it has (class) type TYPE.
7063 If found, return value, else return NULL.
7065 Searches recursively through wrapper fields (e.g., '_parent').
7067 In the case of homonyms in the tagged types, please refer to the
7068 long explanation in find_struct_field's function documentation. */
7070 static struct value *
7071 ada_search_struct_field (const char *name, struct value *arg, int offset,
7072 struct type *type)
7074 int i;
7075 int parent_offset = -1;
7077 type = ada_check_typedef (type);
7078 for (i = 0; i < type->num_fields (); i += 1)
7080 const char *t_field_name = type->field (i).name ();
7082 if (t_field_name == NULL)
7083 continue;
7085 else if (ada_is_parent_field (type, i))
7087 /* This is a field pointing us to the parent type of a tagged
7088 type. As hinted in this function's documentation, we give
7089 preference to fields in the current record first, so what
7090 we do here is just record the index of this field before
7091 we skip it. If it turns out we couldn't find our field
7092 in the current record, then we'll get back to it and search
7093 inside it whether the field might exist in the parent. */
7095 parent_offset = i;
7096 continue;
7099 else if (field_name_match (t_field_name, name))
7100 return ada_value_primitive_field (arg, offset, i, type);
7102 else if (ada_is_wrapper_field (type, i))
7104 struct value *v = /* Do not let indent join lines here. */
7105 ada_search_struct_field (name, arg,
7106 offset + type->field (i).loc_bitpos () / 8,
7107 type->field (i).type ());
7109 if (v != NULL)
7110 return v;
7113 else if (ada_is_variant_part (type, i))
7115 /* PNH: Do we ever get here? See find_struct_field. */
7116 int j;
7117 struct type *field_type = ada_check_typedef (type->field (i).type ());
7118 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7120 for (j = 0; j < field_type->num_fields (); j += 1)
7122 struct value *v = ada_search_struct_field /* Force line
7123 break. */
7124 (name, arg,
7125 var_offset + field_type->field (j).loc_bitpos () / 8,
7126 field_type->field (j).type ());
7128 if (v != NULL)
7129 return v;
7134 /* Field not found so far. If this is a tagged type which
7135 has a parent, try finding that field in the parent now. */
7137 if (parent_offset != -1)
7139 struct value *v = ada_search_struct_field (
7140 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7141 type->field (parent_offset).type ());
7143 if (v != NULL)
7144 return v;
7147 return NULL;
7150 static struct value *ada_index_struct_field_1 (int *, struct value *,
7151 int, struct type *);
7154 /* Return field #INDEX in ARG, where the index is that returned by
7155 * find_struct_field through its INDEX_P argument. Adjust the address
7156 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7157 * If found, return value, else return NULL. */
7159 static struct value *
7160 ada_index_struct_field (int index, struct value *arg, int offset,
7161 struct type *type)
7163 return ada_index_struct_field_1 (&index, arg, offset, type);
7167 /* Auxiliary function for ada_index_struct_field. Like
7168 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7169 * *INDEX_P. */
7171 static struct value *
7172 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7173 struct type *type)
7175 int i;
7176 type = ada_check_typedef (type);
7178 for (i = 0; i < type->num_fields (); i += 1)
7180 if (type->field (i).name () == NULL)
7181 continue;
7182 else if (ada_is_wrapper_field (type, i))
7184 struct value *v = /* Do not let indent join lines here. */
7185 ada_index_struct_field_1 (index_p, arg,
7186 offset + type->field (i).loc_bitpos () / 8,
7187 type->field (i).type ());
7189 if (v != NULL)
7190 return v;
7193 else if (ada_is_variant_part (type, i))
7195 /* PNH: Do we ever get here? See ada_search_struct_field,
7196 find_struct_field. */
7197 error (_("Cannot assign this kind of variant record"));
7199 else if (*index_p == 0)
7200 return ada_value_primitive_field (arg, offset, i, type);
7201 else
7202 *index_p -= 1;
7204 return NULL;
7207 /* Return a string representation of type TYPE. */
7209 static std::string
7210 type_as_string (struct type *type)
7212 string_file tmp_stream;
7214 type_print (type, "", &tmp_stream, -1);
7216 return tmp_stream.release ();
7219 /* Given a type TYPE, look up the type of the component of type named NAME.
7221 Matches any field whose name has NAME as a prefix, possibly
7222 followed by "___".
7224 TYPE can be either a struct or union. If REFOK, TYPE may also
7225 be a (pointer or reference)+ to a struct or union, and the
7226 ultimate target type will be searched.
7228 Looks recursively into variant clauses and parent types.
7230 In the case of homonyms in the tagged types, please refer to the
7231 long explanation in find_struct_field's function documentation.
7233 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7234 TYPE is not a type of the right kind. */
7236 static struct type *
7237 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7238 int noerr)
7240 if (name == NULL)
7241 goto BadName;
7243 if (refok && type != NULL)
7244 while (1)
7246 type = ada_check_typedef (type);
7247 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7248 break;
7249 type = type->target_type ();
7252 if (type == NULL
7253 || (type->code () != TYPE_CODE_STRUCT
7254 && type->code () != TYPE_CODE_UNION))
7256 if (noerr)
7257 return NULL;
7259 error (_("Type %s is not a structure or union type"),
7260 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7263 type = to_static_fixed_type (type);
7265 struct type *result;
7266 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7267 nullptr);
7268 if (result != nullptr)
7269 return result;
7271 BadName:
7272 if (!noerr)
7274 const char *name_str = name != NULL ? name : _("<null>");
7276 error (_("Type %s has no component named %s"),
7277 type_as_string (type).c_str (), name_str);
7280 return NULL;
7283 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7284 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7285 represents an unchecked union (that is, the variant part of a
7286 record that is named in an Unchecked_Union pragma). */
7288 static int
7289 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7291 const char *discrim_name = ada_variant_discrim_name (var_type);
7293 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7297 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7298 within OUTER, determine which variant clause (field number in VAR_TYPE,
7299 numbering from 0) is applicable. Returns -1 if none are. */
7302 ada_which_variant_applies (struct type *var_type, struct value *outer)
7304 int others_clause;
7305 int i;
7306 const char *discrim_name = ada_variant_discrim_name (var_type);
7307 struct value *discrim;
7308 LONGEST discrim_val;
7310 /* Using plain value_from_contents_and_address here causes problems
7311 because we will end up trying to resolve a type that is currently
7312 being constructed. */
7313 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7314 if (discrim == NULL)
7315 return -1;
7316 discrim_val = value_as_long (discrim);
7318 others_clause = -1;
7319 for (i = 0; i < var_type->num_fields (); i += 1)
7321 if (ada_is_others_clause (var_type, i))
7322 others_clause = i;
7323 else if (ada_in_variant (discrim_val, var_type, i))
7324 return i;
7327 return others_clause;
7332 /* Dynamic-Sized Records */
7334 /* Strategy: The type ostensibly attached to a value with dynamic size
7335 (i.e., a size that is not statically recorded in the debugging
7336 data) does not accurately reflect the size or layout of the value.
7337 Our strategy is to convert these values to values with accurate,
7338 conventional types that are constructed on the fly. */
7340 /* There is a subtle and tricky problem here. In general, we cannot
7341 determine the size of dynamic records without its data. However,
7342 the 'struct value' data structure, which GDB uses to represent
7343 quantities in the inferior process (the target), requires the size
7344 of the type at the time of its allocation in order to reserve space
7345 for GDB's internal copy of the data. That's why the
7346 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7347 rather than struct value*s.
7349 However, GDB's internal history variables ($1, $2, etc.) are
7350 struct value*s containing internal copies of the data that are not, in
7351 general, the same as the data at their corresponding addresses in
7352 the target. Fortunately, the types we give to these values are all
7353 conventional, fixed-size types (as per the strategy described
7354 above), so that we don't usually have to perform the
7355 'to_fixed_xxx_type' conversions to look at their values.
7356 Unfortunately, there is one exception: if one of the internal
7357 history variables is an array whose elements are unconstrained
7358 records, then we will need to create distinct fixed types for each
7359 element selected. */
7361 /* The upshot of all of this is that many routines take a (type, host
7362 address, target address) triple as arguments to represent a value.
7363 The host address, if non-null, is supposed to contain an internal
7364 copy of the relevant data; otherwise, the program is to consult the
7365 target at the target address. */
7367 /* Assuming that VAL0 represents a pointer value, the result of
7368 dereferencing it. Differs from value_ind in its treatment of
7369 dynamic-sized types. */
7371 struct value *
7372 ada_value_ind (struct value *val0)
7374 struct value *val = value_ind (val0);
7376 if (ada_is_tagged_type (val->type (), 0))
7377 val = ada_tag_value_at_base_address (val);
7379 return ada_to_fixed_value (val);
7382 /* The value resulting from dereferencing any "reference to"
7383 qualifiers on VAL0. */
7385 static struct value *
7386 ada_coerce_ref (struct value *val0)
7388 if (val0->type ()->code () == TYPE_CODE_REF)
7390 struct value *val = val0;
7392 val = coerce_ref (val);
7394 if (ada_is_tagged_type (val->type (), 0))
7395 val = ada_tag_value_at_base_address (val);
7397 return ada_to_fixed_value (val);
7399 else
7400 return val0;
7403 /* Return the bit alignment required for field #F of template type TYPE. */
7405 static unsigned int
7406 field_alignment (struct type *type, int f)
7408 const char *name = type->field (f).name ();
7409 int len;
7410 int align_offset;
7412 /* The field name should never be null, unless the debugging information
7413 is somehow malformed. In this case, we assume the field does not
7414 require any alignment. */
7415 if (name == NULL)
7416 return 1;
7418 len = strlen (name);
7420 if (!isdigit (name[len - 1]))
7421 return 1;
7423 if (isdigit (name[len - 2]))
7424 align_offset = len - 2;
7425 else
7426 align_offset = len - 1;
7428 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7429 return TARGET_CHAR_BIT;
7431 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7434 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7436 static struct symbol *
7437 ada_find_any_type_symbol (const char *name)
7439 return standard_lookup (name, get_selected_block (nullptr),
7440 SEARCH_TYPE_DOMAIN);
7443 /* Find a type named NAME. Ignores ambiguity. This routine will look
7444 solely for types defined by debug info, it will not search the GDB
7445 primitive types. */
7447 static struct type *
7448 ada_find_any_type (const char *name)
7450 struct symbol *sym = ada_find_any_type_symbol (name);
7452 if (sym != NULL)
7453 return sym->type ();
7455 return NULL;
7458 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7459 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7460 symbol, in which case it is returned. Otherwise, this looks for
7461 symbols whose name is that of NAME_SYM suffixed with "___XR".
7462 Return symbol if found, and NULL otherwise. */
7464 static bool
7465 ada_is_renaming_symbol (struct symbol *name_sym)
7467 const char *name = name_sym->linkage_name ();
7468 return strstr (name, "___XR") != NULL;
7471 /* Because of GNAT encoding conventions, several GDB symbols may match a
7472 given type name. If the type denoted by TYPE0 is to be preferred to
7473 that of TYPE1 for purposes of type printing, return non-zero;
7474 otherwise return 0. */
7477 ada_prefer_type (struct type *type0, struct type *type1)
7479 if (type1 == NULL)
7480 return 1;
7481 else if (type0 == NULL)
7482 return 0;
7483 else if (type1->code () == TYPE_CODE_VOID)
7484 return 1;
7485 else if (type0->code () == TYPE_CODE_VOID)
7486 return 0;
7487 else if (type1->name () == NULL && type0->name () != NULL)
7488 return 1;
7489 else if (ada_is_constrained_packed_array_type (type0))
7490 return 1;
7491 else if (ada_is_array_descriptor_type (type0)
7492 && !ada_is_array_descriptor_type (type1))
7493 return 1;
7494 else
7496 const char *type0_name = type0->name ();
7497 const char *type1_name = type1->name ();
7499 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7500 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7501 return 1;
7503 return 0;
7506 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7507 null. */
7509 const char *
7510 ada_type_name (struct type *type)
7512 if (type == NULL)
7513 return NULL;
7514 return type->name ();
7517 /* Search the list of "descriptive" types associated to TYPE for a type
7518 whose name is NAME. */
7520 static struct type *
7521 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7523 struct type *result, *tmp;
7525 if (ada_ignore_descriptive_types_p)
7526 return NULL;
7528 /* If there no descriptive-type info, then there is no parallel type
7529 to be found. */
7530 if (!HAVE_GNAT_AUX_INFO (type))
7531 return NULL;
7533 result = TYPE_DESCRIPTIVE_TYPE (type);
7534 while (result != NULL)
7536 const char *result_name = ada_type_name (result);
7538 if (result_name == NULL)
7540 warning (_("unexpected null name on descriptive type"));
7541 return NULL;
7544 /* If the names match, stop. */
7545 if (strcmp (result_name, name) == 0)
7546 break;
7548 /* Otherwise, look at the next item on the list, if any. */
7549 if (HAVE_GNAT_AUX_INFO (result))
7550 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7551 else
7552 tmp = NULL;
7554 /* If not found either, try after having resolved the typedef. */
7555 if (tmp != NULL)
7556 result = tmp;
7557 else
7559 result = check_typedef (result);
7560 if (HAVE_GNAT_AUX_INFO (result))
7561 result = TYPE_DESCRIPTIVE_TYPE (result);
7562 else
7563 result = NULL;
7567 /* If we didn't find a match, see whether this is a packed array. With
7568 older compilers, the descriptive type information is either absent or
7569 irrelevant when it comes to packed arrays so the above lookup fails.
7570 Fall back to using a parallel lookup by name in this case. */
7571 if (result == NULL && ada_is_constrained_packed_array_type (type))
7572 return ada_find_any_type (name);
7574 return result;
7577 /* Find a parallel type to TYPE with the specified NAME, using the
7578 descriptive type taken from the debugging information, if available,
7579 and otherwise using the (slower) name-based method. */
7581 static struct type *
7582 ada_find_parallel_type_with_name (struct type *type, const char *name)
7584 struct type *result = NULL;
7586 if (HAVE_GNAT_AUX_INFO (type))
7587 result = find_parallel_type_by_descriptive_type (type, name);
7588 else
7589 result = ada_find_any_type (name);
7591 return result;
7594 /* Same as above, but specify the name of the parallel type by appending
7595 SUFFIX to the name of TYPE. */
7597 struct type *
7598 ada_find_parallel_type (struct type *type, const char *suffix)
7600 char *name;
7601 const char *type_name = ada_type_name (type);
7602 int len;
7604 if (type_name == NULL)
7605 return NULL;
7607 len = strlen (type_name);
7609 name = (char *) alloca (len + strlen (suffix) + 1);
7611 strcpy (name, type_name);
7612 strcpy (name + len, suffix);
7614 return ada_find_parallel_type_with_name (type, name);
7617 /* If TYPE is a variable-size record type, return the corresponding template
7618 type describing its fields. Otherwise, return NULL. */
7620 static struct type *
7621 dynamic_template_type (struct type *type)
7623 type = ada_check_typedef (type);
7625 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7626 || ada_type_name (type) == NULL)
7627 return NULL;
7628 else
7630 int len = strlen (ada_type_name (type));
7632 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7633 return type;
7634 else
7635 return ada_find_parallel_type (type, "___XVE");
7639 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7640 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7642 static int
7643 is_dynamic_field (struct type *templ_type, int field_num)
7645 const char *name = templ_type->field (field_num).name ();
7647 return name != NULL
7648 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7649 && strstr (name, "___XVL") != NULL;
7652 /* The index of the variant field of TYPE, or -1 if TYPE does not
7653 represent a variant record type. */
7655 static int
7656 variant_field_index (struct type *type)
7658 int f;
7660 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7661 return -1;
7663 for (f = 0; f < type->num_fields (); f += 1)
7665 if (ada_is_variant_part (type, f))
7666 return f;
7668 return -1;
7671 /* A record type with no fields. */
7673 static struct type *
7674 empty_record (struct type *templ)
7676 struct type *type = type_allocator (templ).new_type ();
7678 type->set_code (TYPE_CODE_STRUCT);
7679 INIT_NONE_SPECIFIC (type);
7680 type->set_name ("<empty>");
7681 type->set_length (0);
7682 return type;
7685 /* An ordinary record type (with fixed-length fields) that describes
7686 the value of type TYPE at VALADDR or ADDRESS (see comments at
7687 the beginning of this section) VAL according to GNAT conventions.
7688 DVAL0 should describe the (portion of a) record that contains any
7689 necessary discriminants. It should be NULL if VAL->type () is
7690 an outer-level type (i.e., as opposed to a branch of a variant.) A
7691 variant field (unless unchecked) is replaced by a particular branch
7692 of the variant.
7694 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7695 length are not statically known are discarded. As a consequence,
7696 VALADDR, ADDRESS and DVAL0 are ignored.
7698 NOTE: Limitations: For now, we assume that dynamic fields and
7699 variants occupy whole numbers of bytes. However, they need not be
7700 byte-aligned. */
7702 struct type *
7703 ada_template_to_fixed_record_type_1 (struct type *type,
7704 const gdb_byte *valaddr,
7705 CORE_ADDR address, struct value *dval0,
7706 int keep_dynamic_fields)
7708 struct value *dval;
7709 struct type *rtype;
7710 int nfields, bit_len;
7711 int variant_field;
7712 long off;
7713 int fld_bit_len;
7714 int f;
7716 scoped_value_mark mark;
7718 /* Compute the number of fields in this record type that are going
7719 to be processed: unless keep_dynamic_fields, this includes only
7720 fields whose position and length are static will be processed. */
7721 if (keep_dynamic_fields)
7722 nfields = type->num_fields ();
7723 else
7725 nfields = 0;
7726 while (nfields < type->num_fields ()
7727 && !ada_is_variant_part (type, nfields)
7728 && !is_dynamic_field (type, nfields))
7729 nfields++;
7732 rtype = type_allocator (type).new_type ();
7733 rtype->set_code (TYPE_CODE_STRUCT);
7734 INIT_NONE_SPECIFIC (rtype);
7735 rtype->alloc_fields (nfields);
7736 rtype->set_name (ada_type_name (type));
7737 rtype->set_is_fixed_instance (true);
7739 off = 0;
7740 bit_len = 0;
7741 variant_field = -1;
7743 for (f = 0; f < nfields; f += 1)
7745 off = align_up (off, field_alignment (type, f))
7746 + type->field (f).loc_bitpos ();
7747 rtype->field (f).set_loc_bitpos (off);
7748 rtype->field (f).set_bitsize (0);
7750 if (ada_is_variant_part (type, f))
7752 variant_field = f;
7753 fld_bit_len = 0;
7755 else if (is_dynamic_field (type, f))
7757 const gdb_byte *field_valaddr = valaddr;
7758 CORE_ADDR field_address = address;
7759 struct type *field_type = type->field (f).type ()->target_type ();
7761 if (dval0 == NULL)
7763 /* Using plain value_from_contents_and_address here
7764 causes problems because we will end up trying to
7765 resolve a type that is currently being
7766 constructed. */
7767 dval = value_from_contents_and_address_unresolved (rtype,
7768 valaddr,
7769 address);
7770 rtype = dval->type ();
7772 else
7773 dval = dval0;
7775 /* If the type referenced by this field is an aligner type, we need
7776 to unwrap that aligner type, because its size might not be set.
7777 Keeping the aligner type would cause us to compute the wrong
7778 size for this field, impacting the offset of the all the fields
7779 that follow this one. */
7780 if (ada_is_aligner_type (field_type))
7782 long field_offset = type->field (f).loc_bitpos ();
7784 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7785 field_address = cond_offset_target (field_address, field_offset);
7786 field_type = ada_aligned_type (field_type);
7789 field_valaddr = cond_offset_host (field_valaddr,
7790 off / TARGET_CHAR_BIT);
7791 field_address = cond_offset_target (field_address,
7792 off / TARGET_CHAR_BIT);
7794 /* Get the fixed type of the field. Note that, in this case,
7795 we do not want to get the real type out of the tag: if
7796 the current field is the parent part of a tagged record,
7797 we will get the tag of the object. Clearly wrong: the real
7798 type of the parent is not the real type of the child. We
7799 would end up in an infinite loop. */
7800 field_type = ada_get_base_type (field_type);
7801 field_type = ada_to_fixed_type (field_type, field_valaddr,
7802 field_address, dval, 0);
7804 rtype->field (f).set_type (field_type);
7805 rtype->field (f).set_name (type->field (f).name ());
7806 /* The multiplication can potentially overflow. But because
7807 the field length has been size-checked just above, and
7808 assuming that the maximum size is a reasonable value,
7809 an overflow should not happen in practice. So rather than
7810 adding overflow recovery code to this already complex code,
7811 we just assume that it's not going to happen. */
7812 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7814 else
7816 /* Note: If this field's type is a typedef, it is important
7817 to preserve the typedef layer.
7819 Otherwise, we might be transforming a typedef to a fat
7820 pointer (encoding a pointer to an unconstrained array),
7821 into a basic fat pointer (encoding an unconstrained
7822 array). As both types are implemented using the same
7823 structure, the typedef is the only clue which allows us
7824 to distinguish between the two options. Stripping it
7825 would prevent us from printing this field appropriately. */
7826 rtype->field (f).set_type (type->field (f).type ());
7827 rtype->field (f).set_name (type->field (f).name ());
7828 if (type->field (f).bitsize () > 0)
7830 fld_bit_len = type->field (f).bitsize ();
7831 rtype->field (f).set_bitsize (fld_bit_len);
7833 else
7835 struct type *field_type = type->field (f).type ();
7837 /* We need to be careful of typedefs when computing
7838 the length of our field. If this is a typedef,
7839 get the length of the target type, not the length
7840 of the typedef. */
7841 if (field_type->code () == TYPE_CODE_TYPEDEF)
7842 field_type = ada_typedef_target_type (field_type);
7844 fld_bit_len =
7845 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7848 if (off + fld_bit_len > bit_len)
7849 bit_len = off + fld_bit_len;
7850 off += fld_bit_len;
7851 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7854 /* We handle the variant part, if any, at the end because of certain
7855 odd cases in which it is re-ordered so as NOT to be the last field of
7856 the record. This can happen in the presence of representation
7857 clauses. */
7858 if (variant_field >= 0)
7860 struct type *branch_type;
7862 off = rtype->field (variant_field).loc_bitpos ();
7864 if (dval0 == NULL)
7866 /* Using plain value_from_contents_and_address here causes
7867 problems because we will end up trying to resolve a type
7868 that is currently being constructed. */
7869 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7870 address);
7871 rtype = dval->type ();
7873 else
7874 dval = dval0;
7876 branch_type =
7877 to_fixed_variant_branch_type
7878 (type->field (variant_field).type (),
7879 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7880 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7881 if (branch_type == NULL)
7883 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7884 rtype->field (f - 1) = rtype->field (f);
7885 rtype->set_num_fields (rtype->num_fields () - 1);
7887 else
7889 rtype->field (variant_field).set_type (branch_type);
7890 rtype->field (variant_field).set_name ("S");
7891 fld_bit_len =
7892 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
7893 if (off + fld_bit_len > bit_len)
7894 bit_len = off + fld_bit_len;
7896 rtype->set_length
7897 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7901 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7902 should contain the alignment of that record, which should be a strictly
7903 positive value. If null or negative, then something is wrong, most
7904 probably in the debug info. In that case, we don't round up the size
7905 of the resulting type. If this record is not part of another structure,
7906 the current RTYPE length might be good enough for our purposes. */
7907 if (type->length () <= 0)
7909 if (rtype->name ())
7910 warning (_("Invalid type size for `%s' detected: %s."),
7911 rtype->name (), pulongest (type->length ()));
7912 else
7913 warning (_("Invalid type size for <unnamed> detected: %s."),
7914 pulongest (type->length ()));
7916 else
7917 rtype->set_length (align_up (rtype->length (), type->length ()));
7919 return rtype;
7922 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7923 of 1. */
7925 static struct type *
7926 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7927 CORE_ADDR address, struct value *dval0)
7929 return ada_template_to_fixed_record_type_1 (type, valaddr,
7930 address, dval0, 1);
7933 /* An ordinary record type in which ___XVL-convention fields and
7934 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7935 static approximations, containing all possible fields. Uses
7936 no runtime values. Useless for use in values, but that's OK,
7937 since the results are used only for type determinations. Works on both
7938 structs and unions. Representation note: to save space, we memorize
7939 the result of this function in the type::target_type of the
7940 template type. */
7942 static struct type *
7943 template_to_static_fixed_type (struct type *type0)
7945 struct type *type;
7946 int nfields;
7947 int f;
7949 /* No need no do anything if the input type is already fixed. */
7950 if (type0->is_fixed_instance ())
7951 return type0;
7953 /* Likewise if we already have computed the static approximation. */
7954 if (type0->target_type () != NULL)
7955 return type0->target_type ();
7957 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
7958 type = type0;
7959 nfields = type0->num_fields ();
7961 /* Whether or not we cloned TYPE0, cache the result so that we don't do
7962 recompute all over next time. */
7963 type0->set_target_type (type);
7965 for (f = 0; f < nfields; f += 1)
7967 struct type *field_type = type0->field (f).type ();
7968 struct type *new_type;
7970 if (is_dynamic_field (type0, f))
7972 field_type = ada_check_typedef (field_type);
7973 new_type = to_static_fixed_type (field_type->target_type ());
7975 else
7976 new_type = static_unwrap_type (field_type);
7978 if (new_type != field_type)
7980 /* Clone TYPE0 only the first time we get a new field type. */
7981 if (type == type0)
7983 type = type_allocator (type0).new_type ();
7984 type0->set_target_type (type);
7985 type->set_code (type0->code ());
7986 INIT_NONE_SPECIFIC (type);
7988 type->copy_fields (type0);
7990 type->set_name (ada_type_name (type0));
7991 type->set_is_fixed_instance (true);
7992 type->set_length (0);
7994 type->field (f).set_type (new_type);
7995 type->field (f).set_name (type0->field (f).name ());
7999 return type;
8002 /* Given an object of type TYPE whose contents are at VALADDR and
8003 whose address in memory is ADDRESS, returns a revision of TYPE,
8004 which should be a non-dynamic-sized record, in which the variant
8005 part, if any, is replaced with the appropriate branch. Looks
8006 for discriminant values in DVAL0, which can be NULL if the record
8007 contains the necessary discriminant values. */
8009 static struct type *
8010 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8011 CORE_ADDR address, struct value *dval0)
8013 struct value *dval;
8014 struct type *rtype;
8015 struct type *branch_type;
8016 int nfields = type->num_fields ();
8017 int variant_field = variant_field_index (type);
8019 if (variant_field == -1)
8020 return type;
8022 scoped_value_mark mark;
8023 if (dval0 == NULL)
8025 dval = value_from_contents_and_address (type, valaddr, address);
8026 type = dval->type ();
8028 else
8029 dval = dval0;
8031 rtype = type_allocator (type).new_type ();
8032 rtype->set_code (TYPE_CODE_STRUCT);
8033 INIT_NONE_SPECIFIC (rtype);
8034 rtype->copy_fields (type);
8036 rtype->set_name (ada_type_name (type));
8037 rtype->set_is_fixed_instance (true);
8038 rtype->set_length (type->length ());
8040 branch_type = to_fixed_variant_branch_type
8041 (type->field (variant_field).type (),
8042 cond_offset_host (valaddr,
8043 type->field (variant_field).loc_bitpos ()
8044 / TARGET_CHAR_BIT),
8045 cond_offset_target (address,
8046 type->field (variant_field).loc_bitpos ()
8047 / TARGET_CHAR_BIT), dval);
8048 if (branch_type == NULL)
8050 int f;
8052 for (f = variant_field + 1; f < nfields; f += 1)
8053 rtype->field (f - 1) = rtype->field (f);
8054 rtype->set_num_fields (rtype->num_fields () - 1);
8056 else
8058 rtype->field (variant_field).set_type (branch_type);
8059 rtype->field (variant_field).set_name ("S");
8060 rtype->field (variant_field).set_bitsize (0);
8061 rtype->set_length (rtype->length () + branch_type->length ());
8064 rtype->set_length (rtype->length ()
8065 - type->field (variant_field).type ()->length ());
8067 return rtype;
8070 /* An ordinary record type (with fixed-length fields) that describes
8071 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8072 beginning of this section]. Any necessary discriminants' values
8073 should be in DVAL, a record value; it may be NULL if the object
8074 at ADDR itself contains any necessary discriminant values.
8075 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8076 values from the record are needed. Except in the case that DVAL,
8077 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8078 unchecked) is replaced by a particular branch of the variant.
8080 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8081 is questionable and may be removed. It can arise during the
8082 processing of an unconstrained-array-of-record type where all the
8083 variant branches have exactly the same size. This is because in
8084 such cases, the compiler does not bother to use the XVS convention
8085 when encoding the record. I am currently dubious of this
8086 shortcut and suspect the compiler should be altered. FIXME. */
8088 static struct type *
8089 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8090 CORE_ADDR address, struct value *dval)
8092 struct type *templ_type;
8094 if (type0->is_fixed_instance ())
8095 return type0;
8097 templ_type = dynamic_template_type (type0);
8099 if (templ_type != NULL)
8100 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8101 else if (variant_field_index (type0) >= 0)
8103 if (dval == NULL && valaddr == NULL && address == 0)
8104 return type0;
8105 return to_record_with_fixed_variant_part (type0, valaddr, address,
8106 dval);
8108 else
8110 type0->set_is_fixed_instance (true);
8111 return type0;
8116 /* An ordinary record type (with fixed-length fields) that describes
8117 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8118 union type. Any necessary discriminants' values should be in DVAL,
8119 a record value. That is, this routine selects the appropriate
8120 branch of the union at ADDR according to the discriminant value
8121 indicated in the union's type name. Returns VAR_TYPE0 itself if
8122 it represents a variant subject to a pragma Unchecked_Union. */
8124 static struct type *
8125 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8126 CORE_ADDR address, struct value *dval)
8128 int which;
8129 struct type *templ_type;
8130 struct type *var_type;
8132 if (var_type0->code () == TYPE_CODE_PTR)
8133 var_type = var_type0->target_type ();
8134 else
8135 var_type = var_type0;
8137 templ_type = ada_find_parallel_type (var_type, "___XVU");
8139 if (templ_type != NULL)
8140 var_type = templ_type;
8142 if (is_unchecked_variant (var_type, dval->type ()))
8143 return var_type0;
8144 which = ada_which_variant_applies (var_type, dval);
8146 if (which < 0)
8147 return empty_record (var_type);
8148 else if (is_dynamic_field (var_type, which))
8149 return to_fixed_record_type
8150 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8151 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8152 return
8153 to_fixed_record_type
8154 (var_type->field (which).type (), valaddr, address, dval);
8155 else
8156 return var_type->field (which).type ();
8159 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8160 ENCODING_TYPE, a type following the GNAT conventions for discrete
8161 type encodings, only carries redundant information. */
8163 static int
8164 ada_is_redundant_range_encoding (struct type *range_type,
8165 struct type *encoding_type)
8167 const char *bounds_str;
8168 int n;
8169 LONGEST lo, hi;
8171 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8173 if (get_base_type (range_type)->code ()
8174 != get_base_type (encoding_type)->code ())
8176 /* The compiler probably used a simple base type to describe
8177 the range type instead of the range's actual base type,
8178 expecting us to get the real base type from the encoding
8179 anyway. In this situation, the encoding cannot be ignored
8180 as redundant. */
8181 return 0;
8184 if (is_dynamic_type (range_type))
8185 return 0;
8187 if (encoding_type->name () == NULL)
8188 return 0;
8190 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8191 if (bounds_str == NULL)
8192 return 0;
8194 n = 8; /* Skip "___XDLU_". */
8195 if (!ada_scan_number (bounds_str, n, &lo, &n))
8196 return 0;
8197 if (range_type->bounds ()->low.const_val () != lo)
8198 return 0;
8200 n += 2; /* Skip the "__" separator between the two bounds. */
8201 if (!ada_scan_number (bounds_str, n, &hi, &n))
8202 return 0;
8203 if (range_type->bounds ()->high.const_val () != hi)
8204 return 0;
8206 return 1;
8209 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8210 a type following the GNAT encoding for describing array type
8211 indices, only carries redundant information. */
8213 static int
8214 ada_is_redundant_index_type_desc (struct type *array_type,
8215 struct type *desc_type)
8217 struct type *this_layer = check_typedef (array_type);
8218 int i;
8220 for (i = 0; i < desc_type->num_fields (); i++)
8222 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8223 desc_type->field (i).type ()))
8224 return 0;
8225 this_layer = check_typedef (this_layer->target_type ());
8228 return 1;
8231 /* Assuming that TYPE0 is an array type describing the type of a value
8232 at ADDR, and that DVAL describes a record containing any
8233 discriminants used in TYPE0, returns a type for the value that
8234 contains no dynamic components (that is, no components whose sizes
8235 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8236 true, gives an error message if the resulting type's size is over
8237 varsize_limit. */
8239 static struct type *
8240 to_fixed_array_type (struct type *type0, struct value *dval,
8241 int ignore_too_big)
8243 struct type *index_type_desc;
8244 struct type *result;
8245 int constrained_packed_array_p;
8246 static const char *xa_suffix = "___XA";
8248 type0 = ada_check_typedef (type0);
8249 if (type0->is_fixed_instance ())
8250 return type0;
8252 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8253 if (constrained_packed_array_p)
8255 type0 = decode_constrained_packed_array_type (type0);
8256 if (type0 == nullptr)
8257 error (_("could not decode constrained packed array type"));
8260 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8262 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8263 encoding suffixed with 'P' may still be generated. If so,
8264 it should be used to find the XA type. */
8266 if (index_type_desc == NULL)
8268 const char *type_name = ada_type_name (type0);
8270 if (type_name != NULL)
8272 const int len = strlen (type_name);
8273 char *name = (char *) alloca (len + strlen (xa_suffix));
8275 if (type_name[len - 1] == 'P')
8277 strcpy (name, type_name);
8278 strcpy (name + len - 1, xa_suffix);
8279 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8284 ada_fixup_array_indexes_type (index_type_desc);
8285 if (index_type_desc != NULL
8286 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8288 /* Ignore this ___XA parallel type, as it does not bring any
8289 useful information. This allows us to avoid creating fixed
8290 versions of the array's index types, which would be identical
8291 to the original ones. This, in turn, can also help avoid
8292 the creation of fixed versions of the array itself. */
8293 index_type_desc = NULL;
8296 if (index_type_desc == NULL)
8298 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8300 /* NOTE: elt_type---the fixed version of elt_type0---should never
8301 depend on the contents of the array in properly constructed
8302 debugging data. */
8303 /* Create a fixed version of the array element type.
8304 We're not providing the address of an element here,
8305 and thus the actual object value cannot be inspected to do
8306 the conversion. This should not be a problem, since arrays of
8307 unconstrained objects are not allowed. In particular, all
8308 the elements of an array of a tagged type should all be of
8309 the same type specified in the debugging info. No need to
8310 consult the object tag. */
8311 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8313 /* Make sure we always create a new array type when dealing with
8314 packed array types, since we're going to fix-up the array
8315 type length and element bitsize a little further down. */
8316 if (elt_type0 == elt_type && !constrained_packed_array_p)
8317 result = type0;
8318 else
8320 type_allocator alloc (type0);
8321 result = create_array_type (alloc, elt_type, type0->index_type ());
8324 else
8326 int i;
8327 struct type *elt_type0;
8329 elt_type0 = type0;
8330 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8331 elt_type0 = elt_type0->target_type ();
8333 /* NOTE: result---the fixed version of elt_type0---should never
8334 depend on the contents of the array in properly constructed
8335 debugging data. */
8336 /* Create a fixed version of the array element type.
8337 We're not providing the address of an element here,
8338 and thus the actual object value cannot be inspected to do
8339 the conversion. This should not be a problem, since arrays of
8340 unconstrained objects are not allowed. In particular, all
8341 the elements of an array of a tagged type should all be of
8342 the same type specified in the debugging info. No need to
8343 consult the object tag. */
8344 result =
8345 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8347 elt_type0 = type0;
8348 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8350 struct type *range_type =
8351 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8353 type_allocator alloc (elt_type0);
8354 result = create_array_type (alloc, result, range_type);
8355 elt_type0 = elt_type0->target_type ();
8359 /* We want to preserve the type name. This can be useful when
8360 trying to get the type name of a value that has already been
8361 printed (for instance, if the user did "print VAR; whatis $". */
8362 result->set_name (type0->name ());
8364 if (constrained_packed_array_p)
8366 /* So far, the resulting type has been created as if the original
8367 type was a regular (non-packed) array type. As a result, the
8368 bitsize of the array elements needs to be set again, and the array
8369 length needs to be recomputed based on that bitsize. */
8370 int len = result->length () / result->target_type ()->length ();
8371 int elt_bitsize = type0->field (0).bitsize ();
8373 result->field (0).set_bitsize (elt_bitsize);
8374 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8375 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8376 result->set_length (result->length () + 1);
8379 result->set_is_fixed_instance (true);
8380 return result;
8384 /* A standard type (containing no dynamically sized components)
8385 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8386 DVAL describes a record containing any discriminants used in TYPE0,
8387 and may be NULL if there are none, or if the object of type TYPE at
8388 ADDRESS or in VALADDR contains these discriminants.
8390 If CHECK_TAG is not null, in the case of tagged types, this function
8391 attempts to locate the object's tag and use it to compute the actual
8392 type. However, when ADDRESS is null, we cannot use it to determine the
8393 location of the tag, and therefore compute the tagged type's actual type.
8394 So we return the tagged type without consulting the tag. */
8396 static struct type *
8397 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8398 CORE_ADDR address, struct value *dval, int check_tag)
8400 type = ada_check_typedef (type);
8402 /* Only un-fixed types need to be handled here. */
8403 if (!HAVE_GNAT_AUX_INFO (type))
8404 return type;
8406 switch (type->code ())
8408 default:
8409 return type;
8410 case TYPE_CODE_STRUCT:
8412 struct type *static_type = to_static_fixed_type (type);
8413 struct type *fixed_record_type =
8414 to_fixed_record_type (type, valaddr, address, NULL);
8416 /* If STATIC_TYPE is a tagged type and we know the object's address,
8417 then we can determine its tag, and compute the object's actual
8418 type from there. Note that we have to use the fixed record
8419 type (the parent part of the record may have dynamic fields
8420 and the way the location of _tag is expressed may depend on
8421 them). */
8423 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8425 struct value *tag =
8426 value_tag_from_contents_and_address
8427 (fixed_record_type,
8428 valaddr,
8429 address);
8430 struct type *real_type = type_from_tag (tag);
8431 struct value *obj =
8432 value_from_contents_and_address (fixed_record_type,
8433 valaddr,
8434 address);
8435 fixed_record_type = obj->type ();
8436 if (real_type != NULL)
8437 return to_fixed_record_type
8438 (real_type, NULL,
8439 ada_tag_value_at_base_address (obj)->address (), NULL);
8442 /* Check to see if there is a parallel ___XVZ variable.
8443 If there is, then it provides the actual size of our type. */
8444 else if (ada_type_name (fixed_record_type) != NULL)
8446 const char *name = ada_type_name (fixed_record_type);
8447 char *xvz_name
8448 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8449 bool xvz_found = false;
8450 LONGEST size;
8452 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8455 xvz_found = get_int_var_value (xvz_name, size);
8457 catch (const gdb_exception_error &except)
8459 /* We found the variable, but somehow failed to read
8460 its value. Rethrow the same error, but with a little
8461 bit more information, to help the user understand
8462 what went wrong (Eg: the variable might have been
8463 optimized out). */
8464 throw_error (except.error,
8465 _("unable to read value of %s (%s)"),
8466 xvz_name, except.what ());
8469 if (xvz_found && fixed_record_type->length () != size)
8471 fixed_record_type = copy_type (fixed_record_type);
8472 fixed_record_type->set_length (size);
8474 /* The FIXED_RECORD_TYPE may have be a stub. We have
8475 observed this when the debugging info is STABS, and
8476 apparently it is something that is hard to fix.
8478 In practice, we don't need the actual type definition
8479 at all, because the presence of the XVZ variable allows us
8480 to assume that there must be a XVS type as well, which we
8481 should be able to use later, when we need the actual type
8482 definition.
8484 In the meantime, pretend that the "fixed" type we are
8485 returning is NOT a stub, because this can cause trouble
8486 when using this type to create new types targeting it.
8487 Indeed, the associated creation routines often check
8488 whether the target type is a stub and will try to replace
8489 it, thus using a type with the wrong size. This, in turn,
8490 might cause the new type to have the wrong size too.
8491 Consider the case of an array, for instance, where the size
8492 of the array is computed from the number of elements in
8493 our array multiplied by the size of its element. */
8494 fixed_record_type->set_is_stub (false);
8497 return fixed_record_type;
8499 case TYPE_CODE_ARRAY:
8500 return to_fixed_array_type (type, dval, 1);
8501 case TYPE_CODE_UNION:
8502 if (dval == NULL)
8503 return type;
8504 else
8505 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8509 /* The same as ada_to_fixed_type_1, except that it preserves the type
8510 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8512 The typedef layer needs be preserved in order to differentiate between
8513 arrays and array pointers when both types are implemented using the same
8514 fat pointer. In the array pointer case, the pointer is encoded as
8515 a typedef of the pointer type. For instance, considering:
8517 type String_Access is access String;
8518 S1 : String_Access := null;
8520 To the debugger, S1 is defined as a typedef of type String. But
8521 to the user, it is a pointer. So if the user tries to print S1,
8522 we should not dereference the array, but print the array address
8523 instead.
8525 If we didn't preserve the typedef layer, we would lose the fact that
8526 the type is to be presented as a pointer (needs de-reference before
8527 being printed). And we would also use the source-level type name. */
8529 struct type *
8530 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8531 CORE_ADDR address, struct value *dval, int check_tag)
8534 struct type *fixed_type =
8535 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8537 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8538 then preserve the typedef layer.
8540 Implementation note: We can only check the main-type portion of
8541 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8542 from TYPE now returns a type that has the same instance flags
8543 as TYPE. For instance, if TYPE is a "typedef const", and its
8544 target type is a "struct", then the typedef elimination will return
8545 a "const" version of the target type. See check_typedef for more
8546 details about how the typedef layer elimination is done.
8548 brobecker/2010-11-19: It seems to me that the only case where it is
8549 useful to preserve the typedef layer is when dealing with fat pointers.
8550 Perhaps, we could add a check for that and preserve the typedef layer
8551 only in that situation. But this seems unnecessary so far, probably
8552 because we call check_typedef/ada_check_typedef pretty much everywhere.
8554 if (type->code () == TYPE_CODE_TYPEDEF
8555 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8556 == TYPE_MAIN_TYPE (fixed_type)))
8557 return type;
8559 return fixed_type;
8562 /* A standard (static-sized) type corresponding as well as possible to
8563 TYPE0, but based on no runtime data. */
8565 static struct type *
8566 to_static_fixed_type (struct type *type0)
8568 struct type *type;
8570 if (type0 == NULL)
8571 return NULL;
8573 if (type0->is_fixed_instance ())
8574 return type0;
8576 type0 = ada_check_typedef (type0);
8578 switch (type0->code ())
8580 default:
8581 return type0;
8582 case TYPE_CODE_STRUCT:
8583 type = dynamic_template_type (type0);
8584 if (type != NULL)
8585 return template_to_static_fixed_type (type);
8586 else
8587 return template_to_static_fixed_type (type0);
8588 case TYPE_CODE_UNION:
8589 type = ada_find_parallel_type (type0, "___XVU");
8590 if (type != NULL)
8591 return template_to_static_fixed_type (type);
8592 else
8593 return template_to_static_fixed_type (type0);
8597 /* A static approximation of TYPE with all type wrappers removed. */
8599 static struct type *
8600 static_unwrap_type (struct type *type)
8602 if (ada_is_aligner_type (type))
8604 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8605 if (ada_type_name (type1) == NULL)
8606 type1->set_name (ada_type_name (type));
8608 return static_unwrap_type (type1);
8610 else
8612 struct type *raw_real_type = ada_get_base_type (type);
8614 if (raw_real_type == type)
8615 return type;
8616 else
8617 return to_static_fixed_type (raw_real_type);
8621 /* In some cases, incomplete and private types require
8622 cross-references that are not resolved as records (for example,
8623 type Foo;
8624 type FooP is access Foo;
8625 V: FooP;
8626 type Foo is array ...;
8627 ). In these cases, since there is no mechanism for producing
8628 cross-references to such types, we instead substitute for FooP a
8629 stub enumeration type that is nowhere resolved, and whose tag is
8630 the name of the actual type. Call these types "non-record stubs". */
8632 /* A type equivalent to TYPE that is not a non-record stub, if one
8633 exists, otherwise TYPE. */
8635 struct type *
8636 ada_check_typedef (struct type *type)
8638 if (type == NULL)
8639 return NULL;
8641 /* If our type is an access to an unconstrained array, which is encoded
8642 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8643 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8644 what allows us to distinguish between fat pointers that represent
8645 array types, and fat pointers that represent array access types
8646 (in both cases, the compiler implements them as fat pointers). */
8647 if (ada_is_access_to_unconstrained_array (type))
8648 return type;
8650 type = check_typedef (type);
8651 if (type == NULL || type->code () != TYPE_CODE_ENUM
8652 || !type->is_stub ()
8653 || type->name () == NULL)
8654 return type;
8655 else
8657 const char *name = type->name ();
8658 struct type *type1 = ada_find_any_type (name);
8660 if (type1 == NULL)
8661 return type;
8663 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8664 stubs pointing to arrays, as we don't create symbols for array
8665 types, only for the typedef-to-array types). If that's the case,
8666 strip the typedef layer. */
8667 if (type1->code () == TYPE_CODE_TYPEDEF)
8668 type1 = ada_check_typedef (type1);
8670 return type1;
8674 /* A value representing the data at VALADDR/ADDRESS as described by
8675 type TYPE0, but with a standard (static-sized) type that correctly
8676 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8677 type, then return VAL0 [this feature is simply to avoid redundant
8678 creation of struct values]. */
8680 static struct value *
8681 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8682 struct value *val0)
8684 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8686 if (type == type0 && val0 != NULL)
8687 return val0;
8689 if (val0->lval () != lval_memory)
8691 /* Our value does not live in memory; it could be a convenience
8692 variable, for instance. Create a not_lval value using val0's
8693 contents. */
8694 return value_from_contents (type, val0->contents ().data ());
8697 return value_from_contents_and_address (type, 0, address);
8700 /* A value representing VAL, but with a standard (static-sized) type
8701 that correctly describes it. Does not necessarily create a new
8702 value. */
8704 struct value *
8705 ada_to_fixed_value (struct value *val)
8707 val = unwrap_value (val);
8708 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8709 return val;
8713 /* Attributes */
8715 /* Evaluate the 'POS attribute applied to ARG. */
8717 static LONGEST
8718 pos_atr (struct value *arg)
8720 struct value *val = coerce_ref (arg);
8721 struct type *type = val->type ();
8723 if (!discrete_type_p (type))
8724 error (_("'POS only defined on discrete types"));
8726 std::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8727 if (!result.has_value ())
8728 error (_("enumeration value is invalid: can't find 'POS"));
8730 return *result;
8733 struct value *
8734 ada_pos_atr (struct type *expect_type,
8735 struct expression *exp,
8736 enum noside noside, enum exp_opcode op,
8737 struct value *arg)
8739 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8740 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8741 return value::zero (type, not_lval);
8742 return value_from_longest (type, pos_atr (arg));
8745 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8747 static struct value *
8748 val_atr (struct type *type, LONGEST val)
8750 gdb_assert (discrete_type_p (type));
8751 if (type->code () == TYPE_CODE_RANGE)
8752 type = type->target_type ();
8753 if (type->code () == TYPE_CODE_ENUM)
8755 if (val < 0 || val >= type->num_fields ())
8756 error (_("argument to 'VAL out of range"));
8757 val = type->field (val).loc_enumval ();
8759 return value_from_longest (type, val);
8762 struct value *
8763 ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8764 struct value *arg)
8766 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8767 return value::zero (type, not_lval);
8769 if (!discrete_type_p (type))
8770 error (_("'VAL only defined on discrete types"));
8771 if (!integer_type_p (arg->type ()))
8772 error (_("'VAL requires integral argument"));
8774 return val_atr (type, value_as_long (arg));
8777 /* Implementation of the enum_rep attribute. */
8778 struct value *
8779 ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8780 struct value *arg)
8782 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8783 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8784 return value::zero (inttype, not_lval);
8786 if (type->code () == TYPE_CODE_RANGE)
8787 type = type->target_type ();
8788 if (type->code () != TYPE_CODE_ENUM)
8789 error (_("'Enum_Rep only defined on enum types"));
8790 if (!types_equal (type, arg->type ()))
8791 error (_("'Enum_Rep requires argument to have same type as enum"));
8793 return value_cast (inttype, arg);
8796 /* Implementation of the enum_val attribute. */
8797 struct value *
8798 ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8799 struct value *arg)
8801 struct type *original_type = type;
8802 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8803 return value::zero (original_type, not_lval);
8805 if (type->code () == TYPE_CODE_RANGE)
8806 type = type->target_type ();
8807 if (type->code () != TYPE_CODE_ENUM)
8808 error (_("'Enum_Val only defined on enum types"));
8809 if (!integer_type_p (arg->type ()))
8810 error (_("'Enum_Val requires integral argument"));
8812 LONGEST value = value_as_long (arg);
8813 for (int i = 0; i < type->num_fields (); ++i)
8815 if (type->field (i).loc_enumval () == value)
8816 return value_from_longest (original_type, value);
8819 error (_("value %s not found in enum"), plongest (value));
8824 /* Evaluation */
8826 /* True if TYPE appears to be an Ada character type.
8827 [At the moment, this is true only for Character and Wide_Character;
8828 It is a heuristic test that could stand improvement]. */
8830 bool
8831 ada_is_character_type (struct type *type)
8833 const char *name;
8835 /* If the type code says it's a character, then assume it really is,
8836 and don't check any further. */
8837 if (type->code () == TYPE_CODE_CHAR)
8838 return true;
8840 /* Otherwise, assume it's a character type iff it is a discrete type
8841 with a known character type name. */
8842 name = ada_type_name (type);
8843 return (name != NULL
8844 && (type->code () == TYPE_CODE_INT
8845 || type->code () == TYPE_CODE_RANGE)
8846 && (strcmp (name, "character") == 0
8847 || strcmp (name, "wide_character") == 0
8848 || strcmp (name, "wide_wide_character") == 0
8849 || strcmp (name, "unsigned char") == 0));
8852 /* True if TYPE appears to be an Ada string type. */
8854 bool
8855 ada_is_string_type (struct type *type)
8857 type = ada_check_typedef (type);
8858 if (type != NULL
8859 && type->code () != TYPE_CODE_PTR
8860 && (ada_is_simple_array_type (type)
8861 || ada_is_array_descriptor_type (type))
8862 && ada_array_arity (type) == 1)
8864 struct type *elttype = ada_array_element_type (type, 1);
8866 return ada_is_character_type (elttype);
8868 else
8869 return false;
8872 /* The compiler sometimes provides a parallel XVS type for a given
8873 PAD type. Normally, it is safe to follow the PAD type directly,
8874 but older versions of the compiler have a bug that causes the offset
8875 of its "F" field to be wrong. Following that field in that case
8876 would lead to incorrect results, but this can be worked around
8877 by ignoring the PAD type and using the associated XVS type instead.
8879 Set to True if the debugger should trust the contents of PAD types.
8880 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8881 static bool trust_pad_over_xvs = true;
8883 /* True if TYPE is a struct type introduced by the compiler to force the
8884 alignment of a value. Such types have a single field with a
8885 distinctive name. */
8888 ada_is_aligner_type (struct type *type)
8890 type = ada_check_typedef (type);
8892 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8893 return 0;
8895 return (type->code () == TYPE_CODE_STRUCT
8896 && type->num_fields () == 1
8897 && strcmp (type->field (0).name (), "F") == 0);
8900 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8901 the parallel type. */
8903 struct type *
8904 ada_get_base_type (struct type *raw_type)
8906 struct type *real_type_namer;
8907 struct type *raw_real_type;
8909 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8910 return raw_type;
8912 if (ada_is_aligner_type (raw_type))
8913 /* The encoding specifies that we should always use the aligner type.
8914 So, even if this aligner type has an associated XVS type, we should
8915 simply ignore it.
8917 According to the compiler gurus, an XVS type parallel to an aligner
8918 type may exist because of a stabs limitation. In stabs, aligner
8919 types are empty because the field has a variable-sized type, and
8920 thus cannot actually be used as an aligner type. As a result,
8921 we need the associated parallel XVS type to decode the type.
8922 Since the policy in the compiler is to not change the internal
8923 representation based on the debugging info format, we sometimes
8924 end up having a redundant XVS type parallel to the aligner type. */
8925 return raw_type;
8927 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8928 if (real_type_namer == NULL
8929 || real_type_namer->code () != TYPE_CODE_STRUCT
8930 || real_type_namer->num_fields () != 1)
8931 return raw_type;
8933 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8935 /* This is an older encoding form where the base type needs to be
8936 looked up by name. We prefer the newer encoding because it is
8937 more efficient. */
8938 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
8939 if (raw_real_type == NULL)
8940 return raw_type;
8941 else
8942 return raw_real_type;
8945 /* The field in our XVS type is a reference to the base type. */
8946 return real_type_namer->field (0).type ()->target_type ();
8949 /* The type of value designated by TYPE, with all aligners removed. */
8951 struct type *
8952 ada_aligned_type (struct type *type)
8954 if (ada_is_aligner_type (type))
8955 return ada_aligned_type (type->field (0).type ());
8956 else
8957 return ada_get_base_type (type);
8961 /* The address of the aligned value in an object at address VALADDR
8962 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
8964 const gdb_byte *
8965 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8967 if (ada_is_aligner_type (type))
8968 return ada_aligned_value_addr
8969 (type->field (0).type (),
8970 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
8971 else
8972 return valaddr;
8977 /* The printed representation of an enumeration literal with encoded
8978 name NAME. The value is good to the next call of ada_enum_name. */
8979 const char *
8980 ada_enum_name (const char *name)
8982 static std::string storage;
8983 const char *tmp;
8985 /* First, unqualify the enumeration name:
8986 1. Search for the last '.' character. If we find one, then skip
8987 all the preceding characters, the unqualified name starts
8988 right after that dot.
8989 2. Otherwise, we may be debugging on a target where the compiler
8990 translates dots into "__". Search forward for double underscores,
8991 but stop searching when we hit an overloading suffix, which is
8992 of the form "__" followed by digits. */
8994 tmp = strrchr (name, '.');
8995 if (tmp != NULL)
8996 name = tmp + 1;
8997 else
8999 while ((tmp = strstr (name, "__")) != NULL)
9001 if (isdigit (tmp[2]))
9002 break;
9003 else
9004 name = tmp + 2;
9008 if (name[0] == 'Q')
9010 int v;
9012 if (name[1] == 'U' || name[1] == 'W')
9014 int offset = 2;
9015 if (name[1] == 'W' && name[2] == 'W')
9017 /* Also handle the QWW case. */
9018 ++offset;
9020 if (sscanf (name + offset, "%x", &v) != 1)
9021 return name;
9023 else if (((name[1] >= '0' && name[1] <= '9')
9024 || (name[1] >= 'a' && name[1] <= 'z'))
9025 && name[2] == '\0')
9027 storage = string_printf ("'%c'", name[1]);
9028 return storage.c_str ();
9030 else
9031 return name;
9033 if (isascii (v) && isprint (v))
9034 storage = string_printf ("'%c'", v);
9035 else if (name[1] == 'U')
9036 storage = string_printf ("'[\"%02x\"]'", v);
9037 else if (name[2] != 'W')
9038 storage = string_printf ("'[\"%04x\"]'", v);
9039 else
9040 storage = string_printf ("'[\"%06x\"]'", v);
9042 return storage.c_str ();
9044 else
9046 tmp = strstr (name, "__");
9047 if (tmp == NULL)
9048 tmp = strstr (name, "$");
9049 if (tmp != NULL)
9051 storage = std::string (name, tmp - name);
9052 return storage.c_str ();
9055 return name;
9059 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9060 there is no parallel type, return nullptr. */
9062 static struct type *
9063 find_base_type (struct type *type)
9065 struct type *raw_real_type
9066 = ada_check_typedef (ada_get_base_type (type));
9068 /* No parallel XVS or XVE type. */
9069 if (type == raw_real_type
9070 && ada_find_parallel_type (type, "___XVE") == nullptr)
9071 return nullptr;
9073 return raw_real_type;
9076 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9077 value it wraps. */
9079 static struct value *
9080 unwrap_value (struct value *val)
9082 struct type *type = ada_check_typedef (val->type ());
9084 if (ada_is_aligner_type (type))
9086 struct value *v = ada_value_struct_elt (val, "F", 0);
9087 struct type *val_type = ada_check_typedef (v->type ());
9089 if (ada_type_name (val_type) == NULL)
9090 val_type->set_name (ada_type_name (type));
9092 return unwrap_value (v);
9094 else
9096 struct type *raw_real_type = find_base_type (type);
9097 if (raw_real_type == nullptr)
9098 return val;
9100 return
9101 coerce_unspec_val_to_type
9102 (val, ada_to_fixed_type (raw_real_type, 0,
9103 val->address (),
9104 NULL, 1));
9108 /* Given two array types T1 and T2, return nonzero iff both arrays
9109 contain the same number of elements. */
9111 static int
9112 ada_same_array_size_p (struct type *t1, struct type *t2)
9114 LONGEST lo1, hi1, lo2, hi2;
9116 /* Get the array bounds in order to verify that the size of
9117 the two arrays match. */
9118 if (!get_array_bounds (t1, &lo1, &hi1)
9119 || !get_array_bounds (t2, &lo2, &hi2))
9120 error (_("unable to determine array bounds"));
9122 /* To make things easier for size comparison, normalize a bit
9123 the case of empty arrays by making sure that the difference
9124 between upper bound and lower bound is always -1. */
9125 if (lo1 > hi1)
9126 hi1 = lo1 - 1;
9127 if (lo2 > hi2)
9128 hi2 = lo2 - 1;
9130 return (hi1 - lo1 == hi2 - lo2);
9133 /* Assuming that VAL is an array of integrals, and TYPE represents
9134 an array with the same number of elements, but with wider integral
9135 elements, return an array "casted" to TYPE. In practice, this
9136 means that the returned array is built by casting each element
9137 of the original array into TYPE's (wider) element type. */
9139 static struct value *
9140 ada_promote_array_of_integrals (struct type *type, struct value *val)
9142 struct type *elt_type = type->target_type ();
9143 LONGEST lo, hi;
9144 LONGEST i;
9146 /* Verify that both val and type are arrays of scalars, and
9147 that the size of val's elements is smaller than the size
9148 of type's element. */
9149 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9150 gdb_assert (is_integral_type (type->target_type ()));
9151 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9152 gdb_assert (is_integral_type (val->type ()->target_type ()));
9153 gdb_assert (type->target_type ()->length ()
9154 > val->type ()->target_type ()->length ());
9156 if (!get_array_bounds (type, &lo, &hi))
9157 error (_("unable to determine array bounds"));
9159 value *res = value::allocate (type);
9160 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9162 /* Promote each array element. */
9163 for (i = 0; i < hi - lo + 1; i++)
9165 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9166 int elt_len = elt_type->length ();
9168 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9171 return res;
9174 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9175 return the converted value. */
9177 static struct value *
9178 coerce_for_assign (struct type *type, struct value *val)
9180 struct type *type2 = val->type ();
9182 if (type == type2)
9183 return val;
9185 type2 = ada_check_typedef (type2);
9186 type = ada_check_typedef (type);
9188 if (type2->code () == TYPE_CODE_PTR
9189 && type->code () == TYPE_CODE_ARRAY)
9191 val = ada_value_ind (val);
9192 type2 = val->type ();
9195 if (type2->code () == TYPE_CODE_ARRAY
9196 && type->code () == TYPE_CODE_ARRAY)
9198 if (!ada_same_array_size_p (type, type2))
9199 error (_("cannot assign arrays of different length"));
9201 if (is_integral_type (type->target_type ())
9202 && is_integral_type (type2->target_type ())
9203 && type2->target_type ()->length () < type->target_type ()->length ())
9205 /* Allow implicit promotion of the array elements to
9206 a wider type. */
9207 return ada_promote_array_of_integrals (type, val);
9210 if (type2->target_type ()->length () != type->target_type ()->length ())
9211 error (_("Incompatible types in assignment"));
9212 val->deprecated_set_type (type);
9214 return val;
9217 static struct value *
9218 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9220 struct type *type1, *type2;
9222 arg1 = coerce_ref (arg1);
9223 arg2 = coerce_ref (arg2);
9224 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9225 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9227 if (type1->code () != TYPE_CODE_INT
9228 || type2->code () != TYPE_CODE_INT)
9229 return value_binop (arg1, arg2, op);
9231 switch (op)
9233 case BINOP_MOD:
9234 case BINOP_DIV:
9235 case BINOP_REM:
9236 break;
9237 default:
9238 return value_binop (arg1, arg2, op);
9241 gdb_mpz v2 = value_as_mpz (arg2);
9242 if (v2.sgn () == 0)
9244 const char *name;
9245 if (op == BINOP_MOD)
9246 name = "mod";
9247 else if (op == BINOP_DIV)
9248 name = "/";
9249 else
9251 gdb_assert (op == BINOP_REM);
9252 name = "rem";
9255 error (_("second operand of %s must not be zero."), name);
9258 if (type1->is_unsigned () || op == BINOP_MOD)
9259 return value_binop (arg1, arg2, op);
9261 gdb_mpz v1 = value_as_mpz (arg1);
9262 gdb_mpz v;
9263 switch (op)
9265 case BINOP_DIV:
9266 v = v1 / v2;
9267 break;
9268 case BINOP_REM:
9269 v = v1 % v2;
9270 if (v * v1 < 0)
9271 v -= v2;
9272 break;
9273 default:
9274 /* Should not reach this point. */
9275 gdb_assert_not_reached ("invalid operator");
9278 return value_from_mpz (type1, v);
9281 static int
9282 ada_value_equal (struct value *arg1, struct value *arg2)
9284 if (ada_is_direct_array_type (arg1->type ())
9285 || ada_is_direct_array_type (arg2->type ()))
9287 struct type *arg1_type, *arg2_type;
9289 /* Automatically dereference any array reference before
9290 we attempt to perform the comparison. */
9291 arg1 = ada_coerce_ref (arg1);
9292 arg2 = ada_coerce_ref (arg2);
9294 arg1 = ada_coerce_to_simple_array (arg1);
9295 arg2 = ada_coerce_to_simple_array (arg2);
9297 arg1_type = ada_check_typedef (arg1->type ());
9298 arg2_type = ada_check_typedef (arg2->type ());
9300 if (arg1_type->code () != TYPE_CODE_ARRAY
9301 || arg2_type->code () != TYPE_CODE_ARRAY)
9302 error (_("Attempt to compare array with non-array"));
9303 /* FIXME: The following works only for types whose
9304 representations use all bits (no padding or undefined bits)
9305 and do not have user-defined equality. */
9306 return (arg1_type->length () == arg2_type->length ()
9307 && memcmp (arg1->contents ().data (),
9308 arg2->contents ().data (),
9309 arg1_type->length ()) == 0);
9311 return value_equal (arg1, arg2);
9314 namespace expr
9317 bool
9318 check_objfile (const std::unique_ptr<ada_component> &comp,
9319 struct objfile *objfile)
9321 return comp->uses_objfile (objfile);
9324 /* See ada-exp.h. */
9326 void
9327 aggregate_assigner::assign (LONGEST index, operation_up &arg)
9329 scoped_value_mark mark;
9331 struct value *elt;
9332 struct type *lhs_type = check_typedef (lhs->type ());
9334 if (lhs_type->code () == TYPE_CODE_ARRAY)
9336 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9337 struct value *index_val = value_from_longest (index_type, index);
9339 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9341 else
9343 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9344 elt = ada_to_fixed_value (elt);
9347 scoped_restore save_index = make_scoped_restore (&m_current_index, index);
9349 ada_aggregate_operation *ag_op
9350 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9351 if (ag_op != nullptr)
9352 ag_op->assign_aggregate (container, elt, exp);
9353 else
9354 value_assign_to_component (container, elt,
9355 arg->evaluate (nullptr, exp,
9356 EVAL_NORMAL));
9359 /* See ada-exp.h. */
9361 value *
9362 aggregate_assigner::current_value () const
9364 /* Note that using an integer type here is incorrect -- the type
9365 should be the array's index type. Unfortunately, though, this
9366 isn't currently available during parsing and type resolution. */
9367 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9368 return value_from_longest (index_type, m_current_index);
9371 bool
9372 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9374 if (m_base != nullptr && m_base->uses_objfile (objfile))
9375 return true;
9376 for (const auto &item : m_components)
9377 if (item->uses_objfile (objfile))
9378 return true;
9379 return false;
9382 void
9383 ada_aggregate_component::dump (ui_file *stream, int depth)
9385 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9386 if (m_base != nullptr)
9388 gdb_printf (stream, _("%*swith delta\n"), depth + 1, "");
9389 m_base->dump (stream, depth + 2);
9391 for (const auto &item : m_components)
9392 item->dump (stream, depth + 1);
9395 void
9396 ada_aggregate_component::assign (aggregate_assigner &assigner)
9398 if (m_base != nullptr)
9400 value *base = m_base->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9401 if (ada_is_direct_array_type (base->type ()))
9402 base = ada_coerce_to_simple_array (base);
9403 if (!types_deeply_equal (assigner.container->type (), base->type ()))
9404 error (_("Type mismatch in delta aggregate"));
9405 value_assign_to_component (assigner.container, assigner.container,
9406 base);
9409 for (auto &item : m_components)
9410 item->assign (assigner);
9413 /* See ada-exp.h. */
9415 ada_aggregate_component::ada_aggregate_component
9416 (operation_up &&base, std::vector<ada_component_up> &&components)
9417 : m_base (std::move (base)),
9418 m_components (std::move (components))
9420 for (const auto &component : m_components)
9421 if (dynamic_cast<const ada_others_component *> (component.get ())
9422 != nullptr)
9424 /* It's invalid and nonsensical to have 'others => ...' with a
9425 delta aggregate. It was simpler to enforce this
9426 restriction here as opposed to in the parser. */
9427 error (_("'others' invalid in delta aggregate"));
9431 /* See ada-exp.h. */
9433 value *
9434 ada_aggregate_operation::assign_aggregate (struct value *container,
9435 struct value *lhs,
9436 struct expression *exp)
9438 struct type *lhs_type;
9439 aggregate_assigner assigner;
9441 container = ada_coerce_ref (container);
9442 if (ada_is_direct_array_type (container->type ()))
9443 container = ada_coerce_to_simple_array (container);
9444 lhs = ada_coerce_ref (lhs);
9445 if (!lhs->deprecated_modifiable ())
9446 error (_("Left operand of assignment is not a modifiable lvalue."));
9448 lhs_type = check_typedef (lhs->type ());
9449 if (ada_is_direct_array_type (lhs_type))
9451 lhs = ada_coerce_to_simple_array (lhs);
9452 lhs_type = check_typedef (lhs->type ());
9453 assigner.low = lhs_type->bounds ()->low.const_val ();
9454 assigner.high = lhs_type->bounds ()->high.const_val ();
9456 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9458 assigner.low = 0;
9459 assigner.high = num_visible_fields (lhs_type) - 1;
9461 else
9462 error (_("Left-hand side must be array or record."));
9464 assigner.indices.push_back (assigner.low - 1);
9465 assigner.indices.push_back (assigner.low - 1);
9466 assigner.indices.push_back (assigner.high + 1);
9467 assigner.indices.push_back (assigner.high + 1);
9469 assigner.container = container;
9470 assigner.lhs = lhs;
9471 assigner.exp = exp;
9473 std::get<0> (m_storage)->assign (assigner);
9475 return container;
9478 bool
9479 ada_positional_component::uses_objfile (struct objfile *objfile)
9481 return m_op->uses_objfile (objfile);
9484 void
9485 ada_positional_component::dump (ui_file *stream, int depth)
9487 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9488 depth, "", m_index);
9489 m_op->dump (stream, depth + 1);
9492 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9493 construct, given that the positions are relative to lower bound
9494 LOW, where HIGH is the upper bound. Record the position in
9495 INDICES. CONTAINER is as for assign_aggregate. */
9496 void
9497 ada_positional_component::assign (aggregate_assigner &assigner)
9499 LONGEST ind = m_index + assigner.low;
9501 if (ind - 1 == assigner.high)
9502 warning (_("Extra components in aggregate ignored."));
9503 if (ind <= assigner.high)
9505 assigner.add_interval (ind, ind);
9506 assigner.assign (ind, m_op);
9510 bool
9511 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9513 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9516 void
9517 ada_discrete_range_association::dump (ui_file *stream, int depth)
9519 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9520 m_low->dump (stream, depth + 1);
9521 m_high->dump (stream, depth + 1);
9524 void
9525 ada_discrete_range_association::assign (aggregate_assigner &assigner,
9526 operation_up &op)
9528 LONGEST lower = value_as_long (m_low->evaluate (nullptr, assigner.exp,
9529 EVAL_NORMAL));
9530 LONGEST upper = value_as_long (m_high->evaluate (nullptr, assigner.exp,
9531 EVAL_NORMAL));
9533 if (lower <= upper && (lower < assigner.low || upper > assigner.high))
9534 error (_("Index in component association out of bounds."));
9536 assigner.add_interval (lower, upper);
9537 while (lower <= upper)
9539 assigner.assign (lower, op);
9540 lower += 1;
9544 bool
9545 ada_name_association::uses_objfile (struct objfile *objfile)
9547 return m_val->uses_objfile (objfile);
9550 void
9551 ada_name_association::dump (ui_file *stream, int depth)
9553 gdb_printf (stream, _("%*sName:\n"), depth, "");
9554 m_val->dump (stream, depth + 1);
9557 void
9558 ada_name_association::assign (aggregate_assigner &assigner,
9559 operation_up &op)
9561 int index;
9563 if (ada_is_direct_array_type (assigner.lhs->type ()))
9565 value *tem = m_val->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9566 index = longest_to_int (value_as_long (tem));
9568 else
9570 ada_string_operation *strop
9571 = dynamic_cast<ada_string_operation *> (m_val.get ());
9573 const char *name;
9574 if (strop != nullptr)
9575 name = strop->get_name ();
9576 else
9578 ada_var_value_operation *vvo
9579 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9580 if (vvo == nullptr)
9581 error (_("Invalid record component association."));
9582 name = vvo->get_symbol ()->natural_name ();
9583 /* In this scenario, the user wrote (name => expr), but
9584 write_name_assoc found some fully-qualified name and
9585 substituted it. This happens because, at parse time, the
9586 meaning of the expression isn't known; but here we know
9587 that just the base name was supplied and it refers to the
9588 name of a field. */
9589 name = ada_unqualified_name (name);
9592 index = 0;
9593 if (! find_struct_field (name, assigner.lhs->type (), 0,
9594 NULL, NULL, NULL, NULL, &index))
9595 error (_("Unknown component name: %s."), name);
9598 assigner.add_interval (index, index);
9599 assigner.assign (index, op);
9602 bool
9603 ada_choices_component::uses_objfile (struct objfile *objfile)
9605 if (m_op->uses_objfile (objfile))
9606 return true;
9607 for (const auto &item : m_assocs)
9608 if (item->uses_objfile (objfile))
9609 return true;
9610 return false;
9613 void
9614 ada_choices_component::dump (ui_file *stream, int depth)
9616 if (m_name.empty ())
9617 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9618 else
9620 gdb_printf (stream, _("%*sIterated choices:\n"), depth, "");
9621 gdb_printf (stream, _("%*sName: %s\n"), depth + 1, "", m_name.c_str ());
9623 m_op->dump (stream, depth + 1);
9625 for (const auto &item : m_assocs)
9626 item->dump (stream, depth + 1);
9629 /* Assign into the components of LHS indexed by the OP_CHOICES
9630 construct at *POS, updating *POS past the construct, given that
9631 the allowable indices are LOW..HIGH. Record the indices assigned
9632 to in INDICES. CONTAINER is as for assign_aggregate. */
9633 void
9634 ada_choices_component::assign (aggregate_assigner &assigner)
9636 scoped_restore save_index = make_scoped_restore (&m_assigner, &assigner);
9637 for (auto &item : m_assocs)
9638 item->assign (assigner, m_op);
9641 void
9642 ada_index_var_operation::dump (struct ui_file *stream, int depth) const
9644 gdb_printf (stream, _("%*sIndex variable: %s\n"), depth, "",
9645 m_var->name ().c_str ());
9648 value *
9649 ada_index_var_operation::evaluate (struct type *expect_type,
9650 struct expression *exp,
9651 enum noside noside)
9653 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9655 /* Note that using an integer type here is incorrect -- the type
9656 should be the array's index type. Unfortunately, though,
9657 this isn't currently available during parsing and type
9658 resolution. */
9659 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9660 return value::zero (index_type, not_lval);
9663 return m_var->current_value ();
9666 bool
9667 ada_others_component::uses_objfile (struct objfile *objfile)
9669 return m_op->uses_objfile (objfile);
9672 void
9673 ada_others_component::dump (ui_file *stream, int depth)
9675 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9676 m_op->dump (stream, depth + 1);
9679 /* Assign the value of the expression in the OP_OTHERS construct in
9680 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9681 have not been previously assigned. The index intervals already assigned
9682 are in INDICES. CONTAINER is as for assign_aggregate. */
9683 void
9684 ada_others_component::assign (aggregate_assigner &assigner)
9686 int num_indices = assigner.indices.size ();
9687 for (int i = 0; i < num_indices - 2; i += 2)
9689 for (LONGEST ind = assigner.indices[i + 1] + 1;
9690 ind < assigner.indices[i + 2];
9691 ind += 1)
9692 assigner.assign (ind, m_op);
9696 struct value *
9697 ada_assign_operation::evaluate (struct type *expect_type,
9698 struct expression *exp,
9699 enum noside noside)
9701 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9702 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
9704 ada_aggregate_operation *ag_op
9705 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9706 if (ag_op != nullptr)
9708 if (noside != EVAL_NORMAL)
9709 return arg1;
9711 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9712 return ada_value_assign (arg1, arg1);
9714 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9715 except if the lhs of our assignment is a convenience variable.
9716 In the case of assigning to a convenience variable, the lhs
9717 should be exactly the result of the evaluation of the rhs. */
9718 struct type *type = arg1->type ();
9719 if (arg1->lval () == lval_internalvar)
9720 type = NULL;
9721 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9722 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9723 return arg1;
9724 if (arg1->lval () == lval_internalvar)
9726 /* Nothing. */
9728 else
9729 arg2 = coerce_for_assign (arg1->type (), arg2);
9730 return ada_value_assign (arg1, arg2);
9733 /* See ada-exp.h. */
9735 void
9736 aggregate_assigner::add_interval (LONGEST from, LONGEST to)
9738 int i, j;
9740 int size = indices.size ();
9741 for (i = 0; i < size; i += 2) {
9742 if (to >= indices[i] && from <= indices[i + 1])
9744 int kh;
9746 for (kh = i + 2; kh < size; kh += 2)
9747 if (to < indices[kh])
9748 break;
9749 if (from < indices[i])
9750 indices[i] = from;
9751 indices[i + 1] = indices[kh - 1];
9752 if (to > indices[i + 1])
9753 indices[i + 1] = to;
9754 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9755 indices.resize (kh - i - 2);
9756 return;
9758 else if (to < indices[i])
9759 break;
9762 indices.resize (indices.size () + 2);
9763 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9764 indices[j] = indices[j - 2];
9765 indices[i] = from;
9766 indices[i + 1] = to;
9769 } /* namespace expr */
9771 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9772 is different. */
9774 static struct value *
9775 ada_value_cast (struct type *type, struct value *arg2)
9777 if (type == ada_check_typedef (arg2->type ()))
9778 return arg2;
9780 return value_cast (type, arg2);
9783 /* Evaluating Ada expressions, and printing their result.
9784 ------------------------------------------------------
9786 1. Introduction:
9787 ----------------
9789 We usually evaluate an Ada expression in order to print its value.
9790 We also evaluate an expression in order to print its type, which
9791 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9792 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9793 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9794 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9795 similar.
9797 Evaluating expressions is a little more complicated for Ada entities
9798 than it is for entities in languages such as C. The main reason for
9799 this is that Ada provides types whose definition might be dynamic.
9800 One example of such types is variant records. Or another example
9801 would be an array whose bounds can only be known at run time.
9803 The following description is a general guide as to what should be
9804 done (and what should NOT be done) in order to evaluate an expression
9805 involving such types, and when. This does not cover how the semantic
9806 information is encoded by GNAT as this is covered separatly. For the
9807 document used as the reference for the GNAT encoding, see exp_dbug.ads
9808 in the GNAT sources.
9810 Ideally, we should embed each part of this description next to its
9811 associated code. Unfortunately, the amount of code is so vast right
9812 now that it's hard to see whether the code handling a particular
9813 situation might be duplicated or not. One day, when the code is
9814 cleaned up, this guide might become redundant with the comments
9815 inserted in the code, and we might want to remove it.
9817 2. ``Fixing'' an Entity, the Simple Case:
9818 -----------------------------------------
9820 When evaluating Ada expressions, the tricky issue is that they may
9821 reference entities whose type contents and size are not statically
9822 known. Consider for instance a variant record:
9824 type Rec (Empty : Boolean := True) is record
9825 case Empty is
9826 when True => null;
9827 when False => Value : Integer;
9828 end case;
9829 end record;
9830 Yes : Rec := (Empty => False, Value => 1);
9831 No : Rec := (empty => True);
9833 The size and contents of that record depends on the value of the
9834 discriminant (Rec.Empty). At this point, neither the debugging
9835 information nor the associated type structure in GDB are able to
9836 express such dynamic types. So what the debugger does is to create
9837 "fixed" versions of the type that applies to the specific object.
9838 We also informally refer to this operation as "fixing" an object,
9839 which means creating its associated fixed type.
9841 Example: when printing the value of variable "Yes" above, its fixed
9842 type would look like this:
9844 type Rec is record
9845 Empty : Boolean;
9846 Value : Integer;
9847 end record;
9849 On the other hand, if we printed the value of "No", its fixed type
9850 would become:
9852 type Rec is record
9853 Empty : Boolean;
9854 end record;
9856 Things become a little more complicated when trying to fix an entity
9857 with a dynamic type that directly contains another dynamic type,
9858 such as an array of variant records, for instance. There are
9859 two possible cases: Arrays, and records.
9861 3. ``Fixing'' Arrays:
9862 ---------------------
9864 The type structure in GDB describes an array in terms of its bounds,
9865 and the type of its elements. By design, all elements in the array
9866 have the same type and we cannot represent an array of variant elements
9867 using the current type structure in GDB. When fixing an array,
9868 we cannot fix the array element, as we would potentially need one
9869 fixed type per element of the array. As a result, the best we can do
9870 when fixing an array is to produce an array whose bounds and size
9871 are correct (allowing us to read it from memory), but without having
9872 touched its element type. Fixing each element will be done later,
9873 when (if) necessary.
9875 Arrays are a little simpler to handle than records, because the same
9876 amount of memory is allocated for each element of the array, even if
9877 the amount of space actually used by each element differs from element
9878 to element. Consider for instance the following array of type Rec:
9880 type Rec_Array is array (1 .. 2) of Rec;
9882 The actual amount of memory occupied by each element might be different
9883 from element to element, depending on the value of their discriminant.
9884 But the amount of space reserved for each element in the array remains
9885 fixed regardless. So we simply need to compute that size using
9886 the debugging information available, from which we can then determine
9887 the array size (we multiply the number of elements of the array by
9888 the size of each element).
9890 The simplest case is when we have an array of a constrained element
9891 type. For instance, consider the following type declarations:
9893 type Bounded_String (Max_Size : Integer) is
9894 Length : Integer;
9895 Buffer : String (1 .. Max_Size);
9896 end record;
9897 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9899 In this case, the compiler describes the array as an array of
9900 variable-size elements (identified by its XVS suffix) for which
9901 the size can be read in the parallel XVZ variable.
9903 In the case of an array of an unconstrained element type, the compiler
9904 wraps the array element inside a private PAD type. This type should not
9905 be shown to the user, and must be "unwrap"'ed before printing. Note
9906 that we also use the adjective "aligner" in our code to designate
9907 these wrapper types.
9909 In some cases, the size allocated for each element is statically
9910 known. In that case, the PAD type already has the correct size,
9911 and the array element should remain unfixed.
9913 But there are cases when this size is not statically known.
9914 For instance, assuming that "Five" is an integer variable:
9916 type Dynamic is array (1 .. Five) of Integer;
9917 type Wrapper (Has_Length : Boolean := False) is record
9918 Data : Dynamic;
9919 case Has_Length is
9920 when True => Length : Integer;
9921 when False => null;
9922 end case;
9923 end record;
9924 type Wrapper_Array is array (1 .. 2) of Wrapper;
9926 Hello : Wrapper_Array := (others => (Has_Length => True,
9927 Data => (others => 17),
9928 Length => 1));
9931 The debugging info would describe variable Hello as being an
9932 array of a PAD type. The size of that PAD type is not statically
9933 known, but can be determined using a parallel XVZ variable.
9934 In that case, a copy of the PAD type with the correct size should
9935 be used for the fixed array.
9937 3. ``Fixing'' record type objects:
9938 ----------------------------------
9940 Things are slightly different from arrays in the case of dynamic
9941 record types. In this case, in order to compute the associated
9942 fixed type, we need to determine the size and offset of each of
9943 its components. This, in turn, requires us to compute the fixed
9944 type of each of these components.
9946 Consider for instance the example:
9948 type Bounded_String (Max_Size : Natural) is record
9949 Str : String (1 .. Max_Size);
9950 Length : Natural;
9951 end record;
9952 My_String : Bounded_String (Max_Size => 10);
9954 In that case, the position of field "Length" depends on the size
9955 of field Str, which itself depends on the value of the Max_Size
9956 discriminant. In order to fix the type of variable My_String,
9957 we need to fix the type of field Str. Therefore, fixing a variant
9958 record requires us to fix each of its components.
9960 However, if a component does not have a dynamic size, the component
9961 should not be fixed. In particular, fields that use a PAD type
9962 should not fixed. Here is an example where this might happen
9963 (assuming type Rec above):
9965 type Container (Big : Boolean) is record
9966 First : Rec;
9967 After : Integer;
9968 case Big is
9969 when True => Another : Integer;
9970 when False => null;
9971 end case;
9972 end record;
9973 My_Container : Container := (Big => False,
9974 First => (Empty => True),
9975 After => 42);
9977 In that example, the compiler creates a PAD type for component First,
9978 whose size is constant, and then positions the component After just
9979 right after it. The offset of component After is therefore constant
9980 in this case.
9982 The debugger computes the position of each field based on an algorithm
9983 that uses, among other things, the actual position and size of the field
9984 preceding it. Let's now imagine that the user is trying to print
9985 the value of My_Container. If the type fixing was recursive, we would
9986 end up computing the offset of field After based on the size of the
9987 fixed version of field First. And since in our example First has
9988 only one actual field, the size of the fixed type is actually smaller
9989 than the amount of space allocated to that field, and thus we would
9990 compute the wrong offset of field After.
9992 To make things more complicated, we need to watch out for dynamic
9993 components of variant records (identified by the ___XVL suffix in
9994 the component name). Even if the target type is a PAD type, the size
9995 of that type might not be statically known. So the PAD type needs
9996 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9997 we might end up with the wrong size for our component. This can be
9998 observed with the following type declarations:
10000 type Octal is new Integer range 0 .. 7;
10001 type Octal_Array is array (Positive range <>) of Octal;
10002 pragma Pack (Octal_Array);
10004 type Octal_Buffer (Size : Positive) is record
10005 Buffer : Octal_Array (1 .. Size);
10006 Length : Integer;
10007 end record;
10009 In that case, Buffer is a PAD type whose size is unset and needs
10010 to be computed by fixing the unwrapped type.
10012 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10013 ----------------------------------------------------------
10015 Lastly, when should the sub-elements of an entity that remained unfixed
10016 thus far, be actually fixed?
10018 The answer is: Only when referencing that element. For instance
10019 when selecting one component of a record, this specific component
10020 should be fixed at that point in time. Or when printing the value
10021 of a record, each component should be fixed before its value gets
10022 printed. Similarly for arrays, the element of the array should be
10023 fixed when printing each element of the array, or when extracting
10024 one element out of that array. On the other hand, fixing should
10025 not be performed on the elements when taking a slice of an array!
10027 Note that one of the side effects of miscomputing the offset and
10028 size of each field is that we end up also miscomputing the size
10029 of the containing type. This can have adverse results when computing
10030 the value of an entity. GDB fetches the value of an entity based
10031 on the size of its type, and thus a wrong size causes GDB to fetch
10032 the wrong amount of memory. In the case where the computed size is
10033 too small, GDB fetches too little data to print the value of our
10034 entity. Results in this case are unpredictable, as we usually read
10035 past the buffer containing the data =:-o. */
10037 /* A helper function for TERNOP_IN_RANGE. */
10039 static value *
10040 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10041 enum noside noside,
10042 value *arg1, value *arg2, value *arg3)
10044 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10045 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10046 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10047 return
10048 value_from_longest (type,
10049 (value_less (arg1, arg3)
10050 || value_equal (arg1, arg3))
10051 && (value_less (arg2, arg1)
10052 || value_equal (arg2, arg1)));
10055 /* A helper function for UNOP_NEG. */
10057 value *
10058 ada_unop_neg (struct type *expect_type,
10059 struct expression *exp,
10060 enum noside noside, enum exp_opcode op,
10061 struct value *arg1)
10063 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10064 return value_neg (arg1);
10067 /* A helper function for UNOP_IN_RANGE. */
10069 value *
10070 ada_unop_in_range (struct type *expect_type,
10071 struct expression *exp,
10072 enum noside noside, enum exp_opcode op,
10073 struct value *arg1, struct type *type)
10075 struct value *arg2, *arg3;
10076 switch (type->code ())
10078 default:
10079 lim_warning (_("Membership test incompletely implemented; "
10080 "always returns true"));
10081 type = language_bool_type (exp->language_defn, exp->gdbarch);
10082 return value_from_longest (type, 1);
10084 case TYPE_CODE_RANGE:
10085 arg2 = value_from_longest (type,
10086 type->bounds ()->low.const_val ());
10087 arg3 = value_from_longest (type,
10088 type->bounds ()->high.const_val ());
10089 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10090 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10091 type = language_bool_type (exp->language_defn, exp->gdbarch);
10092 return
10093 value_from_longest (type,
10094 (value_less (arg1, arg3)
10095 || value_equal (arg1, arg3))
10096 && (value_less (arg2, arg1)
10097 || value_equal (arg2, arg1)));
10101 /* A helper function for OP_ATR_TAG. */
10103 value *
10104 ada_atr_tag (struct type *expect_type,
10105 struct expression *exp,
10106 enum noside noside, enum exp_opcode op,
10107 struct value *arg1)
10109 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10110 return value::zero (ada_tag_type (arg1), not_lval);
10112 return ada_value_tag (arg1);
10115 /* A helper function for OP_ATR_SIZE. */
10117 value *
10118 ada_atr_size (struct type *expect_type,
10119 struct expression *exp,
10120 enum noside noside, enum exp_opcode op,
10121 struct value *arg1)
10123 struct type *type = arg1->type ();
10125 /* If the argument is a reference, then dereference its type, since
10126 the user is really asking for the size of the actual object,
10127 not the size of the pointer. */
10128 if (type->code () == TYPE_CODE_REF)
10129 type = type->target_type ();
10131 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10132 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10133 else
10134 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10135 TARGET_CHAR_BIT * type->length ());
10138 /* A helper function for UNOP_ABS. */
10140 value *
10141 ada_abs (struct type *expect_type,
10142 struct expression *exp,
10143 enum noside noside, enum exp_opcode op,
10144 struct value *arg1)
10146 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10147 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10148 return value_neg (arg1);
10149 else
10150 return arg1;
10153 /* A helper function for BINOP_MUL. */
10155 value *
10156 ada_mult_binop (struct type *expect_type,
10157 struct expression *exp,
10158 enum noside noside, enum exp_opcode op,
10159 struct value *arg1, struct value *arg2)
10161 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10163 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10164 return value::zero (arg1->type (), not_lval);
10166 else
10168 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10169 return ada_value_binop (arg1, arg2, op);
10173 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10175 value *
10176 ada_equal_binop (struct type *expect_type,
10177 struct expression *exp,
10178 enum noside noside, enum exp_opcode op,
10179 struct value *arg1, struct value *arg2)
10181 int tem;
10182 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10183 tem = 0;
10184 else
10186 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10187 tem = ada_value_equal (arg1, arg2);
10189 if (op == BINOP_NOTEQUAL)
10190 tem = !tem;
10191 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10192 return value_from_longest (type, tem);
10195 /* A helper function for TERNOP_SLICE. */
10197 value *
10198 ada_ternop_slice (struct expression *exp,
10199 enum noside noside,
10200 struct value *array, struct value *low_bound_val,
10201 struct value *high_bound_val)
10203 LONGEST low_bound;
10204 LONGEST high_bound;
10206 low_bound_val = coerce_ref (low_bound_val);
10207 high_bound_val = coerce_ref (high_bound_val);
10208 low_bound = value_as_long (low_bound_val);
10209 high_bound = value_as_long (high_bound_val);
10211 /* If this is a reference to an aligner type, then remove all
10212 the aligners. */
10213 if (array->type ()->code () == TYPE_CODE_REF
10214 && ada_is_aligner_type (array->type ()->target_type ()))
10215 array->type ()->set_target_type
10216 (ada_aligned_type (array->type ()->target_type ()));
10218 if (ada_is_any_packed_array_type (array->type ()))
10219 error (_("cannot slice a packed array"));
10221 /* If this is a reference to an array or an array lvalue,
10222 convert to a pointer. */
10223 if (array->type ()->code () == TYPE_CODE_REF
10224 || (array->type ()->code () == TYPE_CODE_ARRAY
10225 && array->lval () == lval_memory))
10226 array = value_addr (array);
10228 if (noside == EVAL_AVOID_SIDE_EFFECTS
10229 && ada_is_array_descriptor_type (ada_check_typedef
10230 (array->type ())))
10231 return empty_array (ada_type_of_array (array, 0), low_bound,
10232 high_bound);
10234 array = ada_coerce_to_simple_array_ptr (array);
10236 /* If we have more than one level of pointer indirection,
10237 dereference the value until we get only one level. */
10238 while (array->type ()->code () == TYPE_CODE_PTR
10239 && (array->type ()->target_type ()->code ()
10240 == TYPE_CODE_PTR))
10241 array = value_ind (array);
10243 /* Make sure we really do have an array type before going further,
10244 to avoid a SEGV when trying to get the index type or the target
10245 type later down the road if the debug info generated by
10246 the compiler is incorrect or incomplete. */
10247 if (!ada_is_simple_array_type (array->type ()))
10248 error (_("cannot take slice of non-array"));
10250 if (ada_check_typedef (array->type ())->code ()
10251 == TYPE_CODE_PTR)
10253 struct type *type0 = ada_check_typedef (array->type ());
10255 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10256 return empty_array (type0->target_type (), low_bound, high_bound);
10257 else
10259 struct type *arr_type0 =
10260 to_fixed_array_type (type0->target_type (), NULL, 1);
10262 return ada_value_slice_from_ptr (array, arr_type0,
10263 longest_to_int (low_bound),
10264 longest_to_int (high_bound));
10267 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10268 return array;
10269 else if (high_bound < low_bound)
10270 return empty_array (array->type (), low_bound, high_bound);
10271 else
10272 return ada_value_slice (array, longest_to_int (low_bound),
10273 longest_to_int (high_bound));
10276 /* A helper function for BINOP_IN_BOUNDS. */
10278 value *
10279 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10280 struct value *arg1, struct value *arg2, int n)
10282 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10284 struct type *type = language_bool_type (exp->language_defn,
10285 exp->gdbarch);
10286 return value::zero (type, not_lval);
10289 struct type *type = ada_index_type (arg2->type (), n, "range");
10290 if (!type)
10291 type = arg1->type ();
10293 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10294 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10296 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10297 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10298 type = language_bool_type (exp->language_defn, exp->gdbarch);
10299 return value_from_longest (type,
10300 (value_less (arg1, arg3)
10301 || value_equal (arg1, arg3))
10302 && (value_less (arg2, arg1)
10303 || value_equal (arg2, arg1)));
10306 /* A helper function for some attribute operations. */
10308 static value *
10309 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10310 struct value *arg1, struct type *type_arg, int tem)
10312 const char *attr_name = nullptr;
10313 if (op == OP_ATR_FIRST)
10314 attr_name = "first";
10315 else if (op == OP_ATR_LAST)
10316 attr_name = "last";
10318 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10320 if (type_arg == NULL)
10321 type_arg = arg1->type ();
10323 if (ada_is_constrained_packed_array_type (type_arg))
10324 type_arg = decode_constrained_packed_array_type (type_arg);
10326 if (!discrete_type_p (type_arg))
10328 switch (op)
10330 default: /* Should never happen. */
10331 error (_("unexpected attribute encountered"));
10332 case OP_ATR_FIRST:
10333 case OP_ATR_LAST:
10334 type_arg = ada_index_type (type_arg, tem,
10335 attr_name);
10336 break;
10337 case OP_ATR_LENGTH:
10338 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10339 break;
10343 return value::zero (type_arg, not_lval);
10345 else if (type_arg == NULL)
10347 arg1 = ada_coerce_ref (arg1);
10349 if (ada_is_constrained_packed_array_type (arg1->type ()))
10350 arg1 = ada_coerce_to_simple_array (arg1);
10352 struct type *type;
10353 if (op == OP_ATR_LENGTH)
10354 type = builtin_type (exp->gdbarch)->builtin_int;
10355 else
10357 type = ada_index_type (arg1->type (), tem,
10358 attr_name);
10359 if (type == NULL)
10360 type = builtin_type (exp->gdbarch)->builtin_int;
10363 switch (op)
10365 default: /* Should never happen. */
10366 error (_("unexpected attribute encountered"));
10367 case OP_ATR_FIRST:
10368 return value_from_longest
10369 (type, ada_array_bound (arg1, tem, 0));
10370 case OP_ATR_LAST:
10371 return value_from_longest
10372 (type, ada_array_bound (arg1, tem, 1));
10373 case OP_ATR_LENGTH:
10374 return value_from_longest
10375 (type, ada_array_length (arg1, tem));
10378 else if (discrete_type_p (type_arg))
10380 struct type *range_type;
10381 const char *name = ada_type_name (type_arg);
10383 range_type = NULL;
10384 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10385 range_type = to_fixed_range_type (type_arg, NULL);
10386 if (range_type == NULL)
10387 range_type = type_arg;
10388 switch (op)
10390 default:
10391 error (_("unexpected attribute encountered"));
10392 case OP_ATR_FIRST:
10393 return value_from_longest
10394 (range_type, ada_discrete_type_low_bound (range_type));
10395 case OP_ATR_LAST:
10396 return value_from_longest
10397 (range_type, ada_discrete_type_high_bound (range_type));
10398 case OP_ATR_LENGTH:
10399 error (_("the 'length attribute applies only to array types"));
10402 else if (type_arg->code () == TYPE_CODE_FLT)
10403 error (_("unimplemented type attribute"));
10404 else
10406 LONGEST low, high;
10408 if (ada_is_constrained_packed_array_type (type_arg))
10409 type_arg = decode_constrained_packed_array_type (type_arg);
10411 struct type *type;
10412 if (op == OP_ATR_LENGTH)
10413 type = builtin_type (exp->gdbarch)->builtin_int;
10414 else
10416 type = ada_index_type (type_arg, tem, attr_name);
10417 if (type == NULL)
10418 type = builtin_type (exp->gdbarch)->builtin_int;
10421 switch (op)
10423 default:
10424 error (_("unexpected attribute encountered"));
10425 case OP_ATR_FIRST:
10426 low = ada_array_bound_from_type (type_arg, tem, 0);
10427 return value_from_longest (type, low);
10428 case OP_ATR_LAST:
10429 high = ada_array_bound_from_type (type_arg, tem, 1);
10430 return value_from_longest (type, high);
10431 case OP_ATR_LENGTH:
10432 low = ada_array_bound_from_type (type_arg, tem, 0);
10433 high = ada_array_bound_from_type (type_arg, tem, 1);
10434 return value_from_longest (type, high - low + 1);
10439 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10441 struct value *
10442 ada_binop_minmax (struct type *expect_type,
10443 struct expression *exp,
10444 enum noside noside, enum exp_opcode op,
10445 struct value *arg1, struct value *arg2)
10447 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10448 return value::zero (arg1->type (), not_lval);
10449 else
10451 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10452 return value_binop (arg1, arg2, op);
10456 /* A helper function for BINOP_EXP. */
10458 struct value *
10459 ada_binop_exp (struct type *expect_type,
10460 struct expression *exp,
10461 enum noside noside, enum exp_opcode op,
10462 struct value *arg1, struct value *arg2)
10464 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10465 return value::zero (arg1->type (), not_lval);
10466 else
10468 /* For integer exponentiation operations,
10469 only promote the first argument. */
10470 if (is_integral_type (arg2->type ()))
10471 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10472 else
10473 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10475 return value_binop (arg1, arg2, op);
10479 namespace expr
10482 /* See ada-exp.h. */
10484 operation_up
10485 ada_resolvable::replace (operation_up &&owner,
10486 struct expression *exp,
10487 bool deprocedure_p,
10488 bool parse_completion,
10489 innermost_block_tracker *tracker,
10490 struct type *context_type)
10492 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10493 return (make_operation<ada_funcall_operation>
10494 (std::move (owner),
10495 std::vector<operation_up> ()));
10496 return std::move (owner);
10499 /* Convert the character literal whose value would be VAL to the
10500 appropriate value of type TYPE, if there is a translation.
10501 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10502 the literal 'A' (VAL == 65), returns 0. */
10504 static LONGEST
10505 convert_char_literal (struct type *type, LONGEST val)
10507 char name[12];
10508 int f;
10510 if (type == NULL)
10511 return val;
10512 type = check_typedef (type);
10513 if (type->code () != TYPE_CODE_ENUM)
10514 return val;
10516 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10517 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10518 else if (val >= 0 && val < 256)
10519 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10520 else if (val >= 0 && val < 0x10000)
10521 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10522 else
10523 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10524 size_t len = strlen (name);
10525 for (f = 0; f < type->num_fields (); f += 1)
10527 /* Check the suffix because an enum constant in a package will
10528 have a name like "pkg__QUxx". This is safe enough because we
10529 already have the correct type, and because mangling means
10530 there can't be clashes. */
10531 const char *ename = type->field (f).name ();
10532 size_t elen = strlen (ename);
10534 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10535 return type->field (f).loc_enumval ();
10537 return val;
10540 value *
10541 ada_char_operation::evaluate (struct type *expect_type,
10542 struct expression *exp,
10543 enum noside noside)
10545 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10546 if (expect_type != nullptr)
10547 result = ada_value_cast (expect_type, result);
10548 return result;
10551 /* See ada-exp.h. */
10553 operation_up
10554 ada_char_operation::replace (operation_up &&owner,
10555 struct expression *exp,
10556 bool deprocedure_p,
10557 bool parse_completion,
10558 innermost_block_tracker *tracker,
10559 struct type *context_type)
10561 operation_up result = std::move (owner);
10563 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10565 LONGEST val = as_longest ();
10566 gdb_assert (result.get () == this);
10567 std::get<0> (m_storage) = context_type;
10568 std::get<1> (m_storage) = convert_char_literal (context_type, val);
10571 return result;
10574 value *
10575 ada_wrapped_operation::evaluate (struct type *expect_type,
10576 struct expression *exp,
10577 enum noside noside)
10579 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10580 if (noside == EVAL_NORMAL)
10581 result = unwrap_value (result);
10583 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10584 then we need to perform the conversion manually, because
10585 evaluate_subexp_standard doesn't do it. This conversion is
10586 necessary in Ada because the different kinds of float/fixed
10587 types in Ada have different representations.
10589 Similarly, we need to perform the conversion from OP_LONG
10590 ourselves. */
10591 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10592 result = ada_value_cast (expect_type, result);
10594 return result;
10597 void
10598 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10599 struct agent_expr *ax,
10600 struct axs_value *value,
10601 struct type *cast_type)
10603 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10605 struct type *type = value->type;
10606 if (ada_is_aligner_type (type))
10607 error (_("Aligner types cannot be handled in agent expressions"));
10608 else if (find_base_type (type) != nullptr)
10609 error (_("Dynamic types cannot be handled in agent expressions"));
10612 value *
10613 ada_string_operation::evaluate (struct type *expect_type,
10614 struct expression *exp,
10615 enum noside noside)
10617 struct type *char_type;
10618 if (expect_type != nullptr && ada_is_string_type (expect_type))
10619 char_type = ada_array_element_type (expect_type, 1);
10620 else
10621 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10623 const std::string &str = std::get<0> (m_storage);
10624 const char *encoding;
10625 switch (char_type->length ())
10627 case 1:
10629 /* Simply copy over the data -- this isn't perhaps strictly
10630 correct according to the encodings, but it is gdb's
10631 historical behavior. */
10632 struct type *stringtype
10633 = lookup_array_range_type (char_type, 1, str.length ());
10634 struct value *val = value::allocate (stringtype);
10635 memcpy (val->contents_raw ().data (), str.c_str (),
10636 str.length ());
10637 return val;
10640 case 2:
10641 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10642 encoding = "UTF-16BE";
10643 else
10644 encoding = "UTF-16LE";
10645 break;
10647 case 4:
10648 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10649 encoding = "UTF-32BE";
10650 else
10651 encoding = "UTF-32LE";
10652 break;
10654 default:
10655 error (_("unexpected character type size %s"),
10656 pulongest (char_type->length ()));
10659 auto_obstack converted;
10660 convert_between_encodings (host_charset (), encoding,
10661 (const gdb_byte *) str.c_str (),
10662 str.length (), 1,
10663 &converted, translit_none);
10665 struct type *stringtype
10666 = lookup_array_range_type (char_type, 1,
10667 obstack_object_size (&converted)
10668 / char_type->length ());
10669 struct value *val = value::allocate (stringtype);
10670 memcpy (val->contents_raw ().data (),
10671 obstack_base (&converted),
10672 obstack_object_size (&converted));
10673 return val;
10676 value *
10677 ada_concat_operation::evaluate (struct type *expect_type,
10678 struct expression *exp,
10679 enum noside noside)
10681 /* If one side is a literal, evaluate the other side first so that
10682 the expected type can be set properly. */
10683 const operation_up &lhs_expr = std::get<0> (m_storage);
10684 const operation_up &rhs_expr = std::get<1> (m_storage);
10686 value *lhs, *rhs;
10687 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10689 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10690 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10692 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10694 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10695 struct type *rhs_type = check_typedef (rhs->type ());
10696 struct type *elt_type = nullptr;
10697 if (rhs_type->code () == TYPE_CODE_ARRAY)
10698 elt_type = rhs_type->target_type ();
10699 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10701 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10703 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10704 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10706 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10708 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10709 struct type *lhs_type = check_typedef (lhs->type ());
10710 struct type *elt_type = nullptr;
10711 if (lhs_type->code () == TYPE_CODE_ARRAY)
10712 elt_type = lhs_type->target_type ();
10713 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10715 else
10716 return concat_operation::evaluate (expect_type, exp, noside);
10718 return value_concat (lhs, rhs);
10721 value *
10722 ada_qual_operation::evaluate (struct type *expect_type,
10723 struct expression *exp,
10724 enum noside noside)
10726 struct type *type = std::get<1> (m_storage);
10727 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10730 value *
10731 ada_ternop_range_operation::evaluate (struct type *expect_type,
10732 struct expression *exp,
10733 enum noside noside)
10735 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10736 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10737 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10738 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10741 value *
10742 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10743 struct expression *exp,
10744 enum noside noside)
10746 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10747 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10749 auto do_op = [this] (LONGEST x, LONGEST y)
10751 if (std::get<0> (m_storage) == BINOP_ADD)
10752 return x + y;
10753 return x - y;
10756 if (arg1->type ()->code () == TYPE_CODE_PTR)
10757 return (value_from_longest
10758 (arg1->type (),
10759 do_op (value_as_long (arg1), value_as_long (arg2))));
10760 if (arg2->type ()->code () == TYPE_CODE_PTR)
10761 return (value_from_longest
10762 (arg2->type (),
10763 do_op (value_as_long (arg1), value_as_long (arg2))));
10764 /* Preserve the original type for use by the range case below.
10765 We cannot cast the result to a reference type, so if ARG1 is
10766 a reference type, find its underlying type. */
10767 struct type *type = arg1->type ();
10768 while (type->code () == TYPE_CODE_REF)
10769 type = type->target_type ();
10770 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10771 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10772 /* We need to special-case the result with a range.
10773 This is done for the benefit of "ptype". gdb's Ada support
10774 historically used the LHS to set the result type here, so
10775 preserve this behavior. */
10776 if (type->code () == TYPE_CODE_RANGE)
10777 arg1 = value_cast (type, arg1);
10778 return arg1;
10781 value *
10782 ada_unop_atr_operation::evaluate (struct type *expect_type,
10783 struct expression *exp,
10784 enum noside noside)
10786 struct type *type_arg = nullptr;
10787 value *val = nullptr;
10789 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10791 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10792 EVAL_AVOID_SIDE_EFFECTS);
10793 type_arg = tem->type ();
10795 else
10796 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10798 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10799 val, type_arg, std::get<2> (m_storage));
10802 value *
10803 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10804 struct expression *exp,
10805 enum noside noside)
10807 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10808 return value::zero (expect_type, not_lval);
10810 const bound_minimal_symbol &b = std::get<0> (m_storage);
10811 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10813 val = ada_value_cast (expect_type, val);
10815 /* Follow the Ada language semantics that do not allow taking
10816 an address of the result of a cast (view conversion in Ada). */
10817 if (val->lval () == lval_memory)
10819 if (val->lazy ())
10820 val->fetch_lazy ();
10821 val->set_lval (not_lval);
10823 return val;
10826 value *
10827 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10828 struct expression *exp,
10829 enum noside noside)
10831 value *val = evaluate_var_value (noside,
10832 std::get<0> (m_storage).block,
10833 std::get<0> (m_storage).symbol);
10835 val = ada_value_cast (expect_type, val);
10837 /* Follow the Ada language semantics that do not allow taking
10838 an address of the result of a cast (view conversion in Ada). */
10839 if (val->lval () == lval_memory)
10841 if (val->lazy ())
10842 val->fetch_lazy ();
10843 val->set_lval (not_lval);
10845 return val;
10848 value *
10849 ada_var_value_operation::evaluate (struct type *expect_type,
10850 struct expression *exp,
10851 enum noside noside)
10853 symbol *sym = std::get<0> (m_storage).symbol;
10855 if (sym->domain () == UNDEF_DOMAIN)
10856 /* Only encountered when an unresolved symbol occurs in a
10857 context other than a function call, in which case, it is
10858 invalid. */
10859 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10860 sym->print_name ());
10862 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10864 struct type *type = static_unwrap_type (sym->type ());
10865 /* Check to see if this is a tagged type. We also need to handle
10866 the case where the type is a reference to a tagged type, but
10867 we have to be careful to exclude pointers to tagged types.
10868 The latter should be shown as usual (as a pointer), whereas
10869 a reference should mostly be transparent to the user. */
10870 if (ada_is_tagged_type (type, 0)
10871 || (type->code () == TYPE_CODE_REF
10872 && ada_is_tagged_type (type->target_type (), 0)))
10874 /* Tagged types are a little special in the fact that the real
10875 type is dynamic and can only be determined by inspecting the
10876 object's tag. This means that we need to get the object's
10877 value first (EVAL_NORMAL) and then extract the actual object
10878 type from its tag.
10880 Note that we cannot skip the final step where we extract
10881 the object type from its tag, because the EVAL_NORMAL phase
10882 results in dynamic components being resolved into fixed ones.
10883 This can cause problems when trying to print the type
10884 description of tagged types whose parent has a dynamic size:
10885 We use the type name of the "_parent" component in order
10886 to print the name of the ancestor type in the type description.
10887 If that component had a dynamic size, the resolution into
10888 a fixed type would result in the loss of that type name,
10889 thus preventing us from printing the name of the ancestor
10890 type in the type description. */
10891 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10893 if (type->code () != TYPE_CODE_REF)
10895 struct type *actual_type;
10897 actual_type = type_from_tag (ada_value_tag (arg1));
10898 if (actual_type == NULL)
10899 /* If, for some reason, we were unable to determine
10900 the actual type from the tag, then use the static
10901 approximation that we just computed as a fallback.
10902 This can happen if the debugging information is
10903 incomplete, for instance. */
10904 actual_type = type;
10905 return value::zero (actual_type, not_lval);
10907 else
10909 /* In the case of a ref, ada_coerce_ref takes care
10910 of determining the actual type. But the evaluation
10911 should return a ref as it should be valid to ask
10912 for its address; so rebuild a ref after coerce. */
10913 arg1 = ada_coerce_ref (arg1);
10914 return value_ref (arg1, TYPE_CODE_REF);
10918 /* Records and unions for which GNAT encodings have been
10919 generated need to be statically fixed as well.
10920 Otherwise, non-static fixing produces a type where
10921 all dynamic properties are removed, which prevents "ptype"
10922 from being able to completely describe the type.
10923 For instance, a case statement in a variant record would be
10924 replaced by the relevant components based on the actual
10925 value of the discriminants. */
10926 if ((type->code () == TYPE_CODE_STRUCT
10927 && dynamic_template_type (type) != NULL)
10928 || (type->code () == TYPE_CODE_UNION
10929 && ada_find_parallel_type (type, "___XVU") != NULL))
10930 return value::zero (to_static_fixed_type (type), not_lval);
10933 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10934 return ada_to_fixed_value (arg1);
10937 bool
10938 ada_var_value_operation::resolve (struct expression *exp,
10939 bool deprocedure_p,
10940 bool parse_completion,
10941 innermost_block_tracker *tracker,
10942 struct type *context_type)
10944 symbol *sym = std::get<0> (m_storage).symbol;
10945 if (sym->domain () == UNDEF_DOMAIN)
10947 block_symbol resolved
10948 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10949 context_type, parse_completion,
10950 deprocedure_p, tracker);
10951 std::get<0> (m_storage) = resolved;
10954 if (deprocedure_p
10955 && (std::get<0> (m_storage).symbol->type ()->code ()
10956 == TYPE_CODE_FUNC))
10957 return true;
10959 return false;
10962 void
10963 ada_var_value_operation::do_generate_ax (struct expression *exp,
10964 struct agent_expr *ax,
10965 struct axs_value *value,
10966 struct type *cast_type)
10968 symbol *sym = std::get<0> (m_storage).symbol;
10970 if (sym->domain () == UNDEF_DOMAIN)
10971 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10972 sym->print_name ());
10974 struct type *type = static_unwrap_type (sym->type ());
10975 if (ada_is_tagged_type (type, 0)
10976 || (type->code () == TYPE_CODE_REF
10977 && ada_is_tagged_type (type->target_type (), 0)))
10978 error (_("Tagged types cannot be handled in agent expressions"));
10980 if ((type->code () == TYPE_CODE_STRUCT
10981 && dynamic_template_type (type) != NULL)
10982 || (type->code () == TYPE_CODE_UNION
10983 && ada_find_parallel_type (type, "___XVU") != NULL))
10984 error (_("Dynamic types cannot be handled in agent expressions"));
10986 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10989 value *
10990 ada_unop_ind_operation::evaluate (struct type *expect_type,
10991 struct expression *exp,
10992 enum noside noside)
10994 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10996 struct type *type = ada_check_typedef (arg1->type ());
10997 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10999 if (ada_is_array_descriptor_type (type))
11001 /* GDB allows dereferencing GNAT array descriptors.
11002 However, for 'ptype' we don't want to try to
11003 "dereference" a thick pointer here -- that will end up
11004 giving us an array with (1 .. 0) for bounds, which is
11005 less clear than (<>). */
11006 struct type *arrType = ada_type_of_array (arg1, 0);
11008 if (arrType == NULL)
11009 error (_("Attempt to dereference null array pointer."));
11010 if (is_thick_pntr (type))
11011 return arg1;
11012 return value_at_lazy (arrType, 0);
11014 else if (type->code () == TYPE_CODE_PTR
11015 || type->code () == TYPE_CODE_REF
11016 /* In C you can dereference an array to get the 1st elt. */
11017 || type->code () == TYPE_CODE_ARRAY)
11019 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11020 only be determined by inspecting the object's tag.
11021 This means that we need to evaluate completely the
11022 expression in order to get its type. */
11024 if ((type->code () == TYPE_CODE_REF
11025 || type->code () == TYPE_CODE_PTR)
11026 && ada_is_tagged_type (type->target_type (), 0))
11028 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11029 EVAL_NORMAL);
11030 type = ada_value_ind (arg1)->type ();
11032 else
11034 type = to_static_fixed_type
11035 (ada_aligned_type
11036 (ada_check_typedef (type->target_type ())));
11038 return value::zero (type, lval_memory);
11040 else if (type->code () == TYPE_CODE_INT)
11042 /* GDB allows dereferencing an int. */
11043 if (expect_type == NULL)
11044 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11045 lval_memory);
11046 else
11048 expect_type =
11049 to_static_fixed_type (ada_aligned_type (expect_type));
11050 return value::zero (expect_type, lval_memory);
11053 else
11054 error (_("Attempt to take contents of a non-pointer value."));
11056 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11057 type = ada_check_typedef (arg1->type ());
11059 if (type->code () == TYPE_CODE_INT)
11060 /* GDB allows dereferencing an int. If we were given
11061 the expect_type, then use that as the target type.
11062 Otherwise, assume that the target type is an int. */
11064 if (expect_type != NULL)
11065 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11066 arg1));
11067 else
11068 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11069 value_as_address (arg1));
11072 if (ada_is_array_descriptor_type (type))
11073 /* GDB allows dereferencing GNAT array descriptors. */
11074 return ada_coerce_to_simple_array (arg1);
11075 else
11076 return ada_value_ind (arg1);
11079 value *
11080 ada_structop_operation::evaluate (struct type *expect_type,
11081 struct expression *exp,
11082 enum noside noside)
11084 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11085 const char *str = std::get<1> (m_storage).c_str ();
11086 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11088 struct type *type;
11089 struct type *type1 = arg1->type ();
11091 if (ada_is_tagged_type (type1, 1))
11093 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11095 /* If the field is not found, check if it exists in the
11096 extension of this object's type. This means that we
11097 need to evaluate completely the expression. */
11099 if (type == NULL)
11101 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11102 EVAL_NORMAL);
11103 arg1 = ada_value_struct_elt (arg1, str, 0);
11104 arg1 = unwrap_value (arg1);
11105 type = ada_to_fixed_value (arg1)->type ();
11108 else
11109 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11111 return value::zero (ada_aligned_type (type), lval_memory);
11113 else
11115 arg1 = ada_value_struct_elt (arg1, str, 0);
11116 arg1 = unwrap_value (arg1);
11117 return ada_to_fixed_value (arg1);
11121 value *
11122 ada_funcall_operation::evaluate (struct type *expect_type,
11123 struct expression *exp,
11124 enum noside noside)
11126 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11127 int nargs = args_up.size ();
11128 std::vector<value *> argvec (nargs);
11129 operation_up &callee_op = std::get<0> (m_storage);
11131 ada_var_value_operation *avv
11132 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11133 if (avv != nullptr
11134 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11135 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11136 avv->get_symbol ()->print_name ());
11138 value *callee = callee_op->evaluate (nullptr, exp, noside);
11139 for (int i = 0; i < args_up.size (); ++i)
11140 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11142 if (ada_is_constrained_packed_array_type
11143 (desc_base_type (callee->type ())))
11144 callee = ada_coerce_to_simple_array (callee);
11145 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11146 && callee->type ()->field (0).bitsize () != 0)
11147 /* This is a packed array that has already been fixed, and
11148 therefore already coerced to a simple array. Nothing further
11149 to do. */
11151 else if (callee->type ()->code () == TYPE_CODE_REF)
11153 /* Make sure we dereference references so that all the code below
11154 feels like it's really handling the referenced value. Wrapping
11155 types (for alignment) may be there, so make sure we strip them as
11156 well. */
11157 callee = ada_to_fixed_value (coerce_ref (callee));
11159 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11160 && callee->lval () == lval_memory)
11161 callee = value_addr (callee);
11163 struct type *type = ada_check_typedef (callee->type ());
11165 /* Ada allows us to implicitly dereference arrays when subscripting
11166 them. So, if this is an array typedef (encoding use for array
11167 access types encoded as fat pointers), strip it now. */
11168 if (type->code () == TYPE_CODE_TYPEDEF)
11169 type = ada_typedef_target_type (type);
11171 if (type->code () == TYPE_CODE_PTR)
11173 switch (ada_check_typedef (type->target_type ())->code ())
11175 case TYPE_CODE_FUNC:
11176 type = ada_check_typedef (type->target_type ());
11177 break;
11178 case TYPE_CODE_ARRAY:
11179 break;
11180 case TYPE_CODE_STRUCT:
11181 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11182 callee = ada_value_ind (callee);
11183 type = ada_check_typedef (type->target_type ());
11184 break;
11185 default:
11186 error (_("cannot subscript or call something of type `%s'"),
11187 ada_type_name (callee->type ()));
11188 break;
11192 switch (type->code ())
11194 case TYPE_CODE_FUNC:
11195 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11197 if (type->target_type () == NULL)
11198 error_call_unknown_return_type (NULL);
11199 return value::allocate (type->target_type ());
11201 return call_function_by_hand (callee, expect_type, argvec);
11202 case TYPE_CODE_INTERNAL_FUNCTION:
11203 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11204 /* We don't know anything about what the internal
11205 function might return, but we have to return
11206 something. */
11207 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11208 not_lval);
11209 else
11210 return call_internal_function (exp->gdbarch, exp->language_defn,
11211 callee, nargs,
11212 argvec.data ());
11214 case TYPE_CODE_STRUCT:
11216 int arity;
11218 arity = ada_array_arity (type);
11219 type = ada_array_element_type (type, nargs);
11220 if (type == NULL)
11221 error (_("cannot subscript or call a record"));
11222 if (arity != nargs)
11223 error (_("wrong number of subscripts; expecting %d"), arity);
11224 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11225 return value::zero (ada_aligned_type (type), lval_memory);
11226 return
11227 unwrap_value (ada_value_subscript
11228 (callee, nargs, argvec.data ()));
11230 case TYPE_CODE_ARRAY:
11231 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11233 type = ada_array_element_type (type, nargs);
11234 if (type == NULL)
11235 error (_("element type of array unknown"));
11236 else
11237 return value::zero (ada_aligned_type (type), lval_memory);
11239 return
11240 unwrap_value (ada_value_subscript
11241 (ada_coerce_to_simple_array (callee),
11242 nargs, argvec.data ()));
11243 case TYPE_CODE_PTR: /* Pointer to array */
11244 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11246 type = to_fixed_array_type (type->target_type (), NULL, 1);
11247 type = ada_array_element_type (type, nargs);
11248 if (type == NULL)
11249 error (_("element type of array unknown"));
11250 else
11251 return value::zero (ada_aligned_type (type), lval_memory);
11253 return
11254 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11255 argvec.data ()));
11257 default:
11258 error (_("Attempt to index or call something other than an "
11259 "array or function"));
11263 bool
11264 ada_funcall_operation::resolve (struct expression *exp,
11265 bool deprocedure_p,
11266 bool parse_completion,
11267 innermost_block_tracker *tracker,
11268 struct type *context_type)
11270 operation_up &callee_op = std::get<0> (m_storage);
11272 ada_var_value_operation *avv
11273 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11274 if (avv == nullptr)
11275 return false;
11277 symbol *sym = avv->get_symbol ();
11278 if (sym->domain () != UNDEF_DOMAIN)
11279 return false;
11281 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11282 int nargs = args_up.size ();
11283 std::vector<value *> argvec (nargs);
11285 for (int i = 0; i < args_up.size (); ++i)
11286 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11288 const block *block = avv->get_block ();
11289 block_symbol resolved
11290 = ada_resolve_funcall (sym, block,
11291 context_type, parse_completion,
11292 nargs, argvec.data (),
11293 tracker);
11295 std::get<0> (m_storage)
11296 = make_operation<ada_var_value_operation> (resolved);
11297 return false;
11300 bool
11301 ada_ternop_slice_operation::resolve (struct expression *exp,
11302 bool deprocedure_p,
11303 bool parse_completion,
11304 innermost_block_tracker *tracker,
11305 struct type *context_type)
11307 /* Historically this check was done during resolution, so we
11308 continue that here. */
11309 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11310 EVAL_AVOID_SIDE_EFFECTS);
11311 if (ada_is_any_packed_array_type (v->type ()))
11312 error (_("cannot slice a packed array"));
11313 return false;
11320 /* Return non-zero iff TYPE represents a System.Address type. */
11323 ada_is_system_address_type (struct type *type)
11325 return (type->name () && strcmp (type->name (), "system__address") == 0);
11330 /* Range types */
11332 /* Scan STR beginning at position K for a discriminant name, and
11333 return the value of that discriminant field of DVAL in *PX. If
11334 PNEW_K is not null, put the position of the character beyond the
11335 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11336 not alter *PX and *PNEW_K if unsuccessful. */
11338 static int
11339 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11340 int *pnew_k)
11342 static std::string storage;
11343 const char *pstart, *pend, *bound;
11344 struct value *bound_val;
11346 if (dval == NULL || str == NULL || str[k] == '\0')
11347 return 0;
11349 pstart = str + k;
11350 pend = strstr (pstart, "__");
11351 if (pend == NULL)
11353 bound = pstart;
11354 k += strlen (bound);
11356 else
11358 int len = pend - pstart;
11360 /* Strip __ and beyond. */
11361 storage = std::string (pstart, len);
11362 bound = storage.c_str ();
11363 k = pend - str;
11366 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11367 if (bound_val == NULL)
11368 return 0;
11370 *px = value_as_long (bound_val);
11371 if (pnew_k != NULL)
11372 *pnew_k = k;
11373 return 1;
11376 /* Value of variable named NAME. Only exact matches are considered.
11377 If no such variable found, then if ERR_MSG is null, returns 0, and
11378 otherwise causes an error with message ERR_MSG. */
11380 static struct value *
11381 get_var_value (const char *name, const char *err_msg)
11383 std::string quoted_name = add_angle_brackets (name);
11385 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11387 std::vector<struct block_symbol> syms
11388 = ada_lookup_symbol_list_worker (lookup_name,
11389 get_selected_block (0),
11390 SEARCH_VFT, 1);
11392 if (syms.size () != 1)
11394 if (err_msg == NULL)
11395 return 0;
11396 else
11397 error (("%s"), err_msg);
11400 return value_of_variable (syms[0].symbol, syms[0].block);
11403 /* Value of integer variable named NAME in the current environment.
11404 If no such variable is found, returns false. Otherwise, sets VALUE
11405 to the variable's value and returns true. */
11407 bool
11408 get_int_var_value (const char *name, LONGEST &value)
11410 struct value *var_val = get_var_value (name, 0);
11412 if (var_val == 0)
11413 return false;
11415 value = value_as_long (var_val);
11416 return true;
11420 /* Return a range type whose base type is that of the range type named
11421 NAME in the current environment, and whose bounds are calculated
11422 from NAME according to the GNAT range encoding conventions.
11423 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11424 corresponding range type from debug information; fall back to using it
11425 if symbol lookup fails. If a new type must be created, allocate it
11426 like ORIG_TYPE was. The bounds information, in general, is encoded
11427 in NAME, the base type given in the named range type. */
11429 static struct type *
11430 to_fixed_range_type (struct type *raw_type, struct value *dval)
11432 const char *name;
11433 struct type *base_type;
11434 const char *subtype_info;
11436 gdb_assert (raw_type != NULL);
11437 gdb_assert (raw_type->name () != NULL);
11439 if (raw_type->code () == TYPE_CODE_RANGE)
11440 base_type = raw_type->target_type ();
11441 else
11442 base_type = raw_type;
11444 name = raw_type->name ();
11445 subtype_info = strstr (name, "___XD");
11446 if (subtype_info == NULL)
11448 LONGEST L = ada_discrete_type_low_bound (raw_type);
11449 LONGEST U = ada_discrete_type_high_bound (raw_type);
11451 if (L < INT_MIN || U > INT_MAX)
11452 return raw_type;
11453 else
11455 type_allocator alloc (raw_type);
11456 return create_static_range_type (alloc, raw_type, L, U);
11459 else
11461 int prefix_len = subtype_info - name;
11462 LONGEST L, U;
11463 struct type *type;
11464 const char *bounds_str;
11465 int n;
11467 subtype_info += 5;
11468 bounds_str = strchr (subtype_info, '_');
11469 n = 1;
11471 if (*subtype_info == 'L')
11473 if (!ada_scan_number (bounds_str, n, &L, &n)
11474 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11475 return raw_type;
11476 if (bounds_str[n] == '_')
11477 n += 2;
11478 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11479 n += 1;
11480 subtype_info += 1;
11482 else
11484 std::string name_buf = std::string (name, prefix_len) + "___L";
11485 if (!get_int_var_value (name_buf.c_str (), L))
11487 lim_warning (_("Unknown lower bound, using 1."));
11488 L = 1;
11492 if (*subtype_info == 'U')
11494 if (!ada_scan_number (bounds_str, n, &U, &n)
11495 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11496 return raw_type;
11498 else
11500 std::string name_buf = std::string (name, prefix_len) + "___U";
11501 if (!get_int_var_value (name_buf.c_str (), U))
11503 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11504 U = L;
11508 type_allocator alloc (raw_type);
11509 type = create_static_range_type (alloc, base_type, L, U);
11510 /* create_static_range_type alters the resulting type's length
11511 to match the size of the base_type, which is not what we want.
11512 Set it back to the original range type's length. */
11513 type->set_length (raw_type->length ());
11514 type->set_name (name);
11515 return type;
11519 /* True iff NAME is the name of a range type. */
11522 ada_is_range_type_name (const char *name)
11524 return (name != NULL && strstr (name, "___XD"));
11528 /* Modular types */
11530 /* True iff TYPE is an Ada modular type. */
11533 ada_is_modular_type (struct type *type)
11535 struct type *subranged_type = get_base_type (type);
11537 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11538 && subranged_type->code () == TYPE_CODE_INT
11539 && subranged_type->is_unsigned ());
11542 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11544 ULONGEST
11545 ada_modulus (struct type *type)
11547 const dynamic_prop &high = type->bounds ()->high;
11549 if (high.is_constant ())
11550 return (ULONGEST) high.const_val () + 1;
11552 /* If TYPE is unresolved, the high bound might be a location list. Return
11553 0, for lack of a better value to return. */
11554 return 0;
11558 /* Ada exception catchpoint support:
11559 ---------------------------------
11561 We support 3 kinds of exception catchpoints:
11562 . catchpoints on Ada exceptions
11563 . catchpoints on unhandled Ada exceptions
11564 . catchpoints on failed assertions
11566 Exceptions raised during failed assertions, or unhandled exceptions
11567 could perfectly be caught with the general catchpoint on Ada exceptions.
11568 However, we can easily differentiate these two special cases, and having
11569 the option to distinguish these two cases from the rest can be useful
11570 to zero-in on certain situations.
11572 Exception catchpoints are a specialized form of breakpoint,
11573 since they rely on inserting breakpoints inside known routines
11574 of the GNAT runtime. The implementation therefore uses a standard
11575 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11576 of breakpoint_ops.
11578 Support in the runtime for exception catchpoints have been changed
11579 a few times already, and these changes affect the implementation
11580 of these catchpoints. In order to be able to support several
11581 variants of the runtime, we use a sniffer that will determine
11582 the runtime variant used by the program being debugged. */
11584 /* Ada's standard exceptions.
11586 The Ada 83 standard also defined Numeric_Error. But there so many
11587 situations where it was unclear from the Ada 83 Reference Manual
11588 (RM) whether Constraint_Error or Numeric_Error should be raised,
11589 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11590 Interpretation saying that anytime the RM says that Numeric_Error
11591 should be raised, the implementation may raise Constraint_Error.
11592 Ada 95 went one step further and pretty much removed Numeric_Error
11593 from the list of standard exceptions (it made it a renaming of
11594 Constraint_Error, to help preserve compatibility when compiling
11595 an Ada83 compiler). As such, we do not include Numeric_Error from
11596 this list of standard exceptions. */
11598 static const char * const standard_exc[] = {
11599 "constraint_error",
11600 "program_error",
11601 "storage_error",
11602 "tasking_error"
11605 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11607 /* A structure that describes how to support exception catchpoints
11608 for a given executable. */
11610 struct exception_support_info
11612 /* The name of the symbol to break on in order to insert
11613 a catchpoint on exceptions. */
11614 const char *catch_exception_sym;
11616 /* The name of the symbol to break on in order to insert
11617 a catchpoint on unhandled exceptions. */
11618 const char *catch_exception_unhandled_sym;
11620 /* The name of the symbol to break on in order to insert
11621 a catchpoint on failed assertions. */
11622 const char *catch_assert_sym;
11624 /* The name of the symbol to break on in order to insert
11625 a catchpoint on exception handling. */
11626 const char *catch_handlers_sym;
11628 /* Assuming that the inferior just triggered an unhandled exception
11629 catchpoint, this function is responsible for returning the address
11630 in inferior memory where the name of that exception is stored.
11631 Return zero if the address could not be computed. */
11632 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11635 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11636 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11638 /* The following exception support info structure describes how to
11639 implement exception catchpoints with the latest version of the
11640 Ada runtime (as of 2019-08-??). */
11642 static const struct exception_support_info default_exception_support_info =
11644 "__gnat_debug_raise_exception", /* catch_exception_sym */
11645 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11646 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11647 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11648 ada_unhandled_exception_name_addr
11651 /* The following exception support info structure describes how to
11652 implement exception catchpoints with an earlier version of the
11653 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11655 static const struct exception_support_info exception_support_info_v0 =
11657 "__gnat_debug_raise_exception", /* catch_exception_sym */
11658 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11659 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11660 "__gnat_begin_handler", /* catch_handlers_sym */
11661 ada_unhandled_exception_name_addr
11664 /* The following exception support info structure describes how to
11665 implement exception catchpoints with a slightly older version
11666 of the Ada runtime. */
11668 static const struct exception_support_info exception_support_info_fallback =
11670 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11671 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11672 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11673 "__gnat_begin_handler", /* catch_handlers_sym */
11674 ada_unhandled_exception_name_addr_from_raise
11677 /* Return nonzero if we can detect the exception support routines
11678 described in EINFO.
11680 This function errors out if an abnormal situation is detected
11681 (for instance, if we find the exception support routines, but
11682 that support is found to be incomplete). */
11684 static int
11685 ada_has_this_exception_support (const struct exception_support_info *einfo)
11687 struct symbol *sym;
11689 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11690 that should be compiled with debugging information. As a result, we
11691 expect to find that symbol in the symtabs. */
11693 sym = standard_lookup (einfo->catch_exception_sym, NULL, SEARCH_VFT);
11694 if (sym == NULL)
11696 /* Perhaps we did not find our symbol because the Ada runtime was
11697 compiled without debugging info, or simply stripped of it.
11698 It happens on some GNU/Linux distributions for instance, where
11699 users have to install a separate debug package in order to get
11700 the runtime's debugging info. In that situation, let the user
11701 know why we cannot insert an Ada exception catchpoint.
11703 Note: Just for the purpose of inserting our Ada exception
11704 catchpoint, we could rely purely on the associated minimal symbol.
11705 But we would be operating in degraded mode anyway, since we are
11706 still lacking the debugging info needed later on to extract
11707 the name of the exception being raised (this name is printed in
11708 the catchpoint message, and is also used when trying to catch
11709 a specific exception). We do not handle this case for now. */
11710 struct bound_minimal_symbol msym
11711 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11713 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11714 error (_("Your Ada runtime appears to be missing some debugging "
11715 "information.\nCannot insert Ada exception catchpoint "
11716 "in this configuration."));
11718 return 0;
11721 /* Make sure that the symbol we found corresponds to a function. */
11723 if (sym->aclass () != LOC_BLOCK)
11724 error (_("Symbol \"%s\" is not a function (class = %d)"),
11725 sym->linkage_name (), sym->aclass ());
11727 sym = standard_lookup (einfo->catch_handlers_sym, NULL, SEARCH_VFT);
11728 if (sym == NULL)
11730 struct bound_minimal_symbol msym
11731 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11733 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11734 error (_("Your Ada runtime appears to be missing some debugging "
11735 "information.\nCannot insert Ada exception catchpoint "
11736 "in this configuration."));
11738 return 0;
11741 /* Make sure that the symbol we found corresponds to a function. */
11743 if (sym->aclass () != LOC_BLOCK)
11744 error (_("Symbol \"%s\" is not a function (class = %d)"),
11745 sym->linkage_name (), sym->aclass ());
11747 return 1;
11750 /* Inspect the Ada runtime and determine which exception info structure
11751 should be used to provide support for exception catchpoints.
11753 This function will always set the per-inferior exception_info,
11754 or raise an error. */
11756 static void
11757 ada_exception_support_info_sniffer (void)
11759 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11761 /* If the exception info is already known, then no need to recompute it. */
11762 if (data->exception_info != NULL)
11763 return;
11765 /* Check the latest (default) exception support info. */
11766 if (ada_has_this_exception_support (&default_exception_support_info))
11768 data->exception_info = &default_exception_support_info;
11769 return;
11772 /* Try the v0 exception suport info. */
11773 if (ada_has_this_exception_support (&exception_support_info_v0))
11775 data->exception_info = &exception_support_info_v0;
11776 return;
11779 /* Try our fallback exception suport info. */
11780 if (ada_has_this_exception_support (&exception_support_info_fallback))
11782 data->exception_info = &exception_support_info_fallback;
11783 return;
11786 throw_error (NOT_FOUND_ERROR,
11787 _("Could not find Ada runtime exception support"));
11790 /* True iff FRAME is very likely to be that of a function that is
11791 part of the runtime system. This is all very heuristic, but is
11792 intended to be used as advice as to what frames are uninteresting
11793 to most users. */
11795 static int
11796 is_known_support_routine (const frame_info_ptr &frame)
11798 enum language func_lang;
11799 int i;
11800 const char *fullname;
11802 /* If this code does not have any debugging information (no symtab),
11803 This cannot be any user code. */
11805 symtab_and_line sal = find_frame_sal (frame);
11806 if (sal.symtab == NULL)
11807 return 1;
11809 /* If there is a symtab, but the associated source file cannot be
11810 located, then assume this is not user code: Selecting a frame
11811 for which we cannot display the code would not be very helpful
11812 for the user. This should also take care of case such as VxWorks
11813 where the kernel has some debugging info provided for a few units. */
11815 fullname = symtab_to_fullname (sal.symtab);
11816 if (access (fullname, R_OK) != 0)
11817 return 1;
11819 /* Check the unit filename against the Ada runtime file naming.
11820 We also check the name of the objfile against the name of some
11821 known system libraries that sometimes come with debugging info
11822 too. */
11824 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11826 re_comp (known_runtime_file_name_patterns[i]);
11827 if (re_exec (lbasename (sal.symtab->filename)))
11828 return 1;
11829 if (sal.symtab->compunit ()->objfile () != NULL
11830 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11831 return 1;
11834 /* Check whether the function is a GNAT-generated entity. */
11836 gdb::unique_xmalloc_ptr<char> func_name
11837 = find_frame_funname (frame, &func_lang, NULL);
11838 if (func_name == NULL)
11839 return 1;
11841 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11843 re_comp (known_auxiliary_function_name_patterns[i]);
11844 if (re_exec (func_name.get ()))
11845 return 1;
11848 return 0;
11851 /* Find the first frame that contains debugging information and that is not
11852 part of the Ada run-time, starting from FI and moving upward. */
11854 void
11855 ada_find_printable_frame (const frame_info_ptr &initial_fi)
11857 for (frame_info_ptr fi = initial_fi; fi != nullptr; fi = get_prev_frame (fi))
11859 if (!is_known_support_routine (fi))
11861 select_frame (fi);
11862 break;
11868 /* Assuming that the inferior just triggered an unhandled exception
11869 catchpoint, return the address in inferior memory where the name
11870 of the exception is stored.
11872 Return zero if the address could not be computed. */
11874 static CORE_ADDR
11875 ada_unhandled_exception_name_addr (void)
11877 return parse_and_eval_address ("e.full_name");
11880 /* Same as ada_unhandled_exception_name_addr, except that this function
11881 should be used when the inferior uses an older version of the runtime,
11882 where the exception name needs to be extracted from a specific frame
11883 several frames up in the callstack. */
11885 static CORE_ADDR
11886 ada_unhandled_exception_name_addr_from_raise (void)
11888 int frame_level;
11889 frame_info_ptr fi;
11890 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11892 /* To determine the name of this exception, we need to select
11893 the frame corresponding to RAISE_SYM_NAME. This frame is
11894 at least 3 levels up, so we simply skip the first 3 frames
11895 without checking the name of their associated function. */
11896 fi = get_current_frame ();
11897 for (frame_level = 0; frame_level < 3; frame_level += 1)
11898 if (fi != NULL)
11899 fi = get_prev_frame (fi);
11901 while (fi != NULL)
11903 enum language func_lang;
11905 gdb::unique_xmalloc_ptr<char> func_name
11906 = find_frame_funname (fi, &func_lang, NULL);
11907 if (func_name != NULL)
11909 if (strcmp (func_name.get (),
11910 data->exception_info->catch_exception_sym) == 0)
11911 break; /* We found the frame we were looking for... */
11913 fi = get_prev_frame (fi);
11916 if (fi == NULL)
11917 return 0;
11919 select_frame (fi);
11920 return parse_and_eval_address ("id.full_name");
11923 /* Assuming the inferior just triggered an Ada exception catchpoint
11924 (of any type), return the address in inferior memory where the name
11925 of the exception is stored, if applicable.
11927 Assumes the selected frame is the current frame.
11929 Return zero if the address could not be computed, or if not relevant. */
11931 static CORE_ADDR
11932 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11934 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11936 switch (ex)
11938 case ada_catch_exception:
11939 return (parse_and_eval_address ("e.full_name"));
11940 break;
11942 case ada_catch_exception_unhandled:
11943 return data->exception_info->unhandled_exception_name_addr ();
11944 break;
11946 case ada_catch_handlers:
11947 return 0; /* The runtimes does not provide access to the exception
11948 name. */
11949 break;
11951 case ada_catch_assert:
11952 return 0; /* Exception name is not relevant in this case. */
11953 break;
11955 default:
11956 internal_error (_("unexpected catchpoint type"));
11957 break;
11960 return 0; /* Should never be reached. */
11963 /* Assuming the inferior is stopped at an exception catchpoint,
11964 return the message which was associated to the exception, if
11965 available. Return NULL if the message could not be retrieved.
11967 Note: The exception message can be associated to an exception
11968 either through the use of the Raise_Exception function, or
11969 more simply (Ada 2005 and later), via:
11971 raise Exception_Name with "exception message";
11975 static gdb::unique_xmalloc_ptr<char>
11976 ada_exception_message_1 (void)
11978 struct value *e_msg_val;
11979 int e_msg_len;
11981 /* For runtimes that support this feature, the exception message
11982 is passed as an unbounded string argument called "message". */
11983 e_msg_val = parse_and_eval ("message");
11984 if (e_msg_val == NULL)
11985 return NULL; /* Exception message not supported. */
11987 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11988 gdb_assert (e_msg_val != NULL);
11989 e_msg_len = e_msg_val->type ()->length ();
11991 /* If the message string is empty, then treat it as if there was
11992 no exception message. */
11993 if (e_msg_len <= 0)
11994 return NULL;
11996 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11997 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
11998 e_msg_len);
11999 e_msg.get ()[e_msg_len] = '\0';
12001 return e_msg;
12004 /* Same as ada_exception_message_1, except that all exceptions are
12005 contained here (returning NULL instead). */
12007 static gdb::unique_xmalloc_ptr<char>
12008 ada_exception_message (void)
12010 gdb::unique_xmalloc_ptr<char> e_msg;
12014 e_msg = ada_exception_message_1 ();
12016 catch (const gdb_exception_error &e)
12018 e_msg.reset (nullptr);
12021 return e_msg;
12024 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12025 any error that ada_exception_name_addr_1 might cause to be thrown.
12026 When an error is intercepted, a warning with the error message is printed,
12027 and zero is returned. */
12029 static CORE_ADDR
12030 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12032 CORE_ADDR result = 0;
12036 result = ada_exception_name_addr_1 (ex);
12039 catch (const gdb_exception_error &e)
12041 warning (_("failed to get exception name: %s"), e.what ());
12042 return 0;
12045 return result;
12048 static std::string ada_exception_catchpoint_cond_string
12049 (const char *excep_string,
12050 enum ada_exception_catchpoint_kind ex);
12052 /* Ada catchpoints.
12054 In the case of catchpoints on Ada exceptions, the catchpoint will
12055 stop the target on every exception the program throws. When a user
12056 specifies the name of a specific exception, we translate this
12057 request into a condition expression (in text form), and then parse
12058 it into an expression stored in each of the catchpoint's locations.
12059 We then use this condition to check whether the exception that was
12060 raised is the one the user is interested in. If not, then the
12061 target is resumed again. We store the name of the requested
12062 exception, in order to be able to re-set the condition expression
12063 when symbols change. */
12065 /* An instance of this type is used to represent an Ada catchpoint. */
12067 struct ada_catchpoint : public code_breakpoint
12069 ada_catchpoint (struct gdbarch *gdbarch_,
12070 enum ada_exception_catchpoint_kind kind,
12071 const char *cond_string,
12072 bool tempflag,
12073 bool enabled,
12074 bool from_tty,
12075 std::string &&excep_string_)
12076 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
12077 m_excep_string (std::move (excep_string_)),
12078 m_kind (kind)
12080 /* Unlike most code_breakpoint types, Ada catchpoints are
12081 pspace-specific. */
12082 pspace = current_program_space;
12083 enable_state = enabled ? bp_enabled : bp_disabled;
12084 language = language_ada;
12086 re_set ();
12089 struct bp_location *allocate_location () override;
12090 void re_set () override;
12091 void check_status (struct bpstat *bs) override;
12092 enum print_stop_action print_it (const bpstat *bs) const override;
12093 bool print_one (const bp_location **) const override;
12094 void print_mention () const override;
12095 void print_recreate (struct ui_file *fp) const override;
12097 private:
12099 /* A helper function for check_status. Returns true if we should
12100 stop for this breakpoint hit. If the user specified a specific
12101 exception, we only want to cause a stop if the program thrown
12102 that exception. */
12103 bool should_stop_exception (const struct bp_location *bl) const;
12105 /* The name of the specific exception the user specified. */
12106 std::string m_excep_string;
12108 /* What kind of catchpoint this is. */
12109 enum ada_exception_catchpoint_kind m_kind;
12112 /* An instance of this type is used to represent an Ada catchpoint
12113 breakpoint location. */
12115 class ada_catchpoint_location : public bp_location
12117 public:
12118 explicit ada_catchpoint_location (ada_catchpoint *owner)
12119 : bp_location (owner, bp_loc_software_breakpoint)
12122 /* The condition that checks whether the exception that was raised
12123 is the specific exception the user specified on catchpoint
12124 creation. */
12125 expression_up excep_cond_expr;
12128 static struct symtab_and_line ada_exception_sal
12129 (enum ada_exception_catchpoint_kind ex);
12131 /* Implement the RE_SET method in the structure for all exception
12132 catchpoint kinds. */
12134 void
12135 ada_catchpoint::re_set ()
12137 std::vector<symtab_and_line> sals;
12140 struct symtab_and_line sal = ada_exception_sal (m_kind);
12141 sals.push_back (sal);
12143 catch (const gdb_exception_error &ex)
12145 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12146 if (ex.error != NOT_FOUND_ERROR)
12147 throw;
12150 update_breakpoint_locations (this, pspace, sals, {});
12152 /* Reparse the exception conditional expressions. One for each
12153 location. */
12155 /* Nothing to do if there's no specific exception to catch. */
12156 if (m_excep_string.empty ())
12157 return;
12159 /* Same if there are no locations... */
12160 if (!has_locations ())
12161 return;
12163 /* Compute the condition expression in text form, from the specific
12164 exception we want to catch. */
12165 std::string cond_string
12166 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
12168 /* Iterate over all the catchpoint's locations, and parse an
12169 expression for each. */
12170 for (bp_location &bl : locations ())
12172 ada_catchpoint_location &ada_loc
12173 = static_cast<ada_catchpoint_location &> (bl);
12174 expression_up exp;
12176 if (!bl.shlib_disabled)
12178 const char *s;
12180 s = cond_string.c_str ();
12183 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
12185 catch (const gdb_exception_error &e)
12187 warning (_("failed to reevaluate internal exception condition "
12188 "for catchpoint %d: %s"),
12189 number, e.what ());
12193 ada_loc.excep_cond_expr = std::move (exp);
12197 /* Implement the ALLOCATE_LOCATION method in the structure for all
12198 exception catchpoint kinds. */
12200 struct bp_location *
12201 ada_catchpoint::allocate_location ()
12203 return new ada_catchpoint_location (this);
12206 /* See declaration. */
12208 bool
12209 ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
12211 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
12212 const struct ada_catchpoint_location *ada_loc
12213 = (const struct ada_catchpoint_location *) bl;
12214 bool stop;
12216 struct internalvar *var = lookup_internalvar ("_ada_exception");
12217 if (c->m_kind == ada_catch_assert)
12218 clear_internalvar (var);
12219 else
12223 const char *expr;
12225 if (c->m_kind == ada_catch_handlers)
12226 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12227 ".all.occurrence.id");
12228 else
12229 expr = "e";
12231 struct value *exc = parse_and_eval (expr);
12232 set_internalvar (var, exc);
12234 catch (const gdb_exception_error &ex)
12236 clear_internalvar (var);
12240 /* With no specific exception, should always stop. */
12241 if (c->m_excep_string.empty ())
12242 return true;
12244 if (ada_loc->excep_cond_expr == NULL)
12246 /* We will have a NULL expression if back when we were creating
12247 the expressions, this location's had failed to parse. */
12248 return true;
12251 stop = true;
12254 scoped_value_mark mark;
12255 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
12257 catch (const gdb_exception_error &ex)
12259 exception_fprintf (gdb_stderr, ex,
12260 _("Error in testing exception condition:\n"));
12263 return stop;
12266 /* Implement the CHECK_STATUS method in the structure for all
12267 exception catchpoint kinds. */
12269 void
12270 ada_catchpoint::check_status (bpstat *bs)
12272 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12275 /* Implement the PRINT_IT method in the structure for all exception
12276 catchpoint kinds. */
12278 enum print_stop_action
12279 ada_catchpoint::print_it (const bpstat *bs) const
12281 struct ui_out *uiout = current_uiout;
12283 annotate_catchpoint (number);
12285 if (uiout->is_mi_like_p ())
12287 uiout->field_string ("reason",
12288 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12289 uiout->field_string ("disp", bpdisp_text (disposition));
12292 uiout->text (disposition == disp_del
12293 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12294 print_num_locno (bs, uiout);
12295 uiout->text (", ");
12297 /* ada_exception_name_addr relies on the selected frame being the
12298 current frame. Need to do this here because this function may be
12299 called more than once when printing a stop, and below, we'll
12300 select the first frame past the Ada run-time (see
12301 ada_find_printable_frame). */
12302 select_frame (get_current_frame ());
12304 switch (m_kind)
12306 case ada_catch_exception:
12307 case ada_catch_exception_unhandled:
12308 case ada_catch_handlers:
12310 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12311 char exception_name[256];
12313 if (addr != 0)
12315 read_memory (addr, (gdb_byte *) exception_name,
12316 sizeof (exception_name) - 1);
12317 exception_name [sizeof (exception_name) - 1] = '\0';
12319 else
12321 /* For some reason, we were unable to read the exception
12322 name. This could happen if the Runtime was compiled
12323 without debugging info, for instance. In that case,
12324 just replace the exception name by the generic string
12325 "exception" - it will read as "an exception" in the
12326 notification we are about to print. */
12327 memcpy (exception_name, "exception", sizeof ("exception"));
12329 /* In the case of unhandled exception breakpoints, we print
12330 the exception name as "unhandled EXCEPTION_NAME", to make
12331 it clearer to the user which kind of catchpoint just got
12332 hit. We used ui_out_text to make sure that this extra
12333 info does not pollute the exception name in the MI case. */
12334 if (m_kind == ada_catch_exception_unhandled)
12335 uiout->text ("unhandled ");
12336 uiout->field_string ("exception-name", exception_name);
12338 break;
12339 case ada_catch_assert:
12340 /* In this case, the name of the exception is not really
12341 important. Just print "failed assertion" to make it clearer
12342 that his program just hit an assertion-failure catchpoint.
12343 We used ui_out_text because this info does not belong in
12344 the MI output. */
12345 uiout->text ("failed assertion");
12346 break;
12349 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12350 if (exception_message != NULL)
12352 uiout->text (" (");
12353 uiout->field_string ("exception-message", exception_message.get ());
12354 uiout->text (")");
12357 uiout->text (" at ");
12358 ada_find_printable_frame (get_current_frame ());
12360 return PRINT_SRC_AND_LOC;
12363 /* Implement the PRINT_ONE method in the structure for all exception
12364 catchpoint kinds. */
12366 bool
12367 ada_catchpoint::print_one (const bp_location **last_loc) const
12369 struct ui_out *uiout = current_uiout;
12370 struct value_print_options opts;
12372 get_user_print_options (&opts);
12374 if (opts.addressprint)
12375 uiout->field_skip ("addr");
12377 annotate_field (5);
12378 switch (m_kind)
12380 case ada_catch_exception:
12381 if (!m_excep_string.empty ())
12383 std::string msg = string_printf (_("`%s' Ada exception"),
12384 m_excep_string.c_str ());
12386 uiout->field_string ("what", msg);
12388 else
12389 uiout->field_string ("what", "all Ada exceptions");
12391 break;
12393 case ada_catch_exception_unhandled:
12394 uiout->field_string ("what", "unhandled Ada exceptions");
12395 break;
12397 case ada_catch_handlers:
12398 if (!m_excep_string.empty ())
12400 uiout->field_fmt ("what",
12401 _("`%s' Ada exception handlers"),
12402 m_excep_string.c_str ());
12404 else
12405 uiout->field_string ("what", "all Ada exceptions handlers");
12406 break;
12408 case ada_catch_assert:
12409 uiout->field_string ("what", "failed Ada assertions");
12410 break;
12412 default:
12413 internal_error (_("unexpected catchpoint type"));
12414 break;
12417 return true;
12420 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12421 for all exception catchpoint kinds. */
12423 void
12424 ada_catchpoint::print_mention () const
12426 struct ui_out *uiout = current_uiout;
12428 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12429 : _("Catchpoint "));
12430 uiout->field_signed ("bkptno", number);
12431 uiout->text (": ");
12433 switch (m_kind)
12435 case ada_catch_exception:
12436 if (!m_excep_string.empty ())
12438 std::string info = string_printf (_("`%s' Ada exception"),
12439 m_excep_string.c_str ());
12440 uiout->text (info);
12442 else
12443 uiout->text (_("all Ada exceptions"));
12444 break;
12446 case ada_catch_exception_unhandled:
12447 uiout->text (_("unhandled Ada exceptions"));
12448 break;
12450 case ada_catch_handlers:
12451 if (!m_excep_string.empty ())
12453 std::string info
12454 = string_printf (_("`%s' Ada exception handlers"),
12455 m_excep_string.c_str ());
12456 uiout->text (info);
12458 else
12459 uiout->text (_("all Ada exceptions handlers"));
12460 break;
12462 case ada_catch_assert:
12463 uiout->text (_("failed Ada assertions"));
12464 break;
12466 default:
12467 internal_error (_("unexpected catchpoint type"));
12468 break;
12472 /* Implement the PRINT_RECREATE method in the structure for all
12473 exception catchpoint kinds. */
12475 void
12476 ada_catchpoint::print_recreate (struct ui_file *fp) const
12478 switch (m_kind)
12480 case ada_catch_exception:
12481 gdb_printf (fp, "catch exception");
12482 if (!m_excep_string.empty ())
12483 gdb_printf (fp, " %s", m_excep_string.c_str ());
12484 break;
12486 case ada_catch_exception_unhandled:
12487 gdb_printf (fp, "catch exception unhandled");
12488 break;
12490 case ada_catch_handlers:
12491 gdb_printf (fp, "catch handlers");
12492 break;
12494 case ada_catch_assert:
12495 gdb_printf (fp, "catch assert");
12496 break;
12498 default:
12499 internal_error (_("unexpected catchpoint type"));
12501 print_recreate_thread (fp);
12504 /* See ada-lang.h. */
12506 bool
12507 is_ada_exception_catchpoint (breakpoint *bp)
12509 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12512 /* Split the arguments specified in a "catch exception" command.
12513 Set EX to the appropriate catchpoint type.
12514 Set EXCEP_STRING to the name of the specific exception if
12515 specified by the user.
12516 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12517 "catch handlers" command. False otherwise.
12518 If a condition is found at the end of the arguments, the condition
12519 expression is stored in COND_STRING (memory must be deallocated
12520 after use). Otherwise COND_STRING is set to NULL. */
12522 static void
12523 catch_ada_exception_command_split (const char *args,
12524 bool is_catch_handlers_cmd,
12525 enum ada_exception_catchpoint_kind *ex,
12526 std::string *excep_string,
12527 std::string *cond_string)
12529 std::string exception_name;
12531 exception_name = extract_arg (&args);
12532 if (exception_name == "if")
12534 /* This is not an exception name; this is the start of a condition
12535 expression for a catchpoint on all exceptions. So, "un-get"
12536 this token, and set exception_name to NULL. */
12537 exception_name.clear ();
12538 args -= 2;
12541 /* Check to see if we have a condition. */
12543 args = skip_spaces (args);
12544 if (startswith (args, "if")
12545 && (isspace (args[2]) || args[2] == '\0'))
12547 args += 2;
12548 args = skip_spaces (args);
12550 if (args[0] == '\0')
12551 error (_("Condition missing after `if' keyword"));
12552 *cond_string = args;
12554 args += strlen (args);
12557 /* Check that we do not have any more arguments. Anything else
12558 is unexpected. */
12560 if (args[0] != '\0')
12561 error (_("Junk at end of expression"));
12563 if (is_catch_handlers_cmd)
12565 /* Catch handling of exceptions. */
12566 *ex = ada_catch_handlers;
12567 *excep_string = exception_name;
12569 else if (exception_name.empty ())
12571 /* Catch all exceptions. */
12572 *ex = ada_catch_exception;
12573 excep_string->clear ();
12575 else if (exception_name == "unhandled")
12577 /* Catch unhandled exceptions. */
12578 *ex = ada_catch_exception_unhandled;
12579 excep_string->clear ();
12581 else
12583 /* Catch a specific exception. */
12584 *ex = ada_catch_exception;
12585 *excep_string = exception_name;
12589 /* Return the name of the symbol on which we should break in order to
12590 implement a catchpoint of the EX kind. */
12592 static const char *
12593 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12595 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12597 gdb_assert (data->exception_info != NULL);
12599 switch (ex)
12601 case ada_catch_exception:
12602 return (data->exception_info->catch_exception_sym);
12603 break;
12604 case ada_catch_exception_unhandled:
12605 return (data->exception_info->catch_exception_unhandled_sym);
12606 break;
12607 case ada_catch_assert:
12608 return (data->exception_info->catch_assert_sym);
12609 break;
12610 case ada_catch_handlers:
12611 return (data->exception_info->catch_handlers_sym);
12612 break;
12613 default:
12614 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12618 /* Return the condition that will be used to match the current exception
12619 being raised with the exception that the user wants to catch. This
12620 assumes that this condition is used when the inferior just triggered
12621 an exception catchpoint.
12622 EX: the type of catchpoints used for catching Ada exceptions. */
12624 static std::string
12625 ada_exception_catchpoint_cond_string (const char *excep_string,
12626 enum ada_exception_catchpoint_kind ex)
12628 bool is_standard_exc = false;
12629 std::string result;
12631 if (ex == ada_catch_handlers)
12633 /* For exception handlers catchpoints, the condition string does
12634 not use the same parameter as for the other exceptions. */
12635 result = ("long_integer (GNAT_GCC_exception_Access"
12636 "(gcc_exception).all.occurrence.id)");
12638 else
12639 result = "long_integer (e)";
12641 /* The standard exceptions are a special case. They are defined in
12642 runtime units that have been compiled without debugging info; if
12643 EXCEP_STRING is the not-fully-qualified name of a standard
12644 exception (e.g. "constraint_error") then, during the evaluation
12645 of the condition expression, the symbol lookup on this name would
12646 *not* return this standard exception. The catchpoint condition
12647 may then be set only on user-defined exceptions which have the
12648 same not-fully-qualified name (e.g. my_package.constraint_error).
12650 To avoid this unexcepted behavior, these standard exceptions are
12651 systematically prefixed by "standard". This means that "catch
12652 exception constraint_error" is rewritten into "catch exception
12653 standard.constraint_error".
12655 If an exception named constraint_error is defined in another package of
12656 the inferior program, then the only way to specify this exception as a
12657 breakpoint condition is to use its fully-qualified named:
12658 e.g. my_package.constraint_error. */
12660 for (const char *name : standard_exc)
12662 if (strcmp (name, excep_string) == 0)
12664 is_standard_exc = true;
12665 break;
12669 result += " = ";
12671 if (is_standard_exc)
12672 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12673 else
12674 string_appendf (result, "long_integer (&%s)", excep_string);
12676 return result;
12679 /* Return the symtab_and_line that should be used to insert an
12680 exception catchpoint of the TYPE kind. */
12682 static struct symtab_and_line
12683 ada_exception_sal (enum ada_exception_catchpoint_kind ex)
12685 const char *sym_name;
12686 struct symbol *sym;
12688 /* First, find out which exception support info to use. */
12689 ada_exception_support_info_sniffer ();
12691 /* Then lookup the function on which we will break in order to catch
12692 the Ada exceptions requested by the user. */
12693 sym_name = ada_exception_sym_name (ex);
12694 sym = standard_lookup (sym_name, NULL, SEARCH_VFT);
12696 if (sym == NULL)
12697 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12698 sym_name);
12700 if (sym->aclass () != LOC_BLOCK)
12701 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12703 return find_function_start_sal (sym, 1);
12706 /* Create an Ada exception catchpoint.
12708 EX_KIND is the kind of exception catchpoint to be created.
12710 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12711 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12712 of the exception to which this catchpoint applies.
12714 COND_STRING, if not empty, is the catchpoint condition.
12716 TEMPFLAG, if nonzero, means that the underlying breakpoint
12717 should be temporary.
12719 FROM_TTY is the usual argument passed to all commands implementations. */
12721 void
12722 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12723 enum ada_exception_catchpoint_kind ex_kind,
12724 std::string &&excep_string,
12725 const std::string &cond_string,
12726 int tempflag,
12727 int enabled,
12728 int from_tty)
12730 std::unique_ptr<ada_catchpoint> c
12731 (new ada_catchpoint (gdbarch, ex_kind,
12732 cond_string.empty () ? nullptr : cond_string.c_str (),
12733 tempflag, enabled, from_tty,
12734 std::move (excep_string)));
12735 install_breakpoint (0, std::move (c), 1);
12738 /* Implement the "catch exception" command. */
12740 static void
12741 catch_ada_exception_command (const char *arg_entry, int from_tty,
12742 struct cmd_list_element *command)
12744 const char *arg = arg_entry;
12745 struct gdbarch *gdbarch = get_current_arch ();
12746 int tempflag;
12747 enum ada_exception_catchpoint_kind ex_kind;
12748 std::string excep_string;
12749 std::string cond_string;
12751 tempflag = command->context () == CATCH_TEMPORARY;
12753 if (!arg)
12754 arg = "";
12755 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12756 &cond_string);
12757 create_ada_exception_catchpoint (gdbarch, ex_kind,
12758 std::move (excep_string), cond_string,
12759 tempflag, 1 /* enabled */,
12760 from_tty);
12763 /* Implement the "catch handlers" command. */
12765 static void
12766 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12767 struct cmd_list_element *command)
12769 const char *arg = arg_entry;
12770 struct gdbarch *gdbarch = get_current_arch ();
12771 int tempflag;
12772 enum ada_exception_catchpoint_kind ex_kind;
12773 std::string excep_string;
12774 std::string cond_string;
12776 tempflag = command->context () == CATCH_TEMPORARY;
12778 if (!arg)
12779 arg = "";
12780 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12781 &cond_string);
12782 create_ada_exception_catchpoint (gdbarch, ex_kind,
12783 std::move (excep_string), cond_string,
12784 tempflag, 1 /* enabled */,
12785 from_tty);
12788 /* Completion function for the Ada "catch" commands. */
12790 static void
12791 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12792 const char *text, const char *word)
12794 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12796 for (const ada_exc_info &info : exceptions)
12798 if (startswith (info.name, word))
12799 tracker.add_completion (make_unique_xstrdup (info.name));
12803 /* Split the arguments specified in a "catch assert" command.
12805 ARGS contains the command's arguments (or the empty string if
12806 no arguments were passed).
12808 If ARGS contains a condition, set COND_STRING to that condition
12809 (the memory needs to be deallocated after use). */
12811 static void
12812 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12814 args = skip_spaces (args);
12816 /* Check whether a condition was provided. */
12817 if (startswith (args, "if")
12818 && (isspace (args[2]) || args[2] == '\0'))
12820 args += 2;
12821 args = skip_spaces (args);
12822 if (args[0] == '\0')
12823 error (_("condition missing after `if' keyword"));
12824 cond_string.assign (args);
12827 /* Otherwise, there should be no other argument at the end of
12828 the command. */
12829 else if (args[0] != '\0')
12830 error (_("Junk at end of arguments."));
12833 /* Implement the "catch assert" command. */
12835 static void
12836 catch_assert_command (const char *arg_entry, int from_tty,
12837 struct cmd_list_element *command)
12839 const char *arg = arg_entry;
12840 struct gdbarch *gdbarch = get_current_arch ();
12841 int tempflag;
12842 std::string cond_string;
12844 tempflag = command->context () == CATCH_TEMPORARY;
12846 if (!arg)
12847 arg = "";
12848 catch_ada_assert_command_split (arg, cond_string);
12849 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12850 {}, cond_string,
12851 tempflag, 1 /* enabled */,
12852 from_tty);
12855 /* Return non-zero if the symbol SYM is an Ada exception object. */
12857 static int
12858 ada_is_exception_sym (struct symbol *sym)
12860 const char *type_name = sym->type ()->name ();
12862 return (sym->aclass () != LOC_TYPEDEF
12863 && sym->aclass () != LOC_BLOCK
12864 && sym->aclass () != LOC_CONST
12865 && sym->aclass () != LOC_UNRESOLVED
12866 && type_name != NULL && strcmp (type_name, "exception") == 0);
12869 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12870 Ada exception object. This matches all exceptions except the ones
12871 defined by the Ada language. */
12873 static int
12874 ada_is_non_standard_exception_sym (struct symbol *sym)
12876 if (!ada_is_exception_sym (sym))
12877 return 0;
12879 for (const char *name : standard_exc)
12880 if (strcmp (sym->linkage_name (), name) == 0)
12881 return 0; /* A standard exception. */
12883 /* Numeric_Error is also a standard exception, so exclude it.
12884 See the STANDARD_EXC description for more details as to why
12885 this exception is not listed in that array. */
12886 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12887 return 0;
12889 return 1;
12892 /* A helper function for std::sort, comparing two struct ada_exc_info
12893 objects.
12895 The comparison is determined first by exception name, and then
12896 by exception address. */
12898 bool
12899 ada_exc_info::operator< (const ada_exc_info &other) const
12901 int result;
12903 result = strcmp (name, other.name);
12904 if (result < 0)
12905 return true;
12906 if (result == 0 && addr < other.addr)
12907 return true;
12908 return false;
12911 bool
12912 ada_exc_info::operator== (const ada_exc_info &other) const
12914 return addr == other.addr && strcmp (name, other.name) == 0;
12917 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12918 routine, but keeping the first SKIP elements untouched.
12920 All duplicates are also removed. */
12922 static void
12923 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12924 int skip)
12926 std::sort (exceptions->begin () + skip, exceptions->end ());
12927 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12928 exceptions->end ());
12931 /* Add all exceptions defined by the Ada standard whose name match
12932 a regular expression.
12934 If PREG is not NULL, then this regexp_t object is used to
12935 perform the symbol name matching. Otherwise, no name-based
12936 filtering is performed.
12938 EXCEPTIONS is a vector of exceptions to which matching exceptions
12939 gets pushed. */
12941 static void
12942 ada_add_standard_exceptions (compiled_regex *preg,
12943 std::vector<ada_exc_info> *exceptions)
12945 for (const char *name : standard_exc)
12947 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12949 symbol_name_match_type match_type = name_match_type_from_name (name);
12950 lookup_name_info lookup_name (name, match_type);
12952 symbol_name_matcher_ftype *match_name
12953 = ada_get_symbol_name_matcher (lookup_name);
12955 /* Iterate over all objfiles irrespective of scope or linker
12956 namespaces so we get all exceptions anywhere in the
12957 progspace. */
12958 for (objfile *objfile : current_program_space->objfiles ())
12960 for (minimal_symbol *msymbol : objfile->msymbols ())
12962 if (match_name (msymbol->linkage_name (), lookup_name,
12963 nullptr)
12964 && msymbol->type () != mst_solib_trampoline)
12966 ada_exc_info info
12967 = {name, msymbol->value_address (objfile)};
12969 exceptions->push_back (info);
12977 /* Add all Ada exceptions defined locally and accessible from the given
12978 FRAME.
12980 If PREG is not NULL, then this regexp_t object is used to
12981 perform the symbol name matching. Otherwise, no name-based
12982 filtering is performed.
12984 EXCEPTIONS is a vector of exceptions to which matching exceptions
12985 gets pushed. */
12987 static void
12988 ada_add_exceptions_from_frame (compiled_regex *preg,
12989 const frame_info_ptr &frame,
12990 std::vector<ada_exc_info> *exceptions)
12992 const struct block *block = get_frame_block (frame, 0);
12994 while (block != 0)
12996 for (struct symbol *sym : block_iterator_range (block))
12998 switch (sym->aclass ())
13000 case LOC_TYPEDEF:
13001 case LOC_BLOCK:
13002 case LOC_CONST:
13003 break;
13004 default:
13005 if (ada_is_exception_sym (sym))
13007 struct ada_exc_info info = {sym->print_name (),
13008 sym->value_address ()};
13010 exceptions->push_back (info);
13014 if (block->function () != NULL)
13015 break;
13016 block = block->superblock ();
13020 /* Return true if NAME matches PREG or if PREG is NULL. */
13022 static bool
13023 name_matches_regex (const char *name, compiled_regex *preg)
13025 return (preg == NULL
13026 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13029 /* Add all exceptions defined globally whose name name match
13030 a regular expression, excluding standard exceptions.
13032 The reason we exclude standard exceptions is that they need
13033 to be handled separately: Standard exceptions are defined inside
13034 a runtime unit which is normally not compiled with debugging info,
13035 and thus usually do not show up in our symbol search. However,
13036 if the unit was in fact built with debugging info, we need to
13037 exclude them because they would duplicate the entry we found
13038 during the special loop that specifically searches for those
13039 standard exceptions.
13041 If PREG is not NULL, then this regexp_t object is used to
13042 perform the symbol name matching. Otherwise, no name-based
13043 filtering is performed.
13045 EXCEPTIONS is a vector of exceptions to which matching exceptions
13046 gets pushed. */
13048 static void
13049 ada_add_global_exceptions (compiled_regex *preg,
13050 std::vector<ada_exc_info> *exceptions)
13052 /* In Ada, the symbol "search name" is a linkage name, whereas the
13053 regular expression used to do the matching refers to the natural
13054 name. So match against the decoded name. */
13055 expand_symtabs_matching (NULL,
13056 lookup_name_info::match_any (),
13057 [&] (const char *search_name)
13059 std::string decoded = ada_decode (search_name);
13060 return name_matches_regex (decoded.c_str (), preg);
13062 NULL,
13063 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13064 SEARCH_VAR_DOMAIN);
13066 /* Iterate over all objfiles irrespective of scope or linker namespaces
13067 so we get all exceptions anywhere in the progspace. */
13068 for (objfile *objfile : current_program_space->objfiles ())
13070 for (compunit_symtab *s : objfile->compunits ())
13072 const struct blockvector *bv = s->blockvector ();
13073 int i;
13075 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13077 const struct block *b = bv->block (i);
13079 for (struct symbol *sym : block_iterator_range (b))
13080 if (ada_is_non_standard_exception_sym (sym)
13081 && name_matches_regex (sym->natural_name (), preg))
13083 struct ada_exc_info info
13084 = {sym->print_name (), sym->value_address ()};
13086 exceptions->push_back (info);
13093 /* Implements ada_exceptions_list with the regular expression passed
13094 as a regex_t, rather than a string.
13096 If not NULL, PREG is used to filter out exceptions whose names
13097 do not match. Otherwise, all exceptions are listed. */
13099 static std::vector<ada_exc_info>
13100 ada_exceptions_list_1 (compiled_regex *preg)
13102 std::vector<ada_exc_info> result;
13103 int prev_len;
13105 /* First, list the known standard exceptions. These exceptions
13106 need to be handled separately, as they are usually defined in
13107 runtime units that have been compiled without debugging info. */
13109 ada_add_standard_exceptions (preg, &result);
13111 /* Next, find all exceptions whose scope is local and accessible
13112 from the currently selected frame. */
13114 if (has_stack_frames ())
13116 prev_len = result.size ();
13117 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13118 &result);
13119 if (result.size () > prev_len)
13120 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13123 /* Add all exceptions whose scope is global. */
13125 prev_len = result.size ();
13126 ada_add_global_exceptions (preg, &result);
13127 if (result.size () > prev_len)
13128 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13130 return result;
13133 /* Return a vector of ada_exc_info.
13135 If REGEXP is NULL, all exceptions are included in the result.
13136 Otherwise, it should contain a valid regular expression,
13137 and only the exceptions whose names match that regular expression
13138 are included in the result.
13140 The exceptions are sorted in the following order:
13141 - Standard exceptions (defined by the Ada language), in
13142 alphabetical order;
13143 - Exceptions only visible from the current frame, in
13144 alphabetical order;
13145 - Exceptions whose scope is global, in alphabetical order. */
13147 std::vector<ada_exc_info>
13148 ada_exceptions_list (const char *regexp)
13150 if (regexp == NULL)
13151 return ada_exceptions_list_1 (NULL);
13153 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13154 return ada_exceptions_list_1 (&reg);
13157 /* Implement the "info exceptions" command. */
13159 static void
13160 info_exceptions_command (const char *regexp, int from_tty)
13162 struct gdbarch *gdbarch = get_current_arch ();
13164 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13166 if (regexp != NULL)
13167 gdb_printf
13168 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13169 else
13170 gdb_printf (_("All defined Ada exceptions:\n"));
13172 for (const ada_exc_info &info : exceptions)
13173 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13177 /* Language vector */
13179 /* symbol_name_matcher_ftype adapter for wild_match. */
13181 static bool
13182 do_wild_match (const char *symbol_search_name,
13183 const lookup_name_info &lookup_name,
13184 completion_match_result *comp_match_res)
13186 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13189 /* symbol_name_matcher_ftype adapter for full_match. */
13191 static bool
13192 do_full_match (const char *symbol_search_name,
13193 const lookup_name_info &lookup_name,
13194 completion_match_result *comp_match_res)
13196 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13198 /* If both symbols start with "_ada_", just let the loop below
13199 handle the comparison. However, if only the symbol name starts
13200 with "_ada_", skip the prefix and let the match proceed as
13201 usual. */
13202 if (startswith (symbol_search_name, "_ada_")
13203 && !startswith (lname, "_ada"))
13204 symbol_search_name += 5;
13205 /* Likewise for ghost entities. */
13206 if (startswith (symbol_search_name, "___ghost_")
13207 && !startswith (lname, "___ghost_"))
13208 symbol_search_name += 9;
13210 int uscore_count = 0;
13211 while (*lname != '\0')
13213 if (*symbol_search_name != *lname)
13215 if (*symbol_search_name == 'B' && uscore_count == 2
13216 && symbol_search_name[1] == '_')
13218 symbol_search_name += 2;
13219 while (isdigit (*symbol_search_name))
13220 ++symbol_search_name;
13221 if (symbol_search_name[0] == '_'
13222 && symbol_search_name[1] == '_')
13224 symbol_search_name += 2;
13225 continue;
13228 return false;
13231 if (*symbol_search_name == '_')
13232 ++uscore_count;
13233 else
13234 uscore_count = 0;
13236 ++symbol_search_name;
13237 ++lname;
13240 return is_name_suffix (symbol_search_name);
13243 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13245 static bool
13246 do_exact_match (const char *symbol_search_name,
13247 const lookup_name_info &lookup_name,
13248 completion_match_result *comp_match_res)
13250 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13253 /* Build the Ada lookup name for LOOKUP_NAME. */
13255 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13257 std::string_view user_name = lookup_name.name ();
13259 if (!user_name.empty () && user_name[0] == '<')
13261 if (user_name.back () == '>')
13262 m_encoded_name = user_name.substr (1, user_name.size () - 2);
13263 else
13264 m_encoded_name = user_name.substr (1, user_name.size () - 1);
13265 m_encoded_p = true;
13266 m_verbatim_p = true;
13267 m_wild_match_p = false;
13268 m_standard_p = false;
13270 else
13272 m_verbatim_p = false;
13274 m_encoded_p = user_name.find ("__") != std::string_view::npos;
13276 if (!m_encoded_p)
13278 const char *folded = ada_fold_name (user_name);
13279 m_encoded_name = ada_encode_1 (folded, false);
13280 if (m_encoded_name.empty ())
13281 m_encoded_name = user_name;
13283 else
13284 m_encoded_name = user_name;
13286 /* Handle the 'package Standard' special case. See description
13287 of m_standard_p. */
13288 if (startswith (m_encoded_name.c_str (), "standard__"))
13290 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13291 m_standard_p = true;
13293 else
13294 m_standard_p = false;
13296 m_decoded_name = ada_decode (m_encoded_name.c_str (), true, false, false);
13298 /* If the name contains a ".", then the user is entering a fully
13299 qualified entity name, and the match must not be done in wild
13300 mode. Similarly, if the user wants to complete what looks
13301 like an encoded name, the match must not be done in wild
13302 mode. Also, in the standard__ special case always do
13303 non-wild matching. */
13304 m_wild_match_p
13305 = (lookup_name.match_type () != symbol_name_match_type::FULL
13306 && !m_encoded_p
13307 && !m_standard_p
13308 && user_name.find ('.') == std::string::npos);
13312 /* symbol_name_matcher_ftype method for Ada. This only handles
13313 completion mode. */
13315 static bool
13316 ada_symbol_name_matches (const char *symbol_search_name,
13317 const lookup_name_info &lookup_name,
13318 completion_match_result *comp_match_res)
13320 return lookup_name.ada ().matches (symbol_search_name,
13321 lookup_name.match_type (),
13322 comp_match_res);
13325 /* A name matcher that matches the symbol name exactly, with
13326 strcmp. */
13328 static bool
13329 literal_symbol_name_matcher (const char *symbol_search_name,
13330 const lookup_name_info &lookup_name,
13331 completion_match_result *comp_match_res)
13333 std::string_view name_view = lookup_name.name ();
13335 if (lookup_name.completion_mode ()
13336 ? (strncmp (symbol_search_name, name_view.data (),
13337 name_view.size ()) == 0)
13338 : symbol_search_name == name_view)
13340 if (comp_match_res != NULL)
13341 comp_match_res->set_match (symbol_search_name);
13342 return true;
13344 else
13345 return false;
13348 /* Implement the "get_symbol_name_matcher" language_defn method for
13349 Ada. */
13351 static symbol_name_matcher_ftype *
13352 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13354 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13355 return literal_symbol_name_matcher;
13357 if (lookup_name.completion_mode ())
13358 return ada_symbol_name_matches;
13359 else
13361 if (lookup_name.ada ().wild_match_p ())
13362 return do_wild_match;
13363 else if (lookup_name.ada ().verbatim_p ())
13364 return do_exact_match;
13365 else
13366 return do_full_match;
13370 /* Class representing the Ada language. */
13372 class ada_language : public language_defn
13374 public:
13375 ada_language ()
13376 : language_defn (language_ada)
13377 { /* Nothing. */ }
13379 /* See language.h. */
13381 const char *name () const override
13382 { return "ada"; }
13384 /* See language.h. */
13386 const char *natural_name () const override
13387 { return "Ada"; }
13389 /* See language.h. */
13391 const std::vector<const char *> &filename_extensions () const override
13393 static const std::vector<const char *> extensions
13394 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13395 return extensions;
13398 /* Print an array element index using the Ada syntax. */
13400 void print_array_index (struct type *index_type,
13401 LONGEST index,
13402 struct ui_file *stream,
13403 const value_print_options *options) const override
13405 struct value *index_value = val_atr (index_type, index);
13407 value_print (index_value, stream, options);
13408 gdb_printf (stream, " => ");
13411 /* Implement the "read_var_value" language_defn method for Ada. */
13413 struct value *read_var_value (struct symbol *var,
13414 const struct block *var_block,
13415 const frame_info_ptr &frame) const override
13417 /* The only case where default_read_var_value is not sufficient
13418 is when VAR is a renaming... */
13419 if (frame != nullptr)
13421 const struct block *frame_block = get_frame_block (frame, NULL);
13422 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13423 return ada_read_renaming_var_value (var, frame_block);
13426 /* This is a typical case where we expect the default_read_var_value
13427 function to work. */
13428 return language_defn::read_var_value (var, var_block, frame);
13431 /* See language.h. */
13432 bool symbol_printing_suppressed (struct symbol *symbol) const override
13434 return symbol->is_artificial ();
13437 /* See language.h. */
13438 struct value *value_string (struct gdbarch *gdbarch,
13439 const char *ptr, ssize_t len) const override
13441 struct type *type = language_string_char_type (this, gdbarch);
13442 value *val = ::value_string (ptr, len, type);
13443 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13444 strings that are arrays of characters, so fix the type now. */
13445 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13446 val->type ()->set_code (TYPE_CODE_ARRAY);
13447 return val;
13450 /* See language.h. */
13451 void language_arch_info (struct gdbarch *gdbarch,
13452 struct language_arch_info *lai) const override
13454 const struct builtin_type *builtin = builtin_type (gdbarch);
13456 /* Helper function to allow shorter lines below. */
13457 auto add = [&] (struct type *t)
13459 lai->add_primitive_type (t);
13462 type_allocator alloc (gdbarch);
13463 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13464 0, "integer"));
13465 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13466 0, "long_integer"));
13467 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13468 0, "short_integer"));
13469 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13470 1, "character");
13471 lai->set_string_char_type (char_type);
13472 add (char_type);
13473 add (init_character_type (alloc, 16, 1, "wide_character"));
13474 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13475 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13476 "float", gdbarch_float_format (gdbarch)));
13477 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13478 "long_float", gdbarch_double_format (gdbarch)));
13479 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13480 0, "long_long_integer"));
13481 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13482 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
13483 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13484 "long_long_float",
13485 gdbarch_long_double_format (gdbarch)));
13486 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13487 0, "natural"));
13488 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13489 0, "positive"));
13490 add (builtin->builtin_void);
13492 struct type *system_addr_ptr
13493 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13494 "void"));
13495 system_addr_ptr->set_name ("system__address");
13496 add (system_addr_ptr);
13498 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13499 type. This is a signed integral type whose size is the same as
13500 the size of addresses. */
13501 unsigned int addr_length = system_addr_ptr->length ();
13502 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13503 "storage_offset"));
13505 lai->set_bool_type (builtin->builtin_bool);
13508 /* See language.h. */
13510 bool iterate_over_symbols
13511 (const struct block *block, const lookup_name_info &name,
13512 domain_search_flags domain,
13513 gdb::function_view<symbol_found_callback_ftype> callback) const override
13515 std::vector<struct block_symbol> results
13516 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13517 for (block_symbol &sym : results)
13519 if (!callback (&sym))
13520 return false;
13523 return true;
13526 /* See language.h. */
13527 bool sniff_from_mangled_name
13528 (const char *mangled,
13529 gdb::unique_xmalloc_ptr<char> *out) const override
13531 std::string demangled = ada_decode (mangled);
13533 *out = NULL;
13535 if (demangled != mangled && demangled[0] != '<')
13537 /* Set the gsymbol language to Ada, but still return 0.
13538 Two reasons for that:
13540 1. For Ada, we prefer computing the symbol's decoded name
13541 on the fly rather than pre-compute it, in order to save
13542 memory (Ada projects are typically very large).
13544 2. There are some areas in the definition of the GNAT
13545 encoding where, with a bit of bad luck, we might be able
13546 to decode a non-Ada symbol, generating an incorrect
13547 demangled name (Eg: names ending with "TB" for instance
13548 are identified as task bodies and so stripped from
13549 the decoded name returned).
13551 Returning true, here, but not setting *DEMANGLED, helps us get
13552 a little bit of the best of both worlds. Because we're last,
13553 we should not affect any of the other languages that were
13554 able to demangle the symbol before us; we get to correctly
13555 tag Ada symbols as such; and even if we incorrectly tagged a
13556 non-Ada symbol, which should be rare, any routing through the
13557 Ada language should be transparent (Ada tries to behave much
13558 like C/C++ with non-Ada symbols). */
13559 return true;
13562 return false;
13565 /* See language.h. */
13567 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13568 int options) const override
13570 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13573 /* See language.h. */
13575 void print_type (struct type *type, const char *varstring,
13576 struct ui_file *stream, int show, int level,
13577 const struct type_print_options *flags) const override
13579 ada_print_type (type, varstring, stream, show, level, flags);
13582 /* See language.h. */
13584 const char *word_break_characters (void) const override
13586 return ada_completer_word_break_characters;
13589 /* See language.h. */
13591 void collect_symbol_completion_matches (completion_tracker &tracker,
13592 complete_symbol_mode mode,
13593 symbol_name_match_type name_match_type,
13594 const char *text, const char *word,
13595 enum type_code code) const override
13597 const struct block *b, *surrounding_static_block = 0;
13599 gdb_assert (code == TYPE_CODE_UNDEF);
13601 lookup_name_info lookup_name (text, name_match_type, true);
13603 /* First, look at the partial symtab symbols. */
13604 expand_symtabs_matching (NULL,
13605 lookup_name,
13606 NULL,
13607 NULL,
13608 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13609 SEARCH_ALL_DOMAINS);
13611 /* At this point scan through the misc symbol vectors and add each
13612 symbol you find to the list. Eventually we want to ignore
13613 anything that isn't a text symbol (everything else will be
13614 handled by the psymtab code above). */
13616 for (objfile *objfile : current_program_space->objfiles ())
13618 for (minimal_symbol *msymbol : objfile->msymbols ())
13620 QUIT;
13622 if (completion_skip_symbol (mode, msymbol))
13623 continue;
13625 language symbol_language = msymbol->language ();
13627 /* Ada minimal symbols won't have their language set to Ada. If
13628 we let completion_list_add_name compare using the
13629 default/C-like matcher, then when completing e.g., symbols in a
13630 package named "pck", we'd match internal Ada symbols like
13631 "pckS", which are invalid in an Ada expression, unless you wrap
13632 them in '<' '>' to request a verbatim match.
13634 Unfortunately, some Ada encoded names successfully demangle as
13635 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13636 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13637 with the wrong language set. Paper over that issue here. */
13638 if (symbol_language == language_unknown
13639 || symbol_language == language_cplus)
13640 symbol_language = language_ada;
13642 completion_list_add_name (tracker,
13643 symbol_language,
13644 msymbol->linkage_name (),
13645 lookup_name, text, word);
13649 /* Search upwards from currently selected frame (so that we can
13650 complete on local vars. */
13652 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13654 if (!b->superblock ())
13655 surrounding_static_block = b; /* For elmin of dups */
13657 for (struct symbol *sym : block_iterator_range (b))
13659 if (completion_skip_symbol (mode, sym))
13660 continue;
13662 completion_list_add_name (tracker,
13663 sym->language (),
13664 sym->linkage_name (),
13665 lookup_name, text, word);
13669 /* Go through the symtabs and check the externs and statics for
13670 symbols which match. */
13672 for (objfile *objfile : current_program_space->objfiles ())
13674 for (compunit_symtab *s : objfile->compunits ())
13676 QUIT;
13677 b = s->blockvector ()->global_block ();
13678 for (struct symbol *sym : block_iterator_range (b))
13680 if (completion_skip_symbol (mode, sym))
13681 continue;
13683 completion_list_add_name (tracker,
13684 sym->language (),
13685 sym->linkage_name (),
13686 lookup_name, text, word);
13691 for (objfile *objfile : current_program_space->objfiles ())
13693 for (compunit_symtab *s : objfile->compunits ())
13695 QUIT;
13696 b = s->blockvector ()->static_block ();
13697 /* Don't do this block twice. */
13698 if (b == surrounding_static_block)
13699 continue;
13700 for (struct symbol *sym : block_iterator_range (b))
13702 if (completion_skip_symbol (mode, sym))
13703 continue;
13705 completion_list_add_name (tracker,
13706 sym->language (),
13707 sym->linkage_name (),
13708 lookup_name, text, word);
13714 /* See language.h. */
13716 gdb::unique_xmalloc_ptr<char> watch_location_expression
13717 (struct type *type, CORE_ADDR addr) const override
13719 type = check_typedef (check_typedef (type)->target_type ());
13720 std::string name = type_to_string (type);
13721 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13724 /* See language.h. */
13726 void value_print (struct value *val, struct ui_file *stream,
13727 const struct value_print_options *options) const override
13729 return ada_value_print (val, stream, options);
13732 /* See language.h. */
13734 void value_print_inner
13735 (struct value *val, struct ui_file *stream, int recurse,
13736 const struct value_print_options *options) const override
13738 return ada_value_print_inner (val, stream, recurse, options);
13741 /* See language.h. */
13743 struct block_symbol lookup_symbol_nonlocal
13744 (const char *name, const struct block *block,
13745 const domain_search_flags domain) const override
13747 struct block_symbol sym;
13749 sym = ada_lookup_symbol (name,
13750 (block == nullptr
13751 ? nullptr
13752 : block->static_block ()),
13753 domain);
13754 if (sym.symbol != NULL)
13755 return sym;
13757 /* If we haven't found a match at this point, try the primitive
13758 types. In other languages, this search is performed before
13759 searching for global symbols in order to short-circuit that
13760 global-symbol search if it happens that the name corresponds
13761 to a primitive type. But we cannot do the same in Ada, because
13762 it is perfectly legitimate for a program to declare a type which
13763 has the same name as a standard type. If looking up a type in
13764 that situation, we have traditionally ignored the primitive type
13765 in favor of user-defined types. This is why, unlike most other
13766 languages, we search the primitive types this late and only after
13767 having searched the global symbols without success. */
13769 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
13771 struct gdbarch *gdbarch;
13773 if (block == NULL)
13774 gdbarch = current_inferior ()->arch ();
13775 else
13776 gdbarch = block->gdbarch ();
13777 sym.symbol
13778 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13779 if (sym.symbol != NULL)
13780 return sym;
13783 return {};
13786 /* See language.h. */
13788 int parser (struct parser_state *ps) const override
13790 warnings_issued = 0;
13791 return ada_parse (ps);
13794 /* See language.h. */
13796 void emitchar (int ch, struct type *chtype,
13797 struct ui_file *stream, int quoter) const override
13799 ada_emit_char (ch, chtype, stream, quoter, 1);
13802 /* See language.h. */
13804 void printchar (int ch, struct type *chtype,
13805 struct ui_file *stream) const override
13807 ada_printchar (ch, chtype, stream);
13810 /* See language.h. */
13812 void printstr (struct ui_file *stream, struct type *elttype,
13813 const gdb_byte *string, unsigned int length,
13814 const char *encoding, int force_ellipses,
13815 const struct value_print_options *options) const override
13817 ada_printstr (stream, elttype, string, length, encoding,
13818 force_ellipses, options);
13821 /* See language.h. */
13823 void print_typedef (struct type *type, struct symbol *new_symbol,
13824 struct ui_file *stream) const override
13826 ada_print_typedef (type, new_symbol, stream);
13829 /* See language.h. */
13831 bool is_string_type_p (struct type *type) const override
13833 return ada_is_string_type (type);
13836 /* See language.h. */
13838 bool is_array_like (struct type *type) const override
13840 return (ada_is_constrained_packed_array_type (type)
13841 || ada_is_array_descriptor_type (type));
13844 /* See language.h. */
13846 struct value *to_array (struct value *val) const override
13847 { return ada_coerce_to_simple_array (val); }
13849 /* See language.h. */
13851 const char *struct_too_deep_ellipsis () const override
13852 { return "(...)"; }
13854 /* See language.h. */
13856 bool c_style_arrays_p () const override
13857 { return false; }
13859 /* See language.h. */
13861 bool store_sym_names_in_linkage_form_p () const override
13862 { return true; }
13864 /* See language.h. */
13866 const struct lang_varobj_ops *varobj_ops () const override
13867 { return &ada_varobj_ops; }
13869 protected:
13870 /* See language.h. */
13872 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13873 (const lookup_name_info &lookup_name) const override
13875 return ada_get_symbol_name_matcher (lookup_name);
13879 /* Single instance of the Ada language class. */
13881 static ada_language ada_language_defn;
13883 /* Command-list for the "set/show ada" prefix command. */
13884 static struct cmd_list_element *set_ada_list;
13885 static struct cmd_list_element *show_ada_list;
13887 /* This module's 'new_objfile' observer. */
13889 static void
13890 ada_new_objfile_observer (struct objfile *objfile)
13892 ada_clear_symbol_cache (objfile->pspace);
13895 /* This module's 'free_objfile' observer. */
13897 static void
13898 ada_free_objfile_observer (struct objfile *objfile)
13900 ada_clear_symbol_cache (objfile->pspace);
13903 /* Charsets known to GNAT. */
13904 static const char * const gnat_source_charsets[] =
13906 /* Note that code below assumes that the default comes first.
13907 Latin-1 is the default here, because that is also GNAT's
13908 default. */
13909 "ISO-8859-1",
13910 "ISO-8859-2",
13911 "ISO-8859-3",
13912 "ISO-8859-4",
13913 "ISO-8859-5",
13914 "ISO-8859-15",
13915 "CP437",
13916 "CP850",
13917 /* Note that this value is special-cased in the encoder and
13918 decoder. */
13919 ada_utf8,
13920 nullptr
13923 void _initialize_ada_language ();
13924 void
13925 _initialize_ada_language ()
13927 add_setshow_prefix_cmd
13928 ("ada", no_class,
13929 _("Prefix command for changing Ada-specific settings."),
13930 _("Generic command for showing Ada-specific settings."),
13931 &set_ada_list, &show_ada_list,
13932 &setlist, &showlist);
13934 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13935 &trust_pad_over_xvs, _("\
13936 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13937 Show whether an optimization trusting PAD types over XVS types is activated."),
13938 _("\
13939 This is related to the encoding used by the GNAT compiler. The debugger\n\
13940 should normally trust the contents of PAD types, but certain older versions\n\
13941 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13942 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13943 work around this bug. It is always safe to turn this option \"off\", but\n\
13944 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13945 this option to \"off\" unless necessary."),
13946 NULL, NULL, &set_ada_list, &show_ada_list);
13948 add_setshow_boolean_cmd ("print-signatures", class_vars,
13949 &print_signatures, _("\
13950 Enable or disable the output of formal and return types for functions in the \
13951 overloads selection menu."), _("\
13952 Show whether the output of formal and return types for functions in the \
13953 overloads selection menu is activated."),
13954 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13956 ada_source_charset = gnat_source_charsets[0];
13957 add_setshow_enum_cmd ("source-charset", class_files,
13958 gnat_source_charsets,
13959 &ada_source_charset, _("\
13960 Set the Ada source character set."), _("\
13961 Show the Ada source character set."), _("\
13962 The character set used for Ada source files.\n\
13963 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13964 nullptr, nullptr,
13965 &set_ada_list, &show_ada_list);
13967 add_catch_command ("exception", _("\
13968 Catch Ada exceptions, when raised.\n\
13969 Usage: catch exception [ARG] [if CONDITION]\n\
13970 Without any argument, stop when any Ada exception is raised.\n\
13971 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13972 being raised does not have a handler (and will therefore lead to the task's\n\
13973 termination).\n\
13974 Otherwise, the catchpoint only stops when the name of the exception being\n\
13975 raised is the same as ARG.\n\
13976 CONDITION is a boolean expression that is evaluated to see whether the\n\
13977 exception should cause a stop."),
13978 catch_ada_exception_command,
13979 catch_ada_completer,
13980 CATCH_PERMANENT,
13981 CATCH_TEMPORARY);
13983 add_catch_command ("handlers", _("\
13984 Catch Ada exceptions, when handled.\n\
13985 Usage: catch handlers [ARG] [if CONDITION]\n\
13986 Without any argument, stop when any Ada exception is handled.\n\
13987 With an argument, catch only exceptions with the given name.\n\
13988 CONDITION is a boolean expression that is evaluated to see whether the\n\
13989 exception should cause a stop."),
13990 catch_ada_handlers_command,
13991 catch_ada_completer,
13992 CATCH_PERMANENT,
13993 CATCH_TEMPORARY);
13994 add_catch_command ("assert", _("\
13995 Catch failed Ada assertions, when raised.\n\
13996 Usage: catch assert [if CONDITION]\n\
13997 CONDITION is a boolean expression that is evaluated to see whether the\n\
13998 exception should cause a stop."),
13999 catch_assert_command,
14000 NULL,
14001 CATCH_PERMANENT,
14002 CATCH_TEMPORARY);
14004 add_info ("exceptions", info_exceptions_command,
14005 _("\
14006 List all Ada exception names.\n\
14007 Usage: info exceptions [REGEXP]\n\
14008 If a regular expression is passed as an argument, only those matching\n\
14009 the regular expression are listed."));
14011 add_setshow_prefix_cmd ("ada", class_maintenance,
14012 _("Set Ada maintenance-related variables."),
14013 _("Show Ada maintenance-related variables."),
14014 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14015 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14017 add_setshow_boolean_cmd
14018 ("ignore-descriptive-types", class_maintenance,
14019 &ada_ignore_descriptive_types_p,
14020 _("Set whether descriptive types generated by GNAT should be ignored."),
14021 _("Show whether descriptive types generated by GNAT should be ignored."),
14022 _("\
14023 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14024 DWARF attribute."),
14025 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14027 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14028 htab_eq_string,
14029 NULL, xcalloc, xfree);
14031 /* The ada-lang observers. */
14032 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14033 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14034 "ada-lang");
14035 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14036 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14038 #ifdef GDB_SELF_TEST
14039 selftests::register_test ("ada-decode", ada_decode_tests);
14040 #endif