arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / gdb / ada-lang.c
blobdc1b841c5d49644d053ef02e861bc72b8cac117b
1 /* Ada language support routines for GDB, the GNU debugger.
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include <ctype.h>
22 #include "event-top.h"
23 #include "exceptions.h"
24 #include "extract-store-integer.h"
25 #include "gdbsupport/gdb_regex.h"
26 #include "frame.h"
27 #include "symtab.h"
28 #include "gdbtypes.h"
29 #include "cli/cli-cmds.h"
30 #include "expression.h"
31 #include "parser-defs.h"
32 #include "language.h"
33 #include "varobj.h"
34 #include "inferior.h"
35 #include "symfile.h"
36 #include "objfiles.h"
37 #include "breakpoint.h"
38 #include "gdbcore.h"
39 #include "hashtab.h"
40 #include "gdbsupport/gdb_obstack.h"
41 #include "ada-lang.h"
42 #include "completer.h"
43 #include "ui-out.h"
44 #include "block.h"
45 #include "infcall.h"
46 #include "annotate.h"
47 #include "valprint.h"
48 #include "source.h"
49 #include "observable.h"
50 #include "stack.h"
51 #include "typeprint.h"
52 #include "namespace.h"
53 #include "cli/cli-style.h"
54 #include "cli/cli-decode.h"
56 #include "value.h"
57 #include "mi/mi-common.h"
58 #include "arch-utils.h"
59 #include "cli/cli-utils.h"
60 #include "gdbsupport/function-view.h"
61 #include "gdbsupport/byte-vector.h"
62 #include "gdbsupport/selftest.h"
63 #include <algorithm>
64 #include "ada-exp.h"
65 #include "charset.h"
66 #include "ax-gdb.h"
68 static struct type *desc_base_type (struct type *);
70 static struct type *desc_bounds_type (struct type *);
72 static struct value *desc_bounds (struct value *);
74 static int fat_pntr_bounds_bitpos (struct type *);
76 static int fat_pntr_bounds_bitsize (struct type *);
78 static struct type *desc_data_target_type (struct type *);
80 static struct value *desc_data (struct value *);
82 static int fat_pntr_data_bitpos (struct type *);
84 static int fat_pntr_data_bitsize (struct type *);
86 static struct value *desc_one_bound (struct value *, int, int);
88 static int desc_bound_bitpos (struct type *, int, int);
90 static int desc_bound_bitsize (struct type *, int, int);
92 static struct type *desc_index_type (struct type *, int);
94 static int desc_arity (struct type *);
96 static int ada_args_match (struct symbol *, struct value **, int);
98 static struct value *make_array_descriptor (struct type *, struct value *);
100 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
101 const struct block *,
102 const lookup_name_info &lookup_name,
103 domain_search_flags, struct objfile *);
105 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
106 const struct block *,
107 const lookup_name_info &lookup_name,
108 domain_search_flags, int, int *);
110 static int is_nonfunction (const std::vector<struct block_symbol> &);
112 static void add_defn_to_vec (std::vector<struct block_symbol> &,
113 struct symbol *,
114 const struct block *);
116 static int possible_user_operator_p (enum exp_opcode, struct value **);
118 static const char *ada_decoded_op_name (enum exp_opcode);
120 static int numeric_type_p (struct type *);
122 static int integer_type_p (struct type *);
124 static int scalar_type_p (struct type *);
126 static int discrete_type_p (struct type *);
128 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
129 int, int);
131 static struct type *ada_find_parallel_type_with_name (struct type *,
132 const char *);
134 static int is_dynamic_field (struct type *, int);
136 static struct type *to_fixed_variant_branch_type (struct type *,
137 const gdb_byte *,
138 CORE_ADDR, struct value *);
140 static struct type *to_fixed_array_type (struct type *, struct value *, int);
142 static struct type *to_fixed_range_type (struct type *, struct value *);
144 static struct type *to_static_fixed_type (struct type *);
145 static struct type *static_unwrap_type (struct type *type);
147 static struct value *unwrap_value (struct value *);
149 static struct type *constrained_packed_array_type (struct type *, long *);
151 static struct type *decode_constrained_packed_array_type (struct type *);
153 static long decode_packed_array_bitsize (struct type *);
155 static struct value *decode_constrained_packed_array (struct value *);
157 static int ada_is_unconstrained_packed_array_type (struct type *);
159 static struct value *value_subscript_packed (struct value *, int,
160 struct value **);
162 static struct value *coerce_unspec_val_to_type (struct value *,
163 struct type *);
165 static int lesseq_defined_than (struct symbol *, struct symbol *);
167 static int equiv_types (struct type *, struct type *);
169 static int is_name_suffix (const char *);
171 static int advance_wild_match (const char **, const char *, char);
173 static bool wild_match (const char *name, const char *patn);
175 static struct value *ada_coerce_ref (struct value *);
177 static LONGEST pos_atr (struct value *);
179 static struct value *val_atr (struct type *, LONGEST);
181 static struct value *ada_search_struct_field (const char *, struct value *, int,
182 struct type *);
184 static int find_struct_field (const char *, struct type *, int,
185 struct type **, int *, int *, int *, int *);
187 static int ada_resolve_function (std::vector<struct block_symbol> &,
188 struct value **, int, const char *,
189 struct type *, bool);
191 static int ada_is_direct_array_type (struct type *);
193 static struct value *ada_index_struct_field (int, struct value *, int,
194 struct type *);
196 static struct type *ada_find_any_type (const char *name);
198 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
199 (const lookup_name_info &lookup_name);
201 static int symbols_are_identical_enums
202 (const std::vector<struct block_symbol> &syms);
204 static bool ada_identical_enum_types_p (struct type *type1,
205 struct type *type2);
208 /* The character set used for source files. */
209 static const char *ada_source_charset;
211 /* The string "UTF-8". This is here so we can check for the UTF-8
212 charset using == rather than strcmp. */
213 static const char ada_utf8[] = "UTF-8";
215 /* Each entry in the UTF-32 case-folding table is of this form. */
216 struct utf8_entry
218 /* The start and end, inclusive, of this range of codepoints. */
219 uint32_t start, end;
220 /* The delta to apply to get the upper-case form. 0 if this is
221 already upper-case. */
222 int upper_delta;
223 /* The delta to apply to get the lower-case form. 0 if this is
224 already lower-case. */
225 int lower_delta;
227 bool operator< (uint32_t val) const
229 return end < val;
233 static const utf8_entry ada_case_fold[] =
235 #include "ada-casefold.h"
240 static const char ada_completer_word_break_characters[] =
241 #ifdef VMS
242 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
243 #else
244 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
245 #endif
247 /* The name of the symbol to use to get the name of the main subprogram. */
248 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
249 = "__gnat_ada_main_program_name";
251 /* Limit on the number of warnings to raise per expression evaluation. */
252 static int warning_limit = 2;
254 /* Number of warning messages issued; reset to 0 by cleanups after
255 expression evaluation. */
256 static int warnings_issued = 0;
258 static const char * const known_runtime_file_name_patterns[] = {
259 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
262 static const char * const known_auxiliary_function_name_patterns[] = {
263 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
266 /* Maintenance-related settings for this module. */
268 static struct cmd_list_element *maint_set_ada_cmdlist;
269 static struct cmd_list_element *maint_show_ada_cmdlist;
271 /* The "maintenance ada set/show ignore-descriptive-type" value. */
273 static bool ada_ignore_descriptive_types_p = false;
275 /* Inferior-specific data. */
277 /* Per-inferior data for this module. */
279 struct ada_inferior_data
281 /* The ada__tags__type_specific_data type, which is used when decoding
282 tagged types. With older versions of GNAT, this type was directly
283 accessible through a component ("tsd") in the object tag. But this
284 is no longer the case, so we cache it for each inferior. */
285 struct type *tsd_type = nullptr;
287 /* The exception_support_info data. This data is used to determine
288 how to implement support for Ada exception catchpoints in a given
289 inferior. */
290 const struct exception_support_info *exception_info = nullptr;
293 /* Our key to this module's inferior data. */
294 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
296 /* Return our inferior data for the given inferior (INF).
298 This function always returns a valid pointer to an allocated
299 ada_inferior_data structure. If INF's inferior data has not
300 been previously set, this functions creates a new one with all
301 fields set to zero, sets INF's inferior to it, and then returns
302 a pointer to that newly allocated ada_inferior_data. */
304 static struct ada_inferior_data *
305 get_ada_inferior_data (struct inferior *inf)
307 struct ada_inferior_data *data;
309 data = ada_inferior_data.get (inf);
310 if (data == NULL)
311 data = ada_inferior_data.emplace (inf);
313 return data;
316 /* Perform all necessary cleanups regarding our module's inferior data
317 that is required after the inferior INF just exited. */
319 static void
320 ada_inferior_exit (struct inferior *inf)
322 ada_inferior_data.clear (inf);
326 /* program-space-specific data. */
328 /* The result of a symbol lookup to be stored in our symbol cache. */
330 struct cache_entry
332 /* The name used to perform the lookup. */
333 std::string name;
334 /* The namespace used during the lookup. */
335 domain_search_flags domain = 0;
336 /* The symbol returned by the lookup, or NULL if no matching symbol
337 was found. */
338 struct symbol *sym = nullptr;
339 /* The block where the symbol was found, or NULL if no matching
340 symbol was found. */
341 const struct block *block = nullptr;
344 /* The symbol cache uses this type when searching. */
346 struct cache_entry_search
348 const char *name;
349 domain_search_flags domain;
351 hashval_t hash () const
353 /* This must agree with hash_cache_entry, below. */
354 return htab_hash_string (name);
358 /* Hash function for cache_entry. */
360 static hashval_t
361 hash_cache_entry (const void *v)
363 const cache_entry *entry = (const cache_entry *) v;
364 return htab_hash_string (entry->name.c_str ());
367 /* Equality function for cache_entry. */
369 static int
370 eq_cache_entry (const void *a, const void *b)
372 const cache_entry *entrya = (const cache_entry *) a;
373 const cache_entry_search *entryb = (const cache_entry_search *) b;
375 return entrya->domain == entryb->domain && entrya->name == entryb->name;
378 /* Key to our per-program-space data. */
379 static const registry<program_space>::key<htab, htab_deleter>
380 ada_pspace_data_handle;
382 /* Return this module's data for the given program space (PSPACE).
383 If not is found, add a zero'ed one now.
385 This function always returns a valid object. */
387 static htab_t
388 get_ada_pspace_data (struct program_space *pspace)
390 htab_t data = ada_pspace_data_handle.get (pspace);
391 if (data == nullptr)
393 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
394 htab_delete_entry<cache_entry>,
395 xcalloc, xfree);
396 ada_pspace_data_handle.set (pspace, data);
399 return data;
402 /* Utilities */
404 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
405 all typedef layers have been peeled. Otherwise, return TYPE.
407 Normally, we really expect a typedef type to only have 1 typedef layer.
408 In other words, we really expect the target type of a typedef type to be
409 a non-typedef type. This is particularly true for Ada units, because
410 the language does not have a typedef vs not-typedef distinction.
411 In that respect, the Ada compiler has been trying to eliminate as many
412 typedef definitions in the debugging information, since they generally
413 do not bring any extra information (we still use typedef under certain
414 circumstances related mostly to the GNAT encoding).
416 Unfortunately, we have seen situations where the debugging information
417 generated by the compiler leads to such multiple typedef layers. For
418 instance, consider the following example with stabs:
420 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
421 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
423 This is an error in the debugging information which causes type
424 pck__float_array___XUP to be defined twice, and the second time,
425 it is defined as a typedef of a typedef.
427 This is on the fringe of legality as far as debugging information is
428 concerned, and certainly unexpected. But it is easy to handle these
429 situations correctly, so we can afford to be lenient in this case. */
431 static struct type *
432 ada_typedef_target_type (struct type *type)
434 while (type->code () == TYPE_CODE_TYPEDEF)
435 type = type->target_type ();
436 return type;
439 /* Given DECODED_NAME a string holding a symbol name in its
440 decoded form (ie using the Ada dotted notation), returns
441 its unqualified name. */
443 static const char *
444 ada_unqualified_name (const char *decoded_name)
446 const char *result;
448 /* If the decoded name starts with '<', it means that the encoded
449 name does not follow standard naming conventions, and thus that
450 it is not your typical Ada symbol name. Trying to unqualify it
451 is therefore pointless and possibly erroneous. */
452 if (decoded_name[0] == '<')
453 return decoded_name;
455 result = strrchr (decoded_name, '.');
456 if (result != NULL)
457 result++; /* Skip the dot... */
458 else
459 result = decoded_name;
461 return result;
464 /* Return a string starting with '<', followed by STR, and '>'. */
466 static std::string
467 add_angle_brackets (const char *str)
469 return string_printf ("<%s>", str);
472 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
473 suffix of FIELD_NAME beginning "___". */
475 static int
476 field_name_match (const char *field_name, const char *target)
478 int len = strlen (target);
480 return
481 (strncmp (field_name, target, len) == 0
482 && (field_name[len] == '\0'
483 || (startswith (field_name + len, "___")
484 && strcmp (field_name + strlen (field_name) - 6,
485 "___XVN") != 0)));
489 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
490 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
491 and return its index. This function also handles fields whose name
492 have ___ suffixes because the compiler sometimes alters their name
493 by adding such a suffix to represent fields with certain constraints.
494 If the field could not be found, return a negative number if
495 MAYBE_MISSING is set. Otherwise raise an error. */
498 ada_get_field_index (const struct type *type, const char *field_name,
499 int maybe_missing)
501 int fieldno;
502 struct type *struct_type = check_typedef ((struct type *) type);
504 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
505 if (field_name_match (struct_type->field (fieldno).name (), field_name))
506 return fieldno;
508 if (!maybe_missing)
509 error (_("Unable to find field %s in struct %s. Aborting"),
510 field_name, struct_type->name ());
512 return -1;
515 /* The length of the prefix of NAME prior to any "___" suffix. */
518 ada_name_prefix_len (const char *name)
520 if (name == NULL)
521 return 0;
522 else
524 const char *p = strstr (name, "___");
526 if (p == NULL)
527 return strlen (name);
528 else
529 return p - name;
533 /* Return non-zero if SUFFIX is a suffix of STR.
534 Return zero if STR is null. */
536 static int
537 is_suffix (const char *str, const char *suffix)
539 int len1, len2;
541 if (str == NULL)
542 return 0;
543 len1 = strlen (str);
544 len2 = strlen (suffix);
545 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
548 /* The contents of value VAL, treated as a value of type TYPE. The
549 result is an lval in memory if VAL is. */
551 static struct value *
552 coerce_unspec_val_to_type (struct value *val, struct type *type)
554 type = ada_check_typedef (type);
555 if (val->type () == type)
556 return val;
557 else
559 struct value *result;
561 if (val->optimized_out ())
562 result = value::allocate_optimized_out (type);
563 else if (val->lazy ()
564 /* Be careful not to make a lazy not_lval value. */
565 || (val->lval () != not_lval
566 && type->length () > val->type ()->length ()))
567 result = value::allocate_lazy (type);
568 else
570 result = value::allocate (type);
571 val->contents_copy (result, 0, 0, type->length ());
573 result->set_component_location (val);
574 result->set_bitsize (val->bitsize ());
575 result->set_bitpos (val->bitpos ());
576 if (result->lval () == lval_memory)
577 result->set_address (val->address ());
578 return result;
582 static const gdb_byte *
583 cond_offset_host (const gdb_byte *valaddr, long offset)
585 if (valaddr == NULL)
586 return NULL;
587 else
588 return valaddr + offset;
591 static CORE_ADDR
592 cond_offset_target (CORE_ADDR address, long offset)
594 if (address == 0)
595 return 0;
596 else
597 return address + offset;
600 /* Issue a warning (as for the definition of warning in utils.c, but
601 with exactly one argument rather than ...), unless the limit on the
602 number of warnings has passed during the evaluation of the current
603 expression. */
605 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
606 provided by "complaint". */
607 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
609 static void
610 lim_warning (const char *format, ...)
612 va_list args;
614 va_start (args, format);
615 warnings_issued += 1;
616 if (warnings_issued <= warning_limit)
617 vwarning (format, args);
619 va_end (args);
622 /* Maximum value of a SIZE-byte signed integer type. */
623 static LONGEST
624 max_of_size (int size)
626 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
628 return top_bit | (top_bit - 1);
631 /* Minimum value of a SIZE-byte signed integer type. */
632 static LONGEST
633 min_of_size (int size)
635 return -max_of_size (size) - 1;
638 /* Maximum value of a SIZE-byte unsigned integer type. */
639 static ULONGEST
640 umax_of_size (int size)
642 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
644 return top_bit | (top_bit - 1);
647 /* Maximum value of integral type T, as a signed quantity. */
648 static LONGEST
649 max_of_type (struct type *t)
651 if (t->is_unsigned ())
652 return (LONGEST) umax_of_size (t->length ());
653 else
654 return max_of_size (t->length ());
657 /* Minimum value of integral type T, as a signed quantity. */
658 static LONGEST
659 min_of_type (struct type *t)
661 if (t->is_unsigned ())
662 return 0;
663 else
664 return min_of_size (t->length ());
667 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
668 LONGEST
669 ada_discrete_type_high_bound (struct type *type)
671 type = resolve_dynamic_type (type, {}, 0);
672 switch (type->code ())
674 case TYPE_CODE_RANGE:
676 const dynamic_prop &high = type->bounds ()->high;
678 if (high.is_constant ())
679 return high.const_val ();
680 else
682 gdb_assert (!high.is_available ());
684 /* This happens when trying to evaluate a type's dynamic bound
685 without a live target. There is nothing relevant for us to
686 return here, so return 0. */
687 return 0;
690 case TYPE_CODE_ENUM:
691 return type->field (type->num_fields () - 1).loc_enumval ();
692 case TYPE_CODE_BOOL:
693 return 1;
694 case TYPE_CODE_CHAR:
695 case TYPE_CODE_INT:
696 return max_of_type (type);
697 default:
698 error (_("Unexpected type in ada_discrete_type_high_bound."));
702 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
703 LONGEST
704 ada_discrete_type_low_bound (struct type *type)
706 type = resolve_dynamic_type (type, {}, 0);
707 switch (type->code ())
709 case TYPE_CODE_RANGE:
711 const dynamic_prop &low = type->bounds ()->low;
713 if (low.is_constant ())
714 return low.const_val ();
715 else
717 gdb_assert (!low.is_available ());
719 /* This happens when trying to evaluate a type's dynamic bound
720 without a live target. There is nothing relevant for us to
721 return here, so return 0. */
722 return 0;
725 case TYPE_CODE_ENUM:
726 return type->field (0).loc_enumval ();
727 case TYPE_CODE_BOOL:
728 return 0;
729 case TYPE_CODE_CHAR:
730 case TYPE_CODE_INT:
731 return min_of_type (type);
732 default:
733 error (_("Unexpected type in ada_discrete_type_low_bound."));
737 /* The identity on non-range types. For range types, the underlying
738 non-range scalar type. */
740 static struct type *
741 get_base_type (struct type *type)
743 while (type != NULL && type->code () == TYPE_CODE_RANGE)
745 if (type == type->target_type () || type->target_type () == NULL)
746 return type;
747 type = type->target_type ();
749 return type;
752 /* Return a decoded version of the given VALUE. This means returning
753 a value whose type is obtained by applying all the GNAT-specific
754 encodings, making the resulting type a static but standard description
755 of the initial type. */
757 struct value *
758 ada_get_decoded_value (struct value *value)
760 struct type *type = ada_check_typedef (value->type ());
762 if (ada_is_array_descriptor_type (type)
763 || (ada_is_constrained_packed_array_type (type)
764 && type->code () != TYPE_CODE_PTR))
766 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
767 value = ada_coerce_to_simple_array_ptr (value);
768 else
769 value = ada_coerce_to_simple_array (value);
771 else
772 value = ada_to_fixed_value (value);
774 return value;
777 /* Same as ada_get_decoded_value, but with the given TYPE.
778 Because there is no associated actual value for this type,
779 the resulting type might be a best-effort approximation in
780 the case of dynamic types. */
782 struct type *
783 ada_get_decoded_type (struct type *type)
785 type = to_static_fixed_type (type);
786 if (ada_is_constrained_packed_array_type (type))
787 type = ada_coerce_to_simple_array_type (type);
788 return type;
793 /* Language Selection */
795 /* If the main procedure is written in Ada, then return its name.
796 The result is good until the next call. Return NULL if the main
797 procedure doesn't appear to be in Ada. */
799 const char *
800 ada_main_name ()
802 static gdb::unique_xmalloc_ptr<char> main_program_name;
804 /* For Ada, the name of the main procedure is stored in a specific
805 string constant, generated by the binder. Look for that symbol,
806 extract its address, and then read that string. If we didn't find
807 that string, then most probably the main procedure is not written
808 in Ada. */
809 bound_minimal_symbol msym
810 = lookup_minimal_symbol (current_program_space,
811 ADA_MAIN_PROGRAM_SYMBOL_NAME);
813 if (msym.minsym != NULL)
815 CORE_ADDR main_program_name_addr = msym.value_address ();
816 if (main_program_name_addr == 0)
817 error (_("Invalid address for Ada main program name."));
819 /* Force trust_readonly, because we always want to fetch this
820 string from the executable, not from inferior memory. If the
821 user changes the exec-file and invokes "start", we want to
822 pick the "main" from the new executable, not one that may
823 come from the still-live inferior. */
824 scoped_restore save_trust_readonly
825 = make_scoped_restore (&trust_readonly, true);
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. */
831 return NULL;
834 /* Symbols */
836 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
837 of NULLs. */
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},
861 {NULL, NULL}
864 /* If STR is a decoded version of a compiler-provided suffix (like the
865 "[cold]" in "symbol[cold]"), return true. Otherwise, return
866 false. */
868 static bool
869 is_compiler_suffix (const char *str)
871 gdb_assert (*str == '[');
872 ++str;
873 while (*str != '\0' && isalpha (*str))
874 ++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. */
880 static void
881 append_hex_encoded (std::string &result, uint32_t one_char)
883 if (one_char <= 0xff)
885 result.append ("U");
886 result.append (phex (one_char, 1));
888 else if (one_char <= 0xffff)
890 result.append ("W");
891 result.append (phex (one_char, 2));
893 else
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. */
904 template<typename T>
905 std::string
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);
910 std::string result;
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]);
919 else
920 append_hex_encoded (result, chars[i]);
922 return result;
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. */
929 static std::string
930 ada_encode_1 (const char *decoded, bool throw_errors)
932 if (decoded == NULL)
933 return {};
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;
942 if (*p == '.')
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 ();
949 break;
951 else if (*p == '"')
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)
961 if (throw_errors)
962 error (_("invalid Ada operator name: %s"), p);
963 else
964 return {};
966 encoding_buffer.append (mapping->encoded);
967 break;
969 else
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. */
976 if (saw_non_ascii)
978 auto_obstack storage;
979 bool is_utf8 = ada_source_charset == ada_utf8;
982 convert_between_encodings
983 (host_charset (),
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. */
995 if (!warned)
997 warned = true;
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;
1007 if (is_utf8)
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)
1024 || c < iter->start
1025 || c > iter->end)
1026 return nullptr;
1027 return &*iter;
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. */
1035 static const char *
1036 ada_fold_name (std::string_view name, bool throw_on_error = false)
1038 static std::string fold_storage;
1040 if (!name.empty () && name[0] == '\'')
1041 fold_storage = name.substr (1, name.size () - 2);
1042 else
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
1053 upper case.
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
1058 forbidden. */
1059 auto_obstack storage;
1062 convert_between_encodings
1063 (host_charset (), HOST_UTF32,
1064 (const gdb_byte *) name.data (),
1065 name.length (), 1,
1066 &storage, translit_none);
1068 catch (const gdb_exception &)
1070 if (throw_on_error)
1071 throw;
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. */
1077 if (!warned)
1079 warned = true;
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 std::string (name).c_str (), host_charset ());
1085 /* We don't try to recover from errors; just return the
1086 original string. */
1087 fold_storage = 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)
1101 chars[i] = low;
1102 else
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,
1112 host_charset (),
1113 (const gdb_byte *) chars,
1114 num_chars * sizeof (uint32_t),
1115 sizeof (uint32_t),
1116 &reconverted,
1117 translit_none);
1118 obstack_1grow (&reconverted, '\0');
1119 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1121 catch (const gdb_exception &)
1123 if (throw_on_error)
1124 throw;
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
1130 equivalence. */
1131 if (!warned)
1133 warned = true;
1134 warning (_("could not convert the lower-cased variant of '%s'\n"
1135 "from UTF-32 to the host encoding (%s)."),
1136 std::string (name).c_str (), host_charset ());
1139 /* We don't try to recover from errors; just return the
1140 original string. */
1141 fold_storage = name;
1145 return fold_storage.c_str ();
1148 /* The "encoded" form of DECODED, according to GNAT conventions. If
1149 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1150 with <...> quoting are not folded in any case. */
1152 std::string
1153 ada_encode (const char *decoded, bool fold)
1155 if (fold && decoded[0] != '<')
1156 decoded = ada_fold_name (decoded);
1157 return ada_encode_1 (decoded, true);
1160 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1162 static int
1163 is_lower_alphanum (const char c)
1165 return (isdigit (c) || (isalpha (c) && islower (c)));
1168 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1169 This function saves in LEN the length of that same symbol name but
1170 without either of these suffixes:
1171 . .{DIGIT}+
1172 . ${DIGIT}+
1173 . ___{DIGIT}+
1174 . __{DIGIT}+.
1176 These are suffixes introduced by the compiler for entities such as
1177 nested subprogram for instance, in order to avoid name clashes.
1178 They do not serve any purpose for the debugger. */
1180 static void
1181 ada_remove_trailing_digits (const char *encoded, int *len)
1183 if (*len > 1 && isdigit (encoded[*len - 1]))
1185 int i = *len - 2;
1187 while (i > 0 && isdigit (encoded[i]))
1188 i--;
1189 if (i >= 0 && encoded[i] == '.')
1190 *len = i;
1191 else if (i >= 0 && encoded[i] == '$')
1192 *len = i;
1193 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1194 *len = i - 2;
1195 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1196 *len = i - 1;
1200 /* Remove the suffix introduced by the compiler for protected object
1201 subprograms. */
1203 static void
1204 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1206 /* Remove trailing N. */
1208 /* Protected entry subprograms are broken into two
1209 separate subprograms: The first one is unprotected, and has
1210 a 'N' suffix; the second is the protected version, and has
1211 the 'P' suffix. The second calls the first one after handling
1212 the protection. Since the P subprograms are internally generated,
1213 we leave these names undecoded, giving the user a clue that this
1214 entity is internal. */
1216 if (*len > 1
1217 && encoded[*len - 1] == 'N'
1218 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1219 *len = *len - 1;
1222 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1223 then update *LEN to remove the suffix and return the offset of the
1224 character just past the ".". Otherwise, return -1. */
1226 static int
1227 remove_compiler_suffix (const char *encoded, int *len)
1229 int offset = *len - 1;
1230 while (offset > 0 && isalpha (encoded[offset]))
1231 --offset;
1232 if (offset > 0 && encoded[offset] == '.')
1234 *len = offset;
1235 return offset + 1;
1237 return -1;
1240 /* Convert an ASCII hex string to a number. Reads exactly N
1241 characters from STR. Returns true on success, false if one of the
1242 digits was not a hex digit. */
1243 static bool
1244 convert_hex (const char *str, int n, uint32_t *out)
1246 uint32_t result = 0;
1248 for (int i = 0; i < n; ++i)
1250 if (!isxdigit (str[i]))
1251 return false;
1252 result <<= 4;
1253 result |= fromhex (str[i]);
1256 *out = result;
1257 return true;
1260 /* Convert a wide character from its ASCII hex representation in STR
1261 (consisting of exactly N characters) to the host encoding,
1262 appending the resulting bytes to OUT. If N==2 and the Ada source
1263 charset is not UTF-8, then hex refers to an encoding in the
1264 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1265 Return false and do not modify OUT on conversion failure. */
1266 static bool
1267 convert_from_hex_encoded (std::string &out, const char *str, int n)
1269 uint32_t value;
1271 if (!convert_hex (str, n, &value))
1272 return false;
1275 auto_obstack bytes;
1276 /* In the 'U' case, the hex digits encode the character in the
1277 Ada source charset. However, if the source charset is UTF-8,
1278 this really means it is a single-byte UTF-32 character. */
1279 if (n == 2 && ada_source_charset != ada_utf8)
1281 gdb_byte one_char = (gdb_byte) value;
1283 convert_between_encodings (ada_source_charset, host_charset (),
1284 &one_char,
1285 sizeof (one_char), sizeof (one_char),
1286 &bytes, translit_none);
1288 else
1289 convert_between_encodings (HOST_UTF32, host_charset (),
1290 (const gdb_byte *) &value,
1291 sizeof (value), sizeof (value),
1292 &bytes, translit_none);
1293 obstack_1grow (&bytes, '\0');
1294 out.append ((const char *) obstack_base (&bytes));
1296 catch (const gdb_exception &)
1298 /* On failure, the caller will just let the encoded form
1299 through, which seems basically reasonable. */
1300 return false;
1303 return true;
1306 /* See ada-lang.h. */
1308 std::string
1309 ada_decode (const char *encoded, bool wrap, bool operators, bool wide)
1311 int i;
1312 int len0;
1313 const char *p;
1314 int at_start_name;
1315 std::string decoded;
1316 int suffix = -1;
1318 /* With function descriptors on PPC64, the value of a symbol named
1319 ".FN", if it exists, is the entry point of the function "FN". */
1320 if (encoded[0] == '.')
1321 encoded += 1;
1323 /* The name of the Ada main procedure starts with "_ada_".
1324 This prefix is not part of the decoded name, so skip this part
1325 if we see this prefix. */
1326 if (startswith (encoded, "_ada_"))
1327 encoded += 5;
1328 /* The "___ghost_" prefix is used for ghost entities. Normally
1329 these aren't preserved but when they are, it's useful to see
1330 them. */
1331 if (startswith (encoded, "___ghost_"))
1332 encoded += 9;
1334 /* If the name starts with '_', then it is not a properly encoded
1335 name, so do not attempt to decode it. Similarly, if the name
1336 starts with '<', the name should not be decoded. */
1337 if (encoded[0] == '_' || encoded[0] == '<')
1338 goto Suppress;
1340 len0 = strlen (encoded);
1342 suffix = remove_compiler_suffix (encoded, &len0);
1344 ada_remove_trailing_digits (encoded, &len0);
1345 ada_remove_po_subprogram_suffix (encoded, &len0);
1347 /* Remove the ___X.* suffix if present. Do not forget to verify that
1348 the suffix is located before the current "end" of ENCODED. We want
1349 to avoid re-matching parts of ENCODED that have previously been
1350 marked as discarded (by decrementing LEN0). */
1351 p = strstr (encoded, "___");
1352 if (p != NULL && p - encoded < len0 - 3)
1354 if (p[3] == 'X')
1355 len0 = p - encoded;
1356 else
1357 goto Suppress;
1360 /* Remove any trailing TKB suffix. It tells us that this symbol
1361 is for the body of a task, but that information does not actually
1362 appear in the decoded name. */
1364 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1365 len0 -= 3;
1367 /* Remove any trailing TB suffix. The TB suffix is slightly different
1368 from the TKB suffix because it is used for non-anonymous task
1369 bodies. */
1371 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1372 len0 -= 2;
1374 /* Remove trailing "B" suffixes. */
1375 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1377 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1378 len0 -= 1;
1380 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1382 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1384 i = len0 - 2;
1385 while ((i >= 0 && isdigit (encoded[i]))
1386 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1387 i -= 1;
1388 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1389 len0 = i - 1;
1390 else if (i >= 0 && encoded[i] == '$')
1391 len0 = i;
1394 /* The first few characters that are not alphabetic are not part
1395 of any encoding we use, so we can copy them over verbatim. */
1397 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1398 decoded.push_back (encoded[i]);
1400 at_start_name = 1;
1401 while (i < len0)
1403 /* Is this a symbol function? */
1404 if (operators && at_start_name && encoded[i] == 'O')
1406 int k;
1408 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1410 int op_len = strlen (ada_opname_table[k].encoded);
1411 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1412 op_len - 1) == 0)
1413 && !isalnum (encoded[i + op_len]))
1415 decoded.append (ada_opname_table[k].decoded);
1416 at_start_name = 0;
1417 i += op_len;
1418 break;
1421 if (ada_opname_table[k].encoded != NULL)
1422 continue;
1424 at_start_name = 0;
1426 /* Replace "TK__" with "__", which will eventually be translated
1427 into "." (just below). */
1429 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1430 i += 2;
1432 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1433 be translated into "." (just below). These are internal names
1434 generated for anonymous blocks inside which our symbol is nested. */
1436 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1437 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1438 && isdigit (encoded [i+4]))
1440 int k = i + 5;
1442 while (k < len0 && isdigit (encoded[k]))
1443 k++; /* Skip any extra digit. */
1445 /* Double-check that the "__B_{DIGITS}+" sequence we found
1446 is indeed followed by "__". */
1447 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1448 i = k;
1451 /* Remove _E{DIGITS}+[sb] */
1453 /* Just as for protected object subprograms, there are 2 categories
1454 of subprograms created by the compiler for each entry. The first
1455 one implements the actual entry code, and has a suffix following
1456 the convention above; the second one implements the barrier and
1457 uses the same convention as above, except that the 'E' is replaced
1458 by a 'B'.
1460 Just as above, we do not decode the name of barrier functions
1461 to give the user a clue that the code he is debugging has been
1462 internally generated. */
1464 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1465 && isdigit (encoded[i+2]))
1467 int k = i + 3;
1469 while (k < len0 && isdigit (encoded[k]))
1470 k++;
1472 if (k < len0
1473 && (encoded[k] == 'b' || encoded[k] == 's'))
1475 k++;
1476 /* Just as an extra precaution, make sure that if this
1477 suffix is followed by anything else, it is a '_'.
1478 Otherwise, we matched this sequence by accident. */
1479 if (k == len0
1480 || (k < len0 && encoded[k] == '_'))
1481 i = k;
1485 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1486 the GNAT front-end in protected object subprograms. */
1488 if (i < len0 + 3
1489 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1491 /* Backtrack a bit up until we reach either the beginning of
1492 the encoded name, or "__". Make sure that we only find
1493 digits or lowercase characters. */
1494 const char *ptr = encoded + i - 1;
1496 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1497 ptr--;
1498 if (ptr < encoded
1499 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1500 i++;
1503 if (wide && i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1505 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1507 i += 3;
1508 continue;
1511 else if (wide && i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1513 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1515 i += 5;
1516 continue;
1519 else if (wide && i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1520 && isxdigit (encoded[i + 2]))
1522 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1524 i += 10;
1525 continue;
1529 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1531 /* This is a X[bn]* sequence not separated from the previous
1532 part of the name with a non-alpha-numeric character (in other
1533 words, immediately following an alpha-numeric character), then
1534 verify that it is placed at the end of the encoded name. If
1535 not, then the encoding is not valid and we should abort the
1536 decoding. Otherwise, just skip it, it is used in body-nested
1537 package names. */
1539 i += 1;
1540 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1541 if (i < len0)
1542 goto Suppress;
1544 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1546 /* Replace '__' by '.'. */
1547 decoded.push_back ('.');
1548 at_start_name = 1;
1549 i += 2;
1551 else
1553 /* It's a character part of the decoded name, so just copy it
1554 over. */
1555 decoded.push_back (encoded[i]);
1556 i += 1;
1560 /* Decoded names should never contain any uppercase character.
1561 Double-check this, and abort the decoding if we find one. */
1563 if (operators)
1565 for (i = 0; i < decoded.length(); ++i)
1566 if (isupper (decoded[i]) || decoded[i] == ' ')
1567 goto Suppress;
1570 /* If the compiler added a suffix, append it now. */
1571 if (suffix >= 0)
1572 decoded = decoded + "[" + &encoded[suffix] + "]";
1574 return decoded;
1576 Suppress:
1577 if (!wrap)
1578 return {};
1580 if (encoded[0] == '<')
1581 decoded = encoded;
1582 else
1583 decoded = '<' + std::string(encoded) + '>';
1584 return decoded;
1587 #ifdef GDB_SELF_TEST
1589 static void
1590 ada_decode_tests ()
1592 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1593 result does not really matter very much. */
1594 SELF_CHECK (ada_decode ("44") == "44");
1597 #endif
1599 /* Table for keeping permanent unique copies of decoded names. Once
1600 allocated, names in this table are never released. While this is a
1601 storage leak, it should not be significant unless there are massive
1602 changes in the set of decoded names in successive versions of a
1603 symbol table loaded during a single session. */
1604 static struct htab *decoded_names_store;
1606 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1607 in the language-specific part of GSYMBOL, if it has not been
1608 previously computed. Tries to save the decoded name in the same
1609 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1610 in any case, the decoded symbol has a lifetime at least that of
1611 GSYMBOL).
1612 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1613 const, but nevertheless modified to a semantically equivalent form
1614 when a decoded name is cached in it. */
1616 const char *
1617 ada_decode_symbol (const struct general_symbol_info *arg)
1619 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1620 const char **resultp =
1621 &gsymbol->language_specific.demangled_name;
1623 if (!gsymbol->ada_mangled)
1625 std::string decoded = ada_decode (gsymbol->linkage_name ());
1626 struct obstack *obstack = gsymbol->language_specific.obstack;
1628 gsymbol->ada_mangled = 1;
1630 if (obstack != NULL)
1631 *resultp = obstack_strdup (obstack, decoded.c_str ());
1632 else
1634 /* Sometimes, we can't find a corresponding objfile, in
1635 which case, we put the result on the heap. Since we only
1636 decode when needed, we hope this usually does not cause a
1637 significant memory leak (FIXME). */
1639 char **slot = (char **) htab_find_slot (decoded_names_store,
1640 decoded.c_str (), INSERT);
1642 if (*slot == NULL)
1643 *slot = xstrdup (decoded.c_str ());
1644 *resultp = *slot;
1648 return *resultp;
1653 /* Arrays */
1655 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1656 generated by the GNAT compiler to describe the index type used
1657 for each dimension of an array, check whether it follows the latest
1658 known encoding. If not, fix it up to conform to the latest encoding.
1659 Otherwise, do nothing. This function also does nothing if
1660 INDEX_DESC_TYPE is NULL.
1662 The GNAT encoding used to describe the array index type evolved a bit.
1663 Initially, the information would be provided through the name of each
1664 field of the structure type only, while the type of these fields was
1665 described as unspecified and irrelevant. The debugger was then expected
1666 to perform a global type lookup using the name of that field in order
1667 to get access to the full index type description. Because these global
1668 lookups can be very expensive, the encoding was later enhanced to make
1669 the global lookup unnecessary by defining the field type as being
1670 the full index type description.
1672 The purpose of this routine is to allow us to support older versions
1673 of the compiler by detecting the use of the older encoding, and by
1674 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1675 we essentially replace each field's meaningless type by the associated
1676 index subtype). */
1678 void
1679 ada_fixup_array_indexes_type (struct type *index_desc_type)
1681 int i;
1683 if (index_desc_type == NULL)
1684 return;
1685 gdb_assert (index_desc_type->num_fields () > 0);
1687 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1688 to check one field only, no need to check them all). If not, return
1689 now.
1691 If our INDEX_DESC_TYPE was generated using the older encoding,
1692 the field type should be a meaningless integer type whose name
1693 is not equal to the field name. */
1694 if (index_desc_type->field (0).type ()->name () != NULL
1695 && strcmp (index_desc_type->field (0).type ()->name (),
1696 index_desc_type->field (0).name ()) == 0)
1697 return;
1699 /* Fixup each field of INDEX_DESC_TYPE. */
1700 for (i = 0; i < index_desc_type->num_fields (); i++)
1702 const char *name = index_desc_type->field (i).name ();
1703 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1705 if (raw_type)
1706 index_desc_type->field (i).set_type (raw_type);
1710 /* The desc_* routines return primitive portions of array descriptors
1711 (fat pointers). */
1713 /* The descriptor or array type, if any, indicated by TYPE; removes
1714 level of indirection, if needed. */
1716 static struct type *
1717 desc_base_type (struct type *type)
1719 if (type == NULL)
1720 return NULL;
1721 type = ada_check_typedef (type);
1722 if (type->code () == TYPE_CODE_TYPEDEF)
1723 type = ada_typedef_target_type (type);
1725 if (type != NULL
1726 && (type->code () == TYPE_CODE_PTR
1727 || type->code () == TYPE_CODE_REF))
1728 return ada_check_typedef (type->target_type ());
1729 else
1730 return type;
1733 /* True iff TYPE indicates a "thin" array pointer type. */
1735 static int
1736 is_thin_pntr (struct type *type)
1738 return
1739 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1740 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1743 /* The descriptor type for thin pointer type TYPE. */
1745 static struct type *
1746 thin_descriptor_type (struct type *type)
1748 struct type *base_type = desc_base_type (type);
1750 if (base_type == NULL)
1751 return NULL;
1752 if (is_suffix (ada_type_name (base_type), "___XVE"))
1753 return base_type;
1754 else
1756 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1758 if (alt_type == NULL)
1759 return base_type;
1760 else
1761 return alt_type;
1765 /* A pointer to the array data for thin-pointer value VAL. */
1767 static struct value *
1768 thin_data_pntr (struct value *val)
1770 struct type *type = ada_check_typedef (val->type ());
1771 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1773 data_type = lookup_pointer_type (data_type);
1775 if (type->code () == TYPE_CODE_PTR)
1776 return value_cast (data_type, val->copy ());
1777 else
1778 return value_from_longest (data_type, val->address ());
1781 /* True iff TYPE indicates a "thick" array pointer type. */
1783 static int
1784 is_thick_pntr (struct type *type)
1786 type = desc_base_type (type);
1787 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1788 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1791 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1792 pointer to one, the type of its bounds data; otherwise, NULL. */
1794 static struct type *
1795 desc_bounds_type (struct type *type)
1797 struct type *r;
1799 type = desc_base_type (type);
1801 if (type == NULL)
1802 return NULL;
1803 else if (is_thin_pntr (type))
1805 type = thin_descriptor_type (type);
1806 if (type == NULL)
1807 return NULL;
1808 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1809 if (r != NULL)
1810 return ada_check_typedef (r);
1812 else if (type->code () == TYPE_CODE_STRUCT)
1814 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1815 if (r != NULL)
1816 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1818 return NULL;
1821 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1822 one, a pointer to its bounds data. Otherwise NULL. */
1824 static struct value *
1825 desc_bounds (struct value *arr)
1827 struct type *type = ada_check_typedef (arr->type ());
1829 if (is_thin_pntr (type))
1831 struct type *bounds_type =
1832 desc_bounds_type (thin_descriptor_type (type));
1833 LONGEST addr;
1835 if (bounds_type == NULL)
1836 error (_("Bad GNAT array descriptor"));
1838 /* NOTE: The following calculation is not really kosher, but
1839 since desc_type is an XVE-encoded type (and shouldn't be),
1840 the correct calculation is a real pain. FIXME (and fix GCC). */
1841 if (type->code () == TYPE_CODE_PTR)
1842 addr = value_as_long (arr);
1843 else
1844 addr = arr->address ();
1846 return
1847 value_from_longest (lookup_pointer_type (bounds_type),
1848 addr - bounds_type->length ());
1851 else if (is_thick_pntr (type))
1853 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1854 _("Bad GNAT array descriptor"));
1855 struct type *p_bounds_type = p_bounds->type ();
1857 if (p_bounds_type
1858 && p_bounds_type->code () == TYPE_CODE_PTR)
1860 struct type *target_type = p_bounds_type->target_type ();
1862 if (target_type->is_stub ())
1863 p_bounds = value_cast (lookup_pointer_type
1864 (ada_check_typedef (target_type)),
1865 p_bounds);
1867 else
1868 error (_("Bad GNAT array descriptor"));
1870 return p_bounds;
1872 else
1873 return NULL;
1876 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1877 position of the field containing the address of the bounds data. */
1879 static int
1880 fat_pntr_bounds_bitpos (struct type *type)
1882 return desc_base_type (type)->field (1).loc_bitpos ();
1885 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1886 size of the field containing the address of the bounds data. */
1888 static int
1889 fat_pntr_bounds_bitsize (struct type *type)
1891 type = desc_base_type (type);
1893 if (type->field (1).bitsize () > 0)
1894 return type->field (1).bitsize ();
1895 else
1896 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1899 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1900 pointer to one, the type of its array data (a array-with-no-bounds type);
1901 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1902 data. */
1904 static struct type *
1905 desc_data_target_type (struct type *type)
1907 type = desc_base_type (type);
1909 /* NOTE: The following is bogus; see comment in desc_bounds. */
1910 if (is_thin_pntr (type))
1911 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1912 else if (is_thick_pntr (type))
1914 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1916 if (data_type
1917 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1918 return ada_check_typedef (data_type->target_type ());
1921 return NULL;
1924 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1925 its array data. */
1927 static struct value *
1928 desc_data (struct value *arr)
1930 struct type *type = arr->type ();
1932 if (is_thin_pntr (type))
1933 return thin_data_pntr (arr);
1934 else if (is_thick_pntr (type))
1935 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1936 _("Bad GNAT array descriptor"));
1937 else
1938 return NULL;
1942 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1943 position of the field containing the address of the data. */
1945 static int
1946 fat_pntr_data_bitpos (struct type *type)
1948 return desc_base_type (type)->field (0).loc_bitpos ();
1951 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1952 size of the field containing the address of the data. */
1954 static int
1955 fat_pntr_data_bitsize (struct type *type)
1957 type = desc_base_type (type);
1959 if (type->field (0).bitsize () > 0)
1960 return type->field (0).bitsize ();
1961 else
1962 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1965 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1966 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. */
1969 static struct value *
1970 desc_one_bound (struct value *bounds, int i, int which)
1972 char bound_name[20];
1973 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1974 which ? 'U' : 'L', i - 1);
1975 return value_struct_elt (&bounds, {}, bound_name, NULL,
1976 _("Bad GNAT array descriptor bounds"));
1979 /* If BOUNDS is an array-bounds structure type, return the bit position
1980 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1981 bound, if WHICH is 1. The first bound is I=1. */
1983 static int
1984 desc_bound_bitpos (struct type *type, int i, int which)
1986 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1989 /* If BOUNDS is an array-bounds structure type, return the bit field size
1990 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1991 bound, if WHICH is 1. The first bound is I=1. */
1993 static int
1994 desc_bound_bitsize (struct type *type, int i, int which)
1996 type = desc_base_type (type);
1998 if (type->field (2 * i + which - 2).bitsize () > 0)
1999 return type->field (2 * i + which - 2).bitsize ();
2000 else
2001 return 8 * type->field (2 * i + which - 2).type ()->length ();
2004 /* If TYPE is the type of an array-bounds structure, the type of its
2005 Ith bound (numbering from 1). Otherwise, NULL. */
2007 static struct type *
2008 desc_index_type (struct type *type, int i)
2010 type = desc_base_type (type);
2012 if (type->code () == TYPE_CODE_STRUCT)
2014 char bound_name[20];
2015 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2016 return lookup_struct_elt_type (type, bound_name, 1);
2018 else
2019 return NULL;
2022 /* The number of index positions in the array-bounds type TYPE.
2023 Return 0 if TYPE is NULL. */
2025 static int
2026 desc_arity (struct type *type)
2028 type = desc_base_type (type);
2030 if (type != NULL)
2031 return type->num_fields () / 2;
2032 return 0;
2035 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2036 an array descriptor type (representing an unconstrained array
2037 type). */
2039 static int
2040 ada_is_direct_array_type (struct type *type)
2042 if (type == NULL)
2043 return 0;
2044 type = ada_check_typedef (type);
2045 return (type->code () == TYPE_CODE_ARRAY
2046 || ada_is_array_descriptor_type (type));
2049 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2050 * to one. */
2052 static int
2053 ada_is_array_type (struct type *type)
2055 while (type != NULL
2056 && (type->code () == TYPE_CODE_PTR
2057 || type->code () == TYPE_CODE_REF))
2058 type = type->target_type ();
2059 return ada_is_direct_array_type (type);
2062 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2065 ada_is_simple_array_type (struct type *type)
2067 if (type == NULL)
2068 return 0;
2069 type = ada_check_typedef (type);
2070 return (type->code () == TYPE_CODE_ARRAY
2071 || (type->code () == TYPE_CODE_PTR
2072 && (ada_check_typedef (type->target_type ())->code ()
2073 == TYPE_CODE_ARRAY)));
2076 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2079 ada_is_array_descriptor_type (struct type *type)
2081 struct type *data_type = desc_data_target_type (type);
2083 if (type == NULL)
2084 return 0;
2085 type = ada_check_typedef (type);
2086 return (data_type != NULL
2087 && data_type->code () == TYPE_CODE_ARRAY
2088 && desc_arity (desc_bounds_type (type)) > 0);
2091 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2092 (fat pointer) returns the type of the array data described---specifically,
2093 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2094 in from the descriptor; otherwise, they are left unspecified. If
2095 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2096 returns NULL. The result is simply the type of ARR if ARR is not
2097 a descriptor. */
2099 static struct type *
2100 ada_type_of_array (struct value *arr, int bounds)
2102 if (ada_is_constrained_packed_array_type (arr->type ()))
2103 return decode_constrained_packed_array_type (arr->type ());
2105 if (!ada_is_array_descriptor_type (arr->type ()))
2106 return arr->type ();
2108 if (!bounds)
2110 struct type *array_type =
2111 ada_check_typedef (desc_data_target_type (arr->type ()));
2113 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2114 array_type->field (0).set_bitsize
2115 (decode_packed_array_bitsize (arr->type ()));
2117 return array_type;
2119 else
2121 struct type *elt_type;
2122 int arity;
2123 struct value *descriptor;
2125 elt_type = ada_array_element_type (arr->type (), -1);
2126 arity = ada_array_arity (arr->type ());
2128 if (elt_type == NULL || arity == 0)
2129 return ada_check_typedef (arr->type ());
2131 descriptor = desc_bounds (arr);
2132 if (value_as_long (descriptor) == 0)
2133 return NULL;
2134 while (arity > 0)
2136 type_allocator alloc (arr->type ());
2137 struct value *low = desc_one_bound (descriptor, arity, 0);
2138 struct value *high = desc_one_bound (descriptor, arity, 1);
2140 arity -= 1;
2141 struct type *range_type
2142 = create_static_range_type (alloc, low->type (),
2143 longest_to_int (value_as_long (low)),
2144 longest_to_int (value_as_long (high)));
2145 elt_type = create_array_type (alloc, elt_type, range_type);
2146 INIT_GNAT_SPECIFIC (elt_type);
2148 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2150 /* We need to store the element packed bitsize, as well as
2151 recompute the array size, because it was previously
2152 computed based on the unpacked element size. */
2153 LONGEST lo = value_as_long (low);
2154 LONGEST hi = value_as_long (high);
2156 elt_type->field (0).set_bitsize
2157 (decode_packed_array_bitsize (arr->type ()));
2159 /* If the array has no element, then the size is already
2160 zero, and does not need to be recomputed. */
2161 if (lo < hi)
2163 int array_bitsize =
2164 (hi - lo + 1) * elt_type->field (0).bitsize ();
2166 elt_type->set_length ((array_bitsize + 7) / 8);
2171 return lookup_pointer_type (elt_type);
2175 /* If ARR does not represent an array, returns ARR unchanged.
2176 Otherwise, returns either a standard GDB array with bounds set
2177 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2178 GDB array. Returns NULL if ARR is a null fat pointer. */
2180 struct value *
2181 ada_coerce_to_simple_array_ptr (struct value *arr)
2183 if (ada_is_array_descriptor_type (arr->type ()))
2185 struct type *arrType = ada_type_of_array (arr, 1);
2187 if (arrType == NULL)
2188 return NULL;
2189 return value_cast (arrType, desc_data (arr)->copy ());
2191 else if (ada_is_constrained_packed_array_type (arr->type ()))
2192 return decode_constrained_packed_array (arr);
2193 else
2194 return arr;
2197 /* If ARR does not represent an array, returns ARR unchanged.
2198 Otherwise, returns a standard GDB array describing ARR (which may
2199 be ARR itself if it already is in the proper form). */
2201 struct value *
2202 ada_coerce_to_simple_array (struct value *arr)
2204 if (ada_is_array_descriptor_type (arr->type ()))
2206 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2208 if (arrVal == NULL)
2209 error (_("Bounds unavailable for null array pointer."));
2210 return value_ind (arrVal);
2212 else if (ada_is_constrained_packed_array_type (arr->type ()))
2213 return decode_constrained_packed_array (arr);
2214 else
2215 return arr;
2218 /* If TYPE represents a GNAT array type, return it translated to an
2219 ordinary GDB array type (possibly with BITSIZE fields indicating
2220 packing). For other types, is the identity. */
2222 struct type *
2223 ada_coerce_to_simple_array_type (struct type *type)
2225 if (ada_is_constrained_packed_array_type (type))
2226 return decode_constrained_packed_array_type (type);
2228 if (ada_is_array_descriptor_type (type))
2229 return ada_check_typedef (desc_data_target_type (type));
2231 return type;
2234 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2236 static int
2237 ada_is_gnat_encoded_packed_array_type (struct type *type)
2239 if (type == NULL)
2240 return 0;
2241 type = desc_base_type (type);
2242 type = ada_check_typedef (type);
2243 return
2244 ada_type_name (type) != NULL
2245 && strstr (ada_type_name (type), "___XP") != NULL;
2248 /* Non-zero iff TYPE represents a standard GNAT constrained
2249 packed-array type. */
2252 ada_is_constrained_packed_array_type (struct type *type)
2254 return ada_is_gnat_encoded_packed_array_type (type)
2255 && !ada_is_array_descriptor_type (type);
2258 /* Non-zero iff TYPE represents an array descriptor for a
2259 unconstrained packed-array type. */
2261 static int
2262 ada_is_unconstrained_packed_array_type (struct type *type)
2264 if (!ada_is_array_descriptor_type (type))
2265 return 0;
2267 if (ada_is_gnat_encoded_packed_array_type (type))
2268 return 1;
2270 /* If we saw GNAT encodings, then the above code is sufficient.
2271 However, with minimal encodings, we will just have a thick
2272 pointer instead. */
2273 if (is_thick_pntr (type))
2275 type = desc_base_type (type);
2276 /* The structure's first field is a pointer to an array, so this
2277 fetches the array type. */
2278 type = type->field (0).type ()->target_type ();
2279 if (type->code () == TYPE_CODE_TYPEDEF)
2280 type = ada_typedef_target_type (type);
2281 /* Now we can see if the array elements are packed. */
2282 return type->field (0).bitsize () > 0;
2285 return 0;
2288 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2289 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2291 static bool
2292 ada_is_any_packed_array_type (struct type *type)
2294 return (ada_is_constrained_packed_array_type (type)
2295 || (type->code () == TYPE_CODE_ARRAY
2296 && type->field (0).bitsize () % 8 != 0));
2299 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2300 return the size of its elements in bits. */
2302 static long
2303 decode_packed_array_bitsize (struct type *type)
2305 const char *raw_name;
2306 const char *tail;
2307 long bits;
2309 /* Access to arrays implemented as fat pointers are encoded as a typedef
2310 of the fat pointer type. We need the name of the fat pointer type
2311 to do the decoding, so strip the typedef layer. */
2312 if (type->code () == TYPE_CODE_TYPEDEF)
2313 type = ada_typedef_target_type (type);
2315 raw_name = ada_type_name (ada_check_typedef (type));
2316 if (!raw_name)
2317 raw_name = ada_type_name (desc_base_type (type));
2319 if (!raw_name)
2320 return 0;
2322 tail = strstr (raw_name, "___XP");
2323 if (tail == nullptr)
2325 gdb_assert (is_thick_pntr (type));
2326 /* The structure's first field is a pointer to an array, so this
2327 fetches the array type. */
2328 type = type->field (0).type ()->target_type ();
2329 /* Now we can see if the array elements are packed. */
2330 return type->field (0).bitsize ();
2333 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2335 lim_warning
2336 (_("could not understand bit size information on packed array"));
2337 return 0;
2340 return bits;
2343 /* Given that TYPE is a standard GDB array type with all bounds filled
2344 in, and that the element size of its ultimate scalar constituents
2345 (that is, either its elements, or, if it is an array of arrays, its
2346 elements' elements, etc.) is *ELT_BITS, return an identical type,
2347 but with the bit sizes of its elements (and those of any
2348 constituent arrays) recorded in the BITSIZE components of its
2349 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2350 in bits.
2352 Note that, for arrays whose index type has an XA encoding where
2353 a bound references a record discriminant, getting that discriminant,
2354 and therefore the actual value of that bound, is not possible
2355 because none of the given parameters gives us access to the record.
2356 This function assumes that it is OK in the context where it is being
2357 used to return an array whose bounds are still dynamic and where
2358 the length is arbitrary. */
2360 static struct type *
2361 constrained_packed_array_type (struct type *type, long *elt_bits)
2363 struct type *new_elt_type;
2364 struct type *new_type;
2365 struct type *index_type_desc;
2366 struct type *index_type;
2367 LONGEST low_bound, high_bound;
2369 type = ada_check_typedef (type);
2370 if (type->code () != TYPE_CODE_ARRAY)
2371 return type;
2373 index_type_desc = ada_find_parallel_type (type, "___XA");
2374 if (index_type_desc)
2375 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2376 NULL);
2377 else
2378 index_type = type->index_type ();
2380 type_allocator alloc (type);
2381 new_elt_type =
2382 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2383 elt_bits);
2384 new_type = create_array_type (alloc, new_elt_type, index_type);
2385 new_type->field (0).set_bitsize (*elt_bits);
2386 new_type->set_name (ada_type_name (type));
2388 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2389 && is_dynamic_type (check_typedef (index_type)))
2390 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2391 low_bound = high_bound = 0;
2392 if (high_bound < low_bound)
2394 *elt_bits = 0;
2395 new_type->set_length (0);
2397 else
2399 *elt_bits *= (high_bound - low_bound + 1);
2400 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2403 new_type->set_is_fixed_instance (true);
2404 return new_type;
2407 /* The array type encoded by TYPE, where
2408 ada_is_constrained_packed_array_type (TYPE). */
2410 static struct type *
2411 decode_constrained_packed_array_type (struct type *type)
2413 const char *raw_name = ada_type_name (ada_check_typedef (type));
2414 char *name;
2415 const char *tail;
2416 struct type *shadow_type;
2417 long bits;
2419 if (!raw_name)
2420 raw_name = ada_type_name (desc_base_type (type));
2422 if (!raw_name)
2423 return NULL;
2425 name = (char *) alloca (strlen (raw_name) + 1);
2426 tail = strstr (raw_name, "___XP");
2427 type = desc_base_type (type);
2429 memcpy (name, raw_name, tail - raw_name);
2430 name[tail - raw_name] = '\000';
2432 shadow_type = ada_find_parallel_type_with_name (type, name);
2434 if (shadow_type == NULL)
2436 lim_warning (_("could not find bounds information on packed array"));
2437 return NULL;
2439 shadow_type = check_typedef (shadow_type);
2441 if (shadow_type->code () != TYPE_CODE_ARRAY)
2443 lim_warning (_("could not understand bounds "
2444 "information on packed array"));
2445 return NULL;
2448 bits = decode_packed_array_bitsize (type);
2449 return constrained_packed_array_type (shadow_type, &bits);
2452 /* Helper function for decode_constrained_packed_array. Set the field
2453 bitsize on a series of packed arrays. Returns the number of
2454 elements in TYPE. */
2456 static LONGEST
2457 recursively_update_array_bitsize (struct type *type)
2459 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2461 LONGEST low, high;
2462 if (!get_discrete_bounds (type->index_type (), &low, &high)
2463 || low > high)
2464 return 0;
2465 LONGEST our_len = high - low + 1;
2467 struct type *elt_type = type->target_type ();
2468 if (elt_type->code () == TYPE_CODE_ARRAY)
2470 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2471 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
2472 type->field (0).set_bitsize (elt_bitsize);
2474 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2475 / HOST_CHAR_BIT));
2478 return our_len;
2481 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2482 array, returns a simple array that denotes that array. Its type is a
2483 standard GDB array type except that the BITSIZEs of the array
2484 target types are set to the number of bits in each element, and the
2485 type length is set appropriately. */
2487 static struct value *
2488 decode_constrained_packed_array (struct value *arr)
2490 struct type *type;
2492 /* If our value is a pointer, then dereference it. Likewise if
2493 the value is a reference. Make sure that this operation does not
2494 cause the target type to be fixed, as this would indirectly cause
2495 this array to be decoded. The rest of the routine assumes that
2496 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2497 and "value_ind" routines to perform the dereferencing, as opposed
2498 to using "ada_coerce_ref" or "ada_value_ind". */
2499 arr = coerce_ref (arr);
2500 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2501 arr = value_ind (arr);
2503 type = decode_constrained_packed_array_type (arr->type ());
2504 if (type == NULL)
2506 error (_("can't unpack array"));
2507 return NULL;
2510 /* Decoding the packed array type could not correctly set the field
2511 bitsizes for any dimension except the innermost, because the
2512 bounds may be variable and were not passed to that function. So,
2513 we further resolve the array bounds here and then update the
2514 sizes. */
2515 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2516 CORE_ADDR address = arr->address ();
2517 gdb::array_view<const gdb_byte> view
2518 = gdb::make_array_view (valaddr, type->length ());
2519 type = resolve_dynamic_type (type, view, address);
2520 recursively_update_array_bitsize (type);
2522 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2523 && ada_is_modular_type (arr->type ()))
2525 /* This is a (right-justified) modular type representing a packed
2526 array with no wrapper. In order to interpret the value through
2527 the (left-justified) packed array type we just built, we must
2528 first left-justify it. */
2529 int bit_size, bit_pos;
2530 ULONGEST mod;
2532 mod = ada_modulus (arr->type ()) - 1;
2533 bit_size = 0;
2534 while (mod > 0)
2536 bit_size += 1;
2537 mod >>= 1;
2539 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2540 arr = ada_value_primitive_packed_val (arr, NULL,
2541 bit_pos / HOST_CHAR_BIT,
2542 bit_pos % HOST_CHAR_BIT,
2543 bit_size,
2544 type);
2547 return coerce_unspec_val_to_type (arr, type);
2551 /* The value of the element of packed array ARR at the ARITY indices
2552 given in IND. ARR must be a simple array. */
2554 static struct value *
2555 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2557 int i;
2558 int bits, elt_off, bit_off;
2559 long elt_total_bit_offset;
2560 struct type *elt_type;
2561 struct value *v;
2563 bits = 0;
2564 elt_total_bit_offset = 0;
2565 elt_type = ada_check_typedef (arr->type ());
2566 for (i = 0; i < arity; i += 1)
2568 if (elt_type->code () != TYPE_CODE_ARRAY
2569 || elt_type->field (0).bitsize () == 0)
2570 error
2571 (_("attempt to do packed indexing of "
2572 "something other than a packed array"));
2573 else
2575 struct type *range_type = elt_type->index_type ();
2576 LONGEST lowerbound, upperbound;
2577 LONGEST idx;
2579 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2581 lim_warning (_("don't know bounds of array"));
2582 lowerbound = upperbound = 0;
2585 idx = pos_atr (ind[i]);
2586 if (idx < lowerbound || idx > upperbound)
2587 lim_warning (_("packed array index %ld out of bounds"),
2588 (long) idx);
2589 bits = elt_type->field (0).bitsize ();
2590 elt_total_bit_offset += (idx - lowerbound) * bits;
2591 elt_type = ada_check_typedef (elt_type->target_type ());
2594 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2595 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2597 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2598 bits, elt_type);
2599 return v;
2602 /* Non-zero iff TYPE includes negative integer values. */
2604 static int
2605 has_negatives (struct type *type)
2607 switch (type->code ())
2609 default:
2610 return 0;
2611 case TYPE_CODE_INT:
2612 return !type->is_unsigned ();
2613 case TYPE_CODE_RANGE:
2614 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2618 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2619 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2620 the unpacked buffer.
2622 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2623 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2625 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2626 zero otherwise.
2628 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2630 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2632 static void
2633 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2634 gdb_byte *unpacked, int unpacked_len,
2635 int is_big_endian, int is_signed_type,
2636 int is_scalar)
2638 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2639 int src_idx; /* Index into the source area */
2640 int src_bytes_left; /* Number of source bytes left to process. */
2641 int srcBitsLeft; /* Number of source bits left to move */
2642 int unusedLS; /* Number of bits in next significant
2643 byte of source that are unused */
2645 int unpacked_idx; /* Index into the unpacked buffer */
2646 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2648 unsigned long accum; /* Staging area for bits being transferred */
2649 int accumSize; /* Number of meaningful bits in accum */
2650 unsigned char sign;
2652 /* Transmit bytes from least to most significant; delta is the direction
2653 the indices move. */
2654 int delta = is_big_endian ? -1 : 1;
2656 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2657 bits from SRC. .*/
2658 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2659 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2660 bit_size, unpacked_len);
2662 srcBitsLeft = bit_size;
2663 src_bytes_left = src_len;
2664 unpacked_bytes_left = unpacked_len;
2665 sign = 0;
2667 if (is_big_endian)
2669 src_idx = src_len - 1;
2670 if (is_signed_type
2671 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2672 sign = ~0;
2674 unusedLS =
2675 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2676 % HOST_CHAR_BIT;
2678 if (is_scalar)
2680 accumSize = 0;
2681 unpacked_idx = unpacked_len - 1;
2683 else
2685 /* Non-scalar values must be aligned at a byte boundary... */
2686 accumSize =
2687 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2688 /* ... And are placed at the beginning (most-significant) bytes
2689 of the target. */
2690 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2691 unpacked_bytes_left = unpacked_idx + 1;
2694 else
2696 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2698 src_idx = unpacked_idx = 0;
2699 unusedLS = bit_offset;
2700 accumSize = 0;
2702 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2703 sign = ~0;
2706 accum = 0;
2707 while (src_bytes_left > 0)
2709 /* Mask for removing bits of the next source byte that are not
2710 part of the value. */
2711 unsigned int unusedMSMask =
2712 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2714 /* Sign-extend bits for this byte. */
2715 unsigned int signMask = sign & ~unusedMSMask;
2717 accum |=
2718 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2719 accumSize += HOST_CHAR_BIT - unusedLS;
2720 if (accumSize >= HOST_CHAR_BIT)
2722 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2723 accumSize -= HOST_CHAR_BIT;
2724 accum >>= HOST_CHAR_BIT;
2725 unpacked_bytes_left -= 1;
2726 unpacked_idx += delta;
2728 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2729 unusedLS = 0;
2730 src_bytes_left -= 1;
2731 src_idx += delta;
2733 while (unpacked_bytes_left > 0)
2735 accum |= sign << accumSize;
2736 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2737 accumSize -= HOST_CHAR_BIT;
2738 if (accumSize < 0)
2739 accumSize = 0;
2740 accum >>= HOST_CHAR_BIT;
2741 unpacked_bytes_left -= 1;
2742 unpacked_idx += delta;
2746 /* Create a new value of type TYPE from the contents of OBJ starting
2747 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2748 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2749 assigning through the result will set the field fetched from.
2750 VALADDR is ignored unless OBJ is NULL, in which case,
2751 VALADDR+OFFSET must address the start of storage containing the
2752 packed value. The value returned in this case is never an lval.
2753 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2755 struct value *
2756 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2757 long offset, int bit_offset, int bit_size,
2758 struct type *type)
2760 struct value *v;
2761 const gdb_byte *src; /* First byte containing data to unpack */
2762 gdb_byte *unpacked;
2763 const int is_scalar = is_scalar_type (type);
2764 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2765 gdb::byte_vector staging;
2767 type = ada_check_typedef (type);
2769 if (obj == NULL)
2770 src = valaddr + offset;
2771 else
2772 src = obj->contents ().data () + offset;
2774 if (is_dynamic_type (type))
2776 /* The length of TYPE might by dynamic, so we need to resolve
2777 TYPE in order to know its actual size, which we then use
2778 to create the contents buffer of the value we return.
2779 The difficulty is that the data containing our object is
2780 packed, and therefore maybe not at a byte boundary. So, what
2781 we do, is unpack the data into a byte-aligned buffer, and then
2782 use that buffer as our object's value for resolving the type. */
2783 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2784 staging.resize (staging_len);
2786 ada_unpack_from_contents (src, bit_offset, bit_size,
2787 staging.data (), staging.size (),
2788 is_big_endian, has_negatives (type),
2789 is_scalar);
2790 type = resolve_dynamic_type (type, staging, 0);
2791 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2793 /* This happens when the length of the object is dynamic,
2794 and is actually smaller than the space reserved for it.
2795 For instance, in an array of variant records, the bit_size
2796 we're given is the array stride, which is constant and
2797 normally equal to the maximum size of its element.
2798 But, in reality, each element only actually spans a portion
2799 of that stride. */
2800 bit_size = type->length () * HOST_CHAR_BIT;
2804 if (obj == NULL)
2806 v = value::allocate (type);
2807 src = valaddr + offset;
2809 else if (obj->lval () == lval_memory && obj->lazy ())
2811 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2812 gdb_byte *buf;
2814 v = value_at (type, obj->address () + offset);
2815 buf = (gdb_byte *) alloca (src_len);
2816 read_memory (v->address (), buf, src_len);
2817 src = buf;
2819 else
2821 v = value::allocate (type);
2822 src = obj->contents ().data () + offset;
2825 if (obj != NULL)
2827 long new_offset = offset;
2829 v->set_component_location (obj);
2830 v->set_bitpos (bit_offset + obj->bitpos ());
2831 v->set_bitsize (bit_size);
2832 if (v->bitpos () >= HOST_CHAR_BIT)
2834 ++new_offset;
2835 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2837 v->set_offset (new_offset);
2839 /* Also set the parent value. This is needed when trying to
2840 assign a new value (in inferior memory). */
2841 v->set_parent (obj);
2843 else
2844 v->set_bitsize (bit_size);
2845 unpacked = v->contents_writeable ().data ();
2847 if (bit_size == 0)
2849 memset (unpacked, 0, type->length ());
2850 return v;
2853 if (staging.size () == type->length ())
2855 /* Small short-cut: If we've unpacked the data into a buffer
2856 of the same size as TYPE's length, then we can reuse that,
2857 instead of doing the unpacking again. */
2858 memcpy (unpacked, staging.data (), staging.size ());
2860 else
2861 ada_unpack_from_contents (src, bit_offset, bit_size,
2862 unpacked, type->length (),
2863 is_big_endian, has_negatives (type), is_scalar);
2865 return v;
2868 /* Store the contents of FROMVAL into the location of TOVAL.
2869 Return a new value with the location of TOVAL and contents of
2870 FROMVAL. Handles assignment into packed fields that have
2871 floating-point or non-scalar types. */
2873 static struct value *
2874 ada_value_assign (struct value *toval, struct value *fromval)
2876 struct type *type = toval->type ();
2877 int bits = toval->bitsize ();
2879 toval = ada_coerce_ref (toval);
2880 fromval = ada_coerce_ref (fromval);
2882 if (ada_is_direct_array_type (toval->type ()))
2883 toval = ada_coerce_to_simple_array (toval);
2884 if (ada_is_direct_array_type (fromval->type ()))
2885 fromval = ada_coerce_to_simple_array (fromval);
2887 if (!toval->deprecated_modifiable ())
2888 error (_("Left operand of assignment is not a modifiable lvalue."));
2890 if (toval->lval () == lval_memory
2891 && bits > 0
2892 && (type->code () == TYPE_CODE_FLT
2893 || type->code () == TYPE_CODE_STRUCT))
2895 int len = (toval->bitpos ()
2896 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2897 int from_size;
2898 gdb_byte *buffer = (gdb_byte *) alloca (len);
2899 struct value *val;
2900 CORE_ADDR to_addr = toval->address ();
2902 if (type->code () == TYPE_CODE_FLT)
2903 fromval = value_cast (type, fromval);
2905 read_memory (to_addr, buffer, len);
2906 from_size = fromval->bitsize ();
2907 if (from_size == 0)
2908 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2910 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2911 ULONGEST from_offset = 0;
2912 if (is_big_endian && is_scalar_type (fromval->type ()))
2913 from_offset = from_size - bits;
2914 copy_bitwise (buffer, toval->bitpos (),
2915 fromval->contents ().data (), from_offset,
2916 bits, is_big_endian);
2917 write_memory_with_notification (to_addr, buffer, len);
2919 val = toval->copy ();
2920 memcpy (val->contents_raw ().data (),
2921 fromval->contents ().data (),
2922 type->length ());
2923 val->deprecated_set_type (type);
2925 return val;
2928 return value_assign (toval, fromval);
2932 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2933 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2934 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2935 COMPONENT, and not the inferior's memory. The current contents
2936 of COMPONENT are ignored.
2938 Although not part of the initial design, this function also works
2939 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2940 had a null address, and COMPONENT had an address which is equal to
2941 its offset inside CONTAINER. */
2943 static void
2944 value_assign_to_component (struct value *container, struct value *component,
2945 struct value *val)
2947 LONGEST offset_in_container =
2948 (LONGEST) (component->address () - container->address ());
2949 int bit_offset_in_container =
2950 component->bitpos () - container->bitpos ();
2951 int bits;
2953 val = value_cast (component->type (), val);
2955 if (component->bitsize () == 0)
2956 bits = TARGET_CHAR_BIT * component->type ()->length ();
2957 else
2958 bits = component->bitsize ();
2960 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2962 int src_offset;
2964 if (is_scalar_type (check_typedef (component->type ())))
2965 src_offset
2966 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2967 else
2968 src_offset = 0;
2969 copy_bitwise ((container->contents_writeable ().data ()
2970 + offset_in_container),
2971 container->bitpos () + bit_offset_in_container,
2972 val->contents ().data (), src_offset, bits, 1);
2974 else
2975 copy_bitwise ((container->contents_writeable ().data ()
2976 + offset_in_container),
2977 container->bitpos () + bit_offset_in_container,
2978 val->contents ().data (), 0, bits, 0);
2981 /* Determine if TYPE is an access to an unconstrained array. */
2983 bool
2984 ada_is_access_to_unconstrained_array (struct type *type)
2986 return (type->code () == TYPE_CODE_TYPEDEF
2987 && is_thick_pntr (ada_typedef_target_type (type)));
2990 /* The value of the element of array ARR at the ARITY indices given in IND.
2991 ARR may be either a simple array, GNAT array descriptor, or pointer
2992 thereto. */
2994 struct value *
2995 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2997 int k;
2998 struct value *elt;
2999 struct type *elt_type;
3001 elt = ada_coerce_to_simple_array (arr);
3003 elt_type = ada_check_typedef (elt->type ());
3004 if (elt_type->code () == TYPE_CODE_ARRAY
3005 && elt_type->field (0).bitsize () > 0)
3006 return value_subscript_packed (elt, arity, ind);
3008 for (k = 0; k < arity; k += 1)
3010 struct type *saved_elt_type = elt_type->target_type ();
3012 if (elt_type->code () != TYPE_CODE_ARRAY)
3013 error (_("too many subscripts (%d expected)"), k);
3015 elt = value_subscript (elt, pos_atr (ind[k]));
3017 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3018 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3020 /* The element is a typedef to an unconstrained array,
3021 except that the value_subscript call stripped the
3022 typedef layer. The typedef layer is GNAT's way to
3023 specify that the element is, at the source level, an
3024 access to the unconstrained array, rather than the
3025 unconstrained array. So, we need to restore that
3026 typedef layer, which we can do by forcing the element's
3027 type back to its original type. Otherwise, the returned
3028 value is going to be printed as the array, rather
3029 than as an access. Another symptom of the same issue
3030 would be that an expression trying to dereference the
3031 element would also be improperly rejected. */
3032 elt->deprecated_set_type (saved_elt_type);
3035 elt_type = ada_check_typedef (elt->type ());
3038 return elt;
3041 /* Assuming ARR is a pointer to a GDB array, the value of the element
3042 of *ARR at the ARITY indices given in IND.
3043 Does not read the entire array into memory.
3045 Note: Unlike what one would expect, this function is used instead of
3046 ada_value_subscript for basically all non-packed array types. The reason
3047 for this is that a side effect of doing our own pointer arithmetics instead
3048 of relying on value_subscript is that there is no implicit typedef peeling.
3049 This is important for arrays of array accesses, where it allows us to
3050 preserve the fact that the array's element is an array access, where the
3051 access part os encoded in a typedef layer. */
3053 static struct value *
3054 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3056 int k;
3057 struct value *array_ind = ada_value_ind (arr);
3058 struct type *type
3059 = check_typedef (array_ind->enclosing_type ());
3061 if (type->code () == TYPE_CODE_ARRAY
3062 && type->field (0).bitsize () > 0)
3063 return value_subscript_packed (array_ind, arity, ind);
3065 for (k = 0; k < arity; k += 1)
3067 LONGEST lwb, upb;
3069 if (type->code () != TYPE_CODE_ARRAY)
3070 error (_("too many subscripts (%d expected)"), k);
3071 arr = value_cast (lookup_pointer_type (type->target_type ()),
3072 arr->copy ());
3073 get_discrete_bounds (type->index_type (), &lwb, &upb);
3074 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3075 type = type->target_type ();
3078 return value_ind (arr);
3081 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3082 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3083 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3084 this array is LOW, as per Ada rules. */
3085 static struct value *
3086 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3087 int low, int high)
3089 struct type *type0 = ada_check_typedef (type);
3090 struct type *base_index_type = type0->index_type ()->target_type ();
3091 type_allocator alloc (base_index_type);
3092 struct type *index_type
3093 = create_static_range_type (alloc, base_index_type, low, high);
3094 struct type *slice_type = create_array_type_with_stride
3095 (alloc, type0->target_type (), index_type,
3096 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3097 type0->field (0).bitsize ());
3098 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3099 std::optional<LONGEST> base_low_pos, low_pos;
3100 CORE_ADDR base;
3102 low_pos = discrete_position (base_index_type, low);
3103 base_low_pos = discrete_position (base_index_type, base_low);
3105 if (!low_pos.has_value () || !base_low_pos.has_value ())
3107 warning (_("unable to get positions in slice, use bounds instead"));
3108 low_pos = low;
3109 base_low_pos = base_low;
3112 ULONGEST stride = slice_type->field (0).bitsize () / 8;
3113 if (stride == 0)
3114 stride = type0->target_type ()->length ();
3116 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3117 return value_at_lazy (slice_type, base);
3121 static struct value *
3122 ada_value_slice (struct value *array, int low, int high)
3124 struct type *type = ada_check_typedef (array->type ());
3125 struct type *base_index_type = type->index_type ()->target_type ();
3126 type_allocator alloc (type->index_type ());
3127 struct type *index_type
3128 = create_static_range_type (alloc, type->index_type (), low, high);
3129 struct type *slice_type = create_array_type_with_stride
3130 (alloc, type->target_type (), index_type,
3131 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3132 type->field (0).bitsize ());
3133 std::optional<LONGEST> low_pos, high_pos;
3136 low_pos = discrete_position (base_index_type, low);
3137 high_pos = discrete_position (base_index_type, high);
3139 if (!low_pos.has_value () || !high_pos.has_value ())
3141 warning (_("unable to get positions in slice, use bounds instead"));
3142 low_pos = low;
3143 high_pos = high;
3146 return value_cast (slice_type,
3147 value_slice (array, low, *high_pos - *low_pos + 1));
3150 /* If type is a record type in the form of a standard GNAT array
3151 descriptor, returns the number of dimensions for type. If arr is a
3152 simple array, returns the number of "array of"s that prefix its
3153 type designation. Otherwise, returns 0. */
3156 ada_array_arity (struct type *type)
3158 int arity;
3160 if (type == NULL)
3161 return 0;
3163 type = desc_base_type (type);
3165 arity = 0;
3166 if (type->code () == TYPE_CODE_STRUCT)
3167 return desc_arity (desc_bounds_type (type));
3168 else
3169 while (type->code () == TYPE_CODE_ARRAY)
3171 arity += 1;
3172 type = ada_check_typedef (type->target_type ());
3175 return arity;
3178 /* If TYPE is a record type in the form of a standard GNAT array
3179 descriptor or a simple array type, returns the element type for
3180 TYPE after indexing by NINDICES indices, or by all indices if
3181 NINDICES is -1. Otherwise, returns NULL. */
3183 struct type *
3184 ada_array_element_type (struct type *type, int nindices)
3186 type = desc_base_type (type);
3188 if (type->code () == TYPE_CODE_STRUCT)
3190 int k;
3191 struct type *p_array_type;
3193 p_array_type = desc_data_target_type (type);
3195 k = ada_array_arity (type);
3196 if (k == 0)
3197 return NULL;
3199 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3200 if (nindices >= 0 && k > nindices)
3201 k = nindices;
3202 while (k > 0 && p_array_type != NULL)
3204 p_array_type = ada_check_typedef (p_array_type->target_type ());
3205 k -= 1;
3207 return p_array_type;
3209 else if (type->code () == TYPE_CODE_ARRAY)
3211 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3213 type = type->target_type ();
3214 /* A multi-dimensional array is represented using a sequence
3215 of array types. If one of these types has a name, then
3216 it is not another dimension of the outer array, but
3217 rather the element type of the outermost array. */
3218 if (type->name () != nullptr)
3219 break;
3220 nindices -= 1;
3222 return type;
3225 return NULL;
3228 /* See ada-lang.h. */
3230 struct type *
3231 ada_index_type (struct type *type, int n, const char *name)
3233 struct type *result_type;
3235 type = desc_base_type (type);
3237 if (n < 0 || n > ada_array_arity (type))
3238 error (_("invalid dimension number to '%s"), name);
3240 if (ada_is_simple_array_type (type))
3242 int i;
3244 for (i = 1; i < n; i += 1)
3246 type = ada_check_typedef (type);
3247 type = type->target_type ();
3249 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3250 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3251 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3252 perhaps stabsread.c would make more sense. */
3253 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3254 result_type = NULL;
3256 else
3258 result_type = desc_index_type (desc_bounds_type (type), n);
3259 if (result_type == NULL)
3260 error (_("attempt to take bound of something that is not an array"));
3263 return result_type;
3266 /* Given that arr is an array type, returns the lower bound of the
3267 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3268 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3269 array-descriptor type. It works for other arrays with bounds supplied
3270 by run-time quantities other than discriminants. */
3272 static LONGEST
3273 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3275 struct type *type, *index_type_desc, *index_type;
3276 int i;
3278 gdb_assert (which == 0 || which == 1);
3280 if (ada_is_constrained_packed_array_type (arr_type))
3281 arr_type = decode_constrained_packed_array_type (arr_type);
3283 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3284 return - which;
3286 if (arr_type->code () == TYPE_CODE_PTR)
3287 type = arr_type->target_type ();
3288 else
3289 type = arr_type;
3291 if (type->is_fixed_instance ())
3293 /* The array has already been fixed, so we do not need to
3294 check the parallel ___XA type again. That encoding has
3295 already been applied, so ignore it now. */
3296 index_type_desc = NULL;
3298 else
3300 index_type_desc = ada_find_parallel_type (type, "___XA");
3301 ada_fixup_array_indexes_type (index_type_desc);
3304 if (index_type_desc != NULL)
3305 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3306 NULL);
3307 else
3309 struct type *elt_type = check_typedef (type);
3311 for (i = 1; i < n; i++)
3312 elt_type = check_typedef (elt_type->target_type ());
3314 index_type = elt_type->index_type ();
3317 return (which == 0
3318 ? ada_discrete_type_low_bound (index_type)
3319 : ada_discrete_type_high_bound (index_type));
3322 /* Given that arr is an array value, returns the lower bound of the
3323 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3324 WHICH is 1. This routine will also work for arrays with bounds
3325 supplied by run-time quantities other than discriminants. */
3327 static LONGEST
3328 ada_array_bound (struct value *arr, int n, int which)
3330 struct type *arr_type;
3332 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3333 arr = value_ind (arr);
3334 arr_type = arr->enclosing_type ();
3336 if (ada_is_constrained_packed_array_type (arr_type))
3337 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3338 else if (ada_is_simple_array_type (arr_type))
3339 return ada_array_bound_from_type (arr_type, n, which);
3340 else
3341 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3344 /* Given that arr is an array value, returns the length of the
3345 nth index. This routine will also work for arrays with bounds
3346 supplied by run-time quantities other than discriminants.
3347 Does not work for arrays indexed by enumeration types with representation
3348 clauses at the moment. */
3350 static LONGEST
3351 ada_array_length (struct value *arr, int n)
3353 struct type *arr_type, *index_type;
3354 int low, high;
3356 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3357 arr = value_ind (arr);
3358 arr_type = arr->enclosing_type ();
3360 if (ada_is_constrained_packed_array_type (arr_type))
3361 return ada_array_length (decode_constrained_packed_array (arr), n);
3363 if (ada_is_simple_array_type (arr_type))
3365 low = ada_array_bound_from_type (arr_type, n, 0);
3366 high = ada_array_bound_from_type (arr_type, n, 1);
3368 else
3370 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3371 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3374 arr_type = check_typedef (arr_type);
3375 index_type = ada_index_type (arr_type, n, "length");
3376 if (index_type != NULL)
3378 struct type *base_type;
3379 if (index_type->code () == TYPE_CODE_RANGE)
3380 base_type = index_type->target_type ();
3381 else
3382 base_type = index_type;
3384 low = pos_atr (value_from_longest (base_type, low));
3385 high = pos_atr (value_from_longest (base_type, high));
3387 return high - low + 1;
3390 /* An array whose type is that of ARR_TYPE (an array type), with
3391 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3392 less than LOW, then LOW-1 is used. */
3394 static struct value *
3395 empty_array (struct type *arr_type, int low, int high)
3397 struct type *arr_type0 = ada_check_typedef (arr_type);
3398 type_allocator alloc (arr_type0->index_type ()->target_type ());
3399 struct type *index_type
3400 = create_static_range_type
3401 (alloc, arr_type0->index_type ()->target_type (), low,
3402 high < low ? low - 1 : high);
3403 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3405 return value::allocate (create_array_type (alloc, elt_type, index_type));
3409 /* Name resolution */
3411 /* The "decoded" name for the user-definable Ada operator corresponding
3412 to OP. */
3414 static const char *
3415 ada_decoded_op_name (enum exp_opcode op)
3417 int i;
3419 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3421 if (ada_opname_table[i].op == op)
3422 return ada_opname_table[i].decoded;
3424 error (_("Could not find operator name for opcode"));
3427 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3428 in a listing of choices during disambiguation (see sort_choices, below).
3429 The idea is that overloadings of a subprogram name from the
3430 same package should sort in their source order. We settle for ordering
3431 such symbols by their trailing number (__N or $N). */
3433 static int
3434 encoded_ordered_before (const char *N0, const char *N1)
3436 if (N1 == NULL)
3437 return 0;
3438 else if (N0 == NULL)
3439 return 1;
3440 else
3442 int k0, k1;
3444 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3446 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3448 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3449 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3451 int n0, n1;
3453 n0 = k0;
3454 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3455 n0 -= 1;
3456 n1 = k1;
3457 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3458 n1 -= 1;
3459 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3460 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3462 return (strcmp (N0, N1) < 0);
3466 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3467 encoded names. */
3469 static void
3470 sort_choices (struct block_symbol syms[], int nsyms)
3472 int i;
3474 for (i = 1; i < nsyms; i += 1)
3476 struct block_symbol sym = syms[i];
3477 int j;
3479 for (j = i - 1; j >= 0; j -= 1)
3481 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3482 sym.symbol->linkage_name ()))
3483 break;
3484 syms[j + 1] = syms[j];
3486 syms[j + 1] = sym;
3490 /* Whether GDB should display formals and return types for functions in the
3491 overloads selection menu. */
3492 static bool print_signatures = true;
3494 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3495 all but functions, the signature is just the name of the symbol. For
3496 functions, this is the name of the function, the list of types for formals
3497 and the return type (if any). */
3499 static void
3500 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3501 const struct type_print_options *flags)
3503 struct type *type = sym->type ();
3505 gdb_printf (stream, "%s", sym->print_name ());
3506 if (!print_signatures
3507 || type == NULL
3508 || type->code () != TYPE_CODE_FUNC)
3509 return;
3511 if (type->num_fields () > 0)
3513 int i;
3515 gdb_printf (stream, " (");
3516 for (i = 0; i < type->num_fields (); ++i)
3518 if (i > 0)
3519 gdb_printf (stream, "; ");
3520 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3521 flags);
3523 gdb_printf (stream, ")");
3525 if (type->target_type () != NULL
3526 && type->target_type ()->code () != TYPE_CODE_VOID)
3528 gdb_printf (stream, " return ");
3529 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3533 /* Read and validate a set of numeric choices from the user in the
3534 range 0 .. N_CHOICES-1. Place the results in increasing
3535 order in CHOICES[0 .. N-1], and return N.
3537 The user types choices as a sequence of numbers on one line
3538 separated by blanks, encoding them as follows:
3540 + A choice of 0 means to cancel the selection, throwing an error.
3541 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3542 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3544 The user is not allowed to choose more than MAX_RESULTS values.
3546 ANNOTATION_SUFFIX, if present, is used to annotate the input
3547 prompts (for use with the -f switch). */
3549 static int
3550 get_selections (int *choices, int n_choices, int max_results,
3551 int is_all_choice, const char *annotation_suffix)
3553 const char *args;
3554 const char *prompt;
3555 int n_chosen;
3556 int first_choice = is_all_choice ? 2 : 1;
3558 prompt = getenv ("PS2");
3559 if (prompt == NULL)
3560 prompt = "> ";
3562 std::string buffer;
3563 args = command_line_input (buffer, prompt, annotation_suffix);
3565 if (args == NULL)
3566 error_no_arg (_("one or more choice numbers"));
3568 n_chosen = 0;
3570 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3571 order, as given in args. Choices are validated. */
3572 while (1)
3574 char *args2;
3575 int choice, j;
3577 args = skip_spaces (args);
3578 if (*args == '\0' && n_chosen == 0)
3579 error_no_arg (_("one or more choice numbers"));
3580 else if (*args == '\0')
3581 break;
3583 choice = strtol (args, &args2, 10);
3584 if (args == args2 || choice < 0
3585 || choice > n_choices + first_choice - 1)
3586 error (_("Argument must be choice number"));
3587 args = args2;
3589 if (choice == 0)
3590 error (_("cancelled"));
3592 if (choice < first_choice)
3594 n_chosen = n_choices;
3595 for (j = 0; j < n_choices; j += 1)
3596 choices[j] = j;
3597 break;
3599 choice -= first_choice;
3601 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3605 if (j < 0 || choice != choices[j])
3607 int k;
3609 for (k = n_chosen - 1; k > j; k -= 1)
3610 choices[k + 1] = choices[k];
3611 choices[j + 1] = choice;
3612 n_chosen += 1;
3616 if (n_chosen > max_results)
3617 error (_("Select no more than %d of the above"), max_results);
3619 return n_chosen;
3622 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3623 by asking the user (if necessary), returning the number selected,
3624 and setting the first elements of SYMS items. Error if no symbols
3625 selected. */
3627 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3628 to be re-integrated one of these days. */
3630 static int
3631 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3633 int i;
3634 int *chosen = XALLOCAVEC (int , nsyms);
3635 int n_chosen;
3636 int first_choice = (max_results == 1) ? 1 : 2;
3637 const char *select_mode = multiple_symbols_select_mode ();
3639 if (max_results < 1)
3640 error (_("Request to select 0 symbols!"));
3641 if (nsyms <= 1)
3642 return nsyms;
3644 if (select_mode == multiple_symbols_cancel)
3645 error (_("\
3646 canceled because the command is ambiguous\n\
3647 See set/show multiple-symbol."));
3649 /* If select_mode is "all", then return all possible symbols.
3650 Only do that if more than one symbol can be selected, of course.
3651 Otherwise, display the menu as usual. */
3652 if (select_mode == multiple_symbols_all && max_results > 1)
3653 return nsyms;
3655 gdb_printf (_("[0] cancel\n"));
3656 if (max_results > 1)
3657 gdb_printf (_("[1] all\n"));
3659 sort_choices (syms, nsyms);
3661 for (i = 0; i < nsyms; i += 1)
3663 if (syms[i].symbol == NULL)
3664 continue;
3666 if (syms[i].symbol->aclass () == LOC_BLOCK)
3668 struct symtab_and_line sal =
3669 find_function_start_sal (syms[i].symbol, 1);
3671 gdb_printf ("[%d] ", i + first_choice);
3672 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3673 &type_print_raw_options);
3674 if (sal.symtab == NULL)
3675 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3676 metadata_style.style ().ptr (), nullptr, sal.line);
3677 else
3678 gdb_printf
3679 (_(" at %ps:%d\n"),
3680 styled_string (file_name_style.style (),
3681 symtab_to_filename_for_display (sal.symtab)),
3682 sal.line);
3683 continue;
3685 else
3687 int is_enumeral =
3688 (syms[i].symbol->aclass () == LOC_CONST
3689 && syms[i].symbol->type () != NULL
3690 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3691 struct symtab *symtab = NULL;
3693 if (syms[i].symbol->is_objfile_owned ())
3694 symtab = syms[i].symbol->symtab ();
3696 if (syms[i].symbol->line () != 0 && symtab != NULL)
3698 gdb_printf ("[%d] ", i + first_choice);
3699 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3700 &type_print_raw_options);
3701 gdb_printf (_(" at %ps:%ps\n"),
3702 styled_string (file_name_style.style (),
3703 symtab_to_filename_for_display (symtab)),
3704 styled_string (line_number_style.style (),
3705 pulongest (syms[i].symbol->line ())));
3707 else if (is_enumeral
3708 && syms[i].symbol->type ()->name () != NULL)
3710 gdb_printf (("[%d] "), i + first_choice);
3711 ada_print_type (syms[i].symbol->type (), NULL,
3712 gdb_stdout, -1, 0, &type_print_raw_options);
3713 gdb_printf (_("'(%s) (enumeral)\n"),
3714 syms[i].symbol->print_name ());
3716 else
3718 gdb_printf ("[%d] ", i + first_choice);
3719 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3720 &type_print_raw_options);
3722 if (symtab != NULL)
3723 gdb_printf (is_enumeral
3724 ? _(" in %ps (enumeral)\n")
3725 : _(" at %ps:?\n"),
3726 styled_string (file_name_style.style (),
3727 symtab_to_filename_for_display (symtab)));
3728 else
3729 gdb_printf (is_enumeral
3730 ? _(" (enumeral)\n")
3731 : _(" at ?\n"));
3736 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3737 "overload-choice");
3739 for (i = 0; i < n_chosen; i += 1)
3740 syms[i] = syms[chosen[i]];
3742 return n_chosen;
3745 /* See ada-lang.h. */
3747 block_symbol
3748 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3749 int nargs, value *argvec[])
3751 if (possible_user_operator_p (op, argvec))
3753 std::vector<struct block_symbol> candidates
3754 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3755 NULL, SEARCH_VFT);
3757 int i = ada_resolve_function (candidates, argvec,
3758 nargs, ada_decoded_op_name (op), NULL,
3759 parse_completion);
3760 if (i >= 0)
3761 return candidates[i];
3763 return {};
3766 /* See ada-lang.h. */
3768 block_symbol
3769 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3770 struct type *context_type,
3771 bool parse_completion,
3772 int nargs, value *argvec[],
3773 innermost_block_tracker *tracker)
3775 std::vector<struct block_symbol> candidates
3776 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3778 int i;
3779 if (candidates.size () == 1)
3780 i = 0;
3781 else
3783 i = ada_resolve_function
3784 (candidates,
3785 argvec, nargs,
3786 sym->linkage_name (),
3787 context_type, parse_completion);
3788 if (i < 0)
3789 error (_("Could not find a match for %s"), sym->print_name ());
3792 tracker->update (candidates[i]);
3793 return candidates[i];
3796 /* Resolve a mention of a name where the context type is an
3797 enumeration type. */
3799 static int
3800 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3801 const char *name, struct type *context_type,
3802 bool parse_completion)
3804 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3805 context_type = ada_check_typedef (context_type);
3807 /* We already know the name matches, so we're just looking for
3808 an element of the correct enum type. */
3809 struct type *type1 = context_type;
3810 for (int i = 0; i < syms.size (); ++i)
3812 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3813 if (type1 == type2)
3814 return i;
3817 for (int i = 0; i < syms.size (); ++i)
3819 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3820 if (strcmp (type1->name (), type2->name ()) != 0)
3821 continue;
3822 if (ada_identical_enum_types_p (type1, type2))
3823 return i;
3826 error (_("No name '%s' in enumeration type '%s'"), name,
3827 ada_type_name (context_type));
3830 /* See ada-lang.h. */
3832 block_symbol
3833 ada_resolve_variable (struct symbol *sym, const struct block *block,
3834 struct type *context_type,
3835 bool parse_completion,
3836 int deprocedure_p,
3837 innermost_block_tracker *tracker)
3839 std::vector<struct block_symbol> candidates
3840 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3842 if (std::any_of (candidates.begin (),
3843 candidates.end (),
3844 [] (block_symbol &bsym)
3846 switch (bsym.symbol->aclass ())
3848 case LOC_REGISTER:
3849 case LOC_ARG:
3850 case LOC_REF_ARG:
3851 case LOC_REGPARM_ADDR:
3852 case LOC_LOCAL:
3853 case LOC_COMPUTED:
3854 return true;
3855 default:
3856 return false;
3860 /* Types tend to get re-introduced locally, so if there
3861 are any local symbols that are not types, first filter
3862 out all types. */
3863 candidates.erase
3864 (std::remove_if
3865 (candidates.begin (),
3866 candidates.end (),
3867 [] (block_symbol &bsym)
3869 return bsym.symbol->aclass () == LOC_TYPEDEF;
3871 candidates.end ());
3874 /* Filter out artificial symbols. */
3875 candidates.erase
3876 (std::remove_if
3877 (candidates.begin (),
3878 candidates.end (),
3879 [] (block_symbol &bsym)
3881 return bsym.symbol->is_artificial ();
3883 candidates.end ());
3885 int i;
3886 if (candidates.empty ())
3887 error (_("No definition found for %s"), sym->print_name ());
3888 else if (candidates.size () == 1)
3889 i = 0;
3890 else if (context_type != nullptr
3891 && context_type->code () == TYPE_CODE_ENUM)
3892 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3893 parse_completion);
3894 else if (context_type == nullptr
3895 && symbols_are_identical_enums (candidates))
3897 /* If all the remaining symbols are identical enumerals, then
3898 just keep the first one and discard the rest.
3900 Unlike what we did previously, we do not discard any entry
3901 unless they are ALL identical. This is because the symbol
3902 comparison is not a strict comparison, but rather a practical
3903 comparison. If all symbols are considered identical, then
3904 we can just go ahead and use the first one and discard the rest.
3905 But if we cannot reduce the list to a single element, we have
3906 to ask the user to disambiguate anyways. And if we have to
3907 present a multiple-choice menu, it's less confusing if the list
3908 isn't missing some choices that were identical and yet distinct. */
3909 candidates.resize (1);
3910 i = 0;
3912 else if (deprocedure_p && !is_nonfunction (candidates))
3914 i = ada_resolve_function
3915 (candidates, NULL, 0,
3916 sym->linkage_name (),
3917 context_type, parse_completion);
3918 if (i < 0)
3919 error (_("Could not find a match for %s"), sym->print_name ());
3921 else
3923 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3924 user_select_syms (candidates.data (), candidates.size (), 1);
3925 i = 0;
3928 tracker->update (candidates[i]);
3929 return candidates[i];
3932 static bool ada_type_match (struct type *ftype, struct type *atype);
3934 /* Helper for ada_type_match that checks that two array types are
3935 compatible. As with that function, FTYPE is the formal type and
3936 ATYPE is the actual type. */
3938 static bool
3939 ada_type_match_arrays (struct type *ftype, struct type *atype)
3941 if (ftype->code () != TYPE_CODE_ARRAY
3942 && !ada_is_array_descriptor_type (ftype))
3943 return false;
3944 if (atype->code () != TYPE_CODE_ARRAY
3945 && !ada_is_array_descriptor_type (atype))
3946 return false;
3948 if (ada_array_arity (ftype) != ada_array_arity (atype))
3949 return false;
3951 struct type *f_elt_type = ada_array_element_type (ftype, -1);
3952 struct type *a_elt_type = ada_array_element_type (atype, -1);
3953 return ada_type_match (f_elt_type, a_elt_type);
3956 /* Return non-zero if formal type FTYPE matches actual type ATYPE.
3957 The term "match" here is rather loose. The match is heuristic and
3958 liberal -- while it tries to reject matches that are obviously
3959 incorrect, it may still let through some that do not strictly
3960 correspond to Ada rules. */
3962 static bool
3963 ada_type_match (struct type *ftype, struct type *atype)
3965 ftype = ada_check_typedef (ftype);
3966 atype = ada_check_typedef (atype);
3968 if (ftype->code () == TYPE_CODE_REF)
3969 ftype = ftype->target_type ();
3970 if (atype->code () == TYPE_CODE_REF)
3971 atype = atype->target_type ();
3973 switch (ftype->code ())
3975 default:
3976 return ftype->code () == atype->code ();
3977 case TYPE_CODE_PTR:
3978 if (atype->code () != TYPE_CODE_PTR)
3979 return false;
3980 atype = atype->target_type ();
3981 /* This can only happen if the actual argument is 'null'. */
3982 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3983 return true;
3984 return ada_type_match (ftype->target_type (), atype);
3985 case TYPE_CODE_INT:
3986 case TYPE_CODE_ENUM:
3987 case TYPE_CODE_RANGE:
3988 switch (atype->code ())
3990 case TYPE_CODE_INT:
3991 case TYPE_CODE_ENUM:
3992 case TYPE_CODE_RANGE:
3993 return true;
3994 default:
3995 return false;
3998 case TYPE_CODE_STRUCT:
3999 if (!ada_is_array_descriptor_type (ftype))
4000 return (atype->code () == TYPE_CODE_STRUCT
4001 && !ada_is_array_descriptor_type (atype));
4003 [[fallthrough]];
4004 case TYPE_CODE_ARRAY:
4005 return ada_type_match_arrays (ftype, atype);
4007 case TYPE_CODE_UNION:
4008 case TYPE_CODE_FLT:
4009 return (atype->code () == ftype->code ());
4013 /* Return non-zero if the formals of FUNC "sufficiently match" the
4014 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
4015 may also be an enumeral, in which case it is treated as a 0-
4016 argument function. */
4018 static int
4019 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
4021 int i;
4022 struct type *func_type = func->type ();
4024 if (func->aclass () == LOC_CONST
4025 && func_type->code () == TYPE_CODE_ENUM)
4026 return (n_actuals == 0);
4027 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
4028 return 0;
4030 if (func_type->num_fields () != n_actuals)
4031 return 0;
4033 for (i = 0; i < n_actuals; i += 1)
4035 if (actuals[i] == NULL)
4036 return 0;
4037 else
4039 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
4040 struct type *atype = ada_check_typedef (actuals[i]->type ());
4042 if (!ada_type_match (ftype, atype))
4043 return 0;
4046 return 1;
4049 /* False iff function type FUNC_TYPE definitely does not produce a value
4050 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4051 FUNC_TYPE is not a valid function type with a non-null return type
4052 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4054 static int
4055 return_match (struct type *func_type, struct type *context_type)
4057 struct type *return_type;
4059 if (func_type == NULL)
4060 return 1;
4062 if (func_type->code () == TYPE_CODE_FUNC)
4063 return_type = get_base_type (func_type->target_type ());
4064 else
4065 return_type = get_base_type (func_type);
4066 if (return_type == NULL)
4067 return 1;
4069 context_type = get_base_type (context_type);
4071 if (return_type->code () == TYPE_CODE_ENUM)
4072 return context_type == NULL || return_type == context_type;
4073 else if (context_type == NULL)
4074 return return_type->code () != TYPE_CODE_VOID;
4075 else
4076 return return_type->code () == context_type->code ();
4080 /* Returns the index in SYMS that contains the symbol for the
4081 function (if any) that matches the types of the NARGS arguments in
4082 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4083 that returns that type, then eliminate matches that don't. If
4084 CONTEXT_TYPE is void and there is at least one match that does not
4085 return void, eliminate all matches that do.
4087 Asks the user if there is more than one match remaining. Returns -1
4088 if there is no such symbol or none is selected. NAME is used
4089 solely for messages. May re-arrange and modify SYMS in
4090 the process; the index returned is for the modified vector. */
4092 static int
4093 ada_resolve_function (std::vector<struct block_symbol> &syms,
4094 struct value **args, int nargs,
4095 const char *name, struct type *context_type,
4096 bool parse_completion)
4098 int fallback;
4099 int k;
4100 int m; /* Number of hits */
4102 m = 0;
4103 /* In the first pass of the loop, we only accept functions matching
4104 context_type. If none are found, we add a second pass of the loop
4105 where every function is accepted. */
4106 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4108 for (k = 0; k < syms.size (); k += 1)
4110 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4112 if (ada_args_match (syms[k].symbol, args, nargs)
4113 && (fallback || return_match (type, context_type)))
4115 syms[m] = syms[k];
4116 m += 1;
4121 /* If we got multiple matches, ask the user which one to use. Don't do this
4122 interactive thing during completion, though, as the purpose of the
4123 completion is providing a list of all possible matches. Prompting the
4124 user to filter it down would be completely unexpected in this case. */
4125 if (m == 0)
4126 return -1;
4127 else if (m > 1 && !parse_completion)
4129 gdb_printf (_("Multiple matches for %s\n"), name);
4130 user_select_syms (syms.data (), m, 1);
4131 return 0;
4133 return 0;
4136 /* Type-class predicates */
4138 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4139 or FLOAT). */
4141 static int
4142 numeric_type_p (struct type *type)
4144 if (type == NULL)
4145 return 0;
4146 else
4148 switch (type->code ())
4150 case TYPE_CODE_INT:
4151 case TYPE_CODE_FLT:
4152 case TYPE_CODE_FIXED_POINT:
4153 return 1;
4154 case TYPE_CODE_RANGE:
4155 return (type == type->target_type ()
4156 || numeric_type_p (type->target_type ()));
4157 default:
4158 return 0;
4163 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4165 static int
4166 integer_type_p (struct type *type)
4168 if (type == NULL)
4169 return 0;
4170 else
4172 switch (type->code ())
4174 case TYPE_CODE_INT:
4175 return 1;
4176 case TYPE_CODE_RANGE:
4177 return (type == type->target_type ()
4178 || integer_type_p (type->target_type ()));
4179 default:
4180 return 0;
4185 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4187 static int
4188 scalar_type_p (struct type *type)
4190 if (type == NULL)
4191 return 0;
4192 else
4194 switch (type->code ())
4196 case TYPE_CODE_INT:
4197 case TYPE_CODE_RANGE:
4198 case TYPE_CODE_ENUM:
4199 case TYPE_CODE_FLT:
4200 case TYPE_CODE_FIXED_POINT:
4201 return 1;
4202 default:
4203 return 0;
4208 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4209 This essentially means one of (INT, RANGE, ENUM) -- but note that
4210 "enum" includes character and boolean as well. */
4212 static int
4213 discrete_type_p (struct type *type)
4215 if (type == NULL)
4216 return 0;
4217 else
4219 switch (type->code ())
4221 case TYPE_CODE_INT:
4222 case TYPE_CODE_RANGE:
4223 case TYPE_CODE_ENUM:
4224 case TYPE_CODE_BOOL:
4225 case TYPE_CODE_CHAR:
4226 return 1;
4227 default:
4228 return 0;
4233 /* Returns non-zero if OP with operands in the vector ARGS could be
4234 a user-defined function. Errs on the side of pre-defined operators
4235 (i.e., result 0). */
4237 static int
4238 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4240 struct type *type0 =
4241 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4242 struct type *type1 =
4243 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4245 if (type0 == NULL)
4246 return 0;
4248 switch (op)
4250 default:
4251 return 0;
4253 case BINOP_ADD:
4254 case BINOP_SUB:
4255 case BINOP_MUL:
4256 case BINOP_DIV:
4257 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4259 case BINOP_REM:
4260 case BINOP_MOD:
4261 case BINOP_BITWISE_AND:
4262 case BINOP_BITWISE_IOR:
4263 case BINOP_BITWISE_XOR:
4264 return (!(integer_type_p (type0) && integer_type_p (type1)));
4266 case BINOP_EQUAL:
4267 case BINOP_NOTEQUAL:
4268 case BINOP_LESS:
4269 case BINOP_GTR:
4270 case BINOP_LEQ:
4271 case BINOP_GEQ:
4272 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4274 case BINOP_CONCAT:
4275 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4277 case BINOP_EXP:
4278 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4280 case UNOP_NEG:
4281 case UNOP_PLUS:
4282 case UNOP_LOGICAL_NOT:
4283 case UNOP_ABS:
4284 return (!numeric_type_p (type0));
4289 /* Renaming */
4291 /* NOTES:
4293 1. In the following, we assume that a renaming type's name may
4294 have an ___XD suffix. It would be nice if this went away at some
4295 point.
4296 2. We handle both the (old) purely type-based representation of
4297 renamings and the (new) variable-based encoding. At some point,
4298 it is devoutly to be hoped that the former goes away
4299 (FIXME: hilfinger-2007-07-09).
4300 3. Subprogram renamings are not implemented, although the XRS
4301 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4303 /* If SYM encodes a renaming,
4305 <renaming> renames <renamed entity>,
4307 sets *LEN to the length of the renamed entity's name,
4308 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4309 the string describing the subcomponent selected from the renamed
4310 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4311 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4312 are undefined). Otherwise, returns a value indicating the category
4313 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4314 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4315 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4316 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4317 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4318 may be NULL, in which case they are not assigned.
4320 [Currently, however, GCC does not generate subprogram renamings.] */
4322 enum ada_renaming_category
4323 ada_parse_renaming (struct symbol *sym,
4324 const char **renamed_entity, int *len,
4325 const char **renaming_expr)
4327 enum ada_renaming_category kind;
4328 const char *info;
4329 const char *suffix;
4331 if (sym == NULL)
4332 return ADA_NOT_RENAMING;
4333 switch (sym->aclass ())
4335 default:
4336 return ADA_NOT_RENAMING;
4337 case LOC_LOCAL:
4338 case LOC_STATIC:
4339 case LOC_COMPUTED:
4340 case LOC_OPTIMIZED_OUT:
4341 info = strstr (sym->linkage_name (), "___XR");
4342 if (info == NULL)
4343 return ADA_NOT_RENAMING;
4344 switch (info[5])
4346 case '_':
4347 kind = ADA_OBJECT_RENAMING;
4348 info += 6;
4349 break;
4350 case 'E':
4351 kind = ADA_EXCEPTION_RENAMING;
4352 info += 7;
4353 break;
4354 case 'P':
4355 kind = ADA_PACKAGE_RENAMING;
4356 info += 7;
4357 break;
4358 case 'S':
4359 kind = ADA_SUBPROGRAM_RENAMING;
4360 info += 7;
4361 break;
4362 default:
4363 return ADA_NOT_RENAMING;
4367 if (renamed_entity != NULL)
4368 *renamed_entity = info;
4369 suffix = strstr (info, "___XE");
4370 if (suffix == NULL || suffix == info)
4371 return ADA_NOT_RENAMING;
4372 if (len != NULL)
4373 *len = strlen (info) - strlen (suffix);
4374 suffix += 5;
4375 if (renaming_expr != NULL)
4376 *renaming_expr = suffix;
4377 return kind;
4380 /* Compute the value of the given RENAMING_SYM, which is expected to
4381 be a symbol encoding a renaming expression. BLOCK is the block
4382 used to evaluate the renaming. */
4384 static struct value *
4385 ada_read_renaming_var_value (struct symbol *renaming_sym,
4386 const struct block *block)
4388 const char *sym_name;
4390 sym_name = renaming_sym->linkage_name ();
4391 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4392 return expr->evaluate ();
4396 /* Evaluation: Function Calls */
4398 /* Return an lvalue containing the value VAL. This is the identity on
4399 lvalues, and otherwise has the side-effect of allocating memory
4400 in the inferior where a copy of the value contents is copied. */
4402 static struct value *
4403 ensure_lval (struct value *val)
4405 if (val->lval () == not_lval
4406 || val->lval () == lval_internalvar)
4408 int len = ada_check_typedef (val->type ())->length ();
4409 const CORE_ADDR addr =
4410 value_as_long (value_allocate_space_in_inferior (len));
4412 val->set_lval (lval_memory);
4413 val->set_address (addr);
4414 write_memory (addr, val->contents ().data (), len);
4417 return val;
4420 /* Given ARG, a value of type (pointer or reference to a)*
4421 structure/union, extract the component named NAME from the ultimate
4422 target structure/union and return it as a value with its
4423 appropriate type.
4425 The routine searches for NAME among all members of the structure itself
4426 and (recursively) among all members of any wrapper members
4427 (e.g., '_parent').
4429 If NO_ERR, then simply return NULL in case of error, rather than
4430 calling error. */
4432 static struct value *
4433 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4435 struct type *t, *t1;
4436 struct value *v;
4437 int check_tag;
4439 v = NULL;
4440 t1 = t = ada_check_typedef (arg->type ());
4441 if (t->code () == TYPE_CODE_REF)
4443 t1 = t->target_type ();
4444 if (t1 == NULL)
4445 goto BadValue;
4446 t1 = ada_check_typedef (t1);
4447 if (t1->code () == TYPE_CODE_PTR)
4449 arg = coerce_ref (arg);
4450 t = t1;
4454 while (t->code () == TYPE_CODE_PTR)
4456 t1 = t->target_type ();
4457 if (t1 == NULL)
4458 goto BadValue;
4459 t1 = ada_check_typedef (t1);
4460 if (t1->code () == TYPE_CODE_PTR)
4462 arg = value_ind (arg);
4463 t = t1;
4465 else
4466 break;
4469 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4470 goto BadValue;
4472 if (t1 == t)
4473 v = ada_search_struct_field (name, arg, 0, t);
4474 else
4476 int bit_offset, bit_size, byte_offset;
4477 struct type *field_type;
4478 CORE_ADDR address;
4480 if (t->code () == TYPE_CODE_PTR)
4481 address = ada_value_ind (arg)->address ();
4482 else
4483 address = ada_coerce_ref (arg)->address ();
4485 /* Check to see if this is a tagged type. We also need to handle
4486 the case where the type is a reference to a tagged type, but
4487 we have to be careful to exclude pointers to tagged types.
4488 The latter should be shown as usual (as a pointer), whereas
4489 a reference should mostly be transparent to the user. */
4491 if (ada_is_tagged_type (t1, 0)
4492 || (t1->code () == TYPE_CODE_REF
4493 && ada_is_tagged_type (t1->target_type (), 0)))
4495 /* We first try to find the searched field in the current type.
4496 If not found then let's look in the fixed type. */
4498 if (!find_struct_field (name, t1, 0,
4499 nullptr, nullptr, nullptr,
4500 nullptr, nullptr))
4501 check_tag = 1;
4502 else
4503 check_tag = 0;
4505 else
4506 check_tag = 0;
4508 /* Convert to fixed type in all cases, so that we have proper
4509 offsets to each field in unconstrained record types. */
4510 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4511 address, NULL, check_tag);
4513 /* Resolve the dynamic type as well. */
4514 arg = value_from_contents_and_address (t1, nullptr, address);
4515 t1 = arg->type ();
4517 if (find_struct_field (name, t1, 0,
4518 &field_type, &byte_offset, &bit_offset,
4519 &bit_size, NULL))
4521 if (bit_size != 0)
4523 if (t->code () == TYPE_CODE_REF)
4524 arg = ada_coerce_ref (arg);
4525 else
4526 arg = ada_value_ind (arg);
4527 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4528 bit_offset, bit_size,
4529 field_type);
4531 else
4532 v = value_at_lazy (field_type, address + byte_offset);
4536 if (v != NULL || no_err)
4537 return v;
4538 else
4539 error (_("There is no member named %s."), name);
4541 BadValue:
4542 if (no_err)
4543 return NULL;
4544 else
4545 error (_("Attempt to extract a component of "
4546 "a value that is not a record."));
4549 /* Return the value ACTUAL, converted to be an appropriate value for a
4550 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4551 allocating any necessary descriptors (fat pointers), or copies of
4552 values not residing in memory, updating it as needed. */
4554 struct value *
4555 ada_convert_actual (struct value *actual, struct type *formal_type0)
4557 struct type *actual_type = ada_check_typedef (actual->type ());
4558 struct type *formal_type = ada_check_typedef (formal_type0);
4559 struct type *formal_target =
4560 formal_type->code () == TYPE_CODE_PTR
4561 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4562 struct type *actual_target =
4563 actual_type->code () == TYPE_CODE_PTR
4564 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4566 if (ada_is_array_descriptor_type (formal_target)
4567 && actual_target->code () == TYPE_CODE_ARRAY)
4568 return make_array_descriptor (formal_type, actual);
4569 else if (formal_type->code () == TYPE_CODE_PTR
4570 || formal_type->code () == TYPE_CODE_REF)
4572 struct value *result;
4574 if (formal_target->code () == TYPE_CODE_ARRAY
4575 && ada_is_array_descriptor_type (actual_target))
4576 result = desc_data (actual);
4577 else if (formal_type->code () != TYPE_CODE_PTR)
4579 if (actual->lval () != lval_memory)
4581 struct value *val;
4583 actual_type = ada_check_typedef (actual->type ());
4584 val = value::allocate (actual_type);
4585 copy (actual->contents (), val->contents_raw ());
4586 actual = ensure_lval (val);
4588 result = value_addr (actual);
4590 else
4591 return actual;
4592 return value_cast_pointers (formal_type, result, 0);
4594 else if (actual_type->code () == TYPE_CODE_PTR)
4595 return ada_value_ind (actual);
4596 else if (ada_is_aligner_type (formal_type))
4598 /* We need to turn this parameter into an aligner type
4599 as well. */
4600 struct value *aligner = value::allocate (formal_type);
4601 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4603 value_assign_to_component (aligner, component, actual);
4604 return aligner;
4607 return actual;
4610 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4611 type TYPE. This is usually an inefficient no-op except on some targets
4612 (such as AVR) where the representation of a pointer and an address
4613 differs. */
4615 static CORE_ADDR
4616 value_pointer (struct value *value, struct type *type)
4618 unsigned len = type->length ();
4619 gdb_byte *buf = (gdb_byte *) alloca (len);
4620 CORE_ADDR addr;
4622 addr = value->address ();
4623 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4624 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4625 return addr;
4629 /* Push a descriptor of type TYPE for array value ARR on the stack at
4630 *SP, updating *SP to reflect the new descriptor. Return either
4631 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4632 to-descriptor type rather than a descriptor type), a struct value *
4633 representing a pointer to this descriptor. */
4635 static struct value *
4636 make_array_descriptor (struct type *type, struct value *arr)
4638 struct type *bounds_type = desc_bounds_type (type);
4639 struct type *desc_type = desc_base_type (type);
4640 struct value *descriptor = value::allocate (desc_type);
4641 struct value *bounds = value::allocate (bounds_type);
4642 int i;
4644 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4645 i > 0; i -= 1)
4647 modify_field (bounds->type (),
4648 bounds->contents_writeable ().data (),
4649 ada_array_bound (arr, i, 0),
4650 desc_bound_bitpos (bounds_type, i, 0),
4651 desc_bound_bitsize (bounds_type, i, 0));
4652 modify_field (bounds->type (),
4653 bounds->contents_writeable ().data (),
4654 ada_array_bound (arr, i, 1),
4655 desc_bound_bitpos (bounds_type, i, 1),
4656 desc_bound_bitsize (bounds_type, i, 1));
4659 bounds = ensure_lval (bounds);
4661 modify_field (descriptor->type (),
4662 descriptor->contents_writeable ().data (),
4663 value_pointer (ensure_lval (arr),
4664 desc_type->field (0).type ()),
4665 fat_pntr_data_bitpos (desc_type),
4666 fat_pntr_data_bitsize (desc_type));
4668 modify_field (descriptor->type (),
4669 descriptor->contents_writeable ().data (),
4670 value_pointer (bounds,
4671 desc_type->field (1).type ()),
4672 fat_pntr_bounds_bitpos (desc_type),
4673 fat_pntr_bounds_bitsize (desc_type));
4675 descriptor = ensure_lval (descriptor);
4677 if (type->code () == TYPE_CODE_PTR)
4678 return value_addr (descriptor);
4679 else
4680 return descriptor;
4683 /* Symbol Cache Module */
4685 /* Performance measurements made as of 2010-01-15 indicate that
4686 this cache does bring some noticeable improvements. Depending
4687 on the type of entity being printed, the cache can make it as much
4688 as an order of magnitude faster than without it.
4690 The descriptive type DWARF extension has significantly reduced
4691 the need for this cache, at least when DWARF is being used. However,
4692 even in this case, some expensive name-based symbol searches are still
4693 sometimes necessary - to find an XVZ variable, mostly. */
4695 /* See ada-lang.h. */
4697 void
4698 ada_clear_symbol_cache (program_space *pspace)
4700 ada_pspace_data_handle.clear (pspace);
4703 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4704 Return 1 if found, 0 otherwise.
4706 If an entry was found and SYM is not NULL, set *SYM to the entry's
4707 SYM. Same principle for BLOCK if not NULL. */
4709 static int
4710 lookup_cached_symbol (const char *name, domain_search_flags domain,
4711 struct symbol **sym, const struct block **block)
4713 htab_t tab = get_ada_pspace_data (current_program_space);
4714 cache_entry_search search;
4715 search.name = name;
4716 search.domain = domain;
4718 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4719 search.hash ());
4720 if (e == nullptr)
4721 return 0;
4722 if (sym != nullptr)
4723 *sym = e->sym;
4724 if (block != nullptr)
4725 *block = e->block;
4726 return 1;
4729 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4730 in domain DOMAIN, save this result in our symbol cache. */
4732 static void
4733 cache_symbol (const char *name, domain_search_flags domain,
4734 struct symbol *sym, const struct block *block)
4736 /* Symbols for builtin types don't have a block.
4737 For now don't cache such symbols. */
4738 if (sym != NULL && !sym->is_objfile_owned ())
4739 return;
4741 /* If the symbol is a local symbol, then do not cache it, as a search
4742 for that symbol depends on the context. To determine whether
4743 the symbol is local or not, we check the block where we found it
4744 against the global and static blocks of its associated symtab. */
4745 if (sym != nullptr)
4747 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4749 if (bv.global_block () != block && bv.static_block () != block)
4750 return;
4753 htab_t tab = get_ada_pspace_data (current_program_space);
4754 cache_entry_search search;
4755 search.name = name;
4756 search.domain = domain;
4758 void **slot = htab_find_slot_with_hash (tab, &search,
4759 search.hash (), INSERT);
4761 cache_entry *e = new cache_entry;
4762 e->name = name;
4763 e->domain = domain;
4764 e->sym = sym;
4765 e->block = block;
4767 *slot = e;
4770 /* Symbol Lookup */
4772 /* Return the symbol name match type that should be used used when
4773 searching for all symbols matching LOOKUP_NAME.
4775 LOOKUP_NAME is expected to be a symbol name after transformation
4776 for Ada lookups. */
4778 static symbol_name_match_type
4779 name_match_type_from_name (const char *lookup_name)
4781 return (strstr (lookup_name, "__") == NULL
4782 ? symbol_name_match_type::WILD
4783 : symbol_name_match_type::FULL);
4786 /* Return the result of a standard (literal, C-like) lookup of NAME in
4787 given DOMAIN, visible from lexical block BLOCK. */
4789 static struct symbol *
4790 standard_lookup (const char *name, const struct block *block,
4791 domain_search_flags domain)
4793 /* Initialize it just to avoid a GCC false warning. */
4794 struct block_symbol sym = {};
4796 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4797 return sym.symbol;
4798 sym = ada_lookup_encoded_symbol (name, block, domain);
4799 cache_symbol (name, domain, sym.symbol, sym.block);
4800 return sym.symbol;
4804 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4805 in the symbol fields of SYMS. We treat enumerals as functions,
4806 since they contend in overloading in the same way. */
4807 static int
4808 is_nonfunction (const std::vector<struct block_symbol> &syms)
4810 for (const block_symbol &sym : syms)
4811 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4812 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4813 || sym.symbol->aclass () != LOC_CONST))
4814 return 1;
4816 return 0;
4819 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4820 struct types. Otherwise, they may not. */
4822 static int
4823 equiv_types (struct type *type0, struct type *type1)
4825 if (type0 == type1)
4826 return 1;
4827 if (type0 == NULL || type1 == NULL
4828 || type0->code () != type1->code ())
4829 return 0;
4830 if ((type0->code () == TYPE_CODE_STRUCT
4831 || type0->code () == TYPE_CODE_ENUM)
4832 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4833 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4834 return 1;
4836 return 0;
4839 /* True iff SYM0 represents the same entity as SYM1, or one that is
4840 no more defined than that of SYM1. */
4842 static int
4843 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4845 if (sym0 == sym1)
4846 return 1;
4847 if (sym0->domain () != sym1->domain ()
4848 || sym0->aclass () != sym1->aclass ())
4849 return 0;
4851 switch (sym0->aclass ())
4853 case LOC_UNDEF:
4854 return 1;
4855 case LOC_TYPEDEF:
4857 struct type *type0 = sym0->type ();
4858 struct type *type1 = sym1->type ();
4859 const char *name0 = sym0->linkage_name ();
4860 const char *name1 = sym1->linkage_name ();
4861 int len0 = strlen (name0);
4863 return
4864 type0->code () == type1->code ()
4865 && (equiv_types (type0, type1)
4866 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4867 && startswith (name1 + len0, "___XV")));
4869 case LOC_CONST:
4870 return sym0->value_longest () == sym1->value_longest ()
4871 && equiv_types (sym0->type (), sym1->type ());
4873 case LOC_STATIC:
4875 const char *name0 = sym0->linkage_name ();
4876 const char *name1 = sym1->linkage_name ();
4877 return (strcmp (name0, name1) == 0
4878 && sym0->value_address () == sym1->value_address ());
4881 default:
4882 return 0;
4886 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4887 records in RESULT. Do nothing if SYM is a duplicate. */
4889 static void
4890 add_defn_to_vec (std::vector<struct block_symbol> &result,
4891 struct symbol *sym,
4892 const struct block *block)
4894 /* Do not try to complete stub types, as the debugger is probably
4895 already scanning all symbols matching a certain name at the
4896 time when this function is called. Trying to replace the stub
4897 type by its associated full type will cause us to restart a scan
4898 which may lead to an infinite recursion. Instead, the client
4899 collecting the matching symbols will end up collecting several
4900 matches, with at least one of them complete. It can then filter
4901 out the stub ones if needed. */
4903 for (int i = result.size () - 1; i >= 0; i -= 1)
4905 if (lesseq_defined_than (sym, result[i].symbol))
4906 return;
4907 else if (lesseq_defined_than (result[i].symbol, sym))
4909 result[i].symbol = sym;
4910 result[i].block = block;
4911 return;
4915 struct block_symbol info;
4916 info.symbol = sym;
4917 info.block = block;
4918 result.push_back (info);
4921 /* Return a bound minimal symbol matching NAME according to Ada
4922 decoding rules. Returns an invalid symbol if there is no such
4923 minimal symbol. Names prefixed with "standard__" are handled
4924 specially: "standard__" is first stripped off, and only static and
4925 global symbols are searched. */
4927 bound_minimal_symbol
4928 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4930 bound_minimal_symbol result;
4932 symbol_name_match_type match_type = name_match_type_from_name (name);
4933 lookup_name_info lookup_name (name, match_type);
4935 symbol_name_matcher_ftype *match_name
4936 = ada_get_symbol_name_matcher (lookup_name);
4938 gdbarch_iterate_over_objfiles_in_search_order
4939 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
4940 [&result, lookup_name, match_name] (struct objfile *obj)
4942 for (minimal_symbol *msymbol : obj->msymbols ())
4944 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4945 && msymbol->type () != mst_solib_trampoline)
4947 result.minsym = msymbol;
4948 result.objfile = obj;
4949 return 1;
4953 return 0;
4954 }, objfile);
4956 return result;
4959 /* True if TYPE is definitely an artificial type supplied to a symbol
4960 for which no debugging information was given in the symbol file. */
4962 static int
4963 is_nondebugging_type (struct type *type)
4965 const char *name = ada_type_name (type);
4967 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4970 /* Return true if TYPE1 and TYPE2 are two enumeration types
4971 that are deemed "identical" for practical purposes.
4973 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4974 types. */
4976 static bool
4977 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4979 /* The heuristic we use here is fairly conservative. We consider
4980 that 2 enumerate types are identical if they have the same
4981 number of enumerals and that all enumerals have the same
4982 underlying value and name. */
4984 if (type1->num_fields () != type2->num_fields ())
4985 return false;
4987 /* All enums in the type should have an identical underlying value. */
4988 for (int i = 0; i < type1->num_fields (); i++)
4989 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4990 return false;
4992 /* All enumerals should also have the same name (modulo any numerical
4993 suffix). */
4994 for (int i = 0; i < type1->num_fields (); i++)
4996 const char *name_1 = type1->field (i).name ();
4997 const char *name_2 = type2->field (i).name ();
4998 int len_1 = strlen (name_1);
4999 int len_2 = strlen (name_2);
5001 ada_remove_trailing_digits (name_1, &len_1);
5002 ada_remove_trailing_digits (name_2, &len_2);
5003 if (len_1 != len_2 || strncmp (name_1, name_2, len_1) != 0)
5004 return false;
5007 return true;
5010 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
5011 that are deemed "identical" for practical purposes. Sometimes,
5012 enumerals are not strictly identical, but their types are so similar
5013 that they can be considered identical.
5015 For instance, consider the following code:
5017 type Color is (Black, Red, Green, Blue, White);
5018 type RGB_Color is new Color range Red .. Blue;
5020 Type RGB_Color is a subrange of an implicit type which is a copy
5021 of type Color. If we call that implicit type RGB_ColorB ("B" is
5022 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5023 As a result, when an expression references any of the enumeral
5024 by name (Eg. "print green"), the expression is technically
5025 ambiguous and the user should be asked to disambiguate. But
5026 doing so would only hinder the user, since it wouldn't matter
5027 what choice he makes, the outcome would always be the same.
5028 So, for practical purposes, we consider them as the same. */
5030 static int
5031 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5033 int i;
5035 /* Before performing a thorough comparison check of each type,
5036 we perform a series of inexpensive checks. We expect that these
5037 checks will quickly fail in the vast majority of cases, and thus
5038 help prevent the unnecessary use of a more expensive comparison.
5039 Said comparison also expects us to make some of these checks
5040 (see ada_identical_enum_types_p). */
5042 /* Quick check: All symbols should have an enum type. */
5043 for (i = 0; i < syms.size (); i++)
5044 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5045 return 0;
5047 /* Quick check: They should all have the same value. */
5048 for (i = 1; i < syms.size (); i++)
5049 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5050 return 0;
5052 /* All the sanity checks passed, so we might have a set of
5053 identical enumeration types. Perform a more complete
5054 comparison of the type of each symbol. */
5055 for (i = 1; i < syms.size (); i++)
5056 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5057 syms[0].symbol->type ()))
5058 return 0;
5060 return 1;
5063 /* Remove any non-debugging symbols in SYMS that definitely
5064 duplicate other symbols in the list (The only case I know of where
5065 this happens is when object files containing stabs-in-ecoff are
5066 linked with files containing ordinary ecoff debugging symbols (or no
5067 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5069 static void
5070 remove_extra_symbols (std::vector<struct block_symbol> &syms)
5072 int i, j;
5074 /* We should never be called with less than 2 symbols, as there
5075 cannot be any extra symbol in that case. But it's easy to
5076 handle, since we have nothing to do in that case. */
5077 if (syms.size () < 2)
5078 return;
5080 i = 0;
5081 while (i < syms.size ())
5083 bool remove_p = false;
5085 /* If two symbols have the same name and one of them is a stub type,
5086 the get rid of the stub. */
5088 if (syms[i].symbol->type ()->is_stub ()
5089 && syms[i].symbol->linkage_name () != NULL)
5091 for (j = 0; !remove_p && j < syms.size (); j++)
5093 if (j != i
5094 && !syms[j].symbol->type ()->is_stub ()
5095 && syms[j].symbol->linkage_name () != NULL
5096 && strcmp (syms[i].symbol->linkage_name (),
5097 syms[j].symbol->linkage_name ()) == 0)
5098 remove_p = true;
5102 /* Two symbols with the same name, same class and same address
5103 should be identical. */
5105 else if (syms[i].symbol->linkage_name () != NULL
5106 && syms[i].symbol->aclass () == LOC_STATIC
5107 && is_nondebugging_type (syms[i].symbol->type ()))
5109 for (j = 0; !remove_p && j < syms.size (); j += 1)
5111 if (i != j
5112 && syms[j].symbol->linkage_name () != NULL
5113 && strcmp (syms[i].symbol->linkage_name (),
5114 syms[j].symbol->linkage_name ()) == 0
5115 && (syms[i].symbol->aclass ()
5116 == syms[j].symbol->aclass ())
5117 && syms[i].symbol->value_address ()
5118 == syms[j].symbol->value_address ())
5119 remove_p = true;
5123 /* Two functions with the same block are identical. */
5125 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5127 for (j = 0; !remove_p && j < syms.size (); j += 1)
5129 if (i != j
5130 && syms[j].symbol->aclass () == LOC_BLOCK
5131 && (syms[i].symbol->value_block ()
5132 == syms[j].symbol->value_block ()))
5133 remove_p = true;
5137 if (remove_p)
5138 syms.erase (syms.begin () + i);
5139 else
5140 i += 1;
5144 /* Given a type that corresponds to a renaming entity, use the type name
5145 to extract the scope (package name or function name, fully qualified,
5146 and following the GNAT encoding convention) where this renaming has been
5147 defined. */
5149 static std::string
5150 xget_renaming_scope (struct type *renaming_type)
5152 /* The renaming types adhere to the following convention:
5153 <scope>__<rename>___<XR extension>.
5154 So, to extract the scope, we search for the "___XR" extension,
5155 and then backtrack until we find the first "__". */
5157 const char *name = renaming_type->name ();
5158 const char *suffix = strstr (name, "___XR");
5159 const char *last;
5161 /* Now, backtrack a bit until we find the first "__". Start looking
5162 at suffix - 3, as the <rename> part is at least one character long. */
5164 for (last = suffix - 3; last > name; last--)
5165 if (last[0] == '_' && last[1] == '_')
5166 break;
5168 /* Make a copy of scope and return it. */
5169 return std::string (name, last);
5172 /* Return nonzero if NAME corresponds to a package name. */
5174 static int
5175 is_package_name (const char *name)
5177 /* Here, We take advantage of the fact that no symbols are generated
5178 for packages, while symbols are generated for each function.
5179 So the condition for NAME represent a package becomes equivalent
5180 to NAME not existing in our list of symbols. There is only one
5181 small complication with library-level functions (see below). */
5183 /* If it is a function that has not been defined at library level,
5184 then we should be able to look it up in the symbols. */
5185 if (standard_lookup (name, NULL, SEARCH_VFT) != NULL)
5186 return 0;
5188 /* Library-level function names start with "_ada_". See if function
5189 "_ada_" followed by NAME can be found. */
5191 /* Do a quick check that NAME does not contain "__", since library-level
5192 functions names cannot contain "__" in them. */
5193 if (strstr (name, "__") != NULL)
5194 return 0;
5196 std::string fun_name = string_printf ("_ada_%s", name);
5198 return (standard_lookup (fun_name.c_str (), NULL, SEARCH_VFT) == NULL);
5201 /* Return nonzero if SYM corresponds to a renaming entity that is
5202 not visible from FUNCTION_NAME. */
5204 static int
5205 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5207 if (sym->aclass () != LOC_TYPEDEF)
5208 return 0;
5210 std::string scope = xget_renaming_scope (sym->type ());
5212 /* If the rename has been defined in a package, then it is visible. */
5213 if (is_package_name (scope.c_str ()))
5214 return 0;
5216 /* Check that the rename is in the current function scope by checking
5217 that its name starts with SCOPE. */
5219 /* If the function name starts with "_ada_", it means that it is
5220 a library-level function. Strip this prefix before doing the
5221 comparison, as the encoding for the renaming does not contain
5222 this prefix. */
5223 if (startswith (function_name, "_ada_"))
5224 function_name += 5;
5226 return !startswith (function_name, scope.c_str ());
5229 /* Remove entries from SYMS that corresponds to a renaming entity that
5230 is not visible from the function associated with CURRENT_BLOCK or
5231 that is superfluous due to the presence of more specific renaming
5232 information. Places surviving symbols in the initial entries of
5233 SYMS.
5235 Rationale:
5236 First, in cases where an object renaming is implemented as a
5237 reference variable, GNAT may produce both the actual reference
5238 variable and the renaming encoding. In this case, we discard the
5239 latter.
5241 Second, GNAT emits a type following a specified encoding for each renaming
5242 entity. Unfortunately, STABS currently does not support the definition
5243 of types that are local to a given lexical block, so all renamings types
5244 are emitted at library level. As a consequence, if an application
5245 contains two renaming entities using the same name, and a user tries to
5246 print the value of one of these entities, the result of the ada symbol
5247 lookup will also contain the wrong renaming type.
5249 This function partially covers for this limitation by attempting to
5250 remove from the SYMS list renaming symbols that should be visible
5251 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5252 method with the current information available. The implementation
5253 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5255 - When the user tries to print a rename in a function while there
5256 is another rename entity defined in a package: Normally, the
5257 rename in the function has precedence over the rename in the
5258 package, so the latter should be removed from the list. This is
5259 currently not the case.
5261 - This function will incorrectly remove valid renames if
5262 the CURRENT_BLOCK corresponds to a function which symbol name
5263 has been changed by an "Export" pragma. As a consequence,
5264 the user will be unable to print such rename entities. */
5266 static void
5267 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5268 const struct block *current_block)
5270 struct symbol *current_function;
5271 const char *current_function_name;
5272 int i;
5273 int is_new_style_renaming;
5275 /* If there is both a renaming foo___XR... encoded as a variable and
5276 a simple variable foo in the same block, discard the latter.
5277 First, zero out such symbols, then compress. */
5278 is_new_style_renaming = 0;
5279 for (i = 0; i < syms->size (); i += 1)
5281 struct symbol *sym = (*syms)[i].symbol;
5282 const struct block *block = (*syms)[i].block;
5283 const char *name;
5284 const char *suffix;
5286 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5287 continue;
5288 name = sym->linkage_name ();
5289 suffix = strstr (name, "___XR");
5291 if (suffix != NULL)
5293 int name_len = suffix - name;
5294 int j;
5296 is_new_style_renaming = 1;
5297 for (j = 0; j < syms->size (); j += 1)
5298 if (i != j && (*syms)[j].symbol != NULL
5299 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5300 name_len) == 0
5301 && block == (*syms)[j].block)
5302 (*syms)[j].symbol = NULL;
5305 if (is_new_style_renaming)
5307 int j, k;
5309 for (j = k = 0; j < syms->size (); j += 1)
5310 if ((*syms)[j].symbol != NULL)
5312 (*syms)[k] = (*syms)[j];
5313 k += 1;
5315 syms->resize (k);
5316 return;
5319 /* Extract the function name associated to CURRENT_BLOCK.
5320 Abort if unable to do so. */
5322 if (current_block == NULL)
5323 return;
5325 current_function = current_block->linkage_function ();
5326 if (current_function == NULL)
5327 return;
5329 current_function_name = current_function->linkage_name ();
5330 if (current_function_name == NULL)
5331 return;
5333 /* Check each of the symbols, and remove it from the list if it is
5334 a type corresponding to a renaming that is out of the scope of
5335 the current block. */
5337 i = 0;
5338 while (i < syms->size ())
5340 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5341 == ADA_OBJECT_RENAMING
5342 && old_renaming_is_invisible ((*syms)[i].symbol,
5343 current_function_name))
5344 syms->erase (syms->begin () + i);
5345 else
5346 i += 1;
5350 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5351 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5353 Note: This function assumes that RESULT is empty. */
5355 static void
5356 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5357 const lookup_name_info &lookup_name,
5358 const struct block *block, domain_search_flags domain)
5360 while (block != NULL)
5362 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5364 /* If we found a non-function match, assume that's the one. We
5365 only check this when finding a function boundary, so that we
5366 can accumulate all results from intervening blocks first. */
5367 if (block->function () != nullptr && is_nonfunction (result))
5368 return;
5370 block = block->superblock ();
5374 /* An object of this type is used as the callback argument when
5375 calling the map_matching_symbols method. */
5377 struct match_data
5379 explicit match_data (std::vector<struct block_symbol> *rp)
5380 : resultp (rp)
5383 DISABLE_COPY_AND_ASSIGN (match_data);
5385 bool operator() (struct block_symbol *bsym);
5387 struct objfile *objfile = nullptr;
5388 std::vector<struct block_symbol> *resultp;
5389 struct symbol *arg_sym = nullptr;
5390 bool found_sym = false;
5393 /* A callback for add_nonlocal_symbols that adds symbol, found in
5394 BSYM, to a list of symbols. */
5396 bool
5397 match_data::operator() (struct block_symbol *bsym)
5399 const struct block *block = bsym->block;
5400 struct symbol *sym = bsym->symbol;
5402 if (sym == NULL)
5404 if (!found_sym && arg_sym != NULL)
5405 add_defn_to_vec (*resultp, arg_sym, block);
5406 found_sym = false;
5407 arg_sym = NULL;
5409 else
5411 if (sym->aclass () == LOC_UNRESOLVED)
5412 return true;
5413 else if (sym->is_argument ())
5414 arg_sym = sym;
5415 else
5417 found_sym = true;
5418 add_defn_to_vec (*resultp, sym, block);
5421 return true;
5424 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5425 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5426 symbols to RESULT. Return whether we found such symbols. */
5428 static int
5429 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5430 const struct block *block,
5431 const lookup_name_info &lookup_name,
5432 domain_search_flags domain)
5434 struct using_direct *renaming;
5435 int defns_mark = result.size ();
5437 symbol_name_matcher_ftype *name_match
5438 = ada_get_symbol_name_matcher (lookup_name);
5440 for (renaming = block->get_using ();
5441 renaming != NULL;
5442 renaming = renaming->next)
5444 const char *r_name;
5446 /* Avoid infinite recursions: skip this renaming if we are actually
5447 already traversing it.
5449 Currently, symbol lookup in Ada don't use the namespace machinery from
5450 C++/Fortran support: skip namespace imports that use them. */
5451 if (renaming->searched
5452 || (renaming->import_src != NULL
5453 && renaming->import_src[0] != '\0')
5454 || (renaming->import_dest != NULL
5455 && renaming->import_dest[0] != '\0'))
5456 continue;
5457 renaming->searched = 1;
5459 /* TODO: here, we perform another name-based symbol lookup, which can
5460 pull its own multiple overloads. In theory, we should be able to do
5461 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5462 not a simple name. But in order to do this, we would need to enhance
5463 the DWARF reader to associate a symbol to this renaming, instead of a
5464 name. So, for now, we do something simpler: re-use the C++/Fortran
5465 namespace machinery. */
5466 r_name = (renaming->alias != NULL
5467 ? renaming->alias
5468 : renaming->declaration);
5469 if (name_match (r_name, lookup_name, NULL))
5471 lookup_name_info decl_lookup_name (renaming->declaration,
5472 lookup_name.match_type ());
5473 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5474 1, NULL);
5476 renaming->searched = 0;
5478 return result.size () != defns_mark;
5481 /* Convenience function to get at the Ada encoded lookup name for
5482 LOOKUP_NAME, as a C string. */
5484 static const char *
5485 ada_lookup_name (const lookup_name_info &lookup_name)
5487 return lookup_name.ada ().lookup_name ().c_str ();
5490 /* A helper for add_nonlocal_symbols. Expand all necessary symtabs
5491 for OBJFILE, then walk the objfile's symtabs and update the
5492 results. */
5494 static void
5495 map_matching_symbols (struct objfile *objfile,
5496 const lookup_name_info &lookup_name,
5497 domain_search_flags domain,
5498 int global,
5499 match_data &data)
5501 data.objfile = objfile;
5502 objfile->expand_symtabs_matching (nullptr, &lookup_name,
5503 nullptr, nullptr,
5504 global
5505 ? SEARCH_GLOBAL_BLOCK
5506 : SEARCH_STATIC_BLOCK,
5507 domain);
5509 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5510 for (compunit_symtab *symtab : objfile->compunits ())
5512 const struct block *block
5513 = symtab->blockvector ()->block (block_kind);
5514 if (!iterate_over_symbols_terminated (block, lookup_name,
5515 domain, data))
5516 break;
5520 /* Add to RESULT all non-local symbols whose name and domain match
5521 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5522 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5523 symbols otherwise. */
5525 static void
5526 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5527 const lookup_name_info &lookup_name,
5528 domain_search_flags domain, int global)
5530 struct match_data data (&result);
5532 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5534 for (objfile *objfile : current_program_space->objfiles ())
5536 map_matching_symbols (objfile, lookup_name, domain, global, data);
5538 for (compunit_symtab *cu : objfile->compunits ())
5540 const struct block *global_block
5541 = cu->blockvector ()->global_block ();
5543 if (ada_add_block_renamings (result, global_block, lookup_name,
5544 domain))
5545 data.found_sym = true;
5549 if (result.empty () && global && !is_wild_match)
5551 const char *name = ada_lookup_name (lookup_name);
5552 std::string bracket_name = std::string ("<_ada_") + name + '>';
5553 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5555 for (objfile *objfile : current_program_space->objfiles ())
5556 map_matching_symbols (objfile, name1, domain, global, data);
5560 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5561 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5562 returning the number of matches. Add these to RESULT.
5564 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5565 symbol match within the nest of blocks whose innermost member is BLOCK,
5566 is the one match returned (no other matches in that or
5567 enclosing blocks is returned). If there are any matches in or
5568 surrounding BLOCK, then these alone are returned.
5570 Names prefixed with "standard__" are handled specially:
5571 "standard__" is first stripped off (by the lookup_name
5572 constructor), and only static and global symbols are searched.
5574 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5575 to lookup global symbols. */
5577 static void
5578 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5579 const struct block *block,
5580 const lookup_name_info &lookup_name,
5581 domain_search_flags domain,
5582 int full_search,
5583 int *made_global_lookup_p)
5585 struct symbol *sym;
5587 if (made_global_lookup_p)
5588 *made_global_lookup_p = 0;
5590 /* Special case: If the user specifies a symbol name inside package
5591 Standard, do a non-wild matching of the symbol name without
5592 the "standard__" prefix. This was primarily introduced in order
5593 to allow the user to specifically access the standard exceptions
5594 using, for instance, Standard.Constraint_Error when Constraint_Error
5595 is ambiguous (due to the user defining its own Constraint_Error
5596 entity inside its program). */
5597 if (lookup_name.ada ().standard_p ())
5598 block = NULL;
5600 /* Check the non-global symbols. If we have ANY match, then we're done. */
5602 if (block != NULL)
5604 if (full_search)
5605 ada_add_local_symbols (result, lookup_name, block, domain);
5606 else
5608 /* In the !full_search case we're are being called by
5609 iterate_over_symbols, and we don't want to search
5610 superblocks. */
5611 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5613 if (!result.empty () || !full_search)
5614 return;
5617 /* No non-global symbols found. Check our cache to see if we have
5618 already performed this search before. If we have, then return
5619 the same result. */
5621 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5622 domain, &sym, &block))
5624 if (sym != NULL)
5625 add_defn_to_vec (result, sym, block);
5626 return;
5629 if (made_global_lookup_p)
5630 *made_global_lookup_p = 1;
5632 /* Search symbols from all global blocks. */
5634 add_nonlocal_symbols (result, lookup_name, domain, 1);
5636 /* Now add symbols from all per-file blocks if we've gotten no hits
5637 (not strictly correct, but perhaps better than an error). */
5639 if (result.empty ())
5640 add_nonlocal_symbols (result, lookup_name, domain, 0);
5643 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5644 is non-zero, enclosing scope and in global scopes.
5646 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5647 blocks and symbol tables (if any) in which they were found.
5649 When full_search is non-zero, any non-function/non-enumeral
5650 symbol match within the nest of blocks whose innermost member is BLOCK,
5651 is the one match returned (no other matches in that or
5652 enclosing blocks is returned). If there are any matches in or
5653 surrounding BLOCK, then these alone are returned.
5655 Names prefixed with "standard__" are handled specially: "standard__"
5656 is first stripped off, and only static and global symbols are searched. */
5658 static std::vector<struct block_symbol>
5659 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5660 const struct block *block,
5661 domain_search_flags domain,
5662 int full_search)
5664 int syms_from_global_search;
5665 std::vector<struct block_symbol> results;
5667 ada_add_all_symbols (results, block, lookup_name,
5668 domain, full_search, &syms_from_global_search);
5670 remove_extra_symbols (results);
5672 if (results.empty () && full_search && syms_from_global_search)
5673 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5675 if (results.size () == 1 && full_search && syms_from_global_search)
5676 cache_symbol (ada_lookup_name (lookup_name), domain,
5677 results[0].symbol, results[0].block);
5679 remove_irrelevant_renamings (&results, block);
5680 return results;
5683 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5684 in global scopes, returning (SYM,BLOCK) tuples.
5686 See ada_lookup_symbol_list_worker for further details. */
5688 std::vector<struct block_symbol>
5689 ada_lookup_symbol_list (const char *name, const struct block *block,
5690 domain_search_flags domain)
5692 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5693 lookup_name_info lookup_name (name, name_match_type);
5695 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5698 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5699 to 1, but choosing the first symbol found if there are multiple
5700 choices. */
5702 block_symbol
5703 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5704 domain_search_flags domain)
5706 /* Since we already have an encoded name, wrap it in '<>' to force a
5707 verbatim match. Otherwise, if the name happens to not look like
5708 an encoded name (because it doesn't include a "__"),
5709 ada_lookup_name_info would re-encode/fold it again, and that
5710 would e.g., incorrectly lowercase object renaming names like
5711 "R28b" -> "r28b". */
5712 std::string verbatim = add_angle_brackets (name);
5713 return ada_lookup_symbol (verbatim.c_str (), block, domain);
5716 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5717 scope and in global scopes, or NULL if none. NAME is folded and
5718 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5719 choosing the first symbol if there are multiple choices. */
5721 struct block_symbol
5722 ada_lookup_symbol (const char *name, const struct block *block0,
5723 domain_search_flags domain)
5725 std::vector<struct block_symbol> candidates
5726 = ada_lookup_symbol_list (name, block0, domain);
5728 if (candidates.empty ())
5729 return {};
5731 return candidates[0];
5735 /* True iff STR is a possible encoded suffix of a normal Ada name
5736 that is to be ignored for matching purposes. Suffixes of parallel
5737 names (e.g., XVE) are not included here. Currently, the possible suffixes
5738 are given by any of the regular expressions:
5740 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5741 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5742 TKB [subprogram suffix for task bodies]
5743 _E[0-9]+[bs]$ [protected object entry suffixes]
5744 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5746 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5747 match is performed. This sequence is used to differentiate homonyms,
5748 is an optional part of a valid name suffix. */
5750 static int
5751 is_name_suffix (const char *str)
5753 int k;
5754 const char *matching;
5755 const int len = strlen (str);
5757 /* Skip optional leading __[0-9]+. */
5759 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5761 str += 3;
5762 while (isdigit (str[0]))
5763 str += 1;
5766 /* [.$][0-9]+ */
5768 if (str[0] == '.' || str[0] == '$')
5770 matching = str + 1;
5771 while (isdigit (matching[0]))
5772 matching += 1;
5773 if (matching[0] == '\0')
5774 return 1;
5777 /* ___[0-9]+ */
5779 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5781 matching = str + 3;
5782 while (isdigit (matching[0]))
5783 matching += 1;
5784 if (matching[0] == '\0')
5785 return 1;
5788 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5790 if (strcmp (str, "TKB") == 0)
5791 return 1;
5793 #if 0
5794 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5795 with a N at the end. Unfortunately, the compiler uses the same
5796 convention for other internal types it creates. So treating
5797 all entity names that end with an "N" as a name suffix causes
5798 some regressions. For instance, consider the case of an enumerated
5799 type. To support the 'Image attribute, it creates an array whose
5800 name ends with N.
5801 Having a single character like this as a suffix carrying some
5802 information is a bit risky. Perhaps we should change the encoding
5803 to be something like "_N" instead. In the meantime, do not do
5804 the following check. */
5805 /* Protected Object Subprograms */
5806 if (len == 1 && str [0] == 'N')
5807 return 1;
5808 #endif
5810 /* _E[0-9]+[bs]$ */
5811 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5813 matching = str + 3;
5814 while (isdigit (matching[0]))
5815 matching += 1;
5816 if ((matching[0] == 'b' || matching[0] == 's')
5817 && matching [1] == '\0')
5818 return 1;
5821 /* ??? We should not modify STR directly, as we are doing below. This
5822 is fine in this case, but may become problematic later if we find
5823 that this alternative did not work, and want to try matching
5824 another one from the beginning of STR. Since we modified it, we
5825 won't be able to find the beginning of the string anymore! */
5826 if (str[0] == 'X')
5828 str += 1;
5829 while (str[0] != '_' && str[0] != '\0')
5831 if (str[0] != 'n' && str[0] != 'b')
5832 return 0;
5833 str += 1;
5837 if (str[0] == '\000')
5838 return 1;
5840 if (str[0] == '_')
5842 if (str[1] != '_' || str[2] == '\000')
5843 return 0;
5844 if (str[2] == '_')
5846 if (strcmp (str + 3, "JM") == 0)
5847 return 1;
5848 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5849 the LJM suffix in favor of the JM one. But we will
5850 still accept LJM as a valid suffix for a reasonable
5851 amount of time, just to allow ourselves to debug programs
5852 compiled using an older version of GNAT. */
5853 if (strcmp (str + 3, "LJM") == 0)
5854 return 1;
5855 if (str[3] != 'X')
5856 return 0;
5857 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5858 || str[4] == 'U' || str[4] == 'P')
5859 return 1;
5860 if (str[4] == 'R' && str[5] != 'T')
5861 return 1;
5862 return 0;
5864 if (!isdigit (str[2]))
5865 return 0;
5866 for (k = 3; str[k] != '\0'; k += 1)
5867 if (!isdigit (str[k]) && str[k] != '_')
5868 return 0;
5869 return 1;
5871 if (str[0] == '$' && isdigit (str[1]))
5873 for (k = 2; str[k] != '\0'; k += 1)
5874 if (!isdigit (str[k]) && str[k] != '_')
5875 return 0;
5876 return 1;
5878 return 0;
5881 /* Return non-zero if the string starting at NAME and ending before
5882 NAME_END contains no capital letters. */
5884 static int
5885 is_valid_name_for_wild_match (const char *name0)
5887 std::string decoded_name = ada_decode (name0);
5888 int i;
5890 /* If the decoded name starts with an angle bracket, it means that
5891 NAME0 does not follow the GNAT encoding format. It should then
5892 not be allowed as a possible wild match. */
5893 if (decoded_name[0] == '<')
5894 return 0;
5896 for (i=0; decoded_name[i] != '\0'; i++)
5897 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5898 return 0;
5900 return 1;
5903 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5904 character which could start a simple name. Assumes that *NAMEP points
5905 somewhere inside the string beginning at NAME0. */
5907 static int
5908 advance_wild_match (const char **namep, const char *name0, char target0)
5910 const char *name = *namep;
5912 while (1)
5914 char t0, t1;
5916 t0 = *name;
5917 if (t0 == '_')
5919 t1 = name[1];
5920 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5922 name += 1;
5923 if (name == name0 + 5 && startswith (name0, "_ada"))
5924 break;
5925 else
5926 name += 1;
5928 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5929 || name[2] == target0))
5931 name += 2;
5932 break;
5934 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5936 /* Names like "pkg__B_N__name", where N is a number, are
5937 block-local. We can handle these by simply skipping
5938 the "B_" here. */
5939 name += 4;
5941 else
5942 return 0;
5944 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5945 name += 1;
5946 else
5947 return 0;
5950 *namep = name;
5951 return 1;
5954 /* Return true iff NAME encodes a name of the form prefix.PATN.
5955 Ignores any informational suffixes of NAME (i.e., for which
5956 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5957 simple name. */
5959 static bool
5960 wild_match (const char *name, const char *patn)
5962 const char *p;
5963 const char *name0 = name;
5965 if (startswith (name, "___ghost_"))
5966 name += 9;
5968 while (1)
5970 const char *match = name;
5972 if (*name == *patn)
5974 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5975 if (*p != *name)
5976 break;
5977 if (*p == '\0' && is_name_suffix (name))
5978 return match == name0 || is_valid_name_for_wild_match (name0);
5980 if (name[-1] == '_')
5981 name -= 1;
5983 if (!advance_wild_match (&name, name0, *patn))
5984 return false;
5988 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
5989 necessary). OBJFILE is the section containing BLOCK. */
5991 static void
5992 ada_add_block_symbols (std::vector<struct block_symbol> &result,
5993 const struct block *block,
5994 const lookup_name_info &lookup_name,
5995 domain_search_flags domain, struct objfile *objfile)
5997 /* A matching argument symbol, if any. */
5998 struct symbol *arg_sym;
5999 /* Set true when we find a matching non-argument symbol. */
6000 bool found_sym;
6002 arg_sym = NULL;
6003 found_sym = false;
6004 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
6006 if (sym->matches (domain))
6008 if (sym->aclass () != LOC_UNRESOLVED)
6010 if (sym->is_argument ())
6011 arg_sym = sym;
6012 else
6014 found_sym = true;
6015 add_defn_to_vec (result, sym, block);
6021 /* Handle renamings. */
6023 if (ada_add_block_renamings (result, block, lookup_name, domain))
6024 found_sym = true;
6026 if (!found_sym && arg_sym != NULL)
6028 add_defn_to_vec (result, arg_sym, block);
6031 if (!lookup_name.ada ().wild_match_p ())
6033 arg_sym = NULL;
6034 found_sym = false;
6035 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6036 const char *name = ada_lookup_name.c_str ();
6037 size_t name_len = ada_lookup_name.size ();
6039 for (struct symbol *sym : block_iterator_range (block))
6041 if (sym->matches (domain))
6043 int cmp;
6045 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6046 if (cmp == 0)
6048 cmp = !startswith (sym->linkage_name (), "_ada_");
6049 if (cmp == 0)
6050 cmp = strncmp (name, sym->linkage_name () + 5,
6051 name_len);
6054 if (cmp == 0
6055 && is_name_suffix (sym->linkage_name () + name_len + 5))
6057 if (sym->aclass () != LOC_UNRESOLVED)
6059 if (sym->is_argument ())
6060 arg_sym = sym;
6061 else
6063 found_sym = true;
6064 add_defn_to_vec (result, sym, block);
6071 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6072 They aren't parameters, right? */
6073 if (!found_sym && arg_sym != NULL)
6075 add_defn_to_vec (result, arg_sym, block);
6081 /* Symbol Completion */
6083 /* See symtab.h. */
6085 bool
6086 ada_lookup_name_info::matches
6087 (const char *sym_name,
6088 symbol_name_match_type match_type,
6089 completion_match_result *comp_match_res) const
6091 bool match = false;
6092 const char *text = m_encoded_name.c_str ();
6093 size_t text_len = m_encoded_name.size ();
6095 /* First, test against the fully qualified name of the symbol. */
6097 if (strncmp (sym_name, text, text_len) == 0)
6098 match = true;
6100 std::string decoded_name = ada_decode (sym_name);
6101 if (match && !m_encoded_p)
6103 /* One needed check before declaring a positive match is to verify
6104 that iff we are doing a verbatim match, the decoded version
6105 of the symbol name starts with '<'. Otherwise, this symbol name
6106 is not a suitable completion. */
6108 bool has_angle_bracket = (decoded_name[0] == '<');
6109 match = (has_angle_bracket == m_verbatim_p);
6112 if (match && !m_verbatim_p)
6114 /* When doing non-verbatim match, another check that needs to
6115 be done is to verify that the potentially matching symbol name
6116 does not include capital letters, because the ada-mode would
6117 not be able to understand these symbol names without the
6118 angle bracket notation. */
6119 const char *tmp;
6121 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6122 if (*tmp != '\0')
6123 match = false;
6126 /* Second: Try wild matching... */
6128 if (!match && m_wild_match_p)
6130 /* Since we are doing wild matching, this means that TEXT
6131 may represent an unqualified symbol name. We therefore must
6132 also compare TEXT against the unqualified name of the symbol. */
6133 sym_name = ada_unqualified_name (decoded_name.c_str ());
6135 if (strncmp (sym_name, text, text_len) == 0)
6136 match = true;
6139 /* Finally: If we found a match, prepare the result to return. */
6141 if (!match)
6142 return false;
6144 if (comp_match_res != NULL)
6146 std::string &match_str = comp_match_res->match.storage ();
6148 if (!m_encoded_p)
6149 match_str = ada_decode (sym_name);
6150 else
6152 if (m_verbatim_p)
6153 match_str = add_angle_brackets (sym_name);
6154 else
6155 match_str = sym_name;
6159 comp_match_res->set_match (match_str.c_str ());
6162 return true;
6165 /* Field Access */
6167 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6168 for tagged types. */
6170 static int
6171 ada_is_dispatch_table_ptr_type (struct type *type)
6173 const char *name;
6175 if (type->code () != TYPE_CODE_PTR)
6176 return 0;
6178 name = type->target_type ()->name ();
6179 if (name == NULL)
6180 return 0;
6182 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6185 /* Return non-zero if TYPE is an interface tag. */
6187 static int
6188 ada_is_interface_tag (struct type *type)
6190 const char *name = type->name ();
6192 if (name == NULL)
6193 return 0;
6195 return (strcmp (name, "ada__tags__interface_tag") == 0);
6198 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6199 to be invisible to users. */
6202 ada_is_ignored_field (struct type *type, int field_num)
6204 if (field_num < 0 || field_num > type->num_fields ())
6205 return 1;
6207 /* Check the name of that field. */
6209 const char *name = type->field (field_num).name ();
6211 /* Anonymous field names should not be printed.
6212 brobecker/2007-02-20: I don't think this can actually happen
6213 but we don't want to print the value of anonymous fields anyway. */
6214 if (name == NULL)
6215 return 1;
6217 /* Normally, fields whose name start with an underscore ("_")
6218 are fields that have been internally generated by the compiler,
6219 and thus should not be printed. The "_parent" field is special,
6220 however: This is a field internally generated by the compiler
6221 for tagged types, and it contains the components inherited from
6222 the parent type. This field should not be printed as is, but
6223 should not be ignored either. */
6224 if (name[0] == '_' && !startswith (name, "_parent"))
6225 return 1;
6227 /* The compiler doesn't document this, but sometimes it emits
6228 a field whose name starts with a capital letter, like 'V148s'.
6229 These aren't marked as artificial in any way, but we know they
6230 should be ignored. However, wrapper fields should not be
6231 ignored. */
6232 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6234 /* Wrapper field. */
6236 else if (isupper (name[0]))
6237 return 1;
6240 /* If this is the dispatch table of a tagged type or an interface tag,
6241 then ignore. */
6242 if (ada_is_tagged_type (type, 1)
6243 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6244 || ada_is_interface_tag (type->field (field_num).type ())))
6245 return 1;
6247 /* Not a special field, so it should not be ignored. */
6248 return 0;
6251 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6252 pointer or reference type whose ultimate target has a tag field. */
6255 ada_is_tagged_type (struct type *type, int refok)
6257 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6260 /* True iff TYPE represents the type of X'Tag */
6263 ada_is_tag_type (struct type *type)
6265 type = ada_check_typedef (type);
6267 if (type == NULL || type->code () != TYPE_CODE_PTR)
6268 return 0;
6269 else
6271 const char *name = ada_type_name (type->target_type ());
6273 return (name != NULL
6274 && strcmp (name, "ada__tags__dispatch_table") == 0);
6278 /* The type of the tag on VAL. */
6280 static struct type *
6281 ada_tag_type (struct value *val)
6283 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6286 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6287 retired at Ada 05). */
6289 static int
6290 is_ada95_tag (struct value *tag)
6292 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6295 /* The value of the tag on VAL. */
6297 static struct value *
6298 ada_value_tag (struct value *val)
6300 return ada_value_struct_elt (val, "_tag", 0);
6303 /* The value of the tag on the object of type TYPE whose contents are
6304 saved at VALADDR, if it is non-null, or is at memory address
6305 ADDRESS. */
6307 static struct value *
6308 value_tag_from_contents_and_address (struct type *type,
6309 const gdb_byte *valaddr,
6310 CORE_ADDR address)
6312 int tag_byte_offset;
6313 struct type *tag_type;
6315 gdb::array_view<const gdb_byte> contents;
6316 if (valaddr != nullptr)
6317 contents = gdb::make_array_view (valaddr, type->length ());
6318 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6319 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6320 NULL, NULL, NULL))
6322 const gdb_byte *valaddr1 = ((valaddr == NULL)
6323 ? NULL
6324 : valaddr + tag_byte_offset);
6325 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6327 return value_from_contents_and_address (tag_type, valaddr1, address1);
6329 return NULL;
6332 static struct type *
6333 type_from_tag (struct value *tag)
6335 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6337 if (type_name != NULL)
6338 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6339 return NULL;
6342 /* Given a value OBJ of a tagged type, return a value of this
6343 type at the base address of the object. The base address, as
6344 defined in Ada.Tags, it is the address of the primary tag of
6345 the object, and therefore where the field values of its full
6346 view can be fetched. */
6348 struct value *
6349 ada_tag_value_at_base_address (struct value *obj)
6351 struct value *val;
6352 LONGEST offset_to_top = 0;
6353 struct type *ptr_type, *obj_type;
6354 struct value *tag;
6355 CORE_ADDR base_address;
6357 obj_type = obj->type ();
6359 /* It is the responsibility of the caller to deref pointers. */
6361 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6362 return obj;
6364 tag = ada_value_tag (obj);
6365 if (!tag)
6366 return obj;
6368 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6370 if (is_ada95_tag (tag))
6371 return obj;
6373 struct type *offset_type
6374 = language_lookup_primitive_type (language_def (language_ada),
6375 current_inferior ()->arch (),
6376 "storage_offset");
6377 ptr_type = lookup_pointer_type (offset_type);
6378 val = value_cast (ptr_type, tag);
6379 if (!val)
6380 return obj;
6382 /* It is perfectly possible that an exception be raised while
6383 trying to determine the base address, just like for the tag;
6384 see ada_tag_name for more details. We do not print the error
6385 message for the same reason. */
6389 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6392 catch (const gdb_exception_error &e)
6394 return obj;
6397 /* If offset is null, nothing to do. */
6399 if (offset_to_top == 0)
6400 return obj;
6402 /* -1 is a special case in Ada.Tags; however, what should be done
6403 is not quite clear from the documentation. So do nothing for
6404 now. */
6406 if (offset_to_top == -1)
6407 return obj;
6409 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6410 top is used. In this situation the offset is stored just after
6411 the tag, in the object itself. */
6412 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6413 if (offset_to_top == last)
6415 struct value *tem = value_addr (tag);
6416 tem = value_ptradd (tem, 1);
6417 tem = value_cast (ptr_type, tem);
6418 offset_to_top = value_as_long (value_ind (tem));
6421 if (offset_to_top > 0)
6423 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6424 from the base address. This was however incompatible with
6425 C++ dispatch table: C++ uses a *negative* value to *add*
6426 to the base address. Ada's convention has therefore been
6427 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6428 use the same convention. Here, we support both cases by
6429 checking the sign of OFFSET_TO_TOP. */
6430 offset_to_top = -offset_to_top;
6433 base_address = obj->address () + offset_to_top;
6434 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6436 /* Make sure that we have a proper tag at the new address.
6437 Otherwise, offset_to_top is bogus (which can happen when
6438 the object is not initialized yet). */
6440 if (!tag)
6441 return obj;
6443 obj_type = type_from_tag (tag);
6445 if (!obj_type)
6446 return obj;
6448 return value_from_contents_and_address (obj_type, NULL, base_address);
6451 /* Return the "ada__tags__type_specific_data" type. */
6453 static struct type *
6454 ada_get_tsd_type (struct inferior *inf)
6456 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6458 if (data->tsd_type == 0)
6459 data->tsd_type
6460 = lookup_transparent_type ("<ada__tags__type_specific_data>",
6461 SEARCH_TYPE_DOMAIN);
6462 return data->tsd_type;
6465 /* Return the TSD (type-specific data) associated to the given TAG.
6466 TAG is assumed to be the tag of a tagged-type entity.
6468 May return NULL if we are unable to get the TSD. */
6470 static struct value *
6471 ada_get_tsd_from_tag (struct value *tag)
6473 struct value *val;
6474 struct type *type;
6476 /* First option: The TSD is simply stored as a field of our TAG.
6477 Only older versions of GNAT would use this format, but we have
6478 to test it first, because there are no visible markers for
6479 the current approach except the absence of that field. */
6481 val = ada_value_struct_elt (tag, "tsd", 1);
6482 if (val)
6483 return val;
6485 /* Try the second representation for the dispatch table (in which
6486 there is no explicit 'tsd' field in the referent of the tag pointer,
6487 and instead the tsd pointer is stored just before the dispatch
6488 table. */
6490 type = ada_get_tsd_type (current_inferior());
6491 if (type == NULL)
6492 return NULL;
6493 type = lookup_pointer_type (lookup_pointer_type (type));
6494 val = value_cast (type, tag);
6495 if (val == NULL)
6496 return NULL;
6497 return value_ind (value_ptradd (val, -1));
6500 /* Given the TSD of a tag (type-specific data), return a string
6501 containing the name of the associated type.
6503 May return NULL if we are unable to determine the tag name. */
6505 static gdb::unique_xmalloc_ptr<char>
6506 ada_tag_name_from_tsd (struct value *tsd)
6508 struct value *val;
6510 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6511 if (val == NULL)
6512 return NULL;
6513 gdb::unique_xmalloc_ptr<char> buffer
6514 = target_read_string (value_as_address (val), INT_MAX);
6515 if (buffer == nullptr)
6516 return nullptr;
6520 /* Let this throw an exception on error. If the data is
6521 uninitialized, we'd rather not have the user see a
6522 warning. */
6523 const char *folded = ada_fold_name (buffer.get (), true);
6524 return make_unique_xstrdup (folded);
6526 catch (const gdb_exception &)
6528 return nullptr;
6532 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6533 a C string.
6535 Return NULL if the TAG is not an Ada tag, or if we were unable to
6536 determine the name of that tag. */
6538 gdb::unique_xmalloc_ptr<char>
6539 ada_tag_name (struct value *tag)
6541 gdb::unique_xmalloc_ptr<char> name;
6543 if (!ada_is_tag_type (tag->type ()))
6544 return NULL;
6546 /* It is perfectly possible that an exception be raised while trying
6547 to determine the TAG's name, even under normal circumstances:
6548 The associated variable may be uninitialized or corrupted, for
6549 instance. We do not let any exception propagate past this point.
6550 instead we return NULL.
6552 We also do not print the error message either (which often is very
6553 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6554 the caller print a more meaningful message if necessary. */
6557 struct value *tsd = ada_get_tsd_from_tag (tag);
6559 if (tsd != NULL)
6560 name = ada_tag_name_from_tsd (tsd);
6562 catch (const gdb_exception_error &e)
6566 return name;
6569 /* The parent type of TYPE, or NULL if none. */
6571 struct type *
6572 ada_parent_type (struct type *type)
6574 int i;
6576 type = ada_check_typedef (type);
6578 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6579 return NULL;
6581 for (i = 0; i < type->num_fields (); i += 1)
6582 if (ada_is_parent_field (type, i))
6584 struct type *parent_type = type->field (i).type ();
6586 /* If the _parent field is a pointer, then dereference it. */
6587 if (parent_type->code () == TYPE_CODE_PTR)
6588 parent_type = parent_type->target_type ();
6589 /* If there is a parallel XVS type, get the actual base type. */
6590 parent_type = ada_get_base_type (parent_type);
6592 return ada_check_typedef (parent_type);
6595 return NULL;
6598 /* True iff field number FIELD_NUM of structure type TYPE contains the
6599 parent-type (inherited) fields of a derived type. Assumes TYPE is
6600 a structure type with at least FIELD_NUM+1 fields. */
6603 ada_is_parent_field (struct type *type, int field_num)
6605 const char *name = ada_check_typedef (type)->field (field_num).name ();
6607 return (name != NULL
6608 && (startswith (name, "PARENT")
6609 || startswith (name, "_parent")));
6612 /* True iff field number FIELD_NUM of structure type TYPE is a
6613 transparent wrapper field (which should be silently traversed when doing
6614 field selection and flattened when printing). Assumes TYPE is a
6615 structure type with at least FIELD_NUM+1 fields. Such fields are always
6616 structures. */
6619 ada_is_wrapper_field (struct type *type, int field_num)
6621 const char *name = type->field (field_num).name ();
6623 if (name != NULL && strcmp (name, "RETVAL") == 0)
6625 /* This happens in functions with "out" or "in out" parameters
6626 which are passed by copy. For such functions, GNAT describes
6627 the function's return type as being a struct where the return
6628 value is in a field called RETVAL, and where the other "out"
6629 or "in out" parameters are fields of that struct. This is not
6630 a wrapper. */
6631 return 0;
6634 return (name != NULL
6635 && (startswith (name, "PARENT")
6636 || strcmp (name, "REP") == 0
6637 || startswith (name, "_parent")
6638 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6641 /* True iff field number FIELD_NUM of structure or union type TYPE
6642 is a variant wrapper. Assumes TYPE is a structure type with at least
6643 FIELD_NUM+1 fields. */
6646 ada_is_variant_part (struct type *type, int field_num)
6648 /* Only Ada types are eligible. */
6649 if (!ADA_TYPE_P (type))
6650 return 0;
6652 struct type *field_type = type->field (field_num).type ();
6654 return (field_type->code () == TYPE_CODE_UNION
6655 || (is_dynamic_field (type, field_num)
6656 && (field_type->target_type ()->code ()
6657 == TYPE_CODE_UNION)));
6660 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6661 whose discriminants are contained in the record type OUTER_TYPE,
6662 returns the type of the controlling discriminant for the variant.
6663 May return NULL if the type could not be found. */
6665 struct type *
6666 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6668 const char *name = ada_variant_discrim_name (var_type);
6670 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6673 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6674 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6675 represents a 'when others' clause; otherwise 0. */
6677 static int
6678 ada_is_others_clause (struct type *type, int field_num)
6680 const char *name = type->field (field_num).name ();
6682 return (name != NULL && name[0] == 'O');
6685 /* Assuming that TYPE0 is the type of the variant part of a record,
6686 returns the name of the discriminant controlling the variant.
6687 The value is valid until the next call to ada_variant_discrim_name. */
6689 const char *
6690 ada_variant_discrim_name (struct type *type0)
6692 static std::string result;
6693 struct type *type;
6694 const char *name;
6695 const char *discrim_end;
6696 const char *discrim_start;
6698 if (type0->code () == TYPE_CODE_PTR)
6699 type = type0->target_type ();
6700 else
6701 type = type0;
6703 name = ada_type_name (type);
6705 if (name == NULL || name[0] == '\000')
6706 return "";
6708 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6709 discrim_end -= 1)
6711 if (startswith (discrim_end, "___XVN"))
6712 break;
6714 if (discrim_end == name)
6715 return "";
6717 for (discrim_start = discrim_end; discrim_start != name + 3;
6718 discrim_start -= 1)
6720 if (discrim_start == name + 1)
6721 return "";
6722 if ((discrim_start > name + 3
6723 && startswith (discrim_start - 3, "___"))
6724 || discrim_start[-1] == '.')
6725 break;
6728 result = std::string (discrim_start, discrim_end - discrim_start);
6729 return result.c_str ();
6732 /* Scan STR for a subtype-encoded number, beginning at position K.
6733 Put the position of the character just past the number scanned in
6734 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6735 Return 1 if there was a valid number at the given position, and 0
6736 otherwise. A "subtype-encoded" number consists of the absolute value
6737 in decimal, followed by the letter 'm' to indicate a negative number.
6738 Assumes 0m does not occur. */
6741 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6743 ULONGEST RU;
6745 if (!isdigit (str[k]))
6746 return 0;
6748 /* Do it the hard way so as not to make any assumption about
6749 the relationship of unsigned long (%lu scan format code) and
6750 LONGEST. */
6751 RU = 0;
6752 while (isdigit (str[k]))
6754 RU = RU * 10 + (str[k] - '0');
6755 k += 1;
6758 if (str[k] == 'm')
6760 if (R != NULL)
6761 *R = (-(LONGEST) (RU - 1)) - 1;
6762 k += 1;
6764 else if (R != NULL)
6765 *R = (LONGEST) RU;
6767 /* NOTE on the above: Technically, C does not say what the results of
6768 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6769 number representable as a LONGEST (although either would probably work
6770 in most implementations). When RU>0, the locution in the then branch
6771 above is always equivalent to the negative of RU. */
6773 if (new_k != NULL)
6774 *new_k = k;
6775 return 1;
6778 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6779 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6780 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6782 static int
6783 ada_in_variant (LONGEST val, struct type *type, int field_num)
6785 const char *name = type->field (field_num).name ();
6786 int p;
6788 p = 0;
6789 while (1)
6791 switch (name[p])
6793 case '\0':
6794 return 0;
6795 case 'S':
6797 LONGEST W;
6799 if (!ada_scan_number (name, p + 1, &W, &p))
6800 return 0;
6801 if (val == W)
6802 return 1;
6803 break;
6805 case 'R':
6807 LONGEST L, U;
6809 if (!ada_scan_number (name, p + 1, &L, &p)
6810 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6811 return 0;
6812 if (val >= L && val <= U)
6813 return 1;
6814 break;
6816 case 'O':
6817 return 1;
6818 default:
6819 return 0;
6824 /* FIXME: Lots of redundancy below. Try to consolidate. */
6826 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6827 ARG_TYPE, extract and return the value of one of its (non-static)
6828 fields. FIELDNO says which field. Differs from value_primitive_field
6829 only in that it can handle packed values of arbitrary type. */
6831 struct value *
6832 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6833 struct type *arg_type)
6835 struct type *type;
6837 arg_type = ada_check_typedef (arg_type);
6838 type = arg_type->field (fieldno).type ();
6840 /* Handle packed fields. It might be that the field is not packed
6841 relative to its containing structure, but the structure itself is
6842 packed; in this case we must take the bit-field path. */
6843 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
6845 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6846 int bit_size = arg_type->field (fieldno).bitsize ();
6848 return ada_value_primitive_packed_val (arg1,
6849 arg1->contents ().data (),
6850 offset + bit_pos / 8,
6851 bit_pos % 8, bit_size, type);
6853 else
6854 return arg1->primitive_field (offset, fieldno, arg_type);
6857 /* Find field with name NAME in object of type TYPE. If found,
6858 set the following for each argument that is non-null:
6859 - *FIELD_TYPE_P to the field's type;
6860 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6861 an object of that type;
6862 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6863 - *BIT_SIZE_P to its size in bits if the field is packed, and
6864 0 otherwise;
6865 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6866 fields up to but not including the desired field, or by the total
6867 number of fields if not found. A NULL value of NAME never
6868 matches; the function just counts visible fields in this case.
6870 Notice that we need to handle when a tagged record hierarchy
6871 has some components with the same name, like in this scenario:
6873 type Top_T is tagged record
6874 N : Integer := 1;
6875 U : Integer := 974;
6876 A : Integer := 48;
6877 end record;
6879 type Middle_T is new Top.Top_T with record
6880 N : Character := 'a';
6881 C : Integer := 3;
6882 end record;
6884 type Bottom_T is new Middle.Middle_T with record
6885 N : Float := 4.0;
6886 C : Character := '5';
6887 X : Integer := 6;
6888 A : Character := 'J';
6889 end record;
6891 Let's say we now have a variable declared and initialized as follow:
6893 TC : Top_A := new Bottom_T;
6895 And then we use this variable to call this function
6897 procedure Assign (Obj: in out Top_T; TV : Integer);
6899 as follow:
6901 Assign (Top_T (B), 12);
6903 Now, we're in the debugger, and we're inside that procedure
6904 then and we want to print the value of obj.c:
6906 Usually, the tagged record or one of the parent type owns the
6907 component to print and there's no issue but in this particular
6908 case, what does it mean to ask for Obj.C? Since the actual
6909 type for object is type Bottom_T, it could mean two things: type
6910 component C from the Middle_T view, but also component C from
6911 Bottom_T. So in that "undefined" case, when the component is
6912 not found in the non-resolved type (which includes all the
6913 components of the parent type), then resolve it and see if we
6914 get better luck once expanded.
6916 In the case of homonyms in the derived tagged type, we don't
6917 guaranty anything, and pick the one that's easiest for us
6918 to program.
6920 Returns 1 if found, 0 otherwise. */
6922 static int
6923 find_struct_field (const char *name, struct type *type, int offset,
6924 struct type **field_type_p,
6925 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6926 int *index_p)
6928 int i;
6929 int parent_offset = -1;
6931 type = ada_check_typedef (type);
6933 if (field_type_p != NULL)
6934 *field_type_p = NULL;
6935 if (byte_offset_p != NULL)
6936 *byte_offset_p = 0;
6937 if (bit_offset_p != NULL)
6938 *bit_offset_p = 0;
6939 if (bit_size_p != NULL)
6940 *bit_size_p = 0;
6942 for (i = 0; i < type->num_fields (); i += 1)
6944 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6945 type. However, we only need the values to be correct when
6946 the caller asks for them. */
6947 int bit_pos = 0, fld_offset = 0;
6948 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6950 bit_pos = type->field (i).loc_bitpos ();
6951 fld_offset = offset + bit_pos / 8;
6954 const char *t_field_name = type->field (i).name ();
6956 if (t_field_name == NULL)
6957 continue;
6959 else if (ada_is_parent_field (type, i))
6961 /* This is a field pointing us to the parent type of a tagged
6962 type. As hinted in this function's documentation, we give
6963 preference to fields in the current record first, so what
6964 we do here is just record the index of this field before
6965 we skip it. If it turns out we couldn't find our field
6966 in the current record, then we'll get back to it and search
6967 inside it whether the field might exist in the parent. */
6969 parent_offset = i;
6970 continue;
6973 else if (name != NULL && field_name_match (t_field_name, name))
6975 int bit_size = type->field (i).bitsize ();
6977 if (field_type_p != NULL)
6978 *field_type_p = type->field (i).type ();
6979 if (byte_offset_p != NULL)
6980 *byte_offset_p = fld_offset;
6981 if (bit_offset_p != NULL)
6982 *bit_offset_p = bit_pos % 8;
6983 if (bit_size_p != NULL)
6984 *bit_size_p = bit_size;
6985 return 1;
6987 else if (ada_is_wrapper_field (type, i))
6989 if (find_struct_field (name, type->field (i).type (), fld_offset,
6990 field_type_p, byte_offset_p, bit_offset_p,
6991 bit_size_p, index_p))
6992 return 1;
6994 else if (ada_is_variant_part (type, i))
6996 /* PNH: Wait. Do we ever execute this section, or is ARG always of
6997 fixed type?? */
6998 int j;
6999 struct type *field_type
7000 = ada_check_typedef (type->field (i).type ());
7002 for (j = 0; j < field_type->num_fields (); j += 1)
7004 if (find_struct_field (name, field_type->field (j).type (),
7005 fld_offset
7006 + field_type->field (j).loc_bitpos () / 8,
7007 field_type_p, byte_offset_p,
7008 bit_offset_p, bit_size_p, index_p))
7009 return 1;
7012 else if (index_p != NULL)
7013 *index_p += 1;
7016 /* Field not found so far. If this is a tagged type which
7017 has a parent, try finding that field in the parent now. */
7019 if (parent_offset != -1)
7021 /* As above, only compute the offset when truly needed. */
7022 int fld_offset = offset;
7023 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7025 int bit_pos = type->field (parent_offset).loc_bitpos ();
7026 fld_offset += bit_pos / 8;
7029 if (find_struct_field (name, type->field (parent_offset).type (),
7030 fld_offset, field_type_p, byte_offset_p,
7031 bit_offset_p, bit_size_p, index_p))
7032 return 1;
7035 return 0;
7038 /* Number of user-visible fields in record type TYPE. */
7040 static int
7041 num_visible_fields (struct type *type)
7043 int n;
7045 n = 0;
7046 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7047 return n;
7050 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7051 and search in it assuming it has (class) type TYPE.
7052 If found, return value, else return NULL.
7054 Searches recursively through wrapper fields (e.g., '_parent').
7056 In the case of homonyms in the tagged types, please refer to the
7057 long explanation in find_struct_field's function documentation. */
7059 static struct value *
7060 ada_search_struct_field (const char *name, struct value *arg, int offset,
7061 struct type *type)
7063 int i;
7064 int parent_offset = -1;
7066 type = ada_check_typedef (type);
7067 for (i = 0; i < type->num_fields (); i += 1)
7069 const char *t_field_name = type->field (i).name ();
7071 if (t_field_name == NULL)
7072 continue;
7074 else if (ada_is_parent_field (type, i))
7076 /* This is a field pointing us to the parent type of a tagged
7077 type. As hinted in this function's documentation, we give
7078 preference to fields in the current record first, so what
7079 we do here is just record the index of this field before
7080 we skip it. If it turns out we couldn't find our field
7081 in the current record, then we'll get back to it and search
7082 inside it whether the field might exist in the parent. */
7084 parent_offset = i;
7085 continue;
7088 else if (field_name_match (t_field_name, name))
7089 return ada_value_primitive_field (arg, offset, i, type);
7091 else if (ada_is_wrapper_field (type, i))
7093 struct value *v = /* Do not let indent join lines here. */
7094 ada_search_struct_field (name, arg,
7095 offset + type->field (i).loc_bitpos () / 8,
7096 type->field (i).type ());
7098 if (v != NULL)
7099 return v;
7102 else if (ada_is_variant_part (type, i))
7104 /* PNH: Do we ever get here? See find_struct_field. */
7105 int j;
7106 struct type *field_type = ada_check_typedef (type->field (i).type ());
7107 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7109 for (j = 0; j < field_type->num_fields (); j += 1)
7111 struct value *v = ada_search_struct_field /* Force line
7112 break. */
7113 (name, arg,
7114 var_offset + field_type->field (j).loc_bitpos () / 8,
7115 field_type->field (j).type ());
7117 if (v != NULL)
7118 return v;
7123 /* Field not found so far. If this is a tagged type which
7124 has a parent, try finding that field in the parent now. */
7126 if (parent_offset != -1)
7128 struct value *v = ada_search_struct_field (
7129 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7130 type->field (parent_offset).type ());
7132 if (v != NULL)
7133 return v;
7136 return NULL;
7139 static struct value *ada_index_struct_field_1 (int *, struct value *,
7140 int, struct type *);
7143 /* Return field #INDEX in ARG, where the index is that returned by
7144 * find_struct_field through its INDEX_P argument. Adjust the address
7145 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7146 * If found, return value, else return NULL. */
7148 static struct value *
7149 ada_index_struct_field (int index, struct value *arg, int offset,
7150 struct type *type)
7152 return ada_index_struct_field_1 (&index, arg, offset, type);
7156 /* Auxiliary function for ada_index_struct_field. Like
7157 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7158 * *INDEX_P. */
7160 static struct value *
7161 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7162 struct type *type)
7164 int i;
7165 type = ada_check_typedef (type);
7167 for (i = 0; i < type->num_fields (); i += 1)
7169 if (type->field (i).name () == NULL)
7170 continue;
7171 else if (ada_is_wrapper_field (type, i))
7173 struct value *v = /* Do not let indent join lines here. */
7174 ada_index_struct_field_1 (index_p, arg,
7175 offset + type->field (i).loc_bitpos () / 8,
7176 type->field (i).type ());
7178 if (v != NULL)
7179 return v;
7182 else if (ada_is_variant_part (type, i))
7184 /* PNH: Do we ever get here? See ada_search_struct_field,
7185 find_struct_field. */
7186 error (_("Cannot assign this kind of variant record"));
7188 else if (*index_p == 0)
7189 return ada_value_primitive_field (arg, offset, i, type);
7190 else
7191 *index_p -= 1;
7193 return NULL;
7196 /* Return a string representation of type TYPE. */
7198 static std::string
7199 type_as_string (struct type *type)
7201 string_file tmp_stream;
7203 type_print (type, "", &tmp_stream, -1);
7205 return tmp_stream.release ();
7208 /* Given a type TYPE, look up the type of the component of type named NAME.
7210 Matches any field whose name has NAME as a prefix, possibly
7211 followed by "___".
7213 TYPE can be either a struct or union. If REFOK, TYPE may also
7214 be a (pointer or reference)+ to a struct or union, and the
7215 ultimate target type will be searched.
7217 Looks recursively into variant clauses and parent types.
7219 In the case of homonyms in the tagged types, please refer to the
7220 long explanation in find_struct_field's function documentation.
7222 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7223 TYPE is not a type of the right kind. */
7225 static struct type *
7226 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7227 int noerr)
7229 if (name == NULL)
7230 goto BadName;
7232 if (refok && type != NULL)
7233 while (1)
7235 type = ada_check_typedef (type);
7236 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7237 break;
7238 type = type->target_type ();
7241 if (type == NULL
7242 || (type->code () != TYPE_CODE_STRUCT
7243 && type->code () != TYPE_CODE_UNION))
7245 if (noerr)
7246 return NULL;
7248 error (_("Type %s is not a structure or union type"),
7249 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7252 type = to_static_fixed_type (type);
7254 struct type *result;
7255 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7256 nullptr);
7257 if (result != nullptr)
7258 return result;
7260 BadName:
7261 if (!noerr)
7263 const char *name_str = name != NULL ? name : _("<null>");
7265 error (_("Type %s has no component named %s"),
7266 type_as_string (type).c_str (), name_str);
7269 return NULL;
7272 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7273 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7274 represents an unchecked union (that is, the variant part of a
7275 record that is named in an Unchecked_Union pragma). */
7277 static int
7278 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7280 const char *discrim_name = ada_variant_discrim_name (var_type);
7282 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7286 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7287 within OUTER, determine which variant clause (field number in VAR_TYPE,
7288 numbering from 0) is applicable. Returns -1 if none are. */
7291 ada_which_variant_applies (struct type *var_type, struct value *outer)
7293 int others_clause;
7294 int i;
7295 const char *discrim_name = ada_variant_discrim_name (var_type);
7296 struct value *discrim;
7297 LONGEST discrim_val;
7299 /* Using plain value_from_contents_and_address here causes problems
7300 because we will end up trying to resolve a type that is currently
7301 being constructed. */
7302 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7303 if (discrim == NULL)
7304 return -1;
7305 discrim_val = value_as_long (discrim);
7307 others_clause = -1;
7308 for (i = 0; i < var_type->num_fields (); i += 1)
7310 if (ada_is_others_clause (var_type, i))
7311 others_clause = i;
7312 else if (ada_in_variant (discrim_val, var_type, i))
7313 return i;
7316 return others_clause;
7321 /* Dynamic-Sized Records */
7323 /* Strategy: The type ostensibly attached to a value with dynamic size
7324 (i.e., a size that is not statically recorded in the debugging
7325 data) does not accurately reflect the size or layout of the value.
7326 Our strategy is to convert these values to values with accurate,
7327 conventional types that are constructed on the fly. */
7329 /* There is a subtle and tricky problem here. In general, we cannot
7330 determine the size of dynamic records without its data. However,
7331 the 'struct value' data structure, which GDB uses to represent
7332 quantities in the inferior process (the target), requires the size
7333 of the type at the time of its allocation in order to reserve space
7334 for GDB's internal copy of the data. That's why the
7335 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7336 rather than struct value*s.
7338 However, GDB's internal history variables ($1, $2, etc.) are
7339 struct value*s containing internal copies of the data that are not, in
7340 general, the same as the data at their corresponding addresses in
7341 the target. Fortunately, the types we give to these values are all
7342 conventional, fixed-size types (as per the strategy described
7343 above), so that we don't usually have to perform the
7344 'to_fixed_xxx_type' conversions to look at their values.
7345 Unfortunately, there is one exception: if one of the internal
7346 history variables is an array whose elements are unconstrained
7347 records, then we will need to create distinct fixed types for each
7348 element selected. */
7350 /* The upshot of all of this is that many routines take a (type, host
7351 address, target address) triple as arguments to represent a value.
7352 The host address, if non-null, is supposed to contain an internal
7353 copy of the relevant data; otherwise, the program is to consult the
7354 target at the target address. */
7356 /* Assuming that VAL0 represents a pointer value, the result of
7357 dereferencing it. Differs from value_ind in its treatment of
7358 dynamic-sized types. */
7360 struct value *
7361 ada_value_ind (struct value *val0)
7363 struct value *val = value_ind (val0);
7365 if (ada_is_tagged_type (val->type (), 0))
7366 val = ada_tag_value_at_base_address (val);
7368 return ada_to_fixed_value (val);
7371 /* The value resulting from dereferencing any "reference to"
7372 qualifiers on VAL0. */
7374 static struct value *
7375 ada_coerce_ref (struct value *val0)
7377 if (val0->type ()->code () == TYPE_CODE_REF)
7379 struct value *val = val0;
7381 val = coerce_ref (val);
7383 if (ada_is_tagged_type (val->type (), 0))
7384 val = ada_tag_value_at_base_address (val);
7386 return ada_to_fixed_value (val);
7388 else
7389 return val0;
7392 /* Return the bit alignment required for field #F of template type TYPE. */
7394 static unsigned int
7395 field_alignment (struct type *type, int f)
7397 const char *name = type->field (f).name ();
7398 int len;
7399 int align_offset;
7401 /* The field name should never be null, unless the debugging information
7402 is somehow malformed. In this case, we assume the field does not
7403 require any alignment. */
7404 if (name == NULL)
7405 return 1;
7407 len = strlen (name);
7409 if (!isdigit (name[len - 1]))
7410 return 1;
7412 if (isdigit (name[len - 2]))
7413 align_offset = len - 2;
7414 else
7415 align_offset = len - 1;
7417 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7418 return TARGET_CHAR_BIT;
7420 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7423 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7425 static struct symbol *
7426 ada_find_any_type_symbol (const char *name)
7428 return standard_lookup (name, get_selected_block (nullptr),
7429 SEARCH_TYPE_DOMAIN);
7432 /* Find a type named NAME. Ignores ambiguity. This routine will look
7433 solely for types defined by debug info, it will not search the GDB
7434 primitive types. */
7436 static struct type *
7437 ada_find_any_type (const char *name)
7439 struct symbol *sym = ada_find_any_type_symbol (name);
7441 if (sym != NULL)
7442 return sym->type ();
7444 return NULL;
7447 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7448 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7449 symbol, in which case it is returned. Otherwise, this looks for
7450 symbols whose name is that of NAME_SYM suffixed with "___XR".
7451 Return symbol if found, and NULL otherwise. */
7453 static bool
7454 ada_is_renaming_symbol (struct symbol *name_sym)
7456 const char *name = name_sym->linkage_name ();
7457 return strstr (name, "___XR") != NULL;
7460 /* Because of GNAT encoding conventions, several GDB symbols may match a
7461 given type name. If the type denoted by TYPE0 is to be preferred to
7462 that of TYPE1 for purposes of type printing, return non-zero;
7463 otherwise return 0. */
7466 ada_prefer_type (struct type *type0, struct type *type1)
7468 if (type1 == NULL)
7469 return 1;
7470 else if (type0 == NULL)
7471 return 0;
7472 else if (type1->code () == TYPE_CODE_VOID)
7473 return 1;
7474 else if (type0->code () == TYPE_CODE_VOID)
7475 return 0;
7476 else if (type1->name () == NULL && type0->name () != NULL)
7477 return 1;
7478 else if (ada_is_constrained_packed_array_type (type0))
7479 return 1;
7480 else if (ada_is_array_descriptor_type (type0)
7481 && !ada_is_array_descriptor_type (type1))
7482 return 1;
7483 else
7485 const char *type0_name = type0->name ();
7486 const char *type1_name = type1->name ();
7488 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7489 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7490 return 1;
7492 return 0;
7495 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7496 null. */
7498 const char *
7499 ada_type_name (struct type *type)
7501 if (type == NULL)
7502 return NULL;
7503 return type->name ();
7506 /* Search the list of "descriptive" types associated to TYPE for a type
7507 whose name is NAME. */
7509 static struct type *
7510 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7512 struct type *result, *tmp;
7514 if (ada_ignore_descriptive_types_p)
7515 return NULL;
7517 /* If there no descriptive-type info, then there is no parallel type
7518 to be found. */
7519 if (!HAVE_GNAT_AUX_INFO (type))
7520 return NULL;
7522 result = TYPE_DESCRIPTIVE_TYPE (type);
7523 while (result != NULL)
7525 const char *result_name = ada_type_name (result);
7527 if (result_name == NULL)
7529 warning (_("unexpected null name on descriptive type"));
7530 return NULL;
7533 /* If the names match, stop. */
7534 if (strcmp (result_name, name) == 0)
7535 break;
7537 /* Otherwise, look at the next item on the list, if any. */
7538 if (HAVE_GNAT_AUX_INFO (result))
7539 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7540 else
7541 tmp = NULL;
7543 /* If not found either, try after having resolved the typedef. */
7544 if (tmp != NULL)
7545 result = tmp;
7546 else
7548 result = check_typedef (result);
7549 if (HAVE_GNAT_AUX_INFO (result))
7550 result = TYPE_DESCRIPTIVE_TYPE (result);
7551 else
7552 result = NULL;
7556 /* If we didn't find a match, see whether this is a packed array. With
7557 older compilers, the descriptive type information is either absent or
7558 irrelevant when it comes to packed arrays so the above lookup fails.
7559 Fall back to using a parallel lookup by name in this case. */
7560 if (result == NULL && ada_is_constrained_packed_array_type (type))
7561 return ada_find_any_type (name);
7563 return result;
7566 /* Find a parallel type to TYPE with the specified NAME, using the
7567 descriptive type taken from the debugging information, if available,
7568 and otherwise using the (slower) name-based method. */
7570 static struct type *
7571 ada_find_parallel_type_with_name (struct type *type, const char *name)
7573 struct type *result = NULL;
7575 if (HAVE_GNAT_AUX_INFO (type))
7576 result = find_parallel_type_by_descriptive_type (type, name);
7577 else
7578 result = ada_find_any_type (name);
7580 return result;
7583 /* Same as above, but specify the name of the parallel type by appending
7584 SUFFIX to the name of TYPE. */
7586 struct type *
7587 ada_find_parallel_type (struct type *type, const char *suffix)
7589 char *name;
7590 const char *type_name = ada_type_name (type);
7591 int len;
7593 if (type_name == NULL)
7594 return NULL;
7596 len = strlen (type_name);
7598 name = (char *) alloca (len + strlen (suffix) + 1);
7600 strcpy (name, type_name);
7601 strcpy (name + len, suffix);
7603 return ada_find_parallel_type_with_name (type, name);
7606 /* If TYPE is a variable-size record type, return the corresponding template
7607 type describing its fields. Otherwise, return NULL. */
7609 static struct type *
7610 dynamic_template_type (struct type *type)
7612 type = ada_check_typedef (type);
7614 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7615 || ada_type_name (type) == NULL)
7616 return NULL;
7617 else
7619 int len = strlen (ada_type_name (type));
7621 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7622 return type;
7623 else
7624 return ada_find_parallel_type (type, "___XVE");
7628 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7629 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7631 static int
7632 is_dynamic_field (struct type *templ_type, int field_num)
7634 const char *name = templ_type->field (field_num).name ();
7636 return name != NULL
7637 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7638 && strstr (name, "___XVL") != NULL;
7641 /* The index of the variant field of TYPE, or -1 if TYPE does not
7642 represent a variant record type. */
7644 static int
7645 variant_field_index (struct type *type)
7647 int f;
7649 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7650 return -1;
7652 for (f = 0; f < type->num_fields (); f += 1)
7654 if (ada_is_variant_part (type, f))
7655 return f;
7657 return -1;
7660 /* A record type with no fields. */
7662 static struct type *
7663 empty_record (struct type *templ)
7665 struct type *type = type_allocator (templ).new_type ();
7667 type->set_code (TYPE_CODE_STRUCT);
7668 INIT_NONE_SPECIFIC (type);
7669 type->set_name ("<empty>");
7670 type->set_length (0);
7671 return type;
7674 /* An ordinary record type (with fixed-length fields) that describes
7675 the value of type TYPE at VALADDR or ADDRESS (see comments at
7676 the beginning of this section) VAL according to GNAT conventions.
7677 DVAL0 should describe the (portion of a) record that contains any
7678 necessary discriminants. It should be NULL if VAL->type () is
7679 an outer-level type (i.e., as opposed to a branch of a variant.) A
7680 variant field (unless unchecked) is replaced by a particular branch
7681 of the variant.
7683 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7684 length are not statically known are discarded. As a consequence,
7685 VALADDR, ADDRESS and DVAL0 are ignored.
7687 NOTE: Limitations: For now, we assume that dynamic fields and
7688 variants occupy whole numbers of bytes. However, they need not be
7689 byte-aligned. */
7691 struct type *
7692 ada_template_to_fixed_record_type_1 (struct type *type,
7693 const gdb_byte *valaddr,
7694 CORE_ADDR address, struct value *dval0,
7695 int keep_dynamic_fields)
7697 struct value *dval;
7698 struct type *rtype;
7699 int nfields, bit_len;
7700 int variant_field;
7701 long off;
7702 int fld_bit_len;
7703 int f;
7705 scoped_value_mark mark;
7707 /* Compute the number of fields in this record type that are going
7708 to be processed: unless keep_dynamic_fields, this includes only
7709 fields whose position and length are static will be processed. */
7710 if (keep_dynamic_fields)
7711 nfields = type->num_fields ();
7712 else
7714 nfields = 0;
7715 while (nfields < type->num_fields ()
7716 && !ada_is_variant_part (type, nfields)
7717 && !is_dynamic_field (type, nfields))
7718 nfields++;
7721 rtype = type_allocator (type).new_type ();
7722 rtype->set_code (TYPE_CODE_STRUCT);
7723 INIT_NONE_SPECIFIC (rtype);
7724 rtype->alloc_fields (nfields);
7725 rtype->set_name (ada_type_name (type));
7726 rtype->set_is_fixed_instance (true);
7728 off = 0;
7729 bit_len = 0;
7730 variant_field = -1;
7732 for (f = 0; f < nfields; f += 1)
7734 off = align_up (off, field_alignment (type, f))
7735 + type->field (f).loc_bitpos ();
7736 rtype->field (f).set_loc_bitpos (off);
7737 rtype->field (f).set_bitsize (0);
7739 if (ada_is_variant_part (type, f))
7741 variant_field = f;
7742 fld_bit_len = 0;
7744 else if (is_dynamic_field (type, f))
7746 const gdb_byte *field_valaddr = valaddr;
7747 CORE_ADDR field_address = address;
7748 struct type *field_type = type->field (f).type ()->target_type ();
7750 if (dval0 == NULL)
7752 /* Using plain value_from_contents_and_address here
7753 causes problems because we will end up trying to
7754 resolve a type that is currently being
7755 constructed. */
7756 dval = value_from_contents_and_address_unresolved (rtype,
7757 valaddr,
7758 address);
7759 rtype = dval->type ();
7761 else
7762 dval = dval0;
7764 /* If the type referenced by this field is an aligner type, we need
7765 to unwrap that aligner type, because its size might not be set.
7766 Keeping the aligner type would cause us to compute the wrong
7767 size for this field, impacting the offset of the all the fields
7768 that follow this one. */
7769 if (ada_is_aligner_type (field_type))
7771 long field_offset = type->field (f).loc_bitpos ();
7773 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7774 field_address = cond_offset_target (field_address, field_offset);
7775 field_type = ada_aligned_type (field_type);
7778 field_valaddr = cond_offset_host (field_valaddr,
7779 off / TARGET_CHAR_BIT);
7780 field_address = cond_offset_target (field_address,
7781 off / TARGET_CHAR_BIT);
7783 /* Get the fixed type of the field. Note that, in this case,
7784 we do not want to get the real type out of the tag: if
7785 the current field is the parent part of a tagged record,
7786 we will get the tag of the object. Clearly wrong: the real
7787 type of the parent is not the real type of the child. We
7788 would end up in an infinite loop. */
7789 field_type = ada_get_base_type (field_type);
7790 field_type = ada_to_fixed_type (field_type, field_valaddr,
7791 field_address, dval, 0);
7793 rtype->field (f).set_type (field_type);
7794 rtype->field (f).set_name (type->field (f).name ());
7795 /* The multiplication can potentially overflow. But because
7796 the field length has been size-checked just above, and
7797 assuming that the maximum size is a reasonable value,
7798 an overflow should not happen in practice. So rather than
7799 adding overflow recovery code to this already complex code,
7800 we just assume that it's not going to happen. */
7801 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7803 else
7805 /* Note: If this field's type is a typedef, it is important
7806 to preserve the typedef layer.
7808 Otherwise, we might be transforming a typedef to a fat
7809 pointer (encoding a pointer to an unconstrained array),
7810 into a basic fat pointer (encoding an unconstrained
7811 array). As both types are implemented using the same
7812 structure, the typedef is the only clue which allows us
7813 to distinguish between the two options. Stripping it
7814 would prevent us from printing this field appropriately. */
7815 rtype->field (f).set_type (type->field (f).type ());
7816 rtype->field (f).set_name (type->field (f).name ());
7817 if (type->field (f).bitsize () > 0)
7819 fld_bit_len = type->field (f).bitsize ();
7820 rtype->field (f).set_bitsize (fld_bit_len);
7822 else
7824 struct type *field_type = type->field (f).type ();
7826 /* We need to be careful of typedefs when computing
7827 the length of our field. If this is a typedef,
7828 get the length of the target type, not the length
7829 of the typedef. */
7830 if (field_type->code () == TYPE_CODE_TYPEDEF)
7831 field_type = ada_typedef_target_type (field_type);
7833 fld_bit_len =
7834 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7837 if (off + fld_bit_len > bit_len)
7838 bit_len = off + fld_bit_len;
7839 off += fld_bit_len;
7840 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7843 /* We handle the variant part, if any, at the end because of certain
7844 odd cases in which it is re-ordered so as NOT to be the last field of
7845 the record. This can happen in the presence of representation
7846 clauses. */
7847 if (variant_field >= 0)
7849 struct type *branch_type;
7851 off = rtype->field (variant_field).loc_bitpos ();
7853 if (dval0 == NULL)
7855 /* Using plain value_from_contents_and_address here causes
7856 problems because we will end up trying to resolve a type
7857 that is currently being constructed. */
7858 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7859 address);
7860 rtype = dval->type ();
7862 else
7863 dval = dval0;
7865 branch_type =
7866 to_fixed_variant_branch_type
7867 (type->field (variant_field).type (),
7868 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7869 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7870 if (branch_type == NULL)
7872 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7873 rtype->field (f - 1) = rtype->field (f);
7874 rtype->set_num_fields (rtype->num_fields () - 1);
7876 else
7878 rtype->field (variant_field).set_type (branch_type);
7879 rtype->field (variant_field).set_name ("S");
7880 fld_bit_len =
7881 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
7882 if (off + fld_bit_len > bit_len)
7883 bit_len = off + fld_bit_len;
7885 rtype->set_length
7886 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7890 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7891 should contain the alignment of that record, which should be a strictly
7892 positive value. If null or negative, then something is wrong, most
7893 probably in the debug info. In that case, we don't round up the size
7894 of the resulting type. If this record is not part of another structure,
7895 the current RTYPE length might be good enough for our purposes. */
7896 if (type->length () <= 0)
7898 if (rtype->name ())
7899 warning (_("Invalid type size for `%s' detected: %s."),
7900 rtype->name (), pulongest (type->length ()));
7901 else
7902 warning (_("Invalid type size for <unnamed> detected: %s."),
7903 pulongest (type->length ()));
7905 else
7906 rtype->set_length (align_up (rtype->length (), type->length ()));
7908 return rtype;
7911 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7912 of 1. */
7914 static struct type *
7915 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7916 CORE_ADDR address, struct value *dval0)
7918 return ada_template_to_fixed_record_type_1 (type, valaddr,
7919 address, dval0, 1);
7922 /* An ordinary record type in which ___XVL-convention fields and
7923 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7924 static approximations, containing all possible fields. Uses
7925 no runtime values. Useless for use in values, but that's OK,
7926 since the results are used only for type determinations. Works on both
7927 structs and unions. Representation note: to save space, we memorize
7928 the result of this function in the type::target_type of the
7929 template type. */
7931 static struct type *
7932 template_to_static_fixed_type (struct type *type0)
7934 struct type *type;
7935 int nfields;
7936 int f;
7938 /* No need no do anything if the input type is already fixed. */
7939 if (type0->is_fixed_instance ())
7940 return type0;
7942 /* Likewise if we already have computed the static approximation. */
7943 if (type0->target_type () != NULL)
7944 return type0->target_type ();
7946 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
7947 type = type0;
7948 nfields = type0->num_fields ();
7950 /* Whether or not we cloned TYPE0, cache the result so that we don't do
7951 recompute all over next time. */
7952 type0->set_target_type (type);
7954 for (f = 0; f < nfields; f += 1)
7956 struct type *field_type = type0->field (f).type ();
7957 struct type *new_type;
7959 if (is_dynamic_field (type0, f))
7961 field_type = ada_check_typedef (field_type);
7962 new_type = to_static_fixed_type (field_type->target_type ());
7964 else
7965 new_type = static_unwrap_type (field_type);
7967 if (new_type != field_type)
7969 /* Clone TYPE0 only the first time we get a new field type. */
7970 if (type == type0)
7972 type = type_allocator (type0).new_type ();
7973 type0->set_target_type (type);
7974 type->set_code (type0->code ());
7975 INIT_NONE_SPECIFIC (type);
7977 type->copy_fields (type0);
7979 type->set_name (ada_type_name (type0));
7980 type->set_is_fixed_instance (true);
7981 type->set_length (0);
7983 type->field (f).set_type (new_type);
7984 type->field (f).set_name (type0->field (f).name ());
7988 return type;
7991 /* Given an object of type TYPE whose contents are at VALADDR and
7992 whose address in memory is ADDRESS, returns a revision of TYPE,
7993 which should be a non-dynamic-sized record, in which the variant
7994 part, if any, is replaced with the appropriate branch. Looks
7995 for discriminant values in DVAL0, which can be NULL if the record
7996 contains the necessary discriminant values. */
7998 static struct type *
7999 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8000 CORE_ADDR address, struct value *dval0)
8002 struct value *dval;
8003 struct type *rtype;
8004 struct type *branch_type;
8005 int nfields = type->num_fields ();
8006 int variant_field = variant_field_index (type);
8008 if (variant_field == -1)
8009 return type;
8011 scoped_value_mark mark;
8012 if (dval0 == NULL)
8014 dval = value_from_contents_and_address (type, valaddr, address);
8015 type = dval->type ();
8017 else
8018 dval = dval0;
8020 rtype = type_allocator (type).new_type ();
8021 rtype->set_code (TYPE_CODE_STRUCT);
8022 INIT_NONE_SPECIFIC (rtype);
8023 rtype->copy_fields (type);
8025 rtype->set_name (ada_type_name (type));
8026 rtype->set_is_fixed_instance (true);
8027 rtype->set_length (type->length ());
8029 branch_type = to_fixed_variant_branch_type
8030 (type->field (variant_field).type (),
8031 cond_offset_host (valaddr,
8032 type->field (variant_field).loc_bitpos ()
8033 / TARGET_CHAR_BIT),
8034 cond_offset_target (address,
8035 type->field (variant_field).loc_bitpos ()
8036 / TARGET_CHAR_BIT), dval);
8037 if (branch_type == NULL)
8039 int f;
8041 for (f = variant_field + 1; f < nfields; f += 1)
8042 rtype->field (f - 1) = rtype->field (f);
8043 rtype->set_num_fields (rtype->num_fields () - 1);
8045 else
8047 rtype->field (variant_field).set_type (branch_type);
8048 rtype->field (variant_field).set_name ("S");
8049 rtype->field (variant_field).set_bitsize (0);
8050 rtype->set_length (rtype->length () + branch_type->length ());
8053 rtype->set_length (rtype->length ()
8054 - type->field (variant_field).type ()->length ());
8056 return rtype;
8059 /* An ordinary record type (with fixed-length fields) that describes
8060 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8061 beginning of this section]. Any necessary discriminants' values
8062 should be in DVAL, a record value; it may be NULL if the object
8063 at ADDR itself contains any necessary discriminant values.
8064 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8065 values from the record are needed. Except in the case that DVAL,
8066 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8067 unchecked) is replaced by a particular branch of the variant.
8069 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8070 is questionable and may be removed. It can arise during the
8071 processing of an unconstrained-array-of-record type where all the
8072 variant branches have exactly the same size. This is because in
8073 such cases, the compiler does not bother to use the XVS convention
8074 when encoding the record. I am currently dubious of this
8075 shortcut and suspect the compiler should be altered. FIXME. */
8077 static struct type *
8078 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8079 CORE_ADDR address, struct value *dval)
8081 struct type *templ_type;
8083 if (type0->is_fixed_instance ())
8084 return type0;
8086 templ_type = dynamic_template_type (type0);
8088 if (templ_type != NULL)
8089 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8090 else if (variant_field_index (type0) >= 0)
8092 if (dval == NULL && valaddr == NULL && address == 0)
8093 return type0;
8094 return to_record_with_fixed_variant_part (type0, valaddr, address,
8095 dval);
8097 else
8099 type0->set_is_fixed_instance (true);
8100 return type0;
8105 /* An ordinary record type (with fixed-length fields) that describes
8106 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8107 union type. Any necessary discriminants' values should be in DVAL,
8108 a record value. That is, this routine selects the appropriate
8109 branch of the union at ADDR according to the discriminant value
8110 indicated in the union's type name. Returns VAR_TYPE0 itself if
8111 it represents a variant subject to a pragma Unchecked_Union. */
8113 static struct type *
8114 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8115 CORE_ADDR address, struct value *dval)
8117 int which;
8118 struct type *templ_type;
8119 struct type *var_type;
8121 if (var_type0->code () == TYPE_CODE_PTR)
8122 var_type = var_type0->target_type ();
8123 else
8124 var_type = var_type0;
8126 templ_type = ada_find_parallel_type (var_type, "___XVU");
8128 if (templ_type != NULL)
8129 var_type = templ_type;
8131 if (is_unchecked_variant (var_type, dval->type ()))
8132 return var_type0;
8133 which = ada_which_variant_applies (var_type, dval);
8135 if (which < 0)
8136 return empty_record (var_type);
8137 else if (is_dynamic_field (var_type, which))
8138 return to_fixed_record_type
8139 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8140 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8141 return
8142 to_fixed_record_type
8143 (var_type->field (which).type (), valaddr, address, dval);
8144 else
8145 return var_type->field (which).type ();
8148 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8149 ENCODING_TYPE, a type following the GNAT conventions for discrete
8150 type encodings, only carries redundant information. */
8152 static int
8153 ada_is_redundant_range_encoding (struct type *range_type,
8154 struct type *encoding_type)
8156 const char *bounds_str;
8157 int n;
8158 LONGEST lo, hi;
8160 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8162 if (get_base_type (range_type)->code ()
8163 != get_base_type (encoding_type)->code ())
8165 /* The compiler probably used a simple base type to describe
8166 the range type instead of the range's actual base type,
8167 expecting us to get the real base type from the encoding
8168 anyway. In this situation, the encoding cannot be ignored
8169 as redundant. */
8170 return 0;
8173 if (is_dynamic_type (range_type))
8174 return 0;
8176 if (encoding_type->name () == NULL)
8177 return 0;
8179 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8180 if (bounds_str == NULL)
8181 return 0;
8183 n = 8; /* Skip "___XDLU_". */
8184 if (!ada_scan_number (bounds_str, n, &lo, &n))
8185 return 0;
8186 if (range_type->bounds ()->low.const_val () != lo)
8187 return 0;
8189 n += 2; /* Skip the "__" separator between the two bounds. */
8190 if (!ada_scan_number (bounds_str, n, &hi, &n))
8191 return 0;
8192 if (range_type->bounds ()->high.const_val () != hi)
8193 return 0;
8195 return 1;
8198 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8199 a type following the GNAT encoding for describing array type
8200 indices, only carries redundant information. */
8202 static int
8203 ada_is_redundant_index_type_desc (struct type *array_type,
8204 struct type *desc_type)
8206 struct type *this_layer = check_typedef (array_type);
8207 int i;
8209 for (i = 0; i < desc_type->num_fields (); i++)
8211 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8212 desc_type->field (i).type ()))
8213 return 0;
8214 this_layer = check_typedef (this_layer->target_type ());
8217 return 1;
8220 /* Assuming that TYPE0 is an array type describing the type of a value
8221 at ADDR, and that DVAL describes a record containing any
8222 discriminants used in TYPE0, returns a type for the value that
8223 contains no dynamic components (that is, no components whose sizes
8224 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8225 true, gives an error message if the resulting type's size is over
8226 varsize_limit. */
8228 static struct type *
8229 to_fixed_array_type (struct type *type0, struct value *dval,
8230 int ignore_too_big)
8232 struct type *index_type_desc;
8233 struct type *result;
8234 int constrained_packed_array_p;
8235 static const char *xa_suffix = "___XA";
8237 type0 = ada_check_typedef (type0);
8238 if (type0->is_fixed_instance ())
8239 return type0;
8241 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8242 if (constrained_packed_array_p)
8244 type0 = decode_constrained_packed_array_type (type0);
8245 if (type0 == nullptr)
8246 error (_("could not decode constrained packed array type"));
8249 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8251 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8252 encoding suffixed with 'P' may still be generated. If so,
8253 it should be used to find the XA type. */
8255 if (index_type_desc == NULL)
8257 const char *type_name = ada_type_name (type0);
8259 if (type_name != NULL)
8261 const int len = strlen (type_name);
8262 char *name = (char *) alloca (len + strlen (xa_suffix));
8264 if (type_name[len - 1] == 'P')
8266 strcpy (name, type_name);
8267 strcpy (name + len - 1, xa_suffix);
8268 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8273 ada_fixup_array_indexes_type (index_type_desc);
8274 if (index_type_desc != NULL
8275 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8277 /* Ignore this ___XA parallel type, as it does not bring any
8278 useful information. This allows us to avoid creating fixed
8279 versions of the array's index types, which would be identical
8280 to the original ones. This, in turn, can also help avoid
8281 the creation of fixed versions of the array itself. */
8282 index_type_desc = NULL;
8285 if (index_type_desc == NULL)
8287 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8289 /* NOTE: elt_type---the fixed version of elt_type0---should never
8290 depend on the contents of the array in properly constructed
8291 debugging data. */
8292 /* Create a fixed version of the array element type.
8293 We're not providing the address of an element here,
8294 and thus the actual object value cannot be inspected to do
8295 the conversion. This should not be a problem, since arrays of
8296 unconstrained objects are not allowed. In particular, all
8297 the elements of an array of a tagged type should all be of
8298 the same type specified in the debugging info. No need to
8299 consult the object tag. */
8300 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8302 /* Make sure we always create a new array type when dealing with
8303 packed array types, since we're going to fix-up the array
8304 type length and element bitsize a little further down. */
8305 if (elt_type0 == elt_type && !constrained_packed_array_p)
8306 result = type0;
8307 else
8309 type_allocator alloc (type0);
8310 result = create_array_type (alloc, elt_type, type0->index_type ());
8313 else
8315 int i;
8316 struct type *elt_type0;
8318 elt_type0 = type0;
8319 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8320 elt_type0 = elt_type0->target_type ();
8322 /* NOTE: result---the fixed version of elt_type0---should never
8323 depend on the contents of the array in properly constructed
8324 debugging data. */
8325 /* Create a fixed version of the array element type.
8326 We're not providing the address of an element here,
8327 and thus the actual object value cannot be inspected to do
8328 the conversion. This should not be a problem, since arrays of
8329 unconstrained objects are not allowed. In particular, all
8330 the elements of an array of a tagged type should all be of
8331 the same type specified in the debugging info. No need to
8332 consult the object tag. */
8333 result =
8334 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8336 elt_type0 = type0;
8337 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8339 struct type *range_type =
8340 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8342 type_allocator alloc (elt_type0);
8343 result = create_array_type (alloc, result, range_type);
8344 elt_type0 = elt_type0->target_type ();
8348 /* We want to preserve the type name. This can be useful when
8349 trying to get the type name of a value that has already been
8350 printed (for instance, if the user did "print VAR; whatis $". */
8351 result->set_name (type0->name ());
8353 if (constrained_packed_array_p)
8355 /* So far, the resulting type has been created as if the original
8356 type was a regular (non-packed) array type. As a result, the
8357 bitsize of the array elements needs to be set again, and the array
8358 length needs to be recomputed based on that bitsize. */
8359 int len = result->length () / result->target_type ()->length ();
8360 int elt_bitsize = type0->field (0).bitsize ();
8362 result->field (0).set_bitsize (elt_bitsize);
8363 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8364 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8365 result->set_length (result->length () + 1);
8368 result->set_is_fixed_instance (true);
8369 return result;
8373 /* A standard type (containing no dynamically sized components)
8374 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8375 DVAL describes a record containing any discriminants used in TYPE0,
8376 and may be NULL if there are none, or if the object of type TYPE at
8377 ADDRESS or in VALADDR contains these discriminants.
8379 If CHECK_TAG is not null, in the case of tagged types, this function
8380 attempts to locate the object's tag and use it to compute the actual
8381 type. However, when ADDRESS is null, we cannot use it to determine the
8382 location of the tag, and therefore compute the tagged type's actual type.
8383 So we return the tagged type without consulting the tag. */
8385 static struct type *
8386 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8387 CORE_ADDR address, struct value *dval, int check_tag)
8389 type = ada_check_typedef (type);
8391 /* Only un-fixed types need to be handled here. */
8392 if (!HAVE_GNAT_AUX_INFO (type))
8393 return type;
8395 switch (type->code ())
8397 default:
8398 return type;
8399 case TYPE_CODE_STRUCT:
8401 struct type *static_type = to_static_fixed_type (type);
8402 struct type *fixed_record_type =
8403 to_fixed_record_type (type, valaddr, address, NULL);
8405 /* If STATIC_TYPE is a tagged type and we know the object's address,
8406 then we can determine its tag, and compute the object's actual
8407 type from there. Note that we have to use the fixed record
8408 type (the parent part of the record may have dynamic fields
8409 and the way the location of _tag is expressed may depend on
8410 them). */
8412 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8414 struct value *tag =
8415 value_tag_from_contents_and_address
8416 (fixed_record_type,
8417 valaddr,
8418 address);
8419 struct type *real_type = type_from_tag (tag);
8420 struct value *obj =
8421 value_from_contents_and_address (fixed_record_type,
8422 valaddr,
8423 address);
8424 fixed_record_type = obj->type ();
8425 if (real_type != NULL)
8426 return to_fixed_record_type
8427 (real_type, NULL,
8428 ada_tag_value_at_base_address (obj)->address (), NULL);
8431 /* Check to see if there is a parallel ___XVZ variable.
8432 If there is, then it provides the actual size of our type. */
8433 else if (ada_type_name (fixed_record_type) != NULL)
8435 const char *name = ada_type_name (fixed_record_type);
8436 char *xvz_name
8437 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8438 bool xvz_found = false;
8439 LONGEST size;
8441 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8444 xvz_found = get_int_var_value (xvz_name, size);
8446 catch (const gdb_exception_error &except)
8448 /* We found the variable, but somehow failed to read
8449 its value. Rethrow the same error, but with a little
8450 bit more information, to help the user understand
8451 what went wrong (Eg: the variable might have been
8452 optimized out). */
8453 throw_error (except.error,
8454 _("unable to read value of %s (%s)"),
8455 xvz_name, except.what ());
8458 if (xvz_found && fixed_record_type->length () != size)
8460 fixed_record_type = copy_type (fixed_record_type);
8461 fixed_record_type->set_length (size);
8463 /* The FIXED_RECORD_TYPE may have be a stub. We have
8464 observed this when the debugging info is STABS, and
8465 apparently it is something that is hard to fix.
8467 In practice, we don't need the actual type definition
8468 at all, because the presence of the XVZ variable allows us
8469 to assume that there must be a XVS type as well, which we
8470 should be able to use later, when we need the actual type
8471 definition.
8473 In the meantime, pretend that the "fixed" type we are
8474 returning is NOT a stub, because this can cause trouble
8475 when using this type to create new types targeting it.
8476 Indeed, the associated creation routines often check
8477 whether the target type is a stub and will try to replace
8478 it, thus using a type with the wrong size. This, in turn,
8479 might cause the new type to have the wrong size too.
8480 Consider the case of an array, for instance, where the size
8481 of the array is computed from the number of elements in
8482 our array multiplied by the size of its element. */
8483 fixed_record_type->set_is_stub (false);
8486 return fixed_record_type;
8488 case TYPE_CODE_ARRAY:
8489 return to_fixed_array_type (type, dval, 1);
8490 case TYPE_CODE_UNION:
8491 if (dval == NULL)
8492 return type;
8493 else
8494 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8498 /* The same as ada_to_fixed_type_1, except that it preserves the type
8499 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8501 The typedef layer needs be preserved in order to differentiate between
8502 arrays and array pointers when both types are implemented using the same
8503 fat pointer. In the array pointer case, the pointer is encoded as
8504 a typedef of the pointer type. For instance, considering:
8506 type String_Access is access String;
8507 S1 : String_Access := null;
8509 To the debugger, S1 is defined as a typedef of type String. But
8510 to the user, it is a pointer. So if the user tries to print S1,
8511 we should not dereference the array, but print the array address
8512 instead.
8514 If we didn't preserve the typedef layer, we would lose the fact that
8515 the type is to be presented as a pointer (needs de-reference before
8516 being printed). And we would also use the source-level type name. */
8518 struct type *
8519 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8520 CORE_ADDR address, struct value *dval, int check_tag)
8523 struct type *fixed_type =
8524 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8526 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8527 then preserve the typedef layer.
8529 Implementation note: We can only check the main-type portion of
8530 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8531 from TYPE now returns a type that has the same instance flags
8532 as TYPE. For instance, if TYPE is a "typedef const", and its
8533 target type is a "struct", then the typedef elimination will return
8534 a "const" version of the target type. See check_typedef for more
8535 details about how the typedef layer elimination is done.
8537 brobecker/2010-11-19: It seems to me that the only case where it is
8538 useful to preserve the typedef layer is when dealing with fat pointers.
8539 Perhaps, we could add a check for that and preserve the typedef layer
8540 only in that situation. But this seems unnecessary so far, probably
8541 because we call check_typedef/ada_check_typedef pretty much everywhere.
8543 if (type->code () == TYPE_CODE_TYPEDEF
8544 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8545 == TYPE_MAIN_TYPE (fixed_type)))
8546 return type;
8548 return fixed_type;
8551 /* A standard (static-sized) type corresponding as well as possible to
8552 TYPE0, but based on no runtime data. */
8554 static struct type *
8555 to_static_fixed_type (struct type *type0)
8557 struct type *type;
8559 if (type0 == NULL)
8560 return NULL;
8562 if (type0->is_fixed_instance ())
8563 return type0;
8565 type0 = ada_check_typedef (type0);
8567 switch (type0->code ())
8569 default:
8570 return type0;
8571 case TYPE_CODE_STRUCT:
8572 type = dynamic_template_type (type0);
8573 if (type != NULL)
8574 return template_to_static_fixed_type (type);
8575 else
8576 return template_to_static_fixed_type (type0);
8577 case TYPE_CODE_UNION:
8578 type = ada_find_parallel_type (type0, "___XVU");
8579 if (type != NULL)
8580 return template_to_static_fixed_type (type);
8581 else
8582 return template_to_static_fixed_type (type0);
8586 /* A static approximation of TYPE with all type wrappers removed. */
8588 static struct type *
8589 static_unwrap_type (struct type *type)
8591 if (ada_is_aligner_type (type))
8593 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8594 if (ada_type_name (type1) == NULL)
8595 type1->set_name (ada_type_name (type));
8597 return static_unwrap_type (type1);
8599 else
8601 struct type *raw_real_type = ada_get_base_type (type);
8603 if (raw_real_type == type)
8604 return type;
8605 else
8606 return to_static_fixed_type (raw_real_type);
8610 /* In some cases, incomplete and private types require
8611 cross-references that are not resolved as records (for example,
8612 type Foo;
8613 type FooP is access Foo;
8614 V: FooP;
8615 type Foo is array ...;
8616 ). In these cases, since there is no mechanism for producing
8617 cross-references to such types, we instead substitute for FooP a
8618 stub enumeration type that is nowhere resolved, and whose tag is
8619 the name of the actual type. Call these types "non-record stubs". */
8621 /* A type equivalent to TYPE that is not a non-record stub, if one
8622 exists, otherwise TYPE. */
8624 struct type *
8625 ada_check_typedef (struct type *type)
8627 if (type == NULL)
8628 return NULL;
8630 /* If our type is an access to an unconstrained array, which is encoded
8631 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8632 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8633 what allows us to distinguish between fat pointers that represent
8634 array types, and fat pointers that represent array access types
8635 (in both cases, the compiler implements them as fat pointers). */
8636 if (ada_is_access_to_unconstrained_array (type))
8637 return type;
8639 type = check_typedef (type);
8640 if (type == NULL || type->code () != TYPE_CODE_ENUM
8641 || !type->is_stub ()
8642 || type->name () == NULL)
8643 return type;
8644 else
8646 const char *name = type->name ();
8647 struct type *type1 = ada_find_any_type (name);
8649 if (type1 == NULL)
8650 return type;
8652 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8653 stubs pointing to arrays, as we don't create symbols for array
8654 types, only for the typedef-to-array types). If that's the case,
8655 strip the typedef layer. */
8656 if (type1->code () == TYPE_CODE_TYPEDEF)
8657 type1 = ada_check_typedef (type1);
8659 return type1;
8663 /* A value representing the data at VALADDR/ADDRESS as described by
8664 type TYPE0, but with a standard (static-sized) type that correctly
8665 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8666 type, then return VAL0 [this feature is simply to avoid redundant
8667 creation of struct values]. */
8669 static struct value *
8670 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8671 struct value *val0)
8673 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8675 if (type == type0 && val0 != NULL)
8676 return val0;
8678 if (val0->lval () != lval_memory)
8680 /* Our value does not live in memory; it could be a convenience
8681 variable, for instance. Create a not_lval value using val0's
8682 contents. */
8683 return value_from_contents (type, val0->contents ().data ());
8686 return value_from_contents_and_address (type, 0, address);
8689 /* A value representing VAL, but with a standard (static-sized) type
8690 that correctly describes it. Does not necessarily create a new
8691 value. */
8693 struct value *
8694 ada_to_fixed_value (struct value *val)
8696 val = unwrap_value (val);
8697 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8698 return val;
8702 /* Attributes */
8704 /* Evaluate the 'POS attribute applied to ARG. */
8706 static LONGEST
8707 pos_atr (struct value *arg)
8709 struct value *val = coerce_ref (arg);
8710 struct type *type = val->type ();
8712 if (!discrete_type_p (type))
8713 error (_("'POS only defined on discrete types"));
8715 std::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8716 if (!result.has_value ())
8717 error (_("enumeration value is invalid: can't find 'POS"));
8719 return *result;
8722 struct value *
8723 ada_pos_atr (struct type *expect_type,
8724 struct expression *exp,
8725 enum noside noside, enum exp_opcode op,
8726 struct value *arg)
8728 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8729 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8730 return value::zero (type, not_lval);
8731 return value_from_longest (type, pos_atr (arg));
8734 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8736 static struct value *
8737 val_atr (struct type *type, LONGEST val)
8739 gdb_assert (discrete_type_p (type));
8740 if (type->code () == TYPE_CODE_RANGE)
8741 type = type->target_type ();
8742 if (type->code () == TYPE_CODE_ENUM)
8744 if (val < 0 || val >= type->num_fields ())
8745 error (_("argument to 'VAL out of range"));
8746 val = type->field (val).loc_enumval ();
8748 return value_from_longest (type, val);
8751 struct value *
8752 ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8753 struct value *arg)
8755 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8756 return value::zero (type, not_lval);
8758 if (!discrete_type_p (type))
8759 error (_("'VAL only defined on discrete types"));
8760 if (!integer_type_p (arg->type ()))
8761 error (_("'VAL requires integral argument"));
8763 return val_atr (type, value_as_long (arg));
8766 /* Implementation of the enum_rep attribute. */
8767 struct value *
8768 ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8769 struct value *arg)
8771 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8772 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8773 return value::zero (inttype, not_lval);
8775 if (type->code () == TYPE_CODE_RANGE)
8776 type = type->target_type ();
8777 if (type->code () != TYPE_CODE_ENUM)
8778 error (_("'Enum_Rep only defined on enum types"));
8779 if (!types_equal (type, arg->type ()))
8780 error (_("'Enum_Rep requires argument to have same type as enum"));
8782 return value_cast (inttype, arg);
8785 /* Implementation of the enum_val attribute. */
8786 struct value *
8787 ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8788 struct value *arg)
8790 struct type *original_type = type;
8791 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8792 return value::zero (original_type, not_lval);
8794 if (type->code () == TYPE_CODE_RANGE)
8795 type = type->target_type ();
8796 if (type->code () != TYPE_CODE_ENUM)
8797 error (_("'Enum_Val only defined on enum types"));
8798 if (!integer_type_p (arg->type ()))
8799 error (_("'Enum_Val requires integral argument"));
8801 LONGEST value = value_as_long (arg);
8802 for (int i = 0; i < type->num_fields (); ++i)
8804 if (type->field (i).loc_enumval () == value)
8805 return value_from_longest (original_type, value);
8808 error (_("value %s not found in enum"), plongest (value));
8813 /* Evaluation */
8815 /* True if TYPE appears to be an Ada character type.
8816 [At the moment, this is true only for Character and Wide_Character;
8817 It is a heuristic test that could stand improvement]. */
8819 bool
8820 ada_is_character_type (struct type *type)
8822 const char *name;
8824 /* If the type code says it's a character, then assume it really is,
8825 and don't check any further. */
8826 if (type->code () == TYPE_CODE_CHAR)
8827 return true;
8829 /* Otherwise, assume it's a character type iff it is a discrete type
8830 with a known character type name. */
8831 name = ada_type_name (type);
8832 return (name != NULL
8833 && (type->code () == TYPE_CODE_INT
8834 || type->code () == TYPE_CODE_RANGE)
8835 && (strcmp (name, "character") == 0
8836 || strcmp (name, "wide_character") == 0
8837 || strcmp (name, "wide_wide_character") == 0
8838 || strcmp (name, "unsigned char") == 0));
8841 /* True if TYPE appears to be an Ada string type. */
8843 bool
8844 ada_is_string_type (struct type *type)
8846 type = ada_check_typedef (type);
8847 if (type != NULL
8848 && type->code () != TYPE_CODE_PTR
8849 && (ada_is_simple_array_type (type)
8850 || ada_is_array_descriptor_type (type))
8851 && ada_array_arity (type) == 1)
8853 struct type *elttype = ada_array_element_type (type, 1);
8855 return ada_is_character_type (elttype);
8857 else
8858 return false;
8861 /* The compiler sometimes provides a parallel XVS type for a given
8862 PAD type. Normally, it is safe to follow the PAD type directly,
8863 but older versions of the compiler have a bug that causes the offset
8864 of its "F" field to be wrong. Following that field in that case
8865 would lead to incorrect results, but this can be worked around
8866 by ignoring the PAD type and using the associated XVS type instead.
8868 Set to True if the debugger should trust the contents of PAD types.
8869 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8870 static bool trust_pad_over_xvs = true;
8872 /* True if TYPE is a struct type introduced by the compiler to force the
8873 alignment of a value. Such types have a single field with a
8874 distinctive name. */
8877 ada_is_aligner_type (struct type *type)
8879 type = ada_check_typedef (type);
8881 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8882 return 0;
8884 return (type->code () == TYPE_CODE_STRUCT
8885 && type->num_fields () == 1
8886 && strcmp (type->field (0).name (), "F") == 0);
8889 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8890 the parallel type. */
8892 struct type *
8893 ada_get_base_type (struct type *raw_type)
8895 struct type *real_type_namer;
8896 struct type *raw_real_type;
8898 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8899 return raw_type;
8901 if (ada_is_aligner_type (raw_type))
8902 /* The encoding specifies that we should always use the aligner type.
8903 So, even if this aligner type has an associated XVS type, we should
8904 simply ignore it.
8906 According to the compiler gurus, an XVS type parallel to an aligner
8907 type may exist because of a stabs limitation. In stabs, aligner
8908 types are empty because the field has a variable-sized type, and
8909 thus cannot actually be used as an aligner type. As a result,
8910 we need the associated parallel XVS type to decode the type.
8911 Since the policy in the compiler is to not change the internal
8912 representation based on the debugging info format, we sometimes
8913 end up having a redundant XVS type parallel to the aligner type. */
8914 return raw_type;
8916 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8917 if (real_type_namer == NULL
8918 || real_type_namer->code () != TYPE_CODE_STRUCT
8919 || real_type_namer->num_fields () != 1)
8920 return raw_type;
8922 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8924 /* This is an older encoding form where the base type needs to be
8925 looked up by name. We prefer the newer encoding because it is
8926 more efficient. */
8927 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
8928 if (raw_real_type == NULL)
8929 return raw_type;
8930 else
8931 return raw_real_type;
8934 /* The field in our XVS type is a reference to the base type. */
8935 return real_type_namer->field (0).type ()->target_type ();
8938 /* The type of value designated by TYPE, with all aligners removed. */
8940 struct type *
8941 ada_aligned_type (struct type *type)
8943 if (ada_is_aligner_type (type))
8944 return ada_aligned_type (type->field (0).type ());
8945 else
8946 return ada_get_base_type (type);
8950 /* The address of the aligned value in an object at address VALADDR
8951 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
8953 const gdb_byte *
8954 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8956 if (ada_is_aligner_type (type))
8957 return ada_aligned_value_addr
8958 (type->field (0).type (),
8959 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
8960 else
8961 return valaddr;
8966 /* The printed representation of an enumeration literal with encoded
8967 name NAME. The value is good to the next call of ada_enum_name. */
8968 const char *
8969 ada_enum_name (const char *name)
8971 static std::string storage;
8972 const char *tmp;
8974 /* First, unqualify the enumeration name:
8975 1. Search for the last '.' character. If we find one, then skip
8976 all the preceding characters, the unqualified name starts
8977 right after that dot.
8978 2. Otherwise, we may be debugging on a target where the compiler
8979 translates dots into "__". Search forward for double underscores,
8980 but stop searching when we hit an overloading suffix, which is
8981 of the form "__" followed by digits. */
8983 tmp = strrchr (name, '.');
8984 if (tmp != NULL)
8985 name = tmp + 1;
8986 else
8988 while ((tmp = strstr (name, "__")) != NULL)
8990 if (isdigit (tmp[2]))
8991 break;
8992 else
8993 name = tmp + 2;
8997 if (name[0] == 'Q')
8999 int v;
9001 if (name[1] == 'U' || name[1] == 'W')
9003 int offset = 2;
9004 if (name[1] == 'W' && name[2] == 'W')
9006 /* Also handle the QWW case. */
9007 ++offset;
9009 if (sscanf (name + offset, "%x", &v) != 1)
9010 return name;
9012 else if (((name[1] >= '0' && name[1] <= '9')
9013 || (name[1] >= 'a' && name[1] <= 'z'))
9014 && name[2] == '\0')
9016 storage = string_printf ("'%c'", name[1]);
9017 return storage.c_str ();
9019 else
9020 return name;
9022 if (isascii (v) && isprint (v))
9023 storage = string_printf ("'%c'", v);
9024 else if (name[1] == 'U')
9025 storage = string_printf ("'[\"%02x\"]'", v);
9026 else if (name[2] != 'W')
9027 storage = string_printf ("'[\"%04x\"]'", v);
9028 else
9029 storage = string_printf ("'[\"%06x\"]'", v);
9031 return storage.c_str ();
9033 else
9035 tmp = strstr (name, "__");
9036 if (tmp == NULL)
9037 tmp = strstr (name, "$");
9038 if (tmp != NULL)
9040 storage = std::string (name, tmp - name);
9041 return storage.c_str ();
9044 return name;
9048 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9049 there is no parallel type, return nullptr. */
9051 static struct type *
9052 find_base_type (struct type *type)
9054 struct type *raw_real_type
9055 = ada_check_typedef (ada_get_base_type (type));
9057 /* No parallel XVS or XVE type. */
9058 if (type == raw_real_type
9059 && ada_find_parallel_type (type, "___XVE") == nullptr)
9060 return nullptr;
9062 return raw_real_type;
9065 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9066 value it wraps. */
9068 static struct value *
9069 unwrap_value (struct value *val)
9071 struct type *type = ada_check_typedef (val->type ());
9073 if (ada_is_aligner_type (type))
9075 struct value *v = ada_value_struct_elt (val, "F", 0);
9076 struct type *val_type = ada_check_typedef (v->type ());
9078 if (ada_type_name (val_type) == NULL)
9079 val_type->set_name (ada_type_name (type));
9081 return unwrap_value (v);
9083 else
9085 struct type *raw_real_type = find_base_type (type);
9086 if (raw_real_type == nullptr)
9087 return val;
9089 return
9090 coerce_unspec_val_to_type
9091 (val, ada_to_fixed_type (raw_real_type, 0,
9092 val->address (),
9093 NULL, 1));
9097 /* Given two array types T1 and T2, return nonzero iff both arrays
9098 contain the same number of elements. */
9100 static int
9101 ada_same_array_size_p (struct type *t1, struct type *t2)
9103 LONGEST lo1, hi1, lo2, hi2;
9105 /* Get the array bounds in order to verify that the size of
9106 the two arrays match. */
9107 if (!get_array_bounds (t1, &lo1, &hi1)
9108 || !get_array_bounds (t2, &lo2, &hi2))
9109 error (_("unable to determine array bounds"));
9111 /* To make things easier for size comparison, normalize a bit
9112 the case of empty arrays by making sure that the difference
9113 between upper bound and lower bound is always -1. */
9114 if (lo1 > hi1)
9115 hi1 = lo1 - 1;
9116 if (lo2 > hi2)
9117 hi2 = lo2 - 1;
9119 return (hi1 - lo1 == hi2 - lo2);
9122 /* Assuming that VAL is an array of integrals, and TYPE represents
9123 an array with the same number of elements, but with wider integral
9124 elements, return an array "casted" to TYPE. In practice, this
9125 means that the returned array is built by casting each element
9126 of the original array into TYPE's (wider) element type. */
9128 static struct value *
9129 ada_promote_array_of_integrals (struct type *type, struct value *val)
9131 struct type *elt_type = type->target_type ();
9132 LONGEST lo, hi;
9133 LONGEST i;
9135 /* Verify that both val and type are arrays of scalars, and
9136 that the size of val's elements is smaller than the size
9137 of type's element. */
9138 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9139 gdb_assert (is_integral_type (type->target_type ()));
9140 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9141 gdb_assert (is_integral_type (val->type ()->target_type ()));
9142 gdb_assert (type->target_type ()->length ()
9143 > val->type ()->target_type ()->length ());
9145 if (!get_array_bounds (type, &lo, &hi))
9146 error (_("unable to determine array bounds"));
9148 value *res = value::allocate (type);
9149 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9151 /* Promote each array element. */
9152 for (i = 0; i < hi - lo + 1; i++)
9154 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9155 int elt_len = elt_type->length ();
9157 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9160 return res;
9163 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9164 return the converted value. */
9166 static struct value *
9167 coerce_for_assign (struct type *type, struct value *val)
9169 struct type *type2 = val->type ();
9171 if (type == type2)
9172 return val;
9174 type2 = ada_check_typedef (type2);
9175 type = ada_check_typedef (type);
9177 if (type2->code () == TYPE_CODE_PTR
9178 && type->code () == TYPE_CODE_ARRAY)
9180 val = ada_value_ind (val);
9181 type2 = val->type ();
9184 if (type2->code () == TYPE_CODE_ARRAY
9185 && type->code () == TYPE_CODE_ARRAY)
9187 if (!ada_same_array_size_p (type, type2))
9188 error (_("cannot assign arrays of different length"));
9190 if (is_integral_type (type->target_type ())
9191 && is_integral_type (type2->target_type ())
9192 && type2->target_type ()->length () < type->target_type ()->length ())
9194 /* Allow implicit promotion of the array elements to
9195 a wider type. */
9196 return ada_promote_array_of_integrals (type, val);
9199 if (type2->target_type ()->length () != type->target_type ()->length ())
9200 error (_("Incompatible types in assignment"));
9201 val->deprecated_set_type (type);
9203 return val;
9206 static struct value *
9207 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9209 struct type *type1, *type2;
9211 arg1 = coerce_ref (arg1);
9212 arg2 = coerce_ref (arg2);
9213 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9214 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9216 if (type1->code () != TYPE_CODE_INT
9217 || type2->code () != TYPE_CODE_INT)
9218 return value_binop (arg1, arg2, op);
9220 switch (op)
9222 case BINOP_MOD:
9223 case BINOP_DIV:
9224 case BINOP_REM:
9225 break;
9226 default:
9227 return value_binop (arg1, arg2, op);
9230 gdb_mpz v2 = value_as_mpz (arg2);
9231 if (v2.sgn () == 0)
9233 const char *name;
9234 if (op == BINOP_MOD)
9235 name = "mod";
9236 else if (op == BINOP_DIV)
9237 name = "/";
9238 else
9240 gdb_assert (op == BINOP_REM);
9241 name = "rem";
9244 error (_("second operand of %s must not be zero."), name);
9247 if (type1->is_unsigned () || op == BINOP_MOD)
9248 return value_binop (arg1, arg2, op);
9250 gdb_mpz v1 = value_as_mpz (arg1);
9251 gdb_mpz v;
9252 switch (op)
9254 case BINOP_DIV:
9255 v = v1 / v2;
9256 break;
9257 case BINOP_REM:
9258 v = v1 % v2;
9259 if (v * v1 < 0)
9260 v -= v2;
9261 break;
9262 default:
9263 /* Should not reach this point. */
9264 gdb_assert_not_reached ("invalid operator");
9267 return value_from_mpz (type1, v);
9270 static int
9271 ada_value_equal (struct value *arg1, struct value *arg2)
9273 if (ada_is_direct_array_type (arg1->type ())
9274 || ada_is_direct_array_type (arg2->type ()))
9276 struct type *arg1_type, *arg2_type;
9278 /* Automatically dereference any array reference before
9279 we attempt to perform the comparison. */
9280 arg1 = ada_coerce_ref (arg1);
9281 arg2 = ada_coerce_ref (arg2);
9283 arg1 = ada_coerce_to_simple_array (arg1);
9284 arg2 = ada_coerce_to_simple_array (arg2);
9286 arg1_type = ada_check_typedef (arg1->type ());
9287 arg2_type = ada_check_typedef (arg2->type ());
9289 if (arg1_type->code () != TYPE_CODE_ARRAY
9290 || arg2_type->code () != TYPE_CODE_ARRAY)
9291 error (_("Attempt to compare array with non-array"));
9292 /* FIXME: The following works only for types whose
9293 representations use all bits (no padding or undefined bits)
9294 and do not have user-defined equality. */
9295 return (arg1_type->length () == arg2_type->length ()
9296 && memcmp (arg1->contents ().data (),
9297 arg2->contents ().data (),
9298 arg1_type->length ()) == 0);
9300 return value_equal (arg1, arg2);
9303 namespace expr
9306 bool
9307 check_objfile (const std::unique_ptr<ada_component> &comp,
9308 struct objfile *objfile)
9310 return comp->uses_objfile (objfile);
9313 /* See ada-exp.h. */
9315 void
9316 aggregate_assigner::assign (LONGEST index, operation_up &arg)
9318 scoped_value_mark mark;
9320 struct value *elt;
9321 struct type *lhs_type = check_typedef (lhs->type ());
9323 if (lhs_type->code () == TYPE_CODE_ARRAY)
9325 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9326 struct value *index_val = value_from_longest (index_type, index);
9328 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9330 else
9332 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9333 elt = ada_to_fixed_value (elt);
9336 scoped_restore save_index = make_scoped_restore (&m_current_index, index);
9338 ada_aggregate_operation *ag_op
9339 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9340 if (ag_op != nullptr)
9341 ag_op->assign_aggregate (container, elt, exp);
9342 else
9343 value_assign_to_component (container, elt,
9344 arg->evaluate (nullptr, exp,
9345 EVAL_NORMAL));
9348 /* See ada-exp.h. */
9350 value *
9351 aggregate_assigner::current_value () const
9353 /* Note that using an integer type here is incorrect -- the type
9354 should be the array's index type. Unfortunately, though, this
9355 isn't currently available during parsing and type resolution. */
9356 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9357 return value_from_longest (index_type, m_current_index);
9360 bool
9361 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9363 if (m_base != nullptr && m_base->uses_objfile (objfile))
9364 return true;
9365 for (const auto &item : m_components)
9366 if (item->uses_objfile (objfile))
9367 return true;
9368 return false;
9371 void
9372 ada_aggregate_component::dump (ui_file *stream, int depth)
9374 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9375 if (m_base != nullptr)
9377 gdb_printf (stream, _("%*swith delta\n"), depth + 1, "");
9378 m_base->dump (stream, depth + 2);
9380 for (const auto &item : m_components)
9381 item->dump (stream, depth + 1);
9384 void
9385 ada_aggregate_component::assign (aggregate_assigner &assigner)
9387 if (m_base != nullptr)
9389 value *base = m_base->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9390 if (ada_is_direct_array_type (base->type ()))
9391 base = ada_coerce_to_simple_array (base);
9392 if (!types_deeply_equal (assigner.container->type (), base->type ()))
9393 error (_("Type mismatch in delta aggregate"));
9394 value_assign_to_component (assigner.container, assigner.container,
9395 base);
9398 for (auto &item : m_components)
9399 item->assign (assigner);
9402 /* See ada-exp.h. */
9404 ada_aggregate_component::ada_aggregate_component
9405 (operation_up &&base, std::vector<ada_component_up> &&components)
9406 : m_base (std::move (base)),
9407 m_components (std::move (components))
9409 for (const auto &component : m_components)
9410 if (dynamic_cast<const ada_others_component *> (component.get ())
9411 != nullptr)
9413 /* It's invalid and nonsensical to have 'others => ...' with a
9414 delta aggregate. It was simpler to enforce this
9415 restriction here as opposed to in the parser. */
9416 error (_("'others' invalid in delta aggregate"));
9420 /* See ada-exp.h. */
9422 value *
9423 ada_aggregate_operation::assign_aggregate (struct value *container,
9424 struct value *lhs,
9425 struct expression *exp)
9427 struct type *lhs_type;
9428 aggregate_assigner assigner;
9430 container = ada_coerce_ref (container);
9431 if (ada_is_direct_array_type (container->type ()))
9432 container = ada_coerce_to_simple_array (container);
9433 lhs = ada_coerce_ref (lhs);
9434 if (!lhs->deprecated_modifiable ())
9435 error (_("Left operand of assignment is not a modifiable lvalue."));
9437 lhs_type = check_typedef (lhs->type ());
9438 if (ada_is_direct_array_type (lhs_type))
9440 lhs = ada_coerce_to_simple_array (lhs);
9441 lhs_type = check_typedef (lhs->type ());
9442 assigner.low = lhs_type->bounds ()->low.const_val ();
9443 assigner.high = lhs_type->bounds ()->high.const_val ();
9445 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9447 assigner.low = 0;
9448 assigner.high = num_visible_fields (lhs_type) - 1;
9450 else
9451 error (_("Left-hand side must be array or record."));
9453 assigner.indices.push_back (assigner.low - 1);
9454 assigner.indices.push_back (assigner.low - 1);
9455 assigner.indices.push_back (assigner.high + 1);
9456 assigner.indices.push_back (assigner.high + 1);
9458 assigner.container = container;
9459 assigner.lhs = lhs;
9460 assigner.exp = exp;
9462 std::get<0> (m_storage)->assign (assigner);
9464 return container;
9467 bool
9468 ada_positional_component::uses_objfile (struct objfile *objfile)
9470 return m_op->uses_objfile (objfile);
9473 void
9474 ada_positional_component::dump (ui_file *stream, int depth)
9476 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9477 depth, "", m_index);
9478 m_op->dump (stream, depth + 1);
9481 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9482 construct, given that the positions are relative to lower bound
9483 LOW, where HIGH is the upper bound. Record the position in
9484 INDICES. CONTAINER is as for assign_aggregate. */
9485 void
9486 ada_positional_component::assign (aggregate_assigner &assigner)
9488 LONGEST ind = m_index + assigner.low;
9490 if (ind - 1 == assigner.high)
9491 warning (_("Extra components in aggregate ignored."));
9492 if (ind <= assigner.high)
9494 assigner.add_interval (ind, ind);
9495 assigner.assign (ind, m_op);
9499 bool
9500 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9502 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9505 void
9506 ada_discrete_range_association::dump (ui_file *stream, int depth)
9508 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9509 m_low->dump (stream, depth + 1);
9510 m_high->dump (stream, depth + 1);
9513 void
9514 ada_discrete_range_association::assign (aggregate_assigner &assigner,
9515 operation_up &op)
9517 LONGEST lower = value_as_long (m_low->evaluate (nullptr, assigner.exp,
9518 EVAL_NORMAL));
9519 LONGEST upper = value_as_long (m_high->evaluate (nullptr, assigner.exp,
9520 EVAL_NORMAL));
9522 if (lower <= upper && (lower < assigner.low || upper > assigner.high))
9523 error (_("Index in component association out of bounds."));
9525 assigner.add_interval (lower, upper);
9526 while (lower <= upper)
9528 assigner.assign (lower, op);
9529 lower += 1;
9533 bool
9534 ada_name_association::uses_objfile (struct objfile *objfile)
9536 return m_val->uses_objfile (objfile);
9539 void
9540 ada_name_association::dump (ui_file *stream, int depth)
9542 gdb_printf (stream, _("%*sName:\n"), depth, "");
9543 m_val->dump (stream, depth + 1);
9546 void
9547 ada_name_association::assign (aggregate_assigner &assigner,
9548 operation_up &op)
9550 int index;
9552 if (ada_is_direct_array_type (assigner.lhs->type ()))
9554 value *tem = m_val->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9555 index = longest_to_int (value_as_long (tem));
9557 else
9559 ada_string_operation *strop
9560 = dynamic_cast<ada_string_operation *> (m_val.get ());
9562 const char *name;
9563 if (strop != nullptr)
9564 name = strop->get_name ();
9565 else
9567 ada_var_value_operation *vvo
9568 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9569 if (vvo == nullptr)
9570 error (_("Invalid record component association."));
9571 name = vvo->get_symbol ()->natural_name ();
9572 /* In this scenario, the user wrote (name => expr), but
9573 write_name_assoc found some fully-qualified name and
9574 substituted it. This happens because, at parse time, the
9575 meaning of the expression isn't known; but here we know
9576 that just the base name was supplied and it refers to the
9577 name of a field. */
9578 name = ada_unqualified_name (name);
9581 index = 0;
9582 if (! find_struct_field (name, assigner.lhs->type (), 0,
9583 NULL, NULL, NULL, NULL, &index))
9584 error (_("Unknown component name: %s."), name);
9587 assigner.add_interval (index, index);
9588 assigner.assign (index, op);
9591 bool
9592 ada_choices_component::uses_objfile (struct objfile *objfile)
9594 if (m_op->uses_objfile (objfile))
9595 return true;
9596 for (const auto &item : m_assocs)
9597 if (item->uses_objfile (objfile))
9598 return true;
9599 return false;
9602 void
9603 ada_choices_component::dump (ui_file *stream, int depth)
9605 if (m_name.empty ())
9606 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9607 else
9609 gdb_printf (stream, _("%*sIterated choices:\n"), depth, "");
9610 gdb_printf (stream, _("%*sName: %s\n"), depth + 1, "", m_name.c_str ());
9612 m_op->dump (stream, depth + 1);
9614 for (const auto &item : m_assocs)
9615 item->dump (stream, depth + 1);
9618 /* Assign into the components of LHS indexed by the OP_CHOICES
9619 construct at *POS, updating *POS past the construct, given that
9620 the allowable indices are LOW..HIGH. Record the indices assigned
9621 to in INDICES. CONTAINER is as for assign_aggregate. */
9622 void
9623 ada_choices_component::assign (aggregate_assigner &assigner)
9625 scoped_restore save_index = make_scoped_restore (&m_assigner, &assigner);
9626 for (auto &item : m_assocs)
9627 item->assign (assigner, m_op);
9630 void
9631 ada_index_var_operation::dump (struct ui_file *stream, int depth) const
9633 gdb_printf (stream, _("%*sIndex variable: %s\n"), depth, "",
9634 m_var->name ().c_str ());
9637 value *
9638 ada_index_var_operation::evaluate (struct type *expect_type,
9639 struct expression *exp,
9640 enum noside noside)
9642 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9644 /* Note that using an integer type here is incorrect -- the type
9645 should be the array's index type. Unfortunately, though,
9646 this isn't currently available during parsing and type
9647 resolution. */
9648 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9649 return value::zero (index_type, not_lval);
9652 return m_var->current_value ();
9655 bool
9656 ada_others_component::uses_objfile (struct objfile *objfile)
9658 return m_op->uses_objfile (objfile);
9661 void
9662 ada_others_component::dump (ui_file *stream, int depth)
9664 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9665 m_op->dump (stream, depth + 1);
9668 /* Assign the value of the expression in the OP_OTHERS construct in
9669 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9670 have not been previously assigned. The index intervals already assigned
9671 are in INDICES. CONTAINER is as for assign_aggregate. */
9672 void
9673 ada_others_component::assign (aggregate_assigner &assigner)
9675 int num_indices = assigner.indices.size ();
9676 for (int i = 0; i < num_indices - 2; i += 2)
9678 for (LONGEST ind = assigner.indices[i + 1] + 1;
9679 ind < assigner.indices[i + 2];
9680 ind += 1)
9681 assigner.assign (ind, m_op);
9685 struct value *
9686 ada_assign_operation::evaluate (struct type *expect_type,
9687 struct expression *exp,
9688 enum noside noside)
9690 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9691 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
9693 ada_aggregate_operation *ag_op
9694 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9695 if (ag_op != nullptr)
9697 if (noside != EVAL_NORMAL)
9698 return arg1;
9700 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9701 return ada_value_assign (arg1, arg1);
9703 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9704 except if the lhs of our assignment is a convenience variable.
9705 In the case of assigning to a convenience variable, the lhs
9706 should be exactly the result of the evaluation of the rhs. */
9707 struct type *type = arg1->type ();
9708 if (arg1->lval () == lval_internalvar)
9709 type = NULL;
9710 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9711 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9712 return arg1;
9713 if (arg1->lval () == lval_internalvar)
9715 /* Nothing. */
9717 else
9718 arg2 = coerce_for_assign (arg1->type (), arg2);
9719 return ada_value_assign (arg1, arg2);
9722 /* See ada-exp.h. */
9724 void
9725 aggregate_assigner::add_interval (LONGEST from, LONGEST to)
9727 int i, j;
9729 int size = indices.size ();
9730 for (i = 0; i < size; i += 2) {
9731 if (to >= indices[i] && from <= indices[i + 1])
9733 int kh;
9735 for (kh = i + 2; kh < size; kh += 2)
9736 if (to < indices[kh])
9737 break;
9738 if (from < indices[i])
9739 indices[i] = from;
9740 indices[i + 1] = indices[kh - 1];
9741 if (to > indices[i + 1])
9742 indices[i + 1] = to;
9743 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9744 indices.resize (kh - i - 2);
9745 return;
9747 else if (to < indices[i])
9748 break;
9751 indices.resize (indices.size () + 2);
9752 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9753 indices[j] = indices[j - 2];
9754 indices[i] = from;
9755 indices[i + 1] = to;
9758 } /* namespace expr */
9760 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9761 is different. */
9763 static struct value *
9764 ada_value_cast (struct type *type, struct value *arg2)
9766 if (type == ada_check_typedef (arg2->type ()))
9767 return arg2;
9769 return value_cast (type, arg2);
9772 /* Evaluating Ada expressions, and printing their result.
9773 ------------------------------------------------------
9775 1. Introduction:
9776 ----------------
9778 We usually evaluate an Ada expression in order to print its value.
9779 We also evaluate an expression in order to print its type, which
9780 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9781 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9782 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9783 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9784 similar.
9786 Evaluating expressions is a little more complicated for Ada entities
9787 than it is for entities in languages such as C. The main reason for
9788 this is that Ada provides types whose definition might be dynamic.
9789 One example of such types is variant records. Or another example
9790 would be an array whose bounds can only be known at run time.
9792 The following description is a general guide as to what should be
9793 done (and what should NOT be done) in order to evaluate an expression
9794 involving such types, and when. This does not cover how the semantic
9795 information is encoded by GNAT as this is covered separatly. For the
9796 document used as the reference for the GNAT encoding, see exp_dbug.ads
9797 in the GNAT sources.
9799 Ideally, we should embed each part of this description next to its
9800 associated code. Unfortunately, the amount of code is so vast right
9801 now that it's hard to see whether the code handling a particular
9802 situation might be duplicated or not. One day, when the code is
9803 cleaned up, this guide might become redundant with the comments
9804 inserted in the code, and we might want to remove it.
9806 2. ``Fixing'' an Entity, the Simple Case:
9807 -----------------------------------------
9809 When evaluating Ada expressions, the tricky issue is that they may
9810 reference entities whose type contents and size are not statically
9811 known. Consider for instance a variant record:
9813 type Rec (Empty : Boolean := True) is record
9814 case Empty is
9815 when True => null;
9816 when False => Value : Integer;
9817 end case;
9818 end record;
9819 Yes : Rec := (Empty => False, Value => 1);
9820 No : Rec := (empty => True);
9822 The size and contents of that record depends on the value of the
9823 discriminant (Rec.Empty). At this point, neither the debugging
9824 information nor the associated type structure in GDB are able to
9825 express such dynamic types. So what the debugger does is to create
9826 "fixed" versions of the type that applies to the specific object.
9827 We also informally refer to this operation as "fixing" an object,
9828 which means creating its associated fixed type.
9830 Example: when printing the value of variable "Yes" above, its fixed
9831 type would look like this:
9833 type Rec is record
9834 Empty : Boolean;
9835 Value : Integer;
9836 end record;
9838 On the other hand, if we printed the value of "No", its fixed type
9839 would become:
9841 type Rec is record
9842 Empty : Boolean;
9843 end record;
9845 Things become a little more complicated when trying to fix an entity
9846 with a dynamic type that directly contains another dynamic type,
9847 such as an array of variant records, for instance. There are
9848 two possible cases: Arrays, and records.
9850 3. ``Fixing'' Arrays:
9851 ---------------------
9853 The type structure in GDB describes an array in terms of its bounds,
9854 and the type of its elements. By design, all elements in the array
9855 have the same type and we cannot represent an array of variant elements
9856 using the current type structure in GDB. When fixing an array,
9857 we cannot fix the array element, as we would potentially need one
9858 fixed type per element of the array. As a result, the best we can do
9859 when fixing an array is to produce an array whose bounds and size
9860 are correct (allowing us to read it from memory), but without having
9861 touched its element type. Fixing each element will be done later,
9862 when (if) necessary.
9864 Arrays are a little simpler to handle than records, because the same
9865 amount of memory is allocated for each element of the array, even if
9866 the amount of space actually used by each element differs from element
9867 to element. Consider for instance the following array of type Rec:
9869 type Rec_Array is array (1 .. 2) of Rec;
9871 The actual amount of memory occupied by each element might be different
9872 from element to element, depending on the value of their discriminant.
9873 But the amount of space reserved for each element in the array remains
9874 fixed regardless. So we simply need to compute that size using
9875 the debugging information available, from which we can then determine
9876 the array size (we multiply the number of elements of the array by
9877 the size of each element).
9879 The simplest case is when we have an array of a constrained element
9880 type. For instance, consider the following type declarations:
9882 type Bounded_String (Max_Size : Integer) is
9883 Length : Integer;
9884 Buffer : String (1 .. Max_Size);
9885 end record;
9886 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9888 In this case, the compiler describes the array as an array of
9889 variable-size elements (identified by its XVS suffix) for which
9890 the size can be read in the parallel XVZ variable.
9892 In the case of an array of an unconstrained element type, the compiler
9893 wraps the array element inside a private PAD type. This type should not
9894 be shown to the user, and must be "unwrap"'ed before printing. Note
9895 that we also use the adjective "aligner" in our code to designate
9896 these wrapper types.
9898 In some cases, the size allocated for each element is statically
9899 known. In that case, the PAD type already has the correct size,
9900 and the array element should remain unfixed.
9902 But there are cases when this size is not statically known.
9903 For instance, assuming that "Five" is an integer variable:
9905 type Dynamic is array (1 .. Five) of Integer;
9906 type Wrapper (Has_Length : Boolean := False) is record
9907 Data : Dynamic;
9908 case Has_Length is
9909 when True => Length : Integer;
9910 when False => null;
9911 end case;
9912 end record;
9913 type Wrapper_Array is array (1 .. 2) of Wrapper;
9915 Hello : Wrapper_Array := (others => (Has_Length => True,
9916 Data => (others => 17),
9917 Length => 1));
9920 The debugging info would describe variable Hello as being an
9921 array of a PAD type. The size of that PAD type is not statically
9922 known, but can be determined using a parallel XVZ variable.
9923 In that case, a copy of the PAD type with the correct size should
9924 be used for the fixed array.
9926 3. ``Fixing'' record type objects:
9927 ----------------------------------
9929 Things are slightly different from arrays in the case of dynamic
9930 record types. In this case, in order to compute the associated
9931 fixed type, we need to determine the size and offset of each of
9932 its components. This, in turn, requires us to compute the fixed
9933 type of each of these components.
9935 Consider for instance the example:
9937 type Bounded_String (Max_Size : Natural) is record
9938 Str : String (1 .. Max_Size);
9939 Length : Natural;
9940 end record;
9941 My_String : Bounded_String (Max_Size => 10);
9943 In that case, the position of field "Length" depends on the size
9944 of field Str, which itself depends on the value of the Max_Size
9945 discriminant. In order to fix the type of variable My_String,
9946 we need to fix the type of field Str. Therefore, fixing a variant
9947 record requires us to fix each of its components.
9949 However, if a component does not have a dynamic size, the component
9950 should not be fixed. In particular, fields that use a PAD type
9951 should not fixed. Here is an example where this might happen
9952 (assuming type Rec above):
9954 type Container (Big : Boolean) is record
9955 First : Rec;
9956 After : Integer;
9957 case Big is
9958 when True => Another : Integer;
9959 when False => null;
9960 end case;
9961 end record;
9962 My_Container : Container := (Big => False,
9963 First => (Empty => True),
9964 After => 42);
9966 In that example, the compiler creates a PAD type for component First,
9967 whose size is constant, and then positions the component After just
9968 right after it. The offset of component After is therefore constant
9969 in this case.
9971 The debugger computes the position of each field based on an algorithm
9972 that uses, among other things, the actual position and size of the field
9973 preceding it. Let's now imagine that the user is trying to print
9974 the value of My_Container. If the type fixing was recursive, we would
9975 end up computing the offset of field After based on the size of the
9976 fixed version of field First. And since in our example First has
9977 only one actual field, the size of the fixed type is actually smaller
9978 than the amount of space allocated to that field, and thus we would
9979 compute the wrong offset of field After.
9981 To make things more complicated, we need to watch out for dynamic
9982 components of variant records (identified by the ___XVL suffix in
9983 the component name). Even if the target type is a PAD type, the size
9984 of that type might not be statically known. So the PAD type needs
9985 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9986 we might end up with the wrong size for our component. This can be
9987 observed with the following type declarations:
9989 type Octal is new Integer range 0 .. 7;
9990 type Octal_Array is array (Positive range <>) of Octal;
9991 pragma Pack (Octal_Array);
9993 type Octal_Buffer (Size : Positive) is record
9994 Buffer : Octal_Array (1 .. Size);
9995 Length : Integer;
9996 end record;
9998 In that case, Buffer is a PAD type whose size is unset and needs
9999 to be computed by fixing the unwrapped type.
10001 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10002 ----------------------------------------------------------
10004 Lastly, when should the sub-elements of an entity that remained unfixed
10005 thus far, be actually fixed?
10007 The answer is: Only when referencing that element. For instance
10008 when selecting one component of a record, this specific component
10009 should be fixed at that point in time. Or when printing the value
10010 of a record, each component should be fixed before its value gets
10011 printed. Similarly for arrays, the element of the array should be
10012 fixed when printing each element of the array, or when extracting
10013 one element out of that array. On the other hand, fixing should
10014 not be performed on the elements when taking a slice of an array!
10016 Note that one of the side effects of miscomputing the offset and
10017 size of each field is that we end up also miscomputing the size
10018 of the containing type. This can have adverse results when computing
10019 the value of an entity. GDB fetches the value of an entity based
10020 on the size of its type, and thus a wrong size causes GDB to fetch
10021 the wrong amount of memory. In the case where the computed size is
10022 too small, GDB fetches too little data to print the value of our
10023 entity. Results in this case are unpredictable, as we usually read
10024 past the buffer containing the data =:-o. */
10026 /* A helper function for TERNOP_IN_RANGE. */
10028 static value *
10029 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10030 enum noside noside,
10031 value *arg1, value *arg2, value *arg3)
10033 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10034 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10035 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10036 return
10037 value_from_longest (type,
10038 (value_less (arg1, arg3)
10039 || value_equal (arg1, arg3))
10040 && (value_less (arg2, arg1)
10041 || value_equal (arg2, arg1)));
10044 /* A helper function for UNOP_NEG. */
10046 value *
10047 ada_unop_neg (struct type *expect_type,
10048 struct expression *exp,
10049 enum noside noside, enum exp_opcode op,
10050 struct value *arg1)
10052 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10053 return value_neg (arg1);
10056 /* A helper function for UNOP_IN_RANGE. */
10058 value *
10059 ada_unop_in_range (struct type *expect_type,
10060 struct expression *exp,
10061 enum noside noside, enum exp_opcode op,
10062 struct value *arg1, struct type *type)
10064 struct value *arg2, *arg3;
10065 switch (type->code ())
10067 default:
10068 lim_warning (_("Membership test incompletely implemented; "
10069 "always returns true"));
10070 type = language_bool_type (exp->language_defn, exp->gdbarch);
10071 return value_from_longest (type, 1);
10073 case TYPE_CODE_RANGE:
10074 arg2 = value_from_longest (type,
10075 type->bounds ()->low.const_val ());
10076 arg3 = value_from_longest (type,
10077 type->bounds ()->high.const_val ());
10078 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10079 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10080 type = language_bool_type (exp->language_defn, exp->gdbarch);
10081 return
10082 value_from_longest (type,
10083 (value_less (arg1, arg3)
10084 || value_equal (arg1, arg3))
10085 && (value_less (arg2, arg1)
10086 || value_equal (arg2, arg1)));
10090 /* A helper function for OP_ATR_TAG. */
10092 value *
10093 ada_atr_tag (struct type *expect_type,
10094 struct expression *exp,
10095 enum noside noside, enum exp_opcode op,
10096 struct value *arg1)
10098 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10099 return value::zero (ada_tag_type (arg1), not_lval);
10101 return ada_value_tag (arg1);
10104 namespace expr
10107 value *
10108 ada_atr_size_operation::evaluate (struct type *expect_type,
10109 struct expression *exp,
10110 enum noside noside)
10112 bool is_type = std::get<0> (m_storage)->opcode () == OP_TYPE;
10113 bool is_size = std::get<1> (m_storage);
10115 enum noside sub_noside = is_type ? EVAL_AVOID_SIDE_EFFECTS : noside;
10116 value *val = std::get<0> (m_storage)->evaluate (nullptr, exp, sub_noside);
10117 struct type *type = ada_check_typedef (val->type ());
10119 if (is_type)
10121 if (is_size)
10122 error (_("gdb cannot apply 'Size to a type"));
10123 if (is_dynamic_type (type) || find_base_type (type) != nullptr)
10124 error (_("cannot apply 'Object_Size to dynamic type"));
10127 /* If the argument is a reference, then dereference its type, since
10128 the user is really asking for the size of the actual object,
10129 not the size of the pointer. */
10130 if (type->code () == TYPE_CODE_REF)
10131 type = type->target_type ();
10133 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10134 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10135 else
10136 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10137 TARGET_CHAR_BIT * type->length ());
10140 } /* namespace expr */
10142 /* A helper function for UNOP_ABS. */
10144 value *
10145 ada_abs (struct type *expect_type,
10146 struct expression *exp,
10147 enum noside noside, enum exp_opcode op,
10148 struct value *arg1)
10150 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10151 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10152 return value_neg (arg1);
10153 else
10154 return arg1;
10157 /* A helper function for BINOP_MUL. */
10159 value *
10160 ada_mult_binop (struct type *expect_type,
10161 struct expression *exp,
10162 enum noside noside, enum exp_opcode op,
10163 struct value *arg1, struct value *arg2)
10165 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10167 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10168 return value::zero (arg1->type (), not_lval);
10170 else
10172 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10173 return ada_value_binop (arg1, arg2, op);
10177 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10179 value *
10180 ada_equal_binop (struct type *expect_type,
10181 struct expression *exp,
10182 enum noside noside, enum exp_opcode op,
10183 struct value *arg1, struct value *arg2)
10185 int tem;
10186 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10187 tem = 0;
10188 else
10190 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10191 tem = ada_value_equal (arg1, arg2);
10193 if (op == BINOP_NOTEQUAL)
10194 tem = !tem;
10195 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10196 return value_from_longest (type, tem);
10199 /* A helper function for TERNOP_SLICE. */
10201 value *
10202 ada_ternop_slice (struct expression *exp,
10203 enum noside noside,
10204 struct value *array, struct value *low_bound_val,
10205 struct value *high_bound_val)
10207 LONGEST low_bound;
10208 LONGEST high_bound;
10210 low_bound_val = coerce_ref (low_bound_val);
10211 high_bound_val = coerce_ref (high_bound_val);
10212 low_bound = value_as_long (low_bound_val);
10213 high_bound = value_as_long (high_bound_val);
10215 /* If this is a reference to an aligner type, then remove all
10216 the aligners. */
10217 if (array->type ()->code () == TYPE_CODE_REF
10218 && ada_is_aligner_type (array->type ()->target_type ()))
10219 array->type ()->set_target_type
10220 (ada_aligned_type (array->type ()->target_type ()));
10222 if (ada_is_any_packed_array_type (array->type ()))
10223 error (_("cannot slice a packed array"));
10225 /* If this is a reference to an array or an array lvalue,
10226 convert to a pointer. */
10227 if (array->type ()->code () == TYPE_CODE_REF
10228 || (array->type ()->code () == TYPE_CODE_ARRAY
10229 && array->lval () == lval_memory))
10230 array = value_addr (array);
10232 if (noside == EVAL_AVOID_SIDE_EFFECTS
10233 && ada_is_array_descriptor_type (ada_check_typedef
10234 (array->type ())))
10235 return empty_array (ada_type_of_array (array, 0), low_bound,
10236 high_bound);
10238 array = ada_coerce_to_simple_array_ptr (array);
10240 /* If we have more than one level of pointer indirection,
10241 dereference the value until we get only one level. */
10242 while (array->type ()->code () == TYPE_CODE_PTR
10243 && (array->type ()->target_type ()->code ()
10244 == TYPE_CODE_PTR))
10245 array = value_ind (array);
10247 /* Make sure we really do have an array type before going further,
10248 to avoid a SEGV when trying to get the index type or the target
10249 type later down the road if the debug info generated by
10250 the compiler is incorrect or incomplete. */
10251 if (!ada_is_simple_array_type (array->type ()))
10252 error (_("cannot take slice of non-array"));
10254 if (ada_check_typedef (array->type ())->code ()
10255 == TYPE_CODE_PTR)
10257 struct type *type0 = ada_check_typedef (array->type ());
10259 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10260 return empty_array (type0->target_type (), low_bound, high_bound);
10261 else
10263 struct type *arr_type0 =
10264 to_fixed_array_type (type0->target_type (), NULL, 1);
10266 return ada_value_slice_from_ptr (array, arr_type0,
10267 longest_to_int (low_bound),
10268 longest_to_int (high_bound));
10271 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10272 return array;
10273 else if (high_bound < low_bound)
10274 return empty_array (array->type (), low_bound, high_bound);
10275 else
10276 return ada_value_slice (array, longest_to_int (low_bound),
10277 longest_to_int (high_bound));
10280 /* A helper function for BINOP_IN_BOUNDS. */
10282 value *
10283 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10284 struct value *arg1, struct value *arg2, int n)
10286 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10288 struct type *type = language_bool_type (exp->language_defn,
10289 exp->gdbarch);
10290 return value::zero (type, not_lval);
10293 struct type *type = ada_index_type (arg2->type (), n, "range");
10294 if (!type)
10295 type = arg1->type ();
10297 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10298 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10300 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10301 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10302 type = language_bool_type (exp->language_defn, exp->gdbarch);
10303 return value_from_longest (type,
10304 (value_less (arg1, arg3)
10305 || value_equal (arg1, arg3))
10306 && (value_less (arg2, arg1)
10307 || value_equal (arg2, arg1)));
10310 /* A helper function for some attribute operations. */
10312 static value *
10313 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10314 struct value *arg1, struct type *type_arg, int tem)
10316 const char *attr_name = nullptr;
10317 if (op == OP_ATR_FIRST)
10318 attr_name = "first";
10319 else if (op == OP_ATR_LAST)
10320 attr_name = "last";
10322 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10324 if (type_arg == NULL)
10325 type_arg = arg1->type ();
10327 if (ada_is_constrained_packed_array_type (type_arg))
10328 type_arg = decode_constrained_packed_array_type (type_arg);
10330 if (!discrete_type_p (type_arg))
10332 switch (op)
10334 default: /* Should never happen. */
10335 error (_("unexpected attribute encountered"));
10336 case OP_ATR_FIRST:
10337 case OP_ATR_LAST:
10338 type_arg = ada_index_type (type_arg, tem,
10339 attr_name);
10340 break;
10341 case OP_ATR_LENGTH:
10342 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10343 break;
10347 return value::zero (type_arg, not_lval);
10349 else if (type_arg == NULL)
10351 arg1 = ada_coerce_ref (arg1);
10353 if (ada_is_constrained_packed_array_type (arg1->type ()))
10354 arg1 = ada_coerce_to_simple_array (arg1);
10356 struct type *type;
10357 if (op == OP_ATR_LENGTH)
10358 type = builtin_type (exp->gdbarch)->builtin_int;
10359 else
10361 type = ada_index_type (arg1->type (), tem,
10362 attr_name);
10363 if (type == NULL)
10364 type = builtin_type (exp->gdbarch)->builtin_int;
10367 switch (op)
10369 default: /* Should never happen. */
10370 error (_("unexpected attribute encountered"));
10371 case OP_ATR_FIRST:
10372 return value_from_longest
10373 (type, ada_array_bound (arg1, tem, 0));
10374 case OP_ATR_LAST:
10375 return value_from_longest
10376 (type, ada_array_bound (arg1, tem, 1));
10377 case OP_ATR_LENGTH:
10378 return value_from_longest
10379 (type, ada_array_length (arg1, tem));
10382 else if (discrete_type_p (type_arg))
10384 struct type *range_type;
10385 const char *name = ada_type_name (type_arg);
10387 range_type = NULL;
10388 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10389 range_type = to_fixed_range_type (type_arg, NULL);
10390 if (range_type == NULL)
10391 range_type = type_arg;
10392 switch (op)
10394 default:
10395 error (_("unexpected attribute encountered"));
10396 case OP_ATR_FIRST:
10397 return value_from_longest
10398 (range_type, ada_discrete_type_low_bound (range_type));
10399 case OP_ATR_LAST:
10400 return value_from_longest
10401 (range_type, ada_discrete_type_high_bound (range_type));
10402 case OP_ATR_LENGTH:
10403 error (_("the 'length attribute applies only to array types"));
10406 else if (type_arg->code () == TYPE_CODE_FLT)
10407 error (_("unimplemented type attribute"));
10408 else
10410 LONGEST low, high;
10412 if (ada_is_constrained_packed_array_type (type_arg))
10413 type_arg = decode_constrained_packed_array_type (type_arg);
10415 struct type *type;
10416 if (op == OP_ATR_LENGTH)
10417 type = builtin_type (exp->gdbarch)->builtin_int;
10418 else
10420 type = ada_index_type (type_arg, tem, attr_name);
10421 if (type == NULL)
10422 type = builtin_type (exp->gdbarch)->builtin_int;
10425 switch (op)
10427 default:
10428 error (_("unexpected attribute encountered"));
10429 case OP_ATR_FIRST:
10430 low = ada_array_bound_from_type (type_arg, tem, 0);
10431 return value_from_longest (type, low);
10432 case OP_ATR_LAST:
10433 high = ada_array_bound_from_type (type_arg, tem, 1);
10434 return value_from_longest (type, high);
10435 case OP_ATR_LENGTH:
10436 low = ada_array_bound_from_type (type_arg, tem, 0);
10437 high = ada_array_bound_from_type (type_arg, tem, 1);
10438 return value_from_longest (type, high - low + 1);
10443 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10445 struct value *
10446 ada_binop_minmax (struct type *expect_type,
10447 struct expression *exp,
10448 enum noside noside, enum exp_opcode op,
10449 struct value *arg1, struct value *arg2)
10451 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10452 return value::zero (arg1->type (), not_lval);
10453 else
10455 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10456 return value_binop (arg1, arg2, op);
10460 /* A helper function for BINOP_EXP. */
10462 struct value *
10463 ada_binop_exp (struct type *expect_type,
10464 struct expression *exp,
10465 enum noside noside, enum exp_opcode op,
10466 struct value *arg1, struct value *arg2)
10468 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10469 return value::zero (arg1->type (), not_lval);
10470 else
10472 /* For integer exponentiation operations,
10473 only promote the first argument. */
10474 if (is_integral_type (arg2->type ()))
10475 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10476 else
10477 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10479 return value_binop (arg1, arg2, op);
10483 namespace expr
10486 /* See ada-exp.h. */
10488 operation_up
10489 ada_resolvable::replace (operation_up &&owner,
10490 struct expression *exp,
10491 bool deprocedure_p,
10492 bool parse_completion,
10493 innermost_block_tracker *tracker,
10494 struct type *context_type)
10496 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10497 return (make_operation<ada_funcall_operation>
10498 (std::move (owner),
10499 std::vector<operation_up> ()));
10500 return std::move (owner);
10503 /* Convert the character literal whose value would be VAL to the
10504 appropriate value of type TYPE, if there is a translation.
10505 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10506 the literal 'A' (VAL == 65), returns 0. */
10508 static LONGEST
10509 convert_char_literal (struct type *type, LONGEST val)
10511 char name[12];
10512 int f;
10514 if (type == NULL)
10515 return val;
10516 type = check_typedef (type);
10517 if (type->code () != TYPE_CODE_ENUM)
10518 return val;
10520 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10521 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10522 else if (val >= 0 && val < 256)
10523 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10524 else if (val >= 0 && val < 0x10000)
10525 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10526 else
10527 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10528 size_t len = strlen (name);
10529 for (f = 0; f < type->num_fields (); f += 1)
10531 /* Check the suffix because an enum constant in a package will
10532 have a name like "pkg__QUxx". This is safe enough because we
10533 already have the correct type, and because mangling means
10534 there can't be clashes. */
10535 const char *ename = type->field (f).name ();
10536 size_t elen = strlen (ename);
10538 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10539 return type->field (f).loc_enumval ();
10541 return val;
10544 value *
10545 ada_char_operation::evaluate (struct type *expect_type,
10546 struct expression *exp,
10547 enum noside noside)
10549 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10550 if (expect_type != nullptr)
10551 result = ada_value_cast (expect_type, result);
10552 return result;
10555 /* See ada-exp.h. */
10557 operation_up
10558 ada_char_operation::replace (operation_up &&owner,
10559 struct expression *exp,
10560 bool deprocedure_p,
10561 bool parse_completion,
10562 innermost_block_tracker *tracker,
10563 struct type *context_type)
10565 operation_up result = std::move (owner);
10567 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10569 LONGEST val = as_longest ();
10570 gdb_assert (result.get () == this);
10571 std::get<0> (m_storage) = context_type;
10572 std::get<1> (m_storage) = convert_char_literal (context_type, val);
10575 return result;
10578 value *
10579 ada_wrapped_operation::evaluate (struct type *expect_type,
10580 struct expression *exp,
10581 enum noside noside)
10583 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10584 if (noside == EVAL_NORMAL)
10585 result = unwrap_value (result);
10587 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10588 then we need to perform the conversion manually, because
10589 evaluate_subexp_standard doesn't do it. This conversion is
10590 necessary in Ada because the different kinds of float/fixed
10591 types in Ada have different representations.
10593 Similarly, we need to perform the conversion from OP_LONG
10594 ourselves. */
10595 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10596 result = ada_value_cast (expect_type, result);
10598 return result;
10601 void
10602 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10603 struct agent_expr *ax,
10604 struct axs_value *value,
10605 struct type *cast_type)
10607 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10609 struct type *type = value->type;
10610 if (ada_is_aligner_type (type))
10611 error (_("Aligner types cannot be handled in agent expressions"));
10612 else if (find_base_type (type) != nullptr)
10613 error (_("Dynamic types cannot be handled in agent expressions"));
10616 value *
10617 ada_string_operation::evaluate (struct type *expect_type,
10618 struct expression *exp,
10619 enum noside noside)
10621 struct type *char_type;
10622 if (expect_type != nullptr && ada_is_string_type (expect_type))
10623 char_type = ada_array_element_type (expect_type, 1);
10624 else
10625 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10627 const std::string &str = std::get<0> (m_storage);
10628 const char *encoding;
10629 switch (char_type->length ())
10631 case 1:
10633 /* Simply copy over the data -- this isn't perhaps strictly
10634 correct according to the encodings, but it is gdb's
10635 historical behavior. */
10636 struct type *stringtype
10637 = lookup_array_range_type (char_type, 1, str.length ());
10638 struct value *val = value::allocate (stringtype);
10639 memcpy (val->contents_raw ().data (), str.c_str (),
10640 str.length ());
10641 return val;
10644 case 2:
10645 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10646 encoding = "UTF-16BE";
10647 else
10648 encoding = "UTF-16LE";
10649 break;
10651 case 4:
10652 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10653 encoding = "UTF-32BE";
10654 else
10655 encoding = "UTF-32LE";
10656 break;
10658 default:
10659 error (_("unexpected character type size %s"),
10660 pulongest (char_type->length ()));
10663 auto_obstack converted;
10664 convert_between_encodings (host_charset (), encoding,
10665 (const gdb_byte *) str.c_str (),
10666 str.length (), 1,
10667 &converted, translit_none);
10669 struct type *stringtype
10670 = lookup_array_range_type (char_type, 1,
10671 obstack_object_size (&converted)
10672 / char_type->length ());
10673 struct value *val = value::allocate (stringtype);
10674 memcpy (val->contents_raw ().data (),
10675 obstack_base (&converted),
10676 obstack_object_size (&converted));
10677 return val;
10680 value *
10681 ada_concat_operation::evaluate (struct type *expect_type,
10682 struct expression *exp,
10683 enum noside noside)
10685 /* If one side is a literal, evaluate the other side first so that
10686 the expected type can be set properly. */
10687 const operation_up &lhs_expr = std::get<0> (m_storage);
10688 const operation_up &rhs_expr = std::get<1> (m_storage);
10690 value *lhs, *rhs;
10691 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10693 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10694 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10696 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10698 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10699 struct type *rhs_type = check_typedef (rhs->type ());
10700 struct type *elt_type = nullptr;
10701 if (rhs_type->code () == TYPE_CODE_ARRAY)
10702 elt_type = rhs_type->target_type ();
10703 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10705 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10707 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10708 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10710 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10712 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10713 struct type *lhs_type = check_typedef (lhs->type ());
10714 struct type *elt_type = nullptr;
10715 if (lhs_type->code () == TYPE_CODE_ARRAY)
10716 elt_type = lhs_type->target_type ();
10717 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10719 else
10720 return concat_operation::evaluate (expect_type, exp, noside);
10722 return value_concat (lhs, rhs);
10725 value *
10726 ada_qual_operation::evaluate (struct type *expect_type,
10727 struct expression *exp,
10728 enum noside noside)
10730 struct type *type = std::get<1> (m_storage);
10731 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10734 value *
10735 ada_ternop_range_operation::evaluate (struct type *expect_type,
10736 struct expression *exp,
10737 enum noside noside)
10739 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10740 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10741 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10742 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10745 value *
10746 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10747 struct expression *exp,
10748 enum noside noside)
10750 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10751 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10753 auto do_op = [this] (LONGEST x, LONGEST y)
10755 if (std::get<0> (m_storage) == BINOP_ADD)
10756 return x + y;
10757 return x - y;
10760 if (arg1->type ()->code () == TYPE_CODE_PTR)
10761 return (value_from_longest
10762 (arg1->type (),
10763 do_op (value_as_long (arg1), value_as_long (arg2))));
10764 if (arg2->type ()->code () == TYPE_CODE_PTR)
10765 return (value_from_longest
10766 (arg2->type (),
10767 do_op (value_as_long (arg1), value_as_long (arg2))));
10768 /* Preserve the original type for use by the range case below.
10769 We cannot cast the result to a reference type, so if ARG1 is
10770 a reference type, find its underlying type. */
10771 struct type *type = arg1->type ();
10772 while (type->code () == TYPE_CODE_REF)
10773 type = type->target_type ();
10774 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10775 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10776 /* We need to special-case the result with a range.
10777 This is done for the benefit of "ptype". gdb's Ada support
10778 historically used the LHS to set the result type here, so
10779 preserve this behavior. */
10780 if (type->code () == TYPE_CODE_RANGE)
10781 arg1 = value_cast (type, arg1);
10782 return arg1;
10785 value *
10786 ada_unop_atr_operation::evaluate (struct type *expect_type,
10787 struct expression *exp,
10788 enum noside noside)
10790 struct type *type_arg = nullptr;
10791 value *val = nullptr;
10793 if (std::get<0> (m_storage)->type_p ())
10795 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10796 EVAL_AVOID_SIDE_EFFECTS);
10797 type_arg = tem->type ();
10799 else
10800 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10802 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10803 val, type_arg, std::get<2> (m_storage));
10806 value *
10807 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10808 struct expression *exp,
10809 enum noside noside)
10811 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10812 return value::zero (expect_type, not_lval);
10814 const bound_minimal_symbol &b = std::get<0> (m_storage);
10815 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10817 val = ada_value_cast (expect_type, val);
10819 /* Follow the Ada language semantics that do not allow taking
10820 an address of the result of a cast (view conversion in Ada). */
10821 if (val->lval () == lval_memory)
10823 if (val->lazy ())
10824 val->fetch_lazy ();
10825 val->set_lval (not_lval);
10827 return val;
10830 value *
10831 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10832 struct expression *exp,
10833 enum noside noside)
10835 value *val = evaluate_var_value (noside,
10836 std::get<0> (m_storage).block,
10837 std::get<0> (m_storage).symbol);
10839 val = ada_value_cast (expect_type, val);
10841 /* Follow the Ada language semantics that do not allow taking
10842 an address of the result of a cast (view conversion in Ada). */
10843 if (val->lval () == lval_memory)
10845 if (val->lazy ())
10846 val->fetch_lazy ();
10847 val->set_lval (not_lval);
10849 return val;
10852 value *
10853 ada_var_value_operation::evaluate (struct type *expect_type,
10854 struct expression *exp,
10855 enum noside noside)
10857 symbol *sym = std::get<0> (m_storage).symbol;
10859 if (sym->domain () == UNDEF_DOMAIN)
10860 /* Only encountered when an unresolved symbol occurs in a
10861 context other than a function call, in which case, it is
10862 invalid. */
10863 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10864 sym->print_name ());
10866 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10868 struct type *type = static_unwrap_type (sym->type ());
10869 /* Check to see if this is a tagged type. We also need to handle
10870 the case where the type is a reference to a tagged type, but
10871 we have to be careful to exclude pointers to tagged types.
10872 The latter should be shown as usual (as a pointer), whereas
10873 a reference should mostly be transparent to the user. */
10874 if (ada_is_tagged_type (type, 0)
10875 || (type->code () == TYPE_CODE_REF
10876 && ada_is_tagged_type (type->target_type (), 0)))
10878 /* Tagged types are a little special in the fact that the real
10879 type is dynamic and can only be determined by inspecting the
10880 object's tag. This means that we need to get the object's
10881 value first (EVAL_NORMAL) and then extract the actual object
10882 type from its tag.
10884 Note that we cannot skip the final step where we extract
10885 the object type from its tag, because the EVAL_NORMAL phase
10886 results in dynamic components being resolved into fixed ones.
10887 This can cause problems when trying to print the type
10888 description of tagged types whose parent has a dynamic size:
10889 We use the type name of the "_parent" component in order
10890 to print the name of the ancestor type in the type description.
10891 If that component had a dynamic size, the resolution into
10892 a fixed type would result in the loss of that type name,
10893 thus preventing us from printing the name of the ancestor
10894 type in the type description. */
10895 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10897 if (type->code () != TYPE_CODE_REF)
10899 struct type *actual_type;
10901 actual_type = type_from_tag (ada_value_tag (arg1));
10902 if (actual_type == NULL)
10903 /* If, for some reason, we were unable to determine
10904 the actual type from the tag, then use the static
10905 approximation that we just computed as a fallback.
10906 This can happen if the debugging information is
10907 incomplete, for instance. */
10908 actual_type = type;
10909 return value::zero (actual_type, not_lval);
10911 else
10913 /* In the case of a ref, ada_coerce_ref takes care
10914 of determining the actual type. But the evaluation
10915 should return a ref as it should be valid to ask
10916 for its address; so rebuild a ref after coerce. */
10917 arg1 = ada_coerce_ref (arg1);
10918 return value_ref (arg1, TYPE_CODE_REF);
10922 /* Records and unions for which GNAT encodings have been
10923 generated need to be statically fixed as well.
10924 Otherwise, non-static fixing produces a type where
10925 all dynamic properties are removed, which prevents "ptype"
10926 from being able to completely describe the type.
10927 For instance, a case statement in a variant record would be
10928 replaced by the relevant components based on the actual
10929 value of the discriminants. */
10930 if ((type->code () == TYPE_CODE_STRUCT
10931 && dynamic_template_type (type) != NULL)
10932 || (type->code () == TYPE_CODE_UNION
10933 && ada_find_parallel_type (type, "___XVU") != NULL))
10934 return value::zero (to_static_fixed_type (type), not_lval);
10937 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10938 return ada_to_fixed_value (arg1);
10941 bool
10942 ada_var_value_operation::resolve (struct expression *exp,
10943 bool deprocedure_p,
10944 bool parse_completion,
10945 innermost_block_tracker *tracker,
10946 struct type *context_type)
10948 symbol *sym = std::get<0> (m_storage).symbol;
10949 if (sym->domain () == UNDEF_DOMAIN)
10951 block_symbol resolved
10952 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10953 context_type, parse_completion,
10954 deprocedure_p, tracker);
10955 std::get<0> (m_storage) = resolved;
10958 if (deprocedure_p
10959 && (std::get<0> (m_storage).symbol->type ()->code ()
10960 == TYPE_CODE_FUNC))
10961 return true;
10963 return false;
10966 void
10967 ada_var_value_operation::do_generate_ax (struct expression *exp,
10968 struct agent_expr *ax,
10969 struct axs_value *value,
10970 struct type *cast_type)
10972 symbol *sym = std::get<0> (m_storage).symbol;
10974 if (sym->domain () == UNDEF_DOMAIN)
10975 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10976 sym->print_name ());
10978 struct type *type = static_unwrap_type (sym->type ());
10979 if (ada_is_tagged_type (type, 0)
10980 || (type->code () == TYPE_CODE_REF
10981 && ada_is_tagged_type (type->target_type (), 0)))
10982 error (_("Tagged types cannot be handled in agent expressions"));
10984 if ((type->code () == TYPE_CODE_STRUCT
10985 && dynamic_template_type (type) != NULL)
10986 || (type->code () == TYPE_CODE_UNION
10987 && ada_find_parallel_type (type, "___XVU") != NULL))
10988 error (_("Dynamic types cannot be handled in agent expressions"));
10990 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10993 value *
10994 ada_unop_ind_operation::evaluate (struct type *expect_type,
10995 struct expression *exp,
10996 enum noside noside)
10998 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11000 struct type *type = ada_check_typedef (arg1->type ());
11001 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11003 if (ada_is_array_descriptor_type (type))
11005 /* GDB allows dereferencing GNAT array descriptors.
11006 However, for 'ptype' we don't want to try to
11007 "dereference" a thick pointer here -- that will end up
11008 giving us an array with (1 .. 0) for bounds, which is
11009 less clear than (<>). */
11010 struct type *arrType = ada_type_of_array (arg1, 0);
11012 if (arrType == NULL)
11013 error (_("Attempt to dereference null array pointer."));
11014 if (is_thick_pntr (type))
11015 return arg1;
11016 return value_at_lazy (arrType, 0);
11018 else if (type->code () == TYPE_CODE_PTR
11019 || type->code () == TYPE_CODE_REF
11020 /* In C you can dereference an array to get the 1st elt. */
11021 || type->code () == TYPE_CODE_ARRAY)
11023 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11024 only be determined by inspecting the object's tag.
11025 This means that we need to evaluate completely the
11026 expression in order to get its type. */
11028 if ((type->code () == TYPE_CODE_REF
11029 || type->code () == TYPE_CODE_PTR)
11030 && ada_is_tagged_type (type->target_type (), 0))
11032 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11033 EVAL_NORMAL);
11034 type = ada_value_ind (arg1)->type ();
11036 else
11038 type = to_static_fixed_type
11039 (ada_aligned_type
11040 (ada_check_typedef (type->target_type ())));
11042 return value::zero (type, lval_memory);
11044 else if (type->code () == TYPE_CODE_INT)
11046 /* GDB allows dereferencing an int. */
11047 if (expect_type == NULL)
11048 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11049 lval_memory);
11050 else
11052 expect_type =
11053 to_static_fixed_type (ada_aligned_type (expect_type));
11054 return value::zero (expect_type, lval_memory);
11057 else
11058 error (_("Attempt to take contents of a non-pointer value."));
11060 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11061 type = ada_check_typedef (arg1->type ());
11063 if (type->code () == TYPE_CODE_INT)
11064 /* GDB allows dereferencing an int. If we were given
11065 the expect_type, then use that as the target type.
11066 Otherwise, assume that the target type is an int. */
11068 if (expect_type != NULL)
11069 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11070 arg1));
11071 else
11072 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11073 value_as_address (arg1));
11076 if (ada_is_array_descriptor_type (type))
11077 /* GDB allows dereferencing GNAT array descriptors. */
11078 return ada_coerce_to_simple_array (arg1);
11079 else
11080 return ada_value_ind (arg1);
11083 value *
11084 ada_structop_operation::evaluate (struct type *expect_type,
11085 struct expression *exp,
11086 enum noside noside)
11088 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11089 const char *str = std::get<1> (m_storage).c_str ();
11090 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11092 struct type *type;
11093 struct type *type1 = arg1->type ();
11095 if (ada_is_tagged_type (type1, 1))
11097 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11099 /* If the field is not found, check if it exists in the
11100 extension of this object's type. This means that we
11101 need to evaluate completely the expression. */
11103 if (type == NULL)
11105 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11106 EVAL_NORMAL);
11107 arg1 = ada_value_struct_elt (arg1, str, 0);
11108 arg1 = unwrap_value (arg1);
11109 type = ada_to_fixed_value (arg1)->type ();
11112 else
11113 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11115 return value::zero (ada_aligned_type (type), lval_memory);
11117 else
11119 arg1 = ada_value_struct_elt (arg1, str, 0);
11120 arg1 = unwrap_value (arg1);
11121 return ada_to_fixed_value (arg1);
11125 value *
11126 ada_funcall_operation::evaluate (struct type *expect_type,
11127 struct expression *exp,
11128 enum noside noside)
11130 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11131 int nargs = args_up.size ();
11132 std::vector<value *> argvec (nargs);
11133 operation_up &callee_op = std::get<0> (m_storage);
11135 ada_var_value_operation *avv
11136 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11137 if (avv != nullptr
11138 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11139 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11140 avv->get_symbol ()->print_name ());
11142 value *callee = callee_op->evaluate (nullptr, exp, noside);
11143 for (int i = 0; i < args_up.size (); ++i)
11144 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11146 if (ada_is_constrained_packed_array_type
11147 (desc_base_type (callee->type ())))
11148 callee = ada_coerce_to_simple_array (callee);
11149 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11150 && callee->type ()->field (0).bitsize () != 0)
11151 /* This is a packed array that has already been fixed, and
11152 therefore already coerced to a simple array. Nothing further
11153 to do. */
11155 else if (callee->type ()->code () == TYPE_CODE_REF)
11157 /* Make sure we dereference references so that all the code below
11158 feels like it's really handling the referenced value. Wrapping
11159 types (for alignment) may be there, so make sure we strip them as
11160 well. */
11161 callee = ada_to_fixed_value (coerce_ref (callee));
11163 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11164 && callee->lval () == lval_memory)
11165 callee = value_addr (callee);
11167 struct type *type = ada_check_typedef (callee->type ());
11169 /* Ada allows us to implicitly dereference arrays when subscripting
11170 them. So, if this is an array typedef (encoding use for array
11171 access types encoded as fat pointers), strip it now. */
11172 if (type->code () == TYPE_CODE_TYPEDEF)
11173 type = ada_typedef_target_type (type);
11175 if (type->code () == TYPE_CODE_PTR)
11177 switch (ada_check_typedef (type->target_type ())->code ())
11179 case TYPE_CODE_FUNC:
11180 type = ada_check_typedef (type->target_type ());
11181 break;
11182 case TYPE_CODE_ARRAY:
11183 break;
11184 case TYPE_CODE_STRUCT:
11185 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11186 callee = ada_value_ind (callee);
11187 type = ada_check_typedef (type->target_type ());
11188 break;
11189 default:
11190 error (_("cannot subscript or call something of type `%s'"),
11191 ada_type_name (callee->type ()));
11192 break;
11196 switch (type->code ())
11198 case TYPE_CODE_FUNC:
11199 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11201 if (type->target_type () == NULL)
11202 error_call_unknown_return_type (NULL);
11203 return value::allocate (type->target_type ());
11205 return call_function_by_hand (callee, expect_type, argvec);
11206 case TYPE_CODE_INTERNAL_FUNCTION:
11207 return call_internal_function (exp->gdbarch, exp->language_defn,
11208 callee, nargs,
11209 argvec.data (), noside);
11211 case TYPE_CODE_STRUCT:
11213 int arity;
11215 arity = ada_array_arity (type);
11216 type = ada_array_element_type (type, nargs);
11217 if (type == NULL)
11218 error (_("cannot subscript or call a record"));
11219 if (arity != nargs)
11220 error (_("wrong number of subscripts; expecting %d"), arity);
11221 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11222 return value::zero (ada_aligned_type (type), lval_memory);
11223 return
11224 unwrap_value (ada_value_subscript
11225 (callee, nargs, argvec.data ()));
11227 case TYPE_CODE_ARRAY:
11228 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11230 type = ada_array_element_type (type, nargs);
11231 if (type == NULL)
11232 error (_("element type of array unknown"));
11233 else
11234 return value::zero (ada_aligned_type (type), lval_memory);
11236 return
11237 unwrap_value (ada_value_subscript
11238 (ada_coerce_to_simple_array (callee),
11239 nargs, argvec.data ()));
11240 case TYPE_CODE_PTR: /* Pointer to array */
11241 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11243 type = to_fixed_array_type (type->target_type (), NULL, 1);
11244 type = ada_array_element_type (type, nargs);
11245 if (type == NULL)
11246 error (_("element type of array unknown"));
11247 else
11248 return value::zero (ada_aligned_type (type), lval_memory);
11250 return
11251 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11252 argvec.data ()));
11254 default:
11255 error (_("Attempt to index or call something other than an "
11256 "array or function"));
11260 bool
11261 ada_funcall_operation::resolve (struct expression *exp,
11262 bool deprocedure_p,
11263 bool parse_completion,
11264 innermost_block_tracker *tracker,
11265 struct type *context_type)
11267 operation_up &callee_op = std::get<0> (m_storage);
11269 ada_var_value_operation *avv
11270 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11271 if (avv == nullptr)
11272 return false;
11274 symbol *sym = avv->get_symbol ();
11275 if (sym->domain () != UNDEF_DOMAIN)
11276 return false;
11278 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11279 int nargs = args_up.size ();
11280 std::vector<value *> argvec (nargs);
11282 for (int i = 0; i < args_up.size (); ++i)
11283 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11285 const block *block = avv->get_block ();
11286 block_symbol resolved
11287 = ada_resolve_funcall (sym, block,
11288 context_type, parse_completion,
11289 nargs, argvec.data (),
11290 tracker);
11292 std::get<0> (m_storage)
11293 = make_operation<ada_var_value_operation> (resolved);
11294 return false;
11297 bool
11298 ada_ternop_slice_operation::resolve (struct expression *exp,
11299 bool deprocedure_p,
11300 bool parse_completion,
11301 innermost_block_tracker *tracker,
11302 struct type *context_type)
11304 /* Historically this check was done during resolution, so we
11305 continue that here. */
11306 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11307 EVAL_AVOID_SIDE_EFFECTS);
11308 if (ada_is_any_packed_array_type (v->type ()))
11309 error (_("cannot slice a packed array"));
11310 return false;
11317 /* Return non-zero iff TYPE represents a System.Address type. */
11320 ada_is_system_address_type (struct type *type)
11322 return (type->name () && strcmp (type->name (), "system__address") == 0);
11327 /* Range types */
11329 /* Scan STR beginning at position K for a discriminant name, and
11330 return the value of that discriminant field of DVAL in *PX. If
11331 PNEW_K is not null, put the position of the character beyond the
11332 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11333 not alter *PX and *PNEW_K if unsuccessful. */
11335 static int
11336 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11337 int *pnew_k)
11339 static std::string storage;
11340 const char *pstart, *pend, *bound;
11341 struct value *bound_val;
11343 if (dval == NULL || str == NULL || str[k] == '\0')
11344 return 0;
11346 pstart = str + k;
11347 pend = strstr (pstart, "__");
11348 if (pend == NULL)
11350 bound = pstart;
11351 k += strlen (bound);
11353 else
11355 int len = pend - pstart;
11357 /* Strip __ and beyond. */
11358 storage = std::string (pstart, len);
11359 bound = storage.c_str ();
11360 k = pend - str;
11363 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11364 if (bound_val == NULL)
11365 return 0;
11367 *px = value_as_long (bound_val);
11368 if (pnew_k != NULL)
11369 *pnew_k = k;
11370 return 1;
11373 /* Value of variable named NAME. Only exact matches are considered.
11374 If no such variable found, then if ERR_MSG is null, returns 0, and
11375 otherwise causes an error with message ERR_MSG. */
11377 static struct value *
11378 get_var_value (const char *name, const char *err_msg)
11380 std::string quoted_name = add_angle_brackets (name);
11382 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11384 std::vector<struct block_symbol> syms
11385 = ada_lookup_symbol_list_worker (lookup_name,
11386 get_selected_block (0),
11387 SEARCH_VFT, 1);
11389 if (syms.size () != 1)
11391 if (err_msg == NULL)
11392 return 0;
11393 else
11394 error (("%s"), err_msg);
11397 return value_of_variable (syms[0].symbol, syms[0].block);
11400 /* Value of integer variable named NAME in the current environment.
11401 If no such variable is found, returns false. Otherwise, sets VALUE
11402 to the variable's value and returns true. */
11404 bool
11405 get_int_var_value (const char *name, LONGEST &value)
11407 struct value *var_val = get_var_value (name, 0);
11409 if (var_val == 0)
11410 return false;
11412 value = value_as_long (var_val);
11413 return true;
11417 /* Return a range type whose base type is that of the range type named
11418 NAME in the current environment, and whose bounds are calculated
11419 from NAME according to the GNAT range encoding conventions.
11420 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11421 corresponding range type from debug information; fall back to using it
11422 if symbol lookup fails. If a new type must be created, allocate it
11423 like ORIG_TYPE was. The bounds information, in general, is encoded
11424 in NAME, the base type given in the named range type. */
11426 static struct type *
11427 to_fixed_range_type (struct type *raw_type, struct value *dval)
11429 const char *name;
11430 struct type *base_type;
11431 const char *subtype_info;
11433 gdb_assert (raw_type != NULL);
11434 gdb_assert (raw_type->name () != NULL);
11436 if (raw_type->code () == TYPE_CODE_RANGE)
11437 base_type = raw_type->target_type ();
11438 else
11439 base_type = raw_type;
11441 name = raw_type->name ();
11442 subtype_info = strstr (name, "___XD");
11443 if (subtype_info == NULL)
11445 LONGEST L = ada_discrete_type_low_bound (raw_type);
11446 LONGEST U = ada_discrete_type_high_bound (raw_type);
11448 if (L < INT_MIN || U > INT_MAX)
11449 return raw_type;
11450 else
11452 type_allocator alloc (raw_type);
11453 return create_static_range_type (alloc, raw_type, L, U);
11456 else
11458 int prefix_len = subtype_info - name;
11459 LONGEST L, U;
11460 struct type *type;
11461 const char *bounds_str;
11462 int n;
11464 subtype_info += 5;
11465 bounds_str = strchr (subtype_info, '_');
11466 n = 1;
11468 if (*subtype_info == 'L')
11470 if (!ada_scan_number (bounds_str, n, &L, &n)
11471 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11472 return raw_type;
11473 if (bounds_str[n] == '_')
11474 n += 2;
11475 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11476 n += 1;
11477 subtype_info += 1;
11479 else
11481 std::string name_buf = std::string (name, prefix_len) + "___L";
11482 if (!get_int_var_value (name_buf.c_str (), L))
11484 lim_warning (_("Unknown lower bound, using 1."));
11485 L = 1;
11489 if (*subtype_info == 'U')
11491 if (!ada_scan_number (bounds_str, n, &U, &n)
11492 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11493 return raw_type;
11495 else
11497 std::string name_buf = std::string (name, prefix_len) + "___U";
11498 if (!get_int_var_value (name_buf.c_str (), U))
11500 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11501 U = L;
11505 type_allocator alloc (raw_type);
11506 type = create_static_range_type (alloc, base_type, L, U);
11507 /* create_static_range_type alters the resulting type's length
11508 to match the size of the base_type, which is not what we want.
11509 Set it back to the original range type's length. */
11510 type->set_length (raw_type->length ());
11511 type->set_name (name);
11512 return type;
11516 /* True iff NAME is the name of a range type. */
11519 ada_is_range_type_name (const char *name)
11521 return (name != NULL && strstr (name, "___XD"));
11525 /* Modular types */
11527 /* True iff TYPE is an Ada modular type. */
11530 ada_is_modular_type (struct type *type)
11532 struct type *subranged_type = get_base_type (type);
11534 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11535 && subranged_type->code () == TYPE_CODE_INT
11536 && subranged_type->is_unsigned ());
11539 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11541 ULONGEST
11542 ada_modulus (struct type *type)
11544 const dynamic_prop &high = type->bounds ()->high;
11546 if (high.is_constant ())
11547 return (ULONGEST) high.const_val () + 1;
11549 /* If TYPE is unresolved, the high bound might be a location list. Return
11550 0, for lack of a better value to return. */
11551 return 0;
11555 /* Ada exception catchpoint support:
11556 ---------------------------------
11558 We support 3 kinds of exception catchpoints:
11559 . catchpoints on Ada exceptions
11560 . catchpoints on unhandled Ada exceptions
11561 . catchpoints on failed assertions
11563 Exceptions raised during failed assertions, or unhandled exceptions
11564 could perfectly be caught with the general catchpoint on Ada exceptions.
11565 However, we can easily differentiate these two special cases, and having
11566 the option to distinguish these two cases from the rest can be useful
11567 to zero-in on certain situations.
11569 Exception catchpoints are a specialized form of breakpoint,
11570 since they rely on inserting breakpoints inside known routines
11571 of the GNAT runtime. The implementation therefore uses a standard
11572 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11573 of breakpoint_ops.
11575 Support in the runtime for exception catchpoints have been changed
11576 a few times already, and these changes affect the implementation
11577 of these catchpoints. In order to be able to support several
11578 variants of the runtime, we use a sniffer that will determine
11579 the runtime variant used by the program being debugged. */
11581 /* Ada's standard exceptions.
11583 The Ada 83 standard also defined Numeric_Error. But there so many
11584 situations where it was unclear from the Ada 83 Reference Manual
11585 (RM) whether Constraint_Error or Numeric_Error should be raised,
11586 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11587 Interpretation saying that anytime the RM says that Numeric_Error
11588 should be raised, the implementation may raise Constraint_Error.
11589 Ada 95 went one step further and pretty much removed Numeric_Error
11590 from the list of standard exceptions (it made it a renaming of
11591 Constraint_Error, to help preserve compatibility when compiling
11592 an Ada83 compiler). As such, we do not include Numeric_Error from
11593 this list of standard exceptions. */
11595 static const char * const standard_exc[] = {
11596 "constraint_error",
11597 "program_error",
11598 "storage_error",
11599 "tasking_error"
11602 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11604 /* A structure that describes how to support exception catchpoints
11605 for a given executable. */
11607 struct exception_support_info
11609 /* The name of the symbol to break on in order to insert
11610 a catchpoint on exceptions. */
11611 const char *catch_exception_sym;
11613 /* The name of the symbol to break on in order to insert
11614 a catchpoint on unhandled exceptions. */
11615 const char *catch_exception_unhandled_sym;
11617 /* The name of the symbol to break on in order to insert
11618 a catchpoint on failed assertions. */
11619 const char *catch_assert_sym;
11621 /* The name of the symbol to break on in order to insert
11622 a catchpoint on exception handling. */
11623 const char *catch_handlers_sym;
11625 /* Assuming that the inferior just triggered an unhandled exception
11626 catchpoint, this function is responsible for returning the address
11627 in inferior memory where the name of that exception is stored.
11628 Return zero if the address could not be computed. */
11629 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11632 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11633 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11635 /* The following exception support info structure describes how to
11636 implement exception catchpoints with the latest version of the
11637 Ada runtime (as of 2019-08-??). */
11639 static const struct exception_support_info default_exception_support_info =
11641 "__gnat_debug_raise_exception", /* catch_exception_sym */
11642 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11643 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11644 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11645 ada_unhandled_exception_name_addr
11648 /* The following exception support info structure describes how to
11649 implement exception catchpoints with an earlier version of the
11650 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11652 static const struct exception_support_info exception_support_info_v0 =
11654 "__gnat_debug_raise_exception", /* catch_exception_sym */
11655 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11656 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11657 "__gnat_begin_handler", /* catch_handlers_sym */
11658 ada_unhandled_exception_name_addr
11661 /* The following exception support info structure describes how to
11662 implement exception catchpoints with a slightly older version
11663 of the Ada runtime. */
11665 static const struct exception_support_info exception_support_info_fallback =
11667 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11668 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11669 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11670 "__gnat_begin_handler", /* catch_handlers_sym */
11671 ada_unhandled_exception_name_addr_from_raise
11674 /* Return nonzero if we can detect the exception support routines
11675 described in EINFO.
11677 This function errors out if an abnormal situation is detected
11678 (for instance, if we find the exception support routines, but
11679 that support is found to be incomplete). */
11681 static int
11682 ada_has_this_exception_support (const struct exception_support_info *einfo)
11684 struct symbol *sym;
11686 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11687 that should be compiled with debugging information. As a result, we
11688 expect to find that symbol in the symtabs. */
11690 sym = standard_lookup (einfo->catch_exception_sym, NULL,
11691 SEARCH_FUNCTION_DOMAIN);
11692 if (sym == NULL)
11694 /* Perhaps we did not find our symbol because the Ada runtime was
11695 compiled without debugging info, or simply stripped of it.
11696 It happens on some GNU/Linux distributions for instance, where
11697 users have to install a separate debug package in order to get
11698 the runtime's debugging info. In that situation, let the user
11699 know why we cannot insert an Ada exception catchpoint.
11701 Note: Just for the purpose of inserting our Ada exception
11702 catchpoint, we could rely purely on the associated minimal symbol.
11703 But we would be operating in degraded mode anyway, since we are
11704 still lacking the debugging info needed later on to extract
11705 the name of the exception being raised (this name is printed in
11706 the catchpoint message, and is also used when trying to catch
11707 a specific exception). We do not handle this case for now. */
11708 bound_minimal_symbol msym
11709 = lookup_minimal_symbol (current_program_space,
11710 einfo->catch_exception_sym);
11712 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11713 error (_("Your Ada runtime appears to be missing some debugging "
11714 "information.\nCannot insert Ada exception catchpoint "
11715 "in this configuration."));
11717 return 0;
11720 /* Make sure that the symbol we found corresponds to a function. */
11722 if (sym->aclass () != LOC_BLOCK)
11723 error (_("Symbol \"%s\" is not a function (class = %d)"),
11724 sym->linkage_name (), sym->aclass ());
11726 sym = standard_lookup (einfo->catch_handlers_sym, NULL,
11727 SEARCH_FUNCTION_DOMAIN);
11728 if (sym == NULL)
11730 bound_minimal_symbol msym
11731 = lookup_minimal_symbol (current_program_space,
11732 einfo->catch_handlers_sym);
11734 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11735 error (_("Your Ada runtime appears to be missing some debugging "
11736 "information.\nCannot insert Ada exception catchpoint "
11737 "in this configuration."));
11739 return 0;
11742 /* Make sure that the symbol we found corresponds to a function. */
11744 if (sym->aclass () != LOC_BLOCK)
11745 error (_("Symbol \"%s\" is not a function (class = %d)"),
11746 sym->linkage_name (), sym->aclass ());
11748 return 1;
11751 /* Inspect the Ada runtime and determine which exception info structure
11752 should be used to provide support for exception catchpoints.
11754 This function will always set the per-inferior exception_info,
11755 or raise an error. */
11757 static void
11758 ada_exception_support_info_sniffer (void)
11760 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11762 /* If the exception info is already known, then no need to recompute it. */
11763 if (data->exception_info != NULL)
11764 return;
11766 /* Check the latest (default) exception support info. */
11767 if (ada_has_this_exception_support (&default_exception_support_info))
11769 data->exception_info = &default_exception_support_info;
11770 return;
11773 /* Try the v0 exception suport info. */
11774 if (ada_has_this_exception_support (&exception_support_info_v0))
11776 data->exception_info = &exception_support_info_v0;
11777 return;
11780 /* Try our fallback exception suport info. */
11781 if (ada_has_this_exception_support (&exception_support_info_fallback))
11783 data->exception_info = &exception_support_info_fallback;
11784 return;
11787 throw_error (NOT_FOUND_ERROR,
11788 _("Could not find Ada runtime exception support"));
11791 /* True iff FRAME is very likely to be that of a function that is
11792 part of the runtime system. This is all very heuristic, but is
11793 intended to be used as advice as to what frames are uninteresting
11794 to most users. */
11796 static int
11797 is_known_support_routine (const frame_info_ptr &frame)
11799 enum language func_lang;
11800 int i;
11801 const char *fullname;
11803 /* If this code does not have any debugging information (no symtab),
11804 This cannot be any user code. */
11806 symtab_and_line sal = find_frame_sal (frame);
11807 if (sal.symtab == NULL)
11808 return 1;
11810 /* If there is a symtab, but the associated source file cannot be
11811 located, then assume this is not user code: Selecting a frame
11812 for which we cannot display the code would not be very helpful
11813 for the user. This should also take care of case such as VxWorks
11814 where the kernel has some debugging info provided for a few units. */
11816 fullname = symtab_to_fullname (sal.symtab);
11817 if (access (fullname, R_OK) != 0)
11818 return 1;
11820 /* Check the unit filename against the Ada runtime file naming.
11821 We also check the name of the objfile against the name of some
11822 known system libraries that sometimes come with debugging info
11823 too. */
11825 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11827 re_comp (known_runtime_file_name_patterns[i]);
11828 if (re_exec (lbasename (sal.symtab->filename)))
11829 return 1;
11830 if (sal.symtab->compunit ()->objfile () != NULL
11831 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11832 return 1;
11835 /* Check whether the function is a GNAT-generated entity. */
11837 gdb::unique_xmalloc_ptr<char> func_name
11838 = find_frame_funname (frame, &func_lang, NULL);
11839 if (func_name == NULL)
11840 return 1;
11842 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11844 re_comp (known_auxiliary_function_name_patterns[i]);
11845 if (re_exec (func_name.get ()))
11846 return 1;
11849 return 0;
11852 /* Find the first frame that contains debugging information and that is not
11853 part of the Ada run-time, starting from FI and moving upward. */
11855 void
11856 ada_find_printable_frame (const frame_info_ptr &initial_fi)
11858 for (frame_info_ptr fi = initial_fi; fi != nullptr; fi = get_prev_frame (fi))
11860 if (!is_known_support_routine (fi))
11862 select_frame (fi);
11863 break;
11869 /* Assuming that the inferior just triggered an unhandled exception
11870 catchpoint, return the address in inferior memory where the name
11871 of the exception is stored.
11873 Return zero if the address could not be computed. */
11875 static CORE_ADDR
11876 ada_unhandled_exception_name_addr (void)
11878 return parse_and_eval_address ("e.full_name");
11881 /* Same as ada_unhandled_exception_name_addr, except that this function
11882 should be used when the inferior uses an older version of the runtime,
11883 where the exception name needs to be extracted from a specific frame
11884 several frames up in the callstack. */
11886 static CORE_ADDR
11887 ada_unhandled_exception_name_addr_from_raise (void)
11889 int frame_level;
11890 frame_info_ptr fi;
11891 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11893 /* To determine the name of this exception, we need to select
11894 the frame corresponding to RAISE_SYM_NAME. This frame is
11895 at least 3 levels up, so we simply skip the first 3 frames
11896 without checking the name of their associated function. */
11897 fi = get_current_frame ();
11898 for (frame_level = 0; frame_level < 3; frame_level += 1)
11899 if (fi != NULL)
11900 fi = get_prev_frame (fi);
11902 while (fi != NULL)
11904 enum language func_lang;
11906 gdb::unique_xmalloc_ptr<char> func_name
11907 = find_frame_funname (fi, &func_lang, NULL);
11908 if (func_name != NULL)
11910 if (strcmp (func_name.get (),
11911 data->exception_info->catch_exception_sym) == 0)
11912 break; /* We found the frame we were looking for... */
11914 fi = get_prev_frame (fi);
11917 if (fi == NULL)
11918 return 0;
11920 select_frame (fi);
11921 return parse_and_eval_address ("id.full_name");
11924 /* Assuming the inferior just triggered an Ada exception catchpoint
11925 (of any type), return the address in inferior memory where the name
11926 of the exception is stored, if applicable.
11928 Assumes the selected frame is the current frame.
11930 Return zero if the address could not be computed, or if not relevant. */
11932 static CORE_ADDR
11933 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11935 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11937 switch (ex)
11939 case ada_catch_exception:
11940 return (parse_and_eval_address ("e.full_name"));
11941 break;
11943 case ada_catch_exception_unhandled:
11944 return data->exception_info->unhandled_exception_name_addr ();
11945 break;
11947 case ada_catch_handlers:
11948 return 0; /* The runtimes does not provide access to the exception
11949 name. */
11950 break;
11952 case ada_catch_assert:
11953 return 0; /* Exception name is not relevant in this case. */
11954 break;
11956 default:
11957 internal_error (_("unexpected catchpoint type"));
11958 break;
11961 return 0; /* Should never be reached. */
11964 /* Assuming the inferior is stopped at an exception catchpoint,
11965 return the message which was associated to the exception, if
11966 available. Return NULL if the message could not be retrieved.
11968 Note: The exception message can be associated to an exception
11969 either through the use of the Raise_Exception function, or
11970 more simply (Ada 2005 and later), via:
11972 raise Exception_Name with "exception message";
11976 static gdb::unique_xmalloc_ptr<char>
11977 ada_exception_message_1 (void)
11979 struct value *e_msg_val;
11980 int e_msg_len;
11982 /* For runtimes that support this feature, the exception message
11983 is passed as an unbounded string argument called "message". */
11984 e_msg_val = parse_and_eval ("message");
11985 if (e_msg_val == NULL)
11986 return NULL; /* Exception message not supported. */
11988 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11989 gdb_assert (e_msg_val != NULL);
11990 e_msg_len = e_msg_val->type ()->length ();
11992 /* If the message string is empty, then treat it as if there was
11993 no exception message. */
11994 if (e_msg_len <= 0)
11995 return NULL;
11997 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11998 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
11999 e_msg_len);
12000 e_msg.get ()[e_msg_len] = '\0';
12002 return e_msg;
12005 /* Same as ada_exception_message_1, except that all exceptions are
12006 contained here (returning NULL instead). */
12008 static gdb::unique_xmalloc_ptr<char>
12009 ada_exception_message (void)
12011 gdb::unique_xmalloc_ptr<char> e_msg;
12015 e_msg = ada_exception_message_1 ();
12017 catch (const gdb_exception_error &e)
12019 e_msg.reset (nullptr);
12022 return e_msg;
12025 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12026 any error that ada_exception_name_addr_1 might cause to be thrown.
12027 When an error is intercepted, a warning with the error message is printed,
12028 and zero is returned. */
12030 static CORE_ADDR
12031 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12033 CORE_ADDR result = 0;
12037 result = ada_exception_name_addr_1 (ex);
12040 catch (const gdb_exception_error &e)
12042 warning (_("failed to get exception name: %s"), e.what ());
12043 return 0;
12046 return result;
12049 static std::string ada_exception_catchpoint_cond_string
12050 (const char *excep_string,
12051 enum ada_exception_catchpoint_kind ex);
12053 /* Ada catchpoints.
12055 In the case of catchpoints on Ada exceptions, the catchpoint will
12056 stop the target on every exception the program throws. When a user
12057 specifies the name of a specific exception, we translate this
12058 request into a condition expression (in text form), and then parse
12059 it into an expression stored in each of the catchpoint's locations.
12060 We then use this condition to check whether the exception that was
12061 raised is the one the user is interested in. If not, then the
12062 target is resumed again. We store the name of the requested
12063 exception, in order to be able to re-set the condition expression
12064 when symbols change. */
12066 /* An instance of this type is used to represent an Ada catchpoint. */
12068 struct ada_catchpoint : public code_breakpoint
12070 ada_catchpoint (struct gdbarch *gdbarch_,
12071 enum ada_exception_catchpoint_kind kind,
12072 const char *cond_string,
12073 bool tempflag,
12074 bool enabled,
12075 bool from_tty,
12076 std::string &&excep_string_)
12077 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
12078 m_excep_string (std::move (excep_string_)),
12079 m_kind (kind)
12081 /* Unlike most code_breakpoint types, Ada catchpoints are
12082 pspace-specific. */
12083 pspace = current_program_space;
12084 enable_state = enabled ? bp_enabled : bp_disabled;
12085 language = language_ada;
12087 re_set (pspace);
12090 struct bp_location *allocate_location () override;
12091 void re_set (program_space *pspace) override;
12092 void check_status (struct bpstat *bs) override;
12093 enum print_stop_action print_it (const bpstat *bs) const override;
12094 bool print_one (const bp_location **) const override;
12095 void print_mention () const override;
12096 void print_recreate (struct ui_file *fp) const override;
12098 private:
12100 /* A helper function for check_status. Returns true if we should
12101 stop for this breakpoint hit. If the user specified a specific
12102 exception, we only want to cause a stop if the program thrown
12103 that exception. */
12104 bool should_stop_exception (const struct bp_location *bl) const;
12106 /* The name of the specific exception the user specified. */
12107 std::string m_excep_string;
12109 /* What kind of catchpoint this is. */
12110 enum ada_exception_catchpoint_kind m_kind;
12113 /* An instance of this type is used to represent an Ada catchpoint
12114 breakpoint location. */
12116 class ada_catchpoint_location : public bp_location
12118 public:
12119 explicit ada_catchpoint_location (ada_catchpoint *owner)
12120 : bp_location (owner, bp_loc_software_breakpoint)
12123 /* The condition that checks whether the exception that was raised
12124 is the specific exception the user specified on catchpoint
12125 creation. */
12126 expression_up excep_cond_expr;
12129 static struct symtab_and_line ada_exception_sal
12130 (enum ada_exception_catchpoint_kind ex);
12132 /* Implement the RE_SET method in the structure for all exception
12133 catchpoint kinds. */
12135 void
12136 ada_catchpoint::re_set (program_space *pspace)
12138 std::vector<symtab_and_line> sals;
12141 struct symtab_and_line sal = ada_exception_sal (m_kind);
12142 sals.push_back (sal);
12144 catch (const gdb_exception_error &ex)
12146 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12147 if (ex.error != NOT_FOUND_ERROR)
12148 throw;
12151 update_breakpoint_locations (this, pspace, sals, {});
12153 /* Reparse the exception conditional expressions. One for each
12154 location. */
12156 /* Nothing to do if there's no specific exception to catch. */
12157 if (m_excep_string.empty ())
12158 return;
12160 /* Same if there are no locations... */
12161 if (!has_locations ())
12162 return;
12164 /* Compute the condition expression in text form, from the specific
12165 exception we want to catch. */
12166 std::string cond_string
12167 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
12169 /* Iterate over all the catchpoint's locations, and parse an
12170 expression for each. */
12171 for (bp_location &bl : locations ())
12173 ada_catchpoint_location &ada_loc
12174 = static_cast<ada_catchpoint_location &> (bl);
12175 expression_up exp;
12177 if (!bl.shlib_disabled)
12179 const char *s;
12181 s = cond_string.c_str ();
12184 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
12186 catch (const gdb_exception_error &e)
12188 warning (_("failed to reevaluate internal exception condition "
12189 "for catchpoint %d: %s"),
12190 number, e.what ());
12194 ada_loc.excep_cond_expr = std::move (exp);
12198 /* Implement the ALLOCATE_LOCATION method in the structure for all
12199 exception catchpoint kinds. */
12201 struct bp_location *
12202 ada_catchpoint::allocate_location ()
12204 return new ada_catchpoint_location (this);
12207 /* See declaration. */
12209 bool
12210 ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
12212 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
12213 const struct ada_catchpoint_location *ada_loc
12214 = (const struct ada_catchpoint_location *) bl;
12215 bool stop;
12217 struct internalvar *var = lookup_internalvar ("_ada_exception");
12218 if (c->m_kind == ada_catch_assert)
12219 clear_internalvar (var);
12220 else
12224 const char *expr;
12226 if (c->m_kind == ada_catch_handlers)
12227 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12228 ".all.occurrence.id");
12229 else
12230 expr = "e";
12232 struct value *exc = parse_and_eval (expr);
12233 set_internalvar (var, exc);
12235 catch (const gdb_exception_error &ex)
12237 clear_internalvar (var);
12241 /* With no specific exception, should always stop. */
12242 if (c->m_excep_string.empty ())
12243 return true;
12245 if (ada_loc->excep_cond_expr == NULL)
12247 /* We will have a NULL expression if back when we were creating
12248 the expressions, this location's had failed to parse. */
12249 return true;
12252 stop = true;
12255 scoped_value_mark mark;
12256 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
12258 catch (const gdb_exception_error &ex)
12260 exception_fprintf (gdb_stderr, ex,
12261 _("Error in testing exception condition:\n"));
12264 return stop;
12267 /* Implement the CHECK_STATUS method in the structure for all
12268 exception catchpoint kinds. */
12270 void
12271 ada_catchpoint::check_status (bpstat *bs)
12273 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12276 /* Implement the PRINT_IT method in the structure for all exception
12277 catchpoint kinds. */
12279 enum print_stop_action
12280 ada_catchpoint::print_it (const bpstat *bs) const
12282 struct ui_out *uiout = current_uiout;
12284 annotate_catchpoint (number);
12286 if (uiout->is_mi_like_p ())
12288 uiout->field_string ("reason",
12289 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12290 uiout->field_string ("disp", bpdisp_text (disposition));
12293 uiout->text (disposition == disp_del
12294 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12295 print_num_locno (bs, uiout);
12296 uiout->text (", ");
12298 /* ada_exception_name_addr relies on the selected frame being the
12299 current frame. Need to do this here because this function may be
12300 called more than once when printing a stop, and below, we'll
12301 select the first frame past the Ada run-time (see
12302 ada_find_printable_frame). */
12303 select_frame (get_current_frame ());
12305 switch (m_kind)
12307 case ada_catch_exception:
12308 case ada_catch_exception_unhandled:
12309 case ada_catch_handlers:
12311 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12312 char exception_name[256];
12314 if (addr != 0)
12316 read_memory (addr, (gdb_byte *) exception_name,
12317 sizeof (exception_name) - 1);
12318 exception_name [sizeof (exception_name) - 1] = '\0';
12320 else
12322 /* For some reason, we were unable to read the exception
12323 name. This could happen if the Runtime was compiled
12324 without debugging info, for instance. In that case,
12325 just replace the exception name by the generic string
12326 "exception" - it will read as "an exception" in the
12327 notification we are about to print. */
12328 memcpy (exception_name, "exception", sizeof ("exception"));
12330 /* In the case of unhandled exception breakpoints, we print
12331 the exception name as "unhandled EXCEPTION_NAME", to make
12332 it clearer to the user which kind of catchpoint just got
12333 hit. We used ui_out_text to make sure that this extra
12334 info does not pollute the exception name in the MI case. */
12335 if (m_kind == ada_catch_exception_unhandled)
12336 uiout->text ("unhandled ");
12337 uiout->field_string ("exception-name", exception_name);
12339 break;
12340 case ada_catch_assert:
12341 /* In this case, the name of the exception is not really
12342 important. Just print "failed assertion" to make it clearer
12343 that his program just hit an assertion-failure catchpoint.
12344 We used ui_out_text because this info does not belong in
12345 the MI output. */
12346 uiout->text ("failed assertion");
12347 break;
12350 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12351 if (exception_message != NULL)
12353 uiout->text (" (");
12354 uiout->field_string ("exception-message", exception_message.get ());
12355 uiout->text (")");
12358 uiout->text (" at ");
12359 ada_find_printable_frame (get_current_frame ());
12361 return PRINT_SRC_AND_LOC;
12364 /* Implement the PRINT_ONE method in the structure for all exception
12365 catchpoint kinds. */
12367 bool
12368 ada_catchpoint::print_one (const bp_location **last_loc) const
12370 struct ui_out *uiout = current_uiout;
12371 struct value_print_options opts;
12373 get_user_print_options (&opts);
12375 if (opts.addressprint)
12376 uiout->field_skip ("addr");
12378 annotate_field (5);
12379 switch (m_kind)
12381 case ada_catch_exception:
12382 if (!m_excep_string.empty ())
12384 std::string msg = string_printf (_("`%s' Ada exception"),
12385 m_excep_string.c_str ());
12387 uiout->field_string ("what", msg);
12389 else
12390 uiout->field_string ("what", "all Ada exceptions");
12392 break;
12394 case ada_catch_exception_unhandled:
12395 uiout->field_string ("what", "unhandled Ada exceptions");
12396 break;
12398 case ada_catch_handlers:
12399 if (!m_excep_string.empty ())
12401 uiout->field_fmt ("what",
12402 _("`%s' Ada exception handlers"),
12403 m_excep_string.c_str ());
12405 else
12406 uiout->field_string ("what", "all Ada exceptions handlers");
12407 break;
12409 case ada_catch_assert:
12410 uiout->field_string ("what", "failed Ada assertions");
12411 break;
12413 default:
12414 internal_error (_("unexpected catchpoint type"));
12415 break;
12418 return true;
12421 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12422 for all exception catchpoint kinds. */
12424 void
12425 ada_catchpoint::print_mention () const
12427 struct ui_out *uiout = current_uiout;
12429 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12430 : _("Catchpoint "));
12431 uiout->field_signed ("bkptno", number);
12432 uiout->text (": ");
12434 switch (m_kind)
12436 case ada_catch_exception:
12437 if (!m_excep_string.empty ())
12439 std::string info = string_printf (_("`%s' Ada exception"),
12440 m_excep_string.c_str ());
12441 uiout->text (info);
12443 else
12444 uiout->text (_("all Ada exceptions"));
12445 break;
12447 case ada_catch_exception_unhandled:
12448 uiout->text (_("unhandled Ada exceptions"));
12449 break;
12451 case ada_catch_handlers:
12452 if (!m_excep_string.empty ())
12454 std::string info
12455 = string_printf (_("`%s' Ada exception handlers"),
12456 m_excep_string.c_str ());
12457 uiout->text (info);
12459 else
12460 uiout->text (_("all Ada exceptions handlers"));
12461 break;
12463 case ada_catch_assert:
12464 uiout->text (_("failed Ada assertions"));
12465 break;
12467 default:
12468 internal_error (_("unexpected catchpoint type"));
12469 break;
12473 /* Implement the PRINT_RECREATE method in the structure for all
12474 exception catchpoint kinds. */
12476 void
12477 ada_catchpoint::print_recreate (struct ui_file *fp) const
12479 switch (m_kind)
12481 case ada_catch_exception:
12482 gdb_printf (fp, "catch exception");
12483 if (!m_excep_string.empty ())
12484 gdb_printf (fp, " %s", m_excep_string.c_str ());
12485 break;
12487 case ada_catch_exception_unhandled:
12488 gdb_printf (fp, "catch exception unhandled");
12489 break;
12491 case ada_catch_handlers:
12492 gdb_printf (fp, "catch handlers");
12493 break;
12495 case ada_catch_assert:
12496 gdb_printf (fp, "catch assert");
12497 break;
12499 default:
12500 internal_error (_("unexpected catchpoint type"));
12502 print_recreate_thread (fp);
12505 /* See ada-lang.h. */
12507 bool
12508 is_ada_exception_catchpoint (breakpoint *bp)
12510 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12513 /* Split the arguments specified in a "catch exception" command.
12514 Set EX to the appropriate catchpoint type.
12515 Set EXCEP_STRING to the name of the specific exception if
12516 specified by the user.
12517 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12518 "catch handlers" command. False otherwise.
12519 If a condition is found at the end of the arguments, the condition
12520 expression is stored in COND_STRING (memory must be deallocated
12521 after use). Otherwise COND_STRING is set to NULL. */
12523 static void
12524 catch_ada_exception_command_split (const char *args,
12525 bool is_catch_handlers_cmd,
12526 enum ada_exception_catchpoint_kind *ex,
12527 std::string *excep_string,
12528 std::string *cond_string)
12530 std::string exception_name;
12532 exception_name = extract_arg (&args);
12533 if (exception_name == "if")
12535 /* This is not an exception name; this is the start of a condition
12536 expression for a catchpoint on all exceptions. So, "un-get"
12537 this token, and set exception_name to NULL. */
12538 exception_name.clear ();
12539 args -= 2;
12542 /* Check to see if we have a condition. */
12544 args = skip_spaces (args);
12545 if (startswith (args, "if")
12546 && (isspace (args[2]) || args[2] == '\0'))
12548 args += 2;
12549 args = skip_spaces (args);
12551 if (args[0] == '\0')
12552 error (_("Condition missing after `if' keyword"));
12553 *cond_string = args;
12555 args += strlen (args);
12558 /* Check that we do not have any more arguments. Anything else
12559 is unexpected. */
12561 if (args[0] != '\0')
12562 error (_("Junk at end of expression"));
12564 if (is_catch_handlers_cmd)
12566 /* Catch handling of exceptions. */
12567 *ex = ada_catch_handlers;
12568 *excep_string = exception_name;
12570 else if (exception_name.empty ())
12572 /* Catch all exceptions. */
12573 *ex = ada_catch_exception;
12574 excep_string->clear ();
12576 else if (exception_name == "unhandled")
12578 /* Catch unhandled exceptions. */
12579 *ex = ada_catch_exception_unhandled;
12580 excep_string->clear ();
12582 else
12584 /* Catch a specific exception. */
12585 *ex = ada_catch_exception;
12586 *excep_string = exception_name;
12590 /* Return the name of the symbol on which we should break in order to
12591 implement a catchpoint of the EX kind. */
12593 static const char *
12594 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12596 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12598 gdb_assert (data->exception_info != NULL);
12600 switch (ex)
12602 case ada_catch_exception:
12603 return (data->exception_info->catch_exception_sym);
12604 break;
12605 case ada_catch_exception_unhandled:
12606 return (data->exception_info->catch_exception_unhandled_sym);
12607 break;
12608 case ada_catch_assert:
12609 return (data->exception_info->catch_assert_sym);
12610 break;
12611 case ada_catch_handlers:
12612 return (data->exception_info->catch_handlers_sym);
12613 break;
12614 default:
12615 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12619 /* Return the condition that will be used to match the current exception
12620 being raised with the exception that the user wants to catch. This
12621 assumes that this condition is used when the inferior just triggered
12622 an exception catchpoint.
12623 EX: the type of catchpoints used for catching Ada exceptions. */
12625 static std::string
12626 ada_exception_catchpoint_cond_string (const char *excep_string,
12627 enum ada_exception_catchpoint_kind ex)
12629 bool is_standard_exc = false;
12630 std::string result;
12632 if (ex == ada_catch_handlers)
12634 /* For exception handlers catchpoints, the condition string does
12635 not use the same parameter as for the other exceptions. */
12636 result = ("long_integer (GNAT_GCC_exception_Access"
12637 "(gcc_exception).all.occurrence.id)");
12639 else
12640 result = "long_integer (e)";
12642 /* The standard exceptions are a special case. They are defined in
12643 runtime units that have been compiled without debugging info; if
12644 EXCEP_STRING is the not-fully-qualified name of a standard
12645 exception (e.g. "constraint_error") then, during the evaluation
12646 of the condition expression, the symbol lookup on this name would
12647 *not* return this standard exception. The catchpoint condition
12648 may then be set only on user-defined exceptions which have the
12649 same not-fully-qualified name (e.g. my_package.constraint_error).
12651 To avoid this unexpected behavior, these standard exceptions are
12652 systematically prefixed by "standard". This means that "catch
12653 exception constraint_error" is rewritten into "catch exception
12654 standard.constraint_error".
12656 If an exception named constraint_error is defined in another package of
12657 the inferior program, then the only way to specify this exception as a
12658 breakpoint condition is to use its fully-qualified named:
12659 e.g. my_package.constraint_error. */
12661 for (const char *name : standard_exc)
12663 if (strcmp (name, excep_string) == 0)
12665 is_standard_exc = true;
12666 break;
12670 result += " = ";
12672 if (is_standard_exc)
12673 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12674 else
12675 string_appendf (result, "long_integer (&%s)", excep_string);
12677 return result;
12680 /* Return the symtab_and_line that should be used to insert an
12681 exception catchpoint of the TYPE kind. */
12683 static struct symtab_and_line
12684 ada_exception_sal (enum ada_exception_catchpoint_kind ex)
12686 const char *sym_name;
12687 struct symbol *sym;
12689 /* First, find out which exception support info to use. */
12690 ada_exception_support_info_sniffer ();
12692 /* Then lookup the function on which we will break in order to catch
12693 the Ada exceptions requested by the user. */
12694 sym_name = ada_exception_sym_name (ex);
12695 sym = standard_lookup (sym_name, NULL, SEARCH_VFT);
12697 if (sym == NULL)
12698 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12699 sym_name);
12701 if (sym->aclass () != LOC_BLOCK)
12702 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12704 return find_function_start_sal (sym, 1);
12707 /* Create an Ada exception catchpoint.
12709 EX_KIND is the kind of exception catchpoint to be created.
12711 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12712 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12713 of the exception to which this catchpoint applies.
12715 COND_STRING, if not empty, is the catchpoint condition.
12717 TEMPFLAG, if nonzero, means that the underlying breakpoint
12718 should be temporary.
12720 FROM_TTY is the usual argument passed to all commands implementations. */
12722 void
12723 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12724 enum ada_exception_catchpoint_kind ex_kind,
12725 std::string &&excep_string,
12726 const std::string &cond_string,
12727 int tempflag,
12728 int enabled,
12729 int from_tty)
12731 /* This works around an obscure issue when an Ada program is
12732 compiled with LTO. */
12733 scoped_restore_current_language save_language (language_ada);
12735 std::unique_ptr<ada_catchpoint> c
12736 (new ada_catchpoint (gdbarch, ex_kind,
12737 cond_string.empty () ? nullptr : cond_string.c_str (),
12738 tempflag, enabled, from_tty,
12739 std::move (excep_string)));
12740 install_breakpoint (0, std::move (c), 1);
12743 /* Implement the "catch exception" command. */
12745 static void
12746 catch_ada_exception_command (const char *arg_entry, int from_tty,
12747 struct cmd_list_element *command)
12749 const char *arg = arg_entry;
12750 struct gdbarch *gdbarch = get_current_arch ();
12751 int tempflag;
12752 enum ada_exception_catchpoint_kind ex_kind;
12753 std::string excep_string;
12754 std::string cond_string;
12756 tempflag = command->context () == CATCH_TEMPORARY;
12758 if (!arg)
12759 arg = "";
12760 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12761 &cond_string);
12762 create_ada_exception_catchpoint (gdbarch, ex_kind,
12763 std::move (excep_string), cond_string,
12764 tempflag, 1 /* enabled */,
12765 from_tty);
12768 /* Implement the "catch handlers" command. */
12770 static void
12771 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12772 struct cmd_list_element *command)
12774 const char *arg = arg_entry;
12775 struct gdbarch *gdbarch = get_current_arch ();
12776 int tempflag;
12777 enum ada_exception_catchpoint_kind ex_kind;
12778 std::string excep_string;
12779 std::string cond_string;
12781 tempflag = command->context () == CATCH_TEMPORARY;
12783 if (!arg)
12784 arg = "";
12785 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12786 &cond_string);
12787 create_ada_exception_catchpoint (gdbarch, ex_kind,
12788 std::move (excep_string), cond_string,
12789 tempflag, 1 /* enabled */,
12790 from_tty);
12793 /* Completion function for the Ada "catch" commands. */
12795 static void
12796 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12797 const char *text, const char *word)
12799 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12801 for (const ada_exc_info &info : exceptions)
12803 if (startswith (info.name, word))
12804 tracker.add_completion (make_unique_xstrdup (info.name));
12808 /* Split the arguments specified in a "catch assert" command.
12810 ARGS contains the command's arguments (or the empty string if
12811 no arguments were passed).
12813 If ARGS contains a condition, set COND_STRING to that condition
12814 (the memory needs to be deallocated after use). */
12816 static void
12817 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12819 args = skip_spaces (args);
12821 /* Check whether a condition was provided. */
12822 if (startswith (args, "if")
12823 && (isspace (args[2]) || args[2] == '\0'))
12825 args += 2;
12826 args = skip_spaces (args);
12827 if (args[0] == '\0')
12828 error (_("condition missing after `if' keyword"));
12829 cond_string.assign (args);
12832 /* Otherwise, there should be no other argument at the end of
12833 the command. */
12834 else if (args[0] != '\0')
12835 error (_("Junk at end of arguments."));
12838 /* Implement the "catch assert" command. */
12840 static void
12841 catch_assert_command (const char *arg_entry, int from_tty,
12842 struct cmd_list_element *command)
12844 const char *arg = arg_entry;
12845 struct gdbarch *gdbarch = get_current_arch ();
12846 int tempflag;
12847 std::string cond_string;
12849 tempflag = command->context () == CATCH_TEMPORARY;
12851 if (!arg)
12852 arg = "";
12853 catch_ada_assert_command_split (arg, cond_string);
12854 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12855 {}, cond_string,
12856 tempflag, 1 /* enabled */,
12857 from_tty);
12860 /* Return non-zero if the symbol SYM is an Ada exception object. */
12862 static int
12863 ada_is_exception_sym (struct symbol *sym)
12865 const char *type_name = sym->type ()->name ();
12867 return (sym->aclass () != LOC_TYPEDEF
12868 && sym->aclass () != LOC_BLOCK
12869 && sym->aclass () != LOC_CONST
12870 && sym->aclass () != LOC_UNRESOLVED
12871 && type_name != NULL && strcmp (type_name, "exception") == 0);
12874 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12875 Ada exception object. This matches all exceptions except the ones
12876 defined by the Ada language. */
12878 static int
12879 ada_is_non_standard_exception_sym (struct symbol *sym)
12881 if (!ada_is_exception_sym (sym))
12882 return 0;
12884 for (const char *name : standard_exc)
12885 if (strcmp (sym->linkage_name (), name) == 0)
12886 return 0; /* A standard exception. */
12888 /* Numeric_Error is also a standard exception, so exclude it.
12889 See the STANDARD_EXC description for more details as to why
12890 this exception is not listed in that array. */
12891 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12892 return 0;
12894 return 1;
12897 /* A helper function for std::sort, comparing two struct ada_exc_info
12898 objects.
12900 The comparison is determined first by exception name, and then
12901 by exception address. */
12903 bool
12904 ada_exc_info::operator< (const ada_exc_info &other) const
12906 int result;
12908 result = strcmp (name, other.name);
12909 if (result < 0)
12910 return true;
12911 if (result == 0 && addr < other.addr)
12912 return true;
12913 return false;
12916 bool
12917 ada_exc_info::operator== (const ada_exc_info &other) const
12919 return addr == other.addr && strcmp (name, other.name) == 0;
12922 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12923 routine, but keeping the first SKIP elements untouched.
12925 All duplicates are also removed. */
12927 static void
12928 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12929 int skip)
12931 std::sort (exceptions->begin () + skip, exceptions->end ());
12932 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12933 exceptions->end ());
12936 /* Add all exceptions defined by the Ada standard whose name match
12937 a regular expression.
12939 If PREG is not NULL, then this regexp_t object is used to
12940 perform the symbol name matching. Otherwise, no name-based
12941 filtering is performed.
12943 EXCEPTIONS is a vector of exceptions to which matching exceptions
12944 gets pushed. */
12946 static void
12947 ada_add_standard_exceptions (compiled_regex *preg,
12948 std::vector<ada_exc_info> *exceptions)
12950 for (const char *name : standard_exc)
12952 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12954 symbol_name_match_type match_type = name_match_type_from_name (name);
12955 lookup_name_info lookup_name (name, match_type);
12957 symbol_name_matcher_ftype *match_name
12958 = ada_get_symbol_name_matcher (lookup_name);
12960 /* Iterate over all objfiles irrespective of scope or linker
12961 namespaces so we get all exceptions anywhere in the
12962 progspace. */
12963 for (objfile *objfile : current_program_space->objfiles ())
12965 for (minimal_symbol *msymbol : objfile->msymbols ())
12967 if (match_name (msymbol->linkage_name (), lookup_name,
12968 nullptr)
12969 && msymbol->type () != mst_solib_trampoline)
12971 ada_exc_info info
12972 = {name, msymbol->value_address (objfile)};
12974 exceptions->push_back (info);
12982 /* Add all Ada exceptions defined locally and accessible from the given
12983 FRAME.
12985 If PREG is not NULL, then this regexp_t object is used to
12986 perform the symbol name matching. Otherwise, no name-based
12987 filtering is performed.
12989 EXCEPTIONS is a vector of exceptions to which matching exceptions
12990 gets pushed. */
12992 static void
12993 ada_add_exceptions_from_frame (compiled_regex *preg,
12994 const frame_info_ptr &frame,
12995 std::vector<ada_exc_info> *exceptions)
12997 const struct block *block = get_frame_block (frame, 0);
12999 while (block != 0)
13001 for (struct symbol *sym : block_iterator_range (block))
13003 switch (sym->aclass ())
13005 case LOC_TYPEDEF:
13006 case LOC_BLOCK:
13007 case LOC_CONST:
13008 break;
13009 default:
13010 if (ada_is_exception_sym (sym))
13012 struct ada_exc_info info = {sym->print_name (),
13013 sym->value_address ()};
13015 exceptions->push_back (info);
13019 if (block->function () != NULL)
13020 break;
13021 block = block->superblock ();
13025 /* Return true if NAME matches PREG or if PREG is NULL. */
13027 static bool
13028 name_matches_regex (const char *name, compiled_regex *preg)
13030 return (preg == NULL
13031 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13034 /* Add all exceptions defined globally whose name name match
13035 a regular expression, excluding standard exceptions.
13037 The reason we exclude standard exceptions is that they need
13038 to be handled separately: Standard exceptions are defined inside
13039 a runtime unit which is normally not compiled with debugging info,
13040 and thus usually do not show up in our symbol search. However,
13041 if the unit was in fact built with debugging info, we need to
13042 exclude them because they would duplicate the entry we found
13043 during the special loop that specifically searches for those
13044 standard exceptions.
13046 If PREG is not NULL, then this regexp_t object is used to
13047 perform the symbol name matching. Otherwise, no name-based
13048 filtering is performed.
13050 EXCEPTIONS is a vector of exceptions to which matching exceptions
13051 gets pushed. */
13053 static void
13054 ada_add_global_exceptions (compiled_regex *preg,
13055 std::vector<ada_exc_info> *exceptions)
13057 /* In Ada, the symbol "search name" is a linkage name, whereas the
13058 regular expression used to do the matching refers to the natural
13059 name. So match against the decoded name. */
13060 expand_symtabs_matching (NULL,
13061 lookup_name_info::match_any (),
13062 [&] (const char *search_name)
13064 std::string decoded = ada_decode (search_name);
13065 return name_matches_regex (decoded.c_str (), preg);
13067 NULL,
13068 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13069 SEARCH_VAR_DOMAIN,
13070 [&] (enum language lang)
13072 /* Try to skip non-Ada CUs. */
13073 return lang == language_ada;
13076 /* Iterate over all objfiles irrespective of scope or linker namespaces
13077 so we get all exceptions anywhere in the progspace. */
13078 for (objfile *objfile : current_program_space->objfiles ())
13080 for (compunit_symtab *s : objfile->compunits ())
13082 const struct blockvector *bv = s->blockvector ();
13083 int i;
13085 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13087 const struct block *b = bv->block (i);
13089 for (struct symbol *sym : block_iterator_range (b))
13090 if (ada_is_non_standard_exception_sym (sym)
13091 && name_matches_regex (sym->natural_name (), preg))
13093 struct ada_exc_info info
13094 = {sym->print_name (), sym->value_address ()};
13096 exceptions->push_back (info);
13103 /* Implements ada_exceptions_list with the regular expression passed
13104 as a regex_t, rather than a string.
13106 If not NULL, PREG is used to filter out exceptions whose names
13107 do not match. Otherwise, all exceptions are listed. */
13109 static std::vector<ada_exc_info>
13110 ada_exceptions_list_1 (compiled_regex *preg)
13112 std::vector<ada_exc_info> result;
13113 int prev_len;
13115 /* First, list the known standard exceptions. These exceptions
13116 need to be handled separately, as they are usually defined in
13117 runtime units that have been compiled without debugging info. */
13119 ada_add_standard_exceptions (preg, &result);
13121 /* Next, find all exceptions whose scope is local and accessible
13122 from the currently selected frame. */
13124 if (has_stack_frames ())
13126 prev_len = result.size ();
13127 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13128 &result);
13129 if (result.size () > prev_len)
13130 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13133 /* Add all exceptions whose scope is global. */
13135 prev_len = result.size ();
13136 ada_add_global_exceptions (preg, &result);
13137 if (result.size () > prev_len)
13138 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13140 return result;
13143 /* Return a vector of ada_exc_info.
13145 If REGEXP is NULL, all exceptions are included in the result.
13146 Otherwise, it should contain a valid regular expression,
13147 and only the exceptions whose names match that regular expression
13148 are included in the result.
13150 The exceptions are sorted in the following order:
13151 - Standard exceptions (defined by the Ada language), in
13152 alphabetical order;
13153 - Exceptions only visible from the current frame, in
13154 alphabetical order;
13155 - Exceptions whose scope is global, in alphabetical order. */
13157 std::vector<ada_exc_info>
13158 ada_exceptions_list (const char *regexp)
13160 if (regexp == NULL)
13161 return ada_exceptions_list_1 (NULL);
13163 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13164 return ada_exceptions_list_1 (&reg);
13167 /* Implement the "info exceptions" command. */
13169 static void
13170 info_exceptions_command (const char *regexp, int from_tty)
13172 struct gdbarch *gdbarch = get_current_arch ();
13174 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13176 if (regexp != NULL)
13177 gdb_printf
13178 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13179 else
13180 gdb_printf (_("All defined Ada exceptions:\n"));
13182 for (const ada_exc_info &info : exceptions)
13183 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13187 /* Language vector */
13189 /* symbol_name_matcher_ftype adapter for wild_match. */
13191 static bool
13192 do_wild_match (const char *symbol_search_name,
13193 const lookup_name_info &lookup_name,
13194 completion_match_result *comp_match_res)
13196 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13199 /* symbol_name_matcher_ftype adapter for full_match. */
13201 static bool
13202 do_full_match (const char *symbol_search_name,
13203 const lookup_name_info &lookup_name,
13204 completion_match_result *comp_match_res)
13206 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13208 /* If both symbols start with "_ada_", just let the loop below
13209 handle the comparison. However, if only the symbol name starts
13210 with "_ada_", skip the prefix and let the match proceed as
13211 usual. */
13212 if (startswith (symbol_search_name, "_ada_")
13213 && !startswith (lname, "_ada"))
13214 symbol_search_name += 5;
13215 /* Likewise for ghost entities. */
13216 if (startswith (symbol_search_name, "___ghost_")
13217 && !startswith (lname, "___ghost_"))
13218 symbol_search_name += 9;
13220 int uscore_count = 0;
13221 while (*lname != '\0')
13223 if (*symbol_search_name != *lname)
13225 if (*symbol_search_name == 'B' && uscore_count == 2
13226 && symbol_search_name[1] == '_')
13228 symbol_search_name += 2;
13229 while (isdigit (*symbol_search_name))
13230 ++symbol_search_name;
13231 if (symbol_search_name[0] == '_'
13232 && symbol_search_name[1] == '_')
13234 symbol_search_name += 2;
13235 continue;
13238 return false;
13241 if (*symbol_search_name == '_')
13242 ++uscore_count;
13243 else
13244 uscore_count = 0;
13246 ++symbol_search_name;
13247 ++lname;
13250 return is_name_suffix (symbol_search_name);
13253 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13255 static bool
13256 do_exact_match (const char *symbol_search_name,
13257 const lookup_name_info &lookup_name,
13258 completion_match_result *comp_match_res)
13260 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13263 /* Build the Ada lookup name for LOOKUP_NAME. */
13265 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13267 std::string_view user_name = lookup_name.name ();
13269 if (!user_name.empty () && user_name[0] == '<')
13271 if (user_name.back () == '>')
13272 m_encoded_name = user_name.substr (1, user_name.size () - 2);
13273 else
13274 m_encoded_name = user_name.substr (1, user_name.size () - 1);
13275 m_encoded_p = true;
13276 m_verbatim_p = true;
13277 m_wild_match_p = false;
13278 m_standard_p = false;
13280 else
13282 m_verbatim_p = false;
13284 m_encoded_p = user_name.find ("__") != std::string_view::npos;
13286 if (!m_encoded_p)
13288 const char *folded = ada_fold_name (user_name);
13289 m_encoded_name = ada_encode_1 (folded, false);
13290 if (m_encoded_name.empty ())
13291 m_encoded_name = user_name;
13293 else
13294 m_encoded_name = user_name;
13296 /* Handle the 'package Standard' special case. See description
13297 of m_standard_p. */
13298 if (startswith (m_encoded_name.c_str (), "standard__"))
13300 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13301 m_standard_p = true;
13303 else
13304 m_standard_p = false;
13306 m_decoded_name = ada_decode (m_encoded_name.c_str (), true, false, false);
13308 /* If the name contains a ".", then the user is entering a fully
13309 qualified entity name, and the match must not be done in wild
13310 mode. Similarly, if the user wants to complete what looks
13311 like an encoded name, the match must not be done in wild
13312 mode. Also, in the standard__ special case always do
13313 non-wild matching. */
13314 m_wild_match_p
13315 = (lookup_name.match_type () != symbol_name_match_type::FULL
13316 && !m_encoded_p
13317 && !m_standard_p
13318 && user_name.find ('.') == std::string::npos);
13322 /* symbol_name_matcher_ftype method for Ada. This only handles
13323 completion mode. */
13325 static bool
13326 ada_symbol_name_matches (const char *symbol_search_name,
13327 const lookup_name_info &lookup_name,
13328 completion_match_result *comp_match_res)
13330 return lookup_name.ada ().matches (symbol_search_name,
13331 lookup_name.match_type (),
13332 comp_match_res);
13335 /* A name matcher that matches the symbol name exactly, with
13336 strcmp. */
13338 static bool
13339 literal_symbol_name_matcher (const char *symbol_search_name,
13340 const lookup_name_info &lookup_name,
13341 completion_match_result *comp_match_res)
13343 std::string_view name_view = lookup_name.name ();
13345 if (lookup_name.completion_mode ()
13346 ? (strncmp (symbol_search_name, name_view.data (),
13347 name_view.size ()) == 0)
13348 : symbol_search_name == name_view)
13350 if (comp_match_res != NULL)
13351 comp_match_res->set_match (symbol_search_name);
13352 return true;
13354 else
13355 return false;
13358 /* Implement the "get_symbol_name_matcher" language_defn method for
13359 Ada. */
13361 static symbol_name_matcher_ftype *
13362 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13364 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13365 return literal_symbol_name_matcher;
13367 if (lookup_name.completion_mode ())
13368 return ada_symbol_name_matches;
13369 else
13371 if (lookup_name.ada ().wild_match_p ())
13372 return do_wild_match;
13373 else if (lookup_name.ada ().verbatim_p ())
13374 return do_exact_match;
13375 else
13376 return do_full_match;
13380 /* Class representing the Ada language. */
13382 class ada_language : public language_defn
13384 public:
13385 ada_language ()
13386 : language_defn (language_ada)
13387 { /* Nothing. */ }
13389 /* See language.h. */
13391 const char *name () const override
13392 { return "ada"; }
13394 /* See language.h. */
13396 const char *natural_name () const override
13397 { return "Ada"; }
13399 /* See language.h. */
13401 const std::vector<const char *> &filename_extensions () const override
13403 static const std::vector<const char *> extensions
13404 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13405 return extensions;
13408 /* Print an array element index using the Ada syntax. */
13410 void print_array_index (struct type *index_type,
13411 LONGEST index,
13412 struct ui_file *stream,
13413 const value_print_options *options) const override
13415 struct value *index_value = val_atr (index_type, index);
13417 value_print (index_value, stream, options);
13418 gdb_printf (stream, " => ");
13421 /* Implement the "read_var_value" language_defn method for Ada. */
13423 struct value *read_var_value (struct symbol *var,
13424 const struct block *var_block,
13425 const frame_info_ptr &frame) const override
13427 /* The only case where default_read_var_value is not sufficient
13428 is when VAR is a renaming... */
13429 if (frame != nullptr)
13431 const struct block *frame_block = get_frame_block (frame, NULL);
13432 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13433 return ada_read_renaming_var_value (var, frame_block);
13436 /* This is a typical case where we expect the default_read_var_value
13437 function to work. */
13438 return language_defn::read_var_value (var, var_block, frame);
13441 /* See language.h. */
13442 bool symbol_printing_suppressed (struct symbol *symbol) const override
13444 return symbol->is_artificial ();
13447 /* See language.h. */
13448 struct value *value_string (struct gdbarch *gdbarch,
13449 const char *ptr, ssize_t len) const override
13451 struct type *type = language_string_char_type (this, gdbarch);
13452 value *val = ::value_string (ptr, len, type);
13453 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13454 strings that are arrays of characters, so fix the type now. */
13455 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13456 val->type ()->set_code (TYPE_CODE_ARRAY);
13457 return val;
13460 /* See language.h. */
13461 void language_arch_info (struct gdbarch *gdbarch,
13462 struct language_arch_info *lai) const override
13464 const struct builtin_type *builtin = builtin_type (gdbarch);
13466 /* Helper function to allow shorter lines below. */
13467 auto add = [&] (struct type *t)
13469 lai->add_primitive_type (t);
13472 type_allocator alloc (gdbarch);
13473 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13474 0, "integer"));
13475 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13476 0, "long_integer"));
13477 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13478 0, "short_integer"));
13479 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13480 1, "character");
13481 lai->set_string_char_type (char_type);
13482 add (char_type);
13483 add (init_character_type (alloc, 16, 1, "wide_character"));
13484 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13485 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13486 "float", gdbarch_float_format (gdbarch)));
13487 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13488 "long_float", gdbarch_double_format (gdbarch)));
13489 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13490 0, "long_long_integer"));
13491 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13492 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
13493 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13494 "long_long_float",
13495 gdbarch_long_double_format (gdbarch)));
13496 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13497 0, "natural"));
13498 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13499 0, "positive"));
13500 add (builtin->builtin_void);
13502 struct type *system_addr_ptr
13503 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13504 "void"));
13505 system_addr_ptr->set_name ("system__address");
13506 add (system_addr_ptr);
13508 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13509 type. This is a signed integral type whose size is the same as
13510 the size of addresses. */
13511 unsigned int addr_length = system_addr_ptr->length ();
13512 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13513 "storage_offset"));
13515 lai->set_bool_type (builtin->builtin_bool);
13518 /* See language.h. */
13520 bool iterate_over_symbols
13521 (const struct block *block, const lookup_name_info &name,
13522 domain_search_flags domain,
13523 gdb::function_view<symbol_found_callback_ftype> callback) const override
13525 std::vector<struct block_symbol> results
13526 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13527 for (block_symbol &sym : results)
13529 if (!callback (&sym))
13530 return false;
13533 return true;
13536 /* See language.h. */
13537 bool sniff_from_mangled_name
13538 (const char *mangled,
13539 gdb::unique_xmalloc_ptr<char> *out) const override
13541 std::string demangled = ada_decode (mangled);
13543 *out = NULL;
13545 if (demangled != mangled && demangled[0] != '<')
13547 /* Set the gsymbol language to Ada, but still return 0.
13548 Two reasons for that:
13550 1. For Ada, we prefer computing the symbol's decoded name
13551 on the fly rather than pre-compute it, in order to save
13552 memory (Ada projects are typically very large).
13554 2. There are some areas in the definition of the GNAT
13555 encoding where, with a bit of bad luck, we might be able
13556 to decode a non-Ada symbol, generating an incorrect
13557 demangled name (Eg: names ending with "TB" for instance
13558 are identified as task bodies and so stripped from
13559 the decoded name returned).
13561 Returning true, here, but not setting *DEMANGLED, helps us get
13562 a little bit of the best of both worlds. Because we're last,
13563 we should not affect any of the other languages that were
13564 able to demangle the symbol before us; we get to correctly
13565 tag Ada symbols as such; and even if we incorrectly tagged a
13566 non-Ada symbol, which should be rare, any routing through the
13567 Ada language should be transparent (Ada tries to behave much
13568 like C/C++ with non-Ada symbols). */
13569 return true;
13572 return false;
13575 /* See language.h. */
13577 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13578 int options) const override
13580 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13583 /* See language.h. */
13585 void print_type (struct type *type, const char *varstring,
13586 struct ui_file *stream, int show, int level,
13587 const struct type_print_options *flags) const override
13589 ada_print_type (type, varstring, stream, show, level, flags);
13592 /* See language.h. */
13594 const char *word_break_characters (void) const override
13596 return ada_completer_word_break_characters;
13599 /* See language.h. */
13601 void collect_symbol_completion_matches (completion_tracker &tracker,
13602 complete_symbol_mode mode,
13603 symbol_name_match_type name_match_type,
13604 const char *text, const char *word,
13605 enum type_code code) const override
13607 const struct block *b, *surrounding_static_block = 0;
13609 gdb_assert (code == TYPE_CODE_UNDEF);
13611 lookup_name_info lookup_name (text, name_match_type, true);
13613 /* First, look at the partial symtab symbols. */
13614 expand_symtabs_matching (NULL,
13615 lookup_name,
13616 NULL,
13617 NULL,
13618 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13619 SEARCH_ALL_DOMAINS);
13621 /* At this point scan through the misc symbol vectors and add each
13622 symbol you find to the list. Eventually we want to ignore
13623 anything that isn't a text symbol (everything else will be
13624 handled by the psymtab code above). */
13626 for (objfile *objfile : current_program_space->objfiles ())
13628 for (minimal_symbol *msymbol : objfile->msymbols ())
13630 QUIT;
13632 if (completion_skip_symbol (mode, msymbol))
13633 continue;
13635 language symbol_language = msymbol->language ();
13637 /* Ada minimal symbols won't have their language set to Ada. If
13638 we let completion_list_add_name compare using the
13639 default/C-like matcher, then when completing e.g., symbols in a
13640 package named "pck", we'd match internal Ada symbols like
13641 "pckS", which are invalid in an Ada expression, unless you wrap
13642 them in '<' '>' to request a verbatim match.
13644 Unfortunately, some Ada encoded names successfully demangle as
13645 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13646 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13647 with the wrong language set. Paper over that issue here. */
13648 if (symbol_language == language_unknown
13649 || symbol_language == language_cplus)
13650 symbol_language = language_ada;
13652 completion_list_add_name (tracker,
13653 symbol_language,
13654 msymbol->linkage_name (),
13655 lookup_name, text, word);
13659 /* Search upwards from currently selected frame (so that we can
13660 complete on local vars. */
13662 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13664 if (!b->superblock ())
13665 surrounding_static_block = b; /* For elmin of dups */
13667 for (struct symbol *sym : block_iterator_range (b))
13669 if (completion_skip_symbol (mode, sym))
13670 continue;
13672 completion_list_add_name (tracker,
13673 sym->language (),
13674 sym->linkage_name (),
13675 lookup_name, text, word);
13679 /* Go through the symtabs and check the externs and statics for
13680 symbols which match. */
13682 for (objfile *objfile : current_program_space->objfiles ())
13684 for (compunit_symtab *s : objfile->compunits ())
13686 QUIT;
13687 b = s->blockvector ()->global_block ();
13688 for (struct symbol *sym : block_iterator_range (b))
13690 if (completion_skip_symbol (mode, sym))
13691 continue;
13693 completion_list_add_name (tracker,
13694 sym->language (),
13695 sym->linkage_name (),
13696 lookup_name, text, word);
13701 for (objfile *objfile : current_program_space->objfiles ())
13703 for (compunit_symtab *s : objfile->compunits ())
13705 QUIT;
13706 b = s->blockvector ()->static_block ();
13707 /* Don't do this block twice. */
13708 if (b == surrounding_static_block)
13709 continue;
13710 for (struct symbol *sym : block_iterator_range (b))
13712 if (completion_skip_symbol (mode, sym))
13713 continue;
13715 completion_list_add_name (tracker,
13716 sym->language (),
13717 sym->linkage_name (),
13718 lookup_name, text, word);
13724 /* See language.h. */
13726 gdb::unique_xmalloc_ptr<char> watch_location_expression
13727 (struct type *type, CORE_ADDR addr) const override
13729 type = check_typedef (check_typedef (type)->target_type ());
13730 std::string name = type_to_string (type);
13731 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13734 /* See language.h. */
13736 void value_print (struct value *val, struct ui_file *stream,
13737 const struct value_print_options *options) const override
13739 return ada_value_print (val, stream, options);
13742 /* See language.h. */
13744 void value_print_inner
13745 (struct value *val, struct ui_file *stream, int recurse,
13746 const struct value_print_options *options) const override
13748 return ada_value_print_inner (val, stream, recurse, options);
13751 /* See language.h. */
13753 struct block_symbol lookup_symbol_nonlocal
13754 (const char *name, const struct block *block,
13755 const domain_search_flags domain) const override
13757 struct block_symbol sym;
13759 sym = ada_lookup_symbol (name,
13760 (block == nullptr
13761 ? nullptr
13762 : block->static_block ()),
13763 domain);
13764 if (sym.symbol != NULL)
13765 return sym;
13767 /* If we haven't found a match at this point, try the primitive
13768 types. In other languages, this search is performed before
13769 searching for global symbols in order to short-circuit that
13770 global-symbol search if it happens that the name corresponds
13771 to a primitive type. But we cannot do the same in Ada, because
13772 it is perfectly legitimate for a program to declare a type which
13773 has the same name as a standard type. If looking up a type in
13774 that situation, we have traditionally ignored the primitive type
13775 in favor of user-defined types. This is why, unlike most other
13776 languages, we search the primitive types this late and only after
13777 having searched the global symbols without success. */
13779 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
13781 struct gdbarch *gdbarch;
13783 if (block == NULL)
13784 gdbarch = current_inferior ()->arch ();
13785 else
13786 gdbarch = block->gdbarch ();
13787 sym.symbol
13788 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13789 if (sym.symbol != NULL)
13790 return sym;
13793 return {};
13796 /* See language.h. */
13798 int parser (struct parser_state *ps) const override
13800 warnings_issued = 0;
13801 return ada_parse (ps);
13804 /* See language.h. */
13806 void emitchar (int ch, struct type *chtype,
13807 struct ui_file *stream, int quoter) const override
13809 ada_emit_char (ch, chtype, stream, quoter, 1);
13812 /* See language.h. */
13814 void printchar (int ch, struct type *chtype,
13815 struct ui_file *stream) const override
13817 ada_printchar (ch, chtype, stream);
13820 /* See language.h. */
13822 void printstr (struct ui_file *stream, struct type *elttype,
13823 const gdb_byte *string, unsigned int length,
13824 const char *encoding, int force_ellipses,
13825 const struct value_print_options *options) const override
13827 ada_printstr (stream, elttype, string, length, encoding,
13828 force_ellipses, options);
13831 /* See language.h. */
13833 void print_typedef (struct type *type, struct symbol *new_symbol,
13834 struct ui_file *stream) const override
13836 ada_print_typedef (type, new_symbol, stream);
13839 /* See language.h. */
13841 bool is_string_type_p (struct type *type) const override
13843 return ada_is_string_type (type);
13846 /* See language.h. */
13848 bool is_array_like (struct type *type) const override
13850 return (ada_is_constrained_packed_array_type (type)
13851 || ada_is_array_descriptor_type (type));
13854 /* See language.h. */
13856 struct value *to_array (struct value *val) const override
13857 { return ada_coerce_to_simple_array (val); }
13859 /* See language.h. */
13861 const char *struct_too_deep_ellipsis () const override
13862 { return "(...)"; }
13864 /* See language.h. */
13866 bool c_style_arrays_p () const override
13867 { return false; }
13869 /* See language.h. */
13871 bool store_sym_names_in_linkage_form_p () const override
13872 { return true; }
13874 /* See language.h. */
13876 const struct lang_varobj_ops *varobj_ops () const override
13877 { return &ada_varobj_ops; }
13879 protected:
13880 /* See language.h. */
13882 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13883 (const lookup_name_info &lookup_name) const override
13885 return ada_get_symbol_name_matcher (lookup_name);
13889 /* Single instance of the Ada language class. */
13891 static ada_language ada_language_defn;
13893 /* Command-list for the "set/show ada" prefix command. */
13894 static struct cmd_list_element *set_ada_list;
13895 static struct cmd_list_element *show_ada_list;
13897 /* This module's 'new_objfile' observer. */
13899 static void
13900 ada_new_objfile_observer (struct objfile *objfile)
13902 ada_clear_symbol_cache (objfile->pspace ());
13905 /* This module's 'free_objfile' observer. */
13907 static void
13908 ada_free_objfile_observer (struct objfile *objfile)
13910 ada_clear_symbol_cache (objfile->pspace ());
13913 /* Charsets known to GNAT. */
13914 static const char * const gnat_source_charsets[] =
13916 /* Note that code below assumes that the default comes first.
13917 Latin-1 is the default here, because that is also GNAT's
13918 default. */
13919 "ISO-8859-1",
13920 "ISO-8859-2",
13921 "ISO-8859-3",
13922 "ISO-8859-4",
13923 "ISO-8859-5",
13924 "ISO-8859-15",
13925 "CP437",
13926 "CP850",
13927 /* Note that this value is special-cased in the encoder and
13928 decoder. */
13929 ada_utf8,
13930 nullptr
13933 void _initialize_ada_language ();
13934 void
13935 _initialize_ada_language ()
13937 add_setshow_prefix_cmd
13938 ("ada", no_class,
13939 _("Prefix command for changing Ada-specific settings."),
13940 _("Generic command for showing Ada-specific settings."),
13941 &set_ada_list, &show_ada_list,
13942 &setlist, &showlist);
13944 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13945 &trust_pad_over_xvs, _("\
13946 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13947 Show whether an optimization trusting PAD types over XVS types is activated."),
13948 _("\
13949 This is related to the encoding used by the GNAT compiler. The debugger\n\
13950 should normally trust the contents of PAD types, but certain older versions\n\
13951 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13952 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13953 work around this bug. It is always safe to turn this option \"off\", but\n\
13954 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13955 this option to \"off\" unless necessary."),
13956 NULL, NULL, &set_ada_list, &show_ada_list);
13958 add_setshow_boolean_cmd ("print-signatures", class_vars,
13959 &print_signatures, _("\
13960 Enable or disable the output of formal and return types for functions in the \
13961 overloads selection menu."), _("\
13962 Show whether the output of formal and return types for functions in the \
13963 overloads selection menu is activated."),
13964 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13966 ada_source_charset = gnat_source_charsets[0];
13967 add_setshow_enum_cmd ("source-charset", class_files,
13968 gnat_source_charsets,
13969 &ada_source_charset, _("\
13970 Set the Ada source character set."), _("\
13971 Show the Ada source character set."), _("\
13972 The character set used for Ada source files.\n\
13973 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13974 nullptr, nullptr,
13975 &set_ada_list, &show_ada_list);
13977 add_catch_command ("exception", _("\
13978 Catch Ada exceptions, when raised.\n\
13979 Usage: catch exception [ARG] [if CONDITION]\n\
13980 Without any argument, stop when any Ada exception is raised.\n\
13981 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13982 being raised does not have a handler (and will therefore lead to the task's\n\
13983 termination).\n\
13984 Otherwise, the catchpoint only stops when the name of the exception being\n\
13985 raised is the same as ARG.\n\
13986 CONDITION is a boolean expression that is evaluated to see whether the\n\
13987 exception should cause a stop."),
13988 catch_ada_exception_command,
13989 catch_ada_completer,
13990 CATCH_PERMANENT,
13991 CATCH_TEMPORARY);
13993 add_catch_command ("handlers", _("\
13994 Catch Ada exceptions, when handled.\n\
13995 Usage: catch handlers [ARG] [if CONDITION]\n\
13996 Without any argument, stop when any Ada exception is handled.\n\
13997 With an argument, catch only exceptions with the given name.\n\
13998 CONDITION is a boolean expression that is evaluated to see whether the\n\
13999 exception should cause a stop."),
14000 catch_ada_handlers_command,
14001 catch_ada_completer,
14002 CATCH_PERMANENT,
14003 CATCH_TEMPORARY);
14004 add_catch_command ("assert", _("\
14005 Catch failed Ada assertions, when raised.\n\
14006 Usage: catch assert [if CONDITION]\n\
14007 CONDITION is a boolean expression that is evaluated to see whether the\n\
14008 exception should cause a stop."),
14009 catch_assert_command,
14010 NULL,
14011 CATCH_PERMANENT,
14012 CATCH_TEMPORARY);
14014 add_info ("exceptions", info_exceptions_command,
14015 _("\
14016 List all Ada exception names.\n\
14017 Usage: info exceptions [REGEXP]\n\
14018 If a regular expression is passed as an argument, only those matching\n\
14019 the regular expression are listed."));
14021 add_setshow_prefix_cmd ("ada", class_maintenance,
14022 _("Set Ada maintenance-related variables."),
14023 _("Show Ada maintenance-related variables."),
14024 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14025 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14027 add_setshow_boolean_cmd
14028 ("ignore-descriptive-types", class_maintenance,
14029 &ada_ignore_descriptive_types_p,
14030 _("Set whether descriptive types generated by GNAT should be ignored."),
14031 _("Show whether descriptive types generated by GNAT should be ignored."),
14032 _("\
14033 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14034 DWARF attribute."),
14035 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14037 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14038 htab_eq_string,
14039 NULL, xcalloc, xfree);
14041 /* The ada-lang observers. */
14042 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14043 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14044 "ada-lang");
14045 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14046 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14048 #ifdef GDB_SELF_TEST
14049 selftests::register_test ("ada-decode", ada_decode_tests);
14050 #endif