Add translations for various sub-directories
[binutils-gdb.git] / gdb / ada-lang.c
blob1cfd8431c157ae925fc1a82c05f2d1a02228d726
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, throw an
1823 exception. */
1825 static struct value *
1826 desc_bounds (struct value *arr)
1828 struct type *type = ada_check_typedef (arr->type ());
1830 if (is_thin_pntr (type))
1832 struct type *bounds_type =
1833 desc_bounds_type (thin_descriptor_type (type));
1834 LONGEST addr;
1836 if (bounds_type == NULL)
1837 error (_("Bad GNAT array descriptor"));
1839 /* NOTE: The following calculation is not really kosher, but
1840 since desc_type is an XVE-encoded type (and shouldn't be),
1841 the correct calculation is a real pain. FIXME (and fix GCC). */
1842 if (type->code () == TYPE_CODE_PTR)
1843 addr = value_as_long (arr);
1844 else
1845 addr = arr->address ();
1847 return
1848 value_from_longest (lookup_pointer_type (bounds_type),
1849 addr - bounds_type->length ());
1852 else if (is_thick_pntr (type))
1854 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1855 _("Bad GNAT array descriptor"));
1856 struct type *p_bounds_type = p_bounds->type ();
1858 if (p_bounds_type
1859 && p_bounds_type->code () == TYPE_CODE_PTR)
1861 struct type *target_type = p_bounds_type->target_type ();
1863 if (target_type->is_stub ())
1864 p_bounds = value_cast (lookup_pointer_type
1865 (ada_check_typedef (target_type)),
1866 p_bounds);
1868 else
1869 error (_("Bad GNAT array descriptor"));
1871 return p_bounds;
1873 else
1874 error (_("Not an array"));
1877 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1878 position of the field containing the address of the bounds data. */
1880 static int
1881 fat_pntr_bounds_bitpos (struct type *type)
1883 return desc_base_type (type)->field (1).loc_bitpos ();
1886 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1887 size of the field containing the address of the bounds data. */
1889 static int
1890 fat_pntr_bounds_bitsize (struct type *type)
1892 type = desc_base_type (type);
1894 if (type->field (1).bitsize () > 0)
1895 return type->field (1).bitsize ();
1896 else
1897 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1900 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1901 pointer to one, the type of its array data (a array-with-no-bounds type);
1902 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1903 data. */
1905 static struct type *
1906 desc_data_target_type (struct type *type)
1908 type = desc_base_type (type);
1910 /* NOTE: The following is bogus; see comment in desc_bounds. */
1911 if (is_thin_pntr (type))
1912 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1913 else if (is_thick_pntr (type))
1915 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1917 if (data_type
1918 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1919 return ada_check_typedef (data_type->target_type ());
1922 return NULL;
1925 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1926 its array data. */
1928 static struct value *
1929 desc_data (struct value *arr)
1931 struct type *type = arr->type ();
1933 if (is_thin_pntr (type))
1934 return thin_data_pntr (arr);
1935 else if (is_thick_pntr (type))
1936 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1937 _("Bad GNAT array descriptor"));
1938 else
1939 return NULL;
1943 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1944 position of the field containing the address of the data. */
1946 static int
1947 fat_pntr_data_bitpos (struct type *type)
1949 return desc_base_type (type)->field (0).loc_bitpos ();
1952 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1953 size of the field containing the address of the data. */
1955 static int
1956 fat_pntr_data_bitsize (struct type *type)
1958 type = desc_base_type (type);
1960 if (type->field (0).bitsize () > 0)
1961 return type->field (0).bitsize ();
1962 else
1963 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1966 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1967 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1968 bound, if WHICH is 1. The first bound is I=1. */
1970 static struct value *
1971 desc_one_bound (struct value *bounds, int i, int which)
1973 char bound_name[20];
1974 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1975 which ? 'U' : 'L', i - 1);
1976 return value_struct_elt (&bounds, {}, bound_name, NULL,
1977 _("Bad GNAT array descriptor bounds"));
1980 /* If BOUNDS is an array-bounds structure type, return the bit position
1981 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1982 bound, if WHICH is 1. The first bound is I=1. */
1984 static int
1985 desc_bound_bitpos (struct type *type, int i, int which)
1987 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1990 /* If BOUNDS is an array-bounds structure type, return the bit field size
1991 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1992 bound, if WHICH is 1. The first bound is I=1. */
1994 static int
1995 desc_bound_bitsize (struct type *type, int i, int which)
1997 type = desc_base_type (type);
1999 if (type->field (2 * i + which - 2).bitsize () > 0)
2000 return type->field (2 * i + which - 2).bitsize ();
2001 else
2002 return 8 * type->field (2 * i + which - 2).type ()->length ();
2005 /* If TYPE is the type of an array-bounds structure, the type of its
2006 Ith bound (numbering from 1). Otherwise, NULL. */
2008 static struct type *
2009 desc_index_type (struct type *type, int i)
2011 type = desc_base_type (type);
2013 if (type->code () == TYPE_CODE_STRUCT)
2015 char bound_name[20];
2016 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2017 return lookup_struct_elt_type (type, bound_name, 1);
2019 else
2020 return NULL;
2023 /* The number of index positions in the array-bounds type TYPE.
2024 Return 0 if TYPE is NULL. */
2026 static int
2027 desc_arity (struct type *type)
2029 type = desc_base_type (type);
2031 if (type != NULL)
2032 return type->num_fields () / 2;
2033 return 0;
2036 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2037 an array descriptor type (representing an unconstrained array
2038 type). */
2040 static int
2041 ada_is_direct_array_type (struct type *type)
2043 if (type == NULL)
2044 return 0;
2045 type = ada_check_typedef (type);
2046 return (type->code () == TYPE_CODE_ARRAY
2047 || ada_is_array_descriptor_type (type));
2050 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2051 * to one. */
2053 static int
2054 ada_is_array_type (struct type *type)
2056 while (type != NULL
2057 && (type->code () == TYPE_CODE_PTR
2058 || type->code () == TYPE_CODE_REF))
2059 type = type->target_type ();
2060 return ada_is_direct_array_type (type);
2063 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2066 ada_is_simple_array_type (struct type *type)
2068 if (type == NULL)
2069 return 0;
2070 type = ada_check_typedef (type);
2071 return (type->code () == TYPE_CODE_ARRAY
2072 || (type->code () == TYPE_CODE_PTR
2073 && (ada_check_typedef (type->target_type ())->code ()
2074 == TYPE_CODE_ARRAY)));
2077 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2080 ada_is_array_descriptor_type (struct type *type)
2082 struct type *data_type = desc_data_target_type (type);
2084 if (type == NULL)
2085 return 0;
2086 type = ada_check_typedef (type);
2087 return (data_type != NULL
2088 && data_type->code () == TYPE_CODE_ARRAY
2089 && desc_arity (desc_bounds_type (type)) > 0);
2092 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2093 (fat pointer) returns the type of the array data described---specifically,
2094 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2095 in from the descriptor; otherwise, they are left unspecified. If
2096 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2097 returns NULL. The result is simply the type of ARR if ARR is not
2098 a descriptor. */
2100 static struct type *
2101 ada_type_of_array (struct value *arr, int bounds)
2103 if (ada_is_constrained_packed_array_type (arr->type ()))
2104 return decode_constrained_packed_array_type (arr->type ());
2106 if (!ada_is_array_descriptor_type (arr->type ()))
2107 return arr->type ();
2109 if (!bounds)
2111 struct type *array_type =
2112 ada_check_typedef (desc_data_target_type (arr->type ()));
2114 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2115 array_type->field (0).set_bitsize
2116 (decode_packed_array_bitsize (arr->type ()));
2118 return array_type;
2120 else
2122 struct type *elt_type;
2123 int arity;
2124 struct value *descriptor;
2126 elt_type = ada_array_element_type (arr->type (), -1);
2127 arity = ada_array_arity (arr->type ());
2129 if (elt_type == NULL || arity == 0)
2130 return ada_check_typedef (arr->type ());
2132 descriptor = desc_bounds (arr);
2133 if (value_as_long (descriptor) == 0)
2134 return NULL;
2135 while (arity > 0)
2137 type_allocator alloc (arr->type ());
2138 struct value *low = desc_one_bound (descriptor, arity, 0);
2139 struct value *high = desc_one_bound (descriptor, arity, 1);
2141 arity -= 1;
2142 struct type *range_type
2143 = create_static_range_type (alloc, low->type (),
2144 longest_to_int (value_as_long (low)),
2145 longest_to_int (value_as_long (high)));
2146 elt_type = create_array_type (alloc, elt_type, range_type);
2147 INIT_GNAT_SPECIFIC (elt_type);
2149 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2151 /* We need to store the element packed bitsize, as well as
2152 recompute the array size, because it was previously
2153 computed based on the unpacked element size. */
2154 LONGEST lo = value_as_long (low);
2155 LONGEST hi = value_as_long (high);
2157 elt_type->field (0).set_bitsize
2158 (decode_packed_array_bitsize (arr->type ()));
2160 /* If the array has no element, then the size is already
2161 zero, and does not need to be recomputed. */
2162 if (lo < hi)
2164 int array_bitsize =
2165 (hi - lo + 1) * elt_type->field (0).bitsize ();
2167 elt_type->set_length ((array_bitsize + 7) / 8);
2172 return lookup_pointer_type (elt_type);
2176 /* If ARR does not represent an array, returns ARR unchanged.
2177 Otherwise, returns either a standard GDB array with bounds set
2178 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2179 GDB array. Returns NULL if ARR is a null fat pointer. */
2181 struct value *
2182 ada_coerce_to_simple_array_ptr (struct value *arr)
2184 if (ada_is_array_descriptor_type (arr->type ()))
2186 struct type *arrType = ada_type_of_array (arr, 1);
2188 if (arrType == NULL)
2189 return NULL;
2190 return value_cast (arrType, desc_data (arr)->copy ());
2192 else if (ada_is_constrained_packed_array_type (arr->type ()))
2193 return decode_constrained_packed_array (arr);
2194 else
2195 return arr;
2198 /* If ARR does not represent an array, returns ARR unchanged.
2199 Otherwise, returns a standard GDB array describing ARR (which may
2200 be ARR itself if it already is in the proper form). */
2202 struct value *
2203 ada_coerce_to_simple_array (struct value *arr)
2205 if (ada_is_array_descriptor_type (arr->type ()))
2207 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2209 if (arrVal == NULL)
2210 error (_("Bounds unavailable for null array pointer."));
2211 return value_ind (arrVal);
2213 else if (ada_is_constrained_packed_array_type (arr->type ()))
2214 return decode_constrained_packed_array (arr);
2215 else
2216 return arr;
2219 /* If TYPE represents a GNAT array type, return it translated to an
2220 ordinary GDB array type (possibly with BITSIZE fields indicating
2221 packing). For other types, is the identity. */
2223 struct type *
2224 ada_coerce_to_simple_array_type (struct type *type)
2226 if (ada_is_constrained_packed_array_type (type))
2227 return decode_constrained_packed_array_type (type);
2229 if (ada_is_array_descriptor_type (type))
2230 return ada_check_typedef (desc_data_target_type (type));
2232 return type;
2235 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2237 static int
2238 ada_is_gnat_encoded_packed_array_type (struct type *type)
2240 if (type == NULL)
2241 return 0;
2242 type = desc_base_type (type);
2243 type = ada_check_typedef (type);
2244 return
2245 ada_type_name (type) != NULL
2246 && strstr (ada_type_name (type), "___XP") != NULL;
2249 /* Non-zero iff TYPE represents a standard GNAT constrained
2250 packed-array type. */
2253 ada_is_constrained_packed_array_type (struct type *type)
2255 return ada_is_gnat_encoded_packed_array_type (type)
2256 && !ada_is_array_descriptor_type (type);
2259 /* Non-zero iff TYPE represents an array descriptor for a
2260 unconstrained packed-array type. */
2262 static int
2263 ada_is_unconstrained_packed_array_type (struct type *type)
2265 if (!ada_is_array_descriptor_type (type))
2266 return 0;
2268 if (ada_is_gnat_encoded_packed_array_type (type))
2269 return 1;
2271 /* If we saw GNAT encodings, then the above code is sufficient.
2272 However, with minimal encodings, we will just have a thick
2273 pointer instead. */
2274 if (is_thick_pntr (type))
2276 type = desc_base_type (type);
2277 /* The structure's first field is a pointer to an array, so this
2278 fetches the array type. */
2279 type = type->field (0).type ()->target_type ();
2280 if (type->code () == TYPE_CODE_TYPEDEF)
2281 type = ada_typedef_target_type (type);
2282 /* Now we can see if the array elements are packed. */
2283 return type->field (0).bitsize () > 0;
2286 return 0;
2289 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2290 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2292 static bool
2293 ada_is_any_packed_array_type (struct type *type)
2295 return (ada_is_constrained_packed_array_type (type)
2296 || (type->code () == TYPE_CODE_ARRAY
2297 && type->field (0).bitsize () % 8 != 0));
2300 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2301 return the size of its elements in bits. */
2303 static long
2304 decode_packed_array_bitsize (struct type *type)
2306 const char *raw_name;
2307 const char *tail;
2308 long bits;
2310 /* Access to arrays implemented as fat pointers are encoded as a typedef
2311 of the fat pointer type. We need the name of the fat pointer type
2312 to do the decoding, so strip the typedef layer. */
2313 if (type->code () == TYPE_CODE_TYPEDEF)
2314 type = ada_typedef_target_type (type);
2316 raw_name = ada_type_name (ada_check_typedef (type));
2317 if (!raw_name)
2318 raw_name = ada_type_name (desc_base_type (type));
2320 if (!raw_name)
2321 return 0;
2323 tail = strstr (raw_name, "___XP");
2324 if (tail == nullptr)
2326 gdb_assert (is_thick_pntr (type));
2327 /* The structure's first field is a pointer to an array, so this
2328 fetches the array type. */
2329 type = type->field (0).type ()->target_type ();
2330 /* Now we can see if the array elements are packed. */
2331 return type->field (0).bitsize ();
2334 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2336 lim_warning
2337 (_("could not understand bit size information on packed array"));
2338 return 0;
2341 return bits;
2344 /* Given that TYPE is a standard GDB array type with all bounds filled
2345 in, and that the element size of its ultimate scalar constituents
2346 (that is, either its elements, or, if it is an array of arrays, its
2347 elements' elements, etc.) is *ELT_BITS, return an identical type,
2348 but with the bit sizes of its elements (and those of any
2349 constituent arrays) recorded in the BITSIZE components of its
2350 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2351 in bits.
2353 Note that, for arrays whose index type has an XA encoding where
2354 a bound references a record discriminant, getting that discriminant,
2355 and therefore the actual value of that bound, is not possible
2356 because none of the given parameters gives us access to the record.
2357 This function assumes that it is OK in the context where it is being
2358 used to return an array whose bounds are still dynamic and where
2359 the length is arbitrary. */
2361 static struct type *
2362 constrained_packed_array_type (struct type *type, long *elt_bits)
2364 struct type *new_elt_type;
2365 struct type *new_type;
2366 struct type *index_type_desc;
2367 struct type *index_type;
2368 LONGEST low_bound, high_bound;
2370 type = ada_check_typedef (type);
2371 if (type->code () != TYPE_CODE_ARRAY)
2372 return type;
2374 index_type_desc = ada_find_parallel_type (type, "___XA");
2375 if (index_type_desc)
2376 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2377 NULL);
2378 else
2379 index_type = type->index_type ();
2381 type_allocator alloc (type);
2382 new_elt_type =
2383 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2384 elt_bits);
2385 new_type = create_array_type (alloc, new_elt_type, index_type);
2386 new_type->field (0).set_bitsize (*elt_bits);
2387 new_type->set_name (ada_type_name (type));
2389 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2390 && is_dynamic_type (check_typedef (index_type)))
2391 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2392 low_bound = high_bound = 0;
2393 if (high_bound < low_bound)
2395 *elt_bits = 0;
2396 new_type->set_length (0);
2398 else
2400 *elt_bits *= (high_bound - low_bound + 1);
2401 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2404 new_type->set_is_fixed_instance (true);
2405 return new_type;
2408 /* The array type encoded by TYPE, where
2409 ada_is_constrained_packed_array_type (TYPE). */
2411 static struct type *
2412 decode_constrained_packed_array_type (struct type *type)
2414 const char *raw_name = ada_type_name (ada_check_typedef (type));
2415 char *name;
2416 const char *tail;
2417 struct type *shadow_type;
2418 long bits;
2420 if (!raw_name)
2421 raw_name = ada_type_name (desc_base_type (type));
2423 if (!raw_name)
2424 return NULL;
2426 name = (char *) alloca (strlen (raw_name) + 1);
2427 tail = strstr (raw_name, "___XP");
2428 type = desc_base_type (type);
2430 memcpy (name, raw_name, tail - raw_name);
2431 name[tail - raw_name] = '\000';
2433 shadow_type = ada_find_parallel_type_with_name (type, name);
2435 if (shadow_type == NULL)
2437 lim_warning (_("could not find bounds information on packed array"));
2438 return NULL;
2440 shadow_type = check_typedef (shadow_type);
2442 if (shadow_type->code () != TYPE_CODE_ARRAY)
2444 lim_warning (_("could not understand bounds "
2445 "information on packed array"));
2446 return NULL;
2449 bits = decode_packed_array_bitsize (type);
2450 return constrained_packed_array_type (shadow_type, &bits);
2453 /* Helper function for decode_constrained_packed_array. Set the field
2454 bitsize on a series of packed arrays. Returns the number of
2455 elements in TYPE. */
2457 static LONGEST
2458 recursively_update_array_bitsize (struct type *type)
2460 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2462 LONGEST low, high;
2463 if (!get_discrete_bounds (type->index_type (), &low, &high)
2464 || low > high)
2465 return 0;
2466 LONGEST our_len = high - low + 1;
2468 struct type *elt_type = type->target_type ();
2469 if (elt_type->code () == TYPE_CODE_ARRAY)
2471 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2472 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
2473 type->field (0).set_bitsize (elt_bitsize);
2475 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2476 / HOST_CHAR_BIT));
2479 return our_len;
2482 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2483 array, returns a simple array that denotes that array. Its type is a
2484 standard GDB array type except that the BITSIZEs of the array
2485 target types are set to the number of bits in each element, and the
2486 type length is set appropriately. */
2488 static struct value *
2489 decode_constrained_packed_array (struct value *arr)
2491 struct type *type;
2493 /* If our value is a pointer, then dereference it. Likewise if
2494 the value is a reference. Make sure that this operation does not
2495 cause the target type to be fixed, as this would indirectly cause
2496 this array to be decoded. The rest of the routine assumes that
2497 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2498 and "value_ind" routines to perform the dereferencing, as opposed
2499 to using "ada_coerce_ref" or "ada_value_ind". */
2500 arr = coerce_ref (arr);
2501 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2502 arr = value_ind (arr);
2504 type = decode_constrained_packed_array_type (arr->type ());
2505 if (type == NULL)
2507 error (_("can't unpack array"));
2508 return NULL;
2511 /* Decoding the packed array type could not correctly set the field
2512 bitsizes for any dimension except the innermost, because the
2513 bounds may be variable and were not passed to that function. So,
2514 we further resolve the array bounds here and then update the
2515 sizes. */
2516 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2517 CORE_ADDR address = arr->address ();
2518 gdb::array_view<const gdb_byte> view
2519 = gdb::make_array_view (valaddr, type->length ());
2520 type = resolve_dynamic_type (type, view, address);
2521 recursively_update_array_bitsize (type);
2523 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2524 && ada_is_modular_type (arr->type ()))
2526 /* This is a (right-justified) modular type representing a packed
2527 array with no wrapper. In order to interpret the value through
2528 the (left-justified) packed array type we just built, we must
2529 first left-justify it. */
2530 int bit_size, bit_pos;
2531 ULONGEST mod;
2533 mod = ada_modulus (arr->type ()) - 1;
2534 bit_size = 0;
2535 while (mod > 0)
2537 bit_size += 1;
2538 mod >>= 1;
2540 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2541 arr = ada_value_primitive_packed_val (arr, NULL,
2542 bit_pos / HOST_CHAR_BIT,
2543 bit_pos % HOST_CHAR_BIT,
2544 bit_size,
2545 type);
2548 return coerce_unspec_val_to_type (arr, type);
2552 /* The value of the element of packed array ARR at the ARITY indices
2553 given in IND. ARR must be a simple array. */
2555 static struct value *
2556 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2558 int i;
2559 int bits, elt_off, bit_off;
2560 long elt_total_bit_offset;
2561 struct type *elt_type;
2562 struct value *v;
2564 bits = 0;
2565 elt_total_bit_offset = 0;
2566 elt_type = ada_check_typedef (arr->type ());
2567 for (i = 0; i < arity; i += 1)
2569 if (elt_type->code () != TYPE_CODE_ARRAY
2570 || elt_type->field (0).bitsize () == 0)
2571 error
2572 (_("attempt to do packed indexing of "
2573 "something other than a packed array"));
2574 else
2576 struct type *range_type = elt_type->index_type ();
2577 LONGEST lowerbound, upperbound;
2578 LONGEST idx;
2580 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2582 lim_warning (_("don't know bounds of array"));
2583 lowerbound = upperbound = 0;
2586 idx = pos_atr (ind[i]);
2587 if (idx < lowerbound || idx > upperbound)
2588 lim_warning (_("packed array index %ld out of bounds"),
2589 (long) idx);
2590 bits = elt_type->field (0).bitsize ();
2591 elt_total_bit_offset += (idx - lowerbound) * bits;
2592 elt_type = ada_check_typedef (elt_type->target_type ());
2595 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2596 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2598 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2599 bits, elt_type);
2600 return v;
2603 /* Non-zero iff TYPE includes negative integer values. */
2605 static int
2606 has_negatives (struct type *type)
2608 switch (type->code ())
2610 default:
2611 return 0;
2612 case TYPE_CODE_INT:
2613 return !type->is_unsigned ();
2614 case TYPE_CODE_RANGE:
2615 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2619 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2620 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2621 the unpacked buffer.
2623 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2624 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2626 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2627 zero otherwise.
2629 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2631 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2633 static void
2634 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2635 gdb_byte *unpacked, int unpacked_len,
2636 int is_big_endian, int is_signed_type,
2637 int is_scalar)
2639 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2640 int src_idx; /* Index into the source area */
2641 int src_bytes_left; /* Number of source bytes left to process. */
2642 int srcBitsLeft; /* Number of source bits left to move */
2643 int unusedLS; /* Number of bits in next significant
2644 byte of source that are unused */
2646 int unpacked_idx; /* Index into the unpacked buffer */
2647 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2649 unsigned long accum; /* Staging area for bits being transferred */
2650 int accumSize; /* Number of meaningful bits in accum */
2651 unsigned char sign;
2653 /* Transmit bytes from least to most significant; delta is the direction
2654 the indices move. */
2655 int delta = is_big_endian ? -1 : 1;
2657 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2658 bits from SRC. .*/
2659 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2660 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2661 bit_size, unpacked_len);
2663 srcBitsLeft = bit_size;
2664 src_bytes_left = src_len;
2665 unpacked_bytes_left = unpacked_len;
2666 sign = 0;
2668 if (is_big_endian)
2670 src_idx = src_len - 1;
2671 if (is_signed_type
2672 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2673 sign = ~0;
2675 unusedLS =
2676 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2677 % HOST_CHAR_BIT;
2679 if (is_scalar)
2681 accumSize = 0;
2682 unpacked_idx = unpacked_len - 1;
2684 else
2686 /* Non-scalar values must be aligned at a byte boundary... */
2687 accumSize =
2688 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2689 /* ... And are placed at the beginning (most-significant) bytes
2690 of the target. */
2691 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2692 unpacked_bytes_left = unpacked_idx + 1;
2695 else
2697 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2699 src_idx = unpacked_idx = 0;
2700 unusedLS = bit_offset;
2701 accumSize = 0;
2703 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2704 sign = ~0;
2707 accum = 0;
2708 while (src_bytes_left > 0)
2710 /* Mask for removing bits of the next source byte that are not
2711 part of the value. */
2712 unsigned int unusedMSMask =
2713 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2715 /* Sign-extend bits for this byte. */
2716 unsigned int signMask = sign & ~unusedMSMask;
2718 accum |=
2719 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2720 accumSize += HOST_CHAR_BIT - unusedLS;
2721 if (accumSize >= HOST_CHAR_BIT)
2723 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2724 accumSize -= HOST_CHAR_BIT;
2725 accum >>= HOST_CHAR_BIT;
2726 unpacked_bytes_left -= 1;
2727 unpacked_idx += delta;
2729 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2730 unusedLS = 0;
2731 src_bytes_left -= 1;
2732 src_idx += delta;
2734 while (unpacked_bytes_left > 0)
2736 accum |= sign << accumSize;
2737 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2738 accumSize -= HOST_CHAR_BIT;
2739 if (accumSize < 0)
2740 accumSize = 0;
2741 accum >>= HOST_CHAR_BIT;
2742 unpacked_bytes_left -= 1;
2743 unpacked_idx += delta;
2747 /* Create a new value of type TYPE from the contents of OBJ starting
2748 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2749 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2750 assigning through the result will set the field fetched from.
2751 VALADDR is ignored unless OBJ is NULL, in which case,
2752 VALADDR+OFFSET must address the start of storage containing the
2753 packed value. The value returned in this case is never an lval.
2754 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2756 struct value *
2757 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2758 long offset, int bit_offset, int bit_size,
2759 struct type *type)
2761 struct value *v;
2762 const gdb_byte *src; /* First byte containing data to unpack */
2763 gdb_byte *unpacked;
2764 const int is_scalar = is_scalar_type (type);
2765 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2766 gdb::byte_vector staging;
2768 type = ada_check_typedef (type);
2770 if (obj == NULL)
2771 src = valaddr + offset;
2772 else
2773 src = obj->contents ().data () + offset;
2775 if (is_dynamic_type (type))
2777 /* The length of TYPE might by dynamic, so we need to resolve
2778 TYPE in order to know its actual size, which we then use
2779 to create the contents buffer of the value we return.
2780 The difficulty is that the data containing our object is
2781 packed, and therefore maybe not at a byte boundary. So, what
2782 we do, is unpack the data into a byte-aligned buffer, and then
2783 use that buffer as our object's value for resolving the type. */
2784 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2785 staging.resize (staging_len);
2787 ada_unpack_from_contents (src, bit_offset, bit_size,
2788 staging.data (), staging.size (),
2789 is_big_endian, has_negatives (type),
2790 is_scalar);
2791 type = resolve_dynamic_type (type, staging, 0);
2792 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2794 /* This happens when the length of the object is dynamic,
2795 and is actually smaller than the space reserved for it.
2796 For instance, in an array of variant records, the bit_size
2797 we're given is the array stride, which is constant and
2798 normally equal to the maximum size of its element.
2799 But, in reality, each element only actually spans a portion
2800 of that stride. */
2801 bit_size = type->length () * HOST_CHAR_BIT;
2805 if (obj == NULL)
2807 v = value::allocate (type);
2808 src = valaddr + offset;
2810 else if (obj->lval () == lval_memory && obj->lazy ())
2812 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2813 gdb_byte *buf;
2815 v = value_at (type, obj->address () + offset);
2816 buf = (gdb_byte *) alloca (src_len);
2817 read_memory (v->address (), buf, src_len);
2818 src = buf;
2820 else
2822 v = value::allocate (type);
2823 src = obj->contents ().data () + offset;
2826 if (obj != NULL)
2828 long new_offset = offset;
2830 v->set_component_location (obj);
2831 v->set_bitpos (bit_offset + obj->bitpos ());
2832 v->set_bitsize (bit_size);
2833 if (v->bitpos () >= HOST_CHAR_BIT)
2835 ++new_offset;
2836 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2838 v->set_offset (new_offset);
2840 /* Also set the parent value. This is needed when trying to
2841 assign a new value (in inferior memory). */
2842 v->set_parent (obj);
2844 else
2845 v->set_bitsize (bit_size);
2846 unpacked = v->contents_writeable ().data ();
2848 if (bit_size == 0)
2850 memset (unpacked, 0, type->length ());
2851 return v;
2854 if (staging.size () == type->length ())
2856 /* Small short-cut: If we've unpacked the data into a buffer
2857 of the same size as TYPE's length, then we can reuse that,
2858 instead of doing the unpacking again. */
2859 memcpy (unpacked, staging.data (), staging.size ());
2861 else
2862 ada_unpack_from_contents (src, bit_offset, bit_size,
2863 unpacked, type->length (),
2864 is_big_endian, has_negatives (type), is_scalar);
2866 return v;
2869 /* Store the contents of FROMVAL into the location of TOVAL.
2870 Return a new value with the location of TOVAL and contents of
2871 FROMVAL. Handles assignment into packed fields that have
2872 floating-point or non-scalar types. */
2874 static struct value *
2875 ada_value_assign (struct value *toval, struct value *fromval)
2877 struct type *type = toval->type ();
2878 int bits = toval->bitsize ();
2880 toval = ada_coerce_ref (toval);
2881 fromval = ada_coerce_ref (fromval);
2883 if (ada_is_direct_array_type (toval->type ()))
2884 toval = ada_coerce_to_simple_array (toval);
2885 if (ada_is_direct_array_type (fromval->type ()))
2886 fromval = ada_coerce_to_simple_array (fromval);
2888 if (!toval->deprecated_modifiable ())
2889 error (_("Left operand of assignment is not a modifiable lvalue."));
2891 if (toval->lval () == lval_memory
2892 && bits > 0
2893 && (type->code () == TYPE_CODE_FLT
2894 || type->code () == TYPE_CODE_STRUCT))
2896 int len = (toval->bitpos ()
2897 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2898 int from_size;
2899 gdb_byte *buffer = (gdb_byte *) alloca (len);
2900 struct value *val;
2901 CORE_ADDR to_addr = toval->address ();
2903 if (type->code () == TYPE_CODE_FLT)
2904 fromval = value_cast (type, fromval);
2906 read_memory (to_addr, buffer, len);
2907 from_size = fromval->bitsize ();
2908 if (from_size == 0)
2909 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2911 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2912 ULONGEST from_offset = 0;
2913 if (is_big_endian && is_scalar_type (fromval->type ()))
2914 from_offset = from_size - bits;
2915 copy_bitwise (buffer, toval->bitpos (),
2916 fromval->contents ().data (), from_offset,
2917 bits, is_big_endian);
2918 write_memory_with_notification (to_addr, buffer, len);
2920 val = toval->copy ();
2921 memcpy (val->contents_raw ().data (),
2922 fromval->contents ().data (),
2923 type->length ());
2924 val->deprecated_set_type (type);
2926 return val;
2929 return value_assign (toval, fromval);
2933 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2934 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2935 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2936 COMPONENT, and not the inferior's memory. The current contents
2937 of COMPONENT are ignored.
2939 Although not part of the initial design, this function also works
2940 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2941 had a null address, and COMPONENT had an address which is equal to
2942 its offset inside CONTAINER. */
2944 static void
2945 value_assign_to_component (struct value *container, struct value *component,
2946 struct value *val)
2948 LONGEST offset_in_container =
2949 (LONGEST) (component->address () - container->address ());
2950 int bit_offset_in_container =
2951 component->bitpos () - container->bitpos ();
2952 int bits;
2954 val = value_cast (component->type (), val);
2956 if (component->bitsize () == 0)
2957 bits = TARGET_CHAR_BIT * component->type ()->length ();
2958 else
2959 bits = component->bitsize ();
2961 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2963 int src_offset;
2965 if (is_scalar_type (check_typedef (component->type ())))
2966 src_offset
2967 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2968 else
2969 src_offset = 0;
2970 copy_bitwise ((container->contents_writeable ().data ()
2971 + offset_in_container),
2972 container->bitpos () + bit_offset_in_container,
2973 val->contents ().data (), src_offset, bits, 1);
2975 else
2976 copy_bitwise ((container->contents_writeable ().data ()
2977 + offset_in_container),
2978 container->bitpos () + bit_offset_in_container,
2979 val->contents ().data (), 0, bits, 0);
2982 /* Determine if TYPE is an access to an unconstrained array. */
2984 bool
2985 ada_is_access_to_unconstrained_array (struct type *type)
2987 return (type->code () == TYPE_CODE_TYPEDEF
2988 && is_thick_pntr (ada_typedef_target_type (type)));
2991 /* The value of the element of array ARR at the ARITY indices given in IND.
2992 ARR may be either a simple array, GNAT array descriptor, or pointer
2993 thereto. */
2995 struct value *
2996 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2998 int k;
2999 struct value *elt;
3000 struct type *elt_type;
3002 elt = ada_coerce_to_simple_array (arr);
3004 elt_type = ada_check_typedef (elt->type ());
3005 if (elt_type->code () == TYPE_CODE_ARRAY
3006 && elt_type->field (0).bitsize () > 0)
3007 return value_subscript_packed (elt, arity, ind);
3009 for (k = 0; k < arity; k += 1)
3011 struct type *saved_elt_type = elt_type->target_type ();
3013 if (elt_type->code () != TYPE_CODE_ARRAY)
3014 error (_("too many subscripts (%d expected)"), k);
3016 elt = value_subscript (elt, pos_atr (ind[k]));
3018 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3019 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3021 /* The element is a typedef to an unconstrained array,
3022 except that the value_subscript call stripped the
3023 typedef layer. The typedef layer is GNAT's way to
3024 specify that the element is, at the source level, an
3025 access to the unconstrained array, rather than the
3026 unconstrained array. So, we need to restore that
3027 typedef layer, which we can do by forcing the element's
3028 type back to its original type. Otherwise, the returned
3029 value is going to be printed as the array, rather
3030 than as an access. Another symptom of the same issue
3031 would be that an expression trying to dereference the
3032 element would also be improperly rejected. */
3033 elt->deprecated_set_type (saved_elt_type);
3036 elt_type = ada_check_typedef (elt->type ());
3039 return elt;
3042 /* Assuming ARR is a pointer to a GDB array, the value of the element
3043 of *ARR at the ARITY indices given in IND.
3044 Does not read the entire array into memory.
3046 Note: Unlike what one would expect, this function is used instead of
3047 ada_value_subscript for basically all non-packed array types. The reason
3048 for this is that a side effect of doing our own pointer arithmetics instead
3049 of relying on value_subscript is that there is no implicit typedef peeling.
3050 This is important for arrays of array accesses, where it allows us to
3051 preserve the fact that the array's element is an array access, where the
3052 access part os encoded in a typedef layer. */
3054 static struct value *
3055 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3057 int k;
3058 struct value *array_ind = ada_value_ind (arr);
3059 struct type *type
3060 = check_typedef (array_ind->enclosing_type ());
3062 if (type->code () == TYPE_CODE_ARRAY
3063 && type->field (0).bitsize () > 0)
3064 return value_subscript_packed (array_ind, arity, ind);
3066 for (k = 0; k < arity; k += 1)
3068 LONGEST lwb, upb;
3070 if (type->code () != TYPE_CODE_ARRAY)
3071 error (_("too many subscripts (%d expected)"), k);
3072 arr = value_cast (lookup_pointer_type (type->target_type ()),
3073 arr->copy ());
3074 get_discrete_bounds (type->index_type (), &lwb, &upb);
3075 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3076 type = type->target_type ();
3079 return value_ind (arr);
3082 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3083 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3084 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3085 this array is LOW, as per Ada rules. */
3086 static struct value *
3087 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3088 int low, int high)
3090 struct type *type0 = ada_check_typedef (type);
3091 struct type *base_index_type = type0->index_type ()->target_type ();
3092 type_allocator alloc (base_index_type);
3093 struct type *index_type
3094 = create_static_range_type (alloc, base_index_type, low, high);
3095 struct type *slice_type = create_array_type_with_stride
3096 (alloc, type0->target_type (), index_type,
3097 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3098 type0->field (0).bitsize ());
3099 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3100 std::optional<LONGEST> base_low_pos, low_pos;
3101 CORE_ADDR base;
3103 low_pos = discrete_position (base_index_type, low);
3104 base_low_pos = discrete_position (base_index_type, base_low);
3106 if (!low_pos.has_value () || !base_low_pos.has_value ())
3108 warning (_("unable to get positions in slice, use bounds instead"));
3109 low_pos = low;
3110 base_low_pos = base_low;
3113 ULONGEST stride = slice_type->field (0).bitsize () / 8;
3114 if (stride == 0)
3115 stride = type0->target_type ()->length ();
3117 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3118 return value_at_lazy (slice_type, base);
3122 static struct value *
3123 ada_value_slice (struct value *array, int low, int high)
3125 struct type *type = ada_check_typedef (array->type ());
3126 struct type *base_index_type = type->index_type ()->target_type ();
3127 type_allocator alloc (type->index_type ());
3128 struct type *index_type
3129 = create_static_range_type (alloc, type->index_type (), low, high);
3130 struct type *slice_type = create_array_type_with_stride
3131 (alloc, type->target_type (), index_type,
3132 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3133 type->field (0).bitsize ());
3134 std::optional<LONGEST> low_pos, high_pos;
3137 low_pos = discrete_position (base_index_type, low);
3138 high_pos = discrete_position (base_index_type, high);
3140 if (!low_pos.has_value () || !high_pos.has_value ())
3142 warning (_("unable to get positions in slice, use bounds instead"));
3143 low_pos = low;
3144 high_pos = high;
3147 return value_cast (slice_type,
3148 value_slice (array, low, *high_pos - *low_pos + 1));
3151 /* If type is a record type in the form of a standard GNAT array
3152 descriptor, returns the number of dimensions for type. If arr is a
3153 simple array, returns the number of "array of"s that prefix its
3154 type designation. Otherwise, returns 0. */
3157 ada_array_arity (struct type *type)
3159 int arity;
3161 if (type == NULL)
3162 return 0;
3164 type = desc_base_type (type);
3166 arity = 0;
3167 if (type->code () == TYPE_CODE_STRUCT)
3168 return desc_arity (desc_bounds_type (type));
3169 else
3170 while (type->code () == TYPE_CODE_ARRAY)
3172 arity += 1;
3173 type = ada_check_typedef (type->target_type ());
3176 return arity;
3179 /* If TYPE is a record type in the form of a standard GNAT array
3180 descriptor or a simple array type, returns the element type for
3181 TYPE after indexing by NINDICES indices, or by all indices if
3182 NINDICES is -1. Otherwise, returns NULL. */
3184 struct type *
3185 ada_array_element_type (struct type *type, int nindices)
3187 type = desc_base_type (type);
3189 if (type->code () == TYPE_CODE_STRUCT)
3191 int k;
3192 struct type *p_array_type;
3194 p_array_type = desc_data_target_type (type);
3196 k = ada_array_arity (type);
3197 if (k == 0)
3198 return NULL;
3200 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3201 if (nindices >= 0 && k > nindices)
3202 k = nindices;
3203 while (k > 0 && p_array_type != NULL)
3205 p_array_type = ada_check_typedef (p_array_type->target_type ());
3206 k -= 1;
3208 return p_array_type;
3210 else if (type->code () == TYPE_CODE_ARRAY)
3212 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3214 type = type->target_type ();
3215 /* A multi-dimensional array is represented using a sequence
3216 of array types. If one of these types has a name, then
3217 it is not another dimension of the outer array, but
3218 rather the element type of the outermost array. */
3219 if (type->name () != nullptr)
3220 break;
3221 nindices -= 1;
3223 return type;
3226 return NULL;
3229 /* See ada-lang.h. */
3231 struct type *
3232 ada_index_type (struct type *type, int n, const char *name)
3234 struct type *result_type;
3236 type = desc_base_type (type);
3238 if (n < 0 || n > ada_array_arity (type))
3239 error (_("invalid dimension number to '%s"), name);
3241 if (ada_is_simple_array_type (type))
3243 int i;
3245 for (i = 1; i < n; i += 1)
3247 type = ada_check_typedef (type);
3248 type = type->target_type ();
3250 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3251 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3252 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3253 perhaps stabsread.c would make more sense. */
3254 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3255 result_type = NULL;
3257 else
3259 result_type = desc_index_type (desc_bounds_type (type), n);
3260 if (result_type == NULL)
3261 error (_("attempt to take bound of something that is not an array"));
3264 return result_type;
3267 /* Given that arr is an array type, returns the lower bound of the
3268 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3269 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3270 array-descriptor type. It works for other arrays with bounds supplied
3271 by run-time quantities other than discriminants. */
3273 static LONGEST
3274 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3276 struct type *type, *index_type_desc, *index_type;
3277 int i;
3279 gdb_assert (which == 0 || which == 1);
3281 if (ada_is_constrained_packed_array_type (arr_type))
3282 arr_type = decode_constrained_packed_array_type (arr_type);
3284 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3285 return - which;
3287 if (arr_type->code () == TYPE_CODE_PTR)
3288 type = arr_type->target_type ();
3289 else
3290 type = arr_type;
3292 if (type->is_fixed_instance ())
3294 /* The array has already been fixed, so we do not need to
3295 check the parallel ___XA type again. That encoding has
3296 already been applied, so ignore it now. */
3297 index_type_desc = NULL;
3299 else
3301 index_type_desc = ada_find_parallel_type (type, "___XA");
3302 ada_fixup_array_indexes_type (index_type_desc);
3305 if (index_type_desc != NULL)
3306 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3307 NULL);
3308 else
3310 struct type *elt_type = check_typedef (type);
3312 for (i = 1; i < n; i++)
3313 elt_type = check_typedef (elt_type->target_type ());
3315 index_type = elt_type->index_type ();
3318 return (which == 0
3319 ? ada_discrete_type_low_bound (index_type)
3320 : ada_discrete_type_high_bound (index_type));
3323 /* Given that arr is an array value, returns the lower bound of the
3324 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3325 WHICH is 1. This routine will also work for arrays with bounds
3326 supplied by run-time quantities other than discriminants. */
3328 static LONGEST
3329 ada_array_bound (struct value *arr, int n, int which)
3331 struct type *arr_type;
3333 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3334 arr = value_ind (arr);
3335 arr_type = arr->enclosing_type ();
3337 if (ada_is_constrained_packed_array_type (arr_type))
3338 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3339 else if (ada_is_simple_array_type (arr_type))
3340 return ada_array_bound_from_type (arr_type, n, which);
3341 else
3342 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3345 /* Given that arr is an array value, returns the length of the
3346 nth index. This routine will also work for arrays with bounds
3347 supplied by run-time quantities other than discriminants.
3348 Does not work for arrays indexed by enumeration types with representation
3349 clauses at the moment. */
3351 static LONGEST
3352 ada_array_length (struct value *arr, int n)
3354 struct type *arr_type, *index_type;
3355 int low, high;
3357 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3358 arr = value_ind (arr);
3359 arr_type = arr->enclosing_type ();
3361 if (ada_is_constrained_packed_array_type (arr_type))
3362 return ada_array_length (decode_constrained_packed_array (arr), n);
3364 if (ada_is_simple_array_type (arr_type))
3366 low = ada_array_bound_from_type (arr_type, n, 0);
3367 high = ada_array_bound_from_type (arr_type, n, 1);
3369 else
3371 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3372 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3375 arr_type = check_typedef (arr_type);
3376 index_type = ada_index_type (arr_type, n, "length");
3377 if (index_type != NULL)
3379 struct type *base_type;
3380 if (index_type->code () == TYPE_CODE_RANGE)
3381 base_type = index_type->target_type ();
3382 else
3383 base_type = index_type;
3385 low = pos_atr (value_from_longest (base_type, low));
3386 high = pos_atr (value_from_longest (base_type, high));
3388 return high - low + 1;
3391 /* An array whose type is that of ARR_TYPE (an array type), with
3392 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3393 less than LOW, then LOW-1 is used. */
3395 static struct value *
3396 empty_array (struct type *arr_type, int low, int high)
3398 struct type *arr_type0 = ada_check_typedef (arr_type);
3399 type_allocator alloc (arr_type0->index_type ()->target_type ());
3400 struct type *index_type
3401 = create_static_range_type
3402 (alloc, arr_type0->index_type ()->target_type (), low,
3403 high < low ? low - 1 : high);
3404 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3406 return value::allocate (create_array_type (alloc, elt_type, index_type));
3410 /* Name resolution */
3412 /* The "decoded" name for the user-definable Ada operator corresponding
3413 to OP. */
3415 static const char *
3416 ada_decoded_op_name (enum exp_opcode op)
3418 int i;
3420 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3422 if (ada_opname_table[i].op == op)
3423 return ada_opname_table[i].decoded;
3425 error (_("Could not find operator name for opcode"));
3428 /* Sort SYMS to put the choices in a canonical order by the encoded
3429 names. */
3431 static void
3432 sort_choices (std::vector<struct block_symbol> &syms)
3434 std::sort (syms.begin (), syms.end (),
3435 [] (const block_symbol &a, const block_symbol &b)
3437 if (!a.symbol->is_objfile_owned ())
3438 return true;
3439 if (!b.symbol->is_objfile_owned ())
3440 return true;
3442 const char *fna = a.symbol->symtab ()->filename;
3443 const char *fnb = b.symbol->symtab ()->filename;
3445 /* First sort by basename. This is done because,
3446 depending on how GNAT was invoked, different sources
3447 might have relative or absolute paths, but we'd like
3448 similar ones to appear together. */
3449 int cmp = strcmp (lbasename (fna), lbasename (fnb));
3450 if (cmp != 0)
3451 return cmp < 0;
3453 /* The basenames are the same, so group identical paths
3454 together. */
3455 cmp = strcmp (fna, fnb);
3456 if (cmp != 0)
3457 return cmp < 0;
3459 if (a.symbol->line () < b.symbol->line ())
3460 return true;
3461 if (a.symbol->line () > b.symbol->line ())
3462 return false;
3464 return strcmp (a.symbol->natural_name (),
3465 b.symbol->natural_name ()) < 0;
3469 /* Whether GDB should display formals and return types for functions in the
3470 overloads selection menu. */
3471 static bool print_signatures = true;
3473 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3474 all but functions, the signature is just the name of the symbol. For
3475 functions, this is the name of the function, the list of types for formals
3476 and the return type (if any). */
3478 static void
3479 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3480 const struct type_print_options *flags)
3482 struct type *type = sym->type ();
3484 gdb_printf (stream, "%s", sym->print_name ());
3485 if (!print_signatures
3486 || type == NULL
3487 || type->code () != TYPE_CODE_FUNC)
3488 return;
3490 if (type->num_fields () > 0)
3492 int i;
3494 gdb_printf (stream, " (");
3495 for (i = 0; i < type->num_fields (); ++i)
3497 if (i > 0)
3498 gdb_printf (stream, "; ");
3499 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3500 flags);
3502 gdb_printf (stream, ")");
3504 if (type->target_type () != NULL
3505 && type->target_type ()->code () != TYPE_CODE_VOID)
3507 gdb_printf (stream, " return ");
3508 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3512 /* Read and validate a set of numeric choices from the user in the
3513 range 0 .. N_CHOICES-1. Place the results in increasing
3514 order in CHOICES[0 .. N-1], and return N.
3516 The user types choices as a sequence of numbers on one line
3517 separated by blanks, encoding them as follows:
3519 + A choice of 0 means to cancel the selection, throwing an error.
3520 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3521 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3523 The user is not allowed to choose more than MAX_RESULTS values.
3525 ANNOTATION_SUFFIX, if present, is used to annotate the input
3526 prompts (for use with the -f switch). */
3528 static int
3529 get_selections (int *choices, int n_choices, int max_results,
3530 int is_all_choice, const char *annotation_suffix)
3532 const char *args;
3533 const char *prompt;
3534 int n_chosen;
3535 int first_choice = is_all_choice ? 2 : 1;
3537 prompt = getenv ("PS2");
3538 if (prompt == NULL)
3539 prompt = "> ";
3541 std::string buffer;
3542 args = command_line_input (buffer, prompt, annotation_suffix);
3544 if (args == NULL)
3545 error_no_arg (_("one or more choice numbers"));
3547 n_chosen = 0;
3549 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3550 order, as given in args. Choices are validated. */
3551 while (1)
3553 char *args2;
3554 int choice, j;
3556 args = skip_spaces (args);
3557 if (*args == '\0' && n_chosen == 0)
3558 error_no_arg (_("one or more choice numbers"));
3559 else if (*args == '\0')
3560 break;
3562 choice = strtol (args, &args2, 10);
3563 if (args == args2 || choice < 0
3564 || choice > n_choices + first_choice - 1)
3565 error (_("Argument must be choice number"));
3566 args = args2;
3568 if (choice == 0)
3569 error (_("cancelled"));
3571 if (choice < first_choice)
3573 n_chosen = n_choices;
3574 for (j = 0; j < n_choices; j += 1)
3575 choices[j] = j;
3576 break;
3578 choice -= first_choice;
3580 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3584 if (j < 0 || choice != choices[j])
3586 int k;
3588 for (k = n_chosen - 1; k > j; k -= 1)
3589 choices[k + 1] = choices[k];
3590 choices[j + 1] = choice;
3591 n_chosen += 1;
3595 if (n_chosen > max_results)
3596 error (_("Select no more than %d of the above"), max_results);
3598 return n_chosen;
3601 /* Given a list symbols in SYMS, select up to MAX_RESULTS>0
3602 by asking the user (if necessary), returning the number selected,
3603 and setting the first elements of SYMS items. Error if no symbols
3604 selected. */
3606 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3607 to be re-integrated one of these days. */
3609 static int
3610 user_select_syms (std::vector<struct block_symbol> &syms, int max_results)
3612 int i;
3613 int first_choice = (max_results == 1) ? 1 : 2;
3614 const char *select_mode = multiple_symbols_select_mode ();
3616 if (max_results < 1)
3617 error (_("Request to select 0 symbols!"));
3618 if (syms.size () <= 1)
3619 return syms.size ();
3621 if (select_mode == multiple_symbols_cancel)
3622 error (_("\
3623 canceled because the command is ambiguous\n\
3624 See set/show multiple-symbol."));
3626 /* If select_mode is "all", then return all possible symbols.
3627 Only do that if more than one symbol can be selected, of course.
3628 Otherwise, display the menu as usual. */
3629 if (select_mode == multiple_symbols_all && max_results > 1)
3630 return syms.size ();
3632 gdb_printf (_("[0] cancel\n"));
3633 if (max_results > 1)
3634 gdb_printf (_("[1] all\n"));
3636 sort_choices (syms);
3638 for (i = 0; i < syms.size (); i += 1)
3640 if (syms[i].symbol == NULL)
3641 continue;
3643 if (syms[i].symbol->aclass () == LOC_BLOCK)
3645 struct symtab_and_line sal =
3646 find_function_start_sal (syms[i].symbol, 1);
3648 gdb_printf ("[%d] ", i + first_choice);
3649 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3650 &type_print_raw_options);
3651 if (sal.symtab == NULL)
3652 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3653 metadata_style.style ().ptr (), nullptr, sal.line);
3654 else
3655 gdb_printf
3656 (_(" at %ps:%d\n"),
3657 styled_string (file_name_style.style (),
3658 symtab_to_filename_for_display (sal.symtab)),
3659 sal.line);
3660 continue;
3662 else
3664 int is_enumeral =
3665 (syms[i].symbol->aclass () == LOC_CONST
3666 && syms[i].symbol->type () != NULL
3667 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3668 struct symtab *symtab = NULL;
3670 if (syms[i].symbol->is_objfile_owned ())
3671 symtab = syms[i].symbol->symtab ();
3673 if (syms[i].symbol->line () != 0 && symtab != NULL)
3675 gdb_printf ("[%d] ", i + first_choice);
3676 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3677 &type_print_raw_options);
3678 gdb_printf (_(" at %ps:%ps\n"),
3679 styled_string (file_name_style.style (),
3680 symtab_to_filename_for_display (symtab)),
3681 styled_string (line_number_style.style (),
3682 pulongest (syms[i].symbol->line ())));
3684 else if (is_enumeral
3685 && syms[i].symbol->type ()->name () != NULL)
3687 gdb_printf (("[%d] "), i + first_choice);
3688 ada_print_type (syms[i].symbol->type (), NULL,
3689 gdb_stdout, -1, 0, &type_print_raw_options);
3690 gdb_printf (_("'(%s) (enumeral)\n"),
3691 syms[i].symbol->print_name ());
3693 else
3695 gdb_printf ("[%d] ", i + first_choice);
3696 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3697 &type_print_raw_options);
3699 if (symtab != NULL)
3700 gdb_printf (is_enumeral
3701 ? _(" in %ps (enumeral)\n")
3702 : _(" at %ps:?\n"),
3703 styled_string (file_name_style.style (),
3704 symtab_to_filename_for_display (symtab)));
3705 else
3706 gdb_printf (is_enumeral
3707 ? _(" (enumeral)\n")
3708 : _(" at ?\n"));
3713 int *chosen = XALLOCAVEC (int , syms.size ());
3714 int n_chosen = get_selections (chosen, syms.size (),
3715 max_results, max_results > 1,
3716 "overload-choice");
3718 for (i = 0; i < n_chosen; i += 1)
3719 syms[i] = syms[chosen[i]];
3721 return n_chosen;
3724 /* See ada-lang.h. */
3726 block_symbol
3727 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3728 int nargs, value *argvec[])
3730 if (possible_user_operator_p (op, argvec))
3732 std::vector<struct block_symbol> candidates
3733 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3734 NULL, SEARCH_VFT);
3736 int i = ada_resolve_function (candidates, argvec,
3737 nargs, ada_decoded_op_name (op), NULL,
3738 parse_completion);
3739 if (i >= 0)
3740 return candidates[i];
3742 return {};
3745 /* See ada-lang.h. */
3747 block_symbol
3748 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3749 struct type *context_type,
3750 bool parse_completion,
3751 int nargs, value *argvec[],
3752 innermost_block_tracker *tracker)
3754 std::vector<struct block_symbol> candidates
3755 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3757 int i;
3758 if (candidates.size () == 1)
3759 i = 0;
3760 else
3762 i = ada_resolve_function
3763 (candidates,
3764 argvec, nargs,
3765 sym->linkage_name (),
3766 context_type, parse_completion);
3767 if (i < 0)
3768 error (_("Could not find a match for %s"), sym->print_name ());
3771 tracker->update (candidates[i]);
3772 return candidates[i];
3775 /* Resolve a mention of a name where the context type is an
3776 enumeration type. */
3778 static int
3779 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3780 const char *name, struct type *context_type,
3781 bool parse_completion)
3783 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3784 context_type = ada_check_typedef (context_type);
3786 /* We already know the name matches, so we're just looking for
3787 an element of the correct enum type. */
3788 struct type *type1 = context_type;
3789 for (int i = 0; i < syms.size (); ++i)
3791 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3792 if (type1 == type2)
3793 return i;
3796 for (int i = 0; i < syms.size (); ++i)
3798 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3799 if (strcmp (type1->name (), type2->name ()) != 0)
3800 continue;
3801 if (ada_identical_enum_types_p (type1, type2))
3802 return i;
3805 error (_("No name '%s' in enumeration type '%s'"), name,
3806 ada_type_name (context_type));
3809 /* See ada-lang.h. */
3811 block_symbol
3812 ada_resolve_variable (struct symbol *sym, const struct block *block,
3813 struct type *context_type,
3814 bool parse_completion,
3815 int deprocedure_p,
3816 innermost_block_tracker *tracker)
3818 std::vector<struct block_symbol> candidates
3819 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3821 if (std::any_of (candidates.begin (),
3822 candidates.end (),
3823 [] (block_symbol &bsym)
3825 switch (bsym.symbol->aclass ())
3827 case LOC_REGISTER:
3828 case LOC_ARG:
3829 case LOC_REF_ARG:
3830 case LOC_REGPARM_ADDR:
3831 case LOC_LOCAL:
3832 case LOC_COMPUTED:
3833 return true;
3834 default:
3835 return false;
3839 /* Types tend to get re-introduced locally, so if there
3840 are any local symbols that are not types, first filter
3841 out all types. */
3842 candidates.erase
3843 (std::remove_if
3844 (candidates.begin (),
3845 candidates.end (),
3846 [] (block_symbol &bsym)
3848 return bsym.symbol->aclass () == LOC_TYPEDEF;
3850 candidates.end ());
3853 /* Filter out artificial symbols. */
3854 candidates.erase
3855 (std::remove_if
3856 (candidates.begin (),
3857 candidates.end (),
3858 [] (block_symbol &bsym)
3860 return bsym.symbol->is_artificial ();
3862 candidates.end ());
3864 int i;
3865 if (candidates.empty ())
3866 error (_("No definition found for %s"), sym->print_name ());
3867 else if (candidates.size () == 1)
3868 i = 0;
3869 else if (context_type != nullptr
3870 && context_type->code () == TYPE_CODE_ENUM)
3871 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3872 parse_completion);
3873 else if (context_type == nullptr
3874 && symbols_are_identical_enums (candidates))
3876 /* If all the remaining symbols are identical enumerals, then
3877 just keep the first one and discard the rest.
3879 Unlike what we did previously, we do not discard any entry
3880 unless they are ALL identical. This is because the symbol
3881 comparison is not a strict comparison, but rather a practical
3882 comparison. If all symbols are considered identical, then
3883 we can just go ahead and use the first one and discard the rest.
3884 But if we cannot reduce the list to a single element, we have
3885 to ask the user to disambiguate anyways. And if we have to
3886 present a multiple-choice menu, it's less confusing if the list
3887 isn't missing some choices that were identical and yet distinct. */
3888 candidates.resize (1);
3889 i = 0;
3891 else if (deprocedure_p && !is_nonfunction (candidates))
3893 i = ada_resolve_function
3894 (candidates, NULL, 0,
3895 sym->linkage_name (),
3896 context_type, parse_completion);
3897 if (i < 0)
3898 error (_("Could not find a match for %s"), sym->print_name ());
3900 else
3902 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3903 user_select_syms (candidates, 1);
3904 i = 0;
3907 tracker->update (candidates[i]);
3908 return candidates[i];
3911 static bool ada_type_match (struct type *ftype, struct type *atype);
3913 /* Helper for ada_type_match that checks that two array types are
3914 compatible. As with that function, FTYPE is the formal type and
3915 ATYPE is the actual type. */
3917 static bool
3918 ada_type_match_arrays (struct type *ftype, struct type *atype)
3920 if (ftype->code () != TYPE_CODE_ARRAY
3921 && !ada_is_array_descriptor_type (ftype))
3922 return false;
3923 if (atype->code () != TYPE_CODE_ARRAY
3924 && !ada_is_array_descriptor_type (atype))
3925 return false;
3927 if (ada_array_arity (ftype) != ada_array_arity (atype))
3928 return false;
3930 struct type *f_elt_type = ada_array_element_type (ftype, -1);
3931 struct type *a_elt_type = ada_array_element_type (atype, -1);
3932 return ada_type_match (f_elt_type, a_elt_type);
3935 /* Return non-zero if formal type FTYPE matches actual type ATYPE.
3936 The term "match" here is rather loose. The match is heuristic and
3937 liberal -- while it tries to reject matches that are obviously
3938 incorrect, it may still let through some that do not strictly
3939 correspond to Ada rules. */
3941 static bool
3942 ada_type_match (struct type *ftype, struct type *atype)
3944 ftype = ada_check_typedef (ftype);
3945 atype = ada_check_typedef (atype);
3947 if (ftype->code () == TYPE_CODE_REF)
3948 ftype = ftype->target_type ();
3949 if (atype->code () == TYPE_CODE_REF)
3950 atype = atype->target_type ();
3952 switch (ftype->code ())
3954 default:
3955 return ftype->code () == atype->code ();
3956 case TYPE_CODE_PTR:
3957 if (atype->code () != TYPE_CODE_PTR)
3958 return false;
3959 atype = atype->target_type ();
3960 /* This can only happen if the actual argument is 'null'. */
3961 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3962 return true;
3963 return ada_type_match (ftype->target_type (), atype);
3964 case TYPE_CODE_INT:
3965 case TYPE_CODE_ENUM:
3966 case TYPE_CODE_RANGE:
3967 switch (atype->code ())
3969 case TYPE_CODE_INT:
3970 case TYPE_CODE_ENUM:
3971 case TYPE_CODE_RANGE:
3972 return true;
3973 default:
3974 return false;
3977 case TYPE_CODE_STRUCT:
3978 if (!ada_is_array_descriptor_type (ftype))
3979 return (atype->code () == TYPE_CODE_STRUCT
3980 && !ada_is_array_descriptor_type (atype));
3982 [[fallthrough]];
3983 case TYPE_CODE_ARRAY:
3984 return ada_type_match_arrays (ftype, atype);
3986 case TYPE_CODE_UNION:
3987 case TYPE_CODE_FLT:
3988 return (atype->code () == ftype->code ());
3992 /* Return non-zero if the formals of FUNC "sufficiently match" the
3993 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3994 may also be an enumeral, in which case it is treated as a 0-
3995 argument function. */
3997 static int
3998 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
4000 int i;
4001 struct type *func_type = func->type ();
4003 if (func->aclass () == LOC_CONST
4004 && func_type->code () == TYPE_CODE_ENUM)
4005 return (n_actuals == 0);
4006 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
4007 return 0;
4009 if (func_type->num_fields () != n_actuals)
4010 return 0;
4012 for (i = 0; i < n_actuals; i += 1)
4014 if (actuals[i] == NULL)
4015 return 0;
4016 else
4018 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
4019 struct type *atype = ada_check_typedef (actuals[i]->type ());
4021 if (!ada_type_match (ftype, atype))
4022 return 0;
4025 return 1;
4028 /* False iff function type FUNC_TYPE definitely does not produce a value
4029 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4030 FUNC_TYPE is not a valid function type with a non-null return type
4031 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4033 static int
4034 return_match (struct type *func_type, struct type *context_type)
4036 struct type *return_type;
4038 if (func_type == NULL)
4039 return 1;
4041 if (func_type->code () == TYPE_CODE_FUNC)
4042 return_type = get_base_type (func_type->target_type ());
4043 else
4044 return_type = get_base_type (func_type);
4045 if (return_type == NULL)
4046 return 1;
4048 context_type = get_base_type (context_type);
4050 if (return_type->code () == TYPE_CODE_ENUM)
4051 return context_type == NULL || return_type == context_type;
4052 else if (context_type == NULL)
4053 return return_type->code () != TYPE_CODE_VOID;
4054 else
4055 return return_type->code () == context_type->code ();
4059 /* Returns the index in SYMS that contains the symbol for the
4060 function (if any) that matches the types of the NARGS arguments in
4061 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4062 that returns that type, then eliminate matches that don't. If
4063 CONTEXT_TYPE is void and there is at least one match that does not
4064 return void, eliminate all matches that do.
4066 Asks the user if there is more than one match remaining. Returns -1
4067 if there is no such symbol or none is selected. NAME is used
4068 solely for messages. May re-arrange and modify SYMS in
4069 the process; the index returned is for the modified vector. */
4071 static int
4072 ada_resolve_function (std::vector<struct block_symbol> &syms,
4073 struct value **args, int nargs,
4074 const char *name, struct type *context_type,
4075 bool parse_completion)
4077 int fallback;
4078 int k;
4079 int m; /* Number of hits */
4081 m = 0;
4082 /* In the first pass of the loop, we only accept functions matching
4083 context_type. If none are found, we add a second pass of the loop
4084 where every function is accepted. */
4085 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4087 for (k = 0; k < syms.size (); k += 1)
4089 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4091 if (ada_args_match (syms[k].symbol, args, nargs)
4092 && (fallback || return_match (type, context_type)))
4094 syms[m] = syms[k];
4095 m += 1;
4100 /* If we got multiple matches, ask the user which one to use. Don't do this
4101 interactive thing during completion, though, as the purpose of the
4102 completion is providing a list of all possible matches. Prompting the
4103 user to filter it down would be completely unexpected in this case. */
4104 if (m == 0)
4105 return -1;
4106 else if (m > 1 && !parse_completion)
4108 gdb_printf (_("Multiple matches for %s\n"), name);
4109 syms.resize (m);
4110 user_select_syms (syms, 1);
4111 return 0;
4113 return 0;
4116 /* Type-class predicates */
4118 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4119 or FLOAT). */
4121 static int
4122 numeric_type_p (struct type *type)
4124 if (type == NULL)
4125 return 0;
4126 else
4128 switch (type->code ())
4130 case TYPE_CODE_INT:
4131 case TYPE_CODE_FLT:
4132 case TYPE_CODE_FIXED_POINT:
4133 return 1;
4134 case TYPE_CODE_RANGE:
4135 return (type == type->target_type ()
4136 || numeric_type_p (type->target_type ()));
4137 default:
4138 return 0;
4143 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4145 static int
4146 integer_type_p (struct type *type)
4148 if (type == NULL)
4149 return 0;
4150 else
4152 switch (type->code ())
4154 case TYPE_CODE_INT:
4155 return 1;
4156 case TYPE_CODE_RANGE:
4157 return (type == type->target_type ()
4158 || integer_type_p (type->target_type ()));
4159 default:
4160 return 0;
4165 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4167 static int
4168 scalar_type_p (struct type *type)
4170 if (type == NULL)
4171 return 0;
4172 else
4174 switch (type->code ())
4176 case TYPE_CODE_INT:
4177 case TYPE_CODE_RANGE:
4178 case TYPE_CODE_ENUM:
4179 case TYPE_CODE_FLT:
4180 case TYPE_CODE_FIXED_POINT:
4181 return 1;
4182 default:
4183 return 0;
4188 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4189 This essentially means one of (INT, RANGE, ENUM) -- but note that
4190 "enum" includes character and boolean as well. */
4192 static int
4193 discrete_type_p (struct type *type)
4195 if (type == NULL)
4196 return 0;
4197 else
4199 switch (type->code ())
4201 case TYPE_CODE_INT:
4202 case TYPE_CODE_RANGE:
4203 case TYPE_CODE_ENUM:
4204 case TYPE_CODE_BOOL:
4205 case TYPE_CODE_CHAR:
4206 return 1;
4207 default:
4208 return 0;
4213 /* Returns non-zero if OP with operands in the vector ARGS could be
4214 a user-defined function. Errs on the side of pre-defined operators
4215 (i.e., result 0). */
4217 static int
4218 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4220 struct type *type0 =
4221 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4222 struct type *type1 =
4223 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4225 if (type0 == NULL)
4226 return 0;
4228 switch (op)
4230 default:
4231 return 0;
4233 case BINOP_ADD:
4234 case BINOP_SUB:
4235 case BINOP_MUL:
4236 case BINOP_DIV:
4237 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4239 case BINOP_REM:
4240 case BINOP_MOD:
4241 case BINOP_BITWISE_AND:
4242 case BINOP_BITWISE_IOR:
4243 case BINOP_BITWISE_XOR:
4244 return (!(integer_type_p (type0) && integer_type_p (type1)));
4246 case BINOP_EQUAL:
4247 case BINOP_NOTEQUAL:
4248 case BINOP_LESS:
4249 case BINOP_GTR:
4250 case BINOP_LEQ:
4251 case BINOP_GEQ:
4252 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4254 case BINOP_CONCAT:
4255 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4257 case BINOP_EXP:
4258 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4260 case UNOP_NEG:
4261 case UNOP_PLUS:
4262 case UNOP_LOGICAL_NOT:
4263 case UNOP_ABS:
4264 return (!numeric_type_p (type0));
4269 /* Renaming */
4271 /* NOTES:
4273 1. In the following, we assume that a renaming type's name may
4274 have an ___XD suffix. It would be nice if this went away at some
4275 point.
4276 2. We handle both the (old) purely type-based representation of
4277 renamings and the (new) variable-based encoding. At some point,
4278 it is devoutly to be hoped that the former goes away
4279 (FIXME: hilfinger-2007-07-09).
4280 3. Subprogram renamings are not implemented, although the XRS
4281 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4283 /* If SYM encodes a renaming,
4285 <renaming> renames <renamed entity>,
4287 sets *LEN to the length of the renamed entity's name,
4288 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4289 the string describing the subcomponent selected from the renamed
4290 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4291 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4292 are undefined). Otherwise, returns a value indicating the category
4293 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4294 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4295 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4296 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4297 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4298 may be NULL, in which case they are not assigned.
4300 [Currently, however, GCC does not generate subprogram renamings.] */
4302 enum ada_renaming_category
4303 ada_parse_renaming (struct symbol *sym,
4304 const char **renamed_entity, int *len,
4305 const char **renaming_expr)
4307 enum ada_renaming_category kind;
4308 const char *info;
4309 const char *suffix;
4311 if (sym == NULL)
4312 return ADA_NOT_RENAMING;
4313 switch (sym->aclass ())
4315 default:
4316 return ADA_NOT_RENAMING;
4317 case LOC_LOCAL:
4318 case LOC_STATIC:
4319 case LOC_COMPUTED:
4320 case LOC_OPTIMIZED_OUT:
4321 info = strstr (sym->linkage_name (), "___XR");
4322 if (info == NULL)
4323 return ADA_NOT_RENAMING;
4324 switch (info[5])
4326 case '_':
4327 kind = ADA_OBJECT_RENAMING;
4328 info += 6;
4329 break;
4330 case 'E':
4331 kind = ADA_EXCEPTION_RENAMING;
4332 info += 7;
4333 break;
4334 case 'P':
4335 kind = ADA_PACKAGE_RENAMING;
4336 info += 7;
4337 break;
4338 case 'S':
4339 kind = ADA_SUBPROGRAM_RENAMING;
4340 info += 7;
4341 break;
4342 default:
4343 return ADA_NOT_RENAMING;
4347 if (renamed_entity != NULL)
4348 *renamed_entity = info;
4349 suffix = strstr (info, "___XE");
4350 if (suffix == NULL || suffix == info)
4351 return ADA_NOT_RENAMING;
4352 if (len != NULL)
4353 *len = strlen (info) - strlen (suffix);
4354 suffix += 5;
4355 if (renaming_expr != NULL)
4356 *renaming_expr = suffix;
4357 return kind;
4360 /* Compute the value of the given RENAMING_SYM, which is expected to
4361 be a symbol encoding a renaming expression. BLOCK is the block
4362 used to evaluate the renaming. */
4364 static struct value *
4365 ada_read_renaming_var_value (struct symbol *renaming_sym,
4366 const struct block *block)
4368 const char *sym_name;
4370 sym_name = renaming_sym->linkage_name ();
4371 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4372 return expr->evaluate ();
4376 /* Evaluation: Function Calls */
4378 /* Return an lvalue containing the value VAL. This is the identity on
4379 lvalues, and otherwise has the side-effect of allocating memory
4380 in the inferior where a copy of the value contents is copied. */
4382 static struct value *
4383 ensure_lval (struct value *val)
4385 if (val->lval () == not_lval
4386 || val->lval () == lval_internalvar)
4388 int len = ada_check_typedef (val->type ())->length ();
4389 const CORE_ADDR addr =
4390 value_as_long (value_allocate_space_in_inferior (len));
4392 val->set_lval (lval_memory);
4393 val->set_address (addr);
4394 write_memory (addr, val->contents ().data (), len);
4397 return val;
4400 /* Given ARG, a value of type (pointer or reference to a)*
4401 structure/union, extract the component named NAME from the ultimate
4402 target structure/union and return it as a value with its
4403 appropriate type.
4405 The routine searches for NAME among all members of the structure itself
4406 and (recursively) among all members of any wrapper members
4407 (e.g., '_parent').
4409 If NO_ERR, then simply return NULL in case of error, rather than
4410 calling error. */
4412 static struct value *
4413 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4415 struct type *t, *t1;
4416 struct value *v;
4417 int check_tag;
4419 v = NULL;
4420 t1 = t = ada_check_typedef (arg->type ());
4421 if (t->code () == TYPE_CODE_REF)
4423 t1 = t->target_type ();
4424 if (t1 == NULL)
4425 goto BadValue;
4426 t1 = ada_check_typedef (t1);
4427 if (t1->code () == TYPE_CODE_PTR)
4429 arg = coerce_ref (arg);
4430 t = t1;
4434 while (t->code () == TYPE_CODE_PTR)
4436 t1 = t->target_type ();
4437 if (t1 == NULL)
4438 goto BadValue;
4439 t1 = ada_check_typedef (t1);
4440 if (t1->code () == TYPE_CODE_PTR)
4442 arg = value_ind (arg);
4443 t = t1;
4445 else
4446 break;
4449 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4450 goto BadValue;
4452 if (t1 == t)
4453 v = ada_search_struct_field (name, arg, 0, t);
4454 else
4456 int bit_offset, bit_size, byte_offset;
4457 struct type *field_type;
4458 CORE_ADDR address;
4460 if (t->code () == TYPE_CODE_PTR)
4461 address = ada_value_ind (arg)->address ();
4462 else
4463 address = ada_coerce_ref (arg)->address ();
4465 /* Check to see if this is a tagged type. We also need to handle
4466 the case where the type is a reference to a tagged type, but
4467 we have to be careful to exclude pointers to tagged types.
4468 The latter should be shown as usual (as a pointer), whereas
4469 a reference should mostly be transparent to the user. */
4471 if (ada_is_tagged_type (t1, 0)
4472 || (t1->code () == TYPE_CODE_REF
4473 && ada_is_tagged_type (t1->target_type (), 0)))
4475 /* We first try to find the searched field in the current type.
4476 If not found then let's look in the fixed type. */
4478 if (!find_struct_field (name, t1, 0,
4479 nullptr, nullptr, nullptr,
4480 nullptr, nullptr))
4481 check_tag = 1;
4482 else
4483 check_tag = 0;
4485 else
4486 check_tag = 0;
4488 /* Convert to fixed type in all cases, so that we have proper
4489 offsets to each field in unconstrained record types. */
4490 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4491 address, NULL, check_tag);
4493 /* Resolve the dynamic type as well. */
4494 arg = value_from_contents_and_address (t1, nullptr, address);
4495 t1 = arg->type ();
4497 if (find_struct_field (name, t1, 0,
4498 &field_type, &byte_offset, &bit_offset,
4499 &bit_size, NULL))
4501 if (bit_size != 0)
4503 if (t->code () == TYPE_CODE_REF)
4504 arg = ada_coerce_ref (arg);
4505 else
4506 arg = ada_value_ind (arg);
4507 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4508 bit_offset, bit_size,
4509 field_type);
4511 else
4512 v = value_at_lazy (field_type, address + byte_offset);
4516 if (v != NULL || no_err)
4517 return v;
4518 else
4519 error (_("There is no member named %s."), name);
4521 BadValue:
4522 if (no_err)
4523 return NULL;
4524 else
4525 error (_("Attempt to extract a component of "
4526 "a value that is not a record."));
4529 /* Return the value ACTUAL, converted to be an appropriate value for a
4530 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4531 allocating any necessary descriptors (fat pointers), or copies of
4532 values not residing in memory, updating it as needed. */
4534 struct value *
4535 ada_convert_actual (struct value *actual, struct type *formal_type0)
4537 struct type *actual_type = ada_check_typedef (actual->type ());
4538 struct type *formal_type = ada_check_typedef (formal_type0);
4539 struct type *formal_target =
4540 formal_type->code () == TYPE_CODE_PTR
4541 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4542 struct type *actual_target =
4543 actual_type->code () == TYPE_CODE_PTR
4544 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4546 if (ada_is_array_descriptor_type (formal_target)
4547 && actual_target->code () == TYPE_CODE_ARRAY)
4548 return make_array_descriptor (formal_type, actual);
4549 else if (formal_type->code () == TYPE_CODE_PTR
4550 || formal_type->code () == TYPE_CODE_REF)
4552 struct value *result;
4554 if (formal_target->code () == TYPE_CODE_ARRAY
4555 && ada_is_array_descriptor_type (actual_target))
4556 result = desc_data (actual);
4557 else if (formal_type->code () != TYPE_CODE_PTR)
4559 if (actual->lval () != lval_memory)
4561 struct value *val;
4563 actual_type = ada_check_typedef (actual->type ());
4564 val = value::allocate (actual_type);
4565 copy (actual->contents (), val->contents_raw ());
4566 actual = ensure_lval (val);
4568 result = value_addr (actual);
4570 else
4571 return actual;
4572 return value_cast_pointers (formal_type, result, 0);
4574 else if (actual_type->code () == TYPE_CODE_PTR)
4575 return ada_value_ind (actual);
4576 else if (ada_is_aligner_type (formal_type))
4578 /* We need to turn this parameter into an aligner type
4579 as well. */
4580 struct value *aligner = value::allocate (formal_type);
4581 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4583 value_assign_to_component (aligner, component, actual);
4584 return aligner;
4587 return actual;
4590 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4591 type TYPE. This is usually an inefficient no-op except on some targets
4592 (such as AVR) where the representation of a pointer and an address
4593 differs. */
4595 static CORE_ADDR
4596 value_pointer (struct value *value, struct type *type)
4598 unsigned len = type->length ();
4599 gdb_byte *buf = (gdb_byte *) alloca (len);
4600 CORE_ADDR addr;
4602 addr = value->address ();
4603 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4604 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4605 return addr;
4609 /* Push a descriptor of type TYPE for array value ARR on the stack at
4610 *SP, updating *SP to reflect the new descriptor. Return either
4611 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4612 to-descriptor type rather than a descriptor type), a struct value *
4613 representing a pointer to this descriptor. */
4615 static struct value *
4616 make_array_descriptor (struct type *type, struct value *arr)
4618 struct type *bounds_type = desc_bounds_type (type);
4619 struct type *desc_type = desc_base_type (type);
4620 struct value *descriptor = value::allocate (desc_type);
4621 struct value *bounds = value::allocate (bounds_type);
4622 int i;
4624 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4625 i > 0; i -= 1)
4627 modify_field (bounds->type (),
4628 bounds->contents_writeable ().data (),
4629 ada_array_bound (arr, i, 0),
4630 desc_bound_bitpos (bounds_type, i, 0),
4631 desc_bound_bitsize (bounds_type, i, 0));
4632 modify_field (bounds->type (),
4633 bounds->contents_writeable ().data (),
4634 ada_array_bound (arr, i, 1),
4635 desc_bound_bitpos (bounds_type, i, 1),
4636 desc_bound_bitsize (bounds_type, i, 1));
4639 bounds = ensure_lval (bounds);
4641 modify_field (descriptor->type (),
4642 descriptor->contents_writeable ().data (),
4643 value_pointer (ensure_lval (arr),
4644 desc_type->field (0).type ()),
4645 fat_pntr_data_bitpos (desc_type),
4646 fat_pntr_data_bitsize (desc_type));
4648 modify_field (descriptor->type (),
4649 descriptor->contents_writeable ().data (),
4650 value_pointer (bounds,
4651 desc_type->field (1).type ()),
4652 fat_pntr_bounds_bitpos (desc_type),
4653 fat_pntr_bounds_bitsize (desc_type));
4655 descriptor = ensure_lval (descriptor);
4657 if (type->code () == TYPE_CODE_PTR)
4658 return value_addr (descriptor);
4659 else
4660 return descriptor;
4663 /* Symbol Cache Module */
4665 /* Performance measurements made as of 2010-01-15 indicate that
4666 this cache does bring some noticeable improvements. Depending
4667 on the type of entity being printed, the cache can make it as much
4668 as an order of magnitude faster than without it.
4670 The descriptive type DWARF extension has significantly reduced
4671 the need for this cache, at least when DWARF is being used. However,
4672 even in this case, some expensive name-based symbol searches are still
4673 sometimes necessary - to find an XVZ variable, mostly. */
4675 /* See ada-lang.h. */
4677 void
4678 ada_clear_symbol_cache (program_space *pspace)
4680 ada_pspace_data_handle.clear (pspace);
4683 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4684 Return 1 if found, 0 otherwise.
4686 If an entry was found and SYM is not NULL, set *SYM to the entry's
4687 SYM. Same principle for BLOCK if not NULL. */
4689 static int
4690 lookup_cached_symbol (const char *name, domain_search_flags domain,
4691 struct symbol **sym, const struct block **block)
4693 htab_t tab = get_ada_pspace_data (current_program_space);
4694 cache_entry_search search;
4695 search.name = name;
4696 search.domain = domain;
4698 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4699 search.hash ());
4700 if (e == nullptr)
4701 return 0;
4702 if (sym != nullptr)
4703 *sym = e->sym;
4704 if (block != nullptr)
4705 *block = e->block;
4706 return 1;
4709 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4710 in domain DOMAIN, save this result in our symbol cache. */
4712 static void
4713 cache_symbol (const char *name, domain_search_flags domain,
4714 struct symbol *sym, const struct block *block)
4716 /* Symbols for builtin types don't have a block.
4717 For now don't cache such symbols. */
4718 if (sym != NULL && !sym->is_objfile_owned ())
4719 return;
4721 /* If the symbol is a local symbol, then do not cache it, as a search
4722 for that symbol depends on the context. To determine whether
4723 the symbol is local or not, we check the block where we found it
4724 against the global and static blocks of its associated symtab. */
4725 if (sym != nullptr)
4727 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4729 if (bv.global_block () != block && bv.static_block () != block)
4730 return;
4733 htab_t tab = get_ada_pspace_data (current_program_space);
4734 cache_entry_search search;
4735 search.name = name;
4736 search.domain = domain;
4738 void **slot = htab_find_slot_with_hash (tab, &search,
4739 search.hash (), INSERT);
4741 cache_entry *e = new cache_entry;
4742 e->name = name;
4743 e->domain = domain;
4744 e->sym = sym;
4745 e->block = block;
4747 *slot = e;
4750 /* Symbol Lookup */
4752 /* Return the symbol name match type that should be used used when
4753 searching for all symbols matching LOOKUP_NAME.
4755 LOOKUP_NAME is expected to be a symbol name after transformation
4756 for Ada lookups. */
4758 static symbol_name_match_type
4759 name_match_type_from_name (const char *lookup_name)
4761 return (strstr (lookup_name, "__") == NULL
4762 ? symbol_name_match_type::WILD
4763 : symbol_name_match_type::FULL);
4766 /* Return the result of a standard (literal, C-like) lookup of NAME in
4767 given DOMAIN, visible from lexical block BLOCK. */
4769 static struct symbol *
4770 standard_lookup (const char *name, const struct block *block,
4771 domain_search_flags domain)
4773 /* Initialize it just to avoid a GCC false warning. */
4774 struct block_symbol sym = {};
4776 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4777 return sym.symbol;
4778 sym = ada_lookup_encoded_symbol (name, block, domain);
4779 cache_symbol (name, domain, sym.symbol, sym.block);
4780 return sym.symbol;
4784 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4785 in the symbol fields of SYMS. We treat enumerals as functions,
4786 since they contend in overloading in the same way. */
4787 static int
4788 is_nonfunction (const std::vector<struct block_symbol> &syms)
4790 for (const block_symbol &sym : syms)
4791 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4792 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4793 || sym.symbol->aclass () != LOC_CONST))
4794 return 1;
4796 return 0;
4799 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4800 struct types. Otherwise, they may not. */
4802 static int
4803 equiv_types (struct type *type0, struct type *type1)
4805 if (type0 == type1)
4806 return 1;
4807 if (type0 == NULL || type1 == NULL
4808 || type0->code () != type1->code ())
4809 return 0;
4810 if ((type0->code () == TYPE_CODE_STRUCT
4811 || type0->code () == TYPE_CODE_ENUM)
4812 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4813 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4814 return 1;
4816 return 0;
4819 /* True iff SYM0 represents the same entity as SYM1, or one that is
4820 no more defined than that of SYM1. */
4822 static int
4823 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4825 if (sym0 == sym1)
4826 return 1;
4827 if (sym0->domain () != sym1->domain ()
4828 || sym0->aclass () != sym1->aclass ())
4829 return 0;
4831 switch (sym0->aclass ())
4833 case LOC_UNDEF:
4834 return 1;
4835 case LOC_TYPEDEF:
4837 struct type *type0 = sym0->type ();
4838 struct type *type1 = sym1->type ();
4839 const char *name0 = sym0->linkage_name ();
4840 const char *name1 = sym1->linkage_name ();
4841 int len0 = strlen (name0);
4843 return
4844 type0->code () == type1->code ()
4845 && (equiv_types (type0, type1)
4846 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4847 && startswith (name1 + len0, "___XV")));
4849 case LOC_CONST:
4850 return sym0->value_longest () == sym1->value_longest ()
4851 && equiv_types (sym0->type (), sym1->type ());
4853 case LOC_STATIC:
4855 const char *name0 = sym0->linkage_name ();
4856 const char *name1 = sym1->linkage_name ();
4857 return (strcmp (name0, name1) == 0
4858 && sym0->value_address () == sym1->value_address ());
4861 default:
4862 return 0;
4866 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4867 records in RESULT. Do nothing if SYM is a duplicate. */
4869 static void
4870 add_defn_to_vec (std::vector<struct block_symbol> &result,
4871 struct symbol *sym,
4872 const struct block *block)
4874 /* Do not try to complete stub types, as the debugger is probably
4875 already scanning all symbols matching a certain name at the
4876 time when this function is called. Trying to replace the stub
4877 type by its associated full type will cause us to restart a scan
4878 which may lead to an infinite recursion. Instead, the client
4879 collecting the matching symbols will end up collecting several
4880 matches, with at least one of them complete. It can then filter
4881 out the stub ones if needed. */
4883 for (int i = result.size () - 1; i >= 0; i -= 1)
4885 if (lesseq_defined_than (sym, result[i].symbol))
4886 return;
4887 else if (lesseq_defined_than (result[i].symbol, sym))
4889 result[i].symbol = sym;
4890 result[i].block = block;
4891 return;
4895 struct block_symbol info;
4896 info.symbol = sym;
4897 info.block = block;
4898 result.push_back (info);
4901 /* Return a bound minimal symbol matching NAME according to Ada
4902 decoding rules. Returns an invalid symbol if there is no such
4903 minimal symbol. Names prefixed with "standard__" are handled
4904 specially: "standard__" is first stripped off, and only static and
4905 global symbols are searched. */
4907 bound_minimal_symbol
4908 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4910 bound_minimal_symbol result;
4912 symbol_name_match_type match_type = name_match_type_from_name (name);
4913 lookup_name_info lookup_name (name, match_type);
4915 symbol_name_matcher_ftype *match_name
4916 = ada_get_symbol_name_matcher (lookup_name);
4918 gdbarch_iterate_over_objfiles_in_search_order
4919 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
4920 [&result, lookup_name, match_name] (struct objfile *obj)
4922 for (minimal_symbol *msymbol : obj->msymbols ())
4924 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4925 && msymbol->type () != mst_solib_trampoline)
4927 result.minsym = msymbol;
4928 result.objfile = obj;
4929 return 1;
4933 return 0;
4934 }, objfile);
4936 return result;
4939 /* True if TYPE is definitely an artificial type supplied to a symbol
4940 for which no debugging information was given in the symbol file. */
4942 static int
4943 is_nondebugging_type (struct type *type)
4945 const char *name = ada_type_name (type);
4947 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4950 /* Return true if TYPE1 and TYPE2 are two enumeration types
4951 that are deemed "identical" for practical purposes.
4953 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4954 types. */
4956 static bool
4957 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4959 /* The heuristic we use here is fairly conservative. We consider
4960 that 2 enumerate types are identical if they have the same
4961 number of enumerals and that all enumerals have the same
4962 underlying value and name. */
4964 if (type1->num_fields () != type2->num_fields ())
4965 return false;
4967 /* All enums in the type should have an identical underlying value. */
4968 for (int i = 0; i < type1->num_fields (); i++)
4969 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4970 return false;
4972 /* All enumerals should also have the same name (modulo any numerical
4973 suffix). */
4974 for (int i = 0; i < type1->num_fields (); i++)
4976 const char *name_1 = type1->field (i).name ();
4977 const char *name_2 = type2->field (i).name ();
4978 int len_1 = strlen (name_1);
4979 int len_2 = strlen (name_2);
4981 ada_remove_trailing_digits (name_1, &len_1);
4982 ada_remove_trailing_digits (name_2, &len_2);
4983 if (len_1 != len_2 || strncmp (name_1, name_2, len_1) != 0)
4984 return false;
4987 return true;
4990 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4991 that are deemed "identical" for practical purposes. Sometimes,
4992 enumerals are not strictly identical, but their types are so similar
4993 that they can be considered identical.
4995 For instance, consider the following code:
4997 type Color is (Black, Red, Green, Blue, White);
4998 type RGB_Color is new Color range Red .. Blue;
5000 Type RGB_Color is a subrange of an implicit type which is a copy
5001 of type Color. If we call that implicit type RGB_ColorB ("B" is
5002 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5003 As a result, when an expression references any of the enumeral
5004 by name (Eg. "print green"), the expression is technically
5005 ambiguous and the user should be asked to disambiguate. But
5006 doing so would only hinder the user, since it wouldn't matter
5007 what choice he makes, the outcome would always be the same.
5008 So, for practical purposes, we consider them as the same. */
5010 static int
5011 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5013 int i;
5015 /* Before performing a thorough comparison check of each type,
5016 we perform a series of inexpensive checks. We expect that these
5017 checks will quickly fail in the vast majority of cases, and thus
5018 help prevent the unnecessary use of a more expensive comparison.
5019 Said comparison also expects us to make some of these checks
5020 (see ada_identical_enum_types_p). */
5022 /* Quick check: All symbols should have an enum type. */
5023 for (i = 0; i < syms.size (); i++)
5024 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5025 return 0;
5027 /* Quick check: They should all have the same value. */
5028 for (i = 1; i < syms.size (); i++)
5029 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5030 return 0;
5032 /* All the sanity checks passed, so we might have a set of
5033 identical enumeration types. Perform a more complete
5034 comparison of the type of each symbol. */
5035 for (i = 1; i < syms.size (); i++)
5036 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5037 syms[0].symbol->type ()))
5038 return 0;
5040 return 1;
5043 /* Remove any non-debugging symbols in SYMS that definitely
5044 duplicate other symbols in the list (The only case I know of where
5045 this happens is when object files containing stabs-in-ecoff are
5046 linked with files containing ordinary ecoff debugging symbols (or no
5047 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5049 static void
5050 remove_extra_symbols (std::vector<struct block_symbol> &syms)
5052 int i, j;
5054 /* We should never be called with less than 2 symbols, as there
5055 cannot be any extra symbol in that case. But it's easy to
5056 handle, since we have nothing to do in that case. */
5057 if (syms.size () < 2)
5058 return;
5060 i = 0;
5061 while (i < syms.size ())
5063 bool remove_p = false;
5065 /* If two symbols have the same name and one of them is a stub type,
5066 the get rid of the stub. */
5068 if (syms[i].symbol->type ()->is_stub ()
5069 && syms[i].symbol->linkage_name () != NULL)
5071 for (j = 0; !remove_p && j < syms.size (); j++)
5073 if (j != i
5074 && !syms[j].symbol->type ()->is_stub ()
5075 && syms[j].symbol->linkage_name () != NULL
5076 && strcmp (syms[i].symbol->linkage_name (),
5077 syms[j].symbol->linkage_name ()) == 0)
5078 remove_p = true;
5082 /* Two symbols with the same name, same class and same address
5083 should be identical. */
5085 else if (syms[i].symbol->linkage_name () != NULL
5086 && syms[i].symbol->aclass () == LOC_STATIC
5087 && is_nondebugging_type (syms[i].symbol->type ()))
5089 for (j = 0; !remove_p && j < syms.size (); j += 1)
5091 if (i != j
5092 && syms[j].symbol->linkage_name () != NULL
5093 && strcmp (syms[i].symbol->linkage_name (),
5094 syms[j].symbol->linkage_name ()) == 0
5095 && (syms[i].symbol->aclass ()
5096 == syms[j].symbol->aclass ())
5097 && syms[i].symbol->value_address ()
5098 == syms[j].symbol->value_address ())
5099 remove_p = true;
5103 /* Two functions with the same block are identical. */
5105 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5107 for (j = 0; !remove_p && j < syms.size (); j += 1)
5109 if (i != j
5110 && syms[j].symbol->aclass () == LOC_BLOCK
5111 && (syms[i].symbol->value_block ()
5112 == syms[j].symbol->value_block ()))
5113 remove_p = true;
5117 if (remove_p)
5118 syms.erase (syms.begin () + i);
5119 else
5120 i += 1;
5124 /* Given a type that corresponds to a renaming entity, use the type name
5125 to extract the scope (package name or function name, fully qualified,
5126 and following the GNAT encoding convention) where this renaming has been
5127 defined. */
5129 static std::string
5130 xget_renaming_scope (struct type *renaming_type)
5132 /* The renaming types adhere to the following convention:
5133 <scope>__<rename>___<XR extension>.
5134 So, to extract the scope, we search for the "___XR" extension,
5135 and then backtrack until we find the first "__". */
5137 const char *name = renaming_type->name ();
5138 const char *suffix = strstr (name, "___XR");
5139 const char *last;
5141 /* Now, backtrack a bit until we find the first "__". Start looking
5142 at suffix - 3, as the <rename> part is at least one character long. */
5144 for (last = suffix - 3; last > name; last--)
5145 if (last[0] == '_' && last[1] == '_')
5146 break;
5148 /* Make a copy of scope and return it. */
5149 return std::string (name, last);
5152 /* Return nonzero if NAME corresponds to a package name. */
5154 static int
5155 is_package_name (const char *name)
5157 /* Here, We take advantage of the fact that no symbols are generated
5158 for packages, while symbols are generated for each function.
5159 So the condition for NAME represent a package becomes equivalent
5160 to NAME not existing in our list of symbols. There is only one
5161 small complication with library-level functions (see below). */
5163 /* If it is a function that has not been defined at library level,
5164 then we should be able to look it up in the symbols. */
5165 if (standard_lookup (name, NULL, SEARCH_VFT) != NULL)
5166 return 0;
5168 /* Library-level function names start with "_ada_". See if function
5169 "_ada_" followed by NAME can be found. */
5171 /* Do a quick check that NAME does not contain "__", since library-level
5172 functions names cannot contain "__" in them. */
5173 if (strstr (name, "__") != NULL)
5174 return 0;
5176 std::string fun_name = string_printf ("_ada_%s", name);
5178 return (standard_lookup (fun_name.c_str (), NULL, SEARCH_VFT) == NULL);
5181 /* Return nonzero if SYM corresponds to a renaming entity that is
5182 not visible from FUNCTION_NAME. */
5184 static int
5185 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5187 if (sym->aclass () != LOC_TYPEDEF)
5188 return 0;
5190 std::string scope = xget_renaming_scope (sym->type ());
5192 /* If the rename has been defined in a package, then it is visible. */
5193 if (is_package_name (scope.c_str ()))
5194 return 0;
5196 /* Check that the rename is in the current function scope by checking
5197 that its name starts with SCOPE. */
5199 /* If the function name starts with "_ada_", it means that it is
5200 a library-level function. Strip this prefix before doing the
5201 comparison, as the encoding for the renaming does not contain
5202 this prefix. */
5203 if (startswith (function_name, "_ada_"))
5204 function_name += 5;
5206 return !startswith (function_name, scope.c_str ());
5209 /* Remove entries from SYMS that corresponds to a renaming entity that
5210 is not visible from the function associated with CURRENT_BLOCK or
5211 that is superfluous due to the presence of more specific renaming
5212 information. Places surviving symbols in the initial entries of
5213 SYMS.
5215 Rationale:
5216 First, in cases where an object renaming is implemented as a
5217 reference variable, GNAT may produce both the actual reference
5218 variable and the renaming encoding. In this case, we discard the
5219 latter.
5221 Second, GNAT emits a type following a specified encoding for each renaming
5222 entity. Unfortunately, STABS currently does not support the definition
5223 of types that are local to a given lexical block, so all renamings types
5224 are emitted at library level. As a consequence, if an application
5225 contains two renaming entities using the same name, and a user tries to
5226 print the value of one of these entities, the result of the ada symbol
5227 lookup will also contain the wrong renaming type.
5229 This function partially covers for this limitation by attempting to
5230 remove from the SYMS list renaming symbols that should be visible
5231 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5232 method with the current information available. The implementation
5233 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5235 - When the user tries to print a rename in a function while there
5236 is another rename entity defined in a package: Normally, the
5237 rename in the function has precedence over the rename in the
5238 package, so the latter should be removed from the list. This is
5239 currently not the case.
5241 - This function will incorrectly remove valid renames if
5242 the CURRENT_BLOCK corresponds to a function which symbol name
5243 has been changed by an "Export" pragma. As a consequence,
5244 the user will be unable to print such rename entities. */
5246 static void
5247 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5248 const struct block *current_block)
5250 struct symbol *current_function;
5251 const char *current_function_name;
5252 int i;
5253 int is_new_style_renaming;
5255 /* If there is both a renaming foo___XR... encoded as a variable and
5256 a simple variable foo in the same block, discard the latter.
5257 First, zero out such symbols, then compress. */
5258 is_new_style_renaming = 0;
5259 for (i = 0; i < syms->size (); i += 1)
5261 struct symbol *sym = (*syms)[i].symbol;
5262 const struct block *block = (*syms)[i].block;
5263 const char *name;
5264 const char *suffix;
5266 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5267 continue;
5268 name = sym->linkage_name ();
5269 suffix = strstr (name, "___XR");
5271 if (suffix != NULL)
5273 int name_len = suffix - name;
5274 int j;
5276 is_new_style_renaming = 1;
5277 for (j = 0; j < syms->size (); j += 1)
5278 if (i != j && (*syms)[j].symbol != NULL
5279 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5280 name_len) == 0
5281 && block == (*syms)[j].block)
5282 (*syms)[j].symbol = NULL;
5285 if (is_new_style_renaming)
5287 int j, k;
5289 for (j = k = 0; j < syms->size (); j += 1)
5290 if ((*syms)[j].symbol != NULL)
5292 (*syms)[k] = (*syms)[j];
5293 k += 1;
5295 syms->resize (k);
5296 return;
5299 /* Extract the function name associated to CURRENT_BLOCK.
5300 Abort if unable to do so. */
5302 if (current_block == NULL)
5303 return;
5305 current_function = current_block->linkage_function ();
5306 if (current_function == NULL)
5307 return;
5309 current_function_name = current_function->linkage_name ();
5310 if (current_function_name == NULL)
5311 return;
5313 /* Check each of the symbols, and remove it from the list if it is
5314 a type corresponding to a renaming that is out of the scope of
5315 the current block. */
5317 i = 0;
5318 while (i < syms->size ())
5320 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5321 == ADA_OBJECT_RENAMING
5322 && old_renaming_is_invisible ((*syms)[i].symbol,
5323 current_function_name))
5324 syms->erase (syms->begin () + i);
5325 else
5326 i += 1;
5330 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5331 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5333 Note: This function assumes that RESULT is empty. */
5335 static void
5336 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5337 const lookup_name_info &lookup_name,
5338 const struct block *block, domain_search_flags domain)
5340 while (block != NULL)
5342 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5344 /* If we found a non-function match, assume that's the one. We
5345 only check this when finding a function boundary, so that we
5346 can accumulate all results from intervening blocks first. */
5347 if (block->function () != nullptr && is_nonfunction (result))
5348 return;
5350 block = block->superblock ();
5354 /* An object of this type is used as the callback argument when
5355 calling the map_matching_symbols method. */
5357 struct match_data
5359 explicit match_data (std::vector<struct block_symbol> *rp)
5360 : resultp (rp)
5363 DISABLE_COPY_AND_ASSIGN (match_data);
5365 bool operator() (struct block_symbol *bsym);
5367 struct objfile *objfile = nullptr;
5368 std::vector<struct block_symbol> *resultp;
5369 struct symbol *arg_sym = nullptr;
5370 bool found_sym = false;
5373 /* A callback for add_nonlocal_symbols that adds symbol, found in
5374 BSYM, to a list of symbols. */
5376 bool
5377 match_data::operator() (struct block_symbol *bsym)
5379 const struct block *block = bsym->block;
5380 struct symbol *sym = bsym->symbol;
5382 if (sym == NULL)
5384 if (!found_sym && arg_sym != NULL)
5385 add_defn_to_vec (*resultp, arg_sym, block);
5386 found_sym = false;
5387 arg_sym = NULL;
5389 else
5391 if (sym->aclass () == LOC_UNRESOLVED)
5392 return true;
5393 else if (sym->is_argument ())
5394 arg_sym = sym;
5395 else
5397 found_sym = true;
5398 add_defn_to_vec (*resultp, sym, block);
5401 return true;
5404 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5405 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5406 symbols to RESULT. Return whether we found such symbols. */
5408 static int
5409 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5410 const struct block *block,
5411 const lookup_name_info &lookup_name,
5412 domain_search_flags domain)
5414 int defns_mark = result.size ();
5416 symbol_name_matcher_ftype *name_match
5417 = ada_get_symbol_name_matcher (lookup_name);
5419 for (using_direct *renaming : block->get_using ())
5421 const char *r_name;
5423 /* Avoid infinite recursions: skip this renaming if we are actually
5424 already traversing it.
5426 Currently, symbol lookup in Ada don't use the namespace machinery from
5427 C++/Fortran support: skip namespace imports that use them. */
5428 if (renaming->searched
5429 || (renaming->import_src != NULL
5430 && renaming->import_src[0] != '\0')
5431 || (renaming->import_dest != NULL
5432 && renaming->import_dest[0] != '\0'))
5433 continue;
5434 renaming->searched = 1;
5436 /* TODO: here, we perform another name-based symbol lookup, which can
5437 pull its own multiple overloads. In theory, we should be able to do
5438 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5439 not a simple name. But in order to do this, we would need to enhance
5440 the DWARF reader to associate a symbol to this renaming, instead of a
5441 name. So, for now, we do something simpler: re-use the C++/Fortran
5442 namespace machinery. */
5443 r_name = (renaming->alias != NULL
5444 ? renaming->alias
5445 : renaming->declaration);
5446 if (name_match (r_name, lookup_name, NULL))
5448 lookup_name_info decl_lookup_name (renaming->declaration,
5449 lookup_name.match_type ());
5450 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5451 1, NULL);
5453 renaming->searched = 0;
5455 return result.size () != defns_mark;
5458 /* Convenience function to get at the Ada encoded lookup name for
5459 LOOKUP_NAME, as a C string. */
5461 static const char *
5462 ada_lookup_name (const lookup_name_info &lookup_name)
5464 return lookup_name.ada ().lookup_name ().c_str ();
5467 /* A helper for add_nonlocal_symbols. Expand all necessary symtabs
5468 for OBJFILE, then walk the objfile's symtabs and update the
5469 results. */
5471 static void
5472 map_matching_symbols (struct objfile *objfile,
5473 const lookup_name_info &lookup_name,
5474 domain_search_flags domain,
5475 int global,
5476 match_data &data)
5478 data.objfile = objfile;
5479 objfile->expand_symtabs_matching (nullptr, &lookup_name,
5480 nullptr, nullptr,
5481 global
5482 ? SEARCH_GLOBAL_BLOCK
5483 : SEARCH_STATIC_BLOCK,
5484 domain);
5486 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5487 for (compunit_symtab *symtab : objfile->compunits ())
5489 const struct block *block
5490 = symtab->blockvector ()->block (block_kind);
5491 if (!iterate_over_symbols_terminated (block, lookup_name,
5492 domain, data))
5493 break;
5497 /* Add to RESULT all non-local symbols whose name and domain match
5498 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5499 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5500 symbols otherwise. */
5502 static void
5503 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5504 const lookup_name_info &lookup_name,
5505 domain_search_flags domain, int global)
5507 struct match_data data (&result);
5509 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5511 for (objfile *objfile : current_program_space->objfiles ())
5513 map_matching_symbols (objfile, lookup_name, domain, global, data);
5515 for (compunit_symtab *cu : objfile->compunits ())
5517 const struct block *global_block
5518 = cu->blockvector ()->global_block ();
5520 if (ada_add_block_renamings (result, global_block, lookup_name,
5521 domain))
5522 data.found_sym = true;
5526 if (result.empty () && global && !is_wild_match)
5528 const char *name = ada_lookup_name (lookup_name);
5529 std::string bracket_name = std::string ("<_ada_") + name + '>';
5530 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5532 for (objfile *objfile : current_program_space->objfiles ())
5533 map_matching_symbols (objfile, name1, domain, global, data);
5537 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5538 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5539 returning the number of matches. Add these to RESULT.
5541 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5542 symbol match within the nest of blocks whose innermost member is BLOCK,
5543 is the one match returned (no other matches in that or
5544 enclosing blocks is returned). If there are any matches in or
5545 surrounding BLOCK, then these alone are returned.
5547 Names prefixed with "standard__" are handled specially:
5548 "standard__" is first stripped off (by the lookup_name
5549 constructor), and only static and global symbols are searched.
5551 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5552 to lookup global symbols. */
5554 static void
5555 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5556 const struct block *block,
5557 const lookup_name_info &lookup_name,
5558 domain_search_flags domain,
5559 int full_search,
5560 int *made_global_lookup_p)
5562 struct symbol *sym;
5564 if (made_global_lookup_p)
5565 *made_global_lookup_p = 0;
5567 /* Special case: If the user specifies a symbol name inside package
5568 Standard, do a non-wild matching of the symbol name without
5569 the "standard__" prefix. This was primarily introduced in order
5570 to allow the user to specifically access the standard exceptions
5571 using, for instance, Standard.Constraint_Error when Constraint_Error
5572 is ambiguous (due to the user defining its own Constraint_Error
5573 entity inside its program). */
5574 if (lookup_name.ada ().standard_p ())
5575 block = NULL;
5577 /* Check the non-global symbols. If we have ANY match, then we're done. */
5579 if (block != NULL)
5581 if (full_search)
5582 ada_add_local_symbols (result, lookup_name, block, domain);
5583 else
5585 /* In the !full_search case we're are being called by
5586 iterate_over_symbols, and we don't want to search
5587 superblocks. */
5588 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5590 if (!result.empty () || !full_search)
5591 return;
5594 /* No non-global symbols found. Check our cache to see if we have
5595 already performed this search before. If we have, then return
5596 the same result. */
5598 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5599 domain, &sym, &block))
5601 if (sym != NULL)
5602 add_defn_to_vec (result, sym, block);
5603 return;
5606 if (made_global_lookup_p)
5607 *made_global_lookup_p = 1;
5609 /* Search symbols from all global blocks. */
5611 add_nonlocal_symbols (result, lookup_name, domain, 1);
5613 /* Now add symbols from all per-file blocks if we've gotten no hits
5614 (not strictly correct, but perhaps better than an error). */
5616 if (result.empty ())
5617 add_nonlocal_symbols (result, lookup_name, domain, 0);
5620 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5621 is non-zero, enclosing scope and in global scopes.
5623 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5624 blocks and symbol tables (if any) in which they were found.
5626 When full_search is non-zero, any non-function/non-enumeral
5627 symbol match within the nest of blocks whose innermost member is BLOCK,
5628 is the one match returned (no other matches in that or
5629 enclosing blocks is returned). If there are any matches in or
5630 surrounding BLOCK, then these alone are returned.
5632 Names prefixed with "standard__" are handled specially: "standard__"
5633 is first stripped off, and only static and global symbols are searched. */
5635 static std::vector<struct block_symbol>
5636 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5637 const struct block *block,
5638 domain_search_flags domain,
5639 int full_search)
5641 int syms_from_global_search;
5642 std::vector<struct block_symbol> results;
5644 ada_add_all_symbols (results, block, lookup_name,
5645 domain, full_search, &syms_from_global_search);
5647 remove_extra_symbols (results);
5649 if (results.empty () && full_search && syms_from_global_search)
5650 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5652 if (results.size () == 1 && full_search && syms_from_global_search)
5653 cache_symbol (ada_lookup_name (lookup_name), domain,
5654 results[0].symbol, results[0].block);
5656 remove_irrelevant_renamings (&results, block);
5657 return results;
5660 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5661 in global scopes, returning (SYM,BLOCK) tuples.
5663 See ada_lookup_symbol_list_worker for further details. */
5665 std::vector<struct block_symbol>
5666 ada_lookup_symbol_list (const char *name, const struct block *block,
5667 domain_search_flags domain)
5669 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5670 lookup_name_info lookup_name (name, name_match_type);
5672 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5675 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5676 to 1, but choosing the first symbol found if there are multiple
5677 choices. */
5679 block_symbol
5680 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5681 domain_search_flags domain)
5683 /* Since we already have an encoded name, wrap it in '<>' to force a
5684 verbatim match. Otherwise, if the name happens to not look like
5685 an encoded name (because it doesn't include a "__"),
5686 ada_lookup_name_info would re-encode/fold it again, and that
5687 would e.g., incorrectly lowercase object renaming names like
5688 "R28b" -> "r28b". */
5689 std::string verbatim = add_angle_brackets (name);
5690 return ada_lookup_symbol (verbatim.c_str (), block, domain);
5693 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5694 scope and in global scopes, or NULL if none. NAME is folded and
5695 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5696 choosing the first symbol if there are multiple choices. */
5698 struct block_symbol
5699 ada_lookup_symbol (const char *name, const struct block *block0,
5700 domain_search_flags domain)
5702 std::vector<struct block_symbol> candidates
5703 = ada_lookup_symbol_list (name, block0, domain);
5705 if (candidates.empty ())
5706 return {};
5708 return candidates[0];
5712 /* True iff STR is a possible encoded suffix of a normal Ada name
5713 that is to be ignored for matching purposes. Suffixes of parallel
5714 names (e.g., XVE) are not included here. Currently, the possible suffixes
5715 are given by any of the regular expressions:
5717 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5718 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5719 TKB [subprogram suffix for task bodies]
5720 _E[0-9]+[bs]$ [protected object entry suffixes]
5721 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5723 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5724 match is performed. This sequence is used to differentiate homonyms,
5725 is an optional part of a valid name suffix. */
5727 static int
5728 is_name_suffix (const char *str)
5730 int k;
5731 const char *matching;
5732 const int len = strlen (str);
5734 /* Skip optional leading __[0-9]+. */
5736 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5738 str += 3;
5739 while (isdigit (str[0]))
5740 str += 1;
5743 /* [.$][0-9]+ */
5745 if (str[0] == '.' || str[0] == '$')
5747 matching = str + 1;
5748 while (isdigit (matching[0]))
5749 matching += 1;
5750 if (matching[0] == '\0')
5751 return 1;
5754 /* ___[0-9]+ */
5756 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5758 matching = str + 3;
5759 while (isdigit (matching[0]))
5760 matching += 1;
5761 if (matching[0] == '\0')
5762 return 1;
5765 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5767 if (strcmp (str, "TKB") == 0)
5768 return 1;
5770 #if 0
5771 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5772 with a N at the end. Unfortunately, the compiler uses the same
5773 convention for other internal types it creates. So treating
5774 all entity names that end with an "N" as a name suffix causes
5775 some regressions. For instance, consider the case of an enumerated
5776 type. To support the 'Image attribute, it creates an array whose
5777 name ends with N.
5778 Having a single character like this as a suffix carrying some
5779 information is a bit risky. Perhaps we should change the encoding
5780 to be something like "_N" instead. In the meantime, do not do
5781 the following check. */
5782 /* Protected Object Subprograms */
5783 if (len == 1 && str [0] == 'N')
5784 return 1;
5785 #endif
5787 /* _E[0-9]+[bs]$ */
5788 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5790 matching = str + 3;
5791 while (isdigit (matching[0]))
5792 matching += 1;
5793 if ((matching[0] == 'b' || matching[0] == 's')
5794 && matching [1] == '\0')
5795 return 1;
5798 /* ??? We should not modify STR directly, as we are doing below. This
5799 is fine in this case, but may become problematic later if we find
5800 that this alternative did not work, and want to try matching
5801 another one from the beginning of STR. Since we modified it, we
5802 won't be able to find the beginning of the string anymore! */
5803 if (str[0] == 'X')
5805 str += 1;
5806 while (str[0] != '_' && str[0] != '\0')
5808 if (str[0] != 'n' && str[0] != 'b')
5809 return 0;
5810 str += 1;
5814 if (str[0] == '\000')
5815 return 1;
5817 if (str[0] == '_')
5819 if (str[1] != '_' || str[2] == '\000')
5820 return 0;
5821 if (str[2] == '_')
5823 if (strcmp (str + 3, "JM") == 0)
5824 return 1;
5825 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5826 the LJM suffix in favor of the JM one. But we will
5827 still accept LJM as a valid suffix for a reasonable
5828 amount of time, just to allow ourselves to debug programs
5829 compiled using an older version of GNAT. */
5830 if (strcmp (str + 3, "LJM") == 0)
5831 return 1;
5832 if (str[3] != 'X')
5833 return 0;
5834 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5835 || str[4] == 'U' || str[4] == 'P')
5836 return 1;
5837 if (str[4] == 'R' && str[5] != 'T')
5838 return 1;
5839 return 0;
5841 if (!isdigit (str[2]))
5842 return 0;
5843 for (k = 3; str[k] != '\0'; k += 1)
5844 if (!isdigit (str[k]) && str[k] != '_')
5845 return 0;
5846 return 1;
5848 if (str[0] == '$' && isdigit (str[1]))
5850 for (k = 2; str[k] != '\0'; k += 1)
5851 if (!isdigit (str[k]) && str[k] != '_')
5852 return 0;
5853 return 1;
5855 return 0;
5858 /* Return non-zero if the string starting at NAME and ending before
5859 NAME_END contains no capital letters. */
5861 static int
5862 is_valid_name_for_wild_match (const char *name0)
5864 std::string decoded_name = ada_decode (name0);
5865 int i;
5867 /* If the decoded name starts with an angle bracket, it means that
5868 NAME0 does not follow the GNAT encoding format. It should then
5869 not be allowed as a possible wild match. */
5870 if (decoded_name[0] == '<')
5871 return 0;
5873 for (i=0; decoded_name[i] != '\0'; i++)
5874 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5875 return 0;
5877 return 1;
5880 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5881 character which could start a simple name. Assumes that *NAMEP points
5882 somewhere inside the string beginning at NAME0. */
5884 static int
5885 advance_wild_match (const char **namep, const char *name0, char target0)
5887 const char *name = *namep;
5889 while (1)
5891 char t0, t1;
5893 t0 = *name;
5894 if (t0 == '_')
5896 t1 = name[1];
5897 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5899 name += 1;
5900 if (name == name0 + 5 && startswith (name0, "_ada"))
5901 break;
5902 else
5903 name += 1;
5905 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5906 || name[2] == target0))
5908 name += 2;
5909 break;
5911 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5913 /* Names like "pkg__B_N__name", where N is a number, are
5914 block-local. We can handle these by simply skipping
5915 the "B_" here. */
5916 name += 4;
5918 else
5919 return 0;
5921 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5922 name += 1;
5923 else
5924 return 0;
5927 *namep = name;
5928 return 1;
5931 /* Return true iff NAME encodes a name of the form prefix.PATN.
5932 Ignores any informational suffixes of NAME (i.e., for which
5933 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5934 simple name. */
5936 static bool
5937 wild_match (const char *name, const char *patn)
5939 const char *p;
5940 const char *name0 = name;
5942 if (startswith (name, "___ghost_"))
5943 name += 9;
5945 while (1)
5947 const char *match = name;
5949 if (*name == *patn)
5951 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5952 if (*p != *name)
5953 break;
5954 if (*p == '\0' && is_name_suffix (name))
5955 return match == name0 || is_valid_name_for_wild_match (name0);
5957 if (name[-1] == '_')
5958 name -= 1;
5960 if (!advance_wild_match (&name, name0, *patn))
5961 return false;
5965 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
5966 necessary). OBJFILE is the section containing BLOCK. */
5968 static void
5969 ada_add_block_symbols (std::vector<struct block_symbol> &result,
5970 const struct block *block,
5971 const lookup_name_info &lookup_name,
5972 domain_search_flags domain, struct objfile *objfile)
5974 /* A matching argument symbol, if any. */
5975 struct symbol *arg_sym;
5976 /* Set true when we find a matching non-argument symbol. */
5977 bool found_sym;
5979 arg_sym = NULL;
5980 found_sym = false;
5981 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
5983 if (sym->matches (domain))
5985 if (sym->aclass () != LOC_UNRESOLVED)
5987 if (sym->is_argument ())
5988 arg_sym = sym;
5989 else
5991 found_sym = true;
5992 add_defn_to_vec (result, sym, block);
5998 /* Handle renamings. */
6000 if (ada_add_block_renamings (result, block, lookup_name, domain))
6001 found_sym = true;
6003 if (!found_sym && arg_sym != NULL)
6005 add_defn_to_vec (result, arg_sym, block);
6008 if (!lookup_name.ada ().wild_match_p ())
6010 arg_sym = NULL;
6011 found_sym = false;
6012 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6013 const char *name = ada_lookup_name.c_str ();
6014 size_t name_len = ada_lookup_name.size ();
6016 for (struct symbol *sym : block_iterator_range (block))
6018 if (sym->matches (domain))
6020 int cmp;
6022 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6023 if (cmp == 0)
6025 cmp = !startswith (sym->linkage_name (), "_ada_");
6026 if (cmp == 0)
6027 cmp = strncmp (name, sym->linkage_name () + 5,
6028 name_len);
6031 if (cmp == 0
6032 && is_name_suffix (sym->linkage_name () + name_len + 5))
6034 if (sym->aclass () != LOC_UNRESOLVED)
6036 if (sym->is_argument ())
6037 arg_sym = sym;
6038 else
6040 found_sym = true;
6041 add_defn_to_vec (result, sym, block);
6048 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6049 They aren't parameters, right? */
6050 if (!found_sym && arg_sym != NULL)
6052 add_defn_to_vec (result, arg_sym, block);
6058 /* Symbol Completion */
6060 /* See symtab.h. */
6062 bool
6063 ada_lookup_name_info::matches
6064 (const char *sym_name,
6065 symbol_name_match_type match_type,
6066 completion_match_result *comp_match_res) const
6068 bool match = false;
6069 const char *text = m_encoded_name.c_str ();
6070 size_t text_len = m_encoded_name.size ();
6072 /* First, test against the fully qualified name of the symbol. */
6074 if (strncmp (sym_name, text, text_len) == 0)
6075 match = true;
6077 std::string decoded_name = ada_decode (sym_name);
6078 if (match && !m_encoded_p)
6080 /* One needed check before declaring a positive match is to verify
6081 that iff we are doing a verbatim match, the decoded version
6082 of the symbol name starts with '<'. Otherwise, this symbol name
6083 is not a suitable completion. */
6085 bool has_angle_bracket = (decoded_name[0] == '<');
6086 match = (has_angle_bracket == m_verbatim_p);
6089 if (match && !m_verbatim_p)
6091 /* When doing non-verbatim match, another check that needs to
6092 be done is to verify that the potentially matching symbol name
6093 does not include capital letters, because the ada-mode would
6094 not be able to understand these symbol names without the
6095 angle bracket notation. */
6096 const char *tmp;
6098 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6099 if (*tmp != '\0')
6100 match = false;
6103 /* Second: Try wild matching... */
6105 if (!match && m_wild_match_p)
6107 /* Since we are doing wild matching, this means that TEXT
6108 may represent an unqualified symbol name. We therefore must
6109 also compare TEXT against the unqualified name of the symbol. */
6110 sym_name = ada_unqualified_name (decoded_name.c_str ());
6112 if (strncmp (sym_name, text, text_len) == 0)
6113 match = true;
6116 /* Finally: If we found a match, prepare the result to return. */
6118 if (!match)
6119 return false;
6121 if (comp_match_res != NULL)
6123 std::string &match_str = comp_match_res->match.storage ();
6125 if (!m_encoded_p)
6126 match_str = ada_decode (sym_name);
6127 else
6129 if (m_verbatim_p)
6130 match_str = add_angle_brackets (sym_name);
6131 else
6132 match_str = sym_name;
6136 comp_match_res->set_match (match_str.c_str ());
6139 return true;
6142 /* Field Access */
6144 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6145 for tagged types. */
6147 static int
6148 ada_is_dispatch_table_ptr_type (struct type *type)
6150 const char *name;
6152 if (type->code () != TYPE_CODE_PTR)
6153 return 0;
6155 name = type->target_type ()->name ();
6156 if (name == NULL)
6157 return 0;
6159 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6162 /* Return non-zero if TYPE is an interface tag. */
6164 static int
6165 ada_is_interface_tag (struct type *type)
6167 const char *name = type->name ();
6169 if (name == NULL)
6170 return 0;
6172 return (strcmp (name, "ada__tags__interface_tag") == 0);
6175 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6176 to be invisible to users. */
6179 ada_is_ignored_field (struct type *type, int field_num)
6181 if (field_num < 0 || field_num > type->num_fields ())
6182 return 1;
6184 /* Check the name of that field. */
6186 const char *name = type->field (field_num).name ();
6188 /* Anonymous field names should not be printed.
6189 brobecker/2007-02-20: I don't think this can actually happen
6190 but we don't want to print the value of anonymous fields anyway. */
6191 if (name == NULL)
6192 return 1;
6194 /* Normally, fields whose name start with an underscore ("_")
6195 are fields that have been internally generated by the compiler,
6196 and thus should not be printed. The "_parent" field is special,
6197 however: This is a field internally generated by the compiler
6198 for tagged types, and it contains the components inherited from
6199 the parent type. This field should not be printed as is, but
6200 should not be ignored either. */
6201 if (name[0] == '_' && !startswith (name, "_parent"))
6202 return 1;
6204 /* The compiler doesn't document this, but sometimes it emits
6205 a field whose name starts with a capital letter, like 'V148s'.
6206 These aren't marked as artificial in any way, but we know they
6207 should be ignored. However, wrapper fields should not be
6208 ignored. */
6209 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6211 /* Wrapper field. */
6213 else if (isupper (name[0]))
6214 return 1;
6217 /* If this is the dispatch table of a tagged type or an interface tag,
6218 then ignore. */
6219 if (ada_is_tagged_type (type, 1)
6220 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6221 || ada_is_interface_tag (type->field (field_num).type ())))
6222 return 1;
6224 /* Not a special field, so it should not be ignored. */
6225 return 0;
6228 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6229 pointer or reference type whose ultimate target has a tag field. */
6232 ada_is_tagged_type (struct type *type, int refok)
6234 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6237 /* True iff TYPE represents the type of X'Tag */
6240 ada_is_tag_type (struct type *type)
6242 type = ada_check_typedef (type);
6244 if (type == NULL || type->code () != TYPE_CODE_PTR)
6245 return 0;
6246 else
6248 const char *name = ada_type_name (type->target_type ());
6250 return (name != NULL
6251 && strcmp (name, "ada__tags__dispatch_table") == 0);
6255 /* The type of the tag on VAL. */
6257 static struct type *
6258 ada_tag_type (struct value *val)
6260 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6263 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6264 retired at Ada 05). */
6266 static int
6267 is_ada95_tag (struct value *tag)
6269 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6272 /* The value of the tag on VAL. */
6274 static struct value *
6275 ada_value_tag (struct value *val)
6277 return ada_value_struct_elt (val, "_tag", 0);
6280 /* The value of the tag on the object of type TYPE whose contents are
6281 saved at VALADDR, if it is non-null, or is at memory address
6282 ADDRESS. */
6284 static struct value *
6285 value_tag_from_contents_and_address (struct type *type,
6286 const gdb_byte *valaddr,
6287 CORE_ADDR address)
6289 int tag_byte_offset;
6290 struct type *tag_type;
6292 gdb::array_view<const gdb_byte> contents;
6293 if (valaddr != nullptr)
6294 contents = gdb::make_array_view (valaddr, type->length ());
6295 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6296 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6297 NULL, NULL, NULL))
6299 const gdb_byte *valaddr1 = ((valaddr == NULL)
6300 ? NULL
6301 : valaddr + tag_byte_offset);
6302 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6304 return value_from_contents_and_address (tag_type, valaddr1, address1);
6306 return NULL;
6309 static struct type *
6310 type_from_tag (struct value *tag)
6312 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6314 if (type_name != NULL)
6315 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6316 return NULL;
6319 /* Given a value OBJ of a tagged type, return a value of this
6320 type at the base address of the object. The base address, as
6321 defined in Ada.Tags, it is the address of the primary tag of
6322 the object, and therefore where the field values of its full
6323 view can be fetched. */
6325 struct value *
6326 ada_tag_value_at_base_address (struct value *obj)
6328 struct value *val;
6329 LONGEST offset_to_top = 0;
6330 struct type *ptr_type, *obj_type;
6331 struct value *tag;
6332 CORE_ADDR base_address;
6334 obj_type = obj->type ();
6336 /* It is the responsibility of the caller to deref pointers. */
6338 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6339 return obj;
6341 tag = ada_value_tag (obj);
6342 if (!tag)
6343 return obj;
6345 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6347 if (is_ada95_tag (tag))
6348 return obj;
6350 struct type *offset_type
6351 = language_lookup_primitive_type (language_def (language_ada),
6352 current_inferior ()->arch (),
6353 "storage_offset");
6354 ptr_type = lookup_pointer_type (offset_type);
6355 val = value_cast (ptr_type, tag);
6356 if (!val)
6357 return obj;
6359 /* It is perfectly possible that an exception be raised while
6360 trying to determine the base address, just like for the tag;
6361 see ada_tag_name for more details. We do not print the error
6362 message for the same reason. */
6366 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6369 catch (const gdb_exception_error &e)
6371 return obj;
6374 /* If offset is null, nothing to do. */
6376 if (offset_to_top == 0)
6377 return obj;
6379 /* -1 is a special case in Ada.Tags; however, what should be done
6380 is not quite clear from the documentation. So do nothing for
6381 now. */
6383 if (offset_to_top == -1)
6384 return obj;
6386 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6387 top is used. In this situation the offset is stored just after
6388 the tag, in the object itself. */
6389 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6390 if (offset_to_top == last)
6392 struct value *tem = value_addr (tag);
6393 tem = value_ptradd (tem, 1);
6394 tem = value_cast (ptr_type, tem);
6395 offset_to_top = value_as_long (value_ind (tem));
6398 if (offset_to_top > 0)
6400 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6401 from the base address. This was however incompatible with
6402 C++ dispatch table: C++ uses a *negative* value to *add*
6403 to the base address. Ada's convention has therefore been
6404 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6405 use the same convention. Here, we support both cases by
6406 checking the sign of OFFSET_TO_TOP. */
6407 offset_to_top = -offset_to_top;
6410 base_address = obj->address () + offset_to_top;
6411 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6413 /* Make sure that we have a proper tag at the new address.
6414 Otherwise, offset_to_top is bogus (which can happen when
6415 the object is not initialized yet). */
6417 if (!tag)
6418 return obj;
6420 obj_type = type_from_tag (tag);
6422 if (!obj_type)
6423 return obj;
6425 return value_from_contents_and_address (obj_type, NULL, base_address);
6428 /* Return the "ada__tags__type_specific_data" type. */
6430 static struct type *
6431 ada_get_tsd_type (struct inferior *inf)
6433 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6435 if (data->tsd_type == 0)
6436 data->tsd_type
6437 = lookup_transparent_type ("<ada__tags__type_specific_data>",
6438 SEARCH_TYPE_DOMAIN);
6439 return data->tsd_type;
6442 /* Return the TSD (type-specific data) associated to the given TAG.
6443 TAG is assumed to be the tag of a tagged-type entity.
6445 May return NULL if we are unable to get the TSD. */
6447 static struct value *
6448 ada_get_tsd_from_tag (struct value *tag)
6450 struct value *val;
6451 struct type *type;
6453 /* First option: The TSD is simply stored as a field of our TAG.
6454 Only older versions of GNAT would use this format, but we have
6455 to test it first, because there are no visible markers for
6456 the current approach except the absence of that field. */
6458 val = ada_value_struct_elt (tag, "tsd", 1);
6459 if (val)
6460 return val;
6462 /* Try the second representation for the dispatch table (in which
6463 there is no explicit 'tsd' field in the referent of the tag pointer,
6464 and instead the tsd pointer is stored just before the dispatch
6465 table. */
6467 type = ada_get_tsd_type (current_inferior());
6468 if (type == NULL)
6469 return NULL;
6470 type = lookup_pointer_type (lookup_pointer_type (type));
6471 val = value_cast (type, tag);
6472 if (val == NULL)
6473 return NULL;
6474 return value_ind (value_ptradd (val, -1));
6477 /* Given the TSD of a tag (type-specific data), return a string
6478 containing the name of the associated type.
6480 May return NULL if we are unable to determine the tag name. */
6482 static gdb::unique_xmalloc_ptr<char>
6483 ada_tag_name_from_tsd (struct value *tsd)
6485 struct value *val;
6487 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6488 if (val == NULL)
6489 return NULL;
6490 gdb::unique_xmalloc_ptr<char> buffer
6491 = target_read_string (value_as_address (val), INT_MAX);
6492 if (buffer == nullptr)
6493 return nullptr;
6497 /* Let this throw an exception on error. If the data is
6498 uninitialized, we'd rather not have the user see a
6499 warning. */
6500 const char *folded = ada_fold_name (buffer.get (), true);
6501 return make_unique_xstrdup (folded);
6503 catch (const gdb_exception &)
6505 return nullptr;
6509 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6510 a C string.
6512 Return NULL if the TAG is not an Ada tag, or if we were unable to
6513 determine the name of that tag. */
6515 gdb::unique_xmalloc_ptr<char>
6516 ada_tag_name (struct value *tag)
6518 gdb::unique_xmalloc_ptr<char> name;
6520 if (!ada_is_tag_type (tag->type ()))
6521 return NULL;
6523 /* It is perfectly possible that an exception be raised while trying
6524 to determine the TAG's name, even under normal circumstances:
6525 The associated variable may be uninitialized or corrupted, for
6526 instance. We do not let any exception propagate past this point.
6527 instead we return NULL.
6529 We also do not print the error message either (which often is very
6530 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6531 the caller print a more meaningful message if necessary. */
6534 struct value *tsd = ada_get_tsd_from_tag (tag);
6536 if (tsd != NULL)
6537 name = ada_tag_name_from_tsd (tsd);
6539 catch (const gdb_exception_error &e)
6543 return name;
6546 /* The parent type of TYPE, or NULL if none. */
6548 struct type *
6549 ada_parent_type (struct type *type)
6551 int i;
6553 type = ada_check_typedef (type);
6555 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6556 return NULL;
6558 for (i = 0; i < type->num_fields (); i += 1)
6559 if (ada_is_parent_field (type, i))
6561 struct type *parent_type = type->field (i).type ();
6563 /* If the _parent field is a pointer, then dereference it. */
6564 if (parent_type->code () == TYPE_CODE_PTR)
6565 parent_type = parent_type->target_type ();
6566 /* If there is a parallel XVS type, get the actual base type. */
6567 parent_type = ada_get_base_type (parent_type);
6569 return ada_check_typedef (parent_type);
6572 return NULL;
6575 /* True iff field number FIELD_NUM of structure type TYPE contains the
6576 parent-type (inherited) fields of a derived type. Assumes TYPE is
6577 a structure type with at least FIELD_NUM+1 fields. */
6580 ada_is_parent_field (struct type *type, int field_num)
6582 const char *name = ada_check_typedef (type)->field (field_num).name ();
6584 return (name != NULL
6585 && (startswith (name, "PARENT")
6586 || startswith (name, "_parent")));
6589 /* True iff field number FIELD_NUM of structure type TYPE is a
6590 transparent wrapper field (which should be silently traversed when doing
6591 field selection and flattened when printing). Assumes TYPE is a
6592 structure type with at least FIELD_NUM+1 fields. Such fields are always
6593 structures. */
6596 ada_is_wrapper_field (struct type *type, int field_num)
6598 const char *name = type->field (field_num).name ();
6600 if (name != NULL && strcmp (name, "RETVAL") == 0)
6602 /* This happens in functions with "out" or "in out" parameters
6603 which are passed by copy. For such functions, GNAT describes
6604 the function's return type as being a struct where the return
6605 value is in a field called RETVAL, and where the other "out"
6606 or "in out" parameters are fields of that struct. This is not
6607 a wrapper. */
6608 return 0;
6611 return (name != NULL
6612 && (startswith (name, "PARENT")
6613 || strcmp (name, "REP") == 0
6614 || startswith (name, "_parent")
6615 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6618 /* True iff field number FIELD_NUM of structure or union type TYPE
6619 is a variant wrapper. Assumes TYPE is a structure type with at least
6620 FIELD_NUM+1 fields. */
6623 ada_is_variant_part (struct type *type, int field_num)
6625 /* Only Ada types are eligible. */
6626 if (!ADA_TYPE_P (type))
6627 return 0;
6629 struct type *field_type = type->field (field_num).type ();
6631 return (field_type->code () == TYPE_CODE_UNION
6632 || (is_dynamic_field (type, field_num)
6633 && (field_type->target_type ()->code ()
6634 == TYPE_CODE_UNION)));
6637 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6638 whose discriminants are contained in the record type OUTER_TYPE,
6639 returns the type of the controlling discriminant for the variant.
6640 May return NULL if the type could not be found. */
6642 struct type *
6643 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6645 const char *name = ada_variant_discrim_name (var_type);
6647 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6650 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6651 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6652 represents a 'when others' clause; otherwise 0. */
6654 static int
6655 ada_is_others_clause (struct type *type, int field_num)
6657 const char *name = type->field (field_num).name ();
6659 return (name != NULL && name[0] == 'O');
6662 /* Assuming that TYPE0 is the type of the variant part of a record,
6663 returns the name of the discriminant controlling the variant.
6664 The value is valid until the next call to ada_variant_discrim_name. */
6666 const char *
6667 ada_variant_discrim_name (struct type *type0)
6669 static std::string result;
6670 struct type *type;
6671 const char *name;
6672 const char *discrim_end;
6673 const char *discrim_start;
6675 if (type0->code () == TYPE_CODE_PTR)
6676 type = type0->target_type ();
6677 else
6678 type = type0;
6680 name = ada_type_name (type);
6682 if (name == NULL || name[0] == '\000')
6683 return "";
6685 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6686 discrim_end -= 1)
6688 if (startswith (discrim_end, "___XVN"))
6689 break;
6691 if (discrim_end == name)
6692 return "";
6694 for (discrim_start = discrim_end; discrim_start != name + 3;
6695 discrim_start -= 1)
6697 if (discrim_start == name + 1)
6698 return "";
6699 if ((discrim_start > name + 3
6700 && startswith (discrim_start - 3, "___"))
6701 || discrim_start[-1] == '.')
6702 break;
6705 result = std::string (discrim_start, discrim_end - discrim_start);
6706 return result.c_str ();
6709 /* Scan STR for a subtype-encoded number, beginning at position K.
6710 Put the position of the character just past the number scanned in
6711 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6712 Return 1 if there was a valid number at the given position, and 0
6713 otherwise. A "subtype-encoded" number consists of the absolute value
6714 in decimal, followed by the letter 'm' to indicate a negative number.
6715 Assumes 0m does not occur. */
6718 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6720 ULONGEST RU;
6722 if (!isdigit (str[k]))
6723 return 0;
6725 /* Do it the hard way so as not to make any assumption about
6726 the relationship of unsigned long (%lu scan format code) and
6727 LONGEST. */
6728 RU = 0;
6729 while (isdigit (str[k]))
6731 RU = RU * 10 + (str[k] - '0');
6732 k += 1;
6735 if (str[k] == 'm')
6737 if (R != NULL)
6738 *R = (-(LONGEST) (RU - 1)) - 1;
6739 k += 1;
6741 else if (R != NULL)
6742 *R = (LONGEST) RU;
6744 /* NOTE on the above: Technically, C does not say what the results of
6745 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6746 number representable as a LONGEST (although either would probably work
6747 in most implementations). When RU>0, the locution in the then branch
6748 above is always equivalent to the negative of RU. */
6750 if (new_k != NULL)
6751 *new_k = k;
6752 return 1;
6755 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6756 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6757 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6759 static int
6760 ada_in_variant (LONGEST val, struct type *type, int field_num)
6762 const char *name = type->field (field_num).name ();
6763 int p;
6765 p = 0;
6766 while (1)
6768 switch (name[p])
6770 case '\0':
6771 return 0;
6772 case 'S':
6774 LONGEST W;
6776 if (!ada_scan_number (name, p + 1, &W, &p))
6777 return 0;
6778 if (val == W)
6779 return 1;
6780 break;
6782 case 'R':
6784 LONGEST L, U;
6786 if (!ada_scan_number (name, p + 1, &L, &p)
6787 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6788 return 0;
6789 if (val >= L && val <= U)
6790 return 1;
6791 break;
6793 case 'O':
6794 return 1;
6795 default:
6796 return 0;
6801 /* FIXME: Lots of redundancy below. Try to consolidate. */
6803 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6804 ARG_TYPE, extract and return the value of one of its (non-static)
6805 fields. FIELDNO says which field. Differs from value_primitive_field
6806 only in that it can handle packed values of arbitrary type. */
6808 struct value *
6809 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6810 struct type *arg_type)
6812 struct type *type;
6814 arg_type = ada_check_typedef (arg_type);
6815 type = arg_type->field (fieldno).type ();
6817 /* Handle packed fields. It might be that the field is not packed
6818 relative to its containing structure, but the structure itself is
6819 packed; in this case we must take the bit-field path. */
6820 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
6822 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6823 int bit_size = arg_type->field (fieldno).bitsize ();
6825 return ada_value_primitive_packed_val (arg1,
6826 arg1->contents ().data (),
6827 offset + bit_pos / 8,
6828 bit_pos % 8, bit_size, type);
6830 else
6831 return arg1->primitive_field (offset, fieldno, arg_type);
6834 /* Find field with name NAME in object of type TYPE. If found,
6835 set the following for each argument that is non-null:
6836 - *FIELD_TYPE_P to the field's type;
6837 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6838 an object of that type;
6839 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6840 - *BIT_SIZE_P to its size in bits if the field is packed, and
6841 0 otherwise;
6842 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6843 fields up to but not including the desired field, or by the total
6844 number of fields if not found. A NULL value of NAME never
6845 matches; the function just counts visible fields in this case.
6847 Notice that we need to handle when a tagged record hierarchy
6848 has some components with the same name, like in this scenario:
6850 type Top_T is tagged record
6851 N : Integer := 1;
6852 U : Integer := 974;
6853 A : Integer := 48;
6854 end record;
6856 type Middle_T is new Top.Top_T with record
6857 N : Character := 'a';
6858 C : Integer := 3;
6859 end record;
6861 type Bottom_T is new Middle.Middle_T with record
6862 N : Float := 4.0;
6863 C : Character := '5';
6864 X : Integer := 6;
6865 A : Character := 'J';
6866 end record;
6868 Let's say we now have a variable declared and initialized as follow:
6870 TC : Top_A := new Bottom_T;
6872 And then we use this variable to call this function
6874 procedure Assign (Obj: in out Top_T; TV : Integer);
6876 as follow:
6878 Assign (Top_T (B), 12);
6880 Now, we're in the debugger, and we're inside that procedure
6881 then and we want to print the value of obj.c:
6883 Usually, the tagged record or one of the parent type owns the
6884 component to print and there's no issue but in this particular
6885 case, what does it mean to ask for Obj.C? Since the actual
6886 type for object is type Bottom_T, it could mean two things: type
6887 component C from the Middle_T view, but also component C from
6888 Bottom_T. So in that "undefined" case, when the component is
6889 not found in the non-resolved type (which includes all the
6890 components of the parent type), then resolve it and see if we
6891 get better luck once expanded.
6893 In the case of homonyms in the derived tagged type, we don't
6894 guaranty anything, and pick the one that's easiest for us
6895 to program.
6897 Returns 1 if found, 0 otherwise. */
6899 static int
6900 find_struct_field (const char *name, struct type *type, int offset,
6901 struct type **field_type_p,
6902 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6903 int *index_p)
6905 int i;
6906 int parent_offset = -1;
6908 type = ada_check_typedef (type);
6910 if (field_type_p != NULL)
6911 *field_type_p = NULL;
6912 if (byte_offset_p != NULL)
6913 *byte_offset_p = 0;
6914 if (bit_offset_p != NULL)
6915 *bit_offset_p = 0;
6916 if (bit_size_p != NULL)
6917 *bit_size_p = 0;
6919 for (i = 0; i < type->num_fields (); i += 1)
6921 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6922 type. However, we only need the values to be correct when
6923 the caller asks for them. */
6924 int bit_pos = 0, fld_offset = 0;
6925 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6927 bit_pos = type->field (i).loc_bitpos ();
6928 fld_offset = offset + bit_pos / 8;
6931 const char *t_field_name = type->field (i).name ();
6933 if (t_field_name == NULL)
6934 continue;
6936 else if (ada_is_parent_field (type, i))
6938 /* This is a field pointing us to the parent type of a tagged
6939 type. As hinted in this function's documentation, we give
6940 preference to fields in the current record first, so what
6941 we do here is just record the index of this field before
6942 we skip it. If it turns out we couldn't find our field
6943 in the current record, then we'll get back to it and search
6944 inside it whether the field might exist in the parent. */
6946 parent_offset = i;
6947 continue;
6950 else if (name != NULL && field_name_match (t_field_name, name))
6952 int bit_size = type->field (i).bitsize ();
6954 if (field_type_p != NULL)
6955 *field_type_p = type->field (i).type ();
6956 if (byte_offset_p != NULL)
6957 *byte_offset_p = fld_offset;
6958 if (bit_offset_p != NULL)
6959 *bit_offset_p = bit_pos % 8;
6960 if (bit_size_p != NULL)
6961 *bit_size_p = bit_size;
6962 return 1;
6964 else if (ada_is_wrapper_field (type, i))
6966 if (find_struct_field (name, type->field (i).type (), fld_offset,
6967 field_type_p, byte_offset_p, bit_offset_p,
6968 bit_size_p, index_p))
6969 return 1;
6971 else if (ada_is_variant_part (type, i))
6973 /* PNH: Wait. Do we ever execute this section, or is ARG always of
6974 fixed type?? */
6975 int j;
6976 struct type *field_type
6977 = ada_check_typedef (type->field (i).type ());
6979 for (j = 0; j < field_type->num_fields (); j += 1)
6981 if (find_struct_field (name, field_type->field (j).type (),
6982 fld_offset
6983 + field_type->field (j).loc_bitpos () / 8,
6984 field_type_p, byte_offset_p,
6985 bit_offset_p, bit_size_p, index_p))
6986 return 1;
6989 else if (index_p != NULL)
6990 *index_p += 1;
6993 /* Field not found so far. If this is a tagged type which
6994 has a parent, try finding that field in the parent now. */
6996 if (parent_offset != -1)
6998 /* As above, only compute the offset when truly needed. */
6999 int fld_offset = offset;
7000 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7002 int bit_pos = type->field (parent_offset).loc_bitpos ();
7003 fld_offset += bit_pos / 8;
7006 if (find_struct_field (name, type->field (parent_offset).type (),
7007 fld_offset, field_type_p, byte_offset_p,
7008 bit_offset_p, bit_size_p, index_p))
7009 return 1;
7012 return 0;
7015 /* Number of user-visible fields in record type TYPE. */
7017 static int
7018 num_visible_fields (struct type *type)
7020 int n;
7022 n = 0;
7023 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7024 return n;
7027 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7028 and search in it assuming it has (class) type TYPE.
7029 If found, return value, else return NULL.
7031 Searches recursively through wrapper fields (e.g., '_parent').
7033 In the case of homonyms in the tagged types, please refer to the
7034 long explanation in find_struct_field's function documentation. */
7036 static struct value *
7037 ada_search_struct_field (const char *name, struct value *arg, int offset,
7038 struct type *type)
7040 int i;
7041 int parent_offset = -1;
7043 type = ada_check_typedef (type);
7044 for (i = 0; i < type->num_fields (); i += 1)
7046 const char *t_field_name = type->field (i).name ();
7048 if (t_field_name == NULL)
7049 continue;
7051 else if (ada_is_parent_field (type, i))
7053 /* This is a field pointing us to the parent type of a tagged
7054 type. As hinted in this function's documentation, we give
7055 preference to fields in the current record first, so what
7056 we do here is just record the index of this field before
7057 we skip it. If it turns out we couldn't find our field
7058 in the current record, then we'll get back to it and search
7059 inside it whether the field might exist in the parent. */
7061 parent_offset = i;
7062 continue;
7065 else if (field_name_match (t_field_name, name))
7066 return ada_value_primitive_field (arg, offset, i, type);
7068 else if (ada_is_wrapper_field (type, i))
7070 struct value *v = /* Do not let indent join lines here. */
7071 ada_search_struct_field (name, arg,
7072 offset + type->field (i).loc_bitpos () / 8,
7073 type->field (i).type ());
7075 if (v != NULL)
7076 return v;
7079 else if (ada_is_variant_part (type, i))
7081 /* PNH: Do we ever get here? See find_struct_field. */
7082 int j;
7083 struct type *field_type = ada_check_typedef (type->field (i).type ());
7084 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7086 for (j = 0; j < field_type->num_fields (); j += 1)
7088 struct value *v = ada_search_struct_field /* Force line
7089 break. */
7090 (name, arg,
7091 var_offset + field_type->field (j).loc_bitpos () / 8,
7092 field_type->field (j).type ());
7094 if (v != NULL)
7095 return v;
7100 /* Field not found so far. If this is a tagged type which
7101 has a parent, try finding that field in the parent now. */
7103 if (parent_offset != -1)
7105 struct value *v = ada_search_struct_field (
7106 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7107 type->field (parent_offset).type ());
7109 if (v != NULL)
7110 return v;
7113 return NULL;
7116 static struct value *ada_index_struct_field_1 (int *, struct value *,
7117 int, struct type *);
7120 /* Return field #INDEX in ARG, where the index is that returned by
7121 * find_struct_field through its INDEX_P argument. Adjust the address
7122 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7123 * If found, return value, else return NULL. */
7125 static struct value *
7126 ada_index_struct_field (int index, struct value *arg, int offset,
7127 struct type *type)
7129 return ada_index_struct_field_1 (&index, arg, offset, type);
7133 /* Auxiliary function for ada_index_struct_field. Like
7134 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7135 * *INDEX_P. */
7137 static struct value *
7138 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7139 struct type *type)
7141 int i;
7142 type = ada_check_typedef (type);
7144 for (i = 0; i < type->num_fields (); i += 1)
7146 if (type->field (i).name () == NULL)
7147 continue;
7148 else if (ada_is_wrapper_field (type, i))
7150 struct value *v = /* Do not let indent join lines here. */
7151 ada_index_struct_field_1 (index_p, arg,
7152 offset + type->field (i).loc_bitpos () / 8,
7153 type->field (i).type ());
7155 if (v != NULL)
7156 return v;
7159 else if (ada_is_variant_part (type, i))
7161 /* PNH: Do we ever get here? See ada_search_struct_field,
7162 find_struct_field. */
7163 error (_("Cannot assign this kind of variant record"));
7165 else if (*index_p == 0)
7166 return ada_value_primitive_field (arg, offset, i, type);
7167 else
7168 *index_p -= 1;
7170 return NULL;
7173 /* Return a string representation of type TYPE. */
7175 static std::string
7176 type_as_string (struct type *type)
7178 string_file tmp_stream;
7180 type_print (type, "", &tmp_stream, -1);
7182 return tmp_stream.release ();
7185 /* Given a type TYPE, look up the type of the component of type named NAME.
7187 Matches any field whose name has NAME as a prefix, possibly
7188 followed by "___".
7190 TYPE can be either a struct or union. If REFOK, TYPE may also
7191 be a (pointer or reference)+ to a struct or union, and the
7192 ultimate target type will be searched.
7194 Looks recursively into variant clauses and parent types.
7196 In the case of homonyms in the tagged types, please refer to the
7197 long explanation in find_struct_field's function documentation.
7199 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7200 TYPE is not a type of the right kind. */
7202 static struct type *
7203 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7204 int noerr)
7206 if (name == NULL)
7207 goto BadName;
7209 if (refok && type != NULL)
7210 while (1)
7212 type = ada_check_typedef (type);
7213 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7214 break;
7215 type = type->target_type ();
7218 if (type == NULL
7219 || (type->code () != TYPE_CODE_STRUCT
7220 && type->code () != TYPE_CODE_UNION))
7222 if (noerr)
7223 return NULL;
7225 error (_("Type %s is not a structure or union type"),
7226 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7229 type = to_static_fixed_type (type);
7231 struct type *result;
7232 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7233 nullptr);
7234 if (result != nullptr)
7235 return result;
7237 BadName:
7238 if (!noerr)
7240 const char *name_str = name != NULL ? name : _("<null>");
7242 error (_("Type %s has no component named %s"),
7243 type_as_string (type).c_str (), name_str);
7246 return NULL;
7249 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7250 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7251 represents an unchecked union (that is, the variant part of a
7252 record that is named in an Unchecked_Union pragma). */
7254 static int
7255 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7257 const char *discrim_name = ada_variant_discrim_name (var_type);
7259 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7263 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7264 within OUTER, determine which variant clause (field number in VAR_TYPE,
7265 numbering from 0) is applicable. Returns -1 if none are. */
7268 ada_which_variant_applies (struct type *var_type, struct value *outer)
7270 int others_clause;
7271 int i;
7272 const char *discrim_name = ada_variant_discrim_name (var_type);
7273 struct value *discrim;
7274 LONGEST discrim_val;
7276 /* Using plain value_from_contents_and_address here causes problems
7277 because we will end up trying to resolve a type that is currently
7278 being constructed. */
7279 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7280 if (discrim == NULL)
7281 return -1;
7282 discrim_val = value_as_long (discrim);
7284 others_clause = -1;
7285 for (i = 0; i < var_type->num_fields (); i += 1)
7287 if (ada_is_others_clause (var_type, i))
7288 others_clause = i;
7289 else if (ada_in_variant (discrim_val, var_type, i))
7290 return i;
7293 return others_clause;
7298 /* Dynamic-Sized Records */
7300 /* Strategy: The type ostensibly attached to a value with dynamic size
7301 (i.e., a size that is not statically recorded in the debugging
7302 data) does not accurately reflect the size or layout of the value.
7303 Our strategy is to convert these values to values with accurate,
7304 conventional types that are constructed on the fly. */
7306 /* There is a subtle and tricky problem here. In general, we cannot
7307 determine the size of dynamic records without its data. However,
7308 the 'struct value' data structure, which GDB uses to represent
7309 quantities in the inferior process (the target), requires the size
7310 of the type at the time of its allocation in order to reserve space
7311 for GDB's internal copy of the data. That's why the
7312 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7313 rather than struct value*s.
7315 However, GDB's internal history variables ($1, $2, etc.) are
7316 struct value*s containing internal copies of the data that are not, in
7317 general, the same as the data at their corresponding addresses in
7318 the target. Fortunately, the types we give to these values are all
7319 conventional, fixed-size types (as per the strategy described
7320 above), so that we don't usually have to perform the
7321 'to_fixed_xxx_type' conversions to look at their values.
7322 Unfortunately, there is one exception: if one of the internal
7323 history variables is an array whose elements are unconstrained
7324 records, then we will need to create distinct fixed types for each
7325 element selected. */
7327 /* The upshot of all of this is that many routines take a (type, host
7328 address, target address) triple as arguments to represent a value.
7329 The host address, if non-null, is supposed to contain an internal
7330 copy of the relevant data; otherwise, the program is to consult the
7331 target at the target address. */
7333 /* Assuming that VAL0 represents a pointer value, the result of
7334 dereferencing it. Differs from value_ind in its treatment of
7335 dynamic-sized types. */
7337 struct value *
7338 ada_value_ind (struct value *val0)
7340 struct value *val = value_ind (val0);
7342 if (ada_is_tagged_type (val->type (), 0))
7343 val = ada_tag_value_at_base_address (val);
7345 return ada_to_fixed_value (val);
7348 /* The value resulting from dereferencing any "reference to"
7349 qualifiers on VAL0. */
7351 static struct value *
7352 ada_coerce_ref (struct value *val0)
7354 if (val0->type ()->code () == TYPE_CODE_REF)
7356 struct value *val = val0;
7358 val = coerce_ref (val);
7360 if (ada_is_tagged_type (val->type (), 0))
7361 val = ada_tag_value_at_base_address (val);
7363 return ada_to_fixed_value (val);
7365 else
7366 return val0;
7369 /* Return the bit alignment required for field #F of template type TYPE. */
7371 static unsigned int
7372 field_alignment (struct type *type, int f)
7374 const char *name = type->field (f).name ();
7375 int len;
7376 int align_offset;
7378 /* The field name should never be null, unless the debugging information
7379 is somehow malformed. In this case, we assume the field does not
7380 require any alignment. */
7381 if (name == NULL)
7382 return 1;
7384 len = strlen (name);
7386 if (!isdigit (name[len - 1]))
7387 return 1;
7389 if (isdigit (name[len - 2]))
7390 align_offset = len - 2;
7391 else
7392 align_offset = len - 1;
7394 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7395 return TARGET_CHAR_BIT;
7397 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7400 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7402 static struct symbol *
7403 ada_find_any_type_symbol (const char *name)
7405 return standard_lookup (name, get_selected_block (nullptr),
7406 SEARCH_TYPE_DOMAIN);
7409 /* Find a type named NAME. Ignores ambiguity. This routine will look
7410 solely for types defined by debug info, it will not search the GDB
7411 primitive types. */
7413 static struct type *
7414 ada_find_any_type (const char *name)
7416 struct symbol *sym = ada_find_any_type_symbol (name);
7418 if (sym != NULL)
7419 return sym->type ();
7421 return NULL;
7424 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7425 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7426 symbol, in which case it is returned. Otherwise, this looks for
7427 symbols whose name is that of NAME_SYM suffixed with "___XR".
7428 Return symbol if found, and NULL otherwise. */
7430 static bool
7431 ada_is_renaming_symbol (struct symbol *name_sym)
7433 const char *name = name_sym->linkage_name ();
7434 return strstr (name, "___XR") != NULL;
7437 /* Because of GNAT encoding conventions, several GDB symbols may match a
7438 given type name. If the type denoted by TYPE0 is to be preferred to
7439 that of TYPE1 for purposes of type printing, return non-zero;
7440 otherwise return 0. */
7443 ada_prefer_type (struct type *type0, struct type *type1)
7445 if (type1 == NULL)
7446 return 1;
7447 else if (type0 == NULL)
7448 return 0;
7449 else if (type1->code () == TYPE_CODE_VOID)
7450 return 1;
7451 else if (type0->code () == TYPE_CODE_VOID)
7452 return 0;
7453 else if (type1->name () == NULL && type0->name () != NULL)
7454 return 1;
7455 else if (ada_is_constrained_packed_array_type (type0))
7456 return 1;
7457 else if (ada_is_array_descriptor_type (type0)
7458 && !ada_is_array_descriptor_type (type1))
7459 return 1;
7460 else
7462 const char *type0_name = type0->name ();
7463 const char *type1_name = type1->name ();
7465 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7466 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7467 return 1;
7469 return 0;
7472 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7473 null. */
7475 const char *
7476 ada_type_name (struct type *type)
7478 if (type == NULL)
7479 return NULL;
7480 return type->name ();
7483 /* Search the list of "descriptive" types associated to TYPE for a type
7484 whose name is NAME. */
7486 static struct type *
7487 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7489 struct type *result, *tmp;
7491 if (ada_ignore_descriptive_types_p)
7492 return NULL;
7494 /* If there no descriptive-type info, then there is no parallel type
7495 to be found. */
7496 if (!HAVE_GNAT_AUX_INFO (type))
7497 return NULL;
7499 result = TYPE_DESCRIPTIVE_TYPE (type);
7500 while (result != NULL)
7502 const char *result_name = ada_type_name (result);
7504 if (result_name == NULL)
7506 warning (_("unexpected null name on descriptive type"));
7507 return NULL;
7510 /* If the names match, stop. */
7511 if (strcmp (result_name, name) == 0)
7512 break;
7514 /* Otherwise, look at the next item on the list, if any. */
7515 if (HAVE_GNAT_AUX_INFO (result))
7516 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7517 else
7518 tmp = NULL;
7520 /* If not found either, try after having resolved the typedef. */
7521 if (tmp != NULL)
7522 result = tmp;
7523 else
7525 result = check_typedef (result);
7526 if (HAVE_GNAT_AUX_INFO (result))
7527 result = TYPE_DESCRIPTIVE_TYPE (result);
7528 else
7529 result = NULL;
7533 /* If we didn't find a match, see whether this is a packed array. With
7534 older compilers, the descriptive type information is either absent or
7535 irrelevant when it comes to packed arrays so the above lookup fails.
7536 Fall back to using a parallel lookup by name in this case. */
7537 if (result == NULL && ada_is_constrained_packed_array_type (type))
7538 return ada_find_any_type (name);
7540 return result;
7543 /* Find a parallel type to TYPE with the specified NAME, using the
7544 descriptive type taken from the debugging information, if available,
7545 and otherwise using the (slower) name-based method. */
7547 static struct type *
7548 ada_find_parallel_type_with_name (struct type *type, const char *name)
7550 struct type *result = NULL;
7552 if (HAVE_GNAT_AUX_INFO (type))
7553 result = find_parallel_type_by_descriptive_type (type, name);
7554 else
7555 result = ada_find_any_type (name);
7557 return result;
7560 /* Same as above, but specify the name of the parallel type by appending
7561 SUFFIX to the name of TYPE. */
7563 struct type *
7564 ada_find_parallel_type (struct type *type, const char *suffix)
7566 char *name;
7567 const char *type_name = ada_type_name (type);
7568 int len;
7570 if (type_name == NULL)
7571 return NULL;
7573 len = strlen (type_name);
7575 name = (char *) alloca (len + strlen (suffix) + 1);
7577 strcpy (name, type_name);
7578 strcpy (name + len, suffix);
7580 return ada_find_parallel_type_with_name (type, name);
7583 /* If TYPE is a variable-size record type, return the corresponding template
7584 type describing its fields. Otherwise, return NULL. */
7586 static struct type *
7587 dynamic_template_type (struct type *type)
7589 type = ada_check_typedef (type);
7591 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7592 || ada_type_name (type) == NULL)
7593 return NULL;
7594 else
7596 int len = strlen (ada_type_name (type));
7598 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7599 return type;
7600 else
7601 return ada_find_parallel_type (type, "___XVE");
7605 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7606 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7608 static int
7609 is_dynamic_field (struct type *templ_type, int field_num)
7611 const char *name = templ_type->field (field_num).name ();
7613 return name != NULL
7614 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7615 && strstr (name, "___XVL") != NULL;
7618 /* The index of the variant field of TYPE, or -1 if TYPE does not
7619 represent a variant record type. */
7621 static int
7622 variant_field_index (struct type *type)
7624 int f;
7626 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7627 return -1;
7629 for (f = 0; f < type->num_fields (); f += 1)
7631 if (ada_is_variant_part (type, f))
7632 return f;
7634 return -1;
7637 /* A record type with no fields. */
7639 static struct type *
7640 empty_record (struct type *templ)
7642 struct type *type = type_allocator (templ).new_type ();
7644 type->set_code (TYPE_CODE_STRUCT);
7645 INIT_NONE_SPECIFIC (type);
7646 type->set_name ("<empty>");
7647 type->set_length (0);
7648 return type;
7651 /* An ordinary record type (with fixed-length fields) that describes
7652 the value of type TYPE at VALADDR or ADDRESS (see comments at
7653 the beginning of this section) VAL according to GNAT conventions.
7654 DVAL0 should describe the (portion of a) record that contains any
7655 necessary discriminants. It should be NULL if VAL->type () is
7656 an outer-level type (i.e., as opposed to a branch of a variant.) A
7657 variant field (unless unchecked) is replaced by a particular branch
7658 of the variant.
7660 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7661 length are not statically known are discarded. As a consequence,
7662 VALADDR, ADDRESS and DVAL0 are ignored.
7664 NOTE: Limitations: For now, we assume that dynamic fields and
7665 variants occupy whole numbers of bytes. However, they need not be
7666 byte-aligned. */
7668 struct type *
7669 ada_template_to_fixed_record_type_1 (struct type *type,
7670 const gdb_byte *valaddr,
7671 CORE_ADDR address, struct value *dval0,
7672 int keep_dynamic_fields)
7674 struct value *dval;
7675 struct type *rtype;
7676 int nfields, bit_len;
7677 int variant_field;
7678 long off;
7679 int fld_bit_len;
7680 int f;
7682 scoped_value_mark mark;
7684 /* Compute the number of fields in this record type that are going
7685 to be processed: unless keep_dynamic_fields, this includes only
7686 fields whose position and length are static will be processed. */
7687 if (keep_dynamic_fields)
7688 nfields = type->num_fields ();
7689 else
7691 nfields = 0;
7692 while (nfields < type->num_fields ()
7693 && !ada_is_variant_part (type, nfields)
7694 && !is_dynamic_field (type, nfields))
7695 nfields++;
7698 rtype = type_allocator (type).new_type ();
7699 rtype->set_code (TYPE_CODE_STRUCT);
7700 INIT_NONE_SPECIFIC (rtype);
7701 rtype->alloc_fields (nfields);
7702 rtype->set_name (ada_type_name (type));
7703 rtype->set_is_fixed_instance (true);
7705 off = 0;
7706 bit_len = 0;
7707 variant_field = -1;
7709 for (f = 0; f < nfields; f += 1)
7711 off = align_up (off, field_alignment (type, f))
7712 + type->field (f).loc_bitpos ();
7713 rtype->field (f).set_loc_bitpos (off);
7714 rtype->field (f).set_bitsize (0);
7716 if (ada_is_variant_part (type, f))
7718 variant_field = f;
7719 fld_bit_len = 0;
7721 else if (is_dynamic_field (type, f))
7723 const gdb_byte *field_valaddr = valaddr;
7724 CORE_ADDR field_address = address;
7725 struct type *field_type = type->field (f).type ()->target_type ();
7727 if (dval0 == NULL)
7729 /* Using plain value_from_contents_and_address here
7730 causes problems because we will end up trying to
7731 resolve a type that is currently being
7732 constructed. */
7733 dval = value_from_contents_and_address_unresolved (rtype,
7734 valaddr,
7735 address);
7736 rtype = dval->type ();
7738 else
7739 dval = dval0;
7741 /* If the type referenced by this field is an aligner type, we need
7742 to unwrap that aligner type, because its size might not be set.
7743 Keeping the aligner type would cause us to compute the wrong
7744 size for this field, impacting the offset of the all the fields
7745 that follow this one. */
7746 if (ada_is_aligner_type (field_type))
7748 long field_offset = type->field (f).loc_bitpos ();
7750 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7751 field_address = cond_offset_target (field_address, field_offset);
7752 field_type = ada_aligned_type (field_type);
7755 field_valaddr = cond_offset_host (field_valaddr,
7756 off / TARGET_CHAR_BIT);
7757 field_address = cond_offset_target (field_address,
7758 off / TARGET_CHAR_BIT);
7760 /* Get the fixed type of the field. Note that, in this case,
7761 we do not want to get the real type out of the tag: if
7762 the current field is the parent part of a tagged record,
7763 we will get the tag of the object. Clearly wrong: the real
7764 type of the parent is not the real type of the child. We
7765 would end up in an infinite loop. */
7766 field_type = ada_get_base_type (field_type);
7767 field_type = ada_to_fixed_type (field_type, field_valaddr,
7768 field_address, dval, 0);
7770 rtype->field (f).set_type (field_type);
7771 rtype->field (f).set_name (type->field (f).name ());
7772 /* The multiplication can potentially overflow. But because
7773 the field length has been size-checked just above, and
7774 assuming that the maximum size is a reasonable value,
7775 an overflow should not happen in practice. So rather than
7776 adding overflow recovery code to this already complex code,
7777 we just assume that it's not going to happen. */
7778 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7780 else
7782 /* Note: If this field's type is a typedef, it is important
7783 to preserve the typedef layer.
7785 Otherwise, we might be transforming a typedef to a fat
7786 pointer (encoding a pointer to an unconstrained array),
7787 into a basic fat pointer (encoding an unconstrained
7788 array). As both types are implemented using the same
7789 structure, the typedef is the only clue which allows us
7790 to distinguish between the two options. Stripping it
7791 would prevent us from printing this field appropriately. */
7792 rtype->field (f).set_type (type->field (f).type ());
7793 rtype->field (f).set_name (type->field (f).name ());
7794 if (type->field (f).bitsize () > 0)
7796 fld_bit_len = type->field (f).bitsize ();
7797 rtype->field (f).set_bitsize (fld_bit_len);
7799 else
7801 struct type *field_type = type->field (f).type ();
7803 /* We need to be careful of typedefs when computing
7804 the length of our field. If this is a typedef,
7805 get the length of the target type, not the length
7806 of the typedef. */
7807 if (field_type->code () == TYPE_CODE_TYPEDEF)
7808 field_type = ada_typedef_target_type (field_type);
7810 fld_bit_len =
7811 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7814 if (off + fld_bit_len > bit_len)
7815 bit_len = off + fld_bit_len;
7816 off += fld_bit_len;
7817 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7820 /* We handle the variant part, if any, at the end because of certain
7821 odd cases in which it is re-ordered so as NOT to be the last field of
7822 the record. This can happen in the presence of representation
7823 clauses. */
7824 if (variant_field >= 0)
7826 struct type *branch_type;
7828 off = rtype->field (variant_field).loc_bitpos ();
7830 if (dval0 == NULL)
7832 /* Using plain value_from_contents_and_address here causes
7833 problems because we will end up trying to resolve a type
7834 that is currently being constructed. */
7835 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7836 address);
7837 rtype = dval->type ();
7839 else
7840 dval = dval0;
7842 branch_type =
7843 to_fixed_variant_branch_type
7844 (type->field (variant_field).type (),
7845 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7846 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7847 if (branch_type == NULL)
7849 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7850 rtype->field (f - 1) = rtype->field (f);
7851 rtype->set_num_fields (rtype->num_fields () - 1);
7853 else
7855 rtype->field (variant_field).set_type (branch_type);
7856 rtype->field (variant_field).set_name ("S");
7857 fld_bit_len =
7858 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
7859 if (off + fld_bit_len > bit_len)
7860 bit_len = off + fld_bit_len;
7862 rtype->set_length
7863 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7867 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7868 should contain the alignment of that record, which should be a strictly
7869 positive value. If null or negative, then something is wrong, most
7870 probably in the debug info. In that case, we don't round up the size
7871 of the resulting type. If this record is not part of another structure,
7872 the current RTYPE length might be good enough for our purposes. */
7873 if (type->length () <= 0)
7875 if (rtype->name ())
7876 warning (_("Invalid type size for `%s' detected: %s."),
7877 rtype->name (), pulongest (type->length ()));
7878 else
7879 warning (_("Invalid type size for <unnamed> detected: %s."),
7880 pulongest (type->length ()));
7882 else
7883 rtype->set_length (align_up (rtype->length (), type->length ()));
7885 return rtype;
7888 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7889 of 1. */
7891 static struct type *
7892 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7893 CORE_ADDR address, struct value *dval0)
7895 return ada_template_to_fixed_record_type_1 (type, valaddr,
7896 address, dval0, 1);
7899 /* An ordinary record type in which ___XVL-convention fields and
7900 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7901 static approximations, containing all possible fields. Uses
7902 no runtime values. Useless for use in values, but that's OK,
7903 since the results are used only for type determinations. Works on both
7904 structs and unions. Representation note: to save space, we memorize
7905 the result of this function in the type::target_type of the
7906 template type. */
7908 static struct type *
7909 template_to_static_fixed_type (struct type *type0)
7911 struct type *type;
7912 int nfields;
7913 int f;
7915 /* No need no do anything if the input type is already fixed. */
7916 if (type0->is_fixed_instance ())
7917 return type0;
7919 /* Likewise if we already have computed the static approximation. */
7920 if (type0->target_type () != NULL)
7921 return type0->target_type ();
7923 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
7924 type = type0;
7925 nfields = type0->num_fields ();
7927 /* Whether or not we cloned TYPE0, cache the result so that we don't do
7928 recompute all over next time. */
7929 type0->set_target_type (type);
7931 for (f = 0; f < nfields; f += 1)
7933 struct type *field_type = type0->field (f).type ();
7934 struct type *new_type;
7936 if (is_dynamic_field (type0, f))
7938 field_type = ada_check_typedef (field_type);
7939 new_type = to_static_fixed_type (field_type->target_type ());
7941 else
7942 new_type = static_unwrap_type (field_type);
7944 if (new_type != field_type)
7946 /* Clone TYPE0 only the first time we get a new field type. */
7947 if (type == type0)
7949 type = type_allocator (type0).new_type ();
7950 type0->set_target_type (type);
7951 type->set_code (type0->code ());
7952 INIT_NONE_SPECIFIC (type);
7954 type->copy_fields (type0);
7956 type->set_name (ada_type_name (type0));
7957 type->set_is_fixed_instance (true);
7958 type->set_length (0);
7960 type->field (f).set_type (new_type);
7961 type->field (f).set_name (type0->field (f).name ());
7965 return type;
7968 /* Given an object of type TYPE whose contents are at VALADDR and
7969 whose address in memory is ADDRESS, returns a revision of TYPE,
7970 which should be a non-dynamic-sized record, in which the variant
7971 part, if any, is replaced with the appropriate branch. Looks
7972 for discriminant values in DVAL0, which can be NULL if the record
7973 contains the necessary discriminant values. */
7975 static struct type *
7976 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
7977 CORE_ADDR address, struct value *dval0)
7979 struct value *dval;
7980 struct type *rtype;
7981 struct type *branch_type;
7982 int nfields = type->num_fields ();
7983 int variant_field = variant_field_index (type);
7985 if (variant_field == -1)
7986 return type;
7988 scoped_value_mark mark;
7989 if (dval0 == NULL)
7991 dval = value_from_contents_and_address (type, valaddr, address);
7992 type = dval->type ();
7994 else
7995 dval = dval0;
7997 rtype = type_allocator (type).new_type ();
7998 rtype->set_code (TYPE_CODE_STRUCT);
7999 INIT_NONE_SPECIFIC (rtype);
8000 rtype->copy_fields (type);
8002 rtype->set_name (ada_type_name (type));
8003 rtype->set_is_fixed_instance (true);
8004 rtype->set_length (type->length ());
8006 branch_type = to_fixed_variant_branch_type
8007 (type->field (variant_field).type (),
8008 cond_offset_host (valaddr,
8009 type->field (variant_field).loc_bitpos ()
8010 / TARGET_CHAR_BIT),
8011 cond_offset_target (address,
8012 type->field (variant_field).loc_bitpos ()
8013 / TARGET_CHAR_BIT), dval);
8014 if (branch_type == NULL)
8016 int f;
8018 for (f = variant_field + 1; f < nfields; f += 1)
8019 rtype->field (f - 1) = rtype->field (f);
8020 rtype->set_num_fields (rtype->num_fields () - 1);
8022 else
8024 rtype->field (variant_field).set_type (branch_type);
8025 rtype->field (variant_field).set_name ("S");
8026 rtype->field (variant_field).set_bitsize (0);
8027 rtype->set_length (rtype->length () + branch_type->length ());
8030 rtype->set_length (rtype->length ()
8031 - type->field (variant_field).type ()->length ());
8033 return rtype;
8036 /* An ordinary record type (with fixed-length fields) that describes
8037 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8038 beginning of this section]. Any necessary discriminants' values
8039 should be in DVAL, a record value; it may be NULL if the object
8040 at ADDR itself contains any necessary discriminant values.
8041 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8042 values from the record are needed. Except in the case that DVAL,
8043 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8044 unchecked) is replaced by a particular branch of the variant.
8046 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8047 is questionable and may be removed. It can arise during the
8048 processing of an unconstrained-array-of-record type where all the
8049 variant branches have exactly the same size. This is because in
8050 such cases, the compiler does not bother to use the XVS convention
8051 when encoding the record. I am currently dubious of this
8052 shortcut and suspect the compiler should be altered. FIXME. */
8054 static struct type *
8055 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8056 CORE_ADDR address, struct value *dval)
8058 struct type *templ_type;
8060 if (type0->is_fixed_instance ())
8061 return type0;
8063 templ_type = dynamic_template_type (type0);
8065 if (templ_type != NULL)
8066 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8067 else if (variant_field_index (type0) >= 0)
8069 if (dval == NULL && valaddr == NULL && address == 0)
8070 return type0;
8071 return to_record_with_fixed_variant_part (type0, valaddr, address,
8072 dval);
8074 else
8076 type0->set_is_fixed_instance (true);
8077 return type0;
8082 /* An ordinary record type (with fixed-length fields) that describes
8083 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8084 union type. Any necessary discriminants' values should be in DVAL,
8085 a record value. That is, this routine selects the appropriate
8086 branch of the union at ADDR according to the discriminant value
8087 indicated in the union's type name. Returns VAR_TYPE0 itself if
8088 it represents a variant subject to a pragma Unchecked_Union. */
8090 static struct type *
8091 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8092 CORE_ADDR address, struct value *dval)
8094 int which;
8095 struct type *templ_type;
8096 struct type *var_type;
8098 if (var_type0->code () == TYPE_CODE_PTR)
8099 var_type = var_type0->target_type ();
8100 else
8101 var_type = var_type0;
8103 templ_type = ada_find_parallel_type (var_type, "___XVU");
8105 if (templ_type != NULL)
8106 var_type = templ_type;
8108 if (is_unchecked_variant (var_type, dval->type ()))
8109 return var_type0;
8110 which = ada_which_variant_applies (var_type, dval);
8112 if (which < 0)
8113 return empty_record (var_type);
8114 else if (is_dynamic_field (var_type, which))
8115 return to_fixed_record_type
8116 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8117 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8118 return
8119 to_fixed_record_type
8120 (var_type->field (which).type (), valaddr, address, dval);
8121 else
8122 return var_type->field (which).type ();
8125 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8126 ENCODING_TYPE, a type following the GNAT conventions for discrete
8127 type encodings, only carries redundant information. */
8129 static int
8130 ada_is_redundant_range_encoding (struct type *range_type,
8131 struct type *encoding_type)
8133 const char *bounds_str;
8134 int n;
8135 LONGEST lo, hi;
8137 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8139 if (get_base_type (range_type)->code ()
8140 != get_base_type (encoding_type)->code ())
8142 /* The compiler probably used a simple base type to describe
8143 the range type instead of the range's actual base type,
8144 expecting us to get the real base type from the encoding
8145 anyway. In this situation, the encoding cannot be ignored
8146 as redundant. */
8147 return 0;
8150 if (is_dynamic_type (range_type))
8151 return 0;
8153 if (encoding_type->name () == NULL)
8154 return 0;
8156 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8157 if (bounds_str == NULL)
8158 return 0;
8160 n = 8; /* Skip "___XDLU_". */
8161 if (!ada_scan_number (bounds_str, n, &lo, &n))
8162 return 0;
8163 if (range_type->bounds ()->low.const_val () != lo)
8164 return 0;
8166 n += 2; /* Skip the "__" separator between the two bounds. */
8167 if (!ada_scan_number (bounds_str, n, &hi, &n))
8168 return 0;
8169 if (range_type->bounds ()->high.const_val () != hi)
8170 return 0;
8172 return 1;
8175 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8176 a type following the GNAT encoding for describing array type
8177 indices, only carries redundant information. */
8179 static int
8180 ada_is_redundant_index_type_desc (struct type *array_type,
8181 struct type *desc_type)
8183 struct type *this_layer = check_typedef (array_type);
8184 int i;
8186 for (i = 0; i < desc_type->num_fields (); i++)
8188 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8189 desc_type->field (i).type ()))
8190 return 0;
8191 this_layer = check_typedef (this_layer->target_type ());
8194 return 1;
8197 /* Assuming that TYPE0 is an array type describing the type of a value
8198 at ADDR, and that DVAL describes a record containing any
8199 discriminants used in TYPE0, returns a type for the value that
8200 contains no dynamic components (that is, no components whose sizes
8201 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8202 true, gives an error message if the resulting type's size is over
8203 varsize_limit. */
8205 static struct type *
8206 to_fixed_array_type (struct type *type0, struct value *dval,
8207 int ignore_too_big)
8209 struct type *index_type_desc;
8210 struct type *result;
8211 int constrained_packed_array_p;
8212 static const char *xa_suffix = "___XA";
8214 type0 = ada_check_typedef (type0);
8215 if (type0->is_fixed_instance ())
8216 return type0;
8218 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8219 if (constrained_packed_array_p)
8221 type0 = decode_constrained_packed_array_type (type0);
8222 if (type0 == nullptr)
8223 error (_("could not decode constrained packed array type"));
8226 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8228 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8229 encoding suffixed with 'P' may still be generated. If so,
8230 it should be used to find the XA type. */
8232 if (index_type_desc == NULL)
8234 const char *type_name = ada_type_name (type0);
8236 if (type_name != NULL)
8238 const int len = strlen (type_name);
8239 char *name = (char *) alloca (len + strlen (xa_suffix));
8241 if (type_name[len - 1] == 'P')
8243 strcpy (name, type_name);
8244 strcpy (name + len - 1, xa_suffix);
8245 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8250 ada_fixup_array_indexes_type (index_type_desc);
8251 if (index_type_desc != NULL
8252 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8254 /* Ignore this ___XA parallel type, as it does not bring any
8255 useful information. This allows us to avoid creating fixed
8256 versions of the array's index types, which would be identical
8257 to the original ones. This, in turn, can also help avoid
8258 the creation of fixed versions of the array itself. */
8259 index_type_desc = NULL;
8262 if (index_type_desc == NULL)
8264 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8266 /* NOTE: elt_type---the fixed version of elt_type0---should never
8267 depend on the contents of the array in properly constructed
8268 debugging data. */
8269 /* Create a fixed version of the array element type.
8270 We're not providing the address of an element here,
8271 and thus the actual object value cannot be inspected to do
8272 the conversion. This should not be a problem, since arrays of
8273 unconstrained objects are not allowed. In particular, all
8274 the elements of an array of a tagged type should all be of
8275 the same type specified in the debugging info. No need to
8276 consult the object tag. */
8277 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8279 /* Make sure we always create a new array type when dealing with
8280 packed array types, since we're going to fix-up the array
8281 type length and element bitsize a little further down. */
8282 if (elt_type0 == elt_type && !constrained_packed_array_p)
8283 result = type0;
8284 else
8286 type_allocator alloc (type0);
8287 result = create_array_type (alloc, elt_type, type0->index_type ());
8290 else
8292 int i;
8293 struct type *elt_type0;
8295 elt_type0 = type0;
8296 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8297 elt_type0 = elt_type0->target_type ();
8299 /* NOTE: result---the fixed version of elt_type0---should never
8300 depend on the contents of the array in properly constructed
8301 debugging data. */
8302 /* Create a fixed version of the array element type.
8303 We're not providing the address of an element here,
8304 and thus the actual object value cannot be inspected to do
8305 the conversion. This should not be a problem, since arrays of
8306 unconstrained objects are not allowed. In particular, all
8307 the elements of an array of a tagged type should all be of
8308 the same type specified in the debugging info. No need to
8309 consult the object tag. */
8310 result =
8311 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8313 elt_type0 = type0;
8314 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8316 struct type *range_type =
8317 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8319 type_allocator alloc (elt_type0);
8320 result = create_array_type (alloc, result, range_type);
8321 elt_type0 = elt_type0->target_type ();
8325 /* We want to preserve the type name. This can be useful when
8326 trying to get the type name of a value that has already been
8327 printed (for instance, if the user did "print VAR; whatis $". */
8328 result->set_name (type0->name ());
8330 if (constrained_packed_array_p)
8332 /* So far, the resulting type has been created as if the original
8333 type was a regular (non-packed) array type. As a result, the
8334 bitsize of the array elements needs to be set again, and the array
8335 length needs to be recomputed based on that bitsize. */
8336 int len = result->length () / result->target_type ()->length ();
8337 int elt_bitsize = type0->field (0).bitsize ();
8339 result->field (0).set_bitsize (elt_bitsize);
8340 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8341 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8342 result->set_length (result->length () + 1);
8345 result->set_is_fixed_instance (true);
8346 return result;
8350 /* A standard type (containing no dynamically sized components)
8351 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8352 DVAL describes a record containing any discriminants used in TYPE0,
8353 and may be NULL if there are none, or if the object of type TYPE at
8354 ADDRESS or in VALADDR contains these discriminants.
8356 If CHECK_TAG is not null, in the case of tagged types, this function
8357 attempts to locate the object's tag and use it to compute the actual
8358 type. However, when ADDRESS is null, we cannot use it to determine the
8359 location of the tag, and therefore compute the tagged type's actual type.
8360 So we return the tagged type without consulting the tag. */
8362 static struct type *
8363 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8364 CORE_ADDR address, struct value *dval, int check_tag)
8366 type = ada_check_typedef (type);
8368 /* Only un-fixed types need to be handled here. */
8369 if (!HAVE_GNAT_AUX_INFO (type))
8370 return type;
8372 switch (type->code ())
8374 default:
8375 return type;
8376 case TYPE_CODE_STRUCT:
8378 struct type *static_type = to_static_fixed_type (type);
8379 struct type *fixed_record_type =
8380 to_fixed_record_type (type, valaddr, address, NULL);
8382 /* If STATIC_TYPE is a tagged type and we know the object's address,
8383 then we can determine its tag, and compute the object's actual
8384 type from there. Note that we have to use the fixed record
8385 type (the parent part of the record may have dynamic fields
8386 and the way the location of _tag is expressed may depend on
8387 them). */
8389 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8391 struct value *tag =
8392 value_tag_from_contents_and_address
8393 (fixed_record_type,
8394 valaddr,
8395 address);
8396 struct type *real_type = type_from_tag (tag);
8397 struct value *obj =
8398 value_from_contents_and_address (fixed_record_type,
8399 valaddr,
8400 address);
8401 fixed_record_type = obj->type ();
8402 if (real_type != NULL)
8403 return to_fixed_record_type
8404 (real_type, NULL,
8405 ada_tag_value_at_base_address (obj)->address (), NULL);
8408 /* Check to see if there is a parallel ___XVZ variable.
8409 If there is, then it provides the actual size of our type. */
8410 else if (ada_type_name (fixed_record_type) != NULL)
8412 const char *name = ada_type_name (fixed_record_type);
8413 char *xvz_name
8414 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8415 bool xvz_found = false;
8416 LONGEST size;
8418 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8421 xvz_found = get_int_var_value (xvz_name, size);
8423 catch (const gdb_exception_error &except)
8425 /* We found the variable, but somehow failed to read
8426 its value. Rethrow the same error, but with a little
8427 bit more information, to help the user understand
8428 what went wrong (Eg: the variable might have been
8429 optimized out). */
8430 throw_error (except.error,
8431 _("unable to read value of %s (%s)"),
8432 xvz_name, except.what ());
8435 if (xvz_found && fixed_record_type->length () != size)
8437 fixed_record_type = copy_type (fixed_record_type);
8438 fixed_record_type->set_length (size);
8440 /* The FIXED_RECORD_TYPE may have be a stub. We have
8441 observed this when the debugging info is STABS, and
8442 apparently it is something that is hard to fix.
8444 In practice, we don't need the actual type definition
8445 at all, because the presence of the XVZ variable allows us
8446 to assume that there must be a XVS type as well, which we
8447 should be able to use later, when we need the actual type
8448 definition.
8450 In the meantime, pretend that the "fixed" type we are
8451 returning is NOT a stub, because this can cause trouble
8452 when using this type to create new types targeting it.
8453 Indeed, the associated creation routines often check
8454 whether the target type is a stub and will try to replace
8455 it, thus using a type with the wrong size. This, in turn,
8456 might cause the new type to have the wrong size too.
8457 Consider the case of an array, for instance, where the size
8458 of the array is computed from the number of elements in
8459 our array multiplied by the size of its element. */
8460 fixed_record_type->set_is_stub (false);
8463 return fixed_record_type;
8465 case TYPE_CODE_ARRAY:
8466 return to_fixed_array_type (type, dval, 1);
8467 case TYPE_CODE_UNION:
8468 if (dval == NULL)
8469 return type;
8470 else
8471 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8475 /* The same as ada_to_fixed_type_1, except that it preserves the type
8476 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8478 The typedef layer needs be preserved in order to differentiate between
8479 arrays and array pointers when both types are implemented using the same
8480 fat pointer. In the array pointer case, the pointer is encoded as
8481 a typedef of the pointer type. For instance, considering:
8483 type String_Access is access String;
8484 S1 : String_Access := null;
8486 To the debugger, S1 is defined as a typedef of type String. But
8487 to the user, it is a pointer. So if the user tries to print S1,
8488 we should not dereference the array, but print the array address
8489 instead.
8491 If we didn't preserve the typedef layer, we would lose the fact that
8492 the type is to be presented as a pointer (needs de-reference before
8493 being printed). And we would also use the source-level type name. */
8495 struct type *
8496 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8497 CORE_ADDR address, struct value *dval, int check_tag)
8500 struct type *fixed_type =
8501 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8503 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8504 then preserve the typedef layer.
8506 Implementation note: We can only check the main-type portion of
8507 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8508 from TYPE now returns a type that has the same instance flags
8509 as TYPE. For instance, if TYPE is a "typedef const", and its
8510 target type is a "struct", then the typedef elimination will return
8511 a "const" version of the target type. See check_typedef for more
8512 details about how the typedef layer elimination is done.
8514 brobecker/2010-11-19: It seems to me that the only case where it is
8515 useful to preserve the typedef layer is when dealing with fat pointers.
8516 Perhaps, we could add a check for that and preserve the typedef layer
8517 only in that situation. But this seems unnecessary so far, probably
8518 because we call check_typedef/ada_check_typedef pretty much everywhere.
8520 if (type->code () == TYPE_CODE_TYPEDEF
8521 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8522 == TYPE_MAIN_TYPE (fixed_type)))
8523 return type;
8525 return fixed_type;
8528 /* A standard (static-sized) type corresponding as well as possible to
8529 TYPE0, but based on no runtime data. */
8531 static struct type *
8532 to_static_fixed_type (struct type *type0)
8534 struct type *type;
8536 if (type0 == NULL)
8537 return NULL;
8539 if (type0->is_fixed_instance ())
8540 return type0;
8542 type0 = ada_check_typedef (type0);
8544 switch (type0->code ())
8546 default:
8547 return type0;
8548 case TYPE_CODE_STRUCT:
8549 type = dynamic_template_type (type0);
8550 if (type != NULL)
8551 return template_to_static_fixed_type (type);
8552 else
8553 return template_to_static_fixed_type (type0);
8554 case TYPE_CODE_UNION:
8555 type = ada_find_parallel_type (type0, "___XVU");
8556 if (type != NULL)
8557 return template_to_static_fixed_type (type);
8558 else
8559 return template_to_static_fixed_type (type0);
8563 /* A static approximation of TYPE with all type wrappers removed. */
8565 static struct type *
8566 static_unwrap_type (struct type *type)
8568 if (ada_is_aligner_type (type))
8570 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8571 if (ada_type_name (type1) == NULL)
8572 type1->set_name (ada_type_name (type));
8574 return static_unwrap_type (type1);
8576 else
8578 struct type *raw_real_type = ada_get_base_type (type);
8580 if (raw_real_type == type)
8581 return type;
8582 else
8583 return to_static_fixed_type (raw_real_type);
8587 /* In some cases, incomplete and private types require
8588 cross-references that are not resolved as records (for example,
8589 type Foo;
8590 type FooP is access Foo;
8591 V: FooP;
8592 type Foo is array ...;
8593 ). In these cases, since there is no mechanism for producing
8594 cross-references to such types, we instead substitute for FooP a
8595 stub enumeration type that is nowhere resolved, and whose tag is
8596 the name of the actual type. Call these types "non-record stubs". */
8598 /* A type equivalent to TYPE that is not a non-record stub, if one
8599 exists, otherwise TYPE. */
8601 struct type *
8602 ada_check_typedef (struct type *type)
8604 if (type == NULL)
8605 return NULL;
8607 /* If our type is an access to an unconstrained array, which is encoded
8608 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8609 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8610 what allows us to distinguish between fat pointers that represent
8611 array types, and fat pointers that represent array access types
8612 (in both cases, the compiler implements them as fat pointers). */
8613 if (ada_is_access_to_unconstrained_array (type))
8614 return type;
8616 type = check_typedef (type);
8617 if (type == NULL || type->code () != TYPE_CODE_ENUM
8618 || !type->is_stub ()
8619 || type->name () == NULL)
8620 return type;
8621 else
8623 const char *name = type->name ();
8624 struct type *type1 = ada_find_any_type (name);
8626 if (type1 == NULL)
8627 return type;
8629 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8630 stubs pointing to arrays, as we don't create symbols for array
8631 types, only for the typedef-to-array types). If that's the case,
8632 strip the typedef layer. */
8633 if (type1->code () == TYPE_CODE_TYPEDEF)
8634 type1 = ada_check_typedef (type1);
8636 return type1;
8640 /* A value representing the data at VALADDR/ADDRESS as described by
8641 type TYPE0, but with a standard (static-sized) type that correctly
8642 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8643 type, then return VAL0 [this feature is simply to avoid redundant
8644 creation of struct values]. */
8646 static struct value *
8647 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8648 struct value *val0)
8650 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8652 if (type == type0 && val0 != NULL)
8653 return val0;
8655 if (val0->lval () != lval_memory)
8657 /* Our value does not live in memory; it could be a convenience
8658 variable, for instance. Create a not_lval value using val0's
8659 contents. */
8660 return value_from_contents (type, val0->contents ().data ());
8663 return value_from_contents_and_address (type, 0, address);
8666 /* A value representing VAL, but with a standard (static-sized) type
8667 that correctly describes it. Does not necessarily create a new
8668 value. */
8670 struct value *
8671 ada_to_fixed_value (struct value *val)
8673 val = unwrap_value (val);
8674 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8675 return val;
8679 /* Attributes */
8681 /* Evaluate the 'POS attribute applied to ARG. */
8683 static LONGEST
8684 pos_atr (struct value *arg)
8686 struct value *val = coerce_ref (arg);
8687 struct type *type = val->type ();
8689 if (!discrete_type_p (type))
8690 error (_("'POS only defined on discrete types"));
8692 std::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8693 if (!result.has_value ())
8694 error (_("enumeration value is invalid: can't find 'POS"));
8696 return *result;
8699 struct value *
8700 ada_pos_atr (struct type *expect_type,
8701 struct expression *exp,
8702 enum noside noside, enum exp_opcode op,
8703 struct value *arg)
8705 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8706 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8707 return value::zero (type, not_lval);
8708 return value_from_longest (type, pos_atr (arg));
8711 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8713 static struct value *
8714 val_atr (struct type *type, LONGEST val)
8716 gdb_assert (discrete_type_p (type));
8717 if (type->code () == TYPE_CODE_RANGE)
8718 type = type->target_type ();
8719 if (type->code () == TYPE_CODE_ENUM)
8721 if (val < 0 || val >= type->num_fields ())
8722 error (_("argument to 'VAL out of range"));
8723 val = type->field (val).loc_enumval ();
8725 return value_from_longest (type, val);
8728 struct value *
8729 ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8730 struct value *arg)
8732 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8733 return value::zero (type, not_lval);
8735 if (!discrete_type_p (type))
8736 error (_("'VAL only defined on discrete types"));
8737 if (!integer_type_p (arg->type ()))
8738 error (_("'VAL requires integral argument"));
8740 return val_atr (type, value_as_long (arg));
8743 /* Implementation of the enum_rep attribute. */
8744 struct value *
8745 ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8746 struct value *arg)
8748 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8749 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8750 return value::zero (inttype, not_lval);
8752 if (type->code () == TYPE_CODE_RANGE)
8753 type = type->target_type ();
8754 if (type->code () != TYPE_CODE_ENUM)
8755 error (_("'Enum_Rep only defined on enum types"));
8756 if (!types_equal (type, arg->type ()))
8757 error (_("'Enum_Rep requires argument to have same type as enum"));
8759 return value_cast (inttype, arg);
8762 /* Implementation of the enum_val attribute. */
8763 struct value *
8764 ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8765 struct value *arg)
8767 struct type *original_type = type;
8768 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8769 return value::zero (original_type, not_lval);
8771 if (type->code () == TYPE_CODE_RANGE)
8772 type = type->target_type ();
8773 if (type->code () != TYPE_CODE_ENUM)
8774 error (_("'Enum_Val only defined on enum types"));
8775 if (!integer_type_p (arg->type ()))
8776 error (_("'Enum_Val requires integral argument"));
8778 LONGEST value = value_as_long (arg);
8779 for (int i = 0; i < type->num_fields (); ++i)
8781 if (type->field (i).loc_enumval () == value)
8782 return value_from_longest (original_type, value);
8785 error (_("value %s not found in enum"), plongest (value));
8790 /* Evaluation */
8792 /* True if TYPE appears to be an Ada character type.
8793 [At the moment, this is true only for Character and Wide_Character;
8794 It is a heuristic test that could stand improvement]. */
8796 bool
8797 ada_is_character_type (struct type *type)
8799 const char *name;
8801 /* If the type code says it's a character, then assume it really is,
8802 and don't check any further. */
8803 if (type->code () == TYPE_CODE_CHAR)
8804 return true;
8806 /* Otherwise, assume it's a character type iff it is a discrete type
8807 with a known character type name. */
8808 name = ada_type_name (type);
8809 return (name != NULL
8810 && (type->code () == TYPE_CODE_INT
8811 || type->code () == TYPE_CODE_RANGE)
8812 && (strcmp (name, "character") == 0
8813 || strcmp (name, "wide_character") == 0
8814 || strcmp (name, "wide_wide_character") == 0
8815 || strcmp (name, "unsigned char") == 0));
8818 /* True if TYPE appears to be an Ada string type. */
8820 bool
8821 ada_is_string_type (struct type *type)
8823 type = ada_check_typedef (type);
8824 if (type != NULL
8825 && type->code () != TYPE_CODE_PTR
8826 && (ada_is_simple_array_type (type)
8827 || ada_is_array_descriptor_type (type))
8828 && ada_array_arity (type) == 1)
8830 struct type *elttype = ada_array_element_type (type, 1);
8832 return ada_is_character_type (elttype);
8834 else
8835 return false;
8838 /* The compiler sometimes provides a parallel XVS type for a given
8839 PAD type. Normally, it is safe to follow the PAD type directly,
8840 but older versions of the compiler have a bug that causes the offset
8841 of its "F" field to be wrong. Following that field in that case
8842 would lead to incorrect results, but this can be worked around
8843 by ignoring the PAD type and using the associated XVS type instead.
8845 Set to True if the debugger should trust the contents of PAD types.
8846 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8847 static bool trust_pad_over_xvs = true;
8849 /* True if TYPE is a struct type introduced by the compiler to force the
8850 alignment of a value. Such types have a single field with a
8851 distinctive name. */
8854 ada_is_aligner_type (struct type *type)
8856 type = ada_check_typedef (type);
8858 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8859 return 0;
8861 return (type->code () == TYPE_CODE_STRUCT
8862 && type->num_fields () == 1
8863 && strcmp (type->field (0).name (), "F") == 0);
8866 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8867 the parallel type. */
8869 struct type *
8870 ada_get_base_type (struct type *raw_type)
8872 struct type *real_type_namer;
8873 struct type *raw_real_type;
8875 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8876 return raw_type;
8878 if (ada_is_aligner_type (raw_type))
8879 /* The encoding specifies that we should always use the aligner type.
8880 So, even if this aligner type has an associated XVS type, we should
8881 simply ignore it.
8883 According to the compiler gurus, an XVS type parallel to an aligner
8884 type may exist because of a stabs limitation. In stabs, aligner
8885 types are empty because the field has a variable-sized type, and
8886 thus cannot actually be used as an aligner type. As a result,
8887 we need the associated parallel XVS type to decode the type.
8888 Since the policy in the compiler is to not change the internal
8889 representation based on the debugging info format, we sometimes
8890 end up having a redundant XVS type parallel to the aligner type. */
8891 return raw_type;
8893 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8894 if (real_type_namer == NULL
8895 || real_type_namer->code () != TYPE_CODE_STRUCT
8896 || real_type_namer->num_fields () != 1)
8897 return raw_type;
8899 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8901 /* This is an older encoding form where the base type needs to be
8902 looked up by name. We prefer the newer encoding because it is
8903 more efficient. */
8904 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
8905 if (raw_real_type == NULL)
8906 return raw_type;
8907 else
8908 return raw_real_type;
8911 /* The field in our XVS type is a reference to the base type. */
8912 return real_type_namer->field (0).type ()->target_type ();
8915 /* The type of value designated by TYPE, with all aligners removed. */
8917 struct type *
8918 ada_aligned_type (struct type *type)
8920 if (ada_is_aligner_type (type))
8921 return ada_aligned_type (type->field (0).type ());
8922 else
8923 return ada_get_base_type (type);
8927 /* The address of the aligned value in an object at address VALADDR
8928 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
8930 const gdb_byte *
8931 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8933 if (ada_is_aligner_type (type))
8934 return ada_aligned_value_addr
8935 (type->field (0).type (),
8936 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
8937 else
8938 return valaddr;
8943 /* The printed representation of an enumeration literal with encoded
8944 name NAME. The value is good to the next call of ada_enum_name. */
8945 const char *
8946 ada_enum_name (const char *name)
8948 static std::string storage;
8949 const char *tmp;
8951 /* First, unqualify the enumeration name:
8952 1. Search for the last '.' character. If we find one, then skip
8953 all the preceding characters, the unqualified name starts
8954 right after that dot.
8955 2. Otherwise, we may be debugging on a target where the compiler
8956 translates dots into "__". Search forward for double underscores,
8957 but stop searching when we hit an overloading suffix, which is
8958 of the form "__" followed by digits. */
8960 tmp = strrchr (name, '.');
8961 if (tmp != NULL)
8962 name = tmp + 1;
8963 else
8965 while ((tmp = strstr (name, "__")) != NULL)
8967 if (isdigit (tmp[2]))
8968 break;
8969 else
8970 name = tmp + 2;
8974 if (name[0] == 'Q')
8976 int v;
8978 if (name[1] == 'U' || name[1] == 'W')
8980 int offset = 2;
8981 if (name[1] == 'W' && name[2] == 'W')
8983 /* Also handle the QWW case. */
8984 ++offset;
8986 if (sscanf (name + offset, "%x", &v) != 1)
8987 return name;
8989 else if (((name[1] >= '0' && name[1] <= '9')
8990 || (name[1] >= 'a' && name[1] <= 'z'))
8991 && name[2] == '\0')
8993 storage = string_printf ("'%c'", name[1]);
8994 return storage.c_str ();
8996 else
8997 return name;
8999 if (isascii (v) && isprint (v))
9000 storage = string_printf ("'%c'", v);
9001 else if (name[1] == 'U')
9002 storage = string_printf ("'[\"%02x\"]'", v);
9003 else if (name[2] != 'W')
9004 storage = string_printf ("'[\"%04x\"]'", v);
9005 else
9006 storage = string_printf ("'[\"%06x\"]'", v);
9008 return storage.c_str ();
9010 else
9012 tmp = strstr (name, "__");
9013 if (tmp == NULL)
9014 tmp = strstr (name, "$");
9015 if (tmp != NULL)
9017 storage = std::string (name, tmp - name);
9018 return storage.c_str ();
9021 return name;
9025 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9026 there is no parallel type, return nullptr. */
9028 static struct type *
9029 find_base_type (struct type *type)
9031 struct type *raw_real_type
9032 = ada_check_typedef (ada_get_base_type (type));
9034 /* No parallel XVS or XVE type. */
9035 if (type == raw_real_type
9036 && ada_find_parallel_type (type, "___XVE") == nullptr)
9037 return nullptr;
9039 return raw_real_type;
9042 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9043 value it wraps. */
9045 static struct value *
9046 unwrap_value (struct value *val)
9048 struct type *type = ada_check_typedef (val->type ());
9050 if (ada_is_aligner_type (type))
9052 struct value *v = ada_value_struct_elt (val, "F", 0);
9053 struct type *val_type = ada_check_typedef (v->type ());
9055 if (ada_type_name (val_type) == NULL)
9056 val_type->set_name (ada_type_name (type));
9058 return unwrap_value (v);
9060 else
9062 struct type *raw_real_type = find_base_type (type);
9063 if (raw_real_type == nullptr)
9064 return val;
9066 return
9067 coerce_unspec_val_to_type
9068 (val, ada_to_fixed_type (raw_real_type, 0,
9069 val->address (),
9070 NULL, 1));
9074 /* Given two array types T1 and T2, return nonzero iff both arrays
9075 contain the same number of elements. */
9077 static int
9078 ada_same_array_size_p (struct type *t1, struct type *t2)
9080 LONGEST lo1, hi1, lo2, hi2;
9082 /* Get the array bounds in order to verify that the size of
9083 the two arrays match. */
9084 if (!get_array_bounds (t1, &lo1, &hi1)
9085 || !get_array_bounds (t2, &lo2, &hi2))
9086 error (_("unable to determine array bounds"));
9088 /* To make things easier for size comparison, normalize a bit
9089 the case of empty arrays by making sure that the difference
9090 between upper bound and lower bound is always -1. */
9091 if (lo1 > hi1)
9092 hi1 = lo1 - 1;
9093 if (lo2 > hi2)
9094 hi2 = lo2 - 1;
9096 return (hi1 - lo1 == hi2 - lo2);
9099 /* Assuming that VAL is an array of integrals, and TYPE represents
9100 an array with the same number of elements, but with wider integral
9101 elements, return an array "casted" to TYPE. In practice, this
9102 means that the returned array is built by casting each element
9103 of the original array into TYPE's (wider) element type. */
9105 static struct value *
9106 ada_promote_array_of_integrals (struct type *type, struct value *val)
9108 struct type *elt_type = type->target_type ();
9109 LONGEST lo, hi;
9110 LONGEST i;
9112 /* Verify that both val and type are arrays of scalars, and
9113 that the size of val's elements is smaller than the size
9114 of type's element. */
9115 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9116 gdb_assert (is_integral_type (type->target_type ()));
9117 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9118 gdb_assert (is_integral_type (val->type ()->target_type ()));
9119 gdb_assert (type->target_type ()->length ()
9120 > val->type ()->target_type ()->length ());
9122 if (!get_array_bounds (type, &lo, &hi))
9123 error (_("unable to determine array bounds"));
9125 value *res = value::allocate (type);
9126 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9128 /* Promote each array element. */
9129 for (i = 0; i < hi - lo + 1; i++)
9131 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9132 int elt_len = elt_type->length ();
9134 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9137 return res;
9140 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9141 return the converted value. */
9143 static struct value *
9144 coerce_for_assign (struct type *type, struct value *val)
9146 struct type *type2 = val->type ();
9148 if (type == type2)
9149 return val;
9151 type2 = ada_check_typedef (type2);
9152 type = ada_check_typedef (type);
9154 if (type2->code () == TYPE_CODE_PTR
9155 && type->code () == TYPE_CODE_ARRAY)
9157 val = ada_value_ind (val);
9158 type2 = val->type ();
9161 if (type2->code () == TYPE_CODE_ARRAY
9162 && type->code () == TYPE_CODE_ARRAY)
9164 if (!ada_same_array_size_p (type, type2))
9165 error (_("cannot assign arrays of different length"));
9167 if (is_integral_type (type->target_type ())
9168 && is_integral_type (type2->target_type ())
9169 && type2->target_type ()->length () < type->target_type ()->length ())
9171 /* Allow implicit promotion of the array elements to
9172 a wider type. */
9173 return ada_promote_array_of_integrals (type, val);
9176 if (type2->target_type ()->length () != type->target_type ()->length ())
9177 error (_("Incompatible types in assignment"));
9178 val->deprecated_set_type (type);
9180 return val;
9183 static struct value *
9184 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9186 struct type *type1, *type2;
9188 arg1 = coerce_ref (arg1);
9189 arg2 = coerce_ref (arg2);
9190 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9191 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9193 if (type1->code () != TYPE_CODE_INT
9194 || type2->code () != TYPE_CODE_INT)
9195 return value_binop (arg1, arg2, op);
9197 switch (op)
9199 case BINOP_MOD:
9200 case BINOP_DIV:
9201 case BINOP_REM:
9202 break;
9203 default:
9204 return value_binop (arg1, arg2, op);
9207 gdb_mpz v2 = value_as_mpz (arg2);
9208 if (v2.sgn () == 0)
9210 const char *name;
9211 if (op == BINOP_MOD)
9212 name = "mod";
9213 else if (op == BINOP_DIV)
9214 name = "/";
9215 else
9217 gdb_assert (op == BINOP_REM);
9218 name = "rem";
9221 error (_("second operand of %s must not be zero."), name);
9224 if (type1->is_unsigned () || op == BINOP_MOD)
9225 return value_binop (arg1, arg2, op);
9227 gdb_mpz v1 = value_as_mpz (arg1);
9228 gdb_mpz v;
9229 switch (op)
9231 case BINOP_DIV:
9232 v = v1 / v2;
9233 break;
9234 case BINOP_REM:
9235 v = v1 % v2;
9236 if (v * v1 < 0)
9237 v -= v2;
9238 break;
9239 default:
9240 /* Should not reach this point. */
9241 gdb_assert_not_reached ("invalid operator");
9244 return value_from_mpz (type1, v);
9247 static int
9248 ada_value_equal (struct value *arg1, struct value *arg2)
9250 if (ada_is_direct_array_type (arg1->type ())
9251 || ada_is_direct_array_type (arg2->type ()))
9253 struct type *arg1_type, *arg2_type;
9255 /* Automatically dereference any array reference before
9256 we attempt to perform the comparison. */
9257 arg1 = ada_coerce_ref (arg1);
9258 arg2 = ada_coerce_ref (arg2);
9260 arg1 = ada_coerce_to_simple_array (arg1);
9261 arg2 = ada_coerce_to_simple_array (arg2);
9263 arg1_type = ada_check_typedef (arg1->type ());
9264 arg2_type = ada_check_typedef (arg2->type ());
9266 if (arg1_type->code () != TYPE_CODE_ARRAY
9267 || arg2_type->code () != TYPE_CODE_ARRAY)
9268 error (_("Attempt to compare array with non-array"));
9269 /* FIXME: The following works only for types whose
9270 representations use all bits (no padding or undefined bits)
9271 and do not have user-defined equality. */
9272 return (arg1_type->length () == arg2_type->length ()
9273 && memcmp (arg1->contents ().data (),
9274 arg2->contents ().data (),
9275 arg1_type->length ()) == 0);
9277 return value_equal (arg1, arg2);
9280 namespace expr
9283 bool
9284 check_objfile (const std::unique_ptr<ada_component> &comp,
9285 struct objfile *objfile)
9287 return comp->uses_objfile (objfile);
9290 /* See ada-exp.h. */
9292 void
9293 aggregate_assigner::assign (LONGEST index, operation_up &arg)
9295 scoped_value_mark mark;
9297 struct value *elt;
9298 struct type *lhs_type = check_typedef (lhs->type ());
9300 if (lhs_type->code () == TYPE_CODE_ARRAY)
9302 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9303 struct value *index_val = value_from_longest (index_type, index);
9305 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9307 else
9309 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9310 elt = ada_to_fixed_value (elt);
9313 scoped_restore save_index = make_scoped_restore (&m_current_index, index);
9315 ada_aggregate_operation *ag_op
9316 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9317 if (ag_op != nullptr)
9318 ag_op->assign_aggregate (container, elt, exp);
9319 else
9320 value_assign_to_component (container, elt,
9321 arg->evaluate (nullptr, exp,
9322 EVAL_NORMAL));
9325 /* See ada-exp.h. */
9327 value *
9328 aggregate_assigner::current_value () const
9330 /* Note that using an integer type here is incorrect -- the type
9331 should be the array's index type. Unfortunately, though, this
9332 isn't currently available during parsing and type resolution. */
9333 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9334 return value_from_longest (index_type, m_current_index);
9337 bool
9338 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9340 if (m_base != nullptr && m_base->uses_objfile (objfile))
9341 return true;
9342 for (const auto &item : m_components)
9343 if (item->uses_objfile (objfile))
9344 return true;
9345 return false;
9348 void
9349 ada_aggregate_component::dump (ui_file *stream, int depth)
9351 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9352 if (m_base != nullptr)
9354 gdb_printf (stream, _("%*swith delta\n"), depth + 1, "");
9355 m_base->dump (stream, depth + 2);
9357 for (const auto &item : m_components)
9358 item->dump (stream, depth + 1);
9361 void
9362 ada_aggregate_component::assign (aggregate_assigner &assigner)
9364 if (m_base != nullptr)
9366 value *base = m_base->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9367 if (ada_is_direct_array_type (base->type ()))
9368 base = ada_coerce_to_simple_array (base);
9369 if (!types_deeply_equal (assigner.container->type (), base->type ()))
9370 error (_("Type mismatch in delta aggregate"));
9371 value_assign_to_component (assigner.container, assigner.container,
9372 base);
9375 for (auto &item : m_components)
9376 item->assign (assigner);
9379 /* See ada-exp.h. */
9381 ada_aggregate_component::ada_aggregate_component
9382 (operation_up &&base, std::vector<ada_component_up> &&components)
9383 : m_base (std::move (base)),
9384 m_components (std::move (components))
9386 for (const auto &component : m_components)
9387 if (dynamic_cast<const ada_others_component *> (component.get ())
9388 != nullptr)
9390 /* It's invalid and nonsensical to have 'others => ...' with a
9391 delta aggregate. It was simpler to enforce this
9392 restriction here as opposed to in the parser. */
9393 error (_("'others' invalid in delta aggregate"));
9397 /* See ada-exp.h. */
9399 value *
9400 ada_aggregate_operation::assign_aggregate (struct value *container,
9401 struct value *lhs,
9402 struct expression *exp)
9404 struct type *lhs_type;
9405 aggregate_assigner assigner;
9407 container = ada_coerce_ref (container);
9408 if (ada_is_direct_array_type (container->type ()))
9409 container = ada_coerce_to_simple_array (container);
9410 lhs = ada_coerce_ref (lhs);
9411 if (!lhs->deprecated_modifiable ())
9412 error (_("Left operand of assignment is not a modifiable lvalue."));
9414 lhs_type = check_typedef (lhs->type ());
9415 if (ada_is_direct_array_type (lhs_type))
9417 lhs = ada_coerce_to_simple_array (lhs);
9418 lhs_type = check_typedef (lhs->type ());
9419 assigner.low = lhs_type->bounds ()->low.const_val ();
9420 assigner.high = lhs_type->bounds ()->high.const_val ();
9422 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9424 assigner.low = 0;
9425 assigner.high = num_visible_fields (lhs_type) - 1;
9427 else
9428 error (_("Left-hand side must be array or record."));
9430 assigner.indices.push_back (assigner.low - 1);
9431 assigner.indices.push_back (assigner.low - 1);
9432 assigner.indices.push_back (assigner.high + 1);
9433 assigner.indices.push_back (assigner.high + 1);
9435 assigner.container = container;
9436 assigner.lhs = lhs;
9437 assigner.exp = exp;
9439 std::get<0> (m_storage)->assign (assigner);
9441 return container;
9444 bool
9445 ada_positional_component::uses_objfile (struct objfile *objfile)
9447 return m_op->uses_objfile (objfile);
9450 void
9451 ada_positional_component::dump (ui_file *stream, int depth)
9453 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9454 depth, "", m_index);
9455 m_op->dump (stream, depth + 1);
9458 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9459 construct, given that the positions are relative to lower bound
9460 LOW, where HIGH is the upper bound. Record the position in
9461 INDICES. CONTAINER is as for assign_aggregate. */
9462 void
9463 ada_positional_component::assign (aggregate_assigner &assigner)
9465 LONGEST ind = m_index + assigner.low;
9467 if (ind - 1 == assigner.high)
9468 warning (_("Extra components in aggregate ignored."));
9469 if (ind <= assigner.high)
9471 assigner.add_interval (ind, ind);
9472 assigner.assign (ind, m_op);
9476 bool
9477 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9479 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9482 void
9483 ada_discrete_range_association::dump (ui_file *stream, int depth)
9485 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9486 m_low->dump (stream, depth + 1);
9487 m_high->dump (stream, depth + 1);
9490 void
9491 ada_discrete_range_association::assign (aggregate_assigner &assigner,
9492 operation_up &op)
9494 LONGEST lower = value_as_long (m_low->evaluate (nullptr, assigner.exp,
9495 EVAL_NORMAL));
9496 LONGEST upper = value_as_long (m_high->evaluate (nullptr, assigner.exp,
9497 EVAL_NORMAL));
9499 if (lower <= upper && (lower < assigner.low || upper > assigner.high))
9500 error (_("Index in component association out of bounds."));
9502 assigner.add_interval (lower, upper);
9503 while (lower <= upper)
9505 assigner.assign (lower, op);
9506 lower += 1;
9510 bool
9511 ada_name_association::uses_objfile (struct objfile *objfile)
9513 return m_val->uses_objfile (objfile);
9516 void
9517 ada_name_association::dump (ui_file *stream, int depth)
9519 gdb_printf (stream, _("%*sName:\n"), depth, "");
9520 m_val->dump (stream, depth + 1);
9523 void
9524 ada_name_association::assign (aggregate_assigner &assigner,
9525 operation_up &op)
9527 int index;
9529 if (ada_is_direct_array_type (assigner.lhs->type ()))
9531 value *tem = m_val->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9532 index = longest_to_int (value_as_long (tem));
9534 else
9536 ada_string_operation *strop
9537 = dynamic_cast<ada_string_operation *> (m_val.get ());
9539 const char *name;
9540 if (strop != nullptr)
9541 name = strop->get_name ();
9542 else
9544 ada_var_value_operation *vvo
9545 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9546 if (vvo == nullptr)
9547 error (_("Invalid record component association."));
9548 name = vvo->get_symbol ()->natural_name ();
9549 /* In this scenario, the user wrote (name => expr), but
9550 write_name_assoc found some fully-qualified name and
9551 substituted it. This happens because, at parse time, the
9552 meaning of the expression isn't known; but here we know
9553 that just the base name was supplied and it refers to the
9554 name of a field. */
9555 name = ada_unqualified_name (name);
9558 index = 0;
9559 if (! find_struct_field (name, assigner.lhs->type (), 0,
9560 NULL, NULL, NULL, NULL, &index))
9561 error (_("Unknown component name: %s."), name);
9564 assigner.add_interval (index, index);
9565 assigner.assign (index, op);
9568 bool
9569 ada_choices_component::uses_objfile (struct objfile *objfile)
9571 if (m_op->uses_objfile (objfile))
9572 return true;
9573 for (const auto &item : m_assocs)
9574 if (item->uses_objfile (objfile))
9575 return true;
9576 return false;
9579 void
9580 ada_choices_component::dump (ui_file *stream, int depth)
9582 if (m_name.empty ())
9583 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9584 else
9586 gdb_printf (stream, _("%*sIterated choices:\n"), depth, "");
9587 gdb_printf (stream, _("%*sName: %s\n"), depth + 1, "", m_name.c_str ());
9589 m_op->dump (stream, depth + 1);
9591 for (const auto &item : m_assocs)
9592 item->dump (stream, depth + 1);
9595 /* Assign into the components of LHS indexed by the OP_CHOICES
9596 construct at *POS, updating *POS past the construct, given that
9597 the allowable indices are LOW..HIGH. Record the indices assigned
9598 to in INDICES. CONTAINER is as for assign_aggregate. */
9599 void
9600 ada_choices_component::assign (aggregate_assigner &assigner)
9602 scoped_restore save_index = make_scoped_restore (&m_assigner, &assigner);
9603 for (auto &item : m_assocs)
9604 item->assign (assigner, m_op);
9607 void
9608 ada_index_var_operation::dump (struct ui_file *stream, int depth) const
9610 gdb_printf (stream, _("%*sIndex variable: %s\n"), depth, "",
9611 m_var->name ().c_str ());
9614 value *
9615 ada_index_var_operation::evaluate (struct type *expect_type,
9616 struct expression *exp,
9617 enum noside noside)
9619 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9621 /* Note that using an integer type here is incorrect -- the type
9622 should be the array's index type. Unfortunately, though,
9623 this isn't currently available during parsing and type
9624 resolution. */
9625 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9626 return value::zero (index_type, not_lval);
9629 return m_var->current_value ();
9632 bool
9633 ada_others_component::uses_objfile (struct objfile *objfile)
9635 return m_op->uses_objfile (objfile);
9638 void
9639 ada_others_component::dump (ui_file *stream, int depth)
9641 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9642 m_op->dump (stream, depth + 1);
9645 /* Assign the value of the expression in the OP_OTHERS construct in
9646 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9647 have not been previously assigned. The index intervals already assigned
9648 are in INDICES. CONTAINER is as for assign_aggregate. */
9649 void
9650 ada_others_component::assign (aggregate_assigner &assigner)
9652 int num_indices = assigner.indices.size ();
9653 for (int i = 0; i < num_indices - 2; i += 2)
9655 for (LONGEST ind = assigner.indices[i + 1] + 1;
9656 ind < assigner.indices[i + 2];
9657 ind += 1)
9658 assigner.assign (ind, m_op);
9662 struct value *
9663 ada_assign_operation::evaluate (struct type *expect_type,
9664 struct expression *exp,
9665 enum noside noside)
9667 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9668 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
9670 ada_aggregate_operation *ag_op
9671 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9672 if (ag_op != nullptr)
9674 if (noside != EVAL_NORMAL)
9675 return arg1;
9677 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9678 return ada_value_assign (arg1, arg1);
9680 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9681 except if the lhs of our assignment is a convenience variable.
9682 In the case of assigning to a convenience variable, the lhs
9683 should be exactly the result of the evaluation of the rhs. */
9684 struct type *type = arg1->type ();
9685 if (arg1->lval () == lval_internalvar)
9686 type = NULL;
9687 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9688 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9689 return arg1;
9690 if (arg1->lval () == lval_internalvar)
9692 /* Nothing. */
9694 else
9695 arg2 = coerce_for_assign (arg1->type (), arg2);
9696 return ada_value_assign (arg1, arg2);
9699 /* See ada-exp.h. */
9701 void
9702 aggregate_assigner::add_interval (LONGEST from, LONGEST to)
9704 int i, j;
9706 int size = indices.size ();
9707 for (i = 0; i < size; i += 2) {
9708 if (to >= indices[i] && from <= indices[i + 1])
9710 int kh;
9712 for (kh = i + 2; kh < size; kh += 2)
9713 if (to < indices[kh])
9714 break;
9715 if (from < indices[i])
9716 indices[i] = from;
9717 indices[i + 1] = indices[kh - 1];
9718 if (to > indices[i + 1])
9719 indices[i + 1] = to;
9720 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9721 indices.resize (kh - i - 2);
9722 return;
9724 else if (to < indices[i])
9725 break;
9728 indices.resize (indices.size () + 2);
9729 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9730 indices[j] = indices[j - 2];
9731 indices[i] = from;
9732 indices[i + 1] = to;
9735 } /* namespace expr */
9737 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9738 is different. */
9740 static struct value *
9741 ada_value_cast (struct type *type, struct value *arg2)
9743 if (type == ada_check_typedef (arg2->type ()))
9744 return arg2;
9746 return value_cast (type, arg2);
9749 /* Evaluating Ada expressions, and printing their result.
9750 ------------------------------------------------------
9752 1. Introduction:
9753 ----------------
9755 We usually evaluate an Ada expression in order to print its value.
9756 We also evaluate an expression in order to print its type, which
9757 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9758 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9759 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9760 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9761 similar.
9763 Evaluating expressions is a little more complicated for Ada entities
9764 than it is for entities in languages such as C. The main reason for
9765 this is that Ada provides types whose definition might be dynamic.
9766 One example of such types is variant records. Or another example
9767 would be an array whose bounds can only be known at run time.
9769 The following description is a general guide as to what should be
9770 done (and what should NOT be done) in order to evaluate an expression
9771 involving such types, and when. This does not cover how the semantic
9772 information is encoded by GNAT as this is covered separatly. For the
9773 document used as the reference for the GNAT encoding, see exp_dbug.ads
9774 in the GNAT sources.
9776 Ideally, we should embed each part of this description next to its
9777 associated code. Unfortunately, the amount of code is so vast right
9778 now that it's hard to see whether the code handling a particular
9779 situation might be duplicated or not. One day, when the code is
9780 cleaned up, this guide might become redundant with the comments
9781 inserted in the code, and we might want to remove it.
9783 2. ``Fixing'' an Entity, the Simple Case:
9784 -----------------------------------------
9786 When evaluating Ada expressions, the tricky issue is that they may
9787 reference entities whose type contents and size are not statically
9788 known. Consider for instance a variant record:
9790 type Rec (Empty : Boolean := True) is record
9791 case Empty is
9792 when True => null;
9793 when False => Value : Integer;
9794 end case;
9795 end record;
9796 Yes : Rec := (Empty => False, Value => 1);
9797 No : Rec := (empty => True);
9799 The size and contents of that record depends on the value of the
9800 discriminant (Rec.Empty). At this point, neither the debugging
9801 information nor the associated type structure in GDB are able to
9802 express such dynamic types. So what the debugger does is to create
9803 "fixed" versions of the type that applies to the specific object.
9804 We also informally refer to this operation as "fixing" an object,
9805 which means creating its associated fixed type.
9807 Example: when printing the value of variable "Yes" above, its fixed
9808 type would look like this:
9810 type Rec is record
9811 Empty : Boolean;
9812 Value : Integer;
9813 end record;
9815 On the other hand, if we printed the value of "No", its fixed type
9816 would become:
9818 type Rec is record
9819 Empty : Boolean;
9820 end record;
9822 Things become a little more complicated when trying to fix an entity
9823 with a dynamic type that directly contains another dynamic type,
9824 such as an array of variant records, for instance. There are
9825 two possible cases: Arrays, and records.
9827 3. ``Fixing'' Arrays:
9828 ---------------------
9830 The type structure in GDB describes an array in terms of its bounds,
9831 and the type of its elements. By design, all elements in the array
9832 have the same type and we cannot represent an array of variant elements
9833 using the current type structure in GDB. When fixing an array,
9834 we cannot fix the array element, as we would potentially need one
9835 fixed type per element of the array. As a result, the best we can do
9836 when fixing an array is to produce an array whose bounds and size
9837 are correct (allowing us to read it from memory), but without having
9838 touched its element type. Fixing each element will be done later,
9839 when (if) necessary.
9841 Arrays are a little simpler to handle than records, because the same
9842 amount of memory is allocated for each element of the array, even if
9843 the amount of space actually used by each element differs from element
9844 to element. Consider for instance the following array of type Rec:
9846 type Rec_Array is array (1 .. 2) of Rec;
9848 The actual amount of memory occupied by each element might be different
9849 from element to element, depending on the value of their discriminant.
9850 But the amount of space reserved for each element in the array remains
9851 fixed regardless. So we simply need to compute that size using
9852 the debugging information available, from which we can then determine
9853 the array size (we multiply the number of elements of the array by
9854 the size of each element).
9856 The simplest case is when we have an array of a constrained element
9857 type. For instance, consider the following type declarations:
9859 type Bounded_String (Max_Size : Integer) is
9860 Length : Integer;
9861 Buffer : String (1 .. Max_Size);
9862 end record;
9863 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9865 In this case, the compiler describes the array as an array of
9866 variable-size elements (identified by its XVS suffix) for which
9867 the size can be read in the parallel XVZ variable.
9869 In the case of an array of an unconstrained element type, the compiler
9870 wraps the array element inside a private PAD type. This type should not
9871 be shown to the user, and must be "unwrap"'ed before printing. Note
9872 that we also use the adjective "aligner" in our code to designate
9873 these wrapper types.
9875 In some cases, the size allocated for each element is statically
9876 known. In that case, the PAD type already has the correct size,
9877 and the array element should remain unfixed.
9879 But there are cases when this size is not statically known.
9880 For instance, assuming that "Five" is an integer variable:
9882 type Dynamic is array (1 .. Five) of Integer;
9883 type Wrapper (Has_Length : Boolean := False) is record
9884 Data : Dynamic;
9885 case Has_Length is
9886 when True => Length : Integer;
9887 when False => null;
9888 end case;
9889 end record;
9890 type Wrapper_Array is array (1 .. 2) of Wrapper;
9892 Hello : Wrapper_Array := (others => (Has_Length => True,
9893 Data => (others => 17),
9894 Length => 1));
9897 The debugging info would describe variable Hello as being an
9898 array of a PAD type. The size of that PAD type is not statically
9899 known, but can be determined using a parallel XVZ variable.
9900 In that case, a copy of the PAD type with the correct size should
9901 be used for the fixed array.
9903 3. ``Fixing'' record type objects:
9904 ----------------------------------
9906 Things are slightly different from arrays in the case of dynamic
9907 record types. In this case, in order to compute the associated
9908 fixed type, we need to determine the size and offset of each of
9909 its components. This, in turn, requires us to compute the fixed
9910 type of each of these components.
9912 Consider for instance the example:
9914 type Bounded_String (Max_Size : Natural) is record
9915 Str : String (1 .. Max_Size);
9916 Length : Natural;
9917 end record;
9918 My_String : Bounded_String (Max_Size => 10);
9920 In that case, the position of field "Length" depends on the size
9921 of field Str, which itself depends on the value of the Max_Size
9922 discriminant. In order to fix the type of variable My_String,
9923 we need to fix the type of field Str. Therefore, fixing a variant
9924 record requires us to fix each of its components.
9926 However, if a component does not have a dynamic size, the component
9927 should not be fixed. In particular, fields that use a PAD type
9928 should not fixed. Here is an example where this might happen
9929 (assuming type Rec above):
9931 type Container (Big : Boolean) is record
9932 First : Rec;
9933 After : Integer;
9934 case Big is
9935 when True => Another : Integer;
9936 when False => null;
9937 end case;
9938 end record;
9939 My_Container : Container := (Big => False,
9940 First => (Empty => True),
9941 After => 42);
9943 In that example, the compiler creates a PAD type for component First,
9944 whose size is constant, and then positions the component After just
9945 right after it. The offset of component After is therefore constant
9946 in this case.
9948 The debugger computes the position of each field based on an algorithm
9949 that uses, among other things, the actual position and size of the field
9950 preceding it. Let's now imagine that the user is trying to print
9951 the value of My_Container. If the type fixing was recursive, we would
9952 end up computing the offset of field After based on the size of the
9953 fixed version of field First. And since in our example First has
9954 only one actual field, the size of the fixed type is actually smaller
9955 than the amount of space allocated to that field, and thus we would
9956 compute the wrong offset of field After.
9958 To make things more complicated, we need to watch out for dynamic
9959 components of variant records (identified by the ___XVL suffix in
9960 the component name). Even if the target type is a PAD type, the size
9961 of that type might not be statically known. So the PAD type needs
9962 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9963 we might end up with the wrong size for our component. This can be
9964 observed with the following type declarations:
9966 type Octal is new Integer range 0 .. 7;
9967 type Octal_Array is array (Positive range <>) of Octal;
9968 pragma Pack (Octal_Array);
9970 type Octal_Buffer (Size : Positive) is record
9971 Buffer : Octal_Array (1 .. Size);
9972 Length : Integer;
9973 end record;
9975 In that case, Buffer is a PAD type whose size is unset and needs
9976 to be computed by fixing the unwrapped type.
9978 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
9979 ----------------------------------------------------------
9981 Lastly, when should the sub-elements of an entity that remained unfixed
9982 thus far, be actually fixed?
9984 The answer is: Only when referencing that element. For instance
9985 when selecting one component of a record, this specific component
9986 should be fixed at that point in time. Or when printing the value
9987 of a record, each component should be fixed before its value gets
9988 printed. Similarly for arrays, the element of the array should be
9989 fixed when printing each element of the array, or when extracting
9990 one element out of that array. On the other hand, fixing should
9991 not be performed on the elements when taking a slice of an array!
9993 Note that one of the side effects of miscomputing the offset and
9994 size of each field is that we end up also miscomputing the size
9995 of the containing type. This can have adverse results when computing
9996 the value of an entity. GDB fetches the value of an entity based
9997 on the size of its type, and thus a wrong size causes GDB to fetch
9998 the wrong amount of memory. In the case where the computed size is
9999 too small, GDB fetches too little data to print the value of our
10000 entity. Results in this case are unpredictable, as we usually read
10001 past the buffer containing the data =:-o. */
10003 /* A helper function for TERNOP_IN_RANGE. */
10005 static value *
10006 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10007 enum noside noside,
10008 value *arg1, value *arg2, value *arg3)
10010 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10011 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10012 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10013 return
10014 value_from_longest (type,
10015 (value_less (arg1, arg3)
10016 || value_equal (arg1, arg3))
10017 && (value_less (arg2, arg1)
10018 || value_equal (arg2, arg1)));
10021 /* A helper function for UNOP_NEG. */
10023 value *
10024 ada_unop_neg (struct type *expect_type,
10025 struct expression *exp,
10026 enum noside noside, enum exp_opcode op,
10027 struct value *arg1)
10029 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10030 return value_neg (arg1);
10033 /* A helper function for UNOP_IN_RANGE. */
10035 value *
10036 ada_unop_in_range (struct type *expect_type,
10037 struct expression *exp,
10038 enum noside noside, enum exp_opcode op,
10039 struct value *arg1, struct type *type)
10041 struct value *arg2, *arg3;
10042 switch (type->code ())
10044 default:
10045 lim_warning (_("Membership test incompletely implemented; "
10046 "always returns true"));
10047 type = language_bool_type (exp->language_defn, exp->gdbarch);
10048 return value_from_longest (type, 1);
10050 case TYPE_CODE_RANGE:
10051 arg2 = value_from_longest (type,
10052 type->bounds ()->low.const_val ());
10053 arg3 = value_from_longest (type,
10054 type->bounds ()->high.const_val ());
10055 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10056 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10057 type = language_bool_type (exp->language_defn, exp->gdbarch);
10058 return
10059 value_from_longest (type,
10060 (value_less (arg1, arg3)
10061 || value_equal (arg1, arg3))
10062 && (value_less (arg2, arg1)
10063 || value_equal (arg2, arg1)));
10067 /* A helper function for OP_ATR_TAG. */
10069 value *
10070 ada_atr_tag (struct type *expect_type,
10071 struct expression *exp,
10072 enum noside noside, enum exp_opcode op,
10073 struct value *arg1)
10075 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10076 return value::zero (ada_tag_type (arg1), not_lval);
10078 return ada_value_tag (arg1);
10081 namespace expr
10084 value *
10085 ada_atr_size_operation::evaluate (struct type *expect_type,
10086 struct expression *exp,
10087 enum noside noside)
10089 bool is_type = std::get<0> (m_storage)->opcode () == OP_TYPE;
10090 bool is_size = std::get<1> (m_storage);
10092 enum noside sub_noside = is_type ? EVAL_AVOID_SIDE_EFFECTS : noside;
10093 value *val = std::get<0> (m_storage)->evaluate (nullptr, exp, sub_noside);
10094 struct type *type = ada_check_typedef (val->type ());
10096 if (is_type)
10098 if (is_size)
10099 error (_("gdb cannot apply 'Size to a type"));
10100 if (is_dynamic_type (type) || find_base_type (type) != nullptr)
10101 error (_("cannot apply 'Object_Size to dynamic type"));
10104 /* If the argument is a reference, then dereference its type, since
10105 the user is really asking for the size of the actual object,
10106 not the size of the pointer. */
10107 if (type->code () == TYPE_CODE_REF)
10108 type = type->target_type ();
10110 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10111 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10112 else
10113 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10114 TARGET_CHAR_BIT * type->length ());
10117 } /* namespace expr */
10119 /* A helper function for UNOP_ABS. */
10121 value *
10122 ada_abs (struct type *expect_type,
10123 struct expression *exp,
10124 enum noside noside, enum exp_opcode op,
10125 struct value *arg1)
10127 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10128 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10129 return value_neg (arg1);
10130 else
10131 return arg1;
10134 /* A helper function for BINOP_MUL. */
10136 value *
10137 ada_mult_binop (struct type *expect_type,
10138 struct expression *exp,
10139 enum noside noside, enum exp_opcode op,
10140 struct value *arg1, struct value *arg2)
10142 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10144 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10145 return value::zero (arg1->type (), not_lval);
10147 else
10149 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10150 return ada_value_binop (arg1, arg2, op);
10154 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10156 value *
10157 ada_equal_binop (struct type *expect_type,
10158 struct expression *exp,
10159 enum noside noside, enum exp_opcode op,
10160 struct value *arg1, struct value *arg2)
10162 int tem;
10163 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10164 tem = 0;
10165 else
10167 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10168 tem = ada_value_equal (arg1, arg2);
10170 if (op == BINOP_NOTEQUAL)
10171 tem = !tem;
10172 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10173 return value_from_longest (type, tem);
10176 /* A helper function for TERNOP_SLICE. */
10178 value *
10179 ada_ternop_slice (struct expression *exp,
10180 enum noside noside,
10181 struct value *array, struct value *low_bound_val,
10182 struct value *high_bound_val)
10184 LONGEST low_bound;
10185 LONGEST high_bound;
10187 low_bound_val = coerce_ref (low_bound_val);
10188 high_bound_val = coerce_ref (high_bound_val);
10189 low_bound = value_as_long (low_bound_val);
10190 high_bound = value_as_long (high_bound_val);
10192 /* If this is a reference to an aligner type, then remove all
10193 the aligners. */
10194 if (array->type ()->code () == TYPE_CODE_REF
10195 && ada_is_aligner_type (array->type ()->target_type ()))
10196 array->type ()->set_target_type
10197 (ada_aligned_type (array->type ()->target_type ()));
10199 if (ada_is_any_packed_array_type (array->type ()))
10200 error (_("cannot slice a packed array"));
10202 /* If this is a reference to an array or an array lvalue,
10203 convert to a pointer. */
10204 if (array->type ()->code () == TYPE_CODE_REF
10205 || (array->type ()->code () == TYPE_CODE_ARRAY
10206 && array->lval () == lval_memory))
10207 array = value_addr (array);
10209 if (noside == EVAL_AVOID_SIDE_EFFECTS
10210 && ada_is_array_descriptor_type (ada_check_typedef
10211 (array->type ())))
10212 return empty_array (ada_type_of_array (array, 0), low_bound,
10213 high_bound);
10215 array = ada_coerce_to_simple_array_ptr (array);
10217 /* If we have more than one level of pointer indirection,
10218 dereference the value until we get only one level. */
10219 while (array->type ()->code () == TYPE_CODE_PTR
10220 && (array->type ()->target_type ()->code ()
10221 == TYPE_CODE_PTR))
10222 array = value_ind (array);
10224 /* Make sure we really do have an array type before going further,
10225 to avoid a SEGV when trying to get the index type or the target
10226 type later down the road if the debug info generated by
10227 the compiler is incorrect or incomplete. */
10228 if (!ada_is_simple_array_type (array->type ()))
10229 error (_("cannot take slice of non-array"));
10231 if (ada_check_typedef (array->type ())->code ()
10232 == TYPE_CODE_PTR)
10234 struct type *type0 = ada_check_typedef (array->type ());
10236 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10237 return empty_array (type0->target_type (), low_bound, high_bound);
10238 else
10240 struct type *arr_type0 =
10241 to_fixed_array_type (type0->target_type (), NULL, 1);
10243 return ada_value_slice_from_ptr (array, arr_type0,
10244 longest_to_int (low_bound),
10245 longest_to_int (high_bound));
10248 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10249 return array;
10250 else if (high_bound < low_bound)
10251 return empty_array (array->type (), low_bound, high_bound);
10252 else
10253 return ada_value_slice (array, longest_to_int (low_bound),
10254 longest_to_int (high_bound));
10257 /* A helper function for BINOP_IN_BOUNDS. */
10259 value *
10260 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10261 struct value *arg1, struct value *arg2, int n)
10263 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10265 struct type *type = language_bool_type (exp->language_defn,
10266 exp->gdbarch);
10267 return value::zero (type, not_lval);
10270 struct type *type = ada_index_type (arg2->type (), n, "range");
10271 if (!type)
10272 type = arg1->type ();
10274 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10275 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10277 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10278 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10279 type = language_bool_type (exp->language_defn, exp->gdbarch);
10280 return value_from_longest (type,
10281 (value_less (arg1, arg3)
10282 || value_equal (arg1, arg3))
10283 && (value_less (arg2, arg1)
10284 || value_equal (arg2, arg1)));
10287 /* A helper function for some attribute operations. */
10289 static value *
10290 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10291 struct value *arg1, struct type *type_arg, int tem)
10293 const char *attr_name = nullptr;
10294 if (op == OP_ATR_FIRST)
10295 attr_name = "first";
10296 else if (op == OP_ATR_LAST)
10297 attr_name = "last";
10299 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10301 if (type_arg == NULL)
10302 type_arg = arg1->type ();
10304 if (ada_is_constrained_packed_array_type (type_arg))
10305 type_arg = decode_constrained_packed_array_type (type_arg);
10307 if (!discrete_type_p (type_arg))
10309 switch (op)
10311 default: /* Should never happen. */
10312 error (_("unexpected attribute encountered"));
10313 case OP_ATR_FIRST:
10314 case OP_ATR_LAST:
10315 type_arg = ada_index_type (type_arg, tem,
10316 attr_name);
10317 break;
10318 case OP_ATR_LENGTH:
10319 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10320 break;
10324 return value::zero (type_arg, not_lval);
10326 else if (type_arg == NULL)
10328 arg1 = ada_coerce_ref (arg1);
10330 if (ada_is_constrained_packed_array_type (arg1->type ()))
10331 arg1 = ada_coerce_to_simple_array (arg1);
10333 struct type *type;
10334 if (op == OP_ATR_LENGTH)
10335 type = builtin_type (exp->gdbarch)->builtin_int;
10336 else
10338 type = ada_index_type (arg1->type (), tem,
10339 attr_name);
10340 if (type == NULL)
10341 type = builtin_type (exp->gdbarch)->builtin_int;
10344 switch (op)
10346 default: /* Should never happen. */
10347 error (_("unexpected attribute encountered"));
10348 case OP_ATR_FIRST:
10349 return value_from_longest
10350 (type, ada_array_bound (arg1, tem, 0));
10351 case OP_ATR_LAST:
10352 return value_from_longest
10353 (type, ada_array_bound (arg1, tem, 1));
10354 case OP_ATR_LENGTH:
10355 return value_from_longest
10356 (type, ada_array_length (arg1, tem));
10359 else if (discrete_type_p (type_arg))
10361 struct type *range_type;
10362 const char *name = ada_type_name (type_arg);
10364 range_type = NULL;
10365 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10366 range_type = to_fixed_range_type (type_arg, NULL);
10367 if (range_type == NULL)
10368 range_type = type_arg;
10369 switch (op)
10371 default:
10372 error (_("unexpected attribute encountered"));
10373 case OP_ATR_FIRST:
10374 return value_from_longest
10375 (range_type, ada_discrete_type_low_bound (range_type));
10376 case OP_ATR_LAST:
10377 return value_from_longest
10378 (range_type, ada_discrete_type_high_bound (range_type));
10379 case OP_ATR_LENGTH:
10380 error (_("the 'length attribute applies only to array types"));
10383 else if (type_arg->code () == TYPE_CODE_FLT)
10384 error (_("unimplemented type attribute"));
10385 else
10387 LONGEST low, high;
10389 if (ada_is_constrained_packed_array_type (type_arg))
10390 type_arg = decode_constrained_packed_array_type (type_arg);
10392 struct type *type;
10393 if (op == OP_ATR_LENGTH)
10394 type = builtin_type (exp->gdbarch)->builtin_int;
10395 else
10397 type = ada_index_type (type_arg, tem, attr_name);
10398 if (type == NULL)
10399 type = builtin_type (exp->gdbarch)->builtin_int;
10402 switch (op)
10404 default:
10405 error (_("unexpected attribute encountered"));
10406 case OP_ATR_FIRST:
10407 low = ada_array_bound_from_type (type_arg, tem, 0);
10408 return value_from_longest (type, low);
10409 case OP_ATR_LAST:
10410 high = ada_array_bound_from_type (type_arg, tem, 1);
10411 return value_from_longest (type, high);
10412 case OP_ATR_LENGTH:
10413 low = ada_array_bound_from_type (type_arg, tem, 0);
10414 high = ada_array_bound_from_type (type_arg, tem, 1);
10415 return value_from_longest (type, high - low + 1);
10420 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10422 struct value *
10423 ada_binop_minmax (struct type *expect_type,
10424 struct expression *exp,
10425 enum noside noside, enum exp_opcode op,
10426 struct value *arg1, struct value *arg2)
10428 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10429 return value::zero (arg1->type (), not_lval);
10430 else
10432 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10433 return value_binop (arg1, arg2, op);
10437 /* A helper function for BINOP_EXP. */
10439 struct value *
10440 ada_binop_exp (struct type *expect_type,
10441 struct expression *exp,
10442 enum noside noside, enum exp_opcode op,
10443 struct value *arg1, struct value *arg2)
10445 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10446 return value::zero (arg1->type (), not_lval);
10447 else
10449 /* For integer exponentiation operations,
10450 only promote the first argument. */
10451 if (is_integral_type (arg2->type ()))
10452 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10453 else
10454 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10456 return value_binop (arg1, arg2, op);
10460 namespace expr
10463 /* See ada-exp.h. */
10465 operation_up
10466 ada_resolvable::replace (operation_up &&owner,
10467 struct expression *exp,
10468 bool deprocedure_p,
10469 bool parse_completion,
10470 innermost_block_tracker *tracker,
10471 struct type *context_type)
10473 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10474 return (make_operation<ada_funcall_operation>
10475 (std::move (owner),
10476 std::vector<operation_up> ()));
10477 return std::move (owner);
10480 /* Convert the character literal whose value would be VAL to the
10481 appropriate value of type TYPE, if there is a translation.
10482 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10483 the literal 'A' (VAL == 65), returns 0. */
10485 static LONGEST
10486 convert_char_literal (struct type *type, LONGEST val)
10488 char name[12];
10489 int f;
10491 if (type == NULL)
10492 return val;
10493 type = check_typedef (type);
10494 if (type->code () != TYPE_CODE_ENUM)
10495 return val;
10497 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10498 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10499 else if (val >= 0 && val < 256)
10500 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10501 else if (val >= 0 && val < 0x10000)
10502 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10503 else
10504 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10505 size_t len = strlen (name);
10506 for (f = 0; f < type->num_fields (); f += 1)
10508 /* Check the suffix because an enum constant in a package will
10509 have a name like "pkg__QUxx". This is safe enough because we
10510 already have the correct type, and because mangling means
10511 there can't be clashes. */
10512 const char *ename = type->field (f).name ();
10513 size_t elen = strlen (ename);
10515 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10516 return type->field (f).loc_enumval ();
10518 return val;
10521 value *
10522 ada_char_operation::evaluate (struct type *expect_type,
10523 struct expression *exp,
10524 enum noside noside)
10526 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10527 if (expect_type != nullptr)
10528 result = ada_value_cast (expect_type, result);
10529 return result;
10532 /* See ada-exp.h. */
10534 operation_up
10535 ada_char_operation::replace (operation_up &&owner,
10536 struct expression *exp,
10537 bool deprocedure_p,
10538 bool parse_completion,
10539 innermost_block_tracker *tracker,
10540 struct type *context_type)
10542 operation_up result = std::move (owner);
10544 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10546 LONGEST val = as_longest ();
10547 gdb_assert (result.get () == this);
10548 std::get<0> (m_storage) = context_type;
10549 std::get<1> (m_storage) = convert_char_literal (context_type, val);
10552 return result;
10555 value *
10556 ada_wrapped_operation::evaluate (struct type *expect_type,
10557 struct expression *exp,
10558 enum noside noside)
10560 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10561 if (noside == EVAL_NORMAL)
10562 result = unwrap_value (result);
10564 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10565 then we need to perform the conversion manually, because
10566 evaluate_subexp_standard doesn't do it. This conversion is
10567 necessary in Ada because the different kinds of float/fixed
10568 types in Ada have different representations.
10570 Similarly, we need to perform the conversion from OP_LONG
10571 ourselves. */
10572 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10573 result = ada_value_cast (expect_type, result);
10575 return result;
10578 void
10579 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10580 struct agent_expr *ax,
10581 struct axs_value *value,
10582 struct type *cast_type)
10584 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10586 struct type *type = value->type;
10587 if (ada_is_aligner_type (type))
10588 error (_("Aligner types cannot be handled in agent expressions"));
10589 else if (find_base_type (type) != nullptr)
10590 error (_("Dynamic types cannot be handled in agent expressions"));
10593 value *
10594 ada_string_operation::evaluate (struct type *expect_type,
10595 struct expression *exp,
10596 enum noside noside)
10598 struct type *char_type;
10599 if (expect_type != nullptr && ada_is_string_type (expect_type))
10600 char_type = ada_array_element_type (expect_type, 1);
10601 else
10602 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10604 const std::string &str = std::get<0> (m_storage);
10605 const char *encoding;
10606 switch (char_type->length ())
10608 case 1:
10610 /* Simply copy over the data -- this isn't perhaps strictly
10611 correct according to the encodings, but it is gdb's
10612 historical behavior. */
10613 struct type *stringtype
10614 = lookup_array_range_type (char_type, 1, str.length ());
10615 struct value *val = value::allocate (stringtype);
10616 memcpy (val->contents_raw ().data (), str.c_str (),
10617 str.length ());
10618 return val;
10621 case 2:
10622 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10623 encoding = "UTF-16BE";
10624 else
10625 encoding = "UTF-16LE";
10626 break;
10628 case 4:
10629 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10630 encoding = "UTF-32BE";
10631 else
10632 encoding = "UTF-32LE";
10633 break;
10635 default:
10636 error (_("unexpected character type size %s"),
10637 pulongest (char_type->length ()));
10640 auto_obstack converted;
10641 convert_between_encodings (host_charset (), encoding,
10642 (const gdb_byte *) str.c_str (),
10643 str.length (), 1,
10644 &converted, translit_none);
10646 struct type *stringtype
10647 = lookup_array_range_type (char_type, 1,
10648 obstack_object_size (&converted)
10649 / char_type->length ());
10650 struct value *val = value::allocate (stringtype);
10651 memcpy (val->contents_raw ().data (),
10652 obstack_base (&converted),
10653 obstack_object_size (&converted));
10654 return val;
10657 value *
10658 ada_concat_operation::evaluate (struct type *expect_type,
10659 struct expression *exp,
10660 enum noside noside)
10662 /* If one side is a literal, evaluate the other side first so that
10663 the expected type can be set properly. */
10664 const operation_up &lhs_expr = std::get<0> (m_storage);
10665 const operation_up &rhs_expr = std::get<1> (m_storage);
10667 value *lhs, *rhs;
10668 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10670 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10671 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10673 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10675 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10676 struct type *rhs_type = check_typedef (rhs->type ());
10677 struct type *elt_type = nullptr;
10678 if (rhs_type->code () == TYPE_CODE_ARRAY)
10679 elt_type = rhs_type->target_type ();
10680 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10682 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10684 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10685 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10687 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10689 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10690 struct type *lhs_type = check_typedef (lhs->type ());
10691 struct type *elt_type = nullptr;
10692 if (lhs_type->code () == TYPE_CODE_ARRAY)
10693 elt_type = lhs_type->target_type ();
10694 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10696 else
10697 return concat_operation::evaluate (expect_type, exp, noside);
10699 return value_concat (lhs, rhs);
10702 value *
10703 ada_qual_operation::evaluate (struct type *expect_type,
10704 struct expression *exp,
10705 enum noside noside)
10707 struct type *type = std::get<1> (m_storage);
10708 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10711 value *
10712 ada_ternop_range_operation::evaluate (struct type *expect_type,
10713 struct expression *exp,
10714 enum noside noside)
10716 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10717 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10718 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10719 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10722 value *
10723 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10724 struct expression *exp,
10725 enum noside noside)
10727 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10728 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10730 auto do_op = [this] (LONGEST x, LONGEST y)
10732 if (std::get<0> (m_storage) == BINOP_ADD)
10733 return x + y;
10734 return x - y;
10737 if (arg1->type ()->code () == TYPE_CODE_PTR)
10738 return (value_from_longest
10739 (arg1->type (),
10740 do_op (value_as_long (arg1), value_as_long (arg2))));
10741 if (arg2->type ()->code () == TYPE_CODE_PTR)
10742 return (value_from_longest
10743 (arg2->type (),
10744 do_op (value_as_long (arg1), value_as_long (arg2))));
10745 /* Preserve the original type for use by the range case below.
10746 We cannot cast the result to a reference type, so if ARG1 is
10747 a reference type, find its underlying type. */
10748 struct type *type = arg1->type ();
10749 while (type->code () == TYPE_CODE_REF)
10750 type = type->target_type ();
10751 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10752 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10753 /* We need to special-case the result with a range.
10754 This is done for the benefit of "ptype". gdb's Ada support
10755 historically used the LHS to set the result type here, so
10756 preserve this behavior. */
10757 if (type->code () == TYPE_CODE_RANGE)
10758 arg1 = value_cast (type, arg1);
10759 return arg1;
10762 value *
10763 ada_unop_atr_operation::evaluate (struct type *expect_type,
10764 struct expression *exp,
10765 enum noside noside)
10767 struct type *type_arg = nullptr;
10768 value *val = nullptr;
10770 if (std::get<0> (m_storage)->type_p ())
10772 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10773 EVAL_AVOID_SIDE_EFFECTS);
10774 type_arg = tem->type ();
10776 else
10777 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10779 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10780 val, type_arg, std::get<2> (m_storage));
10783 value *
10784 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10785 struct expression *exp,
10786 enum noside noside)
10788 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10789 return value::zero (expect_type, not_lval);
10791 const bound_minimal_symbol &b = std::get<0> (m_storage);
10792 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10794 val = ada_value_cast (expect_type, val);
10796 /* Follow the Ada language semantics that do not allow taking
10797 an address of the result of a cast (view conversion in Ada). */
10798 if (val->lval () == lval_memory)
10800 if (val->lazy ())
10801 val->fetch_lazy ();
10802 val->set_lval (not_lval);
10804 return val;
10807 value *
10808 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10809 struct expression *exp,
10810 enum noside noside)
10812 value *val = evaluate_var_value (noside,
10813 std::get<0> (m_storage).block,
10814 std::get<0> (m_storage).symbol);
10816 val = ada_value_cast (expect_type, val);
10818 /* Follow the Ada language semantics that do not allow taking
10819 an address of the result of a cast (view conversion in Ada). */
10820 if (val->lval () == lval_memory)
10822 if (val->lazy ())
10823 val->fetch_lazy ();
10824 val->set_lval (not_lval);
10826 return val;
10829 value *
10830 ada_var_value_operation::evaluate (struct type *expect_type,
10831 struct expression *exp,
10832 enum noside noside)
10834 symbol *sym = std::get<0> (m_storage).symbol;
10836 if (sym->domain () == UNDEF_DOMAIN)
10837 /* Only encountered when an unresolved symbol occurs in a
10838 context other than a function call, in which case, it is
10839 invalid. */
10840 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10841 sym->print_name ());
10843 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10845 struct type *type = static_unwrap_type (sym->type ());
10846 /* Check to see if this is a tagged type. We also need to handle
10847 the case where the type is a reference to a tagged type, but
10848 we have to be careful to exclude pointers to tagged types.
10849 The latter should be shown as usual (as a pointer), whereas
10850 a reference should mostly be transparent to the user. */
10851 if (ada_is_tagged_type (type, 0)
10852 || (type->code () == TYPE_CODE_REF
10853 && ada_is_tagged_type (type->target_type (), 0)))
10855 /* Tagged types are a little special in the fact that the real
10856 type is dynamic and can only be determined by inspecting the
10857 object's tag. This means that we need to get the object's
10858 value first (EVAL_NORMAL) and then extract the actual object
10859 type from its tag.
10861 Note that we cannot skip the final step where we extract
10862 the object type from its tag, because the EVAL_NORMAL phase
10863 results in dynamic components being resolved into fixed ones.
10864 This can cause problems when trying to print the type
10865 description of tagged types whose parent has a dynamic size:
10866 We use the type name of the "_parent" component in order
10867 to print the name of the ancestor type in the type description.
10868 If that component had a dynamic size, the resolution into
10869 a fixed type would result in the loss of that type name,
10870 thus preventing us from printing the name of the ancestor
10871 type in the type description. */
10872 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10874 if (type->code () != TYPE_CODE_REF)
10876 struct type *actual_type;
10878 actual_type = type_from_tag (ada_value_tag (arg1));
10879 if (actual_type == NULL)
10880 /* If, for some reason, we were unable to determine
10881 the actual type from the tag, then use the static
10882 approximation that we just computed as a fallback.
10883 This can happen if the debugging information is
10884 incomplete, for instance. */
10885 actual_type = type;
10886 return value::zero (actual_type, not_lval);
10888 else
10890 /* In the case of a ref, ada_coerce_ref takes care
10891 of determining the actual type. But the evaluation
10892 should return a ref as it should be valid to ask
10893 for its address; so rebuild a ref after coerce. */
10894 arg1 = ada_coerce_ref (arg1);
10895 return value_ref (arg1, TYPE_CODE_REF);
10899 /* Records and unions for which GNAT encodings have been
10900 generated need to be statically fixed as well.
10901 Otherwise, non-static fixing produces a type where
10902 all dynamic properties are removed, which prevents "ptype"
10903 from being able to completely describe the type.
10904 For instance, a case statement in a variant record would be
10905 replaced by the relevant components based on the actual
10906 value of the discriminants. */
10907 if ((type->code () == TYPE_CODE_STRUCT
10908 && dynamic_template_type (type) != NULL)
10909 || (type->code () == TYPE_CODE_UNION
10910 && ada_find_parallel_type (type, "___XVU") != NULL))
10911 return value::zero (to_static_fixed_type (type), not_lval);
10914 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10915 return ada_to_fixed_value (arg1);
10918 bool
10919 ada_var_value_operation::resolve (struct expression *exp,
10920 bool deprocedure_p,
10921 bool parse_completion,
10922 innermost_block_tracker *tracker,
10923 struct type *context_type)
10925 symbol *sym = std::get<0> (m_storage).symbol;
10926 if (sym->domain () == UNDEF_DOMAIN)
10928 block_symbol resolved
10929 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10930 context_type, parse_completion,
10931 deprocedure_p, tracker);
10932 std::get<0> (m_storage) = resolved;
10935 if (deprocedure_p
10936 && (std::get<0> (m_storage).symbol->type ()->code ()
10937 == TYPE_CODE_FUNC))
10938 return true;
10940 return false;
10943 void
10944 ada_var_value_operation::do_generate_ax (struct expression *exp,
10945 struct agent_expr *ax,
10946 struct axs_value *value,
10947 struct type *cast_type)
10949 symbol *sym = std::get<0> (m_storage).symbol;
10951 if (sym->domain () == UNDEF_DOMAIN)
10952 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10953 sym->print_name ());
10955 struct type *type = static_unwrap_type (sym->type ());
10956 if (ada_is_tagged_type (type, 0)
10957 || (type->code () == TYPE_CODE_REF
10958 && ada_is_tagged_type (type->target_type (), 0)))
10959 error (_("Tagged types cannot be handled in agent expressions"));
10961 if ((type->code () == TYPE_CODE_STRUCT
10962 && dynamic_template_type (type) != NULL)
10963 || (type->code () == TYPE_CODE_UNION
10964 && ada_find_parallel_type (type, "___XVU") != NULL))
10965 error (_("Dynamic types cannot be handled in agent expressions"));
10967 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10970 value *
10971 ada_unop_ind_operation::evaluate (struct type *expect_type,
10972 struct expression *exp,
10973 enum noside noside)
10975 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10977 struct type *type = ada_check_typedef (arg1->type ());
10978 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10980 if (ada_is_array_descriptor_type (type))
10982 /* GDB allows dereferencing GNAT array descriptors.
10983 However, for 'ptype' we don't want to try to
10984 "dereference" a thick pointer here -- that will end up
10985 giving us an array with (1 .. 0) for bounds, which is
10986 less clear than (<>). */
10987 struct type *arrType = ada_type_of_array (arg1, 0);
10989 if (arrType == NULL)
10990 error (_("Attempt to dereference null array pointer."));
10991 if (is_thick_pntr (type))
10992 return arg1;
10993 return value_at_lazy (arrType, 0);
10995 else if (type->code () == TYPE_CODE_PTR
10996 || type->code () == TYPE_CODE_REF
10997 /* In C you can dereference an array to get the 1st elt. */
10998 || type->code () == TYPE_CODE_ARRAY)
11000 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11001 only be determined by inspecting the object's tag.
11002 This means that we need to evaluate completely the
11003 expression in order to get its type. */
11005 if ((type->code () == TYPE_CODE_REF
11006 || type->code () == TYPE_CODE_PTR)
11007 && ada_is_tagged_type (type->target_type (), 0))
11009 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11010 EVAL_NORMAL);
11011 type = ada_value_ind (arg1)->type ();
11013 else
11015 type = to_static_fixed_type
11016 (ada_aligned_type
11017 (ada_check_typedef (type->target_type ())));
11019 return value::zero (type, lval_memory);
11021 else if (type->code () == TYPE_CODE_INT)
11023 /* GDB allows dereferencing an int. */
11024 if (expect_type == NULL)
11025 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11026 lval_memory);
11027 else
11029 expect_type =
11030 to_static_fixed_type (ada_aligned_type (expect_type));
11031 return value::zero (expect_type, lval_memory);
11034 else
11035 error (_("Attempt to take contents of a non-pointer value."));
11037 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11038 type = ada_check_typedef (arg1->type ());
11040 if (type->code () == TYPE_CODE_INT)
11041 /* GDB allows dereferencing an int. If we were given
11042 the expect_type, then use that as the target type.
11043 Otherwise, assume that the target type is an int. */
11045 if (expect_type != NULL)
11046 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11047 arg1));
11048 else
11049 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11050 value_as_address (arg1));
11053 if (ada_is_array_descriptor_type (type))
11054 /* GDB allows dereferencing GNAT array descriptors. */
11055 return ada_coerce_to_simple_array (arg1);
11056 else
11057 return ada_value_ind (arg1);
11060 value *
11061 ada_structop_operation::evaluate (struct type *expect_type,
11062 struct expression *exp,
11063 enum noside noside)
11065 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11066 const char *str = std::get<1> (m_storage).c_str ();
11067 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11069 struct type *type;
11070 struct type *type1 = arg1->type ();
11072 if (ada_is_tagged_type (type1, 1))
11074 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11076 /* If the field is not found, check if it exists in the
11077 extension of this object's type. This means that we
11078 need to evaluate completely the expression. */
11080 if (type == NULL)
11082 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11083 EVAL_NORMAL);
11084 arg1 = ada_value_struct_elt (arg1, str, 0);
11085 arg1 = unwrap_value (arg1);
11086 type = ada_to_fixed_value (arg1)->type ();
11089 else
11090 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11092 return value::zero (ada_aligned_type (type), lval_memory);
11094 else
11096 arg1 = ada_value_struct_elt (arg1, str, 0);
11097 arg1 = unwrap_value (arg1);
11098 return ada_to_fixed_value (arg1);
11102 value *
11103 ada_funcall_operation::evaluate (struct type *expect_type,
11104 struct expression *exp,
11105 enum noside noside)
11107 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11108 int nargs = args_up.size ();
11109 std::vector<value *> argvec (nargs);
11110 operation_up &callee_op = std::get<0> (m_storage);
11112 ada_var_value_operation *avv
11113 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11114 if (avv != nullptr
11115 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11116 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11117 avv->get_symbol ()->print_name ());
11119 value *callee = callee_op->evaluate (nullptr, exp, noside);
11120 for (int i = 0; i < args_up.size (); ++i)
11121 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11123 if (ada_is_constrained_packed_array_type
11124 (desc_base_type (callee->type ())))
11125 callee = ada_coerce_to_simple_array (callee);
11126 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11127 && callee->type ()->field (0).bitsize () != 0)
11128 /* This is a packed array that has already been fixed, and
11129 therefore already coerced to a simple array. Nothing further
11130 to do. */
11132 else if (callee->type ()->code () == TYPE_CODE_REF)
11134 /* Make sure we dereference references so that all the code below
11135 feels like it's really handling the referenced value. Wrapping
11136 types (for alignment) may be there, so make sure we strip them as
11137 well. */
11138 callee = ada_to_fixed_value (coerce_ref (callee));
11140 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11141 && callee->lval () == lval_memory)
11142 callee = value_addr (callee);
11144 struct type *type = ada_check_typedef (callee->type ());
11146 /* Ada allows us to implicitly dereference arrays when subscripting
11147 them. So, if this is an array typedef (encoding use for array
11148 access types encoded as fat pointers), strip it now. */
11149 if (type->code () == TYPE_CODE_TYPEDEF)
11150 type = ada_typedef_target_type (type);
11152 if (type->code () == TYPE_CODE_PTR)
11154 switch (ada_check_typedef (type->target_type ())->code ())
11156 case TYPE_CODE_FUNC:
11157 type = ada_check_typedef (type->target_type ());
11158 break;
11159 case TYPE_CODE_ARRAY:
11160 break;
11161 case TYPE_CODE_STRUCT:
11162 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11163 callee = ada_value_ind (callee);
11164 type = ada_check_typedef (type->target_type ());
11165 break;
11166 default:
11167 error (_("cannot subscript or call something of type `%s'"),
11168 ada_type_name (callee->type ()));
11169 break;
11173 switch (type->code ())
11175 case TYPE_CODE_FUNC:
11176 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11178 if (type->target_type () == NULL)
11179 error_call_unknown_return_type (NULL);
11180 return value::allocate (type->target_type ());
11182 return call_function_by_hand (callee, expect_type, argvec);
11183 case TYPE_CODE_INTERNAL_FUNCTION:
11184 return call_internal_function (exp->gdbarch, exp->language_defn,
11185 callee, nargs,
11186 argvec.data (), noside);
11188 case TYPE_CODE_STRUCT:
11190 int arity;
11192 arity = ada_array_arity (type);
11193 type = ada_array_element_type (type, nargs);
11194 if (type == NULL)
11195 error (_("cannot subscript or call a record"));
11196 if (arity != nargs)
11197 error (_("wrong number of subscripts; expecting %d"), arity);
11198 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11199 return value::zero (ada_aligned_type (type), lval_memory);
11200 return
11201 unwrap_value (ada_value_subscript
11202 (callee, nargs, argvec.data ()));
11204 case TYPE_CODE_ARRAY:
11205 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11207 type = ada_array_element_type (type, nargs);
11208 if (type == NULL)
11209 error (_("element type of array unknown"));
11210 else
11211 return value::zero (ada_aligned_type (type), lval_memory);
11213 return
11214 unwrap_value (ada_value_subscript
11215 (ada_coerce_to_simple_array (callee),
11216 nargs, argvec.data ()));
11217 case TYPE_CODE_PTR: /* Pointer to array */
11218 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11220 type = to_fixed_array_type (type->target_type (), NULL, 1);
11221 type = ada_array_element_type (type, nargs);
11222 if (type == NULL)
11223 error (_("element type of array unknown"));
11224 else
11225 return value::zero (ada_aligned_type (type), lval_memory);
11227 return
11228 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11229 argvec.data ()));
11231 default:
11232 error (_("Attempt to index or call something other than an "
11233 "array or function"));
11237 bool
11238 ada_funcall_operation::resolve (struct expression *exp,
11239 bool deprocedure_p,
11240 bool parse_completion,
11241 innermost_block_tracker *tracker,
11242 struct type *context_type)
11244 operation_up &callee_op = std::get<0> (m_storage);
11246 ada_var_value_operation *avv
11247 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11248 if (avv == nullptr)
11249 return false;
11251 symbol *sym = avv->get_symbol ();
11252 if (sym->domain () != UNDEF_DOMAIN)
11253 return false;
11255 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11256 int nargs = args_up.size ();
11257 std::vector<value *> argvec (nargs);
11259 for (int i = 0; i < args_up.size (); ++i)
11260 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11262 const block *block = avv->get_block ();
11263 block_symbol resolved
11264 = ada_resolve_funcall (sym, block,
11265 context_type, parse_completion,
11266 nargs, argvec.data (),
11267 tracker);
11269 std::get<0> (m_storage)
11270 = make_operation<ada_var_value_operation> (resolved);
11271 return false;
11274 bool
11275 ada_ternop_slice_operation::resolve (struct expression *exp,
11276 bool deprocedure_p,
11277 bool parse_completion,
11278 innermost_block_tracker *tracker,
11279 struct type *context_type)
11281 /* Historically this check was done during resolution, so we
11282 continue that here. */
11283 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11284 EVAL_AVOID_SIDE_EFFECTS);
11285 if (ada_is_any_packed_array_type (v->type ()))
11286 error (_("cannot slice a packed array"));
11287 return false;
11294 /* Return non-zero iff TYPE represents a System.Address type. */
11297 ada_is_system_address_type (struct type *type)
11299 return (type->name () && strcmp (type->name (), "system__address") == 0);
11304 /* Range types */
11306 /* Scan STR beginning at position K for a discriminant name, and
11307 return the value of that discriminant field of DVAL in *PX. If
11308 PNEW_K is not null, put the position of the character beyond the
11309 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11310 not alter *PX and *PNEW_K if unsuccessful. */
11312 static int
11313 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11314 int *pnew_k)
11316 static std::string storage;
11317 const char *pstart, *pend, *bound;
11318 struct value *bound_val;
11320 if (dval == NULL || str == NULL || str[k] == '\0')
11321 return 0;
11323 pstart = str + k;
11324 pend = strstr (pstart, "__");
11325 if (pend == NULL)
11327 bound = pstart;
11328 k += strlen (bound);
11330 else
11332 int len = pend - pstart;
11334 /* Strip __ and beyond. */
11335 storage = std::string (pstart, len);
11336 bound = storage.c_str ();
11337 k = pend - str;
11340 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11341 if (bound_val == NULL)
11342 return 0;
11344 *px = value_as_long (bound_val);
11345 if (pnew_k != NULL)
11346 *pnew_k = k;
11347 return 1;
11350 /* Value of variable named NAME. Only exact matches are considered.
11351 If no such variable found, then if ERR_MSG is null, returns 0, and
11352 otherwise causes an error with message ERR_MSG. */
11354 static struct value *
11355 get_var_value (const char *name, const char *err_msg)
11357 std::string quoted_name = add_angle_brackets (name);
11359 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11361 std::vector<struct block_symbol> syms
11362 = ada_lookup_symbol_list_worker (lookup_name,
11363 get_selected_block (0),
11364 SEARCH_VFT, 1);
11366 if (syms.size () != 1)
11368 if (err_msg == NULL)
11369 return 0;
11370 else
11371 error (("%s"), err_msg);
11374 return value_of_variable (syms[0].symbol, syms[0].block);
11377 /* Value of integer variable named NAME in the current environment.
11378 If no such variable is found, returns false. Otherwise, sets VALUE
11379 to the variable's value and returns true. */
11381 bool
11382 get_int_var_value (const char *name, LONGEST &value)
11384 struct value *var_val = get_var_value (name, 0);
11386 if (var_val == 0)
11387 return false;
11389 value = value_as_long (var_val);
11390 return true;
11394 /* Return a range type whose base type is that of the range type named
11395 NAME in the current environment, and whose bounds are calculated
11396 from NAME according to the GNAT range encoding conventions.
11397 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11398 corresponding range type from debug information; fall back to using it
11399 if symbol lookup fails. If a new type must be created, allocate it
11400 like ORIG_TYPE was. The bounds information, in general, is encoded
11401 in NAME, the base type given in the named range type. */
11403 static struct type *
11404 to_fixed_range_type (struct type *raw_type, struct value *dval)
11406 const char *name;
11407 struct type *base_type;
11408 const char *subtype_info;
11410 gdb_assert (raw_type != NULL);
11411 gdb_assert (raw_type->name () != NULL);
11413 if (raw_type->code () == TYPE_CODE_RANGE)
11414 base_type = raw_type->target_type ();
11415 else
11416 base_type = raw_type;
11418 name = raw_type->name ();
11419 subtype_info = strstr (name, "___XD");
11420 if (subtype_info == NULL)
11422 LONGEST L = ada_discrete_type_low_bound (raw_type);
11423 LONGEST U = ada_discrete_type_high_bound (raw_type);
11425 if (L < INT_MIN || U > INT_MAX)
11426 return raw_type;
11427 else
11429 type_allocator alloc (raw_type);
11430 return create_static_range_type (alloc, raw_type, L, U);
11433 else
11435 int prefix_len = subtype_info - name;
11436 LONGEST L, U;
11437 struct type *type;
11438 const char *bounds_str;
11439 int n;
11441 subtype_info += 5;
11442 bounds_str = strchr (subtype_info, '_');
11443 n = 1;
11445 if (*subtype_info == 'L')
11447 if (!ada_scan_number (bounds_str, n, &L, &n)
11448 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11449 return raw_type;
11450 if (bounds_str[n] == '_')
11451 n += 2;
11452 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11453 n += 1;
11454 subtype_info += 1;
11456 else
11458 std::string name_buf = std::string (name, prefix_len) + "___L";
11459 if (!get_int_var_value (name_buf.c_str (), L))
11461 lim_warning (_("Unknown lower bound, using 1."));
11462 L = 1;
11466 if (*subtype_info == 'U')
11468 if (!ada_scan_number (bounds_str, n, &U, &n)
11469 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11470 return raw_type;
11472 else
11474 std::string name_buf = std::string (name, prefix_len) + "___U";
11475 if (!get_int_var_value (name_buf.c_str (), U))
11477 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11478 U = L;
11482 type_allocator alloc (raw_type);
11483 type = create_static_range_type (alloc, base_type, L, U);
11484 /* create_static_range_type alters the resulting type's length
11485 to match the size of the base_type, which is not what we want.
11486 Set it back to the original range type's length. */
11487 type->set_length (raw_type->length ());
11488 type->set_name (name);
11489 return type;
11493 /* True iff NAME is the name of a range type. */
11496 ada_is_range_type_name (const char *name)
11498 return (name != NULL && strstr (name, "___XD"));
11502 /* Modular types */
11504 /* True iff TYPE is an Ada modular type. */
11507 ada_is_modular_type (struct type *type)
11509 struct type *subranged_type = get_base_type (type);
11511 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11512 && subranged_type->code () == TYPE_CODE_INT
11513 && subranged_type->is_unsigned ());
11516 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11518 ULONGEST
11519 ada_modulus (struct type *type)
11521 const dynamic_prop &high = type->bounds ()->high;
11523 if (high.is_constant ())
11524 return (ULONGEST) high.const_val () + 1;
11526 /* If TYPE is unresolved, the high bound might be a location list. Return
11527 0, for lack of a better value to return. */
11528 return 0;
11532 /* Ada exception catchpoint support:
11533 ---------------------------------
11535 We support 3 kinds of exception catchpoints:
11536 . catchpoints on Ada exceptions
11537 . catchpoints on unhandled Ada exceptions
11538 . catchpoints on failed assertions
11540 Exceptions raised during failed assertions, or unhandled exceptions
11541 could perfectly be caught with the general catchpoint on Ada exceptions.
11542 However, we can easily differentiate these two special cases, and having
11543 the option to distinguish these two cases from the rest can be useful
11544 to zero-in on certain situations.
11546 Exception catchpoints are a specialized form of breakpoint,
11547 since they rely on inserting breakpoints inside known routines
11548 of the GNAT runtime. The implementation therefore uses a standard
11549 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11550 of breakpoint_ops.
11552 Support in the runtime for exception catchpoints have been changed
11553 a few times already, and these changes affect the implementation
11554 of these catchpoints. In order to be able to support several
11555 variants of the runtime, we use a sniffer that will determine
11556 the runtime variant used by the program being debugged. */
11558 /* Ada's standard exceptions.
11560 The Ada 83 standard also defined Numeric_Error. But there so many
11561 situations where it was unclear from the Ada 83 Reference Manual
11562 (RM) whether Constraint_Error or Numeric_Error should be raised,
11563 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11564 Interpretation saying that anytime the RM says that Numeric_Error
11565 should be raised, the implementation may raise Constraint_Error.
11566 Ada 95 went one step further and pretty much removed Numeric_Error
11567 from the list of standard exceptions (it made it a renaming of
11568 Constraint_Error, to help preserve compatibility when compiling
11569 an Ada83 compiler). As such, we do not include Numeric_Error from
11570 this list of standard exceptions. */
11572 static const char * const standard_exc[] = {
11573 "constraint_error",
11574 "program_error",
11575 "storage_error",
11576 "tasking_error"
11579 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11581 /* A structure that describes how to support exception catchpoints
11582 for a given executable. */
11584 struct exception_support_info
11586 /* The name of the symbol to break on in order to insert
11587 a catchpoint on exceptions. */
11588 const char *catch_exception_sym;
11590 /* The name of the symbol to break on in order to insert
11591 a catchpoint on unhandled exceptions. */
11592 const char *catch_exception_unhandled_sym;
11594 /* The name of the symbol to break on in order to insert
11595 a catchpoint on failed assertions. */
11596 const char *catch_assert_sym;
11598 /* The name of the symbol to break on in order to insert
11599 a catchpoint on exception handling. */
11600 const char *catch_handlers_sym;
11602 /* Assuming that the inferior just triggered an unhandled exception
11603 catchpoint, this function is responsible for returning the address
11604 in inferior memory where the name of that exception is stored.
11605 Return zero if the address could not be computed. */
11606 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11609 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11610 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11612 /* The following exception support info structure describes how to
11613 implement exception catchpoints with the latest version of the
11614 Ada runtime (as of 2019-08-??). */
11616 static const struct exception_support_info default_exception_support_info =
11618 "__gnat_debug_raise_exception", /* catch_exception_sym */
11619 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11620 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11621 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11622 ada_unhandled_exception_name_addr
11625 /* The following exception support info structure describes how to
11626 implement exception catchpoints with an earlier version of the
11627 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11629 static const struct exception_support_info exception_support_info_v0 =
11631 "__gnat_debug_raise_exception", /* catch_exception_sym */
11632 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11633 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11634 "__gnat_begin_handler", /* catch_handlers_sym */
11635 ada_unhandled_exception_name_addr
11638 /* The following exception support info structure describes how to
11639 implement exception catchpoints with a slightly older version
11640 of the Ada runtime. */
11642 static const struct exception_support_info exception_support_info_fallback =
11644 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11645 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11646 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11647 "__gnat_begin_handler", /* catch_handlers_sym */
11648 ada_unhandled_exception_name_addr_from_raise
11651 /* Return nonzero if we can detect the exception support routines
11652 described in EINFO.
11654 This function errors out if an abnormal situation is detected
11655 (for instance, if we find the exception support routines, but
11656 that support is found to be incomplete). */
11658 static int
11659 ada_has_this_exception_support (const struct exception_support_info *einfo)
11661 struct symbol *sym;
11663 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11664 that should be compiled with debugging information. As a result, we
11665 expect to find that symbol in the symtabs. */
11667 sym = standard_lookup (einfo->catch_exception_sym, NULL,
11668 SEARCH_FUNCTION_DOMAIN);
11669 if (sym == NULL)
11671 /* Perhaps we did not find our symbol because the Ada runtime was
11672 compiled without debugging info, or simply stripped of it.
11673 It happens on some GNU/Linux distributions for instance, where
11674 users have to install a separate debug package in order to get
11675 the runtime's debugging info. In that situation, let the user
11676 know why we cannot insert an Ada exception catchpoint.
11678 Note: Just for the purpose of inserting our Ada exception
11679 catchpoint, we could rely purely on the associated minimal symbol.
11680 But we would be operating in degraded mode anyway, since we are
11681 still lacking the debugging info needed later on to extract
11682 the name of the exception being raised (this name is printed in
11683 the catchpoint message, and is also used when trying to catch
11684 a specific exception). We do not handle this case for now. */
11685 bound_minimal_symbol msym
11686 = lookup_minimal_symbol (current_program_space,
11687 einfo->catch_exception_sym);
11689 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11690 error (_("Your Ada runtime appears to be missing some debugging "
11691 "information.\nCannot insert Ada exception catchpoint "
11692 "in this configuration."));
11694 return 0;
11697 /* Make sure that the symbol we found corresponds to a function. */
11699 if (sym->aclass () != LOC_BLOCK)
11700 error (_("Symbol \"%s\" is not a function (class = %d)"),
11701 sym->linkage_name (), sym->aclass ());
11703 sym = standard_lookup (einfo->catch_handlers_sym, NULL,
11704 SEARCH_FUNCTION_DOMAIN);
11705 if (sym == NULL)
11707 bound_minimal_symbol msym
11708 = lookup_minimal_symbol (current_program_space,
11709 einfo->catch_handlers_sym);
11711 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11712 error (_("Your Ada runtime appears to be missing some debugging "
11713 "information.\nCannot insert Ada exception catchpoint "
11714 "in this configuration."));
11716 return 0;
11719 /* Make sure that the symbol we found corresponds to a function. */
11721 if (sym->aclass () != LOC_BLOCK)
11722 error (_("Symbol \"%s\" is not a function (class = %d)"),
11723 sym->linkage_name (), sym->aclass ());
11725 return 1;
11728 /* Inspect the Ada runtime and determine which exception info structure
11729 should be used to provide support for exception catchpoints.
11731 This function will always set the per-inferior exception_info,
11732 or raise an error. */
11734 static void
11735 ada_exception_support_info_sniffer (void)
11737 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11739 /* If the exception info is already known, then no need to recompute it. */
11740 if (data->exception_info != NULL)
11741 return;
11743 /* Check the latest (default) exception support info. */
11744 if (ada_has_this_exception_support (&default_exception_support_info))
11746 data->exception_info = &default_exception_support_info;
11747 return;
11750 /* Try the v0 exception suport info. */
11751 if (ada_has_this_exception_support (&exception_support_info_v0))
11753 data->exception_info = &exception_support_info_v0;
11754 return;
11757 /* Try our fallback exception suport info. */
11758 if (ada_has_this_exception_support (&exception_support_info_fallback))
11760 data->exception_info = &exception_support_info_fallback;
11761 return;
11764 throw_error (NOT_FOUND_ERROR,
11765 _("Could not find Ada runtime exception support"));
11768 /* True iff FRAME is very likely to be that of a function that is
11769 part of the runtime system. This is all very heuristic, but is
11770 intended to be used as advice as to what frames are uninteresting
11771 to most users. */
11773 static int
11774 is_known_support_routine (const frame_info_ptr &frame)
11776 enum language func_lang;
11777 int i;
11778 const char *fullname;
11780 /* If this code does not have any debugging information (no symtab),
11781 This cannot be any user code. */
11783 symtab_and_line sal = find_frame_sal (frame);
11784 if (sal.symtab == NULL)
11785 return 1;
11787 /* If there is a symtab, but the associated source file cannot be
11788 located, then assume this is not user code: Selecting a frame
11789 for which we cannot display the code would not be very helpful
11790 for the user. This should also take care of case such as VxWorks
11791 where the kernel has some debugging info provided for a few units. */
11793 fullname = symtab_to_fullname (sal.symtab);
11794 if (access (fullname, R_OK) != 0)
11795 return 1;
11797 /* Check the unit filename against the Ada runtime file naming.
11798 We also check the name of the objfile against the name of some
11799 known system libraries that sometimes come with debugging info
11800 too. */
11802 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11804 re_comp (known_runtime_file_name_patterns[i]);
11805 if (re_exec (lbasename (sal.symtab->filename)))
11806 return 1;
11807 if (sal.symtab->compunit ()->objfile () != NULL
11808 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11809 return 1;
11812 /* Check whether the function is a GNAT-generated entity. */
11814 gdb::unique_xmalloc_ptr<char> func_name
11815 = find_frame_funname (frame, &func_lang, NULL);
11816 if (func_name == NULL)
11817 return 1;
11819 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11821 re_comp (known_auxiliary_function_name_patterns[i]);
11822 if (re_exec (func_name.get ()))
11823 return 1;
11826 return 0;
11829 /* Find the first frame that contains debugging information and that is not
11830 part of the Ada run-time, starting from FI and moving upward. */
11832 void
11833 ada_find_printable_frame (const frame_info_ptr &initial_fi)
11835 for (frame_info_ptr fi = initial_fi; fi != nullptr; fi = get_prev_frame (fi))
11837 if (!is_known_support_routine (fi))
11839 select_frame (fi);
11840 break;
11846 /* Assuming that the inferior just triggered an unhandled exception
11847 catchpoint, return the address in inferior memory where the name
11848 of the exception is stored.
11850 Return zero if the address could not be computed. */
11852 static CORE_ADDR
11853 ada_unhandled_exception_name_addr (void)
11855 return parse_and_eval_address ("e.full_name");
11858 /* Same as ada_unhandled_exception_name_addr, except that this function
11859 should be used when the inferior uses an older version of the runtime,
11860 where the exception name needs to be extracted from a specific frame
11861 several frames up in the callstack. */
11863 static CORE_ADDR
11864 ada_unhandled_exception_name_addr_from_raise (void)
11866 int frame_level;
11867 frame_info_ptr fi;
11868 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11870 /* To determine the name of this exception, we need to select
11871 the frame corresponding to RAISE_SYM_NAME. This frame is
11872 at least 3 levels up, so we simply skip the first 3 frames
11873 without checking the name of their associated function. */
11874 fi = get_current_frame ();
11875 for (frame_level = 0; frame_level < 3; frame_level += 1)
11876 if (fi != NULL)
11877 fi = get_prev_frame (fi);
11879 while (fi != NULL)
11881 enum language func_lang;
11883 gdb::unique_xmalloc_ptr<char> func_name
11884 = find_frame_funname (fi, &func_lang, NULL);
11885 if (func_name != NULL)
11887 if (strcmp (func_name.get (),
11888 data->exception_info->catch_exception_sym) == 0)
11889 break; /* We found the frame we were looking for... */
11891 fi = get_prev_frame (fi);
11894 if (fi == NULL)
11895 return 0;
11897 select_frame (fi);
11898 return parse_and_eval_address ("id.full_name");
11901 /* Assuming the inferior just triggered an Ada exception catchpoint
11902 (of any type), return the address in inferior memory where the name
11903 of the exception is stored, if applicable.
11905 Assumes the selected frame is the current frame.
11907 Return zero if the address could not be computed, or if not relevant. */
11909 static CORE_ADDR
11910 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11912 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11914 switch (ex)
11916 case ada_catch_exception:
11917 return (parse_and_eval_address ("e.full_name"));
11918 break;
11920 case ada_catch_exception_unhandled:
11921 return data->exception_info->unhandled_exception_name_addr ();
11922 break;
11924 case ada_catch_handlers:
11925 return 0; /* The runtimes does not provide access to the exception
11926 name. */
11927 break;
11929 case ada_catch_assert:
11930 return 0; /* Exception name is not relevant in this case. */
11931 break;
11933 default:
11934 internal_error (_("unexpected catchpoint type"));
11935 break;
11938 return 0; /* Should never be reached. */
11941 /* Assuming the inferior is stopped at an exception catchpoint,
11942 return the message which was associated to the exception, if
11943 available. Return NULL if the message could not be retrieved.
11945 Note: The exception message can be associated to an exception
11946 either through the use of the Raise_Exception function, or
11947 more simply (Ada 2005 and later), via:
11949 raise Exception_Name with "exception message";
11953 static gdb::unique_xmalloc_ptr<char>
11954 ada_exception_message_1 (void)
11956 struct value *e_msg_val;
11957 int e_msg_len;
11959 /* For runtimes that support this feature, the exception message
11960 is passed as an unbounded string argument called "message". */
11961 e_msg_val = parse_and_eval ("message");
11962 if (e_msg_val == NULL)
11963 return NULL; /* Exception message not supported. */
11965 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11966 gdb_assert (e_msg_val != NULL);
11967 e_msg_len = e_msg_val->type ()->length ();
11969 /* If the message string is empty, then treat it as if there was
11970 no exception message. */
11971 if (e_msg_len <= 0)
11972 return NULL;
11974 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11975 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
11976 e_msg_len);
11977 e_msg.get ()[e_msg_len] = '\0';
11979 return e_msg;
11982 /* Same as ada_exception_message_1, except that all exceptions are
11983 contained here (returning NULL instead). */
11985 static gdb::unique_xmalloc_ptr<char>
11986 ada_exception_message (void)
11988 gdb::unique_xmalloc_ptr<char> e_msg;
11992 e_msg = ada_exception_message_1 ();
11994 catch (const gdb_exception_error &e)
11996 e_msg.reset (nullptr);
11999 return e_msg;
12002 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12003 any error that ada_exception_name_addr_1 might cause to be thrown.
12004 When an error is intercepted, a warning with the error message is printed,
12005 and zero is returned. */
12007 static CORE_ADDR
12008 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12010 CORE_ADDR result = 0;
12014 result = ada_exception_name_addr_1 (ex);
12017 catch (const gdb_exception_error &e)
12019 warning (_("failed to get exception name: %s"), e.what ());
12020 return 0;
12023 return result;
12026 static std::string ada_exception_catchpoint_cond_string
12027 (const char *excep_string,
12028 enum ada_exception_catchpoint_kind ex);
12030 /* Ada catchpoints.
12032 In the case of catchpoints on Ada exceptions, the catchpoint will
12033 stop the target on every exception the program throws. When a user
12034 specifies the name of a specific exception, we translate this
12035 request into a condition expression (in text form), and then parse
12036 it into an expression stored in each of the catchpoint's locations.
12037 We then use this condition to check whether the exception that was
12038 raised is the one the user is interested in. If not, then the
12039 target is resumed again. We store the name of the requested
12040 exception, in order to be able to re-set the condition expression
12041 when symbols change. */
12043 /* An instance of this type is used to represent an Ada catchpoint. */
12045 struct ada_catchpoint : public code_breakpoint
12047 ada_catchpoint (struct gdbarch *gdbarch_,
12048 enum ada_exception_catchpoint_kind kind,
12049 const char *cond_string,
12050 bool tempflag,
12051 bool enabled,
12052 bool from_tty,
12053 std::string &&excep_string_)
12054 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
12055 m_excep_string (std::move (excep_string_)),
12056 m_kind (kind)
12058 /* Unlike most code_breakpoint types, Ada catchpoints are
12059 pspace-specific. */
12060 pspace = current_program_space;
12061 enable_state = enabled ? bp_enabled : bp_disabled;
12062 language = language_ada;
12064 re_set (pspace);
12067 struct bp_location *allocate_location () override;
12068 void re_set (program_space *pspace) override;
12069 void check_status (struct bpstat *bs) override;
12070 enum print_stop_action print_it (const bpstat *bs) const override;
12071 bool print_one (const bp_location **) const override;
12072 void print_mention () const override;
12073 void print_recreate (struct ui_file *fp) const override;
12075 private:
12077 /* A helper function for check_status. Returns true if we should
12078 stop for this breakpoint hit. If the user specified a specific
12079 exception, we only want to cause a stop if the program thrown
12080 that exception. */
12081 bool should_stop_exception (const struct bp_location *bl) const;
12083 /* The name of the specific exception the user specified. */
12084 std::string m_excep_string;
12086 /* What kind of catchpoint this is. */
12087 enum ada_exception_catchpoint_kind m_kind;
12090 /* An instance of this type is used to represent an Ada catchpoint
12091 breakpoint location. */
12093 class ada_catchpoint_location : public bp_location
12095 public:
12096 explicit ada_catchpoint_location (ada_catchpoint *owner)
12097 : bp_location (owner, bp_loc_software_breakpoint)
12100 /* The condition that checks whether the exception that was raised
12101 is the specific exception the user specified on catchpoint
12102 creation. */
12103 expression_up excep_cond_expr;
12106 static struct symtab_and_line ada_exception_sal
12107 (enum ada_exception_catchpoint_kind ex);
12109 /* Implement the RE_SET method in the structure for all exception
12110 catchpoint kinds. */
12112 void
12113 ada_catchpoint::re_set (program_space *pspace)
12115 std::vector<symtab_and_line> sals;
12118 struct symtab_and_line sal = ada_exception_sal (m_kind);
12119 sals.push_back (sal);
12121 catch (const gdb_exception_error &ex)
12123 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12124 if (ex.error != NOT_FOUND_ERROR)
12125 throw;
12128 update_breakpoint_locations (this, pspace, sals, {});
12130 /* Reparse the exception conditional expressions. One for each
12131 location. */
12133 /* Nothing to do if there's no specific exception to catch. */
12134 if (m_excep_string.empty ())
12135 return;
12137 /* Same if there are no locations... */
12138 if (!has_locations ())
12139 return;
12141 /* Compute the condition expression in text form, from the specific
12142 exception we want to catch. */
12143 std::string cond_string
12144 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
12146 /* Iterate over all the catchpoint's locations, and parse an
12147 expression for each. */
12148 for (bp_location &bl : locations ())
12150 ada_catchpoint_location &ada_loc
12151 = static_cast<ada_catchpoint_location &> (bl);
12152 expression_up exp;
12154 if (!bl.shlib_disabled)
12156 const char *s;
12158 s = cond_string.c_str ();
12161 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
12163 catch (const gdb_exception_error &e)
12165 warning (_("failed to reevaluate internal exception condition "
12166 "for catchpoint %d: %s"),
12167 number, e.what ());
12171 ada_loc.excep_cond_expr = std::move (exp);
12175 /* Implement the ALLOCATE_LOCATION method in the structure for all
12176 exception catchpoint kinds. */
12178 struct bp_location *
12179 ada_catchpoint::allocate_location ()
12181 return new ada_catchpoint_location (this);
12184 /* See declaration. */
12186 bool
12187 ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
12189 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
12190 const struct ada_catchpoint_location *ada_loc
12191 = (const struct ada_catchpoint_location *) bl;
12192 bool stop;
12194 struct internalvar *var = lookup_internalvar ("_ada_exception");
12195 if (c->m_kind == ada_catch_assert)
12196 clear_internalvar (var);
12197 else
12201 const char *expr;
12203 if (c->m_kind == ada_catch_handlers)
12204 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12205 ".all.occurrence.id");
12206 else
12207 expr = "e";
12209 struct value *exc = parse_and_eval (expr);
12210 set_internalvar (var, exc);
12212 catch (const gdb_exception_error &ex)
12214 clear_internalvar (var);
12218 /* With no specific exception, should always stop. */
12219 if (c->m_excep_string.empty ())
12220 return true;
12222 if (ada_loc->excep_cond_expr == NULL)
12224 /* We will have a NULL expression if back when we were creating
12225 the expressions, this location's had failed to parse. */
12226 return true;
12229 stop = true;
12232 scoped_value_mark mark;
12233 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
12235 catch (const gdb_exception_error &ex)
12237 exception_fprintf (gdb_stderr, ex,
12238 _("Error in testing exception condition:\n"));
12241 return stop;
12244 /* Implement the CHECK_STATUS method in the structure for all
12245 exception catchpoint kinds. */
12247 void
12248 ada_catchpoint::check_status (bpstat *bs)
12250 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12253 /* Implement the PRINT_IT method in the structure for all exception
12254 catchpoint kinds. */
12256 enum print_stop_action
12257 ada_catchpoint::print_it (const bpstat *bs) const
12259 struct ui_out *uiout = current_uiout;
12261 annotate_catchpoint (number);
12263 if (uiout->is_mi_like_p ())
12265 uiout->field_string ("reason",
12266 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12267 uiout->field_string ("disp", bpdisp_text (disposition));
12270 uiout->text (disposition == disp_del
12271 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12272 print_num_locno (bs, uiout);
12273 uiout->text (", ");
12275 /* ada_exception_name_addr relies on the selected frame being the
12276 current frame. Need to do this here because this function may be
12277 called more than once when printing a stop, and below, we'll
12278 select the first frame past the Ada run-time (see
12279 ada_find_printable_frame). */
12280 select_frame (get_current_frame ());
12282 switch (m_kind)
12284 case ada_catch_exception:
12285 case ada_catch_exception_unhandled:
12286 case ada_catch_handlers:
12288 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12289 char exception_name[256];
12291 if (addr != 0)
12293 read_memory (addr, (gdb_byte *) exception_name,
12294 sizeof (exception_name) - 1);
12295 exception_name [sizeof (exception_name) - 1] = '\0';
12297 else
12299 /* For some reason, we were unable to read the exception
12300 name. This could happen if the Runtime was compiled
12301 without debugging info, for instance. In that case,
12302 just replace the exception name by the generic string
12303 "exception" - it will read as "an exception" in the
12304 notification we are about to print. */
12305 memcpy (exception_name, "exception", sizeof ("exception"));
12307 /* In the case of unhandled exception breakpoints, we print
12308 the exception name as "unhandled EXCEPTION_NAME", to make
12309 it clearer to the user which kind of catchpoint just got
12310 hit. We used ui_out_text to make sure that this extra
12311 info does not pollute the exception name in the MI case. */
12312 if (m_kind == ada_catch_exception_unhandled)
12313 uiout->text ("unhandled ");
12314 uiout->field_string ("exception-name", exception_name);
12316 break;
12317 case ada_catch_assert:
12318 /* In this case, the name of the exception is not really
12319 important. Just print "failed assertion" to make it clearer
12320 that his program just hit an assertion-failure catchpoint.
12321 We used ui_out_text because this info does not belong in
12322 the MI output. */
12323 uiout->text ("failed assertion");
12324 break;
12327 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12328 if (exception_message != NULL)
12330 uiout->text (" (");
12331 uiout->field_string ("exception-message", exception_message.get ());
12332 uiout->text (")");
12335 uiout->text (" at ");
12336 ada_find_printable_frame (get_current_frame ());
12338 return PRINT_SRC_AND_LOC;
12341 /* Implement the PRINT_ONE method in the structure for all exception
12342 catchpoint kinds. */
12344 bool
12345 ada_catchpoint::print_one (const bp_location **last_loc) const
12347 struct ui_out *uiout = current_uiout;
12348 struct value_print_options opts;
12350 get_user_print_options (&opts);
12352 if (opts.addressprint)
12353 uiout->field_skip ("addr");
12355 annotate_field (5);
12356 switch (m_kind)
12358 case ada_catch_exception:
12359 if (!m_excep_string.empty ())
12361 std::string msg = string_printf (_("`%s' Ada exception"),
12362 m_excep_string.c_str ());
12364 uiout->field_string ("what", msg);
12366 else
12367 uiout->field_string ("what", "all Ada exceptions");
12369 break;
12371 case ada_catch_exception_unhandled:
12372 uiout->field_string ("what", "unhandled Ada exceptions");
12373 break;
12375 case ada_catch_handlers:
12376 if (!m_excep_string.empty ())
12378 uiout->field_fmt ("what",
12379 _("`%s' Ada exception handlers"),
12380 m_excep_string.c_str ());
12382 else
12383 uiout->field_string ("what", "all Ada exceptions handlers");
12384 break;
12386 case ada_catch_assert:
12387 uiout->field_string ("what", "failed Ada assertions");
12388 break;
12390 default:
12391 internal_error (_("unexpected catchpoint type"));
12392 break;
12395 return true;
12398 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12399 for all exception catchpoint kinds. */
12401 void
12402 ada_catchpoint::print_mention () const
12404 struct ui_out *uiout = current_uiout;
12406 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12407 : _("Catchpoint "));
12408 uiout->field_signed ("bkptno", number);
12409 uiout->text (": ");
12411 switch (m_kind)
12413 case ada_catch_exception:
12414 if (!m_excep_string.empty ())
12416 std::string info = string_printf (_("`%s' Ada exception"),
12417 m_excep_string.c_str ());
12418 uiout->text (info);
12420 else
12421 uiout->text (_("all Ada exceptions"));
12422 break;
12424 case ada_catch_exception_unhandled:
12425 uiout->text (_("unhandled Ada exceptions"));
12426 break;
12428 case ada_catch_handlers:
12429 if (!m_excep_string.empty ())
12431 std::string info
12432 = string_printf (_("`%s' Ada exception handlers"),
12433 m_excep_string.c_str ());
12434 uiout->text (info);
12436 else
12437 uiout->text (_("all Ada exceptions handlers"));
12438 break;
12440 case ada_catch_assert:
12441 uiout->text (_("failed Ada assertions"));
12442 break;
12444 default:
12445 internal_error (_("unexpected catchpoint type"));
12446 break;
12450 /* Implement the PRINT_RECREATE method in the structure for all
12451 exception catchpoint kinds. */
12453 void
12454 ada_catchpoint::print_recreate (struct ui_file *fp) const
12456 switch (m_kind)
12458 case ada_catch_exception:
12459 gdb_printf (fp, "catch exception");
12460 if (!m_excep_string.empty ())
12461 gdb_printf (fp, " %s", m_excep_string.c_str ());
12462 break;
12464 case ada_catch_exception_unhandled:
12465 gdb_printf (fp, "catch exception unhandled");
12466 break;
12468 case ada_catch_handlers:
12469 gdb_printf (fp, "catch handlers");
12470 break;
12472 case ada_catch_assert:
12473 gdb_printf (fp, "catch assert");
12474 break;
12476 default:
12477 internal_error (_("unexpected catchpoint type"));
12479 print_recreate_thread (fp);
12482 /* See ada-lang.h. */
12484 bool
12485 is_ada_exception_catchpoint (breakpoint *bp)
12487 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12490 /* Split the arguments specified in a "catch exception" command.
12491 Set EX to the appropriate catchpoint type.
12492 Set EXCEP_STRING to the name of the specific exception if
12493 specified by the user.
12494 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12495 "catch handlers" command. False otherwise.
12496 If a condition is found at the end of the arguments, the condition
12497 expression is stored in COND_STRING (memory must be deallocated
12498 after use). Otherwise COND_STRING is set to NULL. */
12500 static void
12501 catch_ada_exception_command_split (const char *args,
12502 bool is_catch_handlers_cmd,
12503 enum ada_exception_catchpoint_kind *ex,
12504 std::string *excep_string,
12505 std::string *cond_string)
12507 std::string exception_name;
12509 exception_name = extract_arg (&args);
12510 if (exception_name == "if")
12512 /* This is not an exception name; this is the start of a condition
12513 expression for a catchpoint on all exceptions. So, "un-get"
12514 this token, and set exception_name to NULL. */
12515 exception_name.clear ();
12516 args -= 2;
12519 /* Check to see if we have a condition. */
12521 args = skip_spaces (args);
12522 if (startswith (args, "if")
12523 && (isspace (args[2]) || args[2] == '\0'))
12525 args += 2;
12526 args = skip_spaces (args);
12528 if (args[0] == '\0')
12529 error (_("Condition missing after `if' keyword"));
12530 *cond_string = args;
12532 args += strlen (args);
12535 /* Check that we do not have any more arguments. Anything else
12536 is unexpected. */
12538 if (args[0] != '\0')
12539 error (_("Junk at end of expression"));
12541 if (is_catch_handlers_cmd)
12543 /* Catch handling of exceptions. */
12544 *ex = ada_catch_handlers;
12545 *excep_string = exception_name;
12547 else if (exception_name.empty ())
12549 /* Catch all exceptions. */
12550 *ex = ada_catch_exception;
12551 excep_string->clear ();
12553 else if (exception_name == "unhandled")
12555 /* Catch unhandled exceptions. */
12556 *ex = ada_catch_exception_unhandled;
12557 excep_string->clear ();
12559 else
12561 /* Catch a specific exception. */
12562 *ex = ada_catch_exception;
12563 *excep_string = exception_name;
12567 /* Return the name of the symbol on which we should break in order to
12568 implement a catchpoint of the EX kind. */
12570 static const char *
12571 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12573 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12575 gdb_assert (data->exception_info != NULL);
12577 switch (ex)
12579 case ada_catch_exception:
12580 return (data->exception_info->catch_exception_sym);
12581 break;
12582 case ada_catch_exception_unhandled:
12583 return (data->exception_info->catch_exception_unhandled_sym);
12584 break;
12585 case ada_catch_assert:
12586 return (data->exception_info->catch_assert_sym);
12587 break;
12588 case ada_catch_handlers:
12589 return (data->exception_info->catch_handlers_sym);
12590 break;
12591 default:
12592 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12596 /* Return the condition that will be used to match the current exception
12597 being raised with the exception that the user wants to catch. This
12598 assumes that this condition is used when the inferior just triggered
12599 an exception catchpoint.
12600 EX: the type of catchpoints used for catching Ada exceptions. */
12602 static std::string
12603 ada_exception_catchpoint_cond_string (const char *excep_string,
12604 enum ada_exception_catchpoint_kind ex)
12606 bool is_standard_exc = false;
12607 std::string result;
12609 if (ex == ada_catch_handlers)
12611 /* For exception handlers catchpoints, the condition string does
12612 not use the same parameter as for the other exceptions. */
12613 result = ("long_integer (GNAT_GCC_exception_Access"
12614 "(gcc_exception).all.occurrence.id)");
12616 else
12617 result = "long_integer (e)";
12619 /* The standard exceptions are a special case. They are defined in
12620 runtime units that have been compiled without debugging info; if
12621 EXCEP_STRING is the not-fully-qualified name of a standard
12622 exception (e.g. "constraint_error") then, during the evaluation
12623 of the condition expression, the symbol lookup on this name would
12624 *not* return this standard exception. The catchpoint condition
12625 may then be set only on user-defined exceptions which have the
12626 same not-fully-qualified name (e.g. my_package.constraint_error).
12628 To avoid this unexpected behavior, these standard exceptions are
12629 systematically prefixed by "standard". This means that "catch
12630 exception constraint_error" is rewritten into "catch exception
12631 standard.constraint_error".
12633 If an exception named constraint_error is defined in another package of
12634 the inferior program, then the only way to specify this exception as a
12635 breakpoint condition is to use its fully-qualified named:
12636 e.g. my_package.constraint_error. */
12638 for (const char *name : standard_exc)
12640 if (strcmp (name, excep_string) == 0)
12642 is_standard_exc = true;
12643 break;
12647 result += " = ";
12649 if (is_standard_exc)
12650 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12651 else
12652 string_appendf (result, "long_integer (&%s)", excep_string);
12654 return result;
12657 /* Return the symtab_and_line that should be used to insert an
12658 exception catchpoint of the TYPE kind. */
12660 static struct symtab_and_line
12661 ada_exception_sal (enum ada_exception_catchpoint_kind ex)
12663 const char *sym_name;
12664 struct symbol *sym;
12666 /* First, find out which exception support info to use. */
12667 ada_exception_support_info_sniffer ();
12669 /* Then lookup the function on which we will break in order to catch
12670 the Ada exceptions requested by the user. */
12671 sym_name = ada_exception_sym_name (ex);
12672 sym = standard_lookup (sym_name, NULL, SEARCH_VFT);
12674 if (sym == NULL)
12675 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12676 sym_name);
12678 if (sym->aclass () != LOC_BLOCK)
12679 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12681 return find_function_start_sal (sym, 1);
12684 /* Create an Ada exception catchpoint.
12686 EX_KIND is the kind of exception catchpoint to be created.
12688 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12689 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12690 of the exception to which this catchpoint applies.
12692 COND_STRING, if not empty, is the catchpoint condition.
12694 TEMPFLAG, if nonzero, means that the underlying breakpoint
12695 should be temporary.
12697 FROM_TTY is the usual argument passed to all commands implementations. */
12699 void
12700 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12701 enum ada_exception_catchpoint_kind ex_kind,
12702 std::string &&excep_string,
12703 const std::string &cond_string,
12704 int tempflag,
12705 int enabled,
12706 int from_tty)
12708 /* This works around an obscure issue when an Ada program is
12709 compiled with LTO. */
12710 scoped_restore_current_language save_language (language_ada);
12712 std::unique_ptr<ada_catchpoint> c
12713 (new ada_catchpoint (gdbarch, ex_kind,
12714 cond_string.empty () ? nullptr : cond_string.c_str (),
12715 tempflag, enabled, from_tty,
12716 std::move (excep_string)));
12717 install_breakpoint (0, std::move (c), 1);
12720 /* Implement the "catch exception" command. */
12722 static void
12723 catch_ada_exception_command (const char *arg_entry, int from_tty,
12724 struct cmd_list_element *command)
12726 const char *arg = arg_entry;
12727 struct gdbarch *gdbarch = get_current_arch ();
12728 int tempflag;
12729 enum ada_exception_catchpoint_kind ex_kind;
12730 std::string excep_string;
12731 std::string cond_string;
12733 tempflag = command->context () == CATCH_TEMPORARY;
12735 if (!arg)
12736 arg = "";
12737 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12738 &cond_string);
12739 create_ada_exception_catchpoint (gdbarch, ex_kind,
12740 std::move (excep_string), cond_string,
12741 tempflag, 1 /* enabled */,
12742 from_tty);
12745 /* Implement the "catch handlers" command. */
12747 static void
12748 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12749 struct cmd_list_element *command)
12751 const char *arg = arg_entry;
12752 struct gdbarch *gdbarch = get_current_arch ();
12753 int tempflag;
12754 enum ada_exception_catchpoint_kind ex_kind;
12755 std::string excep_string;
12756 std::string cond_string;
12758 tempflag = command->context () == CATCH_TEMPORARY;
12760 if (!arg)
12761 arg = "";
12762 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12763 &cond_string);
12764 create_ada_exception_catchpoint (gdbarch, ex_kind,
12765 std::move (excep_string), cond_string,
12766 tempflag, 1 /* enabled */,
12767 from_tty);
12770 /* Completion function for the Ada "catch" commands. */
12772 static void
12773 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12774 const char *text, const char *word)
12776 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12778 for (const ada_exc_info &info : exceptions)
12780 if (startswith (info.name, word))
12781 tracker.add_completion (make_unique_xstrdup (info.name));
12785 /* Split the arguments specified in a "catch assert" command.
12787 ARGS contains the command's arguments (or the empty string if
12788 no arguments were passed).
12790 If ARGS contains a condition, set COND_STRING to that condition
12791 (the memory needs to be deallocated after use). */
12793 static void
12794 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12796 args = skip_spaces (args);
12798 /* Check whether a condition was provided. */
12799 if (startswith (args, "if")
12800 && (isspace (args[2]) || args[2] == '\0'))
12802 args += 2;
12803 args = skip_spaces (args);
12804 if (args[0] == '\0')
12805 error (_("condition missing after `if' keyword"));
12806 cond_string.assign (args);
12809 /* Otherwise, there should be no other argument at the end of
12810 the command. */
12811 else if (args[0] != '\0')
12812 error (_("Junk at end of arguments."));
12815 /* Implement the "catch assert" command. */
12817 static void
12818 catch_assert_command (const char *arg_entry, int from_tty,
12819 struct cmd_list_element *command)
12821 const char *arg = arg_entry;
12822 struct gdbarch *gdbarch = get_current_arch ();
12823 int tempflag;
12824 std::string cond_string;
12826 tempflag = command->context () == CATCH_TEMPORARY;
12828 if (!arg)
12829 arg = "";
12830 catch_ada_assert_command_split (arg, cond_string);
12831 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12832 {}, cond_string,
12833 tempflag, 1 /* enabled */,
12834 from_tty);
12837 /* Return non-zero if the symbol SYM is an Ada exception object. */
12839 static int
12840 ada_is_exception_sym (struct symbol *sym)
12842 const char *type_name = sym->type ()->name ();
12844 return (sym->aclass () != LOC_TYPEDEF
12845 && sym->aclass () != LOC_BLOCK
12846 && sym->aclass () != LOC_CONST
12847 && sym->aclass () != LOC_UNRESOLVED
12848 && type_name != NULL && strcmp (type_name, "exception") == 0);
12851 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12852 Ada exception object. This matches all exceptions except the ones
12853 defined by the Ada language. */
12855 static int
12856 ada_is_non_standard_exception_sym (struct symbol *sym)
12858 if (!ada_is_exception_sym (sym))
12859 return 0;
12861 for (const char *name : standard_exc)
12862 if (strcmp (sym->linkage_name (), name) == 0)
12863 return 0; /* A standard exception. */
12865 /* Numeric_Error is also a standard exception, so exclude it.
12866 See the STANDARD_EXC description for more details as to why
12867 this exception is not listed in that array. */
12868 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12869 return 0;
12871 return 1;
12874 /* A helper function for std::sort, comparing two struct ada_exc_info
12875 objects.
12877 The comparison is determined first by exception name, and then
12878 by exception address. */
12880 bool
12881 ada_exc_info::operator< (const ada_exc_info &other) const
12883 int result;
12885 result = strcmp (name, other.name);
12886 if (result < 0)
12887 return true;
12888 if (result == 0 && addr < other.addr)
12889 return true;
12890 return false;
12893 bool
12894 ada_exc_info::operator== (const ada_exc_info &other) const
12896 return addr == other.addr && strcmp (name, other.name) == 0;
12899 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12900 routine, but keeping the first SKIP elements untouched.
12902 All duplicates are also removed. */
12904 static void
12905 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12906 int skip)
12908 std::sort (exceptions->begin () + skip, exceptions->end ());
12909 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12910 exceptions->end ());
12913 /* Add all exceptions defined by the Ada standard whose name match
12914 a regular expression.
12916 If PREG is not NULL, then this regexp_t object is used to
12917 perform the symbol name matching. Otherwise, no name-based
12918 filtering is performed.
12920 EXCEPTIONS is a vector of exceptions to which matching exceptions
12921 gets pushed. */
12923 static void
12924 ada_add_standard_exceptions (compiled_regex *preg,
12925 std::vector<ada_exc_info> *exceptions)
12927 for (const char *name : standard_exc)
12929 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12931 symbol_name_match_type match_type = name_match_type_from_name (name);
12932 lookup_name_info lookup_name (name, match_type);
12934 symbol_name_matcher_ftype *match_name
12935 = ada_get_symbol_name_matcher (lookup_name);
12937 /* Iterate over all objfiles irrespective of scope or linker
12938 namespaces so we get all exceptions anywhere in the
12939 progspace. */
12940 for (objfile *objfile : current_program_space->objfiles ())
12942 for (minimal_symbol *msymbol : objfile->msymbols ())
12944 if (match_name (msymbol->linkage_name (), lookup_name,
12945 nullptr)
12946 && msymbol->type () != mst_solib_trampoline)
12948 ada_exc_info info
12949 = {name, msymbol->value_address (objfile)};
12951 exceptions->push_back (info);
12959 /* Add all Ada exceptions defined locally and accessible from the given
12960 FRAME.
12962 If PREG is not NULL, then this regexp_t object is used to
12963 perform the symbol name matching. Otherwise, no name-based
12964 filtering is performed.
12966 EXCEPTIONS is a vector of exceptions to which matching exceptions
12967 gets pushed. */
12969 static void
12970 ada_add_exceptions_from_frame (compiled_regex *preg,
12971 const frame_info_ptr &frame,
12972 std::vector<ada_exc_info> *exceptions)
12974 const struct block *block = get_frame_block (frame, 0);
12976 while (block != 0)
12978 for (struct symbol *sym : block_iterator_range (block))
12980 switch (sym->aclass ())
12982 case LOC_TYPEDEF:
12983 case LOC_BLOCK:
12984 case LOC_CONST:
12985 break;
12986 default:
12987 if (ada_is_exception_sym (sym))
12989 struct ada_exc_info info = {sym->print_name (),
12990 sym->value_address ()};
12992 exceptions->push_back (info);
12996 if (block->function () != NULL)
12997 break;
12998 block = block->superblock ();
13002 /* Return true if NAME matches PREG or if PREG is NULL. */
13004 static bool
13005 name_matches_regex (const char *name, compiled_regex *preg)
13007 return (preg == NULL
13008 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13011 /* Add all exceptions defined globally whose name name match
13012 a regular expression, excluding standard exceptions.
13014 The reason we exclude standard exceptions is that they need
13015 to be handled separately: Standard exceptions are defined inside
13016 a runtime unit which is normally not compiled with debugging info,
13017 and thus usually do not show up in our symbol search. However,
13018 if the unit was in fact built with debugging info, we need to
13019 exclude them because they would duplicate the entry we found
13020 during the special loop that specifically searches for those
13021 standard exceptions.
13023 If PREG is not NULL, then this regexp_t object is used to
13024 perform the symbol name matching. Otherwise, no name-based
13025 filtering is performed.
13027 EXCEPTIONS is a vector of exceptions to which matching exceptions
13028 gets pushed. */
13030 static void
13031 ada_add_global_exceptions (compiled_regex *preg,
13032 std::vector<ada_exc_info> *exceptions)
13034 /* In Ada, the symbol "search name" is a linkage name, whereas the
13035 regular expression used to do the matching refers to the natural
13036 name. So match against the decoded name. */
13037 expand_symtabs_matching (NULL,
13038 lookup_name_info::match_any (),
13039 [&] (const char *search_name)
13041 std::string decoded = ada_decode (search_name);
13042 return name_matches_regex (decoded.c_str (), preg);
13044 NULL,
13045 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13046 SEARCH_VAR_DOMAIN,
13047 [&] (enum language lang)
13049 /* Try to skip non-Ada CUs. */
13050 return lang == language_ada;
13053 /* Iterate over all objfiles irrespective of scope or linker namespaces
13054 so we get all exceptions anywhere in the progspace. */
13055 for (objfile *objfile : current_program_space->objfiles ())
13057 for (compunit_symtab *s : objfile->compunits ())
13059 const struct blockvector *bv = s->blockvector ();
13060 int i;
13062 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13064 const struct block *b = bv->block (i);
13066 for (struct symbol *sym : block_iterator_range (b))
13067 if (ada_is_non_standard_exception_sym (sym)
13068 && name_matches_regex (sym->natural_name (), preg))
13070 struct ada_exc_info info
13071 = {sym->print_name (), sym->value_address ()};
13073 exceptions->push_back (info);
13080 /* Implements ada_exceptions_list with the regular expression passed
13081 as a regex_t, rather than a string.
13083 If not NULL, PREG is used to filter out exceptions whose names
13084 do not match. Otherwise, all exceptions are listed. */
13086 static std::vector<ada_exc_info>
13087 ada_exceptions_list_1 (compiled_regex *preg)
13089 std::vector<ada_exc_info> result;
13090 int prev_len;
13092 /* First, list the known standard exceptions. These exceptions
13093 need to be handled separately, as they are usually defined in
13094 runtime units that have been compiled without debugging info. */
13096 ada_add_standard_exceptions (preg, &result);
13098 /* Next, find all exceptions whose scope is local and accessible
13099 from the currently selected frame. */
13101 if (has_stack_frames ())
13103 prev_len = result.size ();
13104 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13105 &result);
13106 if (result.size () > prev_len)
13107 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13110 /* Add all exceptions whose scope is global. */
13112 prev_len = result.size ();
13113 ada_add_global_exceptions (preg, &result);
13114 if (result.size () > prev_len)
13115 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13117 return result;
13120 /* Return a vector of ada_exc_info.
13122 If REGEXP is NULL, all exceptions are included in the result.
13123 Otherwise, it should contain a valid regular expression,
13124 and only the exceptions whose names match that regular expression
13125 are included in the result.
13127 The exceptions are sorted in the following order:
13128 - Standard exceptions (defined by the Ada language), in
13129 alphabetical order;
13130 - Exceptions only visible from the current frame, in
13131 alphabetical order;
13132 - Exceptions whose scope is global, in alphabetical order. */
13134 std::vector<ada_exc_info>
13135 ada_exceptions_list (const char *regexp)
13137 if (regexp == NULL)
13138 return ada_exceptions_list_1 (NULL);
13140 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13141 return ada_exceptions_list_1 (&reg);
13144 /* Implement the "info exceptions" command. */
13146 static void
13147 info_exceptions_command (const char *regexp, int from_tty)
13149 struct gdbarch *gdbarch = get_current_arch ();
13151 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13153 if (regexp != NULL)
13154 gdb_printf
13155 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13156 else
13157 gdb_printf (_("All defined Ada exceptions:\n"));
13159 for (const ada_exc_info &info : exceptions)
13160 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13164 /* Language vector */
13166 /* symbol_name_matcher_ftype adapter for wild_match. */
13168 static bool
13169 do_wild_match (const char *symbol_search_name,
13170 const lookup_name_info &lookup_name,
13171 completion_match_result *comp_match_res)
13173 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13176 /* symbol_name_matcher_ftype adapter for full_match. */
13178 static bool
13179 do_full_match (const char *symbol_search_name,
13180 const lookup_name_info &lookup_name,
13181 completion_match_result *comp_match_res)
13183 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13185 /* If both symbols start with "_ada_", just let the loop below
13186 handle the comparison. However, if only the symbol name starts
13187 with "_ada_", skip the prefix and let the match proceed as
13188 usual. */
13189 if (startswith (symbol_search_name, "_ada_")
13190 && !startswith (lname, "_ada"))
13191 symbol_search_name += 5;
13192 /* Likewise for ghost entities. */
13193 if (startswith (symbol_search_name, "___ghost_")
13194 && !startswith (lname, "___ghost_"))
13195 symbol_search_name += 9;
13197 int uscore_count = 0;
13198 while (*lname != '\0')
13200 if (*symbol_search_name != *lname)
13202 if (*symbol_search_name == 'B' && uscore_count == 2
13203 && symbol_search_name[1] == '_')
13205 symbol_search_name += 2;
13206 while (isdigit (*symbol_search_name))
13207 ++symbol_search_name;
13208 if (symbol_search_name[0] == '_'
13209 && symbol_search_name[1] == '_')
13211 symbol_search_name += 2;
13212 continue;
13215 return false;
13218 if (*symbol_search_name == '_')
13219 ++uscore_count;
13220 else
13221 uscore_count = 0;
13223 ++symbol_search_name;
13224 ++lname;
13227 return is_name_suffix (symbol_search_name);
13230 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13232 static bool
13233 do_exact_match (const char *symbol_search_name,
13234 const lookup_name_info &lookup_name,
13235 completion_match_result *comp_match_res)
13237 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13240 /* Build the Ada lookup name for LOOKUP_NAME. */
13242 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13244 std::string_view user_name = lookup_name.name ();
13246 if (!user_name.empty () && user_name[0] == '<')
13248 if (user_name.back () == '>')
13249 m_encoded_name = user_name.substr (1, user_name.size () - 2);
13250 else
13251 m_encoded_name = user_name.substr (1, user_name.size () - 1);
13252 m_encoded_p = true;
13253 m_verbatim_p = true;
13254 m_wild_match_p = false;
13255 m_standard_p = false;
13257 else
13259 m_verbatim_p = false;
13261 m_encoded_p = user_name.find ("__") != std::string_view::npos;
13263 if (!m_encoded_p)
13265 const char *folded = ada_fold_name (user_name);
13266 m_encoded_name = ada_encode_1 (folded, false);
13267 if (m_encoded_name.empty ())
13268 m_encoded_name = user_name;
13270 else
13271 m_encoded_name = user_name;
13273 /* Handle the 'package Standard' special case. See description
13274 of m_standard_p. */
13275 if (startswith (m_encoded_name.c_str (), "standard__"))
13277 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13278 m_standard_p = true;
13280 else
13281 m_standard_p = false;
13283 m_decoded_name = ada_decode (m_encoded_name.c_str (), true, false, false);
13285 /* If the name contains a ".", then the user is entering a fully
13286 qualified entity name, and the match must not be done in wild
13287 mode. Similarly, if the user wants to complete what looks
13288 like an encoded name, the match must not be done in wild
13289 mode. Also, in the standard__ special case always do
13290 non-wild matching. */
13291 m_wild_match_p
13292 = (lookup_name.match_type () != symbol_name_match_type::FULL
13293 && !m_encoded_p
13294 && !m_standard_p
13295 && user_name.find ('.') == std::string::npos);
13299 /* symbol_name_matcher_ftype method for Ada. This only handles
13300 completion mode. */
13302 static bool
13303 ada_symbol_name_matches (const char *symbol_search_name,
13304 const lookup_name_info &lookup_name,
13305 completion_match_result *comp_match_res)
13307 return lookup_name.ada ().matches (symbol_search_name,
13308 lookup_name.match_type (),
13309 comp_match_res);
13312 /* A name matcher that matches the symbol name exactly, with
13313 strcmp. */
13315 static bool
13316 literal_symbol_name_matcher (const char *symbol_search_name,
13317 const lookup_name_info &lookup_name,
13318 completion_match_result *comp_match_res)
13320 std::string_view name_view = lookup_name.name ();
13322 if (lookup_name.completion_mode ()
13323 ? (strncmp (symbol_search_name, name_view.data (),
13324 name_view.size ()) == 0)
13325 : symbol_search_name == name_view)
13327 if (comp_match_res != NULL)
13328 comp_match_res->set_match (symbol_search_name);
13329 return true;
13331 else
13332 return false;
13335 /* Implement the "get_symbol_name_matcher" language_defn method for
13336 Ada. */
13338 static symbol_name_matcher_ftype *
13339 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13341 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13342 return literal_symbol_name_matcher;
13344 if (lookup_name.completion_mode ())
13345 return ada_symbol_name_matches;
13346 else
13348 if (lookup_name.ada ().wild_match_p ())
13349 return do_wild_match;
13350 else if (lookup_name.ada ().verbatim_p ())
13351 return do_exact_match;
13352 else
13353 return do_full_match;
13357 /* Class representing the Ada language. */
13359 class ada_language : public language_defn
13361 public:
13362 ada_language ()
13363 : language_defn (language_ada)
13364 { /* Nothing. */ }
13366 /* See language.h. */
13368 const char *name () const override
13369 { return "ada"; }
13371 /* See language.h. */
13373 const char *natural_name () const override
13374 { return "Ada"; }
13376 /* See language.h. */
13378 const std::vector<const char *> &filename_extensions () const override
13380 static const std::vector<const char *> extensions
13381 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13382 return extensions;
13385 /* Print an array element index using the Ada syntax. */
13387 void print_array_index (struct type *index_type,
13388 LONGEST index,
13389 struct ui_file *stream,
13390 const value_print_options *options) const override
13392 struct value *index_value = val_atr (index_type, index);
13394 value_print (index_value, stream, options);
13395 gdb_printf (stream, " => ");
13398 /* Implement the "read_var_value" language_defn method for Ada. */
13400 struct value *read_var_value (struct symbol *var,
13401 const struct block *var_block,
13402 const frame_info_ptr &frame) const override
13404 /* The only case where default_read_var_value is not sufficient
13405 is when VAR is a renaming... */
13406 if (frame != nullptr)
13408 const struct block *frame_block = get_frame_block (frame, NULL);
13409 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13410 return ada_read_renaming_var_value (var, frame_block);
13413 /* This is a typical case where we expect the default_read_var_value
13414 function to work. */
13415 return language_defn::read_var_value (var, var_block, frame);
13418 /* See language.h. */
13419 bool symbol_printing_suppressed (struct symbol *symbol) const override
13421 return symbol->is_artificial ();
13424 /* See language.h. */
13425 struct value *value_string (struct gdbarch *gdbarch,
13426 const char *ptr, ssize_t len) const override
13428 struct type *type = language_string_char_type (this, gdbarch);
13429 value *val = ::value_string (ptr, len, type);
13430 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13431 strings that are arrays of characters, so fix the type now. */
13432 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13433 val->type ()->set_code (TYPE_CODE_ARRAY);
13434 return val;
13437 /* See language.h. */
13438 void language_arch_info (struct gdbarch *gdbarch,
13439 struct language_arch_info *lai) const override
13441 const struct builtin_type *builtin = builtin_type (gdbarch);
13443 /* Helper function to allow shorter lines below. */
13444 auto add = [&] (struct type *t)
13446 lai->add_primitive_type (t);
13449 type_allocator alloc (gdbarch);
13450 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13451 0, "integer"));
13452 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13453 0, "long_integer"));
13454 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13455 0, "short_integer"));
13456 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13457 1, "character");
13458 lai->set_string_char_type (char_type);
13459 add (char_type);
13460 add (init_character_type (alloc, 16, 1, "wide_character"));
13461 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13462 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13463 "float", gdbarch_float_format (gdbarch)));
13464 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13465 "long_float", gdbarch_double_format (gdbarch)));
13466 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13467 0, "long_long_integer"));
13468 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13469 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
13470 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13471 "long_long_float",
13472 gdbarch_long_double_format (gdbarch)));
13473 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13474 0, "natural"));
13475 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13476 0, "positive"));
13477 add (builtin->builtin_void);
13479 struct type *system_addr_ptr
13480 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13481 "void"));
13482 system_addr_ptr->set_name ("system__address");
13483 add (system_addr_ptr);
13485 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13486 type. This is a signed integral type whose size is the same as
13487 the size of addresses. */
13488 unsigned int addr_length = system_addr_ptr->length ();
13489 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13490 "storage_offset"));
13492 lai->set_bool_type (builtin->builtin_bool);
13495 /* See language.h. */
13497 bool iterate_over_symbols
13498 (const struct block *block, const lookup_name_info &name,
13499 domain_search_flags domain,
13500 gdb::function_view<symbol_found_callback_ftype> callback) const override
13502 std::vector<struct block_symbol> results
13503 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13504 for (block_symbol &sym : results)
13506 if (!callback (&sym))
13507 return false;
13510 return true;
13513 /* See language.h. */
13514 bool sniff_from_mangled_name
13515 (const char *mangled,
13516 gdb::unique_xmalloc_ptr<char> *out) const override
13518 std::string demangled = ada_decode (mangled);
13520 *out = NULL;
13522 if (demangled != mangled && demangled[0] != '<')
13524 /* Set the gsymbol language to Ada, but still return 0.
13525 Two reasons for that:
13527 1. For Ada, we prefer computing the symbol's decoded name
13528 on the fly rather than pre-compute it, in order to save
13529 memory (Ada projects are typically very large).
13531 2. There are some areas in the definition of the GNAT
13532 encoding where, with a bit of bad luck, we might be able
13533 to decode a non-Ada symbol, generating an incorrect
13534 demangled name (Eg: names ending with "TB" for instance
13535 are identified as task bodies and so stripped from
13536 the decoded name returned).
13538 Returning true, here, but not setting *DEMANGLED, helps us get
13539 a little bit of the best of both worlds. Because we're last,
13540 we should not affect any of the other languages that were
13541 able to demangle the symbol before us; we get to correctly
13542 tag Ada symbols as such; and even if we incorrectly tagged a
13543 non-Ada symbol, which should be rare, any routing through the
13544 Ada language should be transparent (Ada tries to behave much
13545 like C/C++ with non-Ada symbols). */
13546 return true;
13549 return false;
13552 /* See language.h. */
13554 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13555 int options) const override
13557 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13560 /* See language.h. */
13562 void print_type (struct type *type, const char *varstring,
13563 struct ui_file *stream, int show, int level,
13564 const struct type_print_options *flags) const override
13566 ada_print_type (type, varstring, stream, show, level, flags);
13569 /* See language.h. */
13571 const char *word_break_characters (void) const override
13573 return ada_completer_word_break_characters;
13576 /* See language.h. */
13578 void collect_symbol_completion_matches (completion_tracker &tracker,
13579 complete_symbol_mode mode,
13580 symbol_name_match_type name_match_type,
13581 const char *text, const char *word,
13582 enum type_code code) const override
13584 const struct block *b, *surrounding_static_block = 0;
13586 gdb_assert (code == TYPE_CODE_UNDEF);
13588 lookup_name_info lookup_name (text, name_match_type, true);
13590 /* First, look at the partial symtab symbols. */
13591 expand_symtabs_matching (NULL,
13592 lookup_name,
13593 NULL,
13594 NULL,
13595 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13596 SEARCH_ALL_DOMAINS);
13598 /* At this point scan through the misc symbol vectors and add each
13599 symbol you find to the list. Eventually we want to ignore
13600 anything that isn't a text symbol (everything else will be
13601 handled by the psymtab code above). */
13603 for (objfile *objfile : current_program_space->objfiles ())
13605 for (minimal_symbol *msymbol : objfile->msymbols ())
13607 QUIT;
13609 if (completion_skip_symbol (mode, msymbol))
13610 continue;
13612 language symbol_language = msymbol->language ();
13614 /* Ada minimal symbols won't have their language set to Ada. If
13615 we let completion_list_add_name compare using the
13616 default/C-like matcher, then when completing e.g., symbols in a
13617 package named "pck", we'd match internal Ada symbols like
13618 "pckS", which are invalid in an Ada expression, unless you wrap
13619 them in '<' '>' to request a verbatim match.
13621 Unfortunately, some Ada encoded names successfully demangle as
13622 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13623 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13624 with the wrong language set. Paper over that issue here. */
13625 if (symbol_language == language_unknown
13626 || symbol_language == language_cplus)
13627 symbol_language = language_ada;
13629 completion_list_add_name (tracker,
13630 symbol_language,
13631 msymbol->linkage_name (),
13632 lookup_name, text, word);
13636 /* Search upwards from currently selected frame (so that we can
13637 complete on local vars. */
13639 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13641 if (b->is_static_block ())
13642 surrounding_static_block = b; /* For elmin of dups */
13644 for (struct symbol *sym : block_iterator_range (b))
13646 if (completion_skip_symbol (mode, sym))
13647 continue;
13649 completion_list_add_name (tracker,
13650 sym->language (),
13651 sym->linkage_name (),
13652 lookup_name, text, word);
13656 /* Go through the symtabs and check the externs and statics for
13657 symbols which match. */
13659 for (objfile *objfile : current_program_space->objfiles ())
13661 for (compunit_symtab *s : objfile->compunits ())
13663 QUIT;
13664 b = s->blockvector ()->global_block ();
13665 for (struct symbol *sym : block_iterator_range (b))
13667 if (completion_skip_symbol (mode, sym))
13668 continue;
13670 completion_list_add_name (tracker,
13671 sym->language (),
13672 sym->linkage_name (),
13673 lookup_name, text, word);
13678 for (objfile *objfile : current_program_space->objfiles ())
13680 for (compunit_symtab *s : objfile->compunits ())
13682 QUIT;
13683 b = s->blockvector ()->static_block ();
13684 /* Don't do this block twice. */
13685 if (b == surrounding_static_block)
13686 continue;
13687 for (struct symbol *sym : block_iterator_range (b))
13689 if (completion_skip_symbol (mode, sym))
13690 continue;
13692 completion_list_add_name (tracker,
13693 sym->language (),
13694 sym->linkage_name (),
13695 lookup_name, text, word);
13701 /* See language.h. */
13703 gdb::unique_xmalloc_ptr<char> watch_location_expression
13704 (struct type *type, CORE_ADDR addr) const override
13706 type = check_typedef (check_typedef (type)->target_type ());
13707 std::string name = type_to_string (type);
13708 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13711 /* See language.h. */
13713 void value_print (struct value *val, struct ui_file *stream,
13714 const struct value_print_options *options) const override
13716 return ada_value_print (val, stream, options);
13719 /* See language.h. */
13721 void value_print_inner
13722 (struct value *val, struct ui_file *stream, int recurse,
13723 const struct value_print_options *options) const override
13725 return ada_value_print_inner (val, stream, recurse, options);
13728 /* See language.h. */
13730 struct block_symbol lookup_symbol_nonlocal
13731 (const char *name, const struct block *block,
13732 const domain_search_flags domain) const override
13734 struct block_symbol sym;
13736 sym = ada_lookup_symbol (name,
13737 (block == nullptr
13738 ? nullptr
13739 : block->static_block ()),
13740 domain);
13741 if (sym.symbol != NULL)
13742 return sym;
13744 /* If we haven't found a match at this point, try the primitive
13745 types. In other languages, this search is performed before
13746 searching for global symbols in order to short-circuit that
13747 global-symbol search if it happens that the name corresponds
13748 to a primitive type. But we cannot do the same in Ada, because
13749 it is perfectly legitimate for a program to declare a type which
13750 has the same name as a standard type. If looking up a type in
13751 that situation, we have traditionally ignored the primitive type
13752 in favor of user-defined types. This is why, unlike most other
13753 languages, we search the primitive types this late and only after
13754 having searched the global symbols without success. */
13756 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
13758 struct gdbarch *gdbarch;
13760 if (block == NULL)
13761 gdbarch = current_inferior ()->arch ();
13762 else
13763 gdbarch = block->gdbarch ();
13764 sym.symbol
13765 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13766 if (sym.symbol != NULL)
13767 return sym;
13770 return {};
13773 /* See language.h. */
13775 int parser (struct parser_state *ps) const override
13777 warnings_issued = 0;
13778 return ada_parse (ps);
13781 /* See language.h. */
13783 void emitchar (int ch, struct type *chtype,
13784 struct ui_file *stream, int quoter) const override
13786 ada_emit_char (ch, chtype, stream, quoter, 1);
13789 /* See language.h. */
13791 void printchar (int ch, struct type *chtype,
13792 struct ui_file *stream) const override
13794 ada_printchar (ch, chtype, stream);
13797 /* See language.h. */
13799 void printstr (struct ui_file *stream, struct type *elttype,
13800 const gdb_byte *string, unsigned int length,
13801 const char *encoding, int force_ellipses,
13802 const struct value_print_options *options) const override
13804 /* ada_printstr doesn't handle UTF-8 too well, but we want this
13805 for lazy-string printing. Defer this case to the generic
13806 code. */
13807 if (encoding != nullptr && strcasecmp (encoding, "UTF-8") == 0)
13808 generic_printstr (stream, elttype, string, length, encoding,
13809 force_ellipses, '"', 0, options);
13810 else
13811 ada_printstr (stream, elttype, string, length, encoding,
13812 force_ellipses, options);
13815 /* See language.h. */
13817 void print_typedef (struct type *type, struct symbol *new_symbol,
13818 struct ui_file *stream) const override
13820 ada_print_typedef (type, new_symbol, stream);
13823 /* See language.h. */
13825 bool is_string_type_p (struct type *type) const override
13827 return ada_is_string_type (type);
13830 /* See language.h. */
13832 bool is_array_like (struct type *type) const override
13834 return (ada_is_constrained_packed_array_type (type)
13835 || ada_is_array_descriptor_type (type));
13838 /* See language.h. */
13840 struct value *to_array (struct value *val) const override
13841 { return ada_coerce_to_simple_array (val); }
13843 /* See language.h. */
13845 const char *struct_too_deep_ellipsis () const override
13846 { return "(...)"; }
13848 /* See language.h. */
13850 bool c_style_arrays_p () const override
13851 { return false; }
13853 /* See language.h. */
13855 bool store_sym_names_in_linkage_form_p () const override
13856 { return true; }
13858 /* See language.h. */
13860 const struct lang_varobj_ops *varobj_ops () const override
13861 { return &ada_varobj_ops; }
13863 protected:
13864 /* See language.h. */
13866 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13867 (const lookup_name_info &lookup_name) const override
13869 return ada_get_symbol_name_matcher (lookup_name);
13873 /* Single instance of the Ada language class. */
13875 static ada_language ada_language_defn;
13877 /* Command-list for the "set/show ada" prefix command. */
13878 static struct cmd_list_element *set_ada_list;
13879 static struct cmd_list_element *show_ada_list;
13881 /* This module's 'new_objfile' observer. */
13883 static void
13884 ada_new_objfile_observer (struct objfile *objfile)
13886 ada_clear_symbol_cache (objfile->pspace ());
13889 /* This module's 'free_objfile' observer. */
13891 static void
13892 ada_free_objfile_observer (struct objfile *objfile)
13894 ada_clear_symbol_cache (objfile->pspace ());
13897 /* Charsets known to GNAT. */
13898 static const char * const gnat_source_charsets[] =
13900 /* Note that code below assumes that the default comes first.
13901 Latin-1 is the default here, because that is also GNAT's
13902 default. */
13903 "ISO-8859-1",
13904 "ISO-8859-2",
13905 "ISO-8859-3",
13906 "ISO-8859-4",
13907 "ISO-8859-5",
13908 "ISO-8859-15",
13909 "CP437",
13910 "CP850",
13911 /* Note that this value is special-cased in the encoder and
13912 decoder. */
13913 ada_utf8,
13914 nullptr
13917 void _initialize_ada_language ();
13918 void
13919 _initialize_ada_language ()
13921 add_setshow_prefix_cmd
13922 ("ada", no_class,
13923 _("Prefix command for changing Ada-specific settings."),
13924 _("Generic command for showing Ada-specific settings."),
13925 &set_ada_list, &show_ada_list,
13926 &setlist, &showlist);
13928 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13929 &trust_pad_over_xvs, _("\
13930 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13931 Show whether an optimization trusting PAD types over XVS types is activated."),
13932 _("\
13933 This is related to the encoding used by the GNAT compiler. The debugger\n\
13934 should normally trust the contents of PAD types, but certain older versions\n\
13935 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13936 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13937 work around this bug. It is always safe to turn this option \"off\", but\n\
13938 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13939 this option to \"off\" unless necessary."),
13940 NULL, NULL, &set_ada_list, &show_ada_list);
13942 add_setshow_boolean_cmd ("print-signatures", class_vars,
13943 &print_signatures, _("\
13944 Control the display of functions in overloads selection menu."), _("\
13945 Show how functions in overloads selection menu will be displayed."),
13946 _("\
13947 When enabled, formal and return types are shown."),
13948 NULL, NULL, &set_ada_list, &show_ada_list);
13950 ada_source_charset = gnat_source_charsets[0];
13951 add_setshow_enum_cmd ("source-charset", class_files,
13952 gnat_source_charsets,
13953 &ada_source_charset, _("\
13954 Set the Ada source character set."), _("\
13955 Show the Ada source character set."), _("\
13956 The character set used for Ada source files.\n\
13957 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13958 nullptr, nullptr,
13959 &set_ada_list, &show_ada_list);
13961 add_catch_command ("exception", _("\
13962 Catch Ada exceptions, when raised.\n\
13963 Usage: catch exception [ARG] [if CONDITION]\n\
13964 Without any argument, stop when any Ada exception is raised.\n\
13965 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13966 being raised does not have a handler (and will therefore lead to the task's\n\
13967 termination).\n\
13968 Otherwise, the catchpoint only stops when the name of the exception being\n\
13969 raised is the same as ARG.\n\
13970 CONDITION is a boolean expression that is evaluated to see whether the\n\
13971 exception should cause a stop."),
13972 catch_ada_exception_command,
13973 catch_ada_completer,
13974 CATCH_PERMANENT,
13975 CATCH_TEMPORARY);
13977 add_catch_command ("handlers", _("\
13978 Catch Ada exceptions, when handled.\n\
13979 Usage: catch handlers [ARG] [if CONDITION]\n\
13980 Without any argument, stop when any Ada exception is handled.\n\
13981 With an argument, catch only exceptions with the given name.\n\
13982 CONDITION is a boolean expression that is evaluated to see whether the\n\
13983 exception should cause a stop."),
13984 catch_ada_handlers_command,
13985 catch_ada_completer,
13986 CATCH_PERMANENT,
13987 CATCH_TEMPORARY);
13988 add_catch_command ("assert", _("\
13989 Catch failed Ada assertions, when raised.\n\
13990 Usage: catch assert [if CONDITION]\n\
13991 CONDITION is a boolean expression that is evaluated to see whether the\n\
13992 exception should cause a stop."),
13993 catch_assert_command,
13994 NULL,
13995 CATCH_PERMANENT,
13996 CATCH_TEMPORARY);
13998 add_info ("exceptions", info_exceptions_command,
13999 _("\
14000 List all Ada exception names.\n\
14001 Usage: info exceptions [REGEXP]\n\
14002 If a regular expression is passed as an argument, only those matching\n\
14003 the regular expression are listed."));
14005 add_setshow_prefix_cmd ("ada", class_maintenance,
14006 _("Set Ada maintenance-related variables."),
14007 _("Show Ada maintenance-related variables."),
14008 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14009 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14011 add_setshow_boolean_cmd
14012 ("ignore-descriptive-types", class_maintenance,
14013 &ada_ignore_descriptive_types_p,
14014 _("Set whether descriptive types generated by GNAT should be ignored."),
14015 _("Show whether descriptive types generated by GNAT should be ignored."),
14016 _("\
14017 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14018 DWARF attribute."),
14019 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14021 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14022 htab_eq_string,
14023 NULL, xcalloc, xfree);
14025 /* The ada-lang observers. */
14026 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14027 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14028 "ada-lang");
14029 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14030 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14032 #ifdef GDB_SELF_TEST
14033 selftests::register_test ("ada-decode", ada_decode_tests);
14034 #endif