1 /* Ada language support routines for GDB, the GNU debugger.
3 Copyright (C) 1992-2022 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/>. */
23 #include "gdbsupport/gdb_regex.h"
28 #include "expression.h"
29 #include "parser-defs.h"
35 #include "breakpoint.h"
38 #include "gdbsupport/gdb_obstack.h"
40 #include "completer.h"
47 #include "observable.h"
49 #include "typeprint.h"
50 #include "namespace.h"
51 #include "cli/cli-style.h"
52 #include "cli/cli-decode.h"
55 #include "mi/mi-common.h"
56 #include "arch-utils.h"
57 #include "cli/cli-utils.h"
58 #include "gdbsupport/function-view.h"
59 #include "gdbsupport/byte-vector.h"
64 /* Define whether or not the C operator '/' truncates towards zero for
65 differently signed operands (truncation direction is undefined in C).
66 Copied from valarith.c. */
68 #ifndef TRUNCATION_TOWARDS_ZERO
69 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
72 static struct type *desc_base_type (struct type *);
74 static struct type *desc_bounds_type (struct type *);
76 static struct value *desc_bounds (struct value *);
78 static int fat_pntr_bounds_bitpos (struct type *);
80 static int fat_pntr_bounds_bitsize (struct type *);
82 static struct type *desc_data_target_type (struct type *);
84 static struct value *desc_data (struct value *);
86 static int fat_pntr_data_bitpos (struct type *);
88 static int fat_pntr_data_bitsize (struct type *);
90 static struct value *desc_one_bound (struct value *, int, int);
92 static int desc_bound_bitpos (struct type *, int, int);
94 static int desc_bound_bitsize (struct type *, int, int);
96 static struct type *desc_index_type (struct type *, int);
98 static int desc_arity (struct type *);
100 static int ada_args_match (struct symbol *, struct value **, int);
102 static struct value *make_array_descriptor (struct type *, struct value *);
104 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
106 const lookup_name_info &lookup_name,
107 domain_enum, struct objfile *);
109 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
110 const struct block *,
111 const lookup_name_info &lookup_name,
112 domain_enum, int, int *);
114 static int is_nonfunction (const std::vector<struct block_symbol> &);
116 static void add_defn_to_vec (std::vector<struct block_symbol> &,
118 const struct block *);
120 static int possible_user_operator_p (enum exp_opcode, struct value **);
122 static const char *ada_decoded_op_name (enum exp_opcode);
124 static int numeric_type_p (struct type *);
126 static int integer_type_p (struct type *);
128 static int scalar_type_p (struct type *);
130 static int discrete_type_p (struct type *);
132 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
135 static struct type *ada_find_parallel_type_with_name (struct type *,
138 static int is_dynamic_field (struct type *, int);
140 static struct type *to_fixed_variant_branch_type (struct type *,
142 CORE_ADDR, struct value *);
144 static struct type *to_fixed_array_type (struct type *, struct value *, int);
146 static struct type *to_fixed_range_type (struct type *, struct value *);
148 static struct type *to_static_fixed_type (struct type *);
149 static struct type *static_unwrap_type (struct type *type);
151 static struct value *unwrap_value (struct value *);
153 static struct type *constrained_packed_array_type (struct type *, long *);
155 static struct type *decode_constrained_packed_array_type (struct type *);
157 static long decode_packed_array_bitsize (struct type *);
159 static struct value *decode_constrained_packed_array (struct value *);
161 static int ada_is_unconstrained_packed_array_type (struct type *);
163 static struct value *value_subscript_packed (struct value *, int,
166 static struct value *coerce_unspec_val_to_type (struct value *,
169 static int lesseq_defined_than (struct symbol *, struct symbol *);
171 static int equiv_types (struct type *, struct type *);
173 static int is_name_suffix (const char *);
175 static int advance_wild_match (const char **, const char *, char);
177 static bool wild_match (const char *name, const char *patn);
179 static struct value *ada_coerce_ref (struct value *);
181 static LONGEST pos_atr (struct value *);
183 static struct value *val_atr (struct type *, LONGEST);
185 static struct symbol *standard_lookup (const char *, const struct block *,
188 static struct value *ada_search_struct_field (const char *, struct value *, int,
191 static int find_struct_field (const char *, struct type *, int,
192 struct type **, int *, int *, int *, int *);
194 static int ada_resolve_function (std::vector<struct block_symbol> &,
195 struct value **, int, const char *,
196 struct type *, bool);
198 static int ada_is_direct_array_type (struct type *);
200 static struct value *ada_index_struct_field (int, struct value *, int,
203 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
206 static struct type *ada_find_any_type (const char *name);
208 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
209 (const lookup_name_info &lookup_name);
213 /* The character set used for source files. */
214 static const char *ada_source_charset;
216 /* The string "UTF-8". This is here so we can check for the UTF-8
217 charset using == rather than strcmp. */
218 static const char ada_utf8[] = "UTF-8";
220 /* Each entry in the UTF-32 case-folding table is of this form. */
223 /* The start and end, inclusive, of this range of codepoints. */
225 /* The delta to apply to get the upper-case form. 0 if this is
226 already upper-case. */
228 /* The delta to apply to get the lower-case form. 0 if this is
229 already lower-case. */
232 bool operator< (uint32_t val) const
238 static const utf8_entry ada_case_fold[] =
240 #include "ada-casefold.h"
245 /* The result of a symbol lookup to be stored in our symbol cache. */
249 /* The name used to perform the lookup. */
251 /* The namespace used during the lookup. */
253 /* The symbol returned by the lookup, or NULL if no matching symbol
256 /* The block where the symbol was found, or NULL if no matching
258 const struct block *block;
259 /* A pointer to the next entry with the same hash. */
260 struct cache_entry *next;
263 /* The Ada symbol cache, used to store the result of Ada-mode symbol
264 lookups in the course of executing the user's commands.
266 The cache is implemented using a simple, fixed-sized hash.
267 The size is fixed on the grounds that there are not likely to be
268 all that many symbols looked up during any given session, regardless
269 of the size of the symbol table. If we decide to go to a resizable
270 table, let's just use the stuff from libiberty instead. */
272 #define HASH_SIZE 1009
274 struct ada_symbol_cache
276 /* An obstack used to store the entries in our cache. */
277 struct auto_obstack cache_space;
279 /* The root of the hash table used to implement our symbol cache. */
280 struct cache_entry *root[HASH_SIZE] {};
283 static const char ada_completer_word_break_characters[] =
285 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
287 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
290 /* The name of the symbol to use to get the name of the main subprogram. */
291 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
292 = "__gnat_ada_main_program_name";
294 /* Limit on the number of warnings to raise per expression evaluation. */
295 static int warning_limit = 2;
297 /* Number of warning messages issued; reset to 0 by cleanups after
298 expression evaluation. */
299 static int warnings_issued = 0;
301 static const char * const known_runtime_file_name_patterns[] = {
302 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
305 static const char * const known_auxiliary_function_name_patterns[] = {
306 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
309 /* Maintenance-related settings for this module. */
311 static struct cmd_list_element *maint_set_ada_cmdlist;
312 static struct cmd_list_element *maint_show_ada_cmdlist;
314 /* The "maintenance ada set/show ignore-descriptive-type" value. */
316 static bool ada_ignore_descriptive_types_p = false;
318 /* Inferior-specific data. */
320 /* Per-inferior data for this module. */
322 struct ada_inferior_data
324 /* The ada__tags__type_specific_data type, which is used when decoding
325 tagged types. With older versions of GNAT, this type was directly
326 accessible through a component ("tsd") in the object tag. But this
327 is no longer the case, so we cache it for each inferior. */
328 struct type *tsd_type = nullptr;
330 /* The exception_support_info data. This data is used to determine
331 how to implement support for Ada exception catchpoints in a given
333 const struct exception_support_info *exception_info = nullptr;
336 /* Our key to this module's inferior data. */
337 static const struct inferior_key<ada_inferior_data> ada_inferior_data;
339 /* Return our inferior data for the given inferior (INF).
341 This function always returns a valid pointer to an allocated
342 ada_inferior_data structure. If INF's inferior data has not
343 been previously set, this functions creates a new one with all
344 fields set to zero, sets INF's inferior to it, and then returns
345 a pointer to that newly allocated ada_inferior_data. */
347 static struct ada_inferior_data *
348 get_ada_inferior_data (struct inferior *inf)
350 struct ada_inferior_data *data;
352 data = ada_inferior_data.get (inf);
354 data = ada_inferior_data.emplace (inf);
359 /* Perform all necessary cleanups regarding our module's inferior data
360 that is required after the inferior INF just exited. */
363 ada_inferior_exit (struct inferior *inf)
365 ada_inferior_data.clear (inf);
369 /* program-space-specific data. */
371 /* This module's per-program-space data. */
372 struct ada_pspace_data
374 /* The Ada symbol cache. */
375 std::unique_ptr<ada_symbol_cache> sym_cache;
378 /* Key to our per-program-space data. */
379 static const struct program_space_key<ada_pspace_data> ada_pspace_data_handle;
381 /* Return this module's data for the given program space (PSPACE).
382 If not is found, add a zero'ed one now.
384 This function always returns a valid object. */
386 static struct ada_pspace_data *
387 get_ada_pspace_data (struct program_space *pspace)
389 struct ada_pspace_data *data;
391 data = ada_pspace_data_handle.get (pspace);
393 data = ada_pspace_data_handle.emplace (pspace);
400 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
401 all typedef layers have been peeled. Otherwise, return TYPE.
403 Normally, we really expect a typedef type to only have 1 typedef layer.
404 In other words, we really expect the target type of a typedef type to be
405 a non-typedef type. This is particularly true for Ada units, because
406 the language does not have a typedef vs not-typedef distinction.
407 In that respect, the Ada compiler has been trying to eliminate as many
408 typedef definitions in the debugging information, since they generally
409 do not bring any extra information (we still use typedef under certain
410 circumstances related mostly to the GNAT encoding).
412 Unfortunately, we have seen situations where the debugging information
413 generated by the compiler leads to such multiple typedef layers. For
414 instance, consider the following example with stabs:
416 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
417 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
419 This is an error in the debugging information which causes type
420 pck__float_array___XUP to be defined twice, and the second time,
421 it is defined as a typedef of a typedef.
423 This is on the fringe of legality as far as debugging information is
424 concerned, and certainly unexpected. But it is easy to handle these
425 situations correctly, so we can afford to be lenient in this case. */
428 ada_typedef_target_type (struct type *type)
430 while (type->code () == TYPE_CODE_TYPEDEF)
431 type = TYPE_TARGET_TYPE (type);
435 /* Given DECODED_NAME a string holding a symbol name in its
436 decoded form (ie using the Ada dotted notation), returns
437 its unqualified name. */
440 ada_unqualified_name (const char *decoded_name)
444 /* If the decoded name starts with '<', it means that the encoded
445 name does not follow standard naming conventions, and thus that
446 it is not your typical Ada symbol name. Trying to unqualify it
447 is therefore pointless and possibly erroneous. */
448 if (decoded_name[0] == '<')
451 result = strrchr (decoded_name, '.');
453 result++; /* Skip the dot... */
455 result = decoded_name;
460 /* Return a string starting with '<', followed by STR, and '>'. */
463 add_angle_brackets (const char *str)
465 return string_printf ("<%s>", str);
468 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
469 suffix of FIELD_NAME beginning "___". */
472 field_name_match (const char *field_name, const char *target)
474 int len = strlen (target);
477 (strncmp (field_name, target, len) == 0
478 && (field_name[len] == '\0'
479 || (startswith (field_name + len, "___")
480 && strcmp (field_name + strlen (field_name) - 6,
485 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
486 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
487 and return its index. This function also handles fields whose name
488 have ___ suffixes because the compiler sometimes alters their name
489 by adding such a suffix to represent fields with certain constraints.
490 If the field could not be found, return a negative number if
491 MAYBE_MISSING is set. Otherwise raise an error. */
494 ada_get_field_index (const struct type *type, const char *field_name,
498 struct type *struct_type = check_typedef ((struct type *) type);
500 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
501 if (field_name_match (struct_type->field (fieldno).name (), field_name))
505 error (_("Unable to find field %s in struct %s. Aborting"),
506 field_name, struct_type->name ());
511 /* The length of the prefix of NAME prior to any "___" suffix. */
514 ada_name_prefix_len (const char *name)
520 const char *p = strstr (name, "___");
523 return strlen (name);
529 /* Return non-zero if SUFFIX is a suffix of STR.
530 Return zero if STR is null. */
533 is_suffix (const char *str, const char *suffix)
540 len2 = strlen (suffix);
541 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
544 /* The contents of value VAL, treated as a value of type TYPE. The
545 result is an lval in memory if VAL is. */
547 static struct value *
548 coerce_unspec_val_to_type (struct value *val, struct type *type)
550 type = ada_check_typedef (type);
551 if (value_type (val) == type)
555 struct value *result;
557 if (value_optimized_out (val))
558 result = allocate_optimized_out_value (type);
559 else if (value_lazy (val)
560 /* Be careful not to make a lazy not_lval value. */
561 || (VALUE_LVAL (val) != not_lval
562 && TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val))))
563 result = allocate_value_lazy (type);
566 result = allocate_value (type);
567 value_contents_copy (result, 0, val, 0, TYPE_LENGTH (type));
569 set_value_component_location (result, val);
570 set_value_bitsize (result, value_bitsize (val));
571 set_value_bitpos (result, value_bitpos (val));
572 if (VALUE_LVAL (result) == lval_memory)
573 set_value_address (result, value_address (val));
578 static const gdb_byte *
579 cond_offset_host (const gdb_byte *valaddr, long offset)
584 return valaddr + offset;
588 cond_offset_target (CORE_ADDR address, long offset)
593 return address + offset;
596 /* Issue a warning (as for the definition of warning in utils.c, but
597 with exactly one argument rather than ...), unless the limit on the
598 number of warnings has passed during the evaluation of the current
601 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
602 provided by "complaint". */
603 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
606 lim_warning (const char *format, ...)
610 va_start (args, format);
611 warnings_issued += 1;
612 if (warnings_issued <= warning_limit)
613 vwarning (format, args);
618 /* Maximum value of a SIZE-byte signed integer type. */
620 max_of_size (int size)
622 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
624 return top_bit | (top_bit - 1);
627 /* Minimum value of a SIZE-byte signed integer type. */
629 min_of_size (int size)
631 return -max_of_size (size) - 1;
634 /* Maximum value of a SIZE-byte unsigned integer type. */
636 umax_of_size (int size)
638 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
640 return top_bit | (top_bit - 1);
643 /* Maximum value of integral type T, as a signed quantity. */
645 max_of_type (struct type *t)
647 if (t->is_unsigned ())
648 return (LONGEST) umax_of_size (TYPE_LENGTH (t));
650 return max_of_size (TYPE_LENGTH (t));
653 /* Minimum value of integral type T, as a signed quantity. */
655 min_of_type (struct type *t)
657 if (t->is_unsigned ())
660 return min_of_size (TYPE_LENGTH (t));
663 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
665 ada_discrete_type_high_bound (struct type *type)
667 type = resolve_dynamic_type (type, {}, 0);
668 switch (type->code ())
670 case TYPE_CODE_RANGE:
672 const dynamic_prop &high = type->bounds ()->high;
674 if (high.kind () == PROP_CONST)
675 return high.const_val ();
678 gdb_assert (high.kind () == PROP_UNDEFINED);
680 /* This happens when trying to evaluate a type's dynamic bound
681 without a live target. There is nothing relevant for us to
682 return here, so return 0. */
687 return type->field (type->num_fields () - 1).loc_enumval ();
692 return max_of_type (type);
694 error (_("Unexpected type in ada_discrete_type_high_bound."));
698 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
700 ada_discrete_type_low_bound (struct type *type)
702 type = resolve_dynamic_type (type, {}, 0);
703 switch (type->code ())
705 case TYPE_CODE_RANGE:
707 const dynamic_prop &low = type->bounds ()->low;
709 if (low.kind () == PROP_CONST)
710 return low.const_val ();
713 gdb_assert (low.kind () == PROP_UNDEFINED);
715 /* This happens when trying to evaluate a type's dynamic bound
716 without a live target. There is nothing relevant for us to
717 return here, so return 0. */
722 return type->field (0).loc_enumval ();
727 return min_of_type (type);
729 error (_("Unexpected type in ada_discrete_type_low_bound."));
733 /* The identity on non-range types. For range types, the underlying
734 non-range scalar type. */
737 get_base_type (struct type *type)
739 while (type != NULL && type->code () == TYPE_CODE_RANGE)
741 if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
743 type = TYPE_TARGET_TYPE (type);
748 /* Return a decoded version of the given VALUE. This means returning
749 a value whose type is obtained by applying all the GNAT-specific
750 encodings, making the resulting type a static but standard description
751 of the initial type. */
754 ada_get_decoded_value (struct value *value)
756 struct type *type = ada_check_typedef (value_type (value));
758 if (ada_is_array_descriptor_type (type)
759 || (ada_is_constrained_packed_array_type (type)
760 && type->code () != TYPE_CODE_PTR))
762 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
763 value = ada_coerce_to_simple_array_ptr (value);
765 value = ada_coerce_to_simple_array (value);
768 value = ada_to_fixed_value (value);
773 /* Same as ada_get_decoded_value, but with the given TYPE.
774 Because there is no associated actual value for this type,
775 the resulting type might be a best-effort approximation in
776 the case of dynamic types. */
779 ada_get_decoded_type (struct type *type)
781 type = to_static_fixed_type (type);
782 if (ada_is_constrained_packed_array_type (type))
783 type = ada_coerce_to_simple_array_type (type);
789 /* Language Selection */
791 /* If the main program is in Ada, return language_ada, otherwise return LANG
792 (the main program is in Ada iif the adainit symbol is found). */
795 ada_update_initial_language (enum language lang)
797 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
803 /* If the main procedure is written in Ada, then return its name.
804 The result is good until the next call. Return NULL if the main
805 procedure doesn't appear to be in Ada. */
810 struct bound_minimal_symbol msym;
811 static gdb::unique_xmalloc_ptr<char> main_program_name;
813 /* For Ada, the name of the main procedure is stored in a specific
814 string constant, generated by the binder. Look for that symbol,
815 extract its address, and then read that string. If we didn't find
816 that string, then most probably the main procedure is not written
818 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
820 if (msym.minsym != NULL)
822 CORE_ADDR main_program_name_addr = msym.value_address ();
823 if (main_program_name_addr == 0)
824 error (_("Invalid address for Ada main program name."));
826 main_program_name = target_read_string (main_program_name_addr, 1024);
827 return main_program_name.get ();
830 /* The main procedure doesn't seem to be in Ada. */
836 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
839 const struct ada_opname_map ada_opname_table[] = {
840 {"Oadd", "\"+\"", BINOP_ADD},
841 {"Osubtract", "\"-\"", BINOP_SUB},
842 {"Omultiply", "\"*\"", BINOP_MUL},
843 {"Odivide", "\"/\"", BINOP_DIV},
844 {"Omod", "\"mod\"", BINOP_MOD},
845 {"Orem", "\"rem\"", BINOP_REM},
846 {"Oexpon", "\"**\"", BINOP_EXP},
847 {"Olt", "\"<\"", BINOP_LESS},
848 {"Ole", "\"<=\"", BINOP_LEQ},
849 {"Ogt", "\">\"", BINOP_GTR},
850 {"Oge", "\">=\"", BINOP_GEQ},
851 {"Oeq", "\"=\"", BINOP_EQUAL},
852 {"One", "\"/=\"", BINOP_NOTEQUAL},
853 {"Oand", "\"and\"", BINOP_BITWISE_AND},
854 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
855 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
856 {"Oconcat", "\"&\"", BINOP_CONCAT},
857 {"Oabs", "\"abs\"", UNOP_ABS},
858 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
859 {"Oadd", "\"+\"", UNOP_PLUS},
860 {"Osubtract", "\"-\"", UNOP_NEG},
864 /* If STR is a decoded version of a compiler-provided suffix (like the
865 "[cold]" in "symbol[cold]"), return true. Otherwise, return
869 is_compiler_suffix (const char *str)
871 gdb_assert (*str == '[');
873 while (*str != '\0' && isalpha (*str))
875 /* We accept a missing "]" in order to support completion. */
876 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
879 /* Append a non-ASCII character to RESULT. */
881 append_hex_encoded (std::string &result, uint32_t one_char)
883 if (one_char <= 0xff)
886 result.append (phex (one_char, 1));
888 else if (one_char <= 0xffff)
891 result.append (phex (one_char, 2));
895 result.append ("WW");
896 result.append (phex (one_char, 4));
900 /* Return a string that is a copy of the data in STORAGE, with
901 non-ASCII characters replaced by the appropriate hex encoding. A
902 template is used because, for UTF-8, we actually want to work with
903 UTF-32 codepoints. */
906 copy_and_hex_encode (struct obstack *storage)
908 const T *chars = (T *) obstack_base (storage);
909 int num_chars = obstack_object_size (storage) / sizeof (T);
911 for (int i = 0; i < num_chars; ++i)
913 if (chars[i] <= 0x7f)
915 /* The host character set has to be a superset of ASCII, as
916 are all the other character sets we can use. */
917 result.push_back (chars[i]);
920 append_hex_encoded (result, chars[i]);
925 /* The "encoded" form of DECODED, according to GNAT conventions. If
926 THROW_ERRORS, throw an error if invalid operator name is found.
927 Otherwise, return the empty string in that case. */
930 ada_encode_1 (const char *decoded, bool throw_errors)
935 std::string encoding_buffer;
936 bool saw_non_ascii = false;
937 for (const char *p = decoded; *p != '\0'; p += 1)
939 if ((*p & 0x80) != 0)
940 saw_non_ascii = true;
943 encoding_buffer.append ("__");
944 else if (*p == '[' && is_compiler_suffix (p))
946 encoding_buffer = encoding_buffer + "." + (p + 1);
947 if (encoding_buffer.back () == ']')
948 encoding_buffer.pop_back ();
953 const struct ada_opname_map *mapping;
955 for (mapping = ada_opname_table;
956 mapping->encoded != NULL
957 && !startswith (p, mapping->decoded); mapping += 1)
959 if (mapping->encoded == NULL)
962 error (_("invalid Ada operator name: %s"), p);
966 encoding_buffer.append (mapping->encoded);
970 encoding_buffer.push_back (*p);
973 /* If a non-ASCII character is seen, we must convert it to the
974 appropriate hex form. As this is more expensive, we keep track
975 of whether it is even necessary. */
978 auto_obstack storage;
979 bool is_utf8 = ada_source_charset == ada_utf8;
982 convert_between_encodings
984 is_utf8 ? HOST_UTF32 : ada_source_charset,
985 (const gdb_byte *) encoding_buffer.c_str (),
986 encoding_buffer.length (), 1,
987 &storage, translit_none);
989 catch (const gdb_exception &)
991 static bool warned = false;
993 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
994 might like to know why. */
998 warning (_("charset conversion failure for '%s'.\n"
999 "You may have the wrong value for 'set ada source-charset'."),
1000 encoding_buffer.c_str ());
1003 /* We don't try to recover from errors. */
1004 return encoding_buffer;
1008 return copy_and_hex_encode<uint32_t> (&storage);
1009 return copy_and_hex_encode<gdb_byte> (&storage);
1012 return encoding_buffer;
1015 /* Find the entry for C in the case-folding table. Return nullptr if
1016 the entry does not cover C. */
1017 static const utf8_entry *
1018 find_case_fold_entry (uint32_t c)
1020 auto iter = std::lower_bound (std::begin (ada_case_fold),
1021 std::end (ada_case_fold),
1023 if (iter == std::end (ada_case_fold)
1030 /* Return NAME folded to lower case, or, if surrounded by single
1031 quotes, unfolded, but with the quotes stripped away. If
1032 THROW_ON_ERROR is true, encoding failures will throw an exception
1033 rather than emitting a warning. Result good to next call. */
1036 ada_fold_name (gdb::string_view name, bool throw_on_error = false)
1038 static std::string fold_storage;
1040 if (!name.empty () && name[0] == '\'')
1041 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
1044 /* Why convert to UTF-32 and implement our own case-folding,
1045 rather than convert to wchar_t and use the platform's
1046 functions? I'm glad you asked.
1048 The main problem is that GNAT implements an unusual rule for
1049 case folding. For ASCII letters, letters in single-byte
1050 encodings (such as ISO-8859-*), and Unicode letters that fit
1051 in a single byte (i.e., code point is <= 0xff), the letter is
1052 folded to lower case. Other Unicode letters are folded to
1055 This rule means that the code must be able to examine the
1056 value of the character. And, some hosts do not use Unicode
1057 for wchar_t, so examining the value of such characters is
1059 auto_obstack storage;
1062 convert_between_encodings
1063 (host_charset (), HOST_UTF32,
1064 (const gdb_byte *) name.data (),
1066 &storage, translit_none);
1068 catch (const gdb_exception &)
1073 static bool warned = false;
1075 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1076 might like to know why. */
1080 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1081 "This normally should not happen, please file a bug report."),
1082 gdb::to_string (name).c_str (), host_charset ());
1085 /* We don't try to recover from errors; just return the
1087 fold_storage = gdb::to_string (name);
1088 return fold_storage.c_str ();
1091 bool is_utf8 = ada_source_charset == ada_utf8;
1092 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1093 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1094 for (int i = 0; i < num_chars; ++i)
1096 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1097 if (entry != nullptr)
1099 uint32_t low = chars[i] + entry->lower_delta;
1100 if (!is_utf8 || low <= 0xff)
1103 chars[i] = chars[i] + entry->upper_delta;
1107 /* Now convert back to ordinary characters. */
1108 auto_obstack reconverted;
1111 convert_between_encodings (HOST_UTF32,
1113 (const gdb_byte *) chars,
1114 num_chars * sizeof (uint32_t),
1118 obstack_1grow (&reconverted, '\0');
1119 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1121 catch (const gdb_exception &)
1126 static bool warned = false;
1128 /* Converting back from UTF-32 shouldn't normally fail, but
1129 there are some host encodings without upper/lower
1134 warning (_("could not convert the lower-cased variant of '%s'\n"
1135 "from UTF-32 to the host encoding (%s)."),
1136 gdb::to_string (name).c_str (), host_charset ());
1139 /* We don't try to recover from errors; just return the
1141 fold_storage = gdb::to_string (name);
1145 return fold_storage.c_str ();
1148 /* The "encoded" form of DECODED, according to GNAT conventions. */
1151 ada_encode (const char *decoded)
1153 if (decoded[0] != '<')
1154 decoded = ada_fold_name (decoded);
1155 return ada_encode_1 (decoded, true);
1158 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1161 is_lower_alphanum (const char c)
1163 return (isdigit (c) || (isalpha (c) && islower (c)));
1166 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1167 This function saves in LEN the length of that same symbol name but
1168 without either of these suffixes:
1174 These are suffixes introduced by the compiler for entities such as
1175 nested subprogram for instance, in order to avoid name clashes.
1176 They do not serve any purpose for the debugger. */
1179 ada_remove_trailing_digits (const char *encoded, int *len)
1181 if (*len > 1 && isdigit (encoded[*len - 1]))
1185 while (i > 0 && isdigit (encoded[i]))
1187 if (i >= 0 && encoded[i] == '.')
1189 else if (i >= 0 && encoded[i] == '$')
1191 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1193 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1198 /* Remove the suffix introduced by the compiler for protected object
1202 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1204 /* Remove trailing N. */
1206 /* Protected entry subprograms are broken into two
1207 separate subprograms: The first one is unprotected, and has
1208 a 'N' suffix; the second is the protected version, and has
1209 the 'P' suffix. The second calls the first one after handling
1210 the protection. Since the P subprograms are internally generated,
1211 we leave these names undecoded, giving the user a clue that this
1212 entity is internal. */
1215 && encoded[*len - 1] == 'N'
1216 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1220 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1221 then update *LEN to remove the suffix and return the offset of the
1222 character just past the ".". Otherwise, return -1. */
1225 remove_compiler_suffix (const char *encoded, int *len)
1227 int offset = *len - 1;
1228 while (offset > 0 && isalpha (encoded[offset]))
1230 if (offset > 0 && encoded[offset] == '.')
1238 /* Convert an ASCII hex string to a number. Reads exactly N
1239 characters from STR. Returns true on success, false if one of the
1240 digits was not a hex digit. */
1242 convert_hex (const char *str, int n, uint32_t *out)
1244 uint32_t result = 0;
1246 for (int i = 0; i < n; ++i)
1248 if (!isxdigit (str[i]))
1251 result |= fromhex (str[i]);
1258 /* Convert a wide character from its ASCII hex representation in STR
1259 (consisting of exactly N characters) to the host encoding,
1260 appending the resulting bytes to OUT. If N==2 and the Ada source
1261 charset is not UTF-8, then hex refers to an encoding in the
1262 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1263 Return false and do not modify OUT on conversion failure. */
1265 convert_from_hex_encoded (std::string &out, const char *str, int n)
1269 if (!convert_hex (str, n, &value))
1274 /* In the 'U' case, the hex digits encode the character in the
1275 Ada source charset. However, if the source charset is UTF-8,
1276 this really means it is a single-byte UTF-32 character. */
1277 if (n == 2 && ada_source_charset != ada_utf8)
1279 gdb_byte one_char = (gdb_byte) value;
1281 convert_between_encodings (ada_source_charset, host_charset (),
1283 sizeof (one_char), sizeof (one_char),
1284 &bytes, translit_none);
1287 convert_between_encodings (HOST_UTF32, host_charset (),
1288 (const gdb_byte *) &value,
1289 sizeof (value), sizeof (value),
1290 &bytes, translit_none);
1291 obstack_1grow (&bytes, '\0');
1292 out.append ((const char *) obstack_base (&bytes));
1294 catch (const gdb_exception &)
1296 /* On failure, the caller will just let the encoded form
1297 through, which seems basically reasonable. */
1304 /* See ada-lang.h. */
1307 ada_decode (const char *encoded, bool wrap, bool operators)
1313 std::string decoded;
1316 /* With function descriptors on PPC64, the value of a symbol named
1317 ".FN", if it exists, is the entry point of the function "FN". */
1318 if (encoded[0] == '.')
1321 /* The name of the Ada main procedure starts with "_ada_".
1322 This prefix is not part of the decoded name, so skip this part
1323 if we see this prefix. */
1324 if (startswith (encoded, "_ada_"))
1326 /* The "___ghost_" prefix is used for ghost entities. Normally
1327 these aren't preserved but when they are, it's useful to see
1329 if (startswith (encoded, "___ghost_"))
1332 /* If the name starts with '_', then it is not a properly encoded
1333 name, so do not attempt to decode it. Similarly, if the name
1334 starts with '<', the name should not be decoded. */
1335 if (encoded[0] == '_' || encoded[0] == '<')
1338 len0 = strlen (encoded);
1340 suffix = remove_compiler_suffix (encoded, &len0);
1342 ada_remove_trailing_digits (encoded, &len0);
1343 ada_remove_po_subprogram_suffix (encoded, &len0);
1345 /* Remove the ___X.* suffix if present. Do not forget to verify that
1346 the suffix is located before the current "end" of ENCODED. We want
1347 to avoid re-matching parts of ENCODED that have previously been
1348 marked as discarded (by decrementing LEN0). */
1349 p = strstr (encoded, "___");
1350 if (p != NULL && p - encoded < len0 - 3)
1358 /* Remove any trailing TKB suffix. It tells us that this symbol
1359 is for the body of a task, but that information does not actually
1360 appear in the decoded name. */
1362 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1365 /* Remove any trailing TB suffix. The TB suffix is slightly different
1366 from the TKB suffix because it is used for non-anonymous task
1369 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1372 /* Remove trailing "B" suffixes. */
1373 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1375 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1378 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1380 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1383 while ((i >= 0 && isdigit (encoded[i]))
1384 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1386 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1388 else if (encoded[i] == '$')
1392 /* The first few characters that are not alphabetic are not part
1393 of any encoding we use, so we can copy them over verbatim. */
1395 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1396 decoded.push_back (encoded[i]);
1401 /* Is this a symbol function? */
1402 if (operators && at_start_name && encoded[i] == 'O')
1406 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1408 int op_len = strlen (ada_opname_table[k].encoded);
1409 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1411 && !isalnum (encoded[i + op_len]))
1413 decoded.append (ada_opname_table[k].decoded);
1419 if (ada_opname_table[k].encoded != NULL)
1424 /* Replace "TK__" with "__", which will eventually be translated
1425 into "." (just below). */
1427 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1430 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1431 be translated into "." (just below). These are internal names
1432 generated for anonymous blocks inside which our symbol is nested. */
1434 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1435 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1436 && isdigit (encoded [i+4]))
1440 while (k < len0 && isdigit (encoded[k]))
1441 k++; /* Skip any extra digit. */
1443 /* Double-check that the "__B_{DIGITS}+" sequence we found
1444 is indeed followed by "__". */
1445 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1449 /* Remove _E{DIGITS}+[sb] */
1451 /* Just as for protected object subprograms, there are 2 categories
1452 of subprograms created by the compiler for each entry. The first
1453 one implements the actual entry code, and has a suffix following
1454 the convention above; the second one implements the barrier and
1455 uses the same convention as above, except that the 'E' is replaced
1458 Just as above, we do not decode the name of barrier functions
1459 to give the user a clue that the code he is debugging has been
1460 internally generated. */
1462 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1463 && isdigit (encoded[i+2]))
1467 while (k < len0 && isdigit (encoded[k]))
1471 && (encoded[k] == 'b' || encoded[k] == 's'))
1474 /* Just as an extra precaution, make sure that if this
1475 suffix is followed by anything else, it is a '_'.
1476 Otherwise, we matched this sequence by accident. */
1478 || (k < len0 && encoded[k] == '_'))
1483 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1484 the GNAT front-end in protected object subprograms. */
1487 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1489 /* Backtrack a bit up until we reach either the begining of
1490 the encoded name, or "__". Make sure that we only find
1491 digits or lowercase characters. */
1492 const char *ptr = encoded + i - 1;
1494 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1497 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1501 if (i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1503 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1509 else if (i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1511 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1517 else if (i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1518 && isxdigit (encoded[i + 2]))
1520 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1527 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1529 /* This is a X[bn]* sequence not separated from the previous
1530 part of the name with a non-alpha-numeric character (in other
1531 words, immediately following an alpha-numeric character), then
1532 verify that it is placed at the end of the encoded name. If
1533 not, then the encoding is not valid and we should abort the
1534 decoding. Otherwise, just skip it, it is used in body-nested
1538 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1542 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1544 /* Replace '__' by '.'. */
1545 decoded.push_back ('.');
1551 /* It's a character part of the decoded name, so just copy it
1553 decoded.push_back (encoded[i]);
1558 /* Decoded names should never contain any uppercase character.
1559 Double-check this, and abort the decoding if we find one. */
1563 for (i = 0; i < decoded.length(); ++i)
1564 if (isupper (decoded[i]) || decoded[i] == ' ')
1568 /* If the compiler added a suffix, append it now. */
1570 decoded = decoded + "[" + &encoded[suffix] + "]";
1578 if (encoded[0] == '<')
1581 decoded = '<' + std::string(encoded) + '>';
1585 /* Table for keeping permanent unique copies of decoded names. Once
1586 allocated, names in this table are never released. While this is a
1587 storage leak, it should not be significant unless there are massive
1588 changes in the set of decoded names in successive versions of a
1589 symbol table loaded during a single session. */
1590 static struct htab *decoded_names_store;
1592 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1593 in the language-specific part of GSYMBOL, if it has not been
1594 previously computed. Tries to save the decoded name in the same
1595 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1596 in any case, the decoded symbol has a lifetime at least that of
1598 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1599 const, but nevertheless modified to a semantically equivalent form
1600 when a decoded name is cached in it. */
1603 ada_decode_symbol (const struct general_symbol_info *arg)
1605 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1606 const char **resultp =
1607 &gsymbol->language_specific.demangled_name;
1609 if (!gsymbol->ada_mangled)
1611 std::string decoded = ada_decode (gsymbol->linkage_name ());
1612 struct obstack *obstack = gsymbol->language_specific.obstack;
1614 gsymbol->ada_mangled = 1;
1616 if (obstack != NULL)
1617 *resultp = obstack_strdup (obstack, decoded.c_str ());
1620 /* Sometimes, we can't find a corresponding objfile, in
1621 which case, we put the result on the heap. Since we only
1622 decode when needed, we hope this usually does not cause a
1623 significant memory leak (FIXME). */
1625 char **slot = (char **) htab_find_slot (decoded_names_store,
1626 decoded.c_str (), INSERT);
1629 *slot = xstrdup (decoded.c_str ());
1641 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1642 generated by the GNAT compiler to describe the index type used
1643 for each dimension of an array, check whether it follows the latest
1644 known encoding. If not, fix it up to conform to the latest encoding.
1645 Otherwise, do nothing. This function also does nothing if
1646 INDEX_DESC_TYPE is NULL.
1648 The GNAT encoding used to describe the array index type evolved a bit.
1649 Initially, the information would be provided through the name of each
1650 field of the structure type only, while the type of these fields was
1651 described as unspecified and irrelevant. The debugger was then expected
1652 to perform a global type lookup using the name of that field in order
1653 to get access to the full index type description. Because these global
1654 lookups can be very expensive, the encoding was later enhanced to make
1655 the global lookup unnecessary by defining the field type as being
1656 the full index type description.
1658 The purpose of this routine is to allow us to support older versions
1659 of the compiler by detecting the use of the older encoding, and by
1660 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1661 we essentially replace each field's meaningless type by the associated
1665 ada_fixup_array_indexes_type (struct type *index_desc_type)
1669 if (index_desc_type == NULL)
1671 gdb_assert (index_desc_type->num_fields () > 0);
1673 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1674 to check one field only, no need to check them all). If not, return
1677 If our INDEX_DESC_TYPE was generated using the older encoding,
1678 the field type should be a meaningless integer type whose name
1679 is not equal to the field name. */
1680 if (index_desc_type->field (0).type ()->name () != NULL
1681 && strcmp (index_desc_type->field (0).type ()->name (),
1682 index_desc_type->field (0).name ()) == 0)
1685 /* Fixup each field of INDEX_DESC_TYPE. */
1686 for (i = 0; i < index_desc_type->num_fields (); i++)
1688 const char *name = index_desc_type->field (i).name ();
1689 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1692 index_desc_type->field (i).set_type (raw_type);
1696 /* The desc_* routines return primitive portions of array descriptors
1699 /* The descriptor or array type, if any, indicated by TYPE; removes
1700 level of indirection, if needed. */
1702 static struct type *
1703 desc_base_type (struct type *type)
1707 type = ada_check_typedef (type);
1708 if (type->code () == TYPE_CODE_TYPEDEF)
1709 type = ada_typedef_target_type (type);
1712 && (type->code () == TYPE_CODE_PTR
1713 || type->code () == TYPE_CODE_REF))
1714 return ada_check_typedef (TYPE_TARGET_TYPE (type));
1719 /* True iff TYPE indicates a "thin" array pointer type. */
1722 is_thin_pntr (struct type *type)
1725 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1726 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1729 /* The descriptor type for thin pointer type TYPE. */
1731 static struct type *
1732 thin_descriptor_type (struct type *type)
1734 struct type *base_type = desc_base_type (type);
1736 if (base_type == NULL)
1738 if (is_suffix (ada_type_name (base_type), "___XVE"))
1742 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1744 if (alt_type == NULL)
1751 /* A pointer to the array data for thin-pointer value VAL. */
1753 static struct value *
1754 thin_data_pntr (struct value *val)
1756 struct type *type = ada_check_typedef (value_type (val));
1757 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1759 data_type = lookup_pointer_type (data_type);
1761 if (type->code () == TYPE_CODE_PTR)
1762 return value_cast (data_type, value_copy (val));
1764 return value_from_longest (data_type, value_address (val));
1767 /* True iff TYPE indicates a "thick" array pointer type. */
1770 is_thick_pntr (struct type *type)
1772 type = desc_base_type (type);
1773 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1774 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1777 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1778 pointer to one, the type of its bounds data; otherwise, NULL. */
1780 static struct type *
1781 desc_bounds_type (struct type *type)
1785 type = desc_base_type (type);
1789 else if (is_thin_pntr (type))
1791 type = thin_descriptor_type (type);
1794 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1796 return ada_check_typedef (r);
1798 else if (type->code () == TYPE_CODE_STRUCT)
1800 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1802 return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1807 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1808 one, a pointer to its bounds data. Otherwise NULL. */
1810 static struct value *
1811 desc_bounds (struct value *arr)
1813 struct type *type = ada_check_typedef (value_type (arr));
1815 if (is_thin_pntr (type))
1817 struct type *bounds_type =
1818 desc_bounds_type (thin_descriptor_type (type));
1821 if (bounds_type == NULL)
1822 error (_("Bad GNAT array descriptor"));
1824 /* NOTE: The following calculation is not really kosher, but
1825 since desc_type is an XVE-encoded type (and shouldn't be),
1826 the correct calculation is a real pain. FIXME (and fix GCC). */
1827 if (type->code () == TYPE_CODE_PTR)
1828 addr = value_as_long (arr);
1830 addr = value_address (arr);
1833 value_from_longest (lookup_pointer_type (bounds_type),
1834 addr - TYPE_LENGTH (bounds_type));
1837 else if (is_thick_pntr (type))
1839 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1840 _("Bad GNAT array descriptor"));
1841 struct type *p_bounds_type = value_type (p_bounds);
1844 && p_bounds_type->code () == TYPE_CODE_PTR)
1846 struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1848 if (target_type->is_stub ())
1849 p_bounds = value_cast (lookup_pointer_type
1850 (ada_check_typedef (target_type)),
1854 error (_("Bad GNAT array descriptor"));
1862 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1863 position of the field containing the address of the bounds data. */
1866 fat_pntr_bounds_bitpos (struct type *type)
1868 return desc_base_type (type)->field (1).loc_bitpos ();
1871 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1872 size of the field containing the address of the bounds data. */
1875 fat_pntr_bounds_bitsize (struct type *type)
1877 type = desc_base_type (type);
1879 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1880 return TYPE_FIELD_BITSIZE (type, 1);
1882 return 8 * TYPE_LENGTH (ada_check_typedef (type->field (1).type ()));
1885 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1886 pointer to one, the type of its array data (a array-with-no-bounds type);
1887 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1890 static struct type *
1891 desc_data_target_type (struct type *type)
1893 type = desc_base_type (type);
1895 /* NOTE: The following is bogus; see comment in desc_bounds. */
1896 if (is_thin_pntr (type))
1897 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1898 else if (is_thick_pntr (type))
1900 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1903 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1904 return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1910 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1913 static struct value *
1914 desc_data (struct value *arr)
1916 struct type *type = value_type (arr);
1918 if (is_thin_pntr (type))
1919 return thin_data_pntr (arr);
1920 else if (is_thick_pntr (type))
1921 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1922 _("Bad GNAT array descriptor"));
1928 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1929 position of the field containing the address of the data. */
1932 fat_pntr_data_bitpos (struct type *type)
1934 return desc_base_type (type)->field (0).loc_bitpos ();
1937 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1938 size of the field containing the address of the data. */
1941 fat_pntr_data_bitsize (struct type *type)
1943 type = desc_base_type (type);
1945 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1946 return TYPE_FIELD_BITSIZE (type, 0);
1948 return TARGET_CHAR_BIT * TYPE_LENGTH (type->field (0).type ());
1951 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1952 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1953 bound, if WHICH is 1. The first bound is I=1. */
1955 static struct value *
1956 desc_one_bound (struct value *bounds, int i, int which)
1958 char bound_name[20];
1959 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1960 which ? 'U' : 'L', i - 1);
1961 return value_struct_elt (&bounds, {}, bound_name, NULL,
1962 _("Bad GNAT array descriptor bounds"));
1965 /* If BOUNDS is an array-bounds structure type, return the bit position
1966 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1967 bound, if WHICH is 1. The first bound is I=1. */
1970 desc_bound_bitpos (struct type *type, int i, int which)
1972 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1975 /* If BOUNDS is an array-bounds structure type, return the bit field size
1976 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1977 bound, if WHICH is 1. The first bound is I=1. */
1980 desc_bound_bitsize (struct type *type, int i, int which)
1982 type = desc_base_type (type);
1984 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1985 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1987 return 8 * TYPE_LENGTH (type->field (2 * i + which - 2).type ());
1990 /* If TYPE is the type of an array-bounds structure, the type of its
1991 Ith bound (numbering from 1). Otherwise, NULL. */
1993 static struct type *
1994 desc_index_type (struct type *type, int i)
1996 type = desc_base_type (type);
1998 if (type->code () == TYPE_CODE_STRUCT)
2000 char bound_name[20];
2001 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2002 return lookup_struct_elt_type (type, bound_name, 1);
2008 /* The number of index positions in the array-bounds type TYPE.
2009 Return 0 if TYPE is NULL. */
2012 desc_arity (struct type *type)
2014 type = desc_base_type (type);
2017 return type->num_fields () / 2;
2021 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2022 an array descriptor type (representing an unconstrained array
2026 ada_is_direct_array_type (struct type *type)
2030 type = ada_check_typedef (type);
2031 return (type->code () == TYPE_CODE_ARRAY
2032 || ada_is_array_descriptor_type (type));
2035 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2039 ada_is_array_type (struct type *type)
2042 && (type->code () == TYPE_CODE_PTR
2043 || type->code () == TYPE_CODE_REF))
2044 type = TYPE_TARGET_TYPE (type);
2045 return ada_is_direct_array_type (type);
2048 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2051 ada_is_simple_array_type (struct type *type)
2055 type = ada_check_typedef (type);
2056 return (type->code () == TYPE_CODE_ARRAY
2057 || (type->code () == TYPE_CODE_PTR
2058 && (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ()
2059 == TYPE_CODE_ARRAY)));
2062 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2065 ada_is_array_descriptor_type (struct type *type)
2067 struct type *data_type = desc_data_target_type (type);
2071 type = ada_check_typedef (type);
2072 return (data_type != NULL
2073 && data_type->code () == TYPE_CODE_ARRAY
2074 && desc_arity (desc_bounds_type (type)) > 0);
2077 /* Non-zero iff type is a partially mal-formed GNAT array
2078 descriptor. FIXME: This is to compensate for some problems with
2079 debugging output from GNAT. Re-examine periodically to see if it
2083 ada_is_bogus_array_descriptor (struct type *type)
2087 && type->code () == TYPE_CODE_STRUCT
2088 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
2089 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
2090 && !ada_is_array_descriptor_type (type);
2094 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2095 (fat pointer) returns the type of the array data described---specifically,
2096 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2097 in from the descriptor; otherwise, they are left unspecified. If
2098 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2099 returns NULL. The result is simply the type of ARR if ARR is not
2102 static struct type *
2103 ada_type_of_array (struct value *arr, int bounds)
2105 if (ada_is_constrained_packed_array_type (value_type (arr)))
2106 return decode_constrained_packed_array_type (value_type (arr));
2108 if (!ada_is_array_descriptor_type (value_type (arr)))
2109 return value_type (arr);
2113 struct type *array_type =
2114 ada_check_typedef (desc_data_target_type (value_type (arr)));
2116 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
2117 TYPE_FIELD_BITSIZE (array_type, 0) =
2118 decode_packed_array_bitsize (value_type (arr));
2124 struct type *elt_type;
2126 struct value *descriptor;
2128 elt_type = ada_array_element_type (value_type (arr), -1);
2129 arity = ada_array_arity (value_type (arr));
2131 if (elt_type == NULL || arity == 0)
2132 return ada_check_typedef (value_type (arr));
2134 descriptor = desc_bounds (arr);
2135 if (value_as_long (descriptor) == 0)
2139 struct type *range_type = alloc_type_copy (value_type (arr));
2140 struct type *array_type = alloc_type_copy (value_type (arr));
2141 struct value *low = desc_one_bound (descriptor, arity, 0);
2142 struct value *high = desc_one_bound (descriptor, arity, 1);
2145 create_static_range_type (range_type, value_type (low),
2146 longest_to_int (value_as_long (low)),
2147 longest_to_int (value_as_long (high)));
2148 elt_type = create_array_type (array_type, elt_type, range_type);
2150 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
2152 /* We need to store the element packed bitsize, as well as
2153 recompute the array size, because it was previously
2154 computed based on the unpacked element size. */
2155 LONGEST lo = value_as_long (low);
2156 LONGEST hi = value_as_long (high);
2158 TYPE_FIELD_BITSIZE (elt_type, 0) =
2159 decode_packed_array_bitsize (value_type (arr));
2160 /* If the array has no element, then the size is already
2161 zero, and does not need to be recomputed. */
2165 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
2167 TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
2172 return lookup_pointer_type (elt_type);
2176 /* If ARR does not represent an array, returns ARR unchanged.
2177 Otherwise, returns either a standard GDB array with bounds set
2178 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2179 GDB array. Returns NULL if ARR is a null fat pointer. */
2182 ada_coerce_to_simple_array_ptr (struct value *arr)
2184 if (ada_is_array_descriptor_type (value_type (arr)))
2186 struct type *arrType = ada_type_of_array (arr, 1);
2188 if (arrType == NULL)
2190 return value_cast (arrType, value_copy (desc_data (arr)));
2192 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2193 return decode_constrained_packed_array (arr);
2198 /* If ARR does not represent an array, returns ARR unchanged.
2199 Otherwise, returns a standard GDB array describing ARR (which may
2200 be ARR itself if it already is in the proper form). */
2203 ada_coerce_to_simple_array (struct value *arr)
2205 if (ada_is_array_descriptor_type (value_type (arr)))
2207 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2210 error (_("Bounds unavailable for null array pointer."));
2211 return value_ind (arrVal);
2213 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2214 return decode_constrained_packed_array (arr);
2219 /* If TYPE represents a GNAT array type, return it translated to an
2220 ordinary GDB array type (possibly with BITSIZE fields indicating
2221 packing). For other types, is the identity. */
2224 ada_coerce_to_simple_array_type (struct type *type)
2226 if (ada_is_constrained_packed_array_type (type))
2227 return decode_constrained_packed_array_type (type);
2229 if (ada_is_array_descriptor_type (type))
2230 return ada_check_typedef (desc_data_target_type (type));
2235 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2238 ada_is_gnat_encoded_packed_array_type (struct type *type)
2242 type = desc_base_type (type);
2243 type = ada_check_typedef (type);
2245 ada_type_name (type) != NULL
2246 && strstr (ada_type_name (type), "___XP") != NULL;
2249 /* Non-zero iff TYPE represents a standard GNAT constrained
2250 packed-array type. */
2253 ada_is_constrained_packed_array_type (struct type *type)
2255 return ada_is_gnat_encoded_packed_array_type (type)
2256 && !ada_is_array_descriptor_type (type);
2259 /* Non-zero iff TYPE represents an array descriptor for a
2260 unconstrained packed-array type. */
2263 ada_is_unconstrained_packed_array_type (struct type *type)
2265 if (!ada_is_array_descriptor_type (type))
2268 if (ada_is_gnat_encoded_packed_array_type (type))
2271 /* If we saw GNAT encodings, then the above code is sufficient.
2272 However, with minimal encodings, we will just have a thick
2274 if (is_thick_pntr (type))
2276 type = desc_base_type (type);
2277 /* The structure's first field is a pointer to an array, so this
2278 fetches the array type. */
2279 type = TYPE_TARGET_TYPE (type->field (0).type ());
2280 if (type->code () == TYPE_CODE_TYPEDEF)
2281 type = ada_typedef_target_type (type);
2282 /* Now we can see if the array elements are packed. */
2283 return TYPE_FIELD_BITSIZE (type, 0) > 0;
2289 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2290 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2293 ada_is_any_packed_array_type (struct type *type)
2295 return (ada_is_constrained_packed_array_type (type)
2296 || (type->code () == TYPE_CODE_ARRAY
2297 && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
2300 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2301 return the size of its elements in bits. */
2304 decode_packed_array_bitsize (struct type *type)
2306 const char *raw_name;
2310 /* Access to arrays implemented as fat pointers are encoded as a typedef
2311 of the fat pointer type. We need the name of the fat pointer type
2312 to do the decoding, so strip the typedef layer. */
2313 if (type->code () == TYPE_CODE_TYPEDEF)
2314 type = ada_typedef_target_type (type);
2316 raw_name = ada_type_name (ada_check_typedef (type));
2318 raw_name = ada_type_name (desc_base_type (type));
2323 tail = strstr (raw_name, "___XP");
2324 if (tail == nullptr)
2326 gdb_assert (is_thick_pntr (type));
2327 /* The structure's first field is a pointer to an array, so this
2328 fetches the array type. */
2329 type = TYPE_TARGET_TYPE (type->field (0).type ());
2330 /* Now we can see if the array elements are packed. */
2331 return TYPE_FIELD_BITSIZE (type, 0);
2334 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2337 (_("could not understand bit size information on packed array"));
2344 /* Given that TYPE is a standard GDB array type with all bounds filled
2345 in, and that the element size of its ultimate scalar constituents
2346 (that is, either its elements, or, if it is an array of arrays, its
2347 elements' elements, etc.) is *ELT_BITS, return an identical type,
2348 but with the bit sizes of its elements (and those of any
2349 constituent arrays) recorded in the BITSIZE components of its
2350 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2353 Note that, for arrays whose index type has an XA encoding where
2354 a bound references a record discriminant, getting that discriminant,
2355 and therefore the actual value of that bound, is not possible
2356 because none of the given parameters gives us access to the record.
2357 This function assumes that it is OK in the context where it is being
2358 used to return an array whose bounds are still dynamic and where
2359 the length is arbitrary. */
2361 static struct type *
2362 constrained_packed_array_type (struct type *type, long *elt_bits)
2364 struct type *new_elt_type;
2365 struct type *new_type;
2366 struct type *index_type_desc;
2367 struct type *index_type;
2368 LONGEST low_bound, high_bound;
2370 type = ada_check_typedef (type);
2371 if (type->code () != TYPE_CODE_ARRAY)
2374 index_type_desc = ada_find_parallel_type (type, "___XA");
2375 if (index_type_desc)
2376 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2379 index_type = type->index_type ();
2381 new_type = alloc_type_copy (type);
2383 constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2385 create_array_type (new_type, new_elt_type, index_type);
2386 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2387 new_type->set_name (ada_type_name (type));
2389 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2390 && is_dynamic_type (check_typedef (index_type)))
2391 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2392 low_bound = high_bound = 0;
2393 if (high_bound < low_bound)
2394 *elt_bits = TYPE_LENGTH (new_type) = 0;
2397 *elt_bits *= (high_bound - low_bound + 1);
2398 TYPE_LENGTH (new_type) =
2399 (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2402 new_type->set_is_fixed_instance (true);
2406 /* The array type encoded by TYPE, where
2407 ada_is_constrained_packed_array_type (TYPE). */
2409 static struct type *
2410 decode_constrained_packed_array_type (struct type *type)
2412 const char *raw_name = ada_type_name (ada_check_typedef (type));
2415 struct type *shadow_type;
2419 raw_name = ada_type_name (desc_base_type (type));
2424 name = (char *) alloca (strlen (raw_name) + 1);
2425 tail = strstr (raw_name, "___XP");
2426 type = desc_base_type (type);
2428 memcpy (name, raw_name, tail - raw_name);
2429 name[tail - raw_name] = '\000';
2431 shadow_type = ada_find_parallel_type_with_name (type, name);
2433 if (shadow_type == NULL)
2435 lim_warning (_("could not find bounds information on packed array"));
2438 shadow_type = check_typedef (shadow_type);
2440 if (shadow_type->code () != TYPE_CODE_ARRAY)
2442 lim_warning (_("could not understand bounds "
2443 "information on packed array"));
2447 bits = decode_packed_array_bitsize (type);
2448 return constrained_packed_array_type (shadow_type, &bits);
2451 /* Helper function for decode_constrained_packed_array. Set the field
2452 bitsize on a series of packed arrays. Returns the number of
2453 elements in TYPE. */
2456 recursively_update_array_bitsize (struct type *type)
2458 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2461 if (!get_discrete_bounds (type->index_type (), &low, &high)
2464 LONGEST our_len = high - low + 1;
2466 struct type *elt_type = TYPE_TARGET_TYPE (type);
2467 if (elt_type->code () == TYPE_CODE_ARRAY)
2469 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2470 LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2471 TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2473 TYPE_LENGTH (type) = ((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2480 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2481 array, returns a simple array that denotes that array. Its type is a
2482 standard GDB array type except that the BITSIZEs of the array
2483 target types are set to the number of bits in each element, and the
2484 type length is set appropriately. */
2486 static struct value *
2487 decode_constrained_packed_array (struct value *arr)
2491 /* If our value is a pointer, then dereference it. Likewise if
2492 the value is a reference. Make sure that this operation does not
2493 cause the target type to be fixed, as this would indirectly cause
2494 this array to be decoded. The rest of the routine assumes that
2495 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2496 and "value_ind" routines to perform the dereferencing, as opposed
2497 to using "ada_coerce_ref" or "ada_value_ind". */
2498 arr = coerce_ref (arr);
2499 if (ada_check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2500 arr = value_ind (arr);
2502 type = decode_constrained_packed_array_type (value_type (arr));
2505 error (_("can't unpack array"));
2509 /* Decoding the packed array type could not correctly set the field
2510 bitsizes for any dimension except the innermost, because the
2511 bounds may be variable and were not passed to that function. So,
2512 we further resolve the array bounds here and then update the
2514 const gdb_byte *valaddr = value_contents_for_printing (arr).data ();
2515 CORE_ADDR address = value_address (arr);
2516 gdb::array_view<const gdb_byte> view
2517 = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
2518 type = resolve_dynamic_type (type, view, address);
2519 recursively_update_array_bitsize (type);
2521 if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2522 && ada_is_modular_type (value_type (arr)))
2524 /* This is a (right-justified) modular type representing a packed
2525 array with no wrapper. In order to interpret the value through
2526 the (left-justified) packed array type we just built, we must
2527 first left-justify it. */
2528 int bit_size, bit_pos;
2531 mod = ada_modulus (value_type (arr)) - 1;
2538 bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2539 arr = ada_value_primitive_packed_val (arr, NULL,
2540 bit_pos / HOST_CHAR_BIT,
2541 bit_pos % HOST_CHAR_BIT,
2546 return coerce_unspec_val_to_type (arr, type);
2550 /* The value of the element of packed array ARR at the ARITY indices
2551 given in IND. ARR must be a simple array. */
2553 static struct value *
2554 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2557 int bits, elt_off, bit_off;
2558 long elt_total_bit_offset;
2559 struct type *elt_type;
2563 elt_total_bit_offset = 0;
2564 elt_type = ada_check_typedef (value_type (arr));
2565 for (i = 0; i < arity; i += 1)
2567 if (elt_type->code () != TYPE_CODE_ARRAY
2568 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2570 (_("attempt to do packed indexing of "
2571 "something other than a packed array"));
2574 struct type *range_type = elt_type->index_type ();
2575 LONGEST lowerbound, upperbound;
2578 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2580 lim_warning (_("don't know bounds of array"));
2581 lowerbound = upperbound = 0;
2584 idx = pos_atr (ind[i]);
2585 if (idx < lowerbound || idx > upperbound)
2586 lim_warning (_("packed array index %ld out of bounds"),
2588 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2589 elt_total_bit_offset += (idx - lowerbound) * bits;
2590 elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2593 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2594 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2596 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2601 /* Non-zero iff TYPE includes negative integer values. */
2604 has_negatives (struct type *type)
2606 switch (type->code ())
2611 return !type->is_unsigned ();
2612 case TYPE_CODE_RANGE:
2613 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2617 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2618 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2619 the unpacked buffer.
2621 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2622 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2624 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2627 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2629 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2632 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2633 gdb_byte *unpacked, int unpacked_len,
2634 int is_big_endian, int is_signed_type,
2637 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2638 int src_idx; /* Index into the source area */
2639 int src_bytes_left; /* Number of source bytes left to process. */
2640 int srcBitsLeft; /* Number of source bits left to move */
2641 int unusedLS; /* Number of bits in next significant
2642 byte of source that are unused */
2644 int unpacked_idx; /* Index into the unpacked buffer */
2645 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2647 unsigned long accum; /* Staging area for bits being transferred */
2648 int accumSize; /* Number of meaningful bits in accum */
2651 /* Transmit bytes from least to most significant; delta is the direction
2652 the indices move. */
2653 int delta = is_big_endian ? -1 : 1;
2655 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2657 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2658 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2659 bit_size, unpacked_len);
2661 srcBitsLeft = bit_size;
2662 src_bytes_left = src_len;
2663 unpacked_bytes_left = unpacked_len;
2668 src_idx = src_len - 1;
2670 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2674 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2680 unpacked_idx = unpacked_len - 1;
2684 /* Non-scalar values must be aligned at a byte boundary... */
2686 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2687 /* ... And are placed at the beginning (most-significant) bytes
2689 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2690 unpacked_bytes_left = unpacked_idx + 1;
2695 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2697 src_idx = unpacked_idx = 0;
2698 unusedLS = bit_offset;
2701 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2706 while (src_bytes_left > 0)
2708 /* Mask for removing bits of the next source byte that are not
2709 part of the value. */
2710 unsigned int unusedMSMask =
2711 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2713 /* Sign-extend bits for this byte. */
2714 unsigned int signMask = sign & ~unusedMSMask;
2717 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2718 accumSize += HOST_CHAR_BIT - unusedLS;
2719 if (accumSize >= HOST_CHAR_BIT)
2721 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2722 accumSize -= HOST_CHAR_BIT;
2723 accum >>= HOST_CHAR_BIT;
2724 unpacked_bytes_left -= 1;
2725 unpacked_idx += delta;
2727 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2729 src_bytes_left -= 1;
2732 while (unpacked_bytes_left > 0)
2734 accum |= sign << accumSize;
2735 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2736 accumSize -= HOST_CHAR_BIT;
2739 accum >>= HOST_CHAR_BIT;
2740 unpacked_bytes_left -= 1;
2741 unpacked_idx += delta;
2745 /* Create a new value of type TYPE from the contents of OBJ starting
2746 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2747 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2748 assigning through the result will set the field fetched from.
2749 VALADDR is ignored unless OBJ is NULL, in which case,
2750 VALADDR+OFFSET must address the start of storage containing the
2751 packed value. The value returned in this case is never an lval.
2752 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2755 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2756 long offset, int bit_offset, int bit_size,
2760 const gdb_byte *src; /* First byte containing data to unpack */
2762 const int is_scalar = is_scalar_type (type);
2763 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2764 gdb::byte_vector staging;
2766 type = ada_check_typedef (type);
2769 src = valaddr + offset;
2771 src = value_contents (obj).data () + offset;
2773 if (is_dynamic_type (type))
2775 /* The length of TYPE might by dynamic, so we need to resolve
2776 TYPE in order to know its actual size, which we then use
2777 to create the contents buffer of the value we return.
2778 The difficulty is that the data containing our object is
2779 packed, and therefore maybe not at a byte boundary. So, what
2780 we do, is unpack the data into a byte-aligned buffer, and then
2781 use that buffer as our object's value for resolving the type. */
2782 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2783 staging.resize (staging_len);
2785 ada_unpack_from_contents (src, bit_offset, bit_size,
2786 staging.data (), staging.size (),
2787 is_big_endian, has_negatives (type),
2789 type = resolve_dynamic_type (type, staging, 0);
2790 if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2792 /* This happens when the length of the object is dynamic,
2793 and is actually smaller than the space reserved for it.
2794 For instance, in an array of variant records, the bit_size
2795 we're given is the array stride, which is constant and
2796 normally equal to the maximum size of its element.
2797 But, in reality, each element only actually spans a portion
2799 bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2805 v = allocate_value (type);
2806 src = valaddr + offset;
2808 else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2810 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2813 v = value_at (type, value_address (obj) + offset);
2814 buf = (gdb_byte *) alloca (src_len);
2815 read_memory (value_address (v), buf, src_len);
2820 v = allocate_value (type);
2821 src = value_contents (obj).data () + offset;
2826 long new_offset = offset;
2828 set_value_component_location (v, obj);
2829 set_value_bitpos (v, bit_offset + value_bitpos (obj));
2830 set_value_bitsize (v, bit_size);
2831 if (value_bitpos (v) >= HOST_CHAR_BIT)
2834 set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2836 set_value_offset (v, new_offset);
2838 /* Also set the parent value. This is needed when trying to
2839 assign a new value (in inferior memory). */
2840 set_value_parent (v, obj);
2843 set_value_bitsize (v, bit_size);
2844 unpacked = value_contents_writeable (v).data ();
2848 memset (unpacked, 0, TYPE_LENGTH (type));
2852 if (staging.size () == TYPE_LENGTH (type))
2854 /* Small short-cut: If we've unpacked the data into a buffer
2855 of the same size as TYPE's length, then we can reuse that,
2856 instead of doing the unpacking again. */
2857 memcpy (unpacked, staging.data (), staging.size ());
2860 ada_unpack_from_contents (src, bit_offset, bit_size,
2861 unpacked, TYPE_LENGTH (type),
2862 is_big_endian, has_negatives (type), is_scalar);
2867 /* Store the contents of FROMVAL into the location of TOVAL.
2868 Return a new value with the location of TOVAL and contents of
2869 FROMVAL. Handles assignment into packed fields that have
2870 floating-point or non-scalar types. */
2872 static struct value *
2873 ada_value_assign (struct value *toval, struct value *fromval)
2875 struct type *type = value_type (toval);
2876 int bits = value_bitsize (toval);
2878 toval = ada_coerce_ref (toval);
2879 fromval = ada_coerce_ref (fromval);
2881 if (ada_is_direct_array_type (value_type (toval)))
2882 toval = ada_coerce_to_simple_array (toval);
2883 if (ada_is_direct_array_type (value_type (fromval)))
2884 fromval = ada_coerce_to_simple_array (fromval);
2886 if (!deprecated_value_modifiable (toval))
2887 error (_("Left operand of assignment is not a modifiable lvalue."));
2889 if (VALUE_LVAL (toval) == lval_memory
2891 && (type->code () == TYPE_CODE_FLT
2892 || type->code () == TYPE_CODE_STRUCT))
2894 int len = (value_bitpos (toval)
2895 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2897 gdb_byte *buffer = (gdb_byte *) alloca (len);
2899 CORE_ADDR to_addr = value_address (toval);
2901 if (type->code () == TYPE_CODE_FLT)
2902 fromval = value_cast (type, fromval);
2904 read_memory (to_addr, buffer, len);
2905 from_size = value_bitsize (fromval);
2907 from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2909 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2910 ULONGEST from_offset = 0;
2911 if (is_big_endian && is_scalar_type (value_type (fromval)))
2912 from_offset = from_size - bits;
2913 copy_bitwise (buffer, value_bitpos (toval),
2914 value_contents (fromval).data (), from_offset,
2915 bits, is_big_endian);
2916 write_memory_with_notification (to_addr, buffer, len);
2918 val = value_copy (toval);
2919 memcpy (value_contents_raw (val).data (),
2920 value_contents (fromval).data (),
2921 TYPE_LENGTH (type));
2922 deprecated_set_value_type (val, type);
2927 return value_assign (toval, fromval);
2931 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2932 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2933 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2934 COMPONENT, and not the inferior's memory. The current contents
2935 of COMPONENT are ignored.
2937 Although not part of the initial design, this function also works
2938 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2939 had a null address, and COMPONENT had an address which is equal to
2940 its offset inside CONTAINER. */
2943 value_assign_to_component (struct value *container, struct value *component,
2946 LONGEST offset_in_container =
2947 (LONGEST) (value_address (component) - value_address (container));
2948 int bit_offset_in_container =
2949 value_bitpos (component) - value_bitpos (container);
2952 val = value_cast (value_type (component), val);
2954 if (value_bitsize (component) == 0)
2955 bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2957 bits = value_bitsize (component);
2959 if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2963 if (is_scalar_type (check_typedef (value_type (component))))
2965 = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2968 copy_bitwise ((value_contents_writeable (container).data ()
2969 + offset_in_container),
2970 value_bitpos (container) + bit_offset_in_container,
2971 value_contents (val).data (), src_offset, bits, 1);
2974 copy_bitwise ((value_contents_writeable (container).data ()
2975 + offset_in_container),
2976 value_bitpos (container) + bit_offset_in_container,
2977 value_contents (val).data (), 0, bits, 0);
2980 /* Determine if TYPE is an access to an unconstrained array. */
2983 ada_is_access_to_unconstrained_array (struct type *type)
2985 return (type->code () == TYPE_CODE_TYPEDEF
2986 && is_thick_pntr (ada_typedef_target_type (type)));
2989 /* The value of the element of array ARR at the ARITY indices given in IND.
2990 ARR may be either a simple array, GNAT array descriptor, or pointer
2994 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2998 struct type *elt_type;
3000 elt = ada_coerce_to_simple_array (arr);
3002 elt_type = ada_check_typedef (value_type (elt));
3003 if (elt_type->code () == TYPE_CODE_ARRAY
3004 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
3005 return value_subscript_packed (elt, arity, ind);
3007 for (k = 0; k < arity; k += 1)
3009 struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
3011 if (elt_type->code () != TYPE_CODE_ARRAY)
3012 error (_("too many subscripts (%d expected)"), k);
3014 elt = value_subscript (elt, pos_atr (ind[k]));
3016 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3017 && value_type (elt)->code () != TYPE_CODE_TYPEDEF)
3019 /* The element is a typedef to an unconstrained array,
3020 except that the value_subscript call stripped the
3021 typedef layer. The typedef layer is GNAT's way to
3022 specify that the element is, at the source level, an
3023 access to the unconstrained array, rather than the
3024 unconstrained array. So, we need to restore that
3025 typedef layer, which we can do by forcing the element's
3026 type back to its original type. Otherwise, the returned
3027 value is going to be printed as the array, rather
3028 than as an access. Another symptom of the same issue
3029 would be that an expression trying to dereference the
3030 element would also be improperly rejected. */
3031 deprecated_set_value_type (elt, saved_elt_type);
3034 elt_type = ada_check_typedef (value_type (elt));
3040 /* Assuming ARR is a pointer to a GDB array, the value of the element
3041 of *ARR at the ARITY indices given in IND.
3042 Does not read the entire array into memory.
3044 Note: Unlike what one would expect, this function is used instead of
3045 ada_value_subscript for basically all non-packed array types. The reason
3046 for this is that a side effect of doing our own pointer arithmetics instead
3047 of relying on value_subscript is that there is no implicit typedef peeling.
3048 This is important for arrays of array accesses, where it allows us to
3049 preserve the fact that the array's element is an array access, where the
3050 access part os encoded in a typedef layer. */
3052 static struct value *
3053 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3056 struct value *array_ind = ada_value_ind (arr);
3058 = check_typedef (value_enclosing_type (array_ind));
3060 if (type->code () == TYPE_CODE_ARRAY
3061 && TYPE_FIELD_BITSIZE (type, 0) > 0)
3062 return value_subscript_packed (array_ind, arity, ind);
3064 for (k = 0; k < arity; k += 1)
3068 if (type->code () != TYPE_CODE_ARRAY)
3069 error (_("too many subscripts (%d expected)"), k);
3070 arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
3072 get_discrete_bounds (type->index_type (), &lwb, &upb);
3073 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3074 type = TYPE_TARGET_TYPE (type);
3077 return value_ind (arr);
3080 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3081 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3082 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3083 this array is LOW, as per Ada rules. */
3084 static struct value *
3085 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3088 struct type *type0 = ada_check_typedef (type);
3089 struct type *base_index_type = TYPE_TARGET_TYPE (type0->index_type ());
3090 struct type *index_type
3091 = create_static_range_type (NULL, base_index_type, low, high);
3092 struct type *slice_type = create_array_type_with_stride
3093 (NULL, TYPE_TARGET_TYPE (type0), index_type,
3094 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3095 TYPE_FIELD_BITSIZE (type0, 0));
3096 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3097 gdb::optional<LONGEST> base_low_pos, low_pos;
3100 low_pos = discrete_position (base_index_type, low);
3101 base_low_pos = discrete_position (base_index_type, base_low);
3103 if (!low_pos.has_value () || !base_low_pos.has_value ())
3105 warning (_("unable to get positions in slice, use bounds instead"));
3107 base_low_pos = base_low;
3110 ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
3112 stride = TYPE_LENGTH (TYPE_TARGET_TYPE (type0));
3114 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3115 return value_at_lazy (slice_type, base);
3119 static struct value *
3120 ada_value_slice (struct value *array, int low, int high)
3122 struct type *type = ada_check_typedef (value_type (array));
3123 struct type *base_index_type = TYPE_TARGET_TYPE (type->index_type ());
3124 struct type *index_type
3125 = create_static_range_type (NULL, type->index_type (), low, high);
3126 struct type *slice_type = create_array_type_with_stride
3127 (NULL, TYPE_TARGET_TYPE (type), index_type,
3128 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3129 TYPE_FIELD_BITSIZE (type, 0));
3130 gdb::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"));
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)
3160 type = desc_base_type (type);
3163 if (type->code () == TYPE_CODE_STRUCT)
3164 return desc_arity (desc_bounds_type (type));
3166 while (type->code () == TYPE_CODE_ARRAY)
3169 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
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. */
3181 ada_array_element_type (struct type *type, int nindices)
3183 type = desc_base_type (type);
3185 if (type->code () == TYPE_CODE_STRUCT)
3188 struct type *p_array_type;
3190 p_array_type = desc_data_target_type (type);
3192 k = ada_array_arity (type);
3196 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3197 if (nindices >= 0 && k > nindices)
3199 while (k > 0 && p_array_type != NULL)
3201 p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
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 (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)
3225 /* See ada-lang.h. */
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))
3241 for (i = 1; i < n; i += 1)
3243 type = ada_check_typedef (type);
3244 type = TYPE_TARGET_TYPE (type);
3246 result_type = TYPE_TARGET_TYPE (ada_check_typedef (type)->index_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)
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"));
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. */
3270 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3272 struct type *type, *index_type_desc, *index_type;
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 (LONGEST) - which;
3283 if (arr_type->code () == TYPE_CODE_PTR)
3284 type = TYPE_TARGET_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;
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 (),
3306 struct type *elt_type = check_typedef (type);
3308 for (i = 1; i < n; i++)
3309 elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
3311 index_type = elt_type->index_type ();
3315 (LONGEST) (which == 0
3316 ? ada_discrete_type_low_bound (index_type)
3317 : ada_discrete_type_high_bound (index_type));
3320 /* Given that arr is an array value, returns the lower bound of the
3321 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3322 WHICH is 1. This routine will also work for arrays with bounds
3323 supplied by run-time quantities other than discriminants. */
3326 ada_array_bound (struct value *arr, int n, int which)
3328 struct type *arr_type;
3330 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3331 arr = value_ind (arr);
3332 arr_type = value_enclosing_type (arr);
3334 if (ada_is_constrained_packed_array_type (arr_type))
3335 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3336 else if (ada_is_simple_array_type (arr_type))
3337 return ada_array_bound_from_type (arr_type, n, which);
3339 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3342 /* Given that arr is an array value, returns the length of the
3343 nth index. This routine will also work for arrays with bounds
3344 supplied by run-time quantities other than discriminants.
3345 Does not work for arrays indexed by enumeration types with representation
3346 clauses at the moment. */
3349 ada_array_length (struct value *arr, int n)
3351 struct type *arr_type, *index_type;
3354 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3355 arr = value_ind (arr);
3356 arr_type = value_enclosing_type (arr);
3358 if (ada_is_constrained_packed_array_type (arr_type))
3359 return ada_array_length (decode_constrained_packed_array (arr), n);
3361 if (ada_is_simple_array_type (arr_type))
3363 low = ada_array_bound_from_type (arr_type, n, 0);
3364 high = ada_array_bound_from_type (arr_type, n, 1);
3368 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3369 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3372 arr_type = check_typedef (arr_type);
3373 index_type = ada_index_type (arr_type, n, "length");
3374 if (index_type != NULL)
3376 struct type *base_type;
3377 if (index_type->code () == TYPE_CODE_RANGE)
3378 base_type = TYPE_TARGET_TYPE (index_type);
3380 base_type = index_type;
3382 low = pos_atr (value_from_longest (base_type, low));
3383 high = pos_atr (value_from_longest (base_type, high));
3385 return high - low + 1;
3388 /* An array whose type is that of ARR_TYPE (an array type), with
3389 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3390 less than LOW, then LOW-1 is used. */
3392 static struct value *
3393 empty_array (struct type *arr_type, int low, int high)
3395 struct type *arr_type0 = ada_check_typedef (arr_type);
3396 struct type *index_type
3397 = create_static_range_type
3398 (NULL, TYPE_TARGET_TYPE (arr_type0->index_type ()), low,
3399 high < low ? low - 1 : high);
3400 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3402 return allocate_value (create_array_type (NULL, elt_type, index_type));
3406 /* Name resolution */
3408 /* The "decoded" name for the user-definable Ada operator corresponding
3412 ada_decoded_op_name (enum exp_opcode op)
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). */
3431 encoded_ordered_before (const char *N0, const char *N1)
3435 else if (N0 == NULL)
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')
3451 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3454 while (N1[n1] == '_' && n1 > 0 && N1[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
3467 sort_choices (struct block_symbol syms[], int nsyms)
3471 for (i = 1; i < nsyms; i += 1)
3473 struct block_symbol sym = syms[i];
3476 for (j = i - 1; j >= 0; j -= 1)
3478 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3479 sym.symbol->linkage_name ()))
3481 syms[j + 1] = syms[j];
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). */
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
3505 || type->code () != TYPE_CODE_FUNC)
3508 if (type->num_fields () > 0)
3512 gdb_printf (stream, " (");
3513 for (i = 0; i < type->num_fields (); ++i)
3516 gdb_printf (stream, "; ");
3517 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3520 gdb_printf (stream, ")");
3522 if (TYPE_TARGET_TYPE (type) != NULL
3523 && TYPE_TARGET_TYPE (type)->code () != TYPE_CODE_VOID)
3525 gdb_printf (stream, " return ");
3526 ada_print_type (TYPE_TARGET_TYPE (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). */
3547 get_selections (int *choices, int n_choices, int max_results,
3548 int is_all_choice, const char *annotation_suffix)
3553 int first_choice = is_all_choice ? 2 : 1;
3555 prompt = getenv ("PS2");
3559 args = command_line_input (prompt, annotation_suffix);
3562 error_no_arg (_("one or more choice numbers"));
3566 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3567 order, as given in args. Choices are validated. */
3573 args = skip_spaces (args);
3574 if (*args == '\0' && n_chosen == 0)
3575 error_no_arg (_("one or more choice numbers"));
3576 else if (*args == '\0')
3579 choice = strtol (args, &args2, 10);
3580 if (args == args2 || choice < 0
3581 || choice > n_choices + first_choice - 1)
3582 error (_("Argument must be choice number"));
3586 error (_("cancelled"));
3588 if (choice < first_choice)
3590 n_chosen = n_choices;
3591 for (j = 0; j < n_choices; j += 1)
3595 choice -= first_choice;
3597 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3601 if (j < 0 || choice != choices[j])
3605 for (k = n_chosen - 1; k > j; k -= 1)
3606 choices[k + 1] = choices[k];
3607 choices[j + 1] = choice;
3612 if (n_chosen > max_results)
3613 error (_("Select no more than %d of the above"), max_results);
3618 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3619 by asking the user (if necessary), returning the number selected,
3620 and setting the first elements of SYMS items. Error if no symbols
3623 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3624 to be re-integrated one of these days. */
3627 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3630 int *chosen = XALLOCAVEC (int , nsyms);
3632 int first_choice = (max_results == 1) ? 1 : 2;
3633 const char *select_mode = multiple_symbols_select_mode ();
3635 if (max_results < 1)
3636 error (_("Request to select 0 symbols!"));
3640 if (select_mode == multiple_symbols_cancel)
3642 canceled because the command is ambiguous\n\
3643 See set/show multiple-symbol."));
3645 /* If select_mode is "all", then return all possible symbols.
3646 Only do that if more than one symbol can be selected, of course.
3647 Otherwise, display the menu as usual. */
3648 if (select_mode == multiple_symbols_all && max_results > 1)
3651 gdb_printf (_("[0] cancel\n"));
3652 if (max_results > 1)
3653 gdb_printf (_("[1] all\n"));
3655 sort_choices (syms, nsyms);
3657 for (i = 0; i < nsyms; i += 1)
3659 if (syms[i].symbol == NULL)
3662 if (syms[i].symbol->aclass () == LOC_BLOCK)
3664 struct symtab_and_line sal =
3665 find_function_start_sal (syms[i].symbol, 1);
3667 gdb_printf ("[%d] ", i + first_choice);
3668 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3669 &type_print_raw_options);
3670 if (sal.symtab == NULL)
3671 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3672 metadata_style.style ().ptr (), nullptr, sal.line);
3676 styled_string (file_name_style.style (),
3677 symtab_to_filename_for_display (sal.symtab)),
3684 (syms[i].symbol->aclass () == LOC_CONST
3685 && syms[i].symbol->type () != NULL
3686 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3687 struct symtab *symtab = NULL;
3689 if (syms[i].symbol->is_objfile_owned ())
3690 symtab = syms[i].symbol->symtab ();
3692 if (syms[i].symbol->line () != 0 && symtab != NULL)
3694 gdb_printf ("[%d] ", i + first_choice);
3695 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3696 &type_print_raw_options);
3697 gdb_printf (_(" at %s:%d\n"),
3698 symtab_to_filename_for_display (symtab),
3699 syms[i].symbol->line ());
3701 else if (is_enumeral
3702 && syms[i].symbol->type ()->name () != NULL)
3704 gdb_printf (("[%d] "), i + first_choice);
3705 ada_print_type (syms[i].symbol->type (), NULL,
3706 gdb_stdout, -1, 0, &type_print_raw_options);
3707 gdb_printf (_("'(%s) (enumeral)\n"),
3708 syms[i].symbol->print_name ());
3712 gdb_printf ("[%d] ", i + first_choice);
3713 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3714 &type_print_raw_options);
3717 gdb_printf (is_enumeral
3718 ? _(" in %s (enumeral)\n")
3720 symtab_to_filename_for_display (symtab));
3722 gdb_printf (is_enumeral
3723 ? _(" (enumeral)\n")
3729 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3732 for (i = 0; i < n_chosen; i += 1)
3733 syms[i] = syms[chosen[i]];
3738 /* See ada-lang.h. */
3741 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3742 int nargs, value *argvec[])
3744 if (possible_user_operator_p (op, argvec))
3746 std::vector<struct block_symbol> candidates
3747 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3750 int i = ada_resolve_function (candidates, argvec,
3751 nargs, ada_decoded_op_name (op), NULL,
3754 return candidates[i];
3759 /* See ada-lang.h. */
3762 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3763 struct type *context_type,
3764 bool parse_completion,
3765 int nargs, value *argvec[],
3766 innermost_block_tracker *tracker)
3768 std::vector<struct block_symbol> candidates
3769 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3772 if (candidates.size () == 1)
3776 i = ada_resolve_function
3779 sym->linkage_name (),
3780 context_type, parse_completion);
3782 error (_("Could not find a match for %s"), sym->print_name ());
3785 tracker->update (candidates[i]);
3786 return candidates[i];
3789 /* Resolve a mention of a name where the context type is an
3790 enumeration type. */
3793 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3794 const char *name, struct type *context_type,
3795 bool parse_completion)
3797 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3798 context_type = ada_check_typedef (context_type);
3800 for (int i = 0; i < syms.size (); ++i)
3802 /* We already know the name matches, so we're just looking for
3803 an element of the correct enum type. */
3804 if (ada_check_typedef (syms[i].symbol->type ()) == context_type)
3808 error (_("No name '%s' in enumeration type '%s'"), name,
3809 ada_type_name (context_type));
3812 /* See ada-lang.h. */
3815 ada_resolve_variable (struct symbol *sym, const struct block *block,
3816 struct type *context_type,
3817 bool parse_completion,
3819 innermost_block_tracker *tracker)
3821 std::vector<struct block_symbol> candidates
3822 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3824 if (std::any_of (candidates.begin (),
3826 [] (block_symbol &bsym)
3828 switch (bsym.symbol->aclass ())
3833 case LOC_REGPARM_ADDR:
3842 /* Types tend to get re-introduced locally, so if there
3843 are any local symbols that are not types, first filter
3847 (candidates.begin (),
3849 [] (block_symbol &bsym)
3851 return bsym.symbol->aclass () == LOC_TYPEDEF;
3856 /* Filter out artificial symbols. */
3859 (candidates.begin (),
3861 [] (block_symbol &bsym)
3863 return bsym.symbol->is_artificial ();
3868 if (candidates.empty ())
3869 error (_("No definition found for %s"), sym->print_name ());
3870 else if (candidates.size () == 1)
3872 else if (context_type != nullptr
3873 && context_type->code () == TYPE_CODE_ENUM)
3874 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3876 else if (deprocedure_p && !is_nonfunction (candidates))
3878 i = ada_resolve_function
3879 (candidates, NULL, 0,
3880 sym->linkage_name (),
3881 context_type, parse_completion);
3883 error (_("Could not find a match for %s"), sym->print_name ());
3887 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3888 user_select_syms (candidates.data (), candidates.size (), 1);
3892 tracker->update (candidates[i]);
3893 return candidates[i];
3896 /* Return non-zero if formal type FTYPE matches actual type ATYPE. */
3897 /* The term "match" here is rather loose. The match is heuristic and
3901 ada_type_match (struct type *ftype, struct type *atype)
3903 ftype = ada_check_typedef (ftype);
3904 atype = ada_check_typedef (atype);
3906 if (ftype->code () == TYPE_CODE_REF)
3907 ftype = TYPE_TARGET_TYPE (ftype);
3908 if (atype->code () == TYPE_CODE_REF)
3909 atype = TYPE_TARGET_TYPE (atype);
3911 switch (ftype->code ())
3914 return ftype->code () == atype->code ();
3916 if (atype->code () != TYPE_CODE_PTR)
3918 atype = TYPE_TARGET_TYPE (atype);
3919 /* This can only happen if the actual argument is 'null'. */
3920 if (atype->code () == TYPE_CODE_INT && TYPE_LENGTH (atype) == 0)
3922 return ada_type_match (TYPE_TARGET_TYPE (ftype), atype);
3924 case TYPE_CODE_ENUM:
3925 case TYPE_CODE_RANGE:
3926 switch (atype->code ())
3929 case TYPE_CODE_ENUM:
3930 case TYPE_CODE_RANGE:
3936 case TYPE_CODE_ARRAY:
3937 return (atype->code () == TYPE_CODE_ARRAY
3938 || ada_is_array_descriptor_type (atype));
3940 case TYPE_CODE_STRUCT:
3941 if (ada_is_array_descriptor_type (ftype))
3942 return (atype->code () == TYPE_CODE_ARRAY
3943 || ada_is_array_descriptor_type (atype));
3945 return (atype->code () == TYPE_CODE_STRUCT
3946 && !ada_is_array_descriptor_type (atype));
3948 case TYPE_CODE_UNION:
3950 return (atype->code () == ftype->code ());
3954 /* Return non-zero if the formals of FUNC "sufficiently match" the
3955 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3956 may also be an enumeral, in which case it is treated as a 0-
3957 argument function. */
3960 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3963 struct type *func_type = func->type ();
3965 if (func->aclass () == LOC_CONST
3966 && func_type->code () == TYPE_CODE_ENUM)
3967 return (n_actuals == 0);
3968 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3971 if (func_type->num_fields () != n_actuals)
3974 for (i = 0; i < n_actuals; i += 1)
3976 if (actuals[i] == NULL)
3980 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3981 struct type *atype = ada_check_typedef (value_type (actuals[i]));
3983 if (!ada_type_match (ftype, atype))
3990 /* False iff function type FUNC_TYPE definitely does not produce a value
3991 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
3992 FUNC_TYPE is not a valid function type with a non-null return type
3993 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
3996 return_match (struct type *func_type, struct type *context_type)
3998 struct type *return_type;
4000 if (func_type == NULL)
4003 if (func_type->code () == TYPE_CODE_FUNC)
4004 return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
4006 return_type = get_base_type (func_type);
4007 if (return_type == NULL)
4010 context_type = get_base_type (context_type);
4012 if (return_type->code () == TYPE_CODE_ENUM)
4013 return context_type == NULL || return_type == context_type;
4014 else if (context_type == NULL)
4015 return return_type->code () != TYPE_CODE_VOID;
4017 return return_type->code () == context_type->code ();
4021 /* Returns the index in SYMS that contains the symbol for the
4022 function (if any) that matches the types of the NARGS arguments in
4023 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4024 that returns that type, then eliminate matches that don't. If
4025 CONTEXT_TYPE is void and there is at least one match that does not
4026 return void, eliminate all matches that do.
4028 Asks the user if there is more than one match remaining. Returns -1
4029 if there is no such symbol or none is selected. NAME is used
4030 solely for messages. May re-arrange and modify SYMS in
4031 the process; the index returned is for the modified vector. */
4034 ada_resolve_function (std::vector<struct block_symbol> &syms,
4035 struct value **args, int nargs,
4036 const char *name, struct type *context_type,
4037 bool parse_completion)
4041 int m; /* Number of hits */
4044 /* In the first pass of the loop, we only accept functions matching
4045 context_type. If none are found, we add a second pass of the loop
4046 where every function is accepted. */
4047 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4049 for (k = 0; k < syms.size (); k += 1)
4051 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4053 if (ada_args_match (syms[k].symbol, args, nargs)
4054 && (fallback || return_match (type, context_type)))
4062 /* If we got multiple matches, ask the user which one to use. Don't do this
4063 interactive thing during completion, though, as the purpose of the
4064 completion is providing a list of all possible matches. Prompting the
4065 user to filter it down would be completely unexpected in this case. */
4068 else if (m > 1 && !parse_completion)
4070 gdb_printf (_("Multiple matches for %s\n"), name);
4071 user_select_syms (syms.data (), m, 1);
4077 /* Type-class predicates */
4079 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4083 numeric_type_p (struct type *type)
4089 switch (type->code ())
4093 case TYPE_CODE_FIXED_POINT:
4095 case TYPE_CODE_RANGE:
4096 return (type == TYPE_TARGET_TYPE (type)
4097 || numeric_type_p (TYPE_TARGET_TYPE (type)));
4104 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4107 integer_type_p (struct type *type)
4113 switch (type->code ())
4117 case TYPE_CODE_RANGE:
4118 return (type == TYPE_TARGET_TYPE (type)
4119 || integer_type_p (TYPE_TARGET_TYPE (type)));
4126 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4129 scalar_type_p (struct type *type)
4135 switch (type->code ())
4138 case TYPE_CODE_RANGE:
4139 case TYPE_CODE_ENUM:
4141 case TYPE_CODE_FIXED_POINT:
4149 /* True iff TYPE is discrete (INT, RANGE, ENUM). */
4152 discrete_type_p (struct type *type)
4158 switch (type->code ())
4161 case TYPE_CODE_RANGE:
4162 case TYPE_CODE_ENUM:
4163 case TYPE_CODE_BOOL:
4171 /* Returns non-zero if OP with operands in the vector ARGS could be
4172 a user-defined function. Errs on the side of pre-defined operators
4173 (i.e., result 0). */
4176 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4178 struct type *type0 =
4179 (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
4180 struct type *type1 =
4181 (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
4195 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4199 case BINOP_BITWISE_AND:
4200 case BINOP_BITWISE_IOR:
4201 case BINOP_BITWISE_XOR:
4202 return (!(integer_type_p (type0) && integer_type_p (type1)));
4205 case BINOP_NOTEQUAL:
4210 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4213 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4216 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4220 case UNOP_LOGICAL_NOT:
4222 return (!numeric_type_p (type0));
4231 1. In the following, we assume that a renaming type's name may
4232 have an ___XD suffix. It would be nice if this went away at some
4234 2. We handle both the (old) purely type-based representation of
4235 renamings and the (new) variable-based encoding. At some point,
4236 it is devoutly to be hoped that the former goes away
4237 (FIXME: hilfinger-2007-07-09).
4238 3. Subprogram renamings are not implemented, although the XRS
4239 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4241 /* If SYM encodes a renaming,
4243 <renaming> renames <renamed entity>,
4245 sets *LEN to the length of the renamed entity's name,
4246 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4247 the string describing the subcomponent selected from the renamed
4248 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4249 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4250 are undefined). Otherwise, returns a value indicating the category
4251 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4252 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4253 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4254 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4255 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4256 may be NULL, in which case they are not assigned.
4258 [Currently, however, GCC does not generate subprogram renamings.] */
4260 enum ada_renaming_category
4261 ada_parse_renaming (struct symbol *sym,
4262 const char **renamed_entity, int *len,
4263 const char **renaming_expr)
4265 enum ada_renaming_category kind;
4270 return ADA_NOT_RENAMING;
4271 switch (sym->aclass ())
4274 return ADA_NOT_RENAMING;
4278 case LOC_OPTIMIZED_OUT:
4279 info = strstr (sym->linkage_name (), "___XR");
4281 return ADA_NOT_RENAMING;
4285 kind = ADA_OBJECT_RENAMING;
4289 kind = ADA_EXCEPTION_RENAMING;
4293 kind = ADA_PACKAGE_RENAMING;
4297 kind = ADA_SUBPROGRAM_RENAMING;
4301 return ADA_NOT_RENAMING;
4305 if (renamed_entity != NULL)
4306 *renamed_entity = info;
4307 suffix = strstr (info, "___XE");
4308 if (suffix == NULL || suffix == info)
4309 return ADA_NOT_RENAMING;
4311 *len = strlen (info) - strlen (suffix);
4313 if (renaming_expr != NULL)
4314 *renaming_expr = suffix;
4318 /* Compute the value of the given RENAMING_SYM, which is expected to
4319 be a symbol encoding a renaming expression. BLOCK is the block
4320 used to evaluate the renaming. */
4322 static struct value *
4323 ada_read_renaming_var_value (struct symbol *renaming_sym,
4324 const struct block *block)
4326 const char *sym_name;
4328 sym_name = renaming_sym->linkage_name ();
4329 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4330 return evaluate_expression (expr.get ());
4334 /* Evaluation: Function Calls */
4336 /* Return an lvalue containing the value VAL. This is the identity on
4337 lvalues, and otherwise has the side-effect of allocating memory
4338 in the inferior where a copy of the value contents is copied. */
4340 static struct value *
4341 ensure_lval (struct value *val)
4343 if (VALUE_LVAL (val) == not_lval
4344 || VALUE_LVAL (val) == lval_internalvar)
4346 int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4347 const CORE_ADDR addr =
4348 value_as_long (value_allocate_space_in_inferior (len));
4350 VALUE_LVAL (val) = lval_memory;
4351 set_value_address (val, addr);
4352 write_memory (addr, value_contents (val).data (), len);
4358 /* Given ARG, a value of type (pointer or reference to a)*
4359 structure/union, extract the component named NAME from the ultimate
4360 target structure/union and return it as a value with its
4363 The routine searches for NAME among all members of the structure itself
4364 and (recursively) among all members of any wrapper members
4367 If NO_ERR, then simply return NULL in case of error, rather than
4370 static struct value *
4371 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4373 struct type *t, *t1;
4378 t1 = t = ada_check_typedef (value_type (arg));
4379 if (t->code () == TYPE_CODE_REF)
4381 t1 = TYPE_TARGET_TYPE (t);
4384 t1 = ada_check_typedef (t1);
4385 if (t1->code () == TYPE_CODE_PTR)
4387 arg = coerce_ref (arg);
4392 while (t->code () == TYPE_CODE_PTR)
4394 t1 = TYPE_TARGET_TYPE (t);
4397 t1 = ada_check_typedef (t1);
4398 if (t1->code () == TYPE_CODE_PTR)
4400 arg = value_ind (arg);
4407 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4411 v = ada_search_struct_field (name, arg, 0, t);
4414 int bit_offset, bit_size, byte_offset;
4415 struct type *field_type;
4418 if (t->code () == TYPE_CODE_PTR)
4419 address = value_address (ada_value_ind (arg));
4421 address = value_address (ada_coerce_ref (arg));
4423 /* Check to see if this is a tagged type. We also need to handle
4424 the case where the type is a reference to a tagged type, but
4425 we have to be careful to exclude pointers to tagged types.
4426 The latter should be shown as usual (as a pointer), whereas
4427 a reference should mostly be transparent to the user. */
4429 if (ada_is_tagged_type (t1, 0)
4430 || (t1->code () == TYPE_CODE_REF
4431 && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
4433 /* We first try to find the searched field in the current type.
4434 If not found then let's look in the fixed type. */
4436 if (!find_struct_field (name, t1, 0,
4437 nullptr, nullptr, nullptr,
4446 /* Convert to fixed type in all cases, so that we have proper
4447 offsets to each field in unconstrained record types. */
4448 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4449 address, NULL, check_tag);
4451 /* Resolve the dynamic type as well. */
4452 arg = value_from_contents_and_address (t1, nullptr, address);
4453 t1 = value_type (arg);
4455 if (find_struct_field (name, t1, 0,
4456 &field_type, &byte_offset, &bit_offset,
4461 if (t->code () == TYPE_CODE_REF)
4462 arg = ada_coerce_ref (arg);
4464 arg = ada_value_ind (arg);
4465 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4466 bit_offset, bit_size,
4470 v = value_at_lazy (field_type, address + byte_offset);
4474 if (v != NULL || no_err)
4477 error (_("There is no member named %s."), name);
4483 error (_("Attempt to extract a component of "
4484 "a value that is not a record."));
4487 /* Return the value ACTUAL, converted to be an appropriate value for a
4488 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4489 allocating any necessary descriptors (fat pointers), or copies of
4490 values not residing in memory, updating it as needed. */
4493 ada_convert_actual (struct value *actual, struct type *formal_type0)
4495 struct type *actual_type = ada_check_typedef (value_type (actual));
4496 struct type *formal_type = ada_check_typedef (formal_type0);
4497 struct type *formal_target =
4498 formal_type->code () == TYPE_CODE_PTR
4499 ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4500 struct type *actual_target =
4501 actual_type->code () == TYPE_CODE_PTR
4502 ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4504 if (ada_is_array_descriptor_type (formal_target)
4505 && actual_target->code () == TYPE_CODE_ARRAY)
4506 return make_array_descriptor (formal_type, actual);
4507 else if (formal_type->code () == TYPE_CODE_PTR
4508 || formal_type->code () == TYPE_CODE_REF)
4510 struct value *result;
4512 if (formal_target->code () == TYPE_CODE_ARRAY
4513 && ada_is_array_descriptor_type (actual_target))
4514 result = desc_data (actual);
4515 else if (formal_type->code () != TYPE_CODE_PTR)
4517 if (VALUE_LVAL (actual) != lval_memory)
4521 actual_type = ada_check_typedef (value_type (actual));
4522 val = allocate_value (actual_type);
4523 copy (value_contents (actual), value_contents_raw (val));
4524 actual = ensure_lval (val);
4526 result = value_addr (actual);
4530 return value_cast_pointers (formal_type, result, 0);
4532 else if (actual_type->code () == TYPE_CODE_PTR)
4533 return ada_value_ind (actual);
4534 else if (ada_is_aligner_type (formal_type))
4536 /* We need to turn this parameter into an aligner type
4538 struct value *aligner = allocate_value (formal_type);
4539 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4541 value_assign_to_component (aligner, component, actual);
4548 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4549 type TYPE. This is usually an inefficient no-op except on some targets
4550 (such as AVR) where the representation of a pointer and an address
4554 value_pointer (struct value *value, struct type *type)
4556 unsigned len = TYPE_LENGTH (type);
4557 gdb_byte *buf = (gdb_byte *) alloca (len);
4560 addr = value_address (value);
4561 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4562 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4567 /* Push a descriptor of type TYPE for array value ARR on the stack at
4568 *SP, updating *SP to reflect the new descriptor. Return either
4569 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4570 to-descriptor type rather than a descriptor type), a struct value *
4571 representing a pointer to this descriptor. */
4573 static struct value *
4574 make_array_descriptor (struct type *type, struct value *arr)
4576 struct type *bounds_type = desc_bounds_type (type);
4577 struct type *desc_type = desc_base_type (type);
4578 struct value *descriptor = allocate_value (desc_type);
4579 struct value *bounds = allocate_value (bounds_type);
4582 for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4585 modify_field (value_type (bounds),
4586 value_contents_writeable (bounds).data (),
4587 ada_array_bound (arr, i, 0),
4588 desc_bound_bitpos (bounds_type, i, 0),
4589 desc_bound_bitsize (bounds_type, i, 0));
4590 modify_field (value_type (bounds),
4591 value_contents_writeable (bounds).data (),
4592 ada_array_bound (arr, i, 1),
4593 desc_bound_bitpos (bounds_type, i, 1),
4594 desc_bound_bitsize (bounds_type, i, 1));
4597 bounds = ensure_lval (bounds);
4599 modify_field (value_type (descriptor),
4600 value_contents_writeable (descriptor).data (),
4601 value_pointer (ensure_lval (arr),
4602 desc_type->field (0).type ()),
4603 fat_pntr_data_bitpos (desc_type),
4604 fat_pntr_data_bitsize (desc_type));
4606 modify_field (value_type (descriptor),
4607 value_contents_writeable (descriptor).data (),
4608 value_pointer (bounds,
4609 desc_type->field (1).type ()),
4610 fat_pntr_bounds_bitpos (desc_type),
4611 fat_pntr_bounds_bitsize (desc_type));
4613 descriptor = ensure_lval (descriptor);
4615 if (type->code () == TYPE_CODE_PTR)
4616 return value_addr (descriptor);
4621 /* Symbol Cache Module */
4623 /* Performance measurements made as of 2010-01-15 indicate that
4624 this cache does bring some noticeable improvements. Depending
4625 on the type of entity being printed, the cache can make it as much
4626 as an order of magnitude faster than without it.
4628 The descriptive type DWARF extension has significantly reduced
4629 the need for this cache, at least when DWARF is being used. However,
4630 even in this case, some expensive name-based symbol searches are still
4631 sometimes necessary - to find an XVZ variable, mostly. */
4633 /* Return the symbol cache associated to the given program space PSPACE.
4634 If not allocated for this PSPACE yet, allocate and initialize one. */
4636 static struct ada_symbol_cache *
4637 ada_get_symbol_cache (struct program_space *pspace)
4639 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4641 if (pspace_data->sym_cache == nullptr)
4642 pspace_data->sym_cache.reset (new ada_symbol_cache);
4644 return pspace_data->sym_cache.get ();
4647 /* Clear all entries from the symbol cache. */
4650 ada_clear_symbol_cache ()
4652 struct ada_pspace_data *pspace_data
4653 = get_ada_pspace_data (current_program_space);
4655 if (pspace_data->sym_cache != nullptr)
4656 pspace_data->sym_cache.reset ();
4659 /* Search our cache for an entry matching NAME and DOMAIN.
4660 Return it if found, or NULL otherwise. */
4662 static struct cache_entry **
4663 find_entry (const char *name, domain_enum domain)
4665 struct ada_symbol_cache *sym_cache
4666 = ada_get_symbol_cache (current_program_space);
4667 int h = msymbol_hash (name) % HASH_SIZE;
4668 struct cache_entry **e;
4670 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4672 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4678 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4679 Return 1 if found, 0 otherwise.
4681 If an entry was found and SYM is not NULL, set *SYM to the entry's
4682 SYM. Same principle for BLOCK if not NULL. */
4685 lookup_cached_symbol (const char *name, domain_enum domain,
4686 struct symbol **sym, const struct block **block)
4688 struct cache_entry **e = find_entry (name, domain);
4695 *block = (*e)->block;
4699 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4700 in domain DOMAIN, save this result in our symbol cache. */
4703 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4704 const struct block *block)
4706 struct ada_symbol_cache *sym_cache
4707 = ada_get_symbol_cache (current_program_space);
4709 struct cache_entry *e;
4711 /* Symbols for builtin types don't have a block.
4712 For now don't cache such symbols. */
4713 if (sym != NULL && !sym->is_objfile_owned ())
4716 /* If the symbol is a local symbol, then do not cache it, as a search
4717 for that symbol depends on the context. To determine whether
4718 the symbol is local or not, we check the block where we found it
4719 against the global and static blocks of its associated symtab. */
4722 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4724 if (bv.global_block () != block && bv.static_block () != block)
4728 h = msymbol_hash (name) % HASH_SIZE;
4729 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4730 e->next = sym_cache->root[h];
4731 sym_cache->root[h] = e;
4732 e->name = obstack_strdup (&sym_cache->cache_space, name);
4740 /* Return the symbol name match type that should be used used when
4741 searching for all symbols matching LOOKUP_NAME.
4743 LOOKUP_NAME is expected to be a symbol name after transformation
4746 static symbol_name_match_type
4747 name_match_type_from_name (const char *lookup_name)
4749 return (strstr (lookup_name, "__") == NULL
4750 ? symbol_name_match_type::WILD
4751 : symbol_name_match_type::FULL);
4754 /* Return the result of a standard (literal, C-like) lookup of NAME in
4755 given DOMAIN, visible from lexical block BLOCK. */
4757 static struct symbol *
4758 standard_lookup (const char *name, const struct block *block,
4761 /* Initialize it just to avoid a GCC false warning. */
4762 struct block_symbol sym = {};
4764 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4766 ada_lookup_encoded_symbol (name, block, domain, &sym);
4767 cache_symbol (name, domain, sym.symbol, sym.block);
4772 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4773 in the symbol fields of SYMS. We treat enumerals as functions,
4774 since they contend in overloading in the same way. */
4776 is_nonfunction (const std::vector<struct block_symbol> &syms)
4778 for (const block_symbol &sym : syms)
4779 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4780 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4781 || sym.symbol->aclass () != LOC_CONST))
4787 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4788 struct types. Otherwise, they may not. */
4791 equiv_types (struct type *type0, struct type *type1)
4795 if (type0 == NULL || type1 == NULL
4796 || type0->code () != type1->code ())
4798 if ((type0->code () == TYPE_CODE_STRUCT
4799 || type0->code () == TYPE_CODE_ENUM)
4800 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4801 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4807 /* True iff SYM0 represents the same entity as SYM1, or one that is
4808 no more defined than that of SYM1. */
4811 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4815 if (sym0->domain () != sym1->domain ()
4816 || sym0->aclass () != sym1->aclass ())
4819 switch (sym0->aclass ())
4825 struct type *type0 = sym0->type ();
4826 struct type *type1 = sym1->type ();
4827 const char *name0 = sym0->linkage_name ();
4828 const char *name1 = sym1->linkage_name ();
4829 int len0 = strlen (name0);
4832 type0->code () == type1->code ()
4833 && (equiv_types (type0, type1)
4834 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4835 && startswith (name1 + len0, "___XV")));
4838 return sym0->value_longest () == sym1->value_longest ()
4839 && equiv_types (sym0->type (), sym1->type ());
4843 const char *name0 = sym0->linkage_name ();
4844 const char *name1 = sym1->linkage_name ();
4845 return (strcmp (name0, name1) == 0
4846 && sym0->value_address () == sym1->value_address ());
4854 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4855 records in RESULT. Do nothing if SYM is a duplicate. */
4858 add_defn_to_vec (std::vector<struct block_symbol> &result,
4860 const struct block *block)
4862 /* Do not try to complete stub types, as the debugger is probably
4863 already scanning all symbols matching a certain name at the
4864 time when this function is called. Trying to replace the stub
4865 type by its associated full type will cause us to restart a scan
4866 which may lead to an infinite recursion. Instead, the client
4867 collecting the matching symbols will end up collecting several
4868 matches, with at least one of them complete. It can then filter
4869 out the stub ones if needed. */
4871 for (int i = result.size () - 1; i >= 0; i -= 1)
4873 if (lesseq_defined_than (sym, result[i].symbol))
4875 else if (lesseq_defined_than (result[i].symbol, sym))
4877 result[i].symbol = sym;
4878 result[i].block = block;
4883 struct block_symbol info;
4886 result.push_back (info);
4889 /* Return a bound minimal symbol matching NAME according to Ada
4890 decoding rules. Returns an invalid symbol if there is no such
4891 minimal symbol. Names prefixed with "standard__" are handled
4892 specially: "standard__" is first stripped off, and only static and
4893 global symbols are searched. */
4895 struct bound_minimal_symbol
4896 ada_lookup_simple_minsym (const char *name)
4898 struct bound_minimal_symbol result;
4900 symbol_name_match_type match_type = name_match_type_from_name (name);
4901 lookup_name_info lookup_name (name, match_type);
4903 symbol_name_matcher_ftype *match_name
4904 = ada_get_symbol_name_matcher (lookup_name);
4906 for (objfile *objfile : current_program_space->objfiles ())
4908 for (minimal_symbol *msymbol : objfile->msymbols ())
4910 if (match_name (msymbol->linkage_name (), lookup_name, NULL)
4911 && msymbol->type () != mst_solib_trampoline)
4913 result.minsym = msymbol;
4914 result.objfile = objfile;
4923 /* True if TYPE is definitely an artificial type supplied to a symbol
4924 for which no debugging information was given in the symbol file. */
4927 is_nondebugging_type (struct type *type)
4929 const char *name = ada_type_name (type);
4931 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4934 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4935 that are deemed "identical" for practical purposes.
4937 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4938 types and that their number of enumerals is identical (in other
4939 words, type1->num_fields () == type2->num_fields ()). */
4942 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4946 /* The heuristic we use here is fairly conservative. We consider
4947 that 2 enumerate types are identical if they have the same
4948 number of enumerals and that all enumerals have the same
4949 underlying value and name. */
4951 /* All enums in the type should have an identical underlying value. */
4952 for (i = 0; i < type1->num_fields (); i++)
4953 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4956 /* All enumerals should also have the same name (modulo any numerical
4958 for (i = 0; i < type1->num_fields (); i++)
4960 const char *name_1 = type1->field (i).name ();
4961 const char *name_2 = type2->field (i).name ();
4962 int len_1 = strlen (name_1);
4963 int len_2 = strlen (name_2);
4965 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4966 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4968 || strncmp (type1->field (i).name (),
4969 type2->field (i).name (),
4977 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4978 that are deemed "identical" for practical purposes. Sometimes,
4979 enumerals are not strictly identical, but their types are so similar
4980 that they can be considered identical.
4982 For instance, consider the following code:
4984 type Color is (Black, Red, Green, Blue, White);
4985 type RGB_Color is new Color range Red .. Blue;
4987 Type RGB_Color is a subrange of an implicit type which is a copy
4988 of type Color. If we call that implicit type RGB_ColorB ("B" is
4989 for "Base Type"), then type RGB_ColorB is a copy of type Color.
4990 As a result, when an expression references any of the enumeral
4991 by name (Eg. "print green"), the expression is technically
4992 ambiguous and the user should be asked to disambiguate. But
4993 doing so would only hinder the user, since it wouldn't matter
4994 what choice he makes, the outcome would always be the same.
4995 So, for practical purposes, we consider them as the same. */
4998 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5002 /* Before performing a thorough comparison check of each type,
5003 we perform a series of inexpensive checks. We expect that these
5004 checks will quickly fail in the vast majority of cases, and thus
5005 help prevent the unnecessary use of a more expensive comparison.
5006 Said comparison also expects us to make some of these checks
5007 (see ada_identical_enum_types_p). */
5009 /* Quick check: All symbols should have an enum type. */
5010 for (i = 0; i < syms.size (); i++)
5011 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5014 /* Quick check: They should all have the same value. */
5015 for (i = 1; i < syms.size (); i++)
5016 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5019 /* Quick check: They should all have the same number of enumerals. */
5020 for (i = 1; i < syms.size (); i++)
5021 if (syms[i].symbol->type ()->num_fields ()
5022 != syms[0].symbol->type ()->num_fields ())
5025 /* All the sanity checks passed, so we might have a set of
5026 identical enumeration types. Perform a more complete
5027 comparison of the type of each symbol. */
5028 for (i = 1; i < syms.size (); i++)
5029 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5030 syms[0].symbol->type ()))
5036 /* Remove any non-debugging symbols in SYMS that definitely
5037 duplicate other symbols in the list (The only case I know of where
5038 this happens is when object files containing stabs-in-ecoff are
5039 linked with files containing ordinary ecoff debugging symbols (or no
5040 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5043 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5047 /* We should never be called with less than 2 symbols, as there
5048 cannot be any extra symbol in that case. But it's easy to
5049 handle, since we have nothing to do in that case. */
5050 if (syms->size () < 2)
5054 while (i < syms->size ())
5058 /* If two symbols have the same name and one of them is a stub type,
5059 the get rid of the stub. */
5061 if ((*syms)[i].symbol->type ()->is_stub ()
5062 && (*syms)[i].symbol->linkage_name () != NULL)
5064 for (j = 0; j < syms->size (); j++)
5067 && !(*syms)[j].symbol->type ()->is_stub ()
5068 && (*syms)[j].symbol->linkage_name () != NULL
5069 && strcmp ((*syms)[i].symbol->linkage_name (),
5070 (*syms)[j].symbol->linkage_name ()) == 0)
5075 /* Two symbols with the same name, same class and same address
5076 should be identical. */
5078 else if ((*syms)[i].symbol->linkage_name () != NULL
5079 && (*syms)[i].symbol->aclass () == LOC_STATIC
5080 && is_nondebugging_type ((*syms)[i].symbol->type ()))
5082 for (j = 0; j < syms->size (); j += 1)
5085 && (*syms)[j].symbol->linkage_name () != NULL
5086 && strcmp ((*syms)[i].symbol->linkage_name (),
5087 (*syms)[j].symbol->linkage_name ()) == 0
5088 && ((*syms)[i].symbol->aclass ()
5089 == (*syms)[j].symbol->aclass ())
5090 && (*syms)[i].symbol->value_address ()
5091 == (*syms)[j].symbol->value_address ())
5097 syms->erase (syms->begin () + i);
5102 /* If all the remaining symbols are identical enumerals, then
5103 just keep the first one and discard the rest.
5105 Unlike what we did previously, we do not discard any entry
5106 unless they are ALL identical. This is because the symbol
5107 comparison is not a strict comparison, but rather a practical
5108 comparison. If all symbols are considered identical, then
5109 we can just go ahead and use the first one and discard the rest.
5110 But if we cannot reduce the list to a single element, we have
5111 to ask the user to disambiguate anyways. And if we have to
5112 present a multiple-choice menu, it's less confusing if the list
5113 isn't missing some choices that were identical and yet distinct. */
5114 if (symbols_are_identical_enums (*syms))
5118 /* Given a type that corresponds to a renaming entity, use the type name
5119 to extract the scope (package name or function name, fully qualified,
5120 and following the GNAT encoding convention) where this renaming has been
5124 xget_renaming_scope (struct type *renaming_type)
5126 /* The renaming types adhere to the following convention:
5127 <scope>__<rename>___<XR extension>.
5128 So, to extract the scope, we search for the "___XR" extension,
5129 and then backtrack until we find the first "__". */
5131 const char *name = renaming_type->name ();
5132 const char *suffix = strstr (name, "___XR");
5135 /* Now, backtrack a bit until we find the first "__". Start looking
5136 at suffix - 3, as the <rename> part is at least one character long. */
5138 for (last = suffix - 3; last > name; last--)
5139 if (last[0] == '_' && last[1] == '_')
5142 /* Make a copy of scope and return it. */
5143 return std::string (name, last);
5146 /* Return nonzero if NAME corresponds to a package name. */
5149 is_package_name (const char *name)
5151 /* Here, We take advantage of the fact that no symbols are generated
5152 for packages, while symbols are generated for each function.
5153 So the condition for NAME represent a package becomes equivalent
5154 to NAME not existing in our list of symbols. There is only one
5155 small complication with library-level functions (see below). */
5157 /* If it is a function that has not been defined at library level,
5158 then we should be able to look it up in the symbols. */
5159 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5162 /* Library-level function names start with "_ada_". See if function
5163 "_ada_" followed by NAME can be found. */
5165 /* Do a quick check that NAME does not contain "__", since library-level
5166 functions names cannot contain "__" in them. */
5167 if (strstr (name, "__") != NULL)
5170 std::string fun_name = string_printf ("_ada_%s", name);
5172 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5175 /* Return nonzero if SYM corresponds to a renaming entity that is
5176 not visible from FUNCTION_NAME. */
5179 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5181 if (sym->aclass () != LOC_TYPEDEF)
5184 std::string scope = xget_renaming_scope (sym->type ());
5186 /* If the rename has been defined in a package, then it is visible. */
5187 if (is_package_name (scope.c_str ()))
5190 /* Check that the rename is in the current function scope by checking
5191 that its name starts with SCOPE. */
5193 /* If the function name starts with "_ada_", it means that it is
5194 a library-level function. Strip this prefix before doing the
5195 comparison, as the encoding for the renaming does not contain
5197 if (startswith (function_name, "_ada_"))
5200 return !startswith (function_name, scope.c_str ());
5203 /* Remove entries from SYMS that corresponds to a renaming entity that
5204 is not visible from the function associated with CURRENT_BLOCK or
5205 that is superfluous due to the presence of more specific renaming
5206 information. Places surviving symbols in the initial entries of
5210 First, in cases where an object renaming is implemented as a
5211 reference variable, GNAT may produce both the actual reference
5212 variable and the renaming encoding. In this case, we discard the
5215 Second, GNAT emits a type following a specified encoding for each renaming
5216 entity. Unfortunately, STABS currently does not support the definition
5217 of types that are local to a given lexical block, so all renamings types
5218 are emitted at library level. As a consequence, if an application
5219 contains two renaming entities using the same name, and a user tries to
5220 print the value of one of these entities, the result of the ada symbol
5221 lookup will also contain the wrong renaming type.
5223 This function partially covers for this limitation by attempting to
5224 remove from the SYMS list renaming symbols that should be visible
5225 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5226 method with the current information available. The implementation
5227 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5229 - When the user tries to print a rename in a function while there
5230 is another rename entity defined in a package: Normally, the
5231 rename in the function has precedence over the rename in the
5232 package, so the latter should be removed from the list. This is
5233 currently not the case.
5235 - This function will incorrectly remove valid renames if
5236 the CURRENT_BLOCK corresponds to a function which symbol name
5237 has been changed by an "Export" pragma. As a consequence,
5238 the user will be unable to print such rename entities. */
5241 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5242 const struct block *current_block)
5244 struct symbol *current_function;
5245 const char *current_function_name;
5247 int is_new_style_renaming;
5249 /* If there is both a renaming foo___XR... encoded as a variable and
5250 a simple variable foo in the same block, discard the latter.
5251 First, zero out such symbols, then compress. */
5252 is_new_style_renaming = 0;
5253 for (i = 0; i < syms->size (); i += 1)
5255 struct symbol *sym = (*syms)[i].symbol;
5256 const struct block *block = (*syms)[i].block;
5260 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5262 name = sym->linkage_name ();
5263 suffix = strstr (name, "___XR");
5267 int name_len = suffix - name;
5270 is_new_style_renaming = 1;
5271 for (j = 0; j < syms->size (); j += 1)
5272 if (i != j && (*syms)[j].symbol != NULL
5273 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5275 && block == (*syms)[j].block)
5276 (*syms)[j].symbol = NULL;
5279 if (is_new_style_renaming)
5283 for (j = k = 0; j < syms->size (); j += 1)
5284 if ((*syms)[j].symbol != NULL)
5286 (*syms)[k] = (*syms)[j];
5293 /* Extract the function name associated to CURRENT_BLOCK.
5294 Abort if unable to do so. */
5296 if (current_block == NULL)
5299 current_function = block_linkage_function (current_block);
5300 if (current_function == NULL)
5303 current_function_name = current_function->linkage_name ();
5304 if (current_function_name == NULL)
5307 /* Check each of the symbols, and remove it from the list if it is
5308 a type corresponding to a renaming that is out of the scope of
5309 the current block. */
5312 while (i < syms->size ())
5314 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5315 == ADA_OBJECT_RENAMING
5316 && old_renaming_is_invisible ((*syms)[i].symbol,
5317 current_function_name))
5318 syms->erase (syms->begin () + i);
5324 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5325 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5327 Note: This function assumes that RESULT is empty. */
5330 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5331 const lookup_name_info &lookup_name,
5332 const struct block *block, domain_enum domain)
5334 while (block != NULL)
5336 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5338 /* If we found a non-function match, assume that's the one. We
5339 only check this when finding a function boundary, so that we
5340 can accumulate all results from intervening blocks first. */
5341 if (block->function () != nullptr && is_nonfunction (result))
5344 block = block->superblock ();
5348 /* An object of this type is used as the callback argument when
5349 calling the map_matching_symbols method. */
5353 explicit match_data (std::vector<struct block_symbol> *rp)
5357 DISABLE_COPY_AND_ASSIGN (match_data);
5359 bool operator() (struct block_symbol *bsym);
5361 struct objfile *objfile = nullptr;
5362 std::vector<struct block_symbol> *resultp;
5363 struct symbol *arg_sym = nullptr;
5364 bool found_sym = false;
5367 /* A callback for add_nonlocal_symbols that adds symbol, found in
5368 BSYM, to a list of symbols. */
5371 match_data::operator() (struct block_symbol *bsym)
5373 const struct block *block = bsym->block;
5374 struct symbol *sym = bsym->symbol;
5378 if (!found_sym && arg_sym != NULL)
5379 add_defn_to_vec (*resultp,
5380 fixup_symbol_section (arg_sym, objfile),
5387 if (sym->aclass () == LOC_UNRESOLVED)
5389 else if (sym->is_argument ())
5394 add_defn_to_vec (*resultp,
5395 fixup_symbol_section (sym, objfile),
5402 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5403 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5404 symbols to RESULT. Return whether we found such symbols. */
5407 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5408 const struct block *block,
5409 const lookup_name_info &lookup_name,
5412 struct using_direct *renaming;
5413 int defns_mark = result.size ();
5415 symbol_name_matcher_ftype *name_match
5416 = ada_get_symbol_name_matcher (lookup_name);
5418 for (renaming = block_using (block);
5420 renaming = renaming->next)
5424 /* Avoid infinite recursions: skip this renaming if we are actually
5425 already traversing it.
5427 Currently, symbol lookup in Ada don't use the namespace machinery from
5428 C++/Fortran support: skip namespace imports that use them. */
5429 if (renaming->searched
5430 || (renaming->import_src != NULL
5431 && renaming->import_src[0] != '\0')
5432 || (renaming->import_dest != NULL
5433 && renaming->import_dest[0] != '\0'))
5435 renaming->searched = 1;
5437 /* TODO: here, we perform another name-based symbol lookup, which can
5438 pull its own multiple overloads. In theory, we should be able to do
5439 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5440 not a simple name. But in order to do this, we would need to enhance
5441 the DWARF reader to associate a symbol to this renaming, instead of a
5442 name. So, for now, we do something simpler: re-use the C++/Fortran
5443 namespace machinery. */
5444 r_name = (renaming->alias != NULL
5446 : renaming->declaration);
5447 if (name_match (r_name, lookup_name, NULL))
5449 lookup_name_info decl_lookup_name (renaming->declaration,
5450 lookup_name.match_type ());
5451 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5454 renaming->searched = 0;
5456 return result.size () != defns_mark;
5459 /* Implements compare_names, but only applying the comparision using
5460 the given CASING. */
5463 compare_names_with_case (const char *string1, const char *string2,
5464 enum case_sensitivity casing)
5466 while (*string1 != '\0' && *string2 != '\0')
5470 if (isspace (*string1) || isspace (*string2))
5471 return strcmp_iw_ordered (string1, string2);
5473 if (casing == case_sensitive_off)
5475 c1 = tolower (*string1);
5476 c2 = tolower (*string2);
5493 return strcmp_iw_ordered (string1, string2);
5495 if (*string2 == '\0')
5497 if (is_name_suffix (string1))
5504 if (*string2 == '(')
5505 return strcmp_iw_ordered (string1, string2);
5508 if (casing == case_sensitive_off)
5509 return tolower (*string1) - tolower (*string2);
5511 return *string1 - *string2;
5516 /* Compare STRING1 to STRING2, with results as for strcmp.
5517 Compatible with strcmp_iw_ordered in that...
5519 strcmp_iw_ordered (STRING1, STRING2) <= 0
5523 compare_names (STRING1, STRING2) <= 0
5525 (they may differ as to what symbols compare equal). */
5528 compare_names (const char *string1, const char *string2)
5532 /* Similar to what strcmp_iw_ordered does, we need to perform
5533 a case-insensitive comparison first, and only resort to
5534 a second, case-sensitive, comparison if the first one was
5535 not sufficient to differentiate the two strings. */
5537 result = compare_names_with_case (string1, string2, case_sensitive_off);
5539 result = compare_names_with_case (string1, string2, case_sensitive_on);
5544 /* Convenience function to get at the Ada encoded lookup name for
5545 LOOKUP_NAME, as a C string. */
5548 ada_lookup_name (const lookup_name_info &lookup_name)
5550 return lookup_name.ada ().lookup_name ().c_str ();
5553 /* A helper for add_nonlocal_symbols. Call expand_matching_symbols
5554 for OBJFILE, then walk the objfile's symtabs and update the
5558 map_matching_symbols (struct objfile *objfile,
5559 const lookup_name_info &lookup_name,
5565 data.objfile = objfile;
5566 objfile->expand_matching_symbols (lookup_name, domain, global,
5567 is_wild_match ? nullptr : compare_names);
5569 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5570 for (compunit_symtab *symtab : objfile->compunits ())
5572 const struct block *block
5573 = symtab->blockvector ()->block (block_kind);
5574 if (!iterate_over_symbols_terminated (block, lookup_name,
5580 /* Add to RESULT all non-local symbols whose name and domain match
5581 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5582 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5583 symbols otherwise. */
5586 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5587 const lookup_name_info &lookup_name,
5588 domain_enum domain, int global)
5590 struct match_data data (&result);
5592 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5594 for (objfile *objfile : current_program_space->objfiles ())
5596 map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5599 for (compunit_symtab *cu : objfile->compunits ())
5601 const struct block *global_block
5602 = cu->blockvector ()->global_block ();
5604 if (ada_add_block_renamings (result, global_block, lookup_name,
5606 data.found_sym = true;
5610 if (result.empty () && global && !is_wild_match)
5612 const char *name = ada_lookup_name (lookup_name);
5613 std::string bracket_name = std::string ("<_ada_") + name + '>';
5614 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5616 for (objfile *objfile : current_program_space->objfiles ())
5617 map_matching_symbols (objfile, name1, false, domain, global, data);
5621 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5622 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5623 returning the number of matches. Add these to RESULT.
5625 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5626 symbol match within the nest of blocks whose innermost member is BLOCK,
5627 is the one match returned (no other matches in that or
5628 enclosing blocks is returned). If there are any matches in or
5629 surrounding BLOCK, then these alone are returned.
5631 Names prefixed with "standard__" are handled specially:
5632 "standard__" is first stripped off (by the lookup_name
5633 constructor), and only static and global symbols are searched.
5635 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5636 to lookup global symbols. */
5639 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5640 const struct block *block,
5641 const lookup_name_info &lookup_name,
5644 int *made_global_lookup_p)
5648 if (made_global_lookup_p)
5649 *made_global_lookup_p = 0;
5651 /* Special case: If the user specifies a symbol name inside package
5652 Standard, do a non-wild matching of the symbol name without
5653 the "standard__" prefix. This was primarily introduced in order
5654 to allow the user to specifically access the standard exceptions
5655 using, for instance, Standard.Constraint_Error when Constraint_Error
5656 is ambiguous (due to the user defining its own Constraint_Error
5657 entity inside its program). */
5658 if (lookup_name.ada ().standard_p ())
5661 /* Check the non-global symbols. If we have ANY match, then we're done. */
5666 ada_add_local_symbols (result, lookup_name, block, domain);
5669 /* In the !full_search case we're are being called by
5670 iterate_over_symbols, and we don't want to search
5672 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5674 if (!result.empty () || !full_search)
5678 /* No non-global symbols found. Check our cache to see if we have
5679 already performed this search before. If we have, then return
5682 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5683 domain, &sym, &block))
5686 add_defn_to_vec (result, sym, block);
5690 if (made_global_lookup_p)
5691 *made_global_lookup_p = 1;
5693 /* Search symbols from all global blocks. */
5695 add_nonlocal_symbols (result, lookup_name, domain, 1);
5697 /* Now add symbols from all per-file blocks if we've gotten no hits
5698 (not strictly correct, but perhaps better than an error). */
5700 if (result.empty ())
5701 add_nonlocal_symbols (result, lookup_name, domain, 0);
5704 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5705 is non-zero, enclosing scope and in global scopes.
5707 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5708 blocks and symbol tables (if any) in which they were found.
5710 When full_search is non-zero, any non-function/non-enumeral
5711 symbol match within the nest of blocks whose innermost member is BLOCK,
5712 is the one match returned (no other matches in that or
5713 enclosing blocks is returned). If there are any matches in or
5714 surrounding BLOCK, then these alone are returned.
5716 Names prefixed with "standard__" are handled specially: "standard__"
5717 is first stripped off, and only static and global symbols are searched. */
5719 static std::vector<struct block_symbol>
5720 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5721 const struct block *block,
5725 int syms_from_global_search;
5726 std::vector<struct block_symbol> results;
5728 ada_add_all_symbols (results, block, lookup_name,
5729 domain, full_search, &syms_from_global_search);
5731 remove_extra_symbols (&results);
5733 if (results.empty () && full_search && syms_from_global_search)
5734 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5736 if (results.size () == 1 && full_search && syms_from_global_search)
5737 cache_symbol (ada_lookup_name (lookup_name), domain,
5738 results[0].symbol, results[0].block);
5740 remove_irrelevant_renamings (&results, block);
5744 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5745 in global scopes, returning (SYM,BLOCK) tuples.
5747 See ada_lookup_symbol_list_worker for further details. */
5749 std::vector<struct block_symbol>
5750 ada_lookup_symbol_list (const char *name, const struct block *block,
5753 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5754 lookup_name_info lookup_name (name, name_match_type);
5756 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5759 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5760 to 1, but choosing the first symbol found if there are multiple
5763 The result is stored in *INFO, which must be non-NULL.
5764 If no match is found, INFO->SYM is set to NULL. */
5767 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5769 struct block_symbol *info)
5771 /* Since we already have an encoded name, wrap it in '<>' to force a
5772 verbatim match. Otherwise, if the name happens to not look like
5773 an encoded name (because it doesn't include a "__"),
5774 ada_lookup_name_info would re-encode/fold it again, and that
5775 would e.g., incorrectly lowercase object renaming names like
5776 "R28b" -> "r28b". */
5777 std::string verbatim = add_angle_brackets (name);
5779 gdb_assert (info != NULL);
5780 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5783 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5784 scope and in global scopes, or NULL if none. NAME is folded and
5785 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5786 choosing the first symbol if there are multiple choices. */
5789 ada_lookup_symbol (const char *name, const struct block *block0,
5792 std::vector<struct block_symbol> candidates
5793 = ada_lookup_symbol_list (name, block0, domain);
5795 if (candidates.empty ())
5798 block_symbol info = candidates[0];
5799 info.symbol = fixup_symbol_section (info.symbol, NULL);
5804 /* True iff STR is a possible encoded suffix of a normal Ada name
5805 that is to be ignored for matching purposes. Suffixes of parallel
5806 names (e.g., XVE) are not included here. Currently, the possible suffixes
5807 are given by any of the regular expressions:
5809 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5810 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5811 TKB [subprogram suffix for task bodies]
5812 _E[0-9]+[bs]$ [protected object entry suffixes]
5813 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5815 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5816 match is performed. This sequence is used to differentiate homonyms,
5817 is an optional part of a valid name suffix. */
5820 is_name_suffix (const char *str)
5823 const char *matching;
5824 const int len = strlen (str);
5826 /* Skip optional leading __[0-9]+. */
5828 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5831 while (isdigit (str[0]))
5837 if (str[0] == '.' || str[0] == '$')
5840 while (isdigit (matching[0]))
5842 if (matching[0] == '\0')
5848 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5851 while (isdigit (matching[0]))
5853 if (matching[0] == '\0')
5857 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5859 if (strcmp (str, "TKB") == 0)
5863 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5864 with a N at the end. Unfortunately, the compiler uses the same
5865 convention for other internal types it creates. So treating
5866 all entity names that end with an "N" as a name suffix causes
5867 some regressions. For instance, consider the case of an enumerated
5868 type. To support the 'Image attribute, it creates an array whose
5870 Having a single character like this as a suffix carrying some
5871 information is a bit risky. Perhaps we should change the encoding
5872 to be something like "_N" instead. In the meantime, do not do
5873 the following check. */
5874 /* Protected Object Subprograms */
5875 if (len == 1 && str [0] == 'N')
5880 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5883 while (isdigit (matching[0]))
5885 if ((matching[0] == 'b' || matching[0] == 's')
5886 && matching [1] == '\0')
5890 /* ??? We should not modify STR directly, as we are doing below. This
5891 is fine in this case, but may become problematic later if we find
5892 that this alternative did not work, and want to try matching
5893 another one from the begining of STR. Since we modified it, we
5894 won't be able to find the begining of the string anymore! */
5898 while (str[0] != '_' && str[0] != '\0')
5900 if (str[0] != 'n' && str[0] != 'b')
5906 if (str[0] == '\000')
5911 if (str[1] != '_' || str[2] == '\000')
5915 if (strcmp (str + 3, "JM") == 0)
5917 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5918 the LJM suffix in favor of the JM one. But we will
5919 still accept LJM as a valid suffix for a reasonable
5920 amount of time, just to allow ourselves to debug programs
5921 compiled using an older version of GNAT. */
5922 if (strcmp (str + 3, "LJM") == 0)
5926 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5927 || str[4] == 'U' || str[4] == 'P')
5929 if (str[4] == 'R' && str[5] != 'T')
5933 if (!isdigit (str[2]))
5935 for (k = 3; str[k] != '\0'; k += 1)
5936 if (!isdigit (str[k]) && str[k] != '_')
5940 if (str[0] == '$' && isdigit (str[1]))
5942 for (k = 2; str[k] != '\0'; k += 1)
5943 if (!isdigit (str[k]) && str[k] != '_')
5950 /* Return non-zero if the string starting at NAME and ending before
5951 NAME_END contains no capital letters. */
5954 is_valid_name_for_wild_match (const char *name0)
5956 std::string decoded_name = ada_decode (name0);
5959 /* If the decoded name starts with an angle bracket, it means that
5960 NAME0 does not follow the GNAT encoding format. It should then
5961 not be allowed as a possible wild match. */
5962 if (decoded_name[0] == '<')
5965 for (i=0; decoded_name[i] != '\0'; i++)
5966 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5972 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5973 character which could start a simple name. Assumes that *NAMEP points
5974 somewhere inside the string beginning at NAME0. */
5977 advance_wild_match (const char **namep, const char *name0, char target0)
5979 const char *name = *namep;
5989 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5992 if (name == name0 + 5 && startswith (name0, "_ada"))
5997 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5998 || name[2] == target0))
6003 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
6005 /* Names like "pkg__B_N__name", where N is a number, are
6006 block-local. We can handle these by simply skipping
6013 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6023 /* Return true iff NAME encodes a name of the form prefix.PATN.
6024 Ignores any informational suffixes of NAME (i.e., for which
6025 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6029 wild_match (const char *name, const char *patn)
6032 const char *name0 = name;
6034 if (startswith (name, "___ghost_"))
6039 const char *match = name;
6043 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6046 if (*p == '\0' && is_name_suffix (name))
6047 return match == name0 || is_valid_name_for_wild_match (name0);
6049 if (name[-1] == '_')
6052 if (!advance_wild_match (&name, name0, *patn))
6057 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6058 necessary). OBJFILE is the section containing BLOCK. */
6061 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6062 const struct block *block,
6063 const lookup_name_info &lookup_name,
6064 domain_enum domain, struct objfile *objfile)
6066 struct block_iterator iter;
6067 /* A matching argument symbol, if any. */
6068 struct symbol *arg_sym;
6069 /* Set true when we find a matching non-argument symbol. */
6075 for (sym = block_iter_match_first (block, lookup_name, &iter);
6077 sym = block_iter_match_next (lookup_name, &iter))
6079 if (symbol_matches_domain (sym->language (), sym->domain (), domain))
6081 if (sym->aclass () != LOC_UNRESOLVED)
6083 if (sym->is_argument ())
6088 add_defn_to_vec (result,
6089 fixup_symbol_section (sym, objfile),
6096 /* Handle renamings. */
6098 if (ada_add_block_renamings (result, block, lookup_name, domain))
6101 if (!found_sym && arg_sym != NULL)
6103 add_defn_to_vec (result,
6104 fixup_symbol_section (arg_sym, objfile),
6108 if (!lookup_name.ada ().wild_match_p ())
6112 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6113 const char *name = ada_lookup_name.c_str ();
6114 size_t name_len = ada_lookup_name.size ();
6116 ALL_BLOCK_SYMBOLS (block, iter, sym)
6118 if (symbol_matches_domain (sym->language (),
6119 sym->domain (), domain))
6123 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6126 cmp = !startswith (sym->linkage_name (), "_ada_");
6128 cmp = strncmp (name, sym->linkage_name () + 5,
6133 && is_name_suffix (sym->linkage_name () + name_len + 5))
6135 if (sym->aclass () != LOC_UNRESOLVED)
6137 if (sym->is_argument ())
6142 add_defn_to_vec (result,
6143 fixup_symbol_section (sym, objfile),
6151 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6152 They aren't parameters, right? */
6153 if (!found_sym && arg_sym != NULL)
6155 add_defn_to_vec (result,
6156 fixup_symbol_section (arg_sym, objfile),
6163 /* Symbol Completion */
6168 ada_lookup_name_info::matches
6169 (const char *sym_name,
6170 symbol_name_match_type match_type,
6171 completion_match_result *comp_match_res) const
6174 const char *text = m_encoded_name.c_str ();
6175 size_t text_len = m_encoded_name.size ();
6177 /* First, test against the fully qualified name of the symbol. */
6179 if (strncmp (sym_name, text, text_len) == 0)
6182 std::string decoded_name = ada_decode (sym_name);
6183 if (match && !m_encoded_p)
6185 /* One needed check before declaring a positive match is to verify
6186 that iff we are doing a verbatim match, the decoded version
6187 of the symbol name starts with '<'. Otherwise, this symbol name
6188 is not a suitable completion. */
6190 bool has_angle_bracket = (decoded_name[0] == '<');
6191 match = (has_angle_bracket == m_verbatim_p);
6194 if (match && !m_verbatim_p)
6196 /* When doing non-verbatim match, another check that needs to
6197 be done is to verify that the potentially matching symbol name
6198 does not include capital letters, because the ada-mode would
6199 not be able to understand these symbol names without the
6200 angle bracket notation. */
6203 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6208 /* Second: Try wild matching... */
6210 if (!match && m_wild_match_p)
6212 /* Since we are doing wild matching, this means that TEXT
6213 may represent an unqualified symbol name. We therefore must
6214 also compare TEXT against the unqualified name of the symbol. */
6215 sym_name = ada_unqualified_name (decoded_name.c_str ());
6217 if (strncmp (sym_name, text, text_len) == 0)
6221 /* Finally: If we found a match, prepare the result to return. */
6226 if (comp_match_res != NULL)
6228 std::string &match_str = comp_match_res->match.storage ();
6231 match_str = ada_decode (sym_name);
6235 match_str = add_angle_brackets (sym_name);
6237 match_str = sym_name;
6241 comp_match_res->set_match (match_str.c_str ());
6249 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6250 for tagged types. */
6253 ada_is_dispatch_table_ptr_type (struct type *type)
6257 if (type->code () != TYPE_CODE_PTR)
6260 name = TYPE_TARGET_TYPE (type)->name ();
6264 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6267 /* Return non-zero if TYPE is an interface tag. */
6270 ada_is_interface_tag (struct type *type)
6272 const char *name = type->name ();
6277 return (strcmp (name, "ada__tags__interface_tag") == 0);
6280 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6281 to be invisible to users. */
6284 ada_is_ignored_field (struct type *type, int field_num)
6286 if (field_num < 0 || field_num > type->num_fields ())
6289 /* Check the name of that field. */
6291 const char *name = type->field (field_num).name ();
6293 /* Anonymous field names should not be printed.
6294 brobecker/2007-02-20: I don't think this can actually happen
6295 but we don't want to print the value of anonymous fields anyway. */
6299 /* Normally, fields whose name start with an underscore ("_")
6300 are fields that have been internally generated by the compiler,
6301 and thus should not be printed. The "_parent" field is special,
6302 however: This is a field internally generated by the compiler
6303 for tagged types, and it contains the components inherited from
6304 the parent type. This field should not be printed as is, but
6305 should not be ignored either. */
6306 if (name[0] == '_' && !startswith (name, "_parent"))
6309 /* The compiler doesn't document this, but sometimes it emits
6310 a field whose name starts with a capital letter, like 'V148s'.
6311 These aren't marked as artificial in any way, but we know they
6312 should be ignored. However, wrapper fields should not be
6314 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6316 /* Wrapper field. */
6318 else if (isupper (name[0]))
6322 /* If this is the dispatch table of a tagged type or an interface tag,
6324 if (ada_is_tagged_type (type, 1)
6325 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6326 || ada_is_interface_tag (type->field (field_num).type ())))
6329 /* Not a special field, so it should not be ignored. */
6333 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6334 pointer or reference type whose ultimate target has a tag field. */
6337 ada_is_tagged_type (struct type *type, int refok)
6339 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6342 /* True iff TYPE represents the type of X'Tag */
6345 ada_is_tag_type (struct type *type)
6347 type = ada_check_typedef (type);
6349 if (type == NULL || type->code () != TYPE_CODE_PTR)
6353 const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
6355 return (name != NULL
6356 && strcmp (name, "ada__tags__dispatch_table") == 0);
6360 /* The type of the tag on VAL. */
6362 static struct type *
6363 ada_tag_type (struct value *val)
6365 return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6368 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6369 retired at Ada 05). */
6372 is_ada95_tag (struct value *tag)
6374 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6377 /* The value of the tag on VAL. */
6379 static struct value *
6380 ada_value_tag (struct value *val)
6382 return ada_value_struct_elt (val, "_tag", 0);
6385 /* The value of the tag on the object of type TYPE whose contents are
6386 saved at VALADDR, if it is non-null, or is at memory address
6389 static struct value *
6390 value_tag_from_contents_and_address (struct type *type,
6391 const gdb_byte *valaddr,
6394 int tag_byte_offset;
6395 struct type *tag_type;
6397 gdb::array_view<const gdb_byte> contents;
6398 if (valaddr != nullptr)
6399 contents = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
6400 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6401 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6404 const gdb_byte *valaddr1 = ((valaddr == NULL)
6406 : valaddr + tag_byte_offset);
6407 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6409 return value_from_contents_and_address (tag_type, valaddr1, address1);
6414 static struct type *
6415 type_from_tag (struct value *tag)
6417 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6419 if (type_name != NULL)
6420 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6424 /* Given a value OBJ of a tagged type, return a value of this
6425 type at the base address of the object. The base address, as
6426 defined in Ada.Tags, it is the address of the primary tag of
6427 the object, and therefore where the field values of its full
6428 view can be fetched. */
6431 ada_tag_value_at_base_address (struct value *obj)
6434 LONGEST offset_to_top = 0;
6435 struct type *ptr_type, *obj_type;
6437 CORE_ADDR base_address;
6439 obj_type = value_type (obj);
6441 /* It is the responsability of the caller to deref pointers. */
6443 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6446 tag = ada_value_tag (obj);
6450 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6452 if (is_ada95_tag (tag))
6455 struct type *offset_type
6456 = language_lookup_primitive_type (language_def (language_ada),
6457 target_gdbarch(), "storage_offset");
6458 ptr_type = lookup_pointer_type (offset_type);
6459 val = value_cast (ptr_type, tag);
6463 /* It is perfectly possible that an exception be raised while
6464 trying to determine the base address, just like for the tag;
6465 see ada_tag_name for more details. We do not print the error
6466 message for the same reason. */
6470 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6473 catch (const gdb_exception_error &e)
6478 /* If offset is null, nothing to do. */
6480 if (offset_to_top == 0)
6483 /* -1 is a special case in Ada.Tags; however, what should be done
6484 is not quite clear from the documentation. So do nothing for
6487 if (offset_to_top == -1)
6490 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6491 top is used. In this situation the offset is stored just after
6492 the tag, in the object itself. */
6493 ULONGEST last = (((ULONGEST) 1) << (8 * TYPE_LENGTH (offset_type) - 1)) - 1;
6494 if (offset_to_top == last)
6496 struct value *tem = value_addr (tag);
6497 tem = value_ptradd (tem, 1);
6498 tem = value_cast (ptr_type, tem);
6499 offset_to_top = value_as_long (value_ind (tem));
6502 if (offset_to_top > 0)
6504 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6505 from the base address. This was however incompatible with
6506 C++ dispatch table: C++ uses a *negative* value to *add*
6507 to the base address. Ada's convention has therefore been
6508 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6509 use the same convention. Here, we support both cases by
6510 checking the sign of OFFSET_TO_TOP. */
6511 offset_to_top = -offset_to_top;
6514 base_address = value_address (obj) + offset_to_top;
6515 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6517 /* Make sure that we have a proper tag at the new address.
6518 Otherwise, offset_to_top is bogus (which can happen when
6519 the object is not initialized yet). */
6524 obj_type = type_from_tag (tag);
6529 return value_from_contents_and_address (obj_type, NULL, base_address);
6532 /* Return the "ada__tags__type_specific_data" type. */
6534 static struct type *
6535 ada_get_tsd_type (struct inferior *inf)
6537 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6539 if (data->tsd_type == 0)
6540 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6541 return data->tsd_type;
6544 /* Return the TSD (type-specific data) associated to the given TAG.
6545 TAG is assumed to be the tag of a tagged-type entity.
6547 May return NULL if we are unable to get the TSD. */
6549 static struct value *
6550 ada_get_tsd_from_tag (struct value *tag)
6555 /* First option: The TSD is simply stored as a field of our TAG.
6556 Only older versions of GNAT would use this format, but we have
6557 to test it first, because there are no visible markers for
6558 the current approach except the absence of that field. */
6560 val = ada_value_struct_elt (tag, "tsd", 1);
6564 /* Try the second representation for the dispatch table (in which
6565 there is no explicit 'tsd' field in the referent of the tag pointer,
6566 and instead the tsd pointer is stored just before the dispatch
6569 type = ada_get_tsd_type (current_inferior());
6572 type = lookup_pointer_type (lookup_pointer_type (type));
6573 val = value_cast (type, tag);
6576 return value_ind (value_ptradd (val, -1));
6579 /* Given the TSD of a tag (type-specific data), return a string
6580 containing the name of the associated type.
6582 May return NULL if we are unable to determine the tag name. */
6584 static gdb::unique_xmalloc_ptr<char>
6585 ada_tag_name_from_tsd (struct value *tsd)
6589 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6592 gdb::unique_xmalloc_ptr<char> buffer
6593 = target_read_string (value_as_address (val), INT_MAX);
6594 if (buffer == nullptr)
6599 /* Let this throw an exception on error. If the data is
6600 uninitialized, we'd rather not have the user see a
6602 const char *folded = ada_fold_name (buffer.get (), true);
6603 return make_unique_xstrdup (folded);
6605 catch (const gdb_exception &)
6611 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6614 Return NULL if the TAG is not an Ada tag, or if we were unable to
6615 determine the name of that tag. */
6617 gdb::unique_xmalloc_ptr<char>
6618 ada_tag_name (struct value *tag)
6620 gdb::unique_xmalloc_ptr<char> name;
6622 if (!ada_is_tag_type (value_type (tag)))
6625 /* It is perfectly possible that an exception be raised while trying
6626 to determine the TAG's name, even under normal circumstances:
6627 The associated variable may be uninitialized or corrupted, for
6628 instance. We do not let any exception propagate past this point.
6629 instead we return NULL.
6631 We also do not print the error message either (which often is very
6632 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6633 the caller print a more meaningful message if necessary. */
6636 struct value *tsd = ada_get_tsd_from_tag (tag);
6639 name = ada_tag_name_from_tsd (tsd);
6641 catch (const gdb_exception_error &e)
6648 /* The parent type of TYPE, or NULL if none. */
6651 ada_parent_type (struct type *type)
6655 type = ada_check_typedef (type);
6657 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6660 for (i = 0; i < type->num_fields (); i += 1)
6661 if (ada_is_parent_field (type, i))
6663 struct type *parent_type = type->field (i).type ();
6665 /* If the _parent field is a pointer, then dereference it. */
6666 if (parent_type->code () == TYPE_CODE_PTR)
6667 parent_type = TYPE_TARGET_TYPE (parent_type);
6668 /* If there is a parallel XVS type, get the actual base type. */
6669 parent_type = ada_get_base_type (parent_type);
6671 return ada_check_typedef (parent_type);
6677 /* True iff field number FIELD_NUM of structure type TYPE contains the
6678 parent-type (inherited) fields of a derived type. Assumes TYPE is
6679 a structure type with at least FIELD_NUM+1 fields. */
6682 ada_is_parent_field (struct type *type, int field_num)
6684 const char *name = ada_check_typedef (type)->field (field_num).name ();
6686 return (name != NULL
6687 && (startswith (name, "PARENT")
6688 || startswith (name, "_parent")));
6691 /* True iff field number FIELD_NUM of structure type TYPE is a
6692 transparent wrapper field (which should be silently traversed when doing
6693 field selection and flattened when printing). Assumes TYPE is a
6694 structure type with at least FIELD_NUM+1 fields. Such fields are always
6698 ada_is_wrapper_field (struct type *type, int field_num)
6700 const char *name = type->field (field_num).name ();
6702 if (name != NULL && strcmp (name, "RETVAL") == 0)
6704 /* This happens in functions with "out" or "in out" parameters
6705 which are passed by copy. For such functions, GNAT describes
6706 the function's return type as being a struct where the return
6707 value is in a field called RETVAL, and where the other "out"
6708 or "in out" parameters are fields of that struct. This is not
6713 return (name != NULL
6714 && (startswith (name, "PARENT")
6715 || strcmp (name, "REP") == 0
6716 || startswith (name, "_parent")
6717 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6720 /* True iff field number FIELD_NUM of structure or union type TYPE
6721 is a variant wrapper. Assumes TYPE is a structure type with at least
6722 FIELD_NUM+1 fields. */
6725 ada_is_variant_part (struct type *type, int field_num)
6727 /* Only Ada types are eligible. */
6728 if (!ADA_TYPE_P (type))
6731 struct type *field_type = type->field (field_num).type ();
6733 return (field_type->code () == TYPE_CODE_UNION
6734 || (is_dynamic_field (type, field_num)
6735 && (TYPE_TARGET_TYPE (field_type)->code ()
6736 == TYPE_CODE_UNION)));
6739 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6740 whose discriminants are contained in the record type OUTER_TYPE,
6741 returns the type of the controlling discriminant for the variant.
6742 May return NULL if the type could not be found. */
6745 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6747 const char *name = ada_variant_discrim_name (var_type);
6749 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6752 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6753 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6754 represents a 'when others' clause; otherwise 0. */
6757 ada_is_others_clause (struct type *type, int field_num)
6759 const char *name = type->field (field_num).name ();
6761 return (name != NULL && name[0] == 'O');
6764 /* Assuming that TYPE0 is the type of the variant part of a record,
6765 returns the name of the discriminant controlling the variant.
6766 The value is valid until the next call to ada_variant_discrim_name. */
6769 ada_variant_discrim_name (struct type *type0)
6771 static std::string result;
6774 const char *discrim_end;
6775 const char *discrim_start;
6777 if (type0->code () == TYPE_CODE_PTR)
6778 type = TYPE_TARGET_TYPE (type0);
6782 name = ada_type_name (type);
6784 if (name == NULL || name[0] == '\000')
6787 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6790 if (startswith (discrim_end, "___XVN"))
6793 if (discrim_end == name)
6796 for (discrim_start = discrim_end; discrim_start != name + 3;
6799 if (discrim_start == name + 1)
6801 if ((discrim_start > name + 3
6802 && startswith (discrim_start - 3, "___"))
6803 || discrim_start[-1] == '.')
6807 result = std::string (discrim_start, discrim_end - discrim_start);
6808 return result.c_str ();
6811 /* Scan STR for a subtype-encoded number, beginning at position K.
6812 Put the position of the character just past the number scanned in
6813 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6814 Return 1 if there was a valid number at the given position, and 0
6815 otherwise. A "subtype-encoded" number consists of the absolute value
6816 in decimal, followed by the letter 'm' to indicate a negative number.
6817 Assumes 0m does not occur. */
6820 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6824 if (!isdigit (str[k]))
6827 /* Do it the hard way so as not to make any assumption about
6828 the relationship of unsigned long (%lu scan format code) and
6831 while (isdigit (str[k]))
6833 RU = RU * 10 + (str[k] - '0');
6840 *R = (-(LONGEST) (RU - 1)) - 1;
6846 /* NOTE on the above: Technically, C does not say what the results of
6847 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6848 number representable as a LONGEST (although either would probably work
6849 in most implementations). When RU>0, the locution in the then branch
6850 above is always equivalent to the negative of RU. */
6857 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6858 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6859 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6862 ada_in_variant (LONGEST val, struct type *type, int field_num)
6864 const char *name = type->field (field_num).name ();
6878 if (!ada_scan_number (name, p + 1, &W, &p))
6888 if (!ada_scan_number (name, p + 1, &L, &p)
6889 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6891 if (val >= L && val <= U)
6903 /* FIXME: Lots of redundancy below. Try to consolidate. */
6905 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6906 ARG_TYPE, extract and return the value of one of its (non-static)
6907 fields. FIELDNO says which field. Differs from value_primitive_field
6908 only in that it can handle packed values of arbitrary type. */
6911 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6912 struct type *arg_type)
6916 arg_type = ada_check_typedef (arg_type);
6917 type = arg_type->field (fieldno).type ();
6919 /* Handle packed fields. It might be that the field is not packed
6920 relative to its containing structure, but the structure itself is
6921 packed; in this case we must take the bit-field path. */
6922 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
6924 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6925 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6927 return ada_value_primitive_packed_val (arg1,
6928 value_contents (arg1).data (),
6929 offset + bit_pos / 8,
6930 bit_pos % 8, bit_size, type);
6933 return value_primitive_field (arg1, offset, fieldno, arg_type);
6936 /* Find field with name NAME in object of type TYPE. If found,
6937 set the following for each argument that is non-null:
6938 - *FIELD_TYPE_P to the field's type;
6939 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6940 an object of that type;
6941 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6942 - *BIT_SIZE_P to its size in bits if the field is packed, and
6944 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6945 fields up to but not including the desired field, or by the total
6946 number of fields if not found. A NULL value of NAME never
6947 matches; the function just counts visible fields in this case.
6949 Notice that we need to handle when a tagged record hierarchy
6950 has some components with the same name, like in this scenario:
6952 type Top_T is tagged record
6958 type Middle_T is new Top.Top_T with record
6959 N : Character := 'a';
6963 type Bottom_T is new Middle.Middle_T with record
6965 C : Character := '5';
6967 A : Character := 'J';
6970 Let's say we now have a variable declared and initialized as follow:
6972 TC : Top_A := new Bottom_T;
6974 And then we use this variable to call this function
6976 procedure Assign (Obj: in out Top_T; TV : Integer);
6980 Assign (Top_T (B), 12);
6982 Now, we're in the debugger, and we're inside that procedure
6983 then and we want to print the value of obj.c:
6985 Usually, the tagged record or one of the parent type owns the
6986 component to print and there's no issue but in this particular
6987 case, what does it mean to ask for Obj.C? Since the actual
6988 type for object is type Bottom_T, it could mean two things: type
6989 component C from the Middle_T view, but also component C from
6990 Bottom_T. So in that "undefined" case, when the component is
6991 not found in the non-resolved type (which includes all the
6992 components of the parent type), then resolve it and see if we
6993 get better luck once expanded.
6995 In the case of homonyms in the derived tagged type, we don't
6996 guaranty anything, and pick the one that's easiest for us
6999 Returns 1 if found, 0 otherwise. */
7002 find_struct_field (const char *name, struct type *type, int offset,
7003 struct type **field_type_p,
7004 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
7008 int parent_offset = -1;
7010 type = ada_check_typedef (type);
7012 if (field_type_p != NULL)
7013 *field_type_p = NULL;
7014 if (byte_offset_p != NULL)
7016 if (bit_offset_p != NULL)
7018 if (bit_size_p != NULL)
7021 for (i = 0; i < type->num_fields (); i += 1)
7023 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7024 type. However, we only need the values to be correct when
7025 the caller asks for them. */
7026 int bit_pos = 0, fld_offset = 0;
7027 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7029 bit_pos = type->field (i).loc_bitpos ();
7030 fld_offset = offset + bit_pos / 8;
7033 const char *t_field_name = type->field (i).name ();
7035 if (t_field_name == NULL)
7038 else if (ada_is_parent_field (type, i))
7040 /* This is a field pointing us to the parent type of a tagged
7041 type. As hinted in this function's documentation, we give
7042 preference to fields in the current record first, so what
7043 we do here is just record the index of this field before
7044 we skip it. If it turns out we couldn't find our field
7045 in the current record, then we'll get back to it and search
7046 inside it whether the field might exist in the parent. */
7052 else if (name != NULL && field_name_match (t_field_name, name))
7054 int bit_size = TYPE_FIELD_BITSIZE (type, i);
7056 if (field_type_p != NULL)
7057 *field_type_p = type->field (i).type ();
7058 if (byte_offset_p != NULL)
7059 *byte_offset_p = fld_offset;
7060 if (bit_offset_p != NULL)
7061 *bit_offset_p = bit_pos % 8;
7062 if (bit_size_p != NULL)
7063 *bit_size_p = bit_size;
7066 else if (ada_is_wrapper_field (type, i))
7068 if (find_struct_field (name, type->field (i).type (), fld_offset,
7069 field_type_p, byte_offset_p, bit_offset_p,
7070 bit_size_p, index_p))
7073 else if (ada_is_variant_part (type, i))
7075 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7078 struct type *field_type
7079 = ada_check_typedef (type->field (i).type ());
7081 for (j = 0; j < field_type->num_fields (); j += 1)
7083 if (find_struct_field (name, field_type->field (j).type (),
7085 + field_type->field (j).loc_bitpos () / 8,
7086 field_type_p, byte_offset_p,
7087 bit_offset_p, bit_size_p, index_p))
7091 else if (index_p != NULL)
7095 /* Field not found so far. If this is a tagged type which
7096 has a parent, try finding that field in the parent now. */
7098 if (parent_offset != -1)
7100 /* As above, only compute the offset when truly needed. */
7101 int fld_offset = offset;
7102 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7104 int bit_pos = type->field (parent_offset).loc_bitpos ();
7105 fld_offset += bit_pos / 8;
7108 if (find_struct_field (name, type->field (parent_offset).type (),
7109 fld_offset, field_type_p, byte_offset_p,
7110 bit_offset_p, bit_size_p, index_p))
7117 /* Number of user-visible fields in record type TYPE. */
7120 num_visible_fields (struct type *type)
7125 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7129 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7130 and search in it assuming it has (class) type TYPE.
7131 If found, return value, else return NULL.
7133 Searches recursively through wrapper fields (e.g., '_parent').
7135 In the case of homonyms in the tagged types, please refer to the
7136 long explanation in find_struct_field's function documentation. */
7138 static struct value *
7139 ada_search_struct_field (const char *name, struct value *arg, int offset,
7143 int parent_offset = -1;
7145 type = ada_check_typedef (type);
7146 for (i = 0; i < type->num_fields (); i += 1)
7148 const char *t_field_name = type->field (i).name ();
7150 if (t_field_name == NULL)
7153 else if (ada_is_parent_field (type, i))
7155 /* This is a field pointing us to the parent type of a tagged
7156 type. As hinted in this function's documentation, we give
7157 preference to fields in the current record first, so what
7158 we do here is just record the index of this field before
7159 we skip it. If it turns out we couldn't find our field
7160 in the current record, then we'll get back to it and search
7161 inside it whether the field might exist in the parent. */
7167 else if (field_name_match (t_field_name, name))
7168 return ada_value_primitive_field (arg, offset, i, type);
7170 else if (ada_is_wrapper_field (type, i))
7172 struct value *v = /* Do not let indent join lines here. */
7173 ada_search_struct_field (name, arg,
7174 offset + type->field (i).loc_bitpos () / 8,
7175 type->field (i).type ());
7181 else if (ada_is_variant_part (type, i))
7183 /* PNH: Do we ever get here? See find_struct_field. */
7185 struct type *field_type = ada_check_typedef (type->field (i).type ());
7186 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7188 for (j = 0; j < field_type->num_fields (); j += 1)
7190 struct value *v = ada_search_struct_field /* Force line
7193 var_offset + field_type->field (j).loc_bitpos () / 8,
7194 field_type->field (j).type ());
7202 /* Field not found so far. If this is a tagged type which
7203 has a parent, try finding that field in the parent now. */
7205 if (parent_offset != -1)
7207 struct value *v = ada_search_struct_field (
7208 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7209 type->field (parent_offset).type ());
7218 static struct value *ada_index_struct_field_1 (int *, struct value *,
7219 int, struct type *);
7222 /* Return field #INDEX in ARG, where the index is that returned by
7223 * find_struct_field through its INDEX_P argument. Adjust the address
7224 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7225 * If found, return value, else return NULL. */
7227 static struct value *
7228 ada_index_struct_field (int index, struct value *arg, int offset,
7231 return ada_index_struct_field_1 (&index, arg, offset, type);
7235 /* Auxiliary function for ada_index_struct_field. Like
7236 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7239 static struct value *
7240 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7244 type = ada_check_typedef (type);
7246 for (i = 0; i < type->num_fields (); i += 1)
7248 if (type->field (i).name () == NULL)
7250 else if (ada_is_wrapper_field (type, i))
7252 struct value *v = /* Do not let indent join lines here. */
7253 ada_index_struct_field_1 (index_p, arg,
7254 offset + type->field (i).loc_bitpos () / 8,
7255 type->field (i).type ());
7261 else if (ada_is_variant_part (type, i))
7263 /* PNH: Do we ever get here? See ada_search_struct_field,
7264 find_struct_field. */
7265 error (_("Cannot assign this kind of variant record"));
7267 else if (*index_p == 0)
7268 return ada_value_primitive_field (arg, offset, i, type);
7275 /* Return a string representation of type TYPE. */
7278 type_as_string (struct type *type)
7280 string_file tmp_stream;
7282 type_print (type, "", &tmp_stream, -1);
7284 return tmp_stream.release ();
7287 /* Given a type TYPE, look up the type of the component of type named NAME.
7288 If DISPP is non-null, add its byte displacement from the beginning of a
7289 structure (pointed to by a value) of type TYPE to *DISPP (does not
7290 work for packed fields).
7292 Matches any field whose name has NAME as a prefix, possibly
7295 TYPE can be either a struct or union. If REFOK, TYPE may also
7296 be a (pointer or reference)+ to a struct or union, and the
7297 ultimate target type will be searched.
7299 Looks recursively into variant clauses and parent types.
7301 In the case of homonyms in the tagged types, please refer to the
7302 long explanation in find_struct_field's function documentation.
7304 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7305 TYPE is not a type of the right kind. */
7307 static struct type *
7308 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7312 int parent_offset = -1;
7317 if (refok && type != NULL)
7320 type = ada_check_typedef (type);
7321 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7323 type = TYPE_TARGET_TYPE (type);
7327 || (type->code () != TYPE_CODE_STRUCT
7328 && type->code () != TYPE_CODE_UNION))
7333 error (_("Type %s is not a structure or union type"),
7334 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7337 type = to_static_fixed_type (type);
7339 for (i = 0; i < type->num_fields (); i += 1)
7341 const char *t_field_name = type->field (i).name ();
7344 if (t_field_name == NULL)
7347 else if (ada_is_parent_field (type, i))
7349 /* This is a field pointing us to the parent type of a tagged
7350 type. As hinted in this function's documentation, we give
7351 preference to fields in the current record first, so what
7352 we do here is just record the index of this field before
7353 we skip it. If it turns out we couldn't find our field
7354 in the current record, then we'll get back to it and search
7355 inside it whether the field might exist in the parent. */
7361 else if (field_name_match (t_field_name, name))
7362 return type->field (i).type ();
7364 else if (ada_is_wrapper_field (type, i))
7366 t = ada_lookup_struct_elt_type (type->field (i).type (), name,
7372 else if (ada_is_variant_part (type, i))
7375 struct type *field_type = ada_check_typedef (type->field (i).type ());
7377 for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7379 /* FIXME pnh 2008/01/26: We check for a field that is
7380 NOT wrapped in a struct, since the compiler sometimes
7381 generates these for unchecked variant types. Revisit
7382 if the compiler changes this practice. */
7383 const char *v_field_name = field_type->field (j).name ();
7385 if (v_field_name != NULL
7386 && field_name_match (v_field_name, name))
7387 t = field_type->field (j).type ();
7389 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
7399 /* Field not found so far. If this is a tagged type which
7400 has a parent, try finding that field in the parent now. */
7402 if (parent_offset != -1)
7406 t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7415 const char *name_str = name != NULL ? name : _("<null>");
7417 error (_("Type %s has no component named %s"),
7418 type_as_string (type).c_str (), name_str);
7424 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7425 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7426 represents an unchecked union (that is, the variant part of a
7427 record that is named in an Unchecked_Union pragma). */
7430 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7432 const char *discrim_name = ada_variant_discrim_name (var_type);
7434 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7438 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7439 within OUTER, determine which variant clause (field number in VAR_TYPE,
7440 numbering from 0) is applicable. Returns -1 if none are. */
7443 ada_which_variant_applies (struct type *var_type, struct value *outer)
7447 const char *discrim_name = ada_variant_discrim_name (var_type);
7448 struct value *discrim;
7449 LONGEST discrim_val;
7451 /* Using plain value_from_contents_and_address here causes problems
7452 because we will end up trying to resolve a type that is currently
7453 being constructed. */
7454 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7455 if (discrim == NULL)
7457 discrim_val = value_as_long (discrim);
7460 for (i = 0; i < var_type->num_fields (); i += 1)
7462 if (ada_is_others_clause (var_type, i))
7464 else if (ada_in_variant (discrim_val, var_type, i))
7468 return others_clause;
7473 /* Dynamic-Sized Records */
7475 /* Strategy: The type ostensibly attached to a value with dynamic size
7476 (i.e., a size that is not statically recorded in the debugging
7477 data) does not accurately reflect the size or layout of the value.
7478 Our strategy is to convert these values to values with accurate,
7479 conventional types that are constructed on the fly. */
7481 /* There is a subtle and tricky problem here. In general, we cannot
7482 determine the size of dynamic records without its data. However,
7483 the 'struct value' data structure, which GDB uses to represent
7484 quantities in the inferior process (the target), requires the size
7485 of the type at the time of its allocation in order to reserve space
7486 for GDB's internal copy of the data. That's why the
7487 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7488 rather than struct value*s.
7490 However, GDB's internal history variables ($1, $2, etc.) are
7491 struct value*s containing internal copies of the data that are not, in
7492 general, the same as the data at their corresponding addresses in
7493 the target. Fortunately, the types we give to these values are all
7494 conventional, fixed-size types (as per the strategy described
7495 above), so that we don't usually have to perform the
7496 'to_fixed_xxx_type' conversions to look at their values.
7497 Unfortunately, there is one exception: if one of the internal
7498 history variables is an array whose elements are unconstrained
7499 records, then we will need to create distinct fixed types for each
7500 element selected. */
7502 /* The upshot of all of this is that many routines take a (type, host
7503 address, target address) triple as arguments to represent a value.
7504 The host address, if non-null, is supposed to contain an internal
7505 copy of the relevant data; otherwise, the program is to consult the
7506 target at the target address. */
7508 /* Assuming that VAL0 represents a pointer value, the result of
7509 dereferencing it. Differs from value_ind in its treatment of
7510 dynamic-sized types. */
7513 ada_value_ind (struct value *val0)
7515 struct value *val = value_ind (val0);
7517 if (ada_is_tagged_type (value_type (val), 0))
7518 val = ada_tag_value_at_base_address (val);
7520 return ada_to_fixed_value (val);
7523 /* The value resulting from dereferencing any "reference to"
7524 qualifiers on VAL0. */
7526 static struct value *
7527 ada_coerce_ref (struct value *val0)
7529 if (value_type (val0)->code () == TYPE_CODE_REF)
7531 struct value *val = val0;
7533 val = coerce_ref (val);
7535 if (ada_is_tagged_type (value_type (val), 0))
7536 val = ada_tag_value_at_base_address (val);
7538 return ada_to_fixed_value (val);
7544 /* Return the bit alignment required for field #F of template type TYPE. */
7547 field_alignment (struct type *type, int f)
7549 const char *name = type->field (f).name ();
7553 /* The field name should never be null, unless the debugging information
7554 is somehow malformed. In this case, we assume the field does not
7555 require any alignment. */
7559 len = strlen (name);
7561 if (!isdigit (name[len - 1]))
7564 if (isdigit (name[len - 2]))
7565 align_offset = len - 2;
7567 align_offset = len - 1;
7569 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7570 return TARGET_CHAR_BIT;
7572 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7575 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7577 static struct symbol *
7578 ada_find_any_type_symbol (const char *name)
7582 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7583 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
7586 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7590 /* Find a type named NAME. Ignores ambiguity. This routine will look
7591 solely for types defined by debug info, it will not search the GDB
7594 static struct type *
7595 ada_find_any_type (const char *name)
7597 struct symbol *sym = ada_find_any_type_symbol (name);
7600 return sym->type ();
7605 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7606 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7607 symbol, in which case it is returned. Otherwise, this looks for
7608 symbols whose name is that of NAME_SYM suffixed with "___XR".
7609 Return symbol if found, and NULL otherwise. */
7612 ada_is_renaming_symbol (struct symbol *name_sym)
7614 const char *name = name_sym->linkage_name ();
7615 return strstr (name, "___XR") != NULL;
7618 /* Because of GNAT encoding conventions, several GDB symbols may match a
7619 given type name. If the type denoted by TYPE0 is to be preferred to
7620 that of TYPE1 for purposes of type printing, return non-zero;
7621 otherwise return 0. */
7624 ada_prefer_type (struct type *type0, struct type *type1)
7628 else if (type0 == NULL)
7630 else if (type1->code () == TYPE_CODE_VOID)
7632 else if (type0->code () == TYPE_CODE_VOID)
7634 else if (type1->name () == NULL && type0->name () != NULL)
7636 else if (ada_is_constrained_packed_array_type (type0))
7638 else if (ada_is_array_descriptor_type (type0)
7639 && !ada_is_array_descriptor_type (type1))
7643 const char *type0_name = type0->name ();
7644 const char *type1_name = type1->name ();
7646 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7647 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7653 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7657 ada_type_name (struct type *type)
7661 return type->name ();
7664 /* Search the list of "descriptive" types associated to TYPE for a type
7665 whose name is NAME. */
7667 static struct type *
7668 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7670 struct type *result, *tmp;
7672 if (ada_ignore_descriptive_types_p)
7675 /* If there no descriptive-type info, then there is no parallel type
7677 if (!HAVE_GNAT_AUX_INFO (type))
7680 result = TYPE_DESCRIPTIVE_TYPE (type);
7681 while (result != NULL)
7683 const char *result_name = ada_type_name (result);
7685 if (result_name == NULL)
7687 warning (_("unexpected null name on descriptive type"));
7691 /* If the names match, stop. */
7692 if (strcmp (result_name, name) == 0)
7695 /* Otherwise, look at the next item on the list, if any. */
7696 if (HAVE_GNAT_AUX_INFO (result))
7697 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7701 /* If not found either, try after having resolved the typedef. */
7706 result = check_typedef (result);
7707 if (HAVE_GNAT_AUX_INFO (result))
7708 result = TYPE_DESCRIPTIVE_TYPE (result);
7714 /* If we didn't find a match, see whether this is a packed array. With
7715 older compilers, the descriptive type information is either absent or
7716 irrelevant when it comes to packed arrays so the above lookup fails.
7717 Fall back to using a parallel lookup by name in this case. */
7718 if (result == NULL && ada_is_constrained_packed_array_type (type))
7719 return ada_find_any_type (name);
7724 /* Find a parallel type to TYPE with the specified NAME, using the
7725 descriptive type taken from the debugging information, if available,
7726 and otherwise using the (slower) name-based method. */
7728 static struct type *
7729 ada_find_parallel_type_with_name (struct type *type, const char *name)
7731 struct type *result = NULL;
7733 if (HAVE_GNAT_AUX_INFO (type))
7734 result = find_parallel_type_by_descriptive_type (type, name);
7736 result = ada_find_any_type (name);
7741 /* Same as above, but specify the name of the parallel type by appending
7742 SUFFIX to the name of TYPE. */
7745 ada_find_parallel_type (struct type *type, const char *suffix)
7748 const char *type_name = ada_type_name (type);
7751 if (type_name == NULL)
7754 len = strlen (type_name);
7756 name = (char *) alloca (len + strlen (suffix) + 1);
7758 strcpy (name, type_name);
7759 strcpy (name + len, suffix);
7761 return ada_find_parallel_type_with_name (type, name);
7764 /* If TYPE is a variable-size record type, return the corresponding template
7765 type describing its fields. Otherwise, return NULL. */
7767 static struct type *
7768 dynamic_template_type (struct type *type)
7770 type = ada_check_typedef (type);
7772 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7773 || ada_type_name (type) == NULL)
7777 int len = strlen (ada_type_name (type));
7779 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7782 return ada_find_parallel_type (type, "___XVE");
7786 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7787 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7790 is_dynamic_field (struct type *templ_type, int field_num)
7792 const char *name = templ_type->field (field_num).name ();
7795 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7796 && strstr (name, "___XVL") != NULL;
7799 /* The index of the variant field of TYPE, or -1 if TYPE does not
7800 represent a variant record type. */
7803 variant_field_index (struct type *type)
7807 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7810 for (f = 0; f < type->num_fields (); f += 1)
7812 if (ada_is_variant_part (type, f))
7818 /* A record type with no fields. */
7820 static struct type *
7821 empty_record (struct type *templ)
7823 struct type *type = alloc_type_copy (templ);
7825 type->set_code (TYPE_CODE_STRUCT);
7826 INIT_NONE_SPECIFIC (type);
7827 type->set_name ("<empty>");
7828 TYPE_LENGTH (type) = 0;
7832 /* An ordinary record type (with fixed-length fields) that describes
7833 the value of type TYPE at VALADDR or ADDRESS (see comments at
7834 the beginning of this section) VAL according to GNAT conventions.
7835 DVAL0 should describe the (portion of a) record that contains any
7836 necessary discriminants. It should be NULL if value_type (VAL) is
7837 an outer-level type (i.e., as opposed to a branch of a variant.) A
7838 variant field (unless unchecked) is replaced by a particular branch
7841 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7842 length are not statically known are discarded. As a consequence,
7843 VALADDR, ADDRESS and DVAL0 are ignored.
7845 NOTE: Limitations: For now, we assume that dynamic fields and
7846 variants occupy whole numbers of bytes. However, they need not be
7850 ada_template_to_fixed_record_type_1 (struct type *type,
7851 const gdb_byte *valaddr,
7852 CORE_ADDR address, struct value *dval0,
7853 int keep_dynamic_fields)
7855 struct value *mark = value_mark ();
7858 int nfields, bit_len;
7864 /* Compute the number of fields in this record type that are going
7865 to be processed: unless keep_dynamic_fields, this includes only
7866 fields whose position and length are static will be processed. */
7867 if (keep_dynamic_fields)
7868 nfields = type->num_fields ();
7872 while (nfields < type->num_fields ()
7873 && !ada_is_variant_part (type, nfields)
7874 && !is_dynamic_field (type, nfields))
7878 rtype = alloc_type_copy (type);
7879 rtype->set_code (TYPE_CODE_STRUCT);
7880 INIT_NONE_SPECIFIC (rtype);
7881 rtype->set_num_fields (nfields);
7883 ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7884 rtype->set_name (ada_type_name (type));
7885 rtype->set_is_fixed_instance (true);
7891 for (f = 0; f < nfields; f += 1)
7893 off = align_up (off, field_alignment (type, f))
7894 + type->field (f).loc_bitpos ();
7895 rtype->field (f).set_loc_bitpos (off);
7896 TYPE_FIELD_BITSIZE (rtype, f) = 0;
7898 if (ada_is_variant_part (type, f))
7903 else if (is_dynamic_field (type, f))
7905 const gdb_byte *field_valaddr = valaddr;
7906 CORE_ADDR field_address = address;
7907 struct type *field_type =
7908 TYPE_TARGET_TYPE (type->field (f).type ());
7912 /* Using plain value_from_contents_and_address here
7913 causes problems because we will end up trying to
7914 resolve a type that is currently being
7916 dval = value_from_contents_and_address_unresolved (rtype,
7919 rtype = value_type (dval);
7924 /* If the type referenced by this field is an aligner type, we need
7925 to unwrap that aligner type, because its size might not be set.
7926 Keeping the aligner type would cause us to compute the wrong
7927 size for this field, impacting the offset of the all the fields
7928 that follow this one. */
7929 if (ada_is_aligner_type (field_type))
7931 long field_offset = type->field (f).loc_bitpos ();
7933 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7934 field_address = cond_offset_target (field_address, field_offset);
7935 field_type = ada_aligned_type (field_type);
7938 field_valaddr = cond_offset_host (field_valaddr,
7939 off / TARGET_CHAR_BIT);
7940 field_address = cond_offset_target (field_address,
7941 off / TARGET_CHAR_BIT);
7943 /* Get the fixed type of the field. Note that, in this case,
7944 we do not want to get the real type out of the tag: if
7945 the current field is the parent part of a tagged record,
7946 we will get the tag of the object. Clearly wrong: the real
7947 type of the parent is not the real type of the child. We
7948 would end up in an infinite loop. */
7949 field_type = ada_get_base_type (field_type);
7950 field_type = ada_to_fixed_type (field_type, field_valaddr,
7951 field_address, dval, 0);
7953 rtype->field (f).set_type (field_type);
7954 rtype->field (f).set_name (type->field (f).name ());
7955 /* The multiplication can potentially overflow. But because
7956 the field length has been size-checked just above, and
7957 assuming that the maximum size is a reasonable value,
7958 an overflow should not happen in practice. So rather than
7959 adding overflow recovery code to this already complex code,
7960 we just assume that it's not going to happen. */
7962 TYPE_LENGTH (rtype->field (f).type ()) * TARGET_CHAR_BIT;
7966 /* Note: If this field's type is a typedef, it is important
7967 to preserve the typedef layer.
7969 Otherwise, we might be transforming a typedef to a fat
7970 pointer (encoding a pointer to an unconstrained array),
7971 into a basic fat pointer (encoding an unconstrained
7972 array). As both types are implemented using the same
7973 structure, the typedef is the only clue which allows us
7974 to distinguish between the two options. Stripping it
7975 would prevent us from printing this field appropriately. */
7976 rtype->field (f).set_type (type->field (f).type ());
7977 rtype->field (f).set_name (type->field (f).name ());
7978 if (TYPE_FIELD_BITSIZE (type, f) > 0)
7980 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7983 struct type *field_type = type->field (f).type ();
7985 /* We need to be careful of typedefs when computing
7986 the length of our field. If this is a typedef,
7987 get the length of the target type, not the length
7989 if (field_type->code () == TYPE_CODE_TYPEDEF)
7990 field_type = ada_typedef_target_type (field_type);
7993 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
7996 if (off + fld_bit_len > bit_len)
7997 bit_len = off + fld_bit_len;
7999 TYPE_LENGTH (rtype) =
8000 align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
8003 /* We handle the variant part, if any, at the end because of certain
8004 odd cases in which it is re-ordered so as NOT to be the last field of
8005 the record. This can happen in the presence of representation
8007 if (variant_field >= 0)
8009 struct type *branch_type;
8011 off = rtype->field (variant_field).loc_bitpos ();
8015 /* Using plain value_from_contents_and_address here causes
8016 problems because we will end up trying to resolve a type
8017 that is currently being constructed. */
8018 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
8020 rtype = value_type (dval);
8026 to_fixed_variant_branch_type
8027 (type->field (variant_field).type (),
8028 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
8029 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
8030 if (branch_type == NULL)
8032 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
8033 rtype->field (f - 1) = rtype->field (f);
8034 rtype->set_num_fields (rtype->num_fields () - 1);
8038 rtype->field (variant_field).set_type (branch_type);
8039 rtype->field (variant_field).set_name ("S");
8041 TYPE_LENGTH (rtype->field (variant_field).type ()) *
8043 if (off + fld_bit_len > bit_len)
8044 bit_len = off + fld_bit_len;
8045 TYPE_LENGTH (rtype) =
8046 align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
8050 /* According to exp_dbug.ads, the size of TYPE for variable-size records
8051 should contain the alignment of that record, which should be a strictly
8052 positive value. If null or negative, then something is wrong, most
8053 probably in the debug info. In that case, we don't round up the size
8054 of the resulting type. If this record is not part of another structure,
8055 the current RTYPE length might be good enough for our purposes. */
8056 if (TYPE_LENGTH (type) <= 0)
8059 warning (_("Invalid type size for `%s' detected: %s."),
8060 rtype->name (), pulongest (TYPE_LENGTH (type)));
8062 warning (_("Invalid type size for <unnamed> detected: %s."),
8063 pulongest (TYPE_LENGTH (type)));
8067 TYPE_LENGTH (rtype) = align_up (TYPE_LENGTH (rtype),
8068 TYPE_LENGTH (type));
8071 value_free_to_mark (mark);
8075 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8078 static struct type *
8079 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8080 CORE_ADDR address, struct value *dval0)
8082 return ada_template_to_fixed_record_type_1 (type, valaddr,
8086 /* An ordinary record type in which ___XVL-convention fields and
8087 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8088 static approximations, containing all possible fields. Uses
8089 no runtime values. Useless for use in values, but that's OK,
8090 since the results are used only for type determinations. Works on both
8091 structs and unions. Representation note: to save space, we memorize
8092 the result of this function in the TYPE_TARGET_TYPE of the
8095 static struct type *
8096 template_to_static_fixed_type (struct type *type0)
8102 /* No need no do anything if the input type is already fixed. */
8103 if (type0->is_fixed_instance ())
8106 /* Likewise if we already have computed the static approximation. */
8107 if (TYPE_TARGET_TYPE (type0) != NULL)
8108 return TYPE_TARGET_TYPE (type0);
8110 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8112 nfields = type0->num_fields ();
8114 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8115 recompute all over next time. */
8116 TYPE_TARGET_TYPE (type0) = type;
8118 for (f = 0; f < nfields; f += 1)
8120 struct type *field_type = type0->field (f).type ();
8121 struct type *new_type;
8123 if (is_dynamic_field (type0, f))
8125 field_type = ada_check_typedef (field_type);
8126 new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
8129 new_type = static_unwrap_type (field_type);
8131 if (new_type != field_type)
8133 /* Clone TYPE0 only the first time we get a new field type. */
8136 TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
8137 type->set_code (type0->code ());
8138 INIT_NONE_SPECIFIC (type);
8139 type->set_num_fields (nfields);
8143 TYPE_ALLOC (type, nfields * sizeof (struct field)));
8144 memcpy (fields, type0->fields (),
8145 sizeof (struct field) * nfields);
8146 type->set_fields (fields);
8148 type->set_name (ada_type_name (type0));
8149 type->set_is_fixed_instance (true);
8150 TYPE_LENGTH (type) = 0;
8152 type->field (f).set_type (new_type);
8153 type->field (f).set_name (type0->field (f).name ());
8160 /* Given an object of type TYPE whose contents are at VALADDR and
8161 whose address in memory is ADDRESS, returns a revision of TYPE,
8162 which should be a non-dynamic-sized record, in which the variant
8163 part, if any, is replaced with the appropriate branch. Looks
8164 for discriminant values in DVAL0, which can be NULL if the record
8165 contains the necessary discriminant values. */
8167 static struct type *
8168 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8169 CORE_ADDR address, struct value *dval0)
8171 struct value *mark = value_mark ();
8174 struct type *branch_type;
8175 int nfields = type->num_fields ();
8176 int variant_field = variant_field_index (type);
8178 if (variant_field == -1)
8183 dval = value_from_contents_and_address (type, valaddr, address);
8184 type = value_type (dval);
8189 rtype = alloc_type_copy (type);
8190 rtype->set_code (TYPE_CODE_STRUCT);
8191 INIT_NONE_SPECIFIC (rtype);
8192 rtype->set_num_fields (nfields);
8195 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8196 memcpy (fields, type->fields (), sizeof (struct field) * nfields);
8197 rtype->set_fields (fields);
8199 rtype->set_name (ada_type_name (type));
8200 rtype->set_is_fixed_instance (true);
8201 TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
8203 branch_type = to_fixed_variant_branch_type
8204 (type->field (variant_field).type (),
8205 cond_offset_host (valaddr,
8206 type->field (variant_field).loc_bitpos ()
8208 cond_offset_target (address,
8209 type->field (variant_field).loc_bitpos ()
8210 / TARGET_CHAR_BIT), dval);
8211 if (branch_type == NULL)
8215 for (f = variant_field + 1; f < nfields; f += 1)
8216 rtype->field (f - 1) = rtype->field (f);
8217 rtype->set_num_fields (rtype->num_fields () - 1);
8221 rtype->field (variant_field).set_type (branch_type);
8222 rtype->field (variant_field).set_name ("S");
8223 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8224 TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
8226 TYPE_LENGTH (rtype) -= TYPE_LENGTH (type->field (variant_field).type ());
8228 value_free_to_mark (mark);
8232 /* An ordinary record type (with fixed-length fields) that describes
8233 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8234 beginning of this section]. Any necessary discriminants' values
8235 should be in DVAL, a record value; it may be NULL if the object
8236 at ADDR itself contains any necessary discriminant values.
8237 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8238 values from the record are needed. Except in the case that DVAL,
8239 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8240 unchecked) is replaced by a particular branch of the variant.
8242 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8243 is questionable and may be removed. It can arise during the
8244 processing of an unconstrained-array-of-record type where all the
8245 variant branches have exactly the same size. This is because in
8246 such cases, the compiler does not bother to use the XVS convention
8247 when encoding the record. I am currently dubious of this
8248 shortcut and suspect the compiler should be altered. FIXME. */
8250 static struct type *
8251 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8252 CORE_ADDR address, struct value *dval)
8254 struct type *templ_type;
8256 if (type0->is_fixed_instance ())
8259 templ_type = dynamic_template_type (type0);
8261 if (templ_type != NULL)
8262 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8263 else if (variant_field_index (type0) >= 0)
8265 if (dval == NULL && valaddr == NULL && address == 0)
8267 return to_record_with_fixed_variant_part (type0, valaddr, address,
8272 type0->set_is_fixed_instance (true);
8278 /* An ordinary record type (with fixed-length fields) that describes
8279 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8280 union type. Any necessary discriminants' values should be in DVAL,
8281 a record value. That is, this routine selects the appropriate
8282 branch of the union at ADDR according to the discriminant value
8283 indicated in the union's type name. Returns VAR_TYPE0 itself if
8284 it represents a variant subject to a pragma Unchecked_Union. */
8286 static struct type *
8287 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8288 CORE_ADDR address, struct value *dval)
8291 struct type *templ_type;
8292 struct type *var_type;
8294 if (var_type0->code () == TYPE_CODE_PTR)
8295 var_type = TYPE_TARGET_TYPE (var_type0);
8297 var_type = var_type0;
8299 templ_type = ada_find_parallel_type (var_type, "___XVU");
8301 if (templ_type != NULL)
8302 var_type = templ_type;
8304 if (is_unchecked_variant (var_type, value_type (dval)))
8306 which = ada_which_variant_applies (var_type, dval);
8309 return empty_record (var_type);
8310 else if (is_dynamic_field (var_type, which))
8311 return to_fixed_record_type
8312 (TYPE_TARGET_TYPE (var_type->field (which).type ()),
8313 valaddr, address, dval);
8314 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8316 to_fixed_record_type
8317 (var_type->field (which).type (), valaddr, address, dval);
8319 return var_type->field (which).type ();
8322 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8323 ENCODING_TYPE, a type following the GNAT conventions for discrete
8324 type encodings, only carries redundant information. */
8327 ada_is_redundant_range_encoding (struct type *range_type,
8328 struct type *encoding_type)
8330 const char *bounds_str;
8334 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8336 if (get_base_type (range_type)->code ()
8337 != get_base_type (encoding_type)->code ())
8339 /* The compiler probably used a simple base type to describe
8340 the range type instead of the range's actual base type,
8341 expecting us to get the real base type from the encoding
8342 anyway. In this situation, the encoding cannot be ignored
8347 if (is_dynamic_type (range_type))
8350 if (encoding_type->name () == NULL)
8353 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8354 if (bounds_str == NULL)
8357 n = 8; /* Skip "___XDLU_". */
8358 if (!ada_scan_number (bounds_str, n, &lo, &n))
8360 if (range_type->bounds ()->low.const_val () != lo)
8363 n += 2; /* Skip the "__" separator between the two bounds. */
8364 if (!ada_scan_number (bounds_str, n, &hi, &n))
8366 if (range_type->bounds ()->high.const_val () != hi)
8372 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8373 a type following the GNAT encoding for describing array type
8374 indices, only carries redundant information. */
8377 ada_is_redundant_index_type_desc (struct type *array_type,
8378 struct type *desc_type)
8380 struct type *this_layer = check_typedef (array_type);
8383 for (i = 0; i < desc_type->num_fields (); i++)
8385 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8386 desc_type->field (i).type ()))
8388 this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
8394 /* Assuming that TYPE0 is an array type describing the type of a value
8395 at ADDR, and that DVAL describes a record containing any
8396 discriminants used in TYPE0, returns a type for the value that
8397 contains no dynamic components (that is, no components whose sizes
8398 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8399 true, gives an error message if the resulting type's size is over
8402 static struct type *
8403 to_fixed_array_type (struct type *type0, struct value *dval,
8406 struct type *index_type_desc;
8407 struct type *result;
8408 int constrained_packed_array_p;
8409 static const char *xa_suffix = "___XA";
8411 type0 = ada_check_typedef (type0);
8412 if (type0->is_fixed_instance ())
8415 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8416 if (constrained_packed_array_p)
8418 type0 = decode_constrained_packed_array_type (type0);
8419 if (type0 == nullptr)
8420 error (_("could not decode constrained packed array type"));
8423 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8425 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8426 encoding suffixed with 'P' may still be generated. If so,
8427 it should be used to find the XA type. */
8429 if (index_type_desc == NULL)
8431 const char *type_name = ada_type_name (type0);
8433 if (type_name != NULL)
8435 const int len = strlen (type_name);
8436 char *name = (char *) alloca (len + strlen (xa_suffix));
8438 if (type_name[len - 1] == 'P')
8440 strcpy (name, type_name);
8441 strcpy (name + len - 1, xa_suffix);
8442 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8447 ada_fixup_array_indexes_type (index_type_desc);
8448 if (index_type_desc != NULL
8449 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8451 /* Ignore this ___XA parallel type, as it does not bring any
8452 useful information. This allows us to avoid creating fixed
8453 versions of the array's index types, which would be identical
8454 to the original ones. This, in turn, can also help avoid
8455 the creation of fixed versions of the array itself. */
8456 index_type_desc = NULL;
8459 if (index_type_desc == NULL)
8461 struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8463 /* NOTE: elt_type---the fixed version of elt_type0---should never
8464 depend on the contents of the array in properly constructed
8466 /* Create a fixed version of the array element type.
8467 We're not providing the address of an element here,
8468 and thus the actual object value cannot be inspected to do
8469 the conversion. This should not be a problem, since arrays of
8470 unconstrained objects are not allowed. In particular, all
8471 the elements of an array of a tagged type should all be of
8472 the same type specified in the debugging info. No need to
8473 consult the object tag. */
8474 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8476 /* Make sure we always create a new array type when dealing with
8477 packed array types, since we're going to fix-up the array
8478 type length and element bitsize a little further down. */
8479 if (elt_type0 == elt_type && !constrained_packed_array_p)
8482 result = create_array_type (alloc_type_copy (type0),
8483 elt_type, type0->index_type ());
8488 struct type *elt_type0;
8491 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8492 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8494 /* NOTE: result---the fixed version of elt_type0---should never
8495 depend on the contents of the array in properly constructed
8497 /* Create a fixed version of the array element type.
8498 We're not providing the address of an element here,
8499 and thus the actual object value cannot be inspected to do
8500 the conversion. This should not be a problem, since arrays of
8501 unconstrained objects are not allowed. In particular, all
8502 the elements of an array of a tagged type should all be of
8503 the same type specified in the debugging info. No need to
8504 consult the object tag. */
8506 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8509 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8511 struct type *range_type =
8512 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8514 result = create_array_type (alloc_type_copy (elt_type0),
8515 result, range_type);
8516 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8520 /* We want to preserve the type name. This can be useful when
8521 trying to get the type name of a value that has already been
8522 printed (for instance, if the user did "print VAR; whatis $". */
8523 result->set_name (type0->name ());
8525 if (constrained_packed_array_p)
8527 /* So far, the resulting type has been created as if the original
8528 type was a regular (non-packed) array type. As a result, the
8529 bitsize of the array elements needs to be set again, and the array
8530 length needs to be recomputed based on that bitsize. */
8531 int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8532 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8534 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8535 TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8536 if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8537 TYPE_LENGTH (result)++;
8540 result->set_is_fixed_instance (true);
8545 /* A standard type (containing no dynamically sized components)
8546 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8547 DVAL describes a record containing any discriminants used in TYPE0,
8548 and may be NULL if there are none, or if the object of type TYPE at
8549 ADDRESS or in VALADDR contains these discriminants.
8551 If CHECK_TAG is not null, in the case of tagged types, this function
8552 attempts to locate the object's tag and use it to compute the actual
8553 type. However, when ADDRESS is null, we cannot use it to determine the
8554 location of the tag, and therefore compute the tagged type's actual type.
8555 So we return the tagged type without consulting the tag. */
8557 static struct type *
8558 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8559 CORE_ADDR address, struct value *dval, int check_tag)
8561 type = ada_check_typedef (type);
8563 /* Only un-fixed types need to be handled here. */
8564 if (!HAVE_GNAT_AUX_INFO (type))
8567 switch (type->code ())
8571 case TYPE_CODE_STRUCT:
8573 struct type *static_type = to_static_fixed_type (type);
8574 struct type *fixed_record_type =
8575 to_fixed_record_type (type, valaddr, address, NULL);
8577 /* If STATIC_TYPE is a tagged type and we know the object's address,
8578 then we can determine its tag, and compute the object's actual
8579 type from there. Note that we have to use the fixed record
8580 type (the parent part of the record may have dynamic fields
8581 and the way the location of _tag is expressed may depend on
8584 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8587 value_tag_from_contents_and_address
8591 struct type *real_type = type_from_tag (tag);
8593 value_from_contents_and_address (fixed_record_type,
8596 fixed_record_type = value_type (obj);
8597 if (real_type != NULL)
8598 return to_fixed_record_type
8600 value_address (ada_tag_value_at_base_address (obj)), NULL);
8603 /* Check to see if there is a parallel ___XVZ variable.
8604 If there is, then it provides the actual size of our type. */
8605 else if (ada_type_name (fixed_record_type) != NULL)
8607 const char *name = ada_type_name (fixed_record_type);
8609 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8610 bool xvz_found = false;
8613 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8616 xvz_found = get_int_var_value (xvz_name, size);
8618 catch (const gdb_exception_error &except)
8620 /* We found the variable, but somehow failed to read
8621 its value. Rethrow the same error, but with a little
8622 bit more information, to help the user understand
8623 what went wrong (Eg: the variable might have been
8625 throw_error (except.error,
8626 _("unable to read value of %s (%s)"),
8627 xvz_name, except.what ());
8630 if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
8632 fixed_record_type = copy_type (fixed_record_type);
8633 TYPE_LENGTH (fixed_record_type) = size;
8635 /* The FIXED_RECORD_TYPE may have be a stub. We have
8636 observed this when the debugging info is STABS, and
8637 apparently it is something that is hard to fix.
8639 In practice, we don't need the actual type definition
8640 at all, because the presence of the XVZ variable allows us
8641 to assume that there must be a XVS type as well, which we
8642 should be able to use later, when we need the actual type
8645 In the meantime, pretend that the "fixed" type we are
8646 returning is NOT a stub, because this can cause trouble
8647 when using this type to create new types targeting it.
8648 Indeed, the associated creation routines often check
8649 whether the target type is a stub and will try to replace
8650 it, thus using a type with the wrong size. This, in turn,
8651 might cause the new type to have the wrong size too.
8652 Consider the case of an array, for instance, where the size
8653 of the array is computed from the number of elements in
8654 our array multiplied by the size of its element. */
8655 fixed_record_type->set_is_stub (false);
8658 return fixed_record_type;
8660 case TYPE_CODE_ARRAY:
8661 return to_fixed_array_type (type, dval, 1);
8662 case TYPE_CODE_UNION:
8666 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8670 /* The same as ada_to_fixed_type_1, except that it preserves the type
8671 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8673 The typedef layer needs be preserved in order to differentiate between
8674 arrays and array pointers when both types are implemented using the same
8675 fat pointer. In the array pointer case, the pointer is encoded as
8676 a typedef of the pointer type. For instance, considering:
8678 type String_Access is access String;
8679 S1 : String_Access := null;
8681 To the debugger, S1 is defined as a typedef of type String. But
8682 to the user, it is a pointer. So if the user tries to print S1,
8683 we should not dereference the array, but print the array address
8686 If we didn't preserve the typedef layer, we would lose the fact that
8687 the type is to be presented as a pointer (needs de-reference before
8688 being printed). And we would also use the source-level type name. */
8691 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8692 CORE_ADDR address, struct value *dval, int check_tag)
8695 struct type *fixed_type =
8696 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8698 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8699 then preserve the typedef layer.
8701 Implementation note: We can only check the main-type portion of
8702 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8703 from TYPE now returns a type that has the same instance flags
8704 as TYPE. For instance, if TYPE is a "typedef const", and its
8705 target type is a "struct", then the typedef elimination will return
8706 a "const" version of the target type. See check_typedef for more
8707 details about how the typedef layer elimination is done.
8709 brobecker/2010-11-19: It seems to me that the only case where it is
8710 useful to preserve the typedef layer is when dealing with fat pointers.
8711 Perhaps, we could add a check for that and preserve the typedef layer
8712 only in that situation. But this seems unnecessary so far, probably
8713 because we call check_typedef/ada_check_typedef pretty much everywhere.
8715 if (type->code () == TYPE_CODE_TYPEDEF
8716 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8717 == TYPE_MAIN_TYPE (fixed_type)))
8723 /* A standard (static-sized) type corresponding as well as possible to
8724 TYPE0, but based on no runtime data. */
8726 static struct type *
8727 to_static_fixed_type (struct type *type0)
8734 if (type0->is_fixed_instance ())
8737 type0 = ada_check_typedef (type0);
8739 switch (type0->code ())
8743 case TYPE_CODE_STRUCT:
8744 type = dynamic_template_type (type0);
8746 return template_to_static_fixed_type (type);
8748 return template_to_static_fixed_type (type0);
8749 case TYPE_CODE_UNION:
8750 type = ada_find_parallel_type (type0, "___XVU");
8752 return template_to_static_fixed_type (type);
8754 return template_to_static_fixed_type (type0);
8758 /* A static approximation of TYPE with all type wrappers removed. */
8760 static struct type *
8761 static_unwrap_type (struct type *type)
8763 if (ada_is_aligner_type (type))
8765 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8766 if (ada_type_name (type1) == NULL)
8767 type1->set_name (ada_type_name (type));
8769 return static_unwrap_type (type1);
8773 struct type *raw_real_type = ada_get_base_type (type);
8775 if (raw_real_type == type)
8778 return to_static_fixed_type (raw_real_type);
8782 /* In some cases, incomplete and private types require
8783 cross-references that are not resolved as records (for example,
8785 type FooP is access Foo;
8787 type Foo is array ...;
8788 ). In these cases, since there is no mechanism for producing
8789 cross-references to such types, we instead substitute for FooP a
8790 stub enumeration type that is nowhere resolved, and whose tag is
8791 the name of the actual type. Call these types "non-record stubs". */
8793 /* A type equivalent to TYPE that is not a non-record stub, if one
8794 exists, otherwise TYPE. */
8797 ada_check_typedef (struct type *type)
8802 /* If our type is an access to an unconstrained array, which is encoded
8803 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8804 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8805 what allows us to distinguish between fat pointers that represent
8806 array types, and fat pointers that represent array access types
8807 (in both cases, the compiler implements them as fat pointers). */
8808 if (ada_is_access_to_unconstrained_array (type))
8811 type = check_typedef (type);
8812 if (type == NULL || type->code () != TYPE_CODE_ENUM
8813 || !type->is_stub ()
8814 || type->name () == NULL)
8818 const char *name = type->name ();
8819 struct type *type1 = ada_find_any_type (name);
8824 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8825 stubs pointing to arrays, as we don't create symbols for array
8826 types, only for the typedef-to-array types). If that's the case,
8827 strip the typedef layer. */
8828 if (type1->code () == TYPE_CODE_TYPEDEF)
8829 type1 = ada_check_typedef (type1);
8835 /* A value representing the data at VALADDR/ADDRESS as described by
8836 type TYPE0, but with a standard (static-sized) type that correctly
8837 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8838 type, then return VAL0 [this feature is simply to avoid redundant
8839 creation of struct values]. */
8841 static struct value *
8842 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8845 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8847 if (type == type0 && val0 != NULL)
8850 if (VALUE_LVAL (val0) != lval_memory)
8852 /* Our value does not live in memory; it could be a convenience
8853 variable, for instance. Create a not_lval value using val0's
8855 return value_from_contents (type, value_contents (val0).data ());
8858 return value_from_contents_and_address (type, 0, address);
8861 /* A value representing VAL, but with a standard (static-sized) type
8862 that correctly describes it. Does not necessarily create a new
8866 ada_to_fixed_value (struct value *val)
8868 val = unwrap_value (val);
8869 val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
8876 /* Table mapping attribute numbers to names.
8877 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
8879 static const char * const attribute_names[] = {
8897 ada_attribute_name (enum exp_opcode n)
8899 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8900 return attribute_names[n - OP_ATR_FIRST + 1];
8902 return attribute_names[0];
8905 /* Evaluate the 'POS attribute applied to ARG. */
8908 pos_atr (struct value *arg)
8910 struct value *val = coerce_ref (arg);
8911 struct type *type = value_type (val);
8913 if (!discrete_type_p (type))
8914 error (_("'POS only defined on discrete types"));
8916 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8917 if (!result.has_value ())
8918 error (_("enumeration value is invalid: can't find 'POS"));
8924 ada_pos_atr (struct type *expect_type,
8925 struct expression *exp,
8926 enum noside noside, enum exp_opcode op,
8929 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8930 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8931 return value_zero (type, not_lval);
8932 return value_from_longest (type, pos_atr (arg));
8935 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8937 static struct value *
8938 val_atr (struct type *type, LONGEST val)
8940 gdb_assert (discrete_type_p (type));
8941 if (type->code () == TYPE_CODE_RANGE)
8942 type = TYPE_TARGET_TYPE (type);
8943 if (type->code () == TYPE_CODE_ENUM)
8945 if (val < 0 || val >= type->num_fields ())
8946 error (_("argument to 'VAL out of range"));
8947 val = type->field (val).loc_enumval ();
8949 return value_from_longest (type, val);
8953 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8955 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8956 return value_zero (type, not_lval);
8958 if (!discrete_type_p (type))
8959 error (_("'VAL only defined on discrete types"));
8960 if (!integer_type_p (value_type (arg)))
8961 error (_("'VAL requires integral argument"));
8963 return val_atr (type, value_as_long (arg));
8969 /* True if TYPE appears to be an Ada character type.
8970 [At the moment, this is true only for Character and Wide_Character;
8971 It is a heuristic test that could stand improvement]. */
8974 ada_is_character_type (struct type *type)
8978 /* If the type code says it's a character, then assume it really is,
8979 and don't check any further. */
8980 if (type->code () == TYPE_CODE_CHAR)
8983 /* Otherwise, assume it's a character type iff it is a discrete type
8984 with a known character type name. */
8985 name = ada_type_name (type);
8986 return (name != NULL
8987 && (type->code () == TYPE_CODE_INT
8988 || type->code () == TYPE_CODE_RANGE)
8989 && (strcmp (name, "character") == 0
8990 || strcmp (name, "wide_character") == 0
8991 || strcmp (name, "wide_wide_character") == 0
8992 || strcmp (name, "unsigned char") == 0));
8995 /* True if TYPE appears to be an Ada string type. */
8998 ada_is_string_type (struct type *type)
9000 type = ada_check_typedef (type);
9002 && type->code () != TYPE_CODE_PTR
9003 && (ada_is_simple_array_type (type)
9004 || ada_is_array_descriptor_type (type))
9005 && ada_array_arity (type) == 1)
9007 struct type *elttype = ada_array_element_type (type, 1);
9009 return ada_is_character_type (elttype);
9015 /* The compiler sometimes provides a parallel XVS type for a given
9016 PAD type. Normally, it is safe to follow the PAD type directly,
9017 but older versions of the compiler have a bug that causes the offset
9018 of its "F" field to be wrong. Following that field in that case
9019 would lead to incorrect results, but this can be worked around
9020 by ignoring the PAD type and using the associated XVS type instead.
9022 Set to True if the debugger should trust the contents of PAD types.
9023 Otherwise, ignore the PAD type if there is a parallel XVS type. */
9024 static bool trust_pad_over_xvs = true;
9026 /* True if TYPE is a struct type introduced by the compiler to force the
9027 alignment of a value. Such types have a single field with a
9028 distinctive name. */
9031 ada_is_aligner_type (struct type *type)
9033 type = ada_check_typedef (type);
9035 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
9038 return (type->code () == TYPE_CODE_STRUCT
9039 && type->num_fields () == 1
9040 && strcmp (type->field (0).name (), "F") == 0);
9043 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
9044 the parallel type. */
9047 ada_get_base_type (struct type *raw_type)
9049 struct type *real_type_namer;
9050 struct type *raw_real_type;
9052 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
9055 if (ada_is_aligner_type (raw_type))
9056 /* The encoding specifies that we should always use the aligner type.
9057 So, even if this aligner type has an associated XVS type, we should
9060 According to the compiler gurus, an XVS type parallel to an aligner
9061 type may exist because of a stabs limitation. In stabs, aligner
9062 types are empty because the field has a variable-sized type, and
9063 thus cannot actually be used as an aligner type. As a result,
9064 we need the associated parallel XVS type to decode the type.
9065 Since the policy in the compiler is to not change the internal
9066 representation based on the debugging info format, we sometimes
9067 end up having a redundant XVS type parallel to the aligner type. */
9070 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9071 if (real_type_namer == NULL
9072 || real_type_namer->code () != TYPE_CODE_STRUCT
9073 || real_type_namer->num_fields () != 1)
9076 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
9078 /* This is an older encoding form where the base type needs to be
9079 looked up by name. We prefer the newer encoding because it is
9081 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
9082 if (raw_real_type == NULL)
9085 return raw_real_type;
9088 /* The field in our XVS type is a reference to the base type. */
9089 return TYPE_TARGET_TYPE (real_type_namer->field (0).type ());
9092 /* The type of value designated by TYPE, with all aligners removed. */
9095 ada_aligned_type (struct type *type)
9097 if (ada_is_aligner_type (type))
9098 return ada_aligned_type (type->field (0).type ());
9100 return ada_get_base_type (type);
9104 /* The address of the aligned value in an object at address VALADDR
9105 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9108 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9110 if (ada_is_aligner_type (type))
9111 return ada_aligned_value_addr
9112 (type->field (0).type (),
9113 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
9120 /* The printed representation of an enumeration literal with encoded
9121 name NAME. The value is good to the next call of ada_enum_name. */
9123 ada_enum_name (const char *name)
9125 static std::string storage;
9128 /* First, unqualify the enumeration name:
9129 1. Search for the last '.' character. If we find one, then skip
9130 all the preceding characters, the unqualified name starts
9131 right after that dot.
9132 2. Otherwise, we may be debugging on a target where the compiler
9133 translates dots into "__". Search forward for double underscores,
9134 but stop searching when we hit an overloading suffix, which is
9135 of the form "__" followed by digits. */
9137 tmp = strrchr (name, '.');
9142 while ((tmp = strstr (name, "__")) != NULL)
9144 if (isdigit (tmp[2]))
9155 if (name[1] == 'U' || name[1] == 'W')
9158 if (name[1] == 'W' && name[2] == 'W')
9160 /* Also handle the QWW case. */
9163 if (sscanf (name + offset, "%x", &v) != 1)
9166 else if (((name[1] >= '0' && name[1] <= '9')
9167 || (name[1] >= 'a' && name[1] <= 'z'))
9170 storage = string_printf ("'%c'", name[1]);
9171 return storage.c_str ();
9176 if (isascii (v) && isprint (v))
9177 storage = string_printf ("'%c'", v);
9178 else if (name[1] == 'U')
9179 storage = string_printf ("'[\"%02x\"]'", v);
9180 else if (name[2] != 'W')
9181 storage = string_printf ("'[\"%04x\"]'", v);
9183 storage = string_printf ("'[\"%06x\"]'", v);
9185 return storage.c_str ();
9189 tmp = strstr (name, "__");
9191 tmp = strstr (name, "$");
9194 storage = std::string (name, tmp - name);
9195 return storage.c_str ();
9202 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9205 static struct value *
9206 unwrap_value (struct value *val)
9208 struct type *type = ada_check_typedef (value_type (val));
9210 if (ada_is_aligner_type (type))
9212 struct value *v = ada_value_struct_elt (val, "F", 0);
9213 struct type *val_type = ada_check_typedef (value_type (v));
9215 if (ada_type_name (val_type) == NULL)
9216 val_type->set_name (ada_type_name (type));
9218 return unwrap_value (v);
9222 struct type *raw_real_type =
9223 ada_check_typedef (ada_get_base_type (type));
9225 /* If there is no parallel XVS or XVE type, then the value is
9226 already unwrapped. Return it without further modification. */
9227 if ((type == raw_real_type)
9228 && ada_find_parallel_type (type, "___XVE") == NULL)
9232 coerce_unspec_val_to_type
9233 (val, ada_to_fixed_type (raw_real_type, 0,
9234 value_address (val),
9239 /* Given two array types T1 and T2, return nonzero iff both arrays
9240 contain the same number of elements. */
9243 ada_same_array_size_p (struct type *t1, struct type *t2)
9245 LONGEST lo1, hi1, lo2, hi2;
9247 /* Get the array bounds in order to verify that the size of
9248 the two arrays match. */
9249 if (!get_array_bounds (t1, &lo1, &hi1)
9250 || !get_array_bounds (t2, &lo2, &hi2))
9251 error (_("unable to determine array bounds"));
9253 /* To make things easier for size comparison, normalize a bit
9254 the case of empty arrays by making sure that the difference
9255 between upper bound and lower bound is always -1. */
9261 return (hi1 - lo1 == hi2 - lo2);
9264 /* Assuming that VAL is an array of integrals, and TYPE represents
9265 an array with the same number of elements, but with wider integral
9266 elements, return an array "casted" to TYPE. In practice, this
9267 means that the returned array is built by casting each element
9268 of the original array into TYPE's (wider) element type. */
9270 static struct value *
9271 ada_promote_array_of_integrals (struct type *type, struct value *val)
9273 struct type *elt_type = TYPE_TARGET_TYPE (type);
9277 /* Verify that both val and type are arrays of scalars, and
9278 that the size of val's elements is smaller than the size
9279 of type's element. */
9280 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9281 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
9282 gdb_assert (value_type (val)->code () == TYPE_CODE_ARRAY);
9283 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
9284 gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
9285 > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
9287 if (!get_array_bounds (type, &lo, &hi))
9288 error (_("unable to determine array bounds"));
9290 value *res = allocate_value (type);
9291 gdb::array_view<gdb_byte> res_contents = value_contents_writeable (res);
9293 /* Promote each array element. */
9294 for (i = 0; i < hi - lo + 1; i++)
9296 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9297 int elt_len = TYPE_LENGTH (elt_type);
9299 copy (value_contents_all (elt), res_contents.slice (elt_len * i, elt_len));
9305 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9306 return the converted value. */
9308 static struct value *
9309 coerce_for_assign (struct type *type, struct value *val)
9311 struct type *type2 = value_type (val);
9316 type2 = ada_check_typedef (type2);
9317 type = ada_check_typedef (type);
9319 if (type2->code () == TYPE_CODE_PTR
9320 && type->code () == TYPE_CODE_ARRAY)
9322 val = ada_value_ind (val);
9323 type2 = value_type (val);
9326 if (type2->code () == TYPE_CODE_ARRAY
9327 && type->code () == TYPE_CODE_ARRAY)
9329 if (!ada_same_array_size_p (type, type2))
9330 error (_("cannot assign arrays of different length"));
9332 if (is_integral_type (TYPE_TARGET_TYPE (type))
9333 && is_integral_type (TYPE_TARGET_TYPE (type2))
9334 && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9335 < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9337 /* Allow implicit promotion of the array elements to
9339 return ada_promote_array_of_integrals (type, val);
9342 if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9343 != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9344 error (_("Incompatible types in assignment"));
9345 deprecated_set_value_type (val, type);
9350 static struct value *
9351 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9354 struct type *type1, *type2;
9357 arg1 = coerce_ref (arg1);
9358 arg2 = coerce_ref (arg2);
9359 type1 = get_base_type (ada_check_typedef (value_type (arg1)));
9360 type2 = get_base_type (ada_check_typedef (value_type (arg2)));
9362 if (type1->code () != TYPE_CODE_INT
9363 || type2->code () != TYPE_CODE_INT)
9364 return value_binop (arg1, arg2, op);
9373 return value_binop (arg1, arg2, op);
9376 v2 = value_as_long (arg2);
9380 if (op == BINOP_MOD)
9382 else if (op == BINOP_DIV)
9386 gdb_assert (op == BINOP_REM);
9390 error (_("second operand of %s must not be zero."), name);
9393 if (type1->is_unsigned () || op == BINOP_MOD)
9394 return value_binop (arg1, arg2, op);
9396 v1 = value_as_long (arg1);
9401 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9402 v += v > 0 ? -1 : 1;
9410 /* Should not reach this point. */
9414 val = allocate_value (type1);
9415 store_unsigned_integer (value_contents_raw (val).data (),
9416 TYPE_LENGTH (value_type (val)),
9417 type_byte_order (type1), v);
9422 ada_value_equal (struct value *arg1, struct value *arg2)
9424 if (ada_is_direct_array_type (value_type (arg1))
9425 || ada_is_direct_array_type (value_type (arg2)))
9427 struct type *arg1_type, *arg2_type;
9429 /* Automatically dereference any array reference before
9430 we attempt to perform the comparison. */
9431 arg1 = ada_coerce_ref (arg1);
9432 arg2 = ada_coerce_ref (arg2);
9434 arg1 = ada_coerce_to_simple_array (arg1);
9435 arg2 = ada_coerce_to_simple_array (arg2);
9437 arg1_type = ada_check_typedef (value_type (arg1));
9438 arg2_type = ada_check_typedef (value_type (arg2));
9440 if (arg1_type->code () != TYPE_CODE_ARRAY
9441 || arg2_type->code () != TYPE_CODE_ARRAY)
9442 error (_("Attempt to compare array with non-array"));
9443 /* FIXME: The following works only for types whose
9444 representations use all bits (no padding or undefined bits)
9445 and do not have user-defined equality. */
9446 return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9447 && memcmp (value_contents (arg1).data (),
9448 value_contents (arg2).data (),
9449 TYPE_LENGTH (arg1_type)) == 0);
9451 return value_equal (arg1, arg2);
9458 check_objfile (const std::unique_ptr<ada_component> &comp,
9459 struct objfile *objfile)
9461 return comp->uses_objfile (objfile);
9464 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9465 component of LHS (a simple array or a record). Does not modify the
9466 inferior's memory, nor does it modify LHS (unless LHS ==
9470 assign_component (struct value *container, struct value *lhs, LONGEST index,
9471 struct expression *exp, operation_up &arg)
9473 scoped_value_mark mark;
9476 struct type *lhs_type = check_typedef (value_type (lhs));
9478 if (lhs_type->code () == TYPE_CODE_ARRAY)
9480 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9481 struct value *index_val = value_from_longest (index_type, index);
9483 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9487 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9488 elt = ada_to_fixed_value (elt);
9491 ada_aggregate_operation *ag_op
9492 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9493 if (ag_op != nullptr)
9494 ag_op->assign_aggregate (container, elt, exp);
9496 value_assign_to_component (container, elt,
9497 arg->evaluate (nullptr, exp,
9502 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9504 for (const auto &item : m_components)
9505 if (item->uses_objfile (objfile))
9511 ada_aggregate_component::dump (ui_file *stream, int depth)
9513 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9514 for (const auto &item : m_components)
9515 item->dump (stream, depth + 1);
9519 ada_aggregate_component::assign (struct value *container,
9520 struct value *lhs, struct expression *exp,
9521 std::vector<LONGEST> &indices,
9522 LONGEST low, LONGEST high)
9524 for (auto &item : m_components)
9525 item->assign (container, lhs, exp, indices, low, high);
9528 /* See ada-exp.h. */
9531 ada_aggregate_operation::assign_aggregate (struct value *container,
9533 struct expression *exp)
9535 struct type *lhs_type;
9536 LONGEST low_index, high_index;
9538 container = ada_coerce_ref (container);
9539 if (ada_is_direct_array_type (value_type (container)))
9540 container = ada_coerce_to_simple_array (container);
9541 lhs = ada_coerce_ref (lhs);
9542 if (!deprecated_value_modifiable (lhs))
9543 error (_("Left operand of assignment is not a modifiable lvalue."));
9545 lhs_type = check_typedef (value_type (lhs));
9546 if (ada_is_direct_array_type (lhs_type))
9548 lhs = ada_coerce_to_simple_array (lhs);
9549 lhs_type = check_typedef (value_type (lhs));
9550 low_index = lhs_type->bounds ()->low.const_val ();
9551 high_index = lhs_type->bounds ()->high.const_val ();
9553 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9556 high_index = num_visible_fields (lhs_type) - 1;
9559 error (_("Left-hand side must be array or record."));
9561 std::vector<LONGEST> indices (4);
9562 indices[0] = indices[1] = low_index - 1;
9563 indices[2] = indices[3] = high_index + 1;
9565 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9566 low_index, high_index);
9572 ada_positional_component::uses_objfile (struct objfile *objfile)
9574 return m_op->uses_objfile (objfile);
9578 ada_positional_component::dump (ui_file *stream, int depth)
9580 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9581 depth, "", m_index);
9582 m_op->dump (stream, depth + 1);
9585 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9586 construct, given that the positions are relative to lower bound
9587 LOW, where HIGH is the upper bound. Record the position in
9588 INDICES. CONTAINER is as for assign_aggregate. */
9590 ada_positional_component::assign (struct value *container,
9591 struct value *lhs, struct expression *exp,
9592 std::vector<LONGEST> &indices,
9593 LONGEST low, LONGEST high)
9595 LONGEST ind = m_index + low;
9597 if (ind - 1 == high)
9598 warning (_("Extra components in aggregate ignored."));
9601 add_component_interval (ind, ind, indices);
9602 assign_component (container, lhs, ind, exp, m_op);
9607 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9609 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9613 ada_discrete_range_association::dump (ui_file *stream, int depth)
9615 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9616 m_low->dump (stream, depth + 1);
9617 m_high->dump (stream, depth + 1);
9621 ada_discrete_range_association::assign (struct value *container,
9623 struct expression *exp,
9624 std::vector<LONGEST> &indices,
9625 LONGEST low, LONGEST high,
9628 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9629 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9631 if (lower <= upper && (lower < low || upper > high))
9632 error (_("Index in component association out of bounds."));
9634 add_component_interval (lower, upper, indices);
9635 while (lower <= upper)
9637 assign_component (container, lhs, lower, exp, op);
9643 ada_name_association::uses_objfile (struct objfile *objfile)
9645 return m_val->uses_objfile (objfile);
9649 ada_name_association::dump (ui_file *stream, int depth)
9651 gdb_printf (stream, _("%*sName:\n"), depth, "");
9652 m_val->dump (stream, depth + 1);
9656 ada_name_association::assign (struct value *container,
9658 struct expression *exp,
9659 std::vector<LONGEST> &indices,
9660 LONGEST low, LONGEST high,
9665 if (ada_is_direct_array_type (value_type (lhs)))
9666 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9670 ada_string_operation *strop
9671 = dynamic_cast<ada_string_operation *> (m_val.get ());
9674 if (strop != nullptr)
9675 name = strop->get_name ();
9678 ada_var_value_operation *vvo
9679 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9681 error (_("Invalid record component association."));
9682 name = vvo->get_symbol ()->natural_name ();
9686 if (! find_struct_field (name, value_type (lhs), 0,
9687 NULL, NULL, NULL, NULL, &index))
9688 error (_("Unknown component name: %s."), name);
9691 add_component_interval (index, index, indices);
9692 assign_component (container, lhs, index, exp, op);
9696 ada_choices_component::uses_objfile (struct objfile *objfile)
9698 if (m_op->uses_objfile (objfile))
9700 for (const auto &item : m_assocs)
9701 if (item->uses_objfile (objfile))
9707 ada_choices_component::dump (ui_file *stream, int depth)
9709 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9710 m_op->dump (stream, depth + 1);
9711 for (const auto &item : m_assocs)
9712 item->dump (stream, depth + 1);
9715 /* Assign into the components of LHS indexed by the OP_CHOICES
9716 construct at *POS, updating *POS past the construct, given that
9717 the allowable indices are LOW..HIGH. Record the indices assigned
9718 to in INDICES. CONTAINER is as for assign_aggregate. */
9720 ada_choices_component::assign (struct value *container,
9721 struct value *lhs, struct expression *exp,
9722 std::vector<LONGEST> &indices,
9723 LONGEST low, LONGEST high)
9725 for (auto &item : m_assocs)
9726 item->assign (container, lhs, exp, indices, low, high, m_op);
9730 ada_others_component::uses_objfile (struct objfile *objfile)
9732 return m_op->uses_objfile (objfile);
9736 ada_others_component::dump (ui_file *stream, int depth)
9738 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9739 m_op->dump (stream, depth + 1);
9742 /* Assign the value of the expression in the OP_OTHERS construct in
9743 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9744 have not been previously assigned. The index intervals already assigned
9745 are in INDICES. CONTAINER is as for assign_aggregate. */
9747 ada_others_component::assign (struct value *container,
9748 struct value *lhs, struct expression *exp,
9749 std::vector<LONGEST> &indices,
9750 LONGEST low, LONGEST high)
9752 int num_indices = indices.size ();
9753 for (int i = 0; i < num_indices - 2; i += 2)
9755 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9756 assign_component (container, lhs, ind, exp, m_op);
9761 ada_assign_operation::evaluate (struct type *expect_type,
9762 struct expression *exp,
9765 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9767 ada_aggregate_operation *ag_op
9768 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9769 if (ag_op != nullptr)
9771 if (noside != EVAL_NORMAL)
9774 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9775 return ada_value_assign (arg1, arg1);
9777 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9778 except if the lhs of our assignment is a convenience variable.
9779 In the case of assigning to a convenience variable, the lhs
9780 should be exactly the result of the evaluation of the rhs. */
9781 struct type *type = value_type (arg1);
9782 if (VALUE_LVAL (arg1) == lval_internalvar)
9784 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9785 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9787 if (VALUE_LVAL (arg1) == lval_internalvar)
9792 arg2 = coerce_for_assign (value_type (arg1), arg2);
9793 return ada_value_assign (arg1, arg2);
9796 } /* namespace expr */
9798 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9799 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9802 add_component_interval (LONGEST low, LONGEST high,
9803 std::vector<LONGEST> &indices)
9807 int size = indices.size ();
9808 for (i = 0; i < size; i += 2) {
9809 if (high >= indices[i] && low <= indices[i + 1])
9813 for (kh = i + 2; kh < size; kh += 2)
9814 if (high < indices[kh])
9816 if (low < indices[i])
9818 indices[i + 1] = indices[kh - 1];
9819 if (high > indices[i + 1])
9820 indices[i + 1] = high;
9821 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9822 indices.resize (kh - i - 2);
9825 else if (high < indices[i])
9829 indices.resize (indices.size () + 2);
9830 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9831 indices[j] = indices[j - 2];
9833 indices[i + 1] = high;
9836 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9839 static struct value *
9840 ada_value_cast (struct type *type, struct value *arg2)
9842 if (type == ada_check_typedef (value_type (arg2)))
9845 return value_cast (type, arg2);
9848 /* Evaluating Ada expressions, and printing their result.
9849 ------------------------------------------------------
9854 We usually evaluate an Ada expression in order to print its value.
9855 We also evaluate an expression in order to print its type, which
9856 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9857 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9858 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9859 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9862 Evaluating expressions is a little more complicated for Ada entities
9863 than it is for entities in languages such as C. The main reason for
9864 this is that Ada provides types whose definition might be dynamic.
9865 One example of such types is variant records. Or another example
9866 would be an array whose bounds can only be known at run time.
9868 The following description is a general guide as to what should be
9869 done (and what should NOT be done) in order to evaluate an expression
9870 involving such types, and when. This does not cover how the semantic
9871 information is encoded by GNAT as this is covered separatly. For the
9872 document used as the reference for the GNAT encoding, see exp_dbug.ads
9873 in the GNAT sources.
9875 Ideally, we should embed each part of this description next to its
9876 associated code. Unfortunately, the amount of code is so vast right
9877 now that it's hard to see whether the code handling a particular
9878 situation might be duplicated or not. One day, when the code is
9879 cleaned up, this guide might become redundant with the comments
9880 inserted in the code, and we might want to remove it.
9882 2. ``Fixing'' an Entity, the Simple Case:
9883 -----------------------------------------
9885 When evaluating Ada expressions, the tricky issue is that they may
9886 reference entities whose type contents and size are not statically
9887 known. Consider for instance a variant record:
9889 type Rec (Empty : Boolean := True) is record
9892 when False => Value : Integer;
9895 Yes : Rec := (Empty => False, Value => 1);
9896 No : Rec := (empty => True);
9898 The size and contents of that record depends on the value of the
9899 descriminant (Rec.Empty). At this point, neither the debugging
9900 information nor the associated type structure in GDB are able to
9901 express such dynamic types. So what the debugger does is to create
9902 "fixed" versions of the type that applies to the specific object.
9903 We also informally refer to this operation as "fixing" an object,
9904 which means creating its associated fixed type.
9906 Example: when printing the value of variable "Yes" above, its fixed
9907 type would look like this:
9914 On the other hand, if we printed the value of "No", its fixed type
9921 Things become a little more complicated when trying to fix an entity
9922 with a dynamic type that directly contains another dynamic type,
9923 such as an array of variant records, for instance. There are
9924 two possible cases: Arrays, and records.
9926 3. ``Fixing'' Arrays:
9927 ---------------------
9929 The type structure in GDB describes an array in terms of its bounds,
9930 and the type of its elements. By design, all elements in the array
9931 have the same type and we cannot represent an array of variant elements
9932 using the current type structure in GDB. When fixing an array,
9933 we cannot fix the array element, as we would potentially need one
9934 fixed type per element of the array. As a result, the best we can do
9935 when fixing an array is to produce an array whose bounds and size
9936 are correct (allowing us to read it from memory), but without having
9937 touched its element type. Fixing each element will be done later,
9938 when (if) necessary.
9940 Arrays are a little simpler to handle than records, because the same
9941 amount of memory is allocated for each element of the array, even if
9942 the amount of space actually used by each element differs from element
9943 to element. Consider for instance the following array of type Rec:
9945 type Rec_Array is array (1 .. 2) of Rec;
9947 The actual amount of memory occupied by each element might be different
9948 from element to element, depending on the value of their discriminant.
9949 But the amount of space reserved for each element in the array remains
9950 fixed regardless. So we simply need to compute that size using
9951 the debugging information available, from which we can then determine
9952 the array size (we multiply the number of elements of the array by
9953 the size of each element).
9955 The simplest case is when we have an array of a constrained element
9956 type. For instance, consider the following type declarations:
9958 type Bounded_String (Max_Size : Integer) is
9960 Buffer : String (1 .. Max_Size);
9962 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9964 In this case, the compiler describes the array as an array of
9965 variable-size elements (identified by its XVS suffix) for which
9966 the size can be read in the parallel XVZ variable.
9968 In the case of an array of an unconstrained element type, the compiler
9969 wraps the array element inside a private PAD type. This type should not
9970 be shown to the user, and must be "unwrap"'ed before printing. Note
9971 that we also use the adjective "aligner" in our code to designate
9972 these wrapper types.
9974 In some cases, the size allocated for each element is statically
9975 known. In that case, the PAD type already has the correct size,
9976 and the array element should remain unfixed.
9978 But there are cases when this size is not statically known.
9979 For instance, assuming that "Five" is an integer variable:
9981 type Dynamic is array (1 .. Five) of Integer;
9982 type Wrapper (Has_Length : Boolean := False) is record
9985 when True => Length : Integer;
9989 type Wrapper_Array is array (1 .. 2) of Wrapper;
9991 Hello : Wrapper_Array := (others => (Has_Length => True,
9992 Data => (others => 17),
9996 The debugging info would describe variable Hello as being an
9997 array of a PAD type. The size of that PAD type is not statically
9998 known, but can be determined using a parallel XVZ variable.
9999 In that case, a copy of the PAD type with the correct size should
10000 be used for the fixed array.
10002 3. ``Fixing'' record type objects:
10003 ----------------------------------
10005 Things are slightly different from arrays in the case of dynamic
10006 record types. In this case, in order to compute the associated
10007 fixed type, we need to determine the size and offset of each of
10008 its components. This, in turn, requires us to compute the fixed
10009 type of each of these components.
10011 Consider for instance the example:
10013 type Bounded_String (Max_Size : Natural) is record
10014 Str : String (1 .. Max_Size);
10017 My_String : Bounded_String (Max_Size => 10);
10019 In that case, the position of field "Length" depends on the size
10020 of field Str, which itself depends on the value of the Max_Size
10021 discriminant. In order to fix the type of variable My_String,
10022 we need to fix the type of field Str. Therefore, fixing a variant
10023 record requires us to fix each of its components.
10025 However, if a component does not have a dynamic size, the component
10026 should not be fixed. In particular, fields that use a PAD type
10027 should not fixed. Here is an example where this might happen
10028 (assuming type Rec above):
10030 type Container (Big : Boolean) is record
10034 when True => Another : Integer;
10035 when False => null;
10038 My_Container : Container := (Big => False,
10039 First => (Empty => True),
10042 In that example, the compiler creates a PAD type for component First,
10043 whose size is constant, and then positions the component After just
10044 right after it. The offset of component After is therefore constant
10047 The debugger computes the position of each field based on an algorithm
10048 that uses, among other things, the actual position and size of the field
10049 preceding it. Let's now imagine that the user is trying to print
10050 the value of My_Container. If the type fixing was recursive, we would
10051 end up computing the offset of field After based on the size of the
10052 fixed version of field First. And since in our example First has
10053 only one actual field, the size of the fixed type is actually smaller
10054 than the amount of space allocated to that field, and thus we would
10055 compute the wrong offset of field After.
10057 To make things more complicated, we need to watch out for dynamic
10058 components of variant records (identified by the ___XVL suffix in
10059 the component name). Even if the target type is a PAD type, the size
10060 of that type might not be statically known. So the PAD type needs
10061 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10062 we might end up with the wrong size for our component. This can be
10063 observed with the following type declarations:
10065 type Octal is new Integer range 0 .. 7;
10066 type Octal_Array is array (Positive range <>) of Octal;
10067 pragma Pack (Octal_Array);
10069 type Octal_Buffer (Size : Positive) is record
10070 Buffer : Octal_Array (1 .. Size);
10074 In that case, Buffer is a PAD type whose size is unset and needs
10075 to be computed by fixing the unwrapped type.
10077 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10078 ----------------------------------------------------------
10080 Lastly, when should the sub-elements of an entity that remained unfixed
10081 thus far, be actually fixed?
10083 The answer is: Only when referencing that element. For instance
10084 when selecting one component of a record, this specific component
10085 should be fixed at that point in time. Or when printing the value
10086 of a record, each component should be fixed before its value gets
10087 printed. Similarly for arrays, the element of the array should be
10088 fixed when printing each element of the array, or when extracting
10089 one element out of that array. On the other hand, fixing should
10090 not be performed on the elements when taking a slice of an array!
10092 Note that one of the side effects of miscomputing the offset and
10093 size of each field is that we end up also miscomputing the size
10094 of the containing type. This can have adverse results when computing
10095 the value of an entity. GDB fetches the value of an entity based
10096 on the size of its type, and thus a wrong size causes GDB to fetch
10097 the wrong amount of memory. In the case where the computed size is
10098 too small, GDB fetches too little data to print the value of our
10099 entity. Results in this case are unpredictable, as we usually read
10100 past the buffer containing the data =:-o. */
10102 /* A helper function for TERNOP_IN_RANGE. */
10105 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10106 enum noside noside,
10107 value *arg1, value *arg2, value *arg3)
10109 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10110 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10111 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10113 value_from_longest (type,
10114 (value_less (arg1, arg3)
10115 || value_equal (arg1, arg3))
10116 && (value_less (arg2, arg1)
10117 || value_equal (arg2, arg1)));
10120 /* A helper function for UNOP_NEG. */
10123 ada_unop_neg (struct type *expect_type,
10124 struct expression *exp,
10125 enum noside noside, enum exp_opcode op,
10126 struct value *arg1)
10128 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10129 return value_neg (arg1);
10132 /* A helper function for UNOP_IN_RANGE. */
10135 ada_unop_in_range (struct type *expect_type,
10136 struct expression *exp,
10137 enum noside noside, enum exp_opcode op,
10138 struct value *arg1, struct type *type)
10140 struct value *arg2, *arg3;
10141 switch (type->code ())
10144 lim_warning (_("Membership test incompletely implemented; "
10145 "always returns true"));
10146 type = language_bool_type (exp->language_defn, exp->gdbarch);
10147 return value_from_longest (type, (LONGEST) 1);
10149 case TYPE_CODE_RANGE:
10150 arg2 = value_from_longest (type,
10151 type->bounds ()->low.const_val ());
10152 arg3 = value_from_longest (type,
10153 type->bounds ()->high.const_val ());
10154 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10155 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10156 type = language_bool_type (exp->language_defn, exp->gdbarch);
10158 value_from_longest (type,
10159 (value_less (arg1, arg3)
10160 || value_equal (arg1, arg3))
10161 && (value_less (arg2, arg1)
10162 || value_equal (arg2, arg1)));
10166 /* A helper function for OP_ATR_TAG. */
10169 ada_atr_tag (struct type *expect_type,
10170 struct expression *exp,
10171 enum noside noside, enum exp_opcode op,
10172 struct value *arg1)
10174 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10175 return value_zero (ada_tag_type (arg1), not_lval);
10177 return ada_value_tag (arg1);
10180 /* A helper function for OP_ATR_SIZE. */
10183 ada_atr_size (struct type *expect_type,
10184 struct expression *exp,
10185 enum noside noside, enum exp_opcode op,
10186 struct value *arg1)
10188 struct type *type = value_type (arg1);
10190 /* If the argument is a reference, then dereference its type, since
10191 the user is really asking for the size of the actual object,
10192 not the size of the pointer. */
10193 if (type->code () == TYPE_CODE_REF)
10194 type = TYPE_TARGET_TYPE (type);
10196 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10197 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10199 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10200 TARGET_CHAR_BIT * TYPE_LENGTH (type));
10203 /* A helper function for UNOP_ABS. */
10206 ada_abs (struct type *expect_type,
10207 struct expression *exp,
10208 enum noside noside, enum exp_opcode op,
10209 struct value *arg1)
10211 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10212 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10213 return value_neg (arg1);
10218 /* A helper function for BINOP_MUL. */
10221 ada_mult_binop (struct type *expect_type,
10222 struct expression *exp,
10223 enum noside noside, enum exp_opcode op,
10224 struct value *arg1, struct value *arg2)
10226 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10228 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10229 return value_zero (value_type (arg1), not_lval);
10233 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10234 return ada_value_binop (arg1, arg2, op);
10238 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10241 ada_equal_binop (struct type *expect_type,
10242 struct expression *exp,
10243 enum noside noside, enum exp_opcode op,
10244 struct value *arg1, struct value *arg2)
10247 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10251 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10252 tem = ada_value_equal (arg1, arg2);
10254 if (op == BINOP_NOTEQUAL)
10256 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10257 return value_from_longest (type, (LONGEST) tem);
10260 /* A helper function for TERNOP_SLICE. */
10263 ada_ternop_slice (struct expression *exp,
10264 enum noside noside,
10265 struct value *array, struct value *low_bound_val,
10266 struct value *high_bound_val)
10269 LONGEST high_bound;
10271 low_bound_val = coerce_ref (low_bound_val);
10272 high_bound_val = coerce_ref (high_bound_val);
10273 low_bound = value_as_long (low_bound_val);
10274 high_bound = value_as_long (high_bound_val);
10276 /* If this is a reference to an aligner type, then remove all
10278 if (value_type (array)->code () == TYPE_CODE_REF
10279 && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
10280 TYPE_TARGET_TYPE (value_type (array)) =
10281 ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
10283 if (ada_is_any_packed_array_type (value_type (array)))
10284 error (_("cannot slice a packed array"));
10286 /* If this is a reference to an array or an array lvalue,
10287 convert to a pointer. */
10288 if (value_type (array)->code () == TYPE_CODE_REF
10289 || (value_type (array)->code () == TYPE_CODE_ARRAY
10290 && VALUE_LVAL (array) == lval_memory))
10291 array = value_addr (array);
10293 if (noside == EVAL_AVOID_SIDE_EFFECTS
10294 && ada_is_array_descriptor_type (ada_check_typedef
10295 (value_type (array))))
10296 return empty_array (ada_type_of_array (array, 0), low_bound,
10299 array = ada_coerce_to_simple_array_ptr (array);
10301 /* If we have more than one level of pointer indirection,
10302 dereference the value until we get only one level. */
10303 while (value_type (array)->code () == TYPE_CODE_PTR
10304 && (TYPE_TARGET_TYPE (value_type (array))->code ()
10306 array = value_ind (array);
10308 /* Make sure we really do have an array type before going further,
10309 to avoid a SEGV when trying to get the index type or the target
10310 type later down the road if the debug info generated by
10311 the compiler is incorrect or incomplete. */
10312 if (!ada_is_simple_array_type (value_type (array)))
10313 error (_("cannot take slice of non-array"));
10315 if (ada_check_typedef (value_type (array))->code ()
10318 struct type *type0 = ada_check_typedef (value_type (array));
10320 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10321 return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
10324 struct type *arr_type0 =
10325 to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
10327 return ada_value_slice_from_ptr (array, arr_type0,
10328 longest_to_int (low_bound),
10329 longest_to_int (high_bound));
10332 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10334 else if (high_bound < low_bound)
10335 return empty_array (value_type (array), low_bound, high_bound);
10337 return ada_value_slice (array, longest_to_int (low_bound),
10338 longest_to_int (high_bound));
10341 /* A helper function for BINOP_IN_BOUNDS. */
10344 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10345 struct value *arg1, struct value *arg2, int n)
10347 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10349 struct type *type = language_bool_type (exp->language_defn,
10351 return value_zero (type, not_lval);
10354 struct type *type = ada_index_type (value_type (arg2), n, "range");
10356 type = value_type (arg1);
10358 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10359 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10361 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10362 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10363 type = language_bool_type (exp->language_defn, exp->gdbarch);
10364 return value_from_longest (type,
10365 (value_less (arg1, arg3)
10366 || value_equal (arg1, arg3))
10367 && (value_less (arg2, arg1)
10368 || value_equal (arg2, arg1)));
10371 /* A helper function for some attribute operations. */
10374 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10375 struct value *arg1, struct type *type_arg, int tem)
10377 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10379 if (type_arg == NULL)
10380 type_arg = value_type (arg1);
10382 if (ada_is_constrained_packed_array_type (type_arg))
10383 type_arg = decode_constrained_packed_array_type (type_arg);
10385 if (!discrete_type_p (type_arg))
10389 default: /* Should never happen. */
10390 error (_("unexpected attribute encountered"));
10393 type_arg = ada_index_type (type_arg, tem,
10394 ada_attribute_name (op));
10396 case OP_ATR_LENGTH:
10397 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10402 return value_zero (type_arg, not_lval);
10404 else if (type_arg == NULL)
10406 arg1 = ada_coerce_ref (arg1);
10408 if (ada_is_constrained_packed_array_type (value_type (arg1)))
10409 arg1 = ada_coerce_to_simple_array (arg1);
10412 if (op == OP_ATR_LENGTH)
10413 type = builtin_type (exp->gdbarch)->builtin_int;
10416 type = ada_index_type (value_type (arg1), tem,
10417 ada_attribute_name (op));
10419 type = builtin_type (exp->gdbarch)->builtin_int;
10424 default: /* Should never happen. */
10425 error (_("unexpected attribute encountered"));
10427 return value_from_longest
10428 (type, ada_array_bound (arg1, tem, 0));
10430 return value_from_longest
10431 (type, ada_array_bound (arg1, tem, 1));
10432 case OP_ATR_LENGTH:
10433 return value_from_longest
10434 (type, ada_array_length (arg1, tem));
10437 else if (discrete_type_p (type_arg))
10439 struct type *range_type;
10440 const char *name = ada_type_name (type_arg);
10443 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10444 range_type = to_fixed_range_type (type_arg, NULL);
10445 if (range_type == NULL)
10446 range_type = type_arg;
10450 error (_("unexpected attribute encountered"));
10452 return value_from_longest
10453 (range_type, ada_discrete_type_low_bound (range_type));
10455 return value_from_longest
10456 (range_type, ada_discrete_type_high_bound (range_type));
10457 case OP_ATR_LENGTH:
10458 error (_("the 'length attribute applies only to array types"));
10461 else if (type_arg->code () == TYPE_CODE_FLT)
10462 error (_("unimplemented type attribute"));
10467 if (ada_is_constrained_packed_array_type (type_arg))
10468 type_arg = decode_constrained_packed_array_type (type_arg);
10471 if (op == OP_ATR_LENGTH)
10472 type = builtin_type (exp->gdbarch)->builtin_int;
10475 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10477 type = builtin_type (exp->gdbarch)->builtin_int;
10483 error (_("unexpected attribute encountered"));
10485 low = ada_array_bound_from_type (type_arg, tem, 0);
10486 return value_from_longest (type, low);
10488 high = ada_array_bound_from_type (type_arg, tem, 1);
10489 return value_from_longest (type, high);
10490 case OP_ATR_LENGTH:
10491 low = ada_array_bound_from_type (type_arg, tem, 0);
10492 high = ada_array_bound_from_type (type_arg, tem, 1);
10493 return value_from_longest (type, high - low + 1);
10498 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10501 ada_binop_minmax (struct type *expect_type,
10502 struct expression *exp,
10503 enum noside noside, enum exp_opcode op,
10504 struct value *arg1, struct value *arg2)
10506 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10507 return value_zero (value_type (arg1), not_lval);
10510 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10511 return value_binop (arg1, arg2, op);
10515 /* A helper function for BINOP_EXP. */
10518 ada_binop_exp (struct type *expect_type,
10519 struct expression *exp,
10520 enum noside noside, enum exp_opcode op,
10521 struct value *arg1, struct value *arg2)
10523 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10524 return value_zero (value_type (arg1), not_lval);
10527 /* For integer exponentiation operations,
10528 only promote the first argument. */
10529 if (is_integral_type (value_type (arg2)))
10530 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10532 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10534 return value_binop (arg1, arg2, op);
10541 /* See ada-exp.h. */
10544 ada_resolvable::replace (operation_up &&owner,
10545 struct expression *exp,
10546 bool deprocedure_p,
10547 bool parse_completion,
10548 innermost_block_tracker *tracker,
10549 struct type *context_type)
10551 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10552 return (make_operation<ada_funcall_operation>
10553 (std::move (owner),
10554 std::vector<operation_up> ()));
10555 return std::move (owner);
10558 /* Convert the character literal whose value would be VAL to the
10559 appropriate value of type TYPE, if there is a translation.
10560 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10561 the literal 'A' (VAL == 65), returns 0. */
10564 convert_char_literal (struct type *type, LONGEST val)
10571 type = check_typedef (type);
10572 if (type->code () != TYPE_CODE_ENUM)
10575 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10576 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10577 else if (val >= 0 && val < 256)
10578 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10579 else if (val >= 0 && val < 0x10000)
10580 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10582 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10583 size_t len = strlen (name);
10584 for (f = 0; f < type->num_fields (); f += 1)
10586 /* Check the suffix because an enum constant in a package will
10587 have a name like "pkg__QUxx". This is safe enough because we
10588 already have the correct type, and because mangling means
10589 there can't be clashes. */
10590 const char *ename = type->field (f).name ();
10591 size_t elen = strlen (ename);
10593 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10594 return type->field (f).loc_enumval ();
10600 ada_char_operation::evaluate (struct type *expect_type,
10601 struct expression *exp,
10602 enum noside noside)
10604 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10605 if (expect_type != nullptr)
10606 result = ada_value_cast (expect_type, result);
10610 /* See ada-exp.h. */
10613 ada_char_operation::replace (operation_up &&owner,
10614 struct expression *exp,
10615 bool deprocedure_p,
10616 bool parse_completion,
10617 innermost_block_tracker *tracker,
10618 struct type *context_type)
10620 operation_up result = std::move (owner);
10622 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10624 gdb_assert (result.get () == this);
10625 std::get<0> (m_storage) = context_type;
10626 std::get<1> (m_storage)
10627 = convert_char_literal (context_type, std::get<1> (m_storage));
10634 ada_wrapped_operation::evaluate (struct type *expect_type,
10635 struct expression *exp,
10636 enum noside noside)
10638 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10639 if (noside == EVAL_NORMAL)
10640 result = unwrap_value (result);
10642 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10643 then we need to perform the conversion manually, because
10644 evaluate_subexp_standard doesn't do it. This conversion is
10645 necessary in Ada because the different kinds of float/fixed
10646 types in Ada have different representations.
10648 Similarly, we need to perform the conversion from OP_LONG
10650 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10651 result = ada_value_cast (expect_type, result);
10657 ada_string_operation::evaluate (struct type *expect_type,
10658 struct expression *exp,
10659 enum noside noside)
10661 struct type *char_type;
10662 if (expect_type != nullptr && ada_is_string_type (expect_type))
10663 char_type = ada_array_element_type (expect_type, 1);
10665 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10667 const std::string &str = std::get<0> (m_storage);
10668 const char *encoding;
10669 switch (TYPE_LENGTH (char_type))
10673 /* Simply copy over the data -- this isn't perhaps strictly
10674 correct according to the encodings, but it is gdb's
10675 historical behavior. */
10676 struct type *stringtype
10677 = lookup_array_range_type (char_type, 1, str.length ());
10678 struct value *val = allocate_value (stringtype);
10679 memcpy (value_contents_raw (val).data (), str.c_str (),
10685 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10686 encoding = "UTF-16BE";
10688 encoding = "UTF-16LE";
10692 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10693 encoding = "UTF-32BE";
10695 encoding = "UTF-32LE";
10699 error (_("unexpected character type size %s"),
10700 pulongest (TYPE_LENGTH (char_type)));
10703 auto_obstack converted;
10704 convert_between_encodings (host_charset (), encoding,
10705 (const gdb_byte *) str.c_str (),
10707 &converted, translit_none);
10709 struct type *stringtype
10710 = lookup_array_range_type (char_type, 1,
10711 obstack_object_size (&converted)
10712 / TYPE_LENGTH (char_type));
10713 struct value *val = allocate_value (stringtype);
10714 memcpy (value_contents_raw (val).data (),
10715 obstack_base (&converted),
10716 obstack_object_size (&converted));
10721 ada_concat_operation::evaluate (struct type *expect_type,
10722 struct expression *exp,
10723 enum noside noside)
10725 /* If one side is a literal, evaluate the other side first so that
10726 the expected type can be set properly. */
10727 const operation_up &lhs_expr = std::get<0> (m_storage);
10728 const operation_up &rhs_expr = std::get<1> (m_storage);
10731 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10733 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10734 lhs = lhs_expr->evaluate (value_type (rhs), exp, noside);
10736 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10738 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10739 struct type *rhs_type = check_typedef (value_type (rhs));
10740 struct type *elt_type = nullptr;
10741 if (rhs_type->code () == TYPE_CODE_ARRAY)
10742 elt_type = TYPE_TARGET_TYPE (rhs_type);
10743 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10745 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10747 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10748 rhs = rhs_expr->evaluate (value_type (lhs), exp, noside);
10750 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10752 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10753 struct type *lhs_type = check_typedef (value_type (lhs));
10754 struct type *elt_type = nullptr;
10755 if (lhs_type->code () == TYPE_CODE_ARRAY)
10756 elt_type = TYPE_TARGET_TYPE (lhs_type);
10757 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10760 return concat_operation::evaluate (expect_type, exp, noside);
10762 return value_concat (lhs, rhs);
10766 ada_qual_operation::evaluate (struct type *expect_type,
10767 struct expression *exp,
10768 enum noside noside)
10770 struct type *type = std::get<1> (m_storage);
10771 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10775 ada_ternop_range_operation::evaluate (struct type *expect_type,
10776 struct expression *exp,
10777 enum noside noside)
10779 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10780 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10781 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10782 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10786 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10787 struct expression *exp,
10788 enum noside noside)
10790 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10791 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10793 auto do_op = [=] (LONGEST x, LONGEST y)
10795 if (std::get<0> (m_storage) == BINOP_ADD)
10800 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10801 return (value_from_longest
10802 (value_type (arg1),
10803 do_op (value_as_long (arg1), value_as_long (arg2))));
10804 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10805 return (value_from_longest
10806 (value_type (arg2),
10807 do_op (value_as_long (arg1), value_as_long (arg2))));
10808 /* Preserve the original type for use by the range case below.
10809 We cannot cast the result to a reference type, so if ARG1 is
10810 a reference type, find its underlying type. */
10811 struct type *type = value_type (arg1);
10812 while (type->code () == TYPE_CODE_REF)
10813 type = TYPE_TARGET_TYPE (type);
10814 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10815 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10816 /* We need to special-case the result with a range.
10817 This is done for the benefit of "ptype". gdb's Ada support
10818 historically used the LHS to set the result type here, so
10819 preserve this behavior. */
10820 if (type->code () == TYPE_CODE_RANGE)
10821 arg1 = value_cast (type, arg1);
10826 ada_unop_atr_operation::evaluate (struct type *expect_type,
10827 struct expression *exp,
10828 enum noside noside)
10830 struct type *type_arg = nullptr;
10831 value *val = nullptr;
10833 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10835 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10836 EVAL_AVOID_SIDE_EFFECTS);
10837 type_arg = value_type (tem);
10840 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10842 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10843 val, type_arg, std::get<2> (m_storage));
10847 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10848 struct expression *exp,
10849 enum noside noside)
10851 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10852 return value_zero (expect_type, not_lval);
10854 const bound_minimal_symbol &b = std::get<0> (m_storage);
10855 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10857 val = ada_value_cast (expect_type, val);
10859 /* Follow the Ada language semantics that do not allow taking
10860 an address of the result of a cast (view conversion in Ada). */
10861 if (VALUE_LVAL (val) == lval_memory)
10863 if (value_lazy (val))
10864 value_fetch_lazy (val);
10865 VALUE_LVAL (val) = not_lval;
10871 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10872 struct expression *exp,
10873 enum noside noside)
10875 value *val = evaluate_var_value (noside,
10876 std::get<0> (m_storage).block,
10877 std::get<0> (m_storage).symbol);
10879 val = ada_value_cast (expect_type, val);
10881 /* Follow the Ada language semantics that do not allow taking
10882 an address of the result of a cast (view conversion in Ada). */
10883 if (VALUE_LVAL (val) == lval_memory)
10885 if (value_lazy (val))
10886 value_fetch_lazy (val);
10887 VALUE_LVAL (val) = not_lval;
10893 ada_var_value_operation::evaluate (struct type *expect_type,
10894 struct expression *exp,
10895 enum noside noside)
10897 symbol *sym = std::get<0> (m_storage).symbol;
10899 if (sym->domain () == UNDEF_DOMAIN)
10900 /* Only encountered when an unresolved symbol occurs in a
10901 context other than a function call, in which case, it is
10903 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10904 sym->print_name ());
10906 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10908 struct type *type = static_unwrap_type (sym->type ());
10909 /* Check to see if this is a tagged type. We also need to handle
10910 the case where the type is a reference to a tagged type, but
10911 we have to be careful to exclude pointers to tagged types.
10912 The latter should be shown as usual (as a pointer), whereas
10913 a reference should mostly be transparent to the user. */
10914 if (ada_is_tagged_type (type, 0)
10915 || (type->code () == TYPE_CODE_REF
10916 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10918 /* Tagged types are a little special in the fact that the real
10919 type is dynamic and can only be determined by inspecting the
10920 object's tag. This means that we need to get the object's
10921 value first (EVAL_NORMAL) and then extract the actual object
10924 Note that we cannot skip the final step where we extract
10925 the object type from its tag, because the EVAL_NORMAL phase
10926 results in dynamic components being resolved into fixed ones.
10927 This can cause problems when trying to print the type
10928 description of tagged types whose parent has a dynamic size:
10929 We use the type name of the "_parent" component in order
10930 to print the name of the ancestor type in the type description.
10931 If that component had a dynamic size, the resolution into
10932 a fixed type would result in the loss of that type name,
10933 thus preventing us from printing the name of the ancestor
10934 type in the type description. */
10935 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10937 if (type->code () != TYPE_CODE_REF)
10939 struct type *actual_type;
10941 actual_type = type_from_tag (ada_value_tag (arg1));
10942 if (actual_type == NULL)
10943 /* If, for some reason, we were unable to determine
10944 the actual type from the tag, then use the static
10945 approximation that we just computed as a fallback.
10946 This can happen if the debugging information is
10947 incomplete, for instance. */
10948 actual_type = type;
10949 return value_zero (actual_type, not_lval);
10953 /* In the case of a ref, ada_coerce_ref takes care
10954 of determining the actual type. But the evaluation
10955 should return a ref as it should be valid to ask
10956 for its address; so rebuild a ref after coerce. */
10957 arg1 = ada_coerce_ref (arg1);
10958 return value_ref (arg1, TYPE_CODE_REF);
10962 /* Records and unions for which GNAT encodings have been
10963 generated need to be statically fixed as well.
10964 Otherwise, non-static fixing produces a type where
10965 all dynamic properties are removed, which prevents "ptype"
10966 from being able to completely describe the type.
10967 For instance, a case statement in a variant record would be
10968 replaced by the relevant components based on the actual
10969 value of the discriminants. */
10970 if ((type->code () == TYPE_CODE_STRUCT
10971 && dynamic_template_type (type) != NULL)
10972 || (type->code () == TYPE_CODE_UNION
10973 && ada_find_parallel_type (type, "___XVU") != NULL))
10974 return value_zero (to_static_fixed_type (type), not_lval);
10977 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10978 return ada_to_fixed_value (arg1);
10982 ada_var_value_operation::resolve (struct expression *exp,
10983 bool deprocedure_p,
10984 bool parse_completion,
10985 innermost_block_tracker *tracker,
10986 struct type *context_type)
10988 symbol *sym = std::get<0> (m_storage).symbol;
10989 if (sym->domain () == UNDEF_DOMAIN)
10991 block_symbol resolved
10992 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10993 context_type, parse_completion,
10994 deprocedure_p, tracker);
10995 std::get<0> (m_storage) = resolved;
10999 && (std::get<0> (m_storage).symbol->type ()->code ()
11000 == TYPE_CODE_FUNC))
11007 ada_atr_val_operation::evaluate (struct type *expect_type,
11008 struct expression *exp,
11009 enum noside noside)
11011 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
11012 return ada_val_atr (noside, std::get<0> (m_storage), arg);
11016 ada_unop_ind_operation::evaluate (struct type *expect_type,
11017 struct expression *exp,
11018 enum noside noside)
11020 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11022 struct type *type = ada_check_typedef (value_type (arg1));
11023 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11025 if (ada_is_array_descriptor_type (type))
11026 /* GDB allows dereferencing GNAT array descriptors. */
11028 struct type *arrType = ada_type_of_array (arg1, 0);
11030 if (arrType == NULL)
11031 error (_("Attempt to dereference null array pointer."));
11032 return value_at_lazy (arrType, 0);
11034 else if (type->code () == TYPE_CODE_PTR
11035 || type->code () == TYPE_CODE_REF
11036 /* In C you can dereference an array to get the 1st elt. */
11037 || type->code () == TYPE_CODE_ARRAY)
11039 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11040 only be determined by inspecting the object's tag.
11041 This means that we need to evaluate completely the
11042 expression in order to get its type. */
11044 if ((type->code () == TYPE_CODE_REF
11045 || type->code () == TYPE_CODE_PTR)
11046 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11048 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11050 type = value_type (ada_value_ind (arg1));
11054 type = to_static_fixed_type
11056 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
11058 return value_zero (type, lval_memory);
11060 else if (type->code () == TYPE_CODE_INT)
11062 /* GDB allows dereferencing an int. */
11063 if (expect_type == NULL)
11064 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11069 to_static_fixed_type (ada_aligned_type (expect_type));
11070 return value_zero (expect_type, lval_memory);
11074 error (_("Attempt to take contents of a non-pointer value."));
11076 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11077 type = ada_check_typedef (value_type (arg1));
11079 if (type->code () == TYPE_CODE_INT)
11080 /* GDB allows dereferencing an int. If we were given
11081 the expect_type, then use that as the target type.
11082 Otherwise, assume that the target type is an int. */
11084 if (expect_type != NULL)
11085 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11088 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11089 (CORE_ADDR) value_as_address (arg1));
11092 if (ada_is_array_descriptor_type (type))
11093 /* GDB allows dereferencing GNAT array descriptors. */
11094 return ada_coerce_to_simple_array (arg1);
11096 return ada_value_ind (arg1);
11100 ada_structop_operation::evaluate (struct type *expect_type,
11101 struct expression *exp,
11102 enum noside noside)
11104 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11105 const char *str = std::get<1> (m_storage).c_str ();
11106 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11109 struct type *type1 = value_type (arg1);
11111 if (ada_is_tagged_type (type1, 1))
11113 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11115 /* If the field is not found, check if it exists in the
11116 extension of this object's type. This means that we
11117 need to evaluate completely the expression. */
11121 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11123 arg1 = ada_value_struct_elt (arg1, str, 0);
11124 arg1 = unwrap_value (arg1);
11125 type = value_type (ada_to_fixed_value (arg1));
11129 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11131 return value_zero (ada_aligned_type (type), lval_memory);
11135 arg1 = ada_value_struct_elt (arg1, str, 0);
11136 arg1 = unwrap_value (arg1);
11137 return ada_to_fixed_value (arg1);
11142 ada_funcall_operation::evaluate (struct type *expect_type,
11143 struct expression *exp,
11144 enum noside noside)
11146 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11147 int nargs = args_up.size ();
11148 std::vector<value *> argvec (nargs);
11149 operation_up &callee_op = std::get<0> (m_storage);
11151 ada_var_value_operation *avv
11152 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11154 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11155 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11156 avv->get_symbol ()->print_name ());
11158 value *callee = callee_op->evaluate (nullptr, exp, noside);
11159 for (int i = 0; i < args_up.size (); ++i)
11160 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11162 if (ada_is_constrained_packed_array_type
11163 (desc_base_type (value_type (callee))))
11164 callee = ada_coerce_to_simple_array (callee);
11165 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11166 && TYPE_FIELD_BITSIZE (value_type (callee), 0) != 0)
11167 /* This is a packed array that has already been fixed, and
11168 therefore already coerced to a simple array. Nothing further
11171 else if (value_type (callee)->code () == TYPE_CODE_REF)
11173 /* Make sure we dereference references so that all the code below
11174 feels like it's really handling the referenced value. Wrapping
11175 types (for alignment) may be there, so make sure we strip them as
11177 callee = ada_to_fixed_value (coerce_ref (callee));
11179 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11180 && VALUE_LVAL (callee) == lval_memory)
11181 callee = value_addr (callee);
11183 struct type *type = ada_check_typedef (value_type (callee));
11185 /* Ada allows us to implicitly dereference arrays when subscripting
11186 them. So, if this is an array typedef (encoding use for array
11187 access types encoded as fat pointers), strip it now. */
11188 if (type->code () == TYPE_CODE_TYPEDEF)
11189 type = ada_typedef_target_type (type);
11191 if (type->code () == TYPE_CODE_PTR)
11193 switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
11195 case TYPE_CODE_FUNC:
11196 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11198 case TYPE_CODE_ARRAY:
11200 case TYPE_CODE_STRUCT:
11201 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11202 callee = ada_value_ind (callee);
11203 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11206 error (_("cannot subscript or call something of type `%s'"),
11207 ada_type_name (value_type (callee)));
11212 switch (type->code ())
11214 case TYPE_CODE_FUNC:
11215 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11217 if (TYPE_TARGET_TYPE (type) == NULL)
11218 error_call_unknown_return_type (NULL);
11219 return allocate_value (TYPE_TARGET_TYPE (type));
11221 return call_function_by_hand (callee, NULL, argvec);
11222 case TYPE_CODE_INTERNAL_FUNCTION:
11223 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11224 /* We don't know anything about what the internal
11225 function might return, but we have to return
11227 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11230 return call_internal_function (exp->gdbarch, exp->language_defn,
11234 case TYPE_CODE_STRUCT:
11238 arity = ada_array_arity (type);
11239 type = ada_array_element_type (type, nargs);
11241 error (_("cannot subscript or call a record"));
11242 if (arity != nargs)
11243 error (_("wrong number of subscripts; expecting %d"), arity);
11244 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11245 return value_zero (ada_aligned_type (type), lval_memory);
11247 unwrap_value (ada_value_subscript
11248 (callee, nargs, argvec.data ()));
11250 case TYPE_CODE_ARRAY:
11251 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11253 type = ada_array_element_type (type, nargs);
11255 error (_("element type of array unknown"));
11257 return value_zero (ada_aligned_type (type), lval_memory);
11260 unwrap_value (ada_value_subscript
11261 (ada_coerce_to_simple_array (callee),
11262 nargs, argvec.data ()));
11263 case TYPE_CODE_PTR: /* Pointer to array */
11264 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11266 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
11267 type = ada_array_element_type (type, nargs);
11269 error (_("element type of array unknown"));
11271 return value_zero (ada_aligned_type (type), lval_memory);
11274 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11278 error (_("Attempt to index or call something other than an "
11279 "array or function"));
11284 ada_funcall_operation::resolve (struct expression *exp,
11285 bool deprocedure_p,
11286 bool parse_completion,
11287 innermost_block_tracker *tracker,
11288 struct type *context_type)
11290 operation_up &callee_op = std::get<0> (m_storage);
11292 ada_var_value_operation *avv
11293 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11294 if (avv == nullptr)
11297 symbol *sym = avv->get_symbol ();
11298 if (sym->domain () != UNDEF_DOMAIN)
11301 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11302 int nargs = args_up.size ();
11303 std::vector<value *> argvec (nargs);
11305 for (int i = 0; i < args_up.size (); ++i)
11306 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11308 const block *block = avv->get_block ();
11309 block_symbol resolved
11310 = ada_resolve_funcall (sym, block,
11311 context_type, parse_completion,
11312 nargs, argvec.data (),
11315 std::get<0> (m_storage)
11316 = make_operation<ada_var_value_operation> (resolved);
11321 ada_ternop_slice_operation::resolve (struct expression *exp,
11322 bool deprocedure_p,
11323 bool parse_completion,
11324 innermost_block_tracker *tracker,
11325 struct type *context_type)
11327 /* Historically this check was done during resolution, so we
11328 continue that here. */
11329 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11330 EVAL_AVOID_SIDE_EFFECTS);
11331 if (ada_is_any_packed_array_type (value_type (v)))
11332 error (_("cannot slice a packed array"));
11340 /* Return non-zero iff TYPE represents a System.Address type. */
11343 ada_is_system_address_type (struct type *type)
11345 return (type->name () && strcmp (type->name (), "system__address") == 0);
11352 /* Scan STR beginning at position K for a discriminant name, and
11353 return the value of that discriminant field of DVAL in *PX. If
11354 PNEW_K is not null, put the position of the character beyond the
11355 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11356 not alter *PX and *PNEW_K if unsuccessful. */
11359 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11362 static std::string storage;
11363 const char *pstart, *pend, *bound;
11364 struct value *bound_val;
11366 if (dval == NULL || str == NULL || str[k] == '\0')
11370 pend = strstr (pstart, "__");
11374 k += strlen (bound);
11378 int len = pend - pstart;
11380 /* Strip __ and beyond. */
11381 storage = std::string (pstart, len);
11382 bound = storage.c_str ();
11386 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
11387 if (bound_val == NULL)
11390 *px = value_as_long (bound_val);
11391 if (pnew_k != NULL)
11396 /* Value of variable named NAME. Only exact matches are considered.
11397 If no such variable found, then if ERR_MSG is null, returns 0, and
11398 otherwise causes an error with message ERR_MSG. */
11400 static struct value *
11401 get_var_value (const char *name, const char *err_msg)
11403 std::string quoted_name = add_angle_brackets (name);
11405 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11407 std::vector<struct block_symbol> syms
11408 = ada_lookup_symbol_list_worker (lookup_name,
11409 get_selected_block (0),
11412 if (syms.size () != 1)
11414 if (err_msg == NULL)
11417 error (("%s"), err_msg);
11420 return value_of_variable (syms[0].symbol, syms[0].block);
11423 /* Value of integer variable named NAME in the current environment.
11424 If no such variable is found, returns false. Otherwise, sets VALUE
11425 to the variable's value and returns true. */
11428 get_int_var_value (const char *name, LONGEST &value)
11430 struct value *var_val = get_var_value (name, 0);
11435 value = value_as_long (var_val);
11440 /* Return a range type whose base type is that of the range type named
11441 NAME in the current environment, and whose bounds are calculated
11442 from NAME according to the GNAT range encoding conventions.
11443 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11444 corresponding range type from debug information; fall back to using it
11445 if symbol lookup fails. If a new type must be created, allocate it
11446 like ORIG_TYPE was. The bounds information, in general, is encoded
11447 in NAME, the base type given in the named range type. */
11449 static struct type *
11450 to_fixed_range_type (struct type *raw_type, struct value *dval)
11453 struct type *base_type;
11454 const char *subtype_info;
11456 gdb_assert (raw_type != NULL);
11457 gdb_assert (raw_type->name () != NULL);
11459 if (raw_type->code () == TYPE_CODE_RANGE)
11460 base_type = TYPE_TARGET_TYPE (raw_type);
11462 base_type = raw_type;
11464 name = raw_type->name ();
11465 subtype_info = strstr (name, "___XD");
11466 if (subtype_info == NULL)
11468 LONGEST L = ada_discrete_type_low_bound (raw_type);
11469 LONGEST U = ada_discrete_type_high_bound (raw_type);
11471 if (L < INT_MIN || U > INT_MAX)
11474 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
11479 int prefix_len = subtype_info - name;
11482 const char *bounds_str;
11486 bounds_str = strchr (subtype_info, '_');
11489 if (*subtype_info == 'L')
11491 if (!ada_scan_number (bounds_str, n, &L, &n)
11492 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11494 if (bounds_str[n] == '_')
11496 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11502 std::string name_buf = std::string (name, prefix_len) + "___L";
11503 if (!get_int_var_value (name_buf.c_str (), L))
11505 lim_warning (_("Unknown lower bound, using 1."));
11510 if (*subtype_info == 'U')
11512 if (!ada_scan_number (bounds_str, n, &U, &n)
11513 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11518 std::string name_buf = std::string (name, prefix_len) + "___U";
11519 if (!get_int_var_value (name_buf.c_str (), U))
11521 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11526 type = create_static_range_type (alloc_type_copy (raw_type),
11528 /* create_static_range_type alters the resulting type's length
11529 to match the size of the base_type, which is not what we want.
11530 Set it back to the original range type's length. */
11531 TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
11532 type->set_name (name);
11537 /* True iff NAME is the name of a range type. */
11540 ada_is_range_type_name (const char *name)
11542 return (name != NULL && strstr (name, "___XD"));
11546 /* Modular types */
11548 /* True iff TYPE is an Ada modular type. */
11551 ada_is_modular_type (struct type *type)
11553 struct type *subranged_type = get_base_type (type);
11555 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11556 && subranged_type->code () == TYPE_CODE_INT
11557 && subranged_type->is_unsigned ());
11560 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11563 ada_modulus (struct type *type)
11565 const dynamic_prop &high = type->bounds ()->high;
11567 if (high.kind () == PROP_CONST)
11568 return (ULONGEST) high.const_val () + 1;
11570 /* If TYPE is unresolved, the high bound might be a location list. Return
11571 0, for lack of a better value to return. */
11576 /* Ada exception catchpoint support:
11577 ---------------------------------
11579 We support 3 kinds of exception catchpoints:
11580 . catchpoints on Ada exceptions
11581 . catchpoints on unhandled Ada exceptions
11582 . catchpoints on failed assertions
11584 Exceptions raised during failed assertions, or unhandled exceptions
11585 could perfectly be caught with the general catchpoint on Ada exceptions.
11586 However, we can easily differentiate these two special cases, and having
11587 the option to distinguish these two cases from the rest can be useful
11588 to zero-in on certain situations.
11590 Exception catchpoints are a specialized form of breakpoint,
11591 since they rely on inserting breakpoints inside known routines
11592 of the GNAT runtime. The implementation therefore uses a standard
11593 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11596 Support in the runtime for exception catchpoints have been changed
11597 a few times already, and these changes affect the implementation
11598 of these catchpoints. In order to be able to support several
11599 variants of the runtime, we use a sniffer that will determine
11600 the runtime variant used by the program being debugged. */
11602 /* Ada's standard exceptions.
11604 The Ada 83 standard also defined Numeric_Error. But there so many
11605 situations where it was unclear from the Ada 83 Reference Manual
11606 (RM) whether Constraint_Error or Numeric_Error should be raised,
11607 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11608 Interpretation saying that anytime the RM says that Numeric_Error
11609 should be raised, the implementation may raise Constraint_Error.
11610 Ada 95 went one step further and pretty much removed Numeric_Error
11611 from the list of standard exceptions (it made it a renaming of
11612 Constraint_Error, to help preserve compatibility when compiling
11613 an Ada83 compiler). As such, we do not include Numeric_Error from
11614 this list of standard exceptions. */
11616 static const char * const standard_exc[] = {
11617 "constraint_error",
11623 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11625 /* A structure that describes how to support exception catchpoints
11626 for a given executable. */
11628 struct exception_support_info
11630 /* The name of the symbol to break on in order to insert
11631 a catchpoint on exceptions. */
11632 const char *catch_exception_sym;
11634 /* The name of the symbol to break on in order to insert
11635 a catchpoint on unhandled exceptions. */
11636 const char *catch_exception_unhandled_sym;
11638 /* The name of the symbol to break on in order to insert
11639 a catchpoint on failed assertions. */
11640 const char *catch_assert_sym;
11642 /* The name of the symbol to break on in order to insert
11643 a catchpoint on exception handling. */
11644 const char *catch_handlers_sym;
11646 /* Assuming that the inferior just triggered an unhandled exception
11647 catchpoint, this function is responsible for returning the address
11648 in inferior memory where the name of that exception is stored.
11649 Return zero if the address could not be computed. */
11650 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11653 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11654 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11656 /* The following exception support info structure describes how to
11657 implement exception catchpoints with the latest version of the
11658 Ada runtime (as of 2019-08-??). */
11660 static const struct exception_support_info default_exception_support_info =
11662 "__gnat_debug_raise_exception", /* catch_exception_sym */
11663 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11664 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11665 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11666 ada_unhandled_exception_name_addr
11669 /* The following exception support info structure describes how to
11670 implement exception catchpoints with an earlier version of the
11671 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11673 static const struct exception_support_info exception_support_info_v0 =
11675 "__gnat_debug_raise_exception", /* catch_exception_sym */
11676 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11677 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11678 "__gnat_begin_handler", /* catch_handlers_sym */
11679 ada_unhandled_exception_name_addr
11682 /* The following exception support info structure describes how to
11683 implement exception catchpoints with a slightly older version
11684 of the Ada runtime. */
11686 static const struct exception_support_info exception_support_info_fallback =
11688 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11689 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11690 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11691 "__gnat_begin_handler", /* catch_handlers_sym */
11692 ada_unhandled_exception_name_addr_from_raise
11695 /* Return nonzero if we can detect the exception support routines
11696 described in EINFO.
11698 This function errors out if an abnormal situation is detected
11699 (for instance, if we find the exception support routines, but
11700 that support is found to be incomplete). */
11703 ada_has_this_exception_support (const struct exception_support_info *einfo)
11705 struct symbol *sym;
11707 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11708 that should be compiled with debugging information. As a result, we
11709 expect to find that symbol in the symtabs. */
11711 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11714 /* Perhaps we did not find our symbol because the Ada runtime was
11715 compiled without debugging info, or simply stripped of it.
11716 It happens on some GNU/Linux distributions for instance, where
11717 users have to install a separate debug package in order to get
11718 the runtime's debugging info. In that situation, let the user
11719 know why we cannot insert an Ada exception catchpoint.
11721 Note: Just for the purpose of inserting our Ada exception
11722 catchpoint, we could rely purely on the associated minimal symbol.
11723 But we would be operating in degraded mode anyway, since we are
11724 still lacking the debugging info needed later on to extract
11725 the name of the exception being raised (this name is printed in
11726 the catchpoint message, and is also used when trying to catch
11727 a specific exception). We do not handle this case for now. */
11728 struct bound_minimal_symbol msym
11729 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11731 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11732 error (_("Your Ada runtime appears to be missing some debugging "
11733 "information.\nCannot insert Ada exception catchpoint "
11734 "in this configuration."));
11739 /* Make sure that the symbol we found corresponds to a function. */
11741 if (sym->aclass () != LOC_BLOCK)
11743 error (_("Symbol \"%s\" is not a function (class = %d)"),
11744 sym->linkage_name (), sym->aclass ());
11748 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11751 struct bound_minimal_symbol msym
11752 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11754 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11755 error (_("Your Ada runtime appears to be missing some debugging "
11756 "information.\nCannot insert Ada exception catchpoint "
11757 "in this configuration."));
11762 /* Make sure that the symbol we found corresponds to a function. */
11764 if (sym->aclass () != LOC_BLOCK)
11766 error (_("Symbol \"%s\" is not a function (class = %d)"),
11767 sym->linkage_name (), sym->aclass ());
11774 /* Inspect the Ada runtime and determine which exception info structure
11775 should be used to provide support for exception catchpoints.
11777 This function will always set the per-inferior exception_info,
11778 or raise an error. */
11781 ada_exception_support_info_sniffer (void)
11783 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11785 /* If the exception info is already known, then no need to recompute it. */
11786 if (data->exception_info != NULL)
11789 /* Check the latest (default) exception support info. */
11790 if (ada_has_this_exception_support (&default_exception_support_info))
11792 data->exception_info = &default_exception_support_info;
11796 /* Try the v0 exception suport info. */
11797 if (ada_has_this_exception_support (&exception_support_info_v0))
11799 data->exception_info = &exception_support_info_v0;
11803 /* Try our fallback exception suport info. */
11804 if (ada_has_this_exception_support (&exception_support_info_fallback))
11806 data->exception_info = &exception_support_info_fallback;
11810 /* Sometimes, it is normal for us to not be able to find the routine
11811 we are looking for. This happens when the program is linked with
11812 the shared version of the GNAT runtime, and the program has not been
11813 started yet. Inform the user of these two possible causes if
11816 if (ada_update_initial_language (language_unknown) != language_ada)
11817 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
11819 /* If the symbol does not exist, then check that the program is
11820 already started, to make sure that shared libraries have been
11821 loaded. If it is not started, this may mean that the symbol is
11822 in a shared library. */
11824 if (inferior_ptid.pid () == 0)
11825 error (_("Unable to insert catchpoint. Try to start the program first."));
11827 /* At this point, we know that we are debugging an Ada program and
11828 that the inferior has been started, but we still are not able to
11829 find the run-time symbols. That can mean that we are in
11830 configurable run time mode, or that a-except as been optimized
11831 out by the linker... In any case, at this point it is not worth
11832 supporting this feature. */
11834 error (_("Cannot insert Ada exception catchpoints in this configuration."));
11837 /* True iff FRAME is very likely to be that of a function that is
11838 part of the runtime system. This is all very heuristic, but is
11839 intended to be used as advice as to what frames are uninteresting
11843 is_known_support_routine (struct frame_info *frame)
11845 enum language func_lang;
11847 const char *fullname;
11849 /* If this code does not have any debugging information (no symtab),
11850 This cannot be any user code. */
11852 symtab_and_line sal = find_frame_sal (frame);
11853 if (sal.symtab == NULL)
11856 /* If there is a symtab, but the associated source file cannot be
11857 located, then assume this is not user code: Selecting a frame
11858 for which we cannot display the code would not be very helpful
11859 for the user. This should also take care of case such as VxWorks
11860 where the kernel has some debugging info provided for a few units. */
11862 fullname = symtab_to_fullname (sal.symtab);
11863 if (access (fullname, R_OK) != 0)
11866 /* Check the unit filename against the Ada runtime file naming.
11867 We also check the name of the objfile against the name of some
11868 known system libraries that sometimes come with debugging info
11871 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11873 re_comp (known_runtime_file_name_patterns[i]);
11874 if (re_exec (lbasename (sal.symtab->filename)))
11876 if (sal.symtab->compunit ()->objfile () != NULL
11877 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11881 /* Check whether the function is a GNAT-generated entity. */
11883 gdb::unique_xmalloc_ptr<char> func_name
11884 = find_frame_funname (frame, &func_lang, NULL);
11885 if (func_name == NULL)
11888 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11890 re_comp (known_auxiliary_function_name_patterns[i]);
11891 if (re_exec (func_name.get ()))
11898 /* Find the first frame that contains debugging information and that is not
11899 part of the Ada run-time, starting from FI and moving upward. */
11902 ada_find_printable_frame (struct frame_info *fi)
11904 for (; fi != NULL; fi = get_prev_frame (fi))
11906 if (!is_known_support_routine (fi))
11915 /* Assuming that the inferior just triggered an unhandled exception
11916 catchpoint, return the address in inferior memory where the name
11917 of the exception is stored.
11919 Return zero if the address could not be computed. */
11922 ada_unhandled_exception_name_addr (void)
11924 return parse_and_eval_address ("e.full_name");
11927 /* Same as ada_unhandled_exception_name_addr, except that this function
11928 should be used when the inferior uses an older version of the runtime,
11929 where the exception name needs to be extracted from a specific frame
11930 several frames up in the callstack. */
11933 ada_unhandled_exception_name_addr_from_raise (void)
11936 struct frame_info *fi;
11937 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11939 /* To determine the name of this exception, we need to select
11940 the frame corresponding to RAISE_SYM_NAME. This frame is
11941 at least 3 levels up, so we simply skip the first 3 frames
11942 without checking the name of their associated function. */
11943 fi = get_current_frame ();
11944 for (frame_level = 0; frame_level < 3; frame_level += 1)
11946 fi = get_prev_frame (fi);
11950 enum language func_lang;
11952 gdb::unique_xmalloc_ptr<char> func_name
11953 = find_frame_funname (fi, &func_lang, NULL);
11954 if (func_name != NULL)
11956 if (strcmp (func_name.get (),
11957 data->exception_info->catch_exception_sym) == 0)
11958 break; /* We found the frame we were looking for... */
11960 fi = get_prev_frame (fi);
11967 return parse_and_eval_address ("id.full_name");
11970 /* Assuming the inferior just triggered an Ada exception catchpoint
11971 (of any type), return the address in inferior memory where the name
11972 of the exception is stored, if applicable.
11974 Assumes the selected frame is the current frame.
11976 Return zero if the address could not be computed, or if not relevant. */
11979 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11981 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11985 case ada_catch_exception:
11986 return (parse_and_eval_address ("e.full_name"));
11989 case ada_catch_exception_unhandled:
11990 return data->exception_info->unhandled_exception_name_addr ();
11993 case ada_catch_handlers:
11994 return 0; /* The runtimes does not provide access to the exception
11998 case ada_catch_assert:
11999 return 0; /* Exception name is not relevant in this case. */
12003 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12007 return 0; /* Should never be reached. */
12010 /* Assuming the inferior is stopped at an exception catchpoint,
12011 return the message which was associated to the exception, if
12012 available. Return NULL if the message could not be retrieved.
12014 Note: The exception message can be associated to an exception
12015 either through the use of the Raise_Exception function, or
12016 more simply (Ada 2005 and later), via:
12018 raise Exception_Name with "exception message";
12022 static gdb::unique_xmalloc_ptr<char>
12023 ada_exception_message_1 (void)
12025 struct value *e_msg_val;
12028 /* For runtimes that support this feature, the exception message
12029 is passed as an unbounded string argument called "message". */
12030 e_msg_val = parse_and_eval ("message");
12031 if (e_msg_val == NULL)
12032 return NULL; /* Exception message not supported. */
12034 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12035 gdb_assert (e_msg_val != NULL);
12036 e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
12038 /* If the message string is empty, then treat it as if there was
12039 no exception message. */
12040 if (e_msg_len <= 0)
12043 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12044 read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
12046 e_msg.get ()[e_msg_len] = '\0';
12051 /* Same as ada_exception_message_1, except that all exceptions are
12052 contained here (returning NULL instead). */
12054 static gdb::unique_xmalloc_ptr<char>
12055 ada_exception_message (void)
12057 gdb::unique_xmalloc_ptr<char> e_msg;
12061 e_msg = ada_exception_message_1 ();
12063 catch (const gdb_exception_error &e)
12065 e_msg.reset (nullptr);
12071 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12072 any error that ada_exception_name_addr_1 might cause to be thrown.
12073 When an error is intercepted, a warning with the error message is printed,
12074 and zero is returned. */
12077 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12079 CORE_ADDR result = 0;
12083 result = ada_exception_name_addr_1 (ex);
12086 catch (const gdb_exception_error &e)
12088 warning (_("failed to get exception name: %s"), e.what ());
12095 static std::string ada_exception_catchpoint_cond_string
12096 (const char *excep_string,
12097 enum ada_exception_catchpoint_kind ex);
12099 /* Ada catchpoints.
12101 In the case of catchpoints on Ada exceptions, the catchpoint will
12102 stop the target on every exception the program throws. When a user
12103 specifies the name of a specific exception, we translate this
12104 request into a condition expression (in text form), and then parse
12105 it into an expression stored in each of the catchpoint's locations.
12106 We then use this condition to check whether the exception that was
12107 raised is the one the user is interested in. If not, then the
12108 target is resumed again. We store the name of the requested
12109 exception, in order to be able to re-set the condition expression
12110 when symbols change. */
12112 /* An instance of this type is used to represent an Ada catchpoint. */
12114 struct ada_catchpoint : public code_breakpoint
12116 ada_catchpoint (struct gdbarch *gdbarch_,
12117 enum ada_exception_catchpoint_kind kind,
12118 struct symtab_and_line sal,
12119 const char *addr_string_,
12123 : code_breakpoint (gdbarch_, bp_catchpoint),
12126 add_location (sal);
12128 /* Unlike most code_breakpoint types, Ada catchpoints are
12129 pspace-specific. */
12130 gdb_assert (sal.pspace != nullptr);
12131 this->pspace = sal.pspace;
12135 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12137 loc_gdbarch = gdbarch;
12139 describe_other_breakpoints (loc_gdbarch,
12140 sal.pspace, sal.pc, sal.section, -1);
12141 /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12142 version for exception catchpoints, because two catchpoints
12143 used for different exception names will use the same address.
12144 In this case, a "breakpoint ... also set at..." warning is
12145 unproductive. Besides, the warning phrasing is also a bit
12146 inappropriate, we should use the word catchpoint, and tell
12147 the user what type of catchpoint it is. The above is good
12148 enough for now, though. */
12151 enable_state = enabled ? bp_enabled : bp_disabled;
12152 disposition = tempflag ? disp_del : disp_donttouch;
12153 locspec = string_to_location_spec (&addr_string_,
12154 language_def (language_ada));
12155 language = language_ada;
12158 struct bp_location *allocate_location () override;
12159 void re_set () override;
12160 void check_status (struct bpstat *bs) override;
12161 enum print_stop_action print_it (const bpstat *bs) const override;
12162 bool print_one (bp_location **) const override;
12163 void print_mention () const override;
12164 void print_recreate (struct ui_file *fp) const override;
12166 /* The name of the specific exception the user specified. */
12167 std::string excep_string;
12169 /* What kind of catchpoint this is. */
12170 enum ada_exception_catchpoint_kind m_kind;
12173 /* An instance of this type is used to represent an Ada catchpoint
12174 breakpoint location. */
12176 class ada_catchpoint_location : public bp_location
12179 explicit ada_catchpoint_location (ada_catchpoint *owner)
12180 : bp_location (owner, bp_loc_software_breakpoint)
12183 /* The condition that checks whether the exception that was raised
12184 is the specific exception the user specified on catchpoint
12186 expression_up excep_cond_expr;
12189 /* Parse the exception condition string in the context of each of the
12190 catchpoint's locations, and store them for later evaluation. */
12193 create_excep_cond_exprs (struct ada_catchpoint *c,
12194 enum ada_exception_catchpoint_kind ex)
12196 /* Nothing to do if there's no specific exception to catch. */
12197 if (c->excep_string.empty ())
12200 /* Same if there are no locations... */
12201 if (c->loc == NULL)
12204 /* Compute the condition expression in text form, from the specific
12205 expection we want to catch. */
12206 std::string cond_string
12207 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12209 /* Iterate over all the catchpoint's locations, and parse an
12210 expression for each. */
12211 for (bp_location *bl : c->locations ())
12213 struct ada_catchpoint_location *ada_loc
12214 = (struct ada_catchpoint_location *) bl;
12217 if (!bl->shlib_disabled)
12221 s = cond_string.c_str ();
12224 exp = parse_exp_1 (&s, bl->address,
12225 block_for_pc (bl->address),
12228 catch (const gdb_exception_error &e)
12230 warning (_("failed to reevaluate internal exception condition "
12231 "for catchpoint %d: %s"),
12232 c->number, e.what ());
12236 ada_loc->excep_cond_expr = std::move (exp);
12240 /* Implement the ALLOCATE_LOCATION method in the structure for all
12241 exception catchpoint kinds. */
12243 struct bp_location *
12244 ada_catchpoint::allocate_location ()
12246 return new ada_catchpoint_location (this);
12249 /* Implement the RE_SET method in the structure for all exception
12250 catchpoint kinds. */
12253 ada_catchpoint::re_set ()
12255 /* Call the base class's method. This updates the catchpoint's
12257 this->code_breakpoint::re_set ();
12259 /* Reparse the exception conditional expressions. One for each
12261 create_excep_cond_exprs (this, m_kind);
12264 /* Returns true if we should stop for this breakpoint hit. If the
12265 user specified a specific exception, we only want to cause a stop
12266 if the program thrown that exception. */
12269 should_stop_exception (const struct bp_location *bl)
12271 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12272 const struct ada_catchpoint_location *ada_loc
12273 = (const struct ada_catchpoint_location *) bl;
12276 struct internalvar *var = lookup_internalvar ("_ada_exception");
12277 if (c->m_kind == ada_catch_assert)
12278 clear_internalvar (var);
12285 if (c->m_kind == ada_catch_handlers)
12286 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12287 ".all.occurrence.id");
12291 struct value *exc = parse_and_eval (expr);
12292 set_internalvar (var, exc);
12294 catch (const gdb_exception_error &ex)
12296 clear_internalvar (var);
12300 /* With no specific exception, should always stop. */
12301 if (c->excep_string.empty ())
12304 if (ada_loc->excep_cond_expr == NULL)
12306 /* We will have a NULL expression if back when we were creating
12307 the expressions, this location's had failed to parse. */
12314 struct value *mark;
12316 mark = value_mark ();
12317 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
12318 value_free_to_mark (mark);
12320 catch (const gdb_exception &ex)
12322 exception_fprintf (gdb_stderr, ex,
12323 _("Error in testing exception condition:\n"));
12329 /* Implement the CHECK_STATUS method in the structure for all
12330 exception catchpoint kinds. */
12333 ada_catchpoint::check_status (bpstat *bs)
12335 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12338 /* Implement the PRINT_IT method in the structure for all exception
12339 catchpoint kinds. */
12341 enum print_stop_action
12342 ada_catchpoint::print_it (const bpstat *bs) const
12344 struct ui_out *uiout = current_uiout;
12346 annotate_catchpoint (number);
12348 if (uiout->is_mi_like_p ())
12350 uiout->field_string ("reason",
12351 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12352 uiout->field_string ("disp", bpdisp_text (disposition));
12355 uiout->text (disposition == disp_del
12356 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12357 uiout->field_signed ("bkptno", number);
12358 uiout->text (", ");
12360 /* ada_exception_name_addr relies on the selected frame being the
12361 current frame. Need to do this here because this function may be
12362 called more than once when printing a stop, and below, we'll
12363 select the first frame past the Ada run-time (see
12364 ada_find_printable_frame). */
12365 select_frame (get_current_frame ());
12369 case ada_catch_exception:
12370 case ada_catch_exception_unhandled:
12371 case ada_catch_handlers:
12373 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12374 char exception_name[256];
12378 read_memory (addr, (gdb_byte *) exception_name,
12379 sizeof (exception_name) - 1);
12380 exception_name [sizeof (exception_name) - 1] = '\0';
12384 /* For some reason, we were unable to read the exception
12385 name. This could happen if the Runtime was compiled
12386 without debugging info, for instance. In that case,
12387 just replace the exception name by the generic string
12388 "exception" - it will read as "an exception" in the
12389 notification we are about to print. */
12390 memcpy (exception_name, "exception", sizeof ("exception"));
12392 /* In the case of unhandled exception breakpoints, we print
12393 the exception name as "unhandled EXCEPTION_NAME", to make
12394 it clearer to the user which kind of catchpoint just got
12395 hit. We used ui_out_text to make sure that this extra
12396 info does not pollute the exception name in the MI case. */
12397 if (m_kind == ada_catch_exception_unhandled)
12398 uiout->text ("unhandled ");
12399 uiout->field_string ("exception-name", exception_name);
12402 case ada_catch_assert:
12403 /* In this case, the name of the exception is not really
12404 important. Just print "failed assertion" to make it clearer
12405 that his program just hit an assertion-failure catchpoint.
12406 We used ui_out_text because this info does not belong in
12408 uiout->text ("failed assertion");
12412 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12413 if (exception_message != NULL)
12415 uiout->text (" (");
12416 uiout->field_string ("exception-message", exception_message.get ());
12420 uiout->text (" at ");
12421 ada_find_printable_frame (get_current_frame ());
12423 return PRINT_SRC_AND_LOC;
12426 /* Implement the PRINT_ONE method in the structure for all exception
12427 catchpoint kinds. */
12430 ada_catchpoint::print_one (bp_location **last_loc) const
12432 struct ui_out *uiout = current_uiout;
12433 struct value_print_options opts;
12435 get_user_print_options (&opts);
12437 if (opts.addressprint)
12438 uiout->field_skip ("addr");
12440 annotate_field (5);
12443 case ada_catch_exception:
12444 if (!excep_string.empty ())
12446 std::string msg = string_printf (_("`%s' Ada exception"),
12447 excep_string.c_str ());
12449 uiout->field_string ("what", msg);
12452 uiout->field_string ("what", "all Ada exceptions");
12456 case ada_catch_exception_unhandled:
12457 uiout->field_string ("what", "unhandled Ada exceptions");
12460 case ada_catch_handlers:
12461 if (!excep_string.empty ())
12463 uiout->field_fmt ("what",
12464 _("`%s' Ada exception handlers"),
12465 excep_string.c_str ());
12468 uiout->field_string ("what", "all Ada exceptions handlers");
12471 case ada_catch_assert:
12472 uiout->field_string ("what", "failed Ada assertions");
12476 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12483 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12484 for all exception catchpoint kinds. */
12487 ada_catchpoint::print_mention () const
12489 struct ui_out *uiout = current_uiout;
12491 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12492 : _("Catchpoint "));
12493 uiout->field_signed ("bkptno", number);
12494 uiout->text (": ");
12498 case ada_catch_exception:
12499 if (!excep_string.empty ())
12501 std::string info = string_printf (_("`%s' Ada exception"),
12502 excep_string.c_str ());
12503 uiout->text (info);
12506 uiout->text (_("all Ada exceptions"));
12509 case ada_catch_exception_unhandled:
12510 uiout->text (_("unhandled Ada exceptions"));
12513 case ada_catch_handlers:
12514 if (!excep_string.empty ())
12517 = string_printf (_("`%s' Ada exception handlers"),
12518 excep_string.c_str ());
12519 uiout->text (info);
12522 uiout->text (_("all Ada exceptions handlers"));
12525 case ada_catch_assert:
12526 uiout->text (_("failed Ada assertions"));
12530 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12535 /* Implement the PRINT_RECREATE method in the structure for all
12536 exception catchpoint kinds. */
12539 ada_catchpoint::print_recreate (struct ui_file *fp) const
12543 case ada_catch_exception:
12544 gdb_printf (fp, "catch exception");
12545 if (!excep_string.empty ())
12546 gdb_printf (fp, " %s", excep_string.c_str ());
12549 case ada_catch_exception_unhandled:
12550 gdb_printf (fp, "catch exception unhandled");
12553 case ada_catch_handlers:
12554 gdb_printf (fp, "catch handlers");
12557 case ada_catch_assert:
12558 gdb_printf (fp, "catch assert");
12562 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12564 print_recreate_thread (fp);
12567 /* See ada-lang.h. */
12570 is_ada_exception_catchpoint (breakpoint *bp)
12572 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12575 /* Split the arguments specified in a "catch exception" command.
12576 Set EX to the appropriate catchpoint type.
12577 Set EXCEP_STRING to the name of the specific exception if
12578 specified by the user.
12579 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12580 "catch handlers" command. False otherwise.
12581 If a condition is found at the end of the arguments, the condition
12582 expression is stored in COND_STRING (memory must be deallocated
12583 after use). Otherwise COND_STRING is set to NULL. */
12586 catch_ada_exception_command_split (const char *args,
12587 bool is_catch_handlers_cmd,
12588 enum ada_exception_catchpoint_kind *ex,
12589 std::string *excep_string,
12590 std::string *cond_string)
12592 std::string exception_name;
12594 exception_name = extract_arg (&args);
12595 if (exception_name == "if")
12597 /* This is not an exception name; this is the start of a condition
12598 expression for a catchpoint on all exceptions. So, "un-get"
12599 this token, and set exception_name to NULL. */
12600 exception_name.clear ();
12604 /* Check to see if we have a condition. */
12606 args = skip_spaces (args);
12607 if (startswith (args, "if")
12608 && (isspace (args[2]) || args[2] == '\0'))
12611 args = skip_spaces (args);
12613 if (args[0] == '\0')
12614 error (_("Condition missing after `if' keyword"));
12615 *cond_string = args;
12617 args += strlen (args);
12620 /* Check that we do not have any more arguments. Anything else
12623 if (args[0] != '\0')
12624 error (_("Junk at end of expression"));
12626 if (is_catch_handlers_cmd)
12628 /* Catch handling of exceptions. */
12629 *ex = ada_catch_handlers;
12630 *excep_string = exception_name;
12632 else if (exception_name.empty ())
12634 /* Catch all exceptions. */
12635 *ex = ada_catch_exception;
12636 excep_string->clear ();
12638 else if (exception_name == "unhandled")
12640 /* Catch unhandled exceptions. */
12641 *ex = ada_catch_exception_unhandled;
12642 excep_string->clear ();
12646 /* Catch a specific exception. */
12647 *ex = ada_catch_exception;
12648 *excep_string = exception_name;
12652 /* Return the name of the symbol on which we should break in order to
12653 implement a catchpoint of the EX kind. */
12655 static const char *
12656 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12658 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12660 gdb_assert (data->exception_info != NULL);
12664 case ada_catch_exception:
12665 return (data->exception_info->catch_exception_sym);
12667 case ada_catch_exception_unhandled:
12668 return (data->exception_info->catch_exception_unhandled_sym);
12670 case ada_catch_assert:
12671 return (data->exception_info->catch_assert_sym);
12673 case ada_catch_handlers:
12674 return (data->exception_info->catch_handlers_sym);
12677 internal_error (__FILE__, __LINE__,
12678 _("unexpected catchpoint kind (%d)"), ex);
12682 /* Return the condition that will be used to match the current exception
12683 being raised with the exception that the user wants to catch. This
12684 assumes that this condition is used when the inferior just triggered
12685 an exception catchpoint.
12686 EX: the type of catchpoints used for catching Ada exceptions. */
12689 ada_exception_catchpoint_cond_string (const char *excep_string,
12690 enum ada_exception_catchpoint_kind ex)
12692 bool is_standard_exc = false;
12693 std::string result;
12695 if (ex == ada_catch_handlers)
12697 /* For exception handlers catchpoints, the condition string does
12698 not use the same parameter as for the other exceptions. */
12699 result = ("long_integer (GNAT_GCC_exception_Access"
12700 "(gcc_exception).all.occurrence.id)");
12703 result = "long_integer (e)";
12705 /* The standard exceptions are a special case. They are defined in
12706 runtime units that have been compiled without debugging info; if
12707 EXCEP_STRING is the not-fully-qualified name of a standard
12708 exception (e.g. "constraint_error") then, during the evaluation
12709 of the condition expression, the symbol lookup on this name would
12710 *not* return this standard exception. The catchpoint condition
12711 may then be set only on user-defined exceptions which have the
12712 same not-fully-qualified name (e.g. my_package.constraint_error).
12714 To avoid this unexcepted behavior, these standard exceptions are
12715 systematically prefixed by "standard". This means that "catch
12716 exception constraint_error" is rewritten into "catch exception
12717 standard.constraint_error".
12719 If an exception named constraint_error is defined in another package of
12720 the inferior program, then the only way to specify this exception as a
12721 breakpoint condition is to use its fully-qualified named:
12722 e.g. my_package.constraint_error. */
12724 for (const char *name : standard_exc)
12726 if (strcmp (name, excep_string) == 0)
12728 is_standard_exc = true;
12735 if (is_standard_exc)
12736 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12738 string_appendf (result, "long_integer (&%s)", excep_string);
12743 /* Return the symtab_and_line that should be used to insert an exception
12744 catchpoint of the TYPE kind.
12746 ADDR_STRING returns the name of the function where the real
12747 breakpoint that implements the catchpoints is set, depending on the
12748 type of catchpoint we need to create. */
12750 static struct symtab_and_line
12751 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12752 std::string *addr_string)
12754 const char *sym_name;
12755 struct symbol *sym;
12757 /* First, find out which exception support info to use. */
12758 ada_exception_support_info_sniffer ();
12760 /* Then lookup the function on which we will break in order to catch
12761 the Ada exceptions requested by the user. */
12762 sym_name = ada_exception_sym_name (ex);
12763 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12766 error (_("Catchpoint symbol not found: %s"), sym_name);
12768 if (sym->aclass () != LOC_BLOCK)
12769 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12771 /* Set ADDR_STRING. */
12772 *addr_string = sym_name;
12774 return find_function_start_sal (sym, 1);
12777 /* Create an Ada exception catchpoint.
12779 EX_KIND is the kind of exception catchpoint to be created.
12781 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12782 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12783 of the exception to which this catchpoint applies.
12785 COND_STRING, if not empty, is the catchpoint condition.
12787 TEMPFLAG, if nonzero, means that the underlying breakpoint
12788 should be temporary.
12790 FROM_TTY is the usual argument passed to all commands implementations. */
12793 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12794 enum ada_exception_catchpoint_kind ex_kind,
12795 const std::string &excep_string,
12796 const std::string &cond_string,
12801 std::string addr_string;
12802 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string);
12804 std::unique_ptr<ada_catchpoint> c
12805 (new ada_catchpoint (gdbarch, ex_kind, sal, addr_string.c_str (),
12806 tempflag, disabled, from_tty));
12807 c->excep_string = excep_string;
12808 create_excep_cond_exprs (c.get (), ex_kind);
12809 if (!cond_string.empty ())
12810 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
12811 install_breakpoint (0, std::move (c), 1);
12814 /* Implement the "catch exception" command. */
12817 catch_ada_exception_command (const char *arg_entry, int from_tty,
12818 struct cmd_list_element *command)
12820 const char *arg = arg_entry;
12821 struct gdbarch *gdbarch = get_current_arch ();
12823 enum ada_exception_catchpoint_kind ex_kind;
12824 std::string excep_string;
12825 std::string cond_string;
12827 tempflag = command->context () == CATCH_TEMPORARY;
12831 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12833 create_ada_exception_catchpoint (gdbarch, ex_kind,
12834 excep_string, cond_string,
12835 tempflag, 1 /* enabled */,
12839 /* Implement the "catch handlers" command. */
12842 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12843 struct cmd_list_element *command)
12845 const char *arg = arg_entry;
12846 struct gdbarch *gdbarch = get_current_arch ();
12848 enum ada_exception_catchpoint_kind ex_kind;
12849 std::string excep_string;
12850 std::string cond_string;
12852 tempflag = command->context () == CATCH_TEMPORARY;
12856 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12858 create_ada_exception_catchpoint (gdbarch, ex_kind,
12859 excep_string, cond_string,
12860 tempflag, 1 /* enabled */,
12864 /* Completion function for the Ada "catch" commands. */
12867 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12868 const char *text, const char *word)
12870 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12872 for (const ada_exc_info &info : exceptions)
12874 if (startswith (info.name, word))
12875 tracker.add_completion (make_unique_xstrdup (info.name));
12879 /* Split the arguments specified in a "catch assert" command.
12881 ARGS contains the command's arguments (or the empty string if
12882 no arguments were passed).
12884 If ARGS contains a condition, set COND_STRING to that condition
12885 (the memory needs to be deallocated after use). */
12888 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12890 args = skip_spaces (args);
12892 /* Check whether a condition was provided. */
12893 if (startswith (args, "if")
12894 && (isspace (args[2]) || args[2] == '\0'))
12897 args = skip_spaces (args);
12898 if (args[0] == '\0')
12899 error (_("condition missing after `if' keyword"));
12900 cond_string.assign (args);
12903 /* Otherwise, there should be no other argument at the end of
12905 else if (args[0] != '\0')
12906 error (_("Junk at end of arguments."));
12909 /* Implement the "catch assert" command. */
12912 catch_assert_command (const char *arg_entry, int from_tty,
12913 struct cmd_list_element *command)
12915 const char *arg = arg_entry;
12916 struct gdbarch *gdbarch = get_current_arch ();
12918 std::string cond_string;
12920 tempflag = command->context () == CATCH_TEMPORARY;
12924 catch_ada_assert_command_split (arg, cond_string);
12925 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12927 tempflag, 1 /* enabled */,
12931 /* Return non-zero if the symbol SYM is an Ada exception object. */
12934 ada_is_exception_sym (struct symbol *sym)
12936 const char *type_name = sym->type ()->name ();
12938 return (sym->aclass () != LOC_TYPEDEF
12939 && sym->aclass () != LOC_BLOCK
12940 && sym->aclass () != LOC_CONST
12941 && sym->aclass () != LOC_UNRESOLVED
12942 && type_name != NULL && strcmp (type_name, "exception") == 0);
12945 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12946 Ada exception object. This matches all exceptions except the ones
12947 defined by the Ada language. */
12950 ada_is_non_standard_exception_sym (struct symbol *sym)
12952 if (!ada_is_exception_sym (sym))
12955 for (const char *name : standard_exc)
12956 if (strcmp (sym->linkage_name (), name) == 0)
12957 return 0; /* A standard exception. */
12959 /* Numeric_Error is also a standard exception, so exclude it.
12960 See the STANDARD_EXC description for more details as to why
12961 this exception is not listed in that array. */
12962 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12968 /* A helper function for std::sort, comparing two struct ada_exc_info
12971 The comparison is determined first by exception name, and then
12972 by exception address. */
12975 ada_exc_info::operator< (const ada_exc_info &other) const
12979 result = strcmp (name, other.name);
12982 if (result == 0 && addr < other.addr)
12988 ada_exc_info::operator== (const ada_exc_info &other) const
12990 return addr == other.addr && strcmp (name, other.name) == 0;
12993 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12994 routine, but keeping the first SKIP elements untouched.
12996 All duplicates are also removed. */
12999 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13002 std::sort (exceptions->begin () + skip, exceptions->end ());
13003 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13004 exceptions->end ());
13007 /* Add all exceptions defined by the Ada standard whose name match
13008 a regular expression.
13010 If PREG is not NULL, then this regexp_t object is used to
13011 perform the symbol name matching. Otherwise, no name-based
13012 filtering is performed.
13014 EXCEPTIONS is a vector of exceptions to which matching exceptions
13018 ada_add_standard_exceptions (compiled_regex *preg,
13019 std::vector<ada_exc_info> *exceptions)
13021 for (const char *name : standard_exc)
13023 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
13025 struct bound_minimal_symbol msymbol
13026 = ada_lookup_simple_minsym (name);
13028 if (msymbol.minsym != NULL)
13030 struct ada_exc_info info
13031 = {name, msymbol.value_address ()};
13033 exceptions->push_back (info);
13039 /* Add all Ada exceptions defined locally and accessible from the given
13042 If PREG is not NULL, then this regexp_t object is used to
13043 perform the symbol name matching. Otherwise, no name-based
13044 filtering is performed.
13046 EXCEPTIONS is a vector of exceptions to which matching exceptions
13050 ada_add_exceptions_from_frame (compiled_regex *preg,
13051 struct frame_info *frame,
13052 std::vector<ada_exc_info> *exceptions)
13054 const struct block *block = get_frame_block (frame, 0);
13058 struct block_iterator iter;
13059 struct symbol *sym;
13061 ALL_BLOCK_SYMBOLS (block, iter, sym)
13063 switch (sym->aclass ())
13070 if (ada_is_exception_sym (sym))
13072 struct ada_exc_info info = {sym->print_name (),
13073 sym->value_address ()};
13075 exceptions->push_back (info);
13079 if (block->function () != NULL)
13081 block = block->superblock ();
13085 /* Return true if NAME matches PREG or if PREG is NULL. */
13088 name_matches_regex (const char *name, compiled_regex *preg)
13090 return (preg == NULL
13091 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13094 /* Add all exceptions defined globally whose name name match
13095 a regular expression, excluding standard exceptions.
13097 The reason we exclude standard exceptions is that they need
13098 to be handled separately: Standard exceptions are defined inside
13099 a runtime unit which is normally not compiled with debugging info,
13100 and thus usually do not show up in our symbol search. However,
13101 if the unit was in fact built with debugging info, we need to
13102 exclude them because they would duplicate the entry we found
13103 during the special loop that specifically searches for those
13104 standard exceptions.
13106 If PREG is not NULL, then this regexp_t object is used to
13107 perform the symbol name matching. Otherwise, no name-based
13108 filtering is performed.
13110 EXCEPTIONS is a vector of exceptions to which matching exceptions
13114 ada_add_global_exceptions (compiled_regex *preg,
13115 std::vector<ada_exc_info> *exceptions)
13117 /* In Ada, the symbol "search name" is a linkage name, whereas the
13118 regular expression used to do the matching refers to the natural
13119 name. So match against the decoded name. */
13120 expand_symtabs_matching (NULL,
13121 lookup_name_info::match_any (),
13122 [&] (const char *search_name)
13124 std::string decoded = ada_decode (search_name);
13125 return name_matches_regex (decoded.c_str (), preg);
13128 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13131 for (objfile *objfile : current_program_space->objfiles ())
13133 for (compunit_symtab *s : objfile->compunits ())
13135 const struct blockvector *bv = s->blockvector ();
13138 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13140 const struct block *b = bv->block (i);
13141 struct block_iterator iter;
13142 struct symbol *sym;
13144 ALL_BLOCK_SYMBOLS (b, iter, sym)
13145 if (ada_is_non_standard_exception_sym (sym)
13146 && name_matches_regex (sym->natural_name (), preg))
13148 struct ada_exc_info info
13149 = {sym->print_name (), sym->value_address ()};
13151 exceptions->push_back (info);
13158 /* Implements ada_exceptions_list with the regular expression passed
13159 as a regex_t, rather than a string.
13161 If not NULL, PREG is used to filter out exceptions whose names
13162 do not match. Otherwise, all exceptions are listed. */
13164 static std::vector<ada_exc_info>
13165 ada_exceptions_list_1 (compiled_regex *preg)
13167 std::vector<ada_exc_info> result;
13170 /* First, list the known standard exceptions. These exceptions
13171 need to be handled separately, as they are usually defined in
13172 runtime units that have been compiled without debugging info. */
13174 ada_add_standard_exceptions (preg, &result);
13176 /* Next, find all exceptions whose scope is local and accessible
13177 from the currently selected frame. */
13179 if (has_stack_frames ())
13181 prev_len = result.size ();
13182 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13184 if (result.size () > prev_len)
13185 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13188 /* Add all exceptions whose scope is global. */
13190 prev_len = result.size ();
13191 ada_add_global_exceptions (preg, &result);
13192 if (result.size () > prev_len)
13193 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13198 /* Return a vector of ada_exc_info.
13200 If REGEXP is NULL, all exceptions are included in the result.
13201 Otherwise, it should contain a valid regular expression,
13202 and only the exceptions whose names match that regular expression
13203 are included in the result.
13205 The exceptions are sorted in the following order:
13206 - Standard exceptions (defined by the Ada language), in
13207 alphabetical order;
13208 - Exceptions only visible from the current frame, in
13209 alphabetical order;
13210 - Exceptions whose scope is global, in alphabetical order. */
13212 std::vector<ada_exc_info>
13213 ada_exceptions_list (const char *regexp)
13215 if (regexp == NULL)
13216 return ada_exceptions_list_1 (NULL);
13218 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13219 return ada_exceptions_list_1 (®);
13222 /* Implement the "info exceptions" command. */
13225 info_exceptions_command (const char *regexp, int from_tty)
13227 struct gdbarch *gdbarch = get_current_arch ();
13229 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13231 if (regexp != NULL)
13233 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13235 gdb_printf (_("All defined Ada exceptions:\n"));
13237 for (const ada_exc_info &info : exceptions)
13238 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13242 /* Language vector */
13244 /* symbol_name_matcher_ftype adapter for wild_match. */
13247 do_wild_match (const char *symbol_search_name,
13248 const lookup_name_info &lookup_name,
13249 completion_match_result *comp_match_res)
13251 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13254 /* symbol_name_matcher_ftype adapter for full_match. */
13257 do_full_match (const char *symbol_search_name,
13258 const lookup_name_info &lookup_name,
13259 completion_match_result *comp_match_res)
13261 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13263 /* If both symbols start with "_ada_", just let the loop below
13264 handle the comparison. However, if only the symbol name starts
13265 with "_ada_", skip the prefix and let the match proceed as
13267 if (startswith (symbol_search_name, "_ada_")
13268 && !startswith (lname, "_ada"))
13269 symbol_search_name += 5;
13270 /* Likewise for ghost entities. */
13271 if (startswith (symbol_search_name, "___ghost_")
13272 && !startswith (lname, "___ghost_"))
13273 symbol_search_name += 9;
13275 int uscore_count = 0;
13276 while (*lname != '\0')
13278 if (*symbol_search_name != *lname)
13280 if (*symbol_search_name == 'B' && uscore_count == 2
13281 && symbol_search_name[1] == '_')
13283 symbol_search_name += 2;
13284 while (isdigit (*symbol_search_name))
13285 ++symbol_search_name;
13286 if (symbol_search_name[0] == '_'
13287 && symbol_search_name[1] == '_')
13289 symbol_search_name += 2;
13296 if (*symbol_search_name == '_')
13301 ++symbol_search_name;
13305 return is_name_suffix (symbol_search_name);
13308 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13311 do_exact_match (const char *symbol_search_name,
13312 const lookup_name_info &lookup_name,
13313 completion_match_result *comp_match_res)
13315 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13318 /* Build the Ada lookup name for LOOKUP_NAME. */
13320 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13322 gdb::string_view user_name = lookup_name.name ();
13324 if (!user_name.empty () && user_name[0] == '<')
13326 if (user_name.back () == '>')
13328 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
13331 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
13332 m_encoded_p = true;
13333 m_verbatim_p = true;
13334 m_wild_match_p = false;
13335 m_standard_p = false;
13339 m_verbatim_p = false;
13341 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
13345 const char *folded = ada_fold_name (user_name);
13346 m_encoded_name = ada_encode_1 (folded, false);
13347 if (m_encoded_name.empty ())
13348 m_encoded_name = gdb::to_string (user_name);
13351 m_encoded_name = gdb::to_string (user_name);
13353 /* Handle the 'package Standard' special case. See description
13354 of m_standard_p. */
13355 if (startswith (m_encoded_name.c_str (), "standard__"))
13357 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13358 m_standard_p = true;
13361 m_standard_p = false;
13363 /* If the name contains a ".", then the user is entering a fully
13364 qualified entity name, and the match must not be done in wild
13365 mode. Similarly, if the user wants to complete what looks
13366 like an encoded name, the match must not be done in wild
13367 mode. Also, in the standard__ special case always do
13368 non-wild matching. */
13370 = (lookup_name.match_type () != symbol_name_match_type::FULL
13373 && user_name.find ('.') == std::string::npos);
13377 /* symbol_name_matcher_ftype method for Ada. This only handles
13378 completion mode. */
13381 ada_symbol_name_matches (const char *symbol_search_name,
13382 const lookup_name_info &lookup_name,
13383 completion_match_result *comp_match_res)
13385 return lookup_name.ada ().matches (symbol_search_name,
13386 lookup_name.match_type (),
13390 /* A name matcher that matches the symbol name exactly, with
13394 literal_symbol_name_matcher (const char *symbol_search_name,
13395 const lookup_name_info &lookup_name,
13396 completion_match_result *comp_match_res)
13398 gdb::string_view name_view = lookup_name.name ();
13400 if (lookup_name.completion_mode ()
13401 ? (strncmp (symbol_search_name, name_view.data (),
13402 name_view.size ()) == 0)
13403 : symbol_search_name == name_view)
13405 if (comp_match_res != NULL)
13406 comp_match_res->set_match (symbol_search_name);
13413 /* Implement the "get_symbol_name_matcher" language_defn method for
13416 static symbol_name_matcher_ftype *
13417 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13419 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13420 return literal_symbol_name_matcher;
13422 if (lookup_name.completion_mode ())
13423 return ada_symbol_name_matches;
13426 if (lookup_name.ada ().wild_match_p ())
13427 return do_wild_match;
13428 else if (lookup_name.ada ().verbatim_p ())
13429 return do_exact_match;
13431 return do_full_match;
13435 /* Class representing the Ada language. */
13437 class ada_language : public language_defn
13441 : language_defn (language_ada)
13444 /* See language.h. */
13446 const char *name () const override
13449 /* See language.h. */
13451 const char *natural_name () const override
13454 /* See language.h. */
13456 const std::vector<const char *> &filename_extensions () const override
13458 static const std::vector<const char *> extensions
13459 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13463 /* Print an array element index using the Ada syntax. */
13465 void print_array_index (struct type *index_type,
13467 struct ui_file *stream,
13468 const value_print_options *options) const override
13470 struct value *index_value = val_atr (index_type, index);
13472 value_print (index_value, stream, options);
13473 gdb_printf (stream, " => ");
13476 /* Implement the "read_var_value" language_defn method for Ada. */
13478 struct value *read_var_value (struct symbol *var,
13479 const struct block *var_block,
13480 struct frame_info *frame) const override
13482 /* The only case where default_read_var_value is not sufficient
13483 is when VAR is a renaming... */
13484 if (frame != nullptr)
13486 const struct block *frame_block = get_frame_block (frame, NULL);
13487 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13488 return ada_read_renaming_var_value (var, frame_block);
13491 /* This is a typical case where we expect the default_read_var_value
13492 function to work. */
13493 return language_defn::read_var_value (var, var_block, frame);
13496 /* See language.h. */
13497 bool symbol_printing_suppressed (struct symbol *symbol) const override
13499 return symbol->is_artificial ();
13502 /* See language.h. */
13503 void language_arch_info (struct gdbarch *gdbarch,
13504 struct language_arch_info *lai) const override
13506 const struct builtin_type *builtin = builtin_type (gdbarch);
13508 /* Helper function to allow shorter lines below. */
13509 auto add = [&] (struct type *t)
13511 lai->add_primitive_type (t);
13514 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13516 add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
13517 0, "long_integer"));
13518 add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
13519 0, "short_integer"));
13520 struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
13522 lai->set_string_char_type (char_type);
13524 add (arch_character_type (gdbarch, 16, 1, "wide_character"));
13525 add (arch_character_type (gdbarch, 32, 1, "wide_wide_character"));
13526 add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
13527 "float", gdbarch_float_format (gdbarch)));
13528 add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
13529 "long_float", gdbarch_double_format (gdbarch)));
13530 add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
13531 0, "long_long_integer"));
13532 add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
13534 gdbarch_long_double_format (gdbarch)));
13535 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13537 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13539 add (builtin->builtin_void);
13541 struct type *system_addr_ptr
13542 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
13544 system_addr_ptr->set_name ("system__address");
13545 add (system_addr_ptr);
13547 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13548 type. This is a signed integral type whose size is the same as
13549 the size of addresses. */
13550 unsigned int addr_length = TYPE_LENGTH (system_addr_ptr);
13551 add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
13552 "storage_offset"));
13554 lai->set_bool_type (builtin->builtin_bool);
13557 /* See language.h. */
13559 bool iterate_over_symbols
13560 (const struct block *block, const lookup_name_info &name,
13561 domain_enum domain,
13562 gdb::function_view<symbol_found_callback_ftype> callback) const override
13564 std::vector<struct block_symbol> results
13565 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13566 for (block_symbol &sym : results)
13568 if (!callback (&sym))
13575 /* See language.h. */
13576 bool sniff_from_mangled_name
13577 (const char *mangled,
13578 gdb::unique_xmalloc_ptr<char> *out) const override
13580 std::string demangled = ada_decode (mangled);
13584 if (demangled != mangled && demangled[0] != '<')
13586 /* Set the gsymbol language to Ada, but still return 0.
13587 Two reasons for that:
13589 1. For Ada, we prefer computing the symbol's decoded name
13590 on the fly rather than pre-compute it, in order to save
13591 memory (Ada projects are typically very large).
13593 2. There are some areas in the definition of the GNAT
13594 encoding where, with a bit of bad luck, we might be able
13595 to decode a non-Ada symbol, generating an incorrect
13596 demangled name (Eg: names ending with "TB" for instance
13597 are identified as task bodies and so stripped from
13598 the decoded name returned).
13600 Returning true, here, but not setting *DEMANGLED, helps us get
13601 a little bit of the best of both worlds. Because we're last,
13602 we should not affect any of the other languages that were
13603 able to demangle the symbol before us; we get to correctly
13604 tag Ada symbols as such; and even if we incorrectly tagged a
13605 non-Ada symbol, which should be rare, any routing through the
13606 Ada language should be transparent (Ada tries to behave much
13607 like C/C++ with non-Ada symbols). */
13614 /* See language.h. */
13616 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13617 int options) const override
13619 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13622 /* See language.h. */
13624 void print_type (struct type *type, const char *varstring,
13625 struct ui_file *stream, int show, int level,
13626 const struct type_print_options *flags) const override
13628 ada_print_type (type, varstring, stream, show, level, flags);
13631 /* See language.h. */
13633 const char *word_break_characters (void) const override
13635 return ada_completer_word_break_characters;
13638 /* See language.h. */
13640 void collect_symbol_completion_matches (completion_tracker &tracker,
13641 complete_symbol_mode mode,
13642 symbol_name_match_type name_match_type,
13643 const char *text, const char *word,
13644 enum type_code code) const override
13646 struct symbol *sym;
13647 const struct block *b, *surrounding_static_block = 0;
13648 struct block_iterator iter;
13650 gdb_assert (code == TYPE_CODE_UNDEF);
13652 lookup_name_info lookup_name (text, name_match_type, true);
13654 /* First, look at the partial symtab symbols. */
13655 expand_symtabs_matching (NULL,
13659 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13662 /* At this point scan through the misc symbol vectors and add each
13663 symbol you find to the list. Eventually we want to ignore
13664 anything that isn't a text symbol (everything else will be
13665 handled by the psymtab code above). */
13667 for (objfile *objfile : current_program_space->objfiles ())
13669 for (minimal_symbol *msymbol : objfile->msymbols ())
13673 if (completion_skip_symbol (mode, msymbol))
13676 language symbol_language = msymbol->language ();
13678 /* Ada minimal symbols won't have their language set to Ada. If
13679 we let completion_list_add_name compare using the
13680 default/C-like matcher, then when completing e.g., symbols in a
13681 package named "pck", we'd match internal Ada symbols like
13682 "pckS", which are invalid in an Ada expression, unless you wrap
13683 them in '<' '>' to request a verbatim match.
13685 Unfortunately, some Ada encoded names successfully demangle as
13686 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13687 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13688 with the wrong language set. Paper over that issue here. */
13689 if (symbol_language == language_auto
13690 || symbol_language == language_cplus)
13691 symbol_language = language_ada;
13693 completion_list_add_name (tracker,
13695 msymbol->linkage_name (),
13696 lookup_name, text, word);
13700 /* Search upwards from currently selected frame (so that we can
13701 complete on local vars. */
13703 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13705 if (!b->superblock ())
13706 surrounding_static_block = b; /* For elmin of dups */
13708 ALL_BLOCK_SYMBOLS (b, iter, sym)
13710 if (completion_skip_symbol (mode, sym))
13713 completion_list_add_name (tracker,
13715 sym->linkage_name (),
13716 lookup_name, text, word);
13720 /* Go through the symtabs and check the externs and statics for
13721 symbols which match. */
13723 for (objfile *objfile : current_program_space->objfiles ())
13725 for (compunit_symtab *s : objfile->compunits ())
13728 b = s->blockvector ()->global_block ();
13729 ALL_BLOCK_SYMBOLS (b, iter, sym)
13731 if (completion_skip_symbol (mode, sym))
13734 completion_list_add_name (tracker,
13736 sym->linkage_name (),
13737 lookup_name, text, word);
13742 for (objfile *objfile : current_program_space->objfiles ())
13744 for (compunit_symtab *s : objfile->compunits ())
13747 b = s->blockvector ()->static_block ();
13748 /* Don't do this block twice. */
13749 if (b == surrounding_static_block)
13751 ALL_BLOCK_SYMBOLS (b, iter, sym)
13753 if (completion_skip_symbol (mode, sym))
13756 completion_list_add_name (tracker,
13758 sym->linkage_name (),
13759 lookup_name, text, word);
13765 /* See language.h. */
13767 gdb::unique_xmalloc_ptr<char> watch_location_expression
13768 (struct type *type, CORE_ADDR addr) const override
13770 type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
13771 std::string name = type_to_string (type);
13772 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13775 /* See language.h. */
13777 void value_print (struct value *val, struct ui_file *stream,
13778 const struct value_print_options *options) const override
13780 return ada_value_print (val, stream, options);
13783 /* See language.h. */
13785 void value_print_inner
13786 (struct value *val, struct ui_file *stream, int recurse,
13787 const struct value_print_options *options) const override
13789 return ada_value_print_inner (val, stream, recurse, options);
13792 /* See language.h. */
13794 struct block_symbol lookup_symbol_nonlocal
13795 (const char *name, const struct block *block,
13796 const domain_enum domain) const override
13798 struct block_symbol sym;
13800 sym = ada_lookup_symbol (name, block_static_block (block), domain);
13801 if (sym.symbol != NULL)
13804 /* If we haven't found a match at this point, try the primitive
13805 types. In other languages, this search is performed before
13806 searching for global symbols in order to short-circuit that
13807 global-symbol search if it happens that the name corresponds
13808 to a primitive type. But we cannot do the same in Ada, because
13809 it is perfectly legitimate for a program to declare a type which
13810 has the same name as a standard type. If looking up a type in
13811 that situation, we have traditionally ignored the primitive type
13812 in favor of user-defined types. This is why, unlike most other
13813 languages, we search the primitive types this late and only after
13814 having searched the global symbols without success. */
13816 if (domain == VAR_DOMAIN)
13818 struct gdbarch *gdbarch;
13821 gdbarch = target_gdbarch ();
13823 gdbarch = block_gdbarch (block);
13825 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13826 if (sym.symbol != NULL)
13833 /* See language.h. */
13835 int parser (struct parser_state *ps) const override
13837 warnings_issued = 0;
13838 return ada_parse (ps);
13841 /* See language.h. */
13843 void emitchar (int ch, struct type *chtype,
13844 struct ui_file *stream, int quoter) const override
13846 ada_emit_char (ch, chtype, stream, quoter, 1);
13849 /* See language.h. */
13851 void printchar (int ch, struct type *chtype,
13852 struct ui_file *stream) const override
13854 ada_printchar (ch, chtype, stream);
13857 /* See language.h. */
13859 void printstr (struct ui_file *stream, struct type *elttype,
13860 const gdb_byte *string, unsigned int length,
13861 const char *encoding, int force_ellipses,
13862 const struct value_print_options *options) const override
13864 ada_printstr (stream, elttype, string, length, encoding,
13865 force_ellipses, options);
13868 /* See language.h. */
13870 void print_typedef (struct type *type, struct symbol *new_symbol,
13871 struct ui_file *stream) const override
13873 ada_print_typedef (type, new_symbol, stream);
13876 /* See language.h. */
13878 bool is_string_type_p (struct type *type) const override
13880 return ada_is_string_type (type);
13883 /* See language.h. */
13885 const char *struct_too_deep_ellipsis () const override
13886 { return "(...)"; }
13888 /* See language.h. */
13890 bool c_style_arrays_p () const override
13893 /* See language.h. */
13895 bool store_sym_names_in_linkage_form_p () const override
13898 /* See language.h. */
13900 const struct lang_varobj_ops *varobj_ops () const override
13901 { return &ada_varobj_ops; }
13904 /* See language.h. */
13906 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13907 (const lookup_name_info &lookup_name) const override
13909 return ada_get_symbol_name_matcher (lookup_name);
13913 /* Single instance of the Ada language class. */
13915 static ada_language ada_language_defn;
13917 /* Command-list for the "set/show ada" prefix command. */
13918 static struct cmd_list_element *set_ada_list;
13919 static struct cmd_list_element *show_ada_list;
13921 /* This module's 'new_objfile' observer. */
13924 ada_new_objfile_observer (struct objfile *objfile)
13926 ada_clear_symbol_cache ();
13929 /* This module's 'free_objfile' observer. */
13932 ada_free_objfile_observer (struct objfile *objfile)
13934 ada_clear_symbol_cache ();
13937 /* Charsets known to GNAT. */
13938 static const char * const gnat_source_charsets[] =
13940 /* Note that code below assumes that the default comes first.
13941 Latin-1 is the default here, because that is also GNAT's
13951 /* Note that this value is special-cased in the encoder and
13957 void _initialize_ada_language ();
13959 _initialize_ada_language ()
13961 add_setshow_prefix_cmd
13963 _("Prefix command for changing Ada-specific settings."),
13964 _("Generic command for showing Ada-specific settings."),
13965 &set_ada_list, &show_ada_list,
13966 &setlist, &showlist);
13968 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13969 &trust_pad_over_xvs, _("\
13970 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13971 Show whether an optimization trusting PAD types over XVS types is activated."),
13973 This is related to the encoding used by the GNAT compiler. The debugger\n\
13974 should normally trust the contents of PAD types, but certain older versions\n\
13975 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13976 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13977 work around this bug. It is always safe to turn this option \"off\", but\n\
13978 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13979 this option to \"off\" unless necessary."),
13980 NULL, NULL, &set_ada_list, &show_ada_list);
13982 add_setshow_boolean_cmd ("print-signatures", class_vars,
13983 &print_signatures, _("\
13984 Enable or disable the output of formal and return types for functions in the \
13985 overloads selection menu."), _("\
13986 Show whether the output of formal and return types for functions in the \
13987 overloads selection menu is activated."),
13988 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13990 ada_source_charset = gnat_source_charsets[0];
13991 add_setshow_enum_cmd ("source-charset", class_files,
13992 gnat_source_charsets,
13993 &ada_source_charset, _("\
13994 Set the Ada source character set."), _("\
13995 Show the Ada source character set."), _("\
13996 The character set used for Ada source files.\n\
13997 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13999 &set_ada_list, &show_ada_list);
14001 add_catch_command ("exception", _("\
14002 Catch Ada exceptions, when raised.\n\
14003 Usage: catch exception [ARG] [if CONDITION]\n\
14004 Without any argument, stop when any Ada exception is raised.\n\
14005 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14006 being raised does not have a handler (and will therefore lead to the task's\n\
14008 Otherwise, the catchpoint only stops when the name of the exception being\n\
14009 raised is the same as ARG.\n\
14010 CONDITION is a boolean expression that is evaluated to see whether the\n\
14011 exception should cause a stop."),
14012 catch_ada_exception_command,
14013 catch_ada_completer,
14017 add_catch_command ("handlers", _("\
14018 Catch Ada exceptions, when handled.\n\
14019 Usage: catch handlers [ARG] [if CONDITION]\n\
14020 Without any argument, stop when any Ada exception is handled.\n\
14021 With an argument, catch only exceptions with the given name.\n\
14022 CONDITION is a boolean expression that is evaluated to see whether the\n\
14023 exception should cause a stop."),
14024 catch_ada_handlers_command,
14025 catch_ada_completer,
14028 add_catch_command ("assert", _("\
14029 Catch failed Ada assertions, when raised.\n\
14030 Usage: catch assert [if CONDITION]\n\
14031 CONDITION is a boolean expression that is evaluated to see whether the\n\
14032 exception should cause a stop."),
14033 catch_assert_command,
14038 add_info ("exceptions", info_exceptions_command,
14040 List all Ada exception names.\n\
14041 Usage: info exceptions [REGEXP]\n\
14042 If a regular expression is passed as an argument, only those matching\n\
14043 the regular expression are listed."));
14045 add_setshow_prefix_cmd ("ada", class_maintenance,
14046 _("Set Ada maintenance-related variables."),
14047 _("Show Ada maintenance-related variables."),
14048 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14049 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14051 add_setshow_boolean_cmd
14052 ("ignore-descriptive-types", class_maintenance,
14053 &ada_ignore_descriptive_types_p,
14054 _("Set whether descriptive types generated by GNAT should be ignored."),
14055 _("Show whether descriptive types generated by GNAT should be ignored."),
14057 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14058 DWARF attribute."),
14059 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14061 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14063 NULL, xcalloc, xfree);
14065 /* The ada-lang observers. */
14066 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14067 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14068 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");