[gdb/dap] Fix dap for python < 3.8
[binutils-gdb.git] / gdb / ada-lang.c
blob53d53e0ffa588669f22432f665f0559055ca411e
1 /* Ada language support routines for GDB, the GNU debugger.
3 Copyright (C) 1992-2023 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 "defs.h"
22 #include <ctype.h>
23 #include "gdbsupport/gdb_regex.h"
24 #include "frame.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "gdbcmd.h"
28 #include "expression.h"
29 #include "parser-defs.h"
30 #include "language.h"
31 #include "varobj.h"
32 #include "inferior.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "breakpoint.h"
36 #include "gdbcore.h"
37 #include "hashtab.h"
38 #include "gdbsupport/gdb_obstack.h"
39 #include "ada-lang.h"
40 #include "completer.h"
41 #include "ui-out.h"
42 #include "block.h"
43 #include "infcall.h"
44 #include "annotate.h"
45 #include "valprint.h"
46 #include "source.h"
47 #include "observable.h"
48 #include "stack.h"
49 #include "typeprint.h"
50 #include "namespace.h"
51 #include "cli/cli-style.h"
52 #include "cli/cli-decode.h"
54 #include "value.h"
55 #include "mi/mi-common.h"
56 #include "arch-utils.h"
57 #include "cli/cli-utils.h"
58 #include "gdbsupport/function-view.h"
59 #include "gdbsupport/byte-vector.h"
60 #include "gdbsupport/selftest.h"
61 #include <algorithm>
62 #include "ada-exp.h"
63 #include "charset.h"
64 #include "ax-gdb.h"
66 static struct type *desc_base_type (struct type *);
68 static struct type *desc_bounds_type (struct type *);
70 static struct value *desc_bounds (struct value *);
72 static int fat_pntr_bounds_bitpos (struct type *);
74 static int fat_pntr_bounds_bitsize (struct type *);
76 static struct type *desc_data_target_type (struct type *);
78 static struct value *desc_data (struct value *);
80 static int fat_pntr_data_bitpos (struct type *);
82 static int fat_pntr_data_bitsize (struct type *);
84 static struct value *desc_one_bound (struct value *, int, int);
86 static int desc_bound_bitpos (struct type *, int, int);
88 static int desc_bound_bitsize (struct type *, int, int);
90 static struct type *desc_index_type (struct type *, int);
92 static int desc_arity (struct type *);
94 static int ada_args_match (struct symbol *, struct value **, int);
96 static struct value *make_array_descriptor (struct type *, struct value *);
98 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
99 const struct block *,
100 const lookup_name_info &lookup_name,
101 domain_enum, struct objfile *);
103 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
104 const struct block *,
105 const lookup_name_info &lookup_name,
106 domain_enum, int, int *);
108 static int is_nonfunction (const std::vector<struct block_symbol> &);
110 static void add_defn_to_vec (std::vector<struct block_symbol> &,
111 struct symbol *,
112 const struct block *);
114 static int possible_user_operator_p (enum exp_opcode, struct value **);
116 static const char *ada_decoded_op_name (enum exp_opcode);
118 static int numeric_type_p (struct type *);
120 static int integer_type_p (struct type *);
122 static int scalar_type_p (struct type *);
124 static int discrete_type_p (struct type *);
126 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
127 int, int);
129 static struct type *ada_find_parallel_type_with_name (struct type *,
130 const char *);
132 static int is_dynamic_field (struct type *, int);
134 static struct type *to_fixed_variant_branch_type (struct type *,
135 const gdb_byte *,
136 CORE_ADDR, struct value *);
138 static struct type *to_fixed_array_type (struct type *, struct value *, int);
140 static struct type *to_fixed_range_type (struct type *, struct value *);
142 static struct type *to_static_fixed_type (struct type *);
143 static struct type *static_unwrap_type (struct type *type);
145 static struct value *unwrap_value (struct value *);
147 static struct type *constrained_packed_array_type (struct type *, long *);
149 static struct type *decode_constrained_packed_array_type (struct type *);
151 static long decode_packed_array_bitsize (struct type *);
153 static struct value *decode_constrained_packed_array (struct value *);
155 static int ada_is_unconstrained_packed_array_type (struct type *);
157 static struct value *value_subscript_packed (struct value *, int,
158 struct value **);
160 static struct value *coerce_unspec_val_to_type (struct value *,
161 struct type *);
163 static int lesseq_defined_than (struct symbol *, struct symbol *);
165 static int equiv_types (struct type *, struct type *);
167 static int is_name_suffix (const char *);
169 static int advance_wild_match (const char **, const char *, char);
171 static bool wild_match (const char *name, const char *patn);
173 static struct value *ada_coerce_ref (struct value *);
175 static LONGEST pos_atr (struct value *);
177 static struct value *val_atr (struct type *, LONGEST);
179 static struct symbol *standard_lookup (const char *, const struct block *,
180 domain_enum);
182 static struct value *ada_search_struct_field (const char *, struct value *, int,
183 struct type *);
185 static int find_struct_field (const char *, struct type *, int,
186 struct type **, int *, int *, int *, int *);
188 static int ada_resolve_function (std::vector<struct block_symbol> &,
189 struct value **, int, const char *,
190 struct type *, bool);
192 static int ada_is_direct_array_type (struct type *);
194 static struct value *ada_index_struct_field (int, struct value *, int,
195 struct type *);
197 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
200 static struct type *ada_find_any_type (const char *name);
202 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
203 (const lookup_name_info &lookup_name);
205 static int symbols_are_identical_enums
206 (const std::vector<struct block_symbol> &syms);
208 static int ada_identical_enum_types_p (struct type *type1, struct type *type2);
211 /* The character set used for source files. */
212 static const char *ada_source_charset;
214 /* The string "UTF-8". This is here so we can check for the UTF-8
215 charset using == rather than strcmp. */
216 static const char ada_utf8[] = "UTF-8";
218 /* Each entry in the UTF-32 case-folding table is of this form. */
219 struct utf8_entry
221 /* The start and end, inclusive, of this range of codepoints. */
222 uint32_t start, end;
223 /* The delta to apply to get the upper-case form. 0 if this is
224 already upper-case. */
225 int upper_delta;
226 /* The delta to apply to get the lower-case form. 0 if this is
227 already lower-case. */
228 int lower_delta;
230 bool operator< (uint32_t val) const
232 return end < val;
236 static const utf8_entry ada_case_fold[] =
238 #include "ada-casefold.h"
243 static const char ada_completer_word_break_characters[] =
244 #ifdef VMS
245 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
246 #else
247 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
248 #endif
250 /* The name of the symbol to use to get the name of the main subprogram. */
251 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
252 = "__gnat_ada_main_program_name";
254 /* Limit on the number of warnings to raise per expression evaluation. */
255 static int warning_limit = 2;
257 /* Number of warning messages issued; reset to 0 by cleanups after
258 expression evaluation. */
259 static int warnings_issued = 0;
261 static const char * const known_runtime_file_name_patterns[] = {
262 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
265 static const char * const known_auxiliary_function_name_patterns[] = {
266 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
269 /* Maintenance-related settings for this module. */
271 static struct cmd_list_element *maint_set_ada_cmdlist;
272 static struct cmd_list_element *maint_show_ada_cmdlist;
274 /* The "maintenance ada set/show ignore-descriptive-type" value. */
276 static bool ada_ignore_descriptive_types_p = false;
278 /* Inferior-specific data. */
280 /* Per-inferior data for this module. */
282 struct ada_inferior_data
284 /* The ada__tags__type_specific_data type, which is used when decoding
285 tagged types. With older versions of GNAT, this type was directly
286 accessible through a component ("tsd") in the object tag. But this
287 is no longer the case, so we cache it for each inferior. */
288 struct type *tsd_type = nullptr;
290 /* The exception_support_info data. This data is used to determine
291 how to implement support for Ada exception catchpoints in a given
292 inferior. */
293 const struct exception_support_info *exception_info = nullptr;
296 /* Our key to this module's inferior data. */
297 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
299 /* Return our inferior data for the given inferior (INF).
301 This function always returns a valid pointer to an allocated
302 ada_inferior_data structure. If INF's inferior data has not
303 been previously set, this functions creates a new one with all
304 fields set to zero, sets INF's inferior to it, and then returns
305 a pointer to that newly allocated ada_inferior_data. */
307 static struct ada_inferior_data *
308 get_ada_inferior_data (struct inferior *inf)
310 struct ada_inferior_data *data;
312 data = ada_inferior_data.get (inf);
313 if (data == NULL)
314 data = ada_inferior_data.emplace (inf);
316 return data;
319 /* Perform all necessary cleanups regarding our module's inferior data
320 that is required after the inferior INF just exited. */
322 static void
323 ada_inferior_exit (struct inferior *inf)
325 ada_inferior_data.clear (inf);
329 /* program-space-specific data. */
331 /* The result of a symbol lookup to be stored in our symbol cache. */
333 struct cache_entry
335 /* The name used to perform the lookup. */
336 std::string name;
337 /* The namespace used during the lookup. */
338 domain_enum domain = UNDEF_DOMAIN;
339 /* The symbol returned by the lookup, or NULL if no matching symbol
340 was found. */
341 struct symbol *sym = nullptr;
342 /* The block where the symbol was found, or NULL if no matching
343 symbol was found. */
344 const struct block *block = nullptr;
347 /* The symbol cache uses this type when searching. */
349 struct cache_entry_search
351 const char *name;
352 domain_enum domain;
354 hashval_t hash () const
356 /* This must agree with hash_cache_entry, below. */
357 return htab_hash_string (name);
361 /* Hash function for cache_entry. */
363 static hashval_t
364 hash_cache_entry (const void *v)
366 const cache_entry *entry = (const cache_entry *) v;
367 return htab_hash_string (entry->name.c_str ());
370 /* Equality function for cache_entry. */
372 static int
373 eq_cache_entry (const void *a, const void *b)
375 const cache_entry *entrya = (const cache_entry *) a;
376 const cache_entry_search *entryb = (const cache_entry_search *) b;
378 return entrya->domain == entryb->domain && entrya->name == entryb->name;
381 /* Key to our per-program-space data. */
382 static const registry<program_space>::key<htab, htab_deleter>
383 ada_pspace_data_handle;
385 /* Return this module's data for the given program space (PSPACE).
386 If not is found, add a zero'ed one now.
388 This function always returns a valid object. */
390 static htab_t
391 get_ada_pspace_data (struct program_space *pspace)
393 htab_t data = ada_pspace_data_handle.get (pspace);
394 if (data == nullptr)
396 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
397 htab_delete_entry<cache_entry>,
398 xcalloc, xfree);
399 ada_pspace_data_handle.set (pspace, data);
402 return data;
405 /* Utilities */
407 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
408 all typedef layers have been peeled. Otherwise, return TYPE.
410 Normally, we really expect a typedef type to only have 1 typedef layer.
411 In other words, we really expect the target type of a typedef type to be
412 a non-typedef type. This is particularly true for Ada units, because
413 the language does not have a typedef vs not-typedef distinction.
414 In that respect, the Ada compiler has been trying to eliminate as many
415 typedef definitions in the debugging information, since they generally
416 do not bring any extra information (we still use typedef under certain
417 circumstances related mostly to the GNAT encoding).
419 Unfortunately, we have seen situations where the debugging information
420 generated by the compiler leads to such multiple typedef layers. For
421 instance, consider the following example with stabs:
423 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
424 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
426 This is an error in the debugging information which causes type
427 pck__float_array___XUP to be defined twice, and the second time,
428 it is defined as a typedef of a typedef.
430 This is on the fringe of legality as far as debugging information is
431 concerned, and certainly unexpected. But it is easy to handle these
432 situations correctly, so we can afford to be lenient in this case. */
434 static struct type *
435 ada_typedef_target_type (struct type *type)
437 while (type->code () == TYPE_CODE_TYPEDEF)
438 type = type->target_type ();
439 return type;
442 /* Given DECODED_NAME a string holding a symbol name in its
443 decoded form (ie using the Ada dotted notation), returns
444 its unqualified name. */
446 static const char *
447 ada_unqualified_name (const char *decoded_name)
449 const char *result;
451 /* If the decoded name starts with '<', it means that the encoded
452 name does not follow standard naming conventions, and thus that
453 it is not your typical Ada symbol name. Trying to unqualify it
454 is therefore pointless and possibly erroneous. */
455 if (decoded_name[0] == '<')
456 return decoded_name;
458 result = strrchr (decoded_name, '.');
459 if (result != NULL)
460 result++; /* Skip the dot... */
461 else
462 result = decoded_name;
464 return result;
467 /* Return a string starting with '<', followed by STR, and '>'. */
469 static std::string
470 add_angle_brackets (const char *str)
472 return string_printf ("<%s>", str);
475 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
476 suffix of FIELD_NAME beginning "___". */
478 static int
479 field_name_match (const char *field_name, const char *target)
481 int len = strlen (target);
483 return
484 (strncmp (field_name, target, len) == 0
485 && (field_name[len] == '\0'
486 || (startswith (field_name + len, "___")
487 && strcmp (field_name + strlen (field_name) - 6,
488 "___XVN") != 0)));
492 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
493 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
494 and return its index. This function also handles fields whose name
495 have ___ suffixes because the compiler sometimes alters their name
496 by adding such a suffix to represent fields with certain constraints.
497 If the field could not be found, return a negative number if
498 MAYBE_MISSING is set. Otherwise raise an error. */
501 ada_get_field_index (const struct type *type, const char *field_name,
502 int maybe_missing)
504 int fieldno;
505 struct type *struct_type = check_typedef ((struct type *) type);
507 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
508 if (field_name_match (struct_type->field (fieldno).name (), field_name))
509 return fieldno;
511 if (!maybe_missing)
512 error (_("Unable to find field %s in struct %s. Aborting"),
513 field_name, struct_type->name ());
515 return -1;
518 /* The length of the prefix of NAME prior to any "___" suffix. */
521 ada_name_prefix_len (const char *name)
523 if (name == NULL)
524 return 0;
525 else
527 const char *p = strstr (name, "___");
529 if (p == NULL)
530 return strlen (name);
531 else
532 return p - name;
536 /* Return non-zero if SUFFIX is a suffix of STR.
537 Return zero if STR is null. */
539 static int
540 is_suffix (const char *str, const char *suffix)
542 int len1, len2;
544 if (str == NULL)
545 return 0;
546 len1 = strlen (str);
547 len2 = strlen (suffix);
548 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
551 /* The contents of value VAL, treated as a value of type TYPE. The
552 result is an lval in memory if VAL is. */
554 static struct value *
555 coerce_unspec_val_to_type (struct value *val, struct type *type)
557 type = ada_check_typedef (type);
558 if (val->type () == type)
559 return val;
560 else
562 struct value *result;
564 if (val->optimized_out ())
565 result = value::allocate_optimized_out (type);
566 else if (val->lazy ()
567 /* Be careful not to make a lazy not_lval value. */
568 || (val->lval () != not_lval
569 && type->length () > val->type ()->length ()))
570 result = value::allocate_lazy (type);
571 else
573 result = value::allocate (type);
574 val->contents_copy (result, 0, 0, type->length ());
576 result->set_component_location (val);
577 result->set_bitsize (val->bitsize ());
578 result->set_bitpos (val->bitpos ());
579 if (result->lval () == lval_memory)
580 result->set_address (val->address ());
581 return result;
585 static const gdb_byte *
586 cond_offset_host (const gdb_byte *valaddr, long offset)
588 if (valaddr == NULL)
589 return NULL;
590 else
591 return valaddr + offset;
594 static CORE_ADDR
595 cond_offset_target (CORE_ADDR address, long offset)
597 if (address == 0)
598 return 0;
599 else
600 return address + offset;
603 /* Issue a warning (as for the definition of warning in utils.c, but
604 with exactly one argument rather than ...), unless the limit on the
605 number of warnings has passed during the evaluation of the current
606 expression. */
608 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
609 provided by "complaint". */
610 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
612 static void
613 lim_warning (const char *format, ...)
615 va_list args;
617 va_start (args, format);
618 warnings_issued += 1;
619 if (warnings_issued <= warning_limit)
620 vwarning (format, args);
622 va_end (args);
625 /* Maximum value of a SIZE-byte signed integer type. */
626 static LONGEST
627 max_of_size (int size)
629 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
631 return top_bit | (top_bit - 1);
634 /* Minimum value of a SIZE-byte signed integer type. */
635 static LONGEST
636 min_of_size (int size)
638 return -max_of_size (size) - 1;
641 /* Maximum value of a SIZE-byte unsigned integer type. */
642 static ULONGEST
643 umax_of_size (int size)
645 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
647 return top_bit | (top_bit - 1);
650 /* Maximum value of integral type T, as a signed quantity. */
651 static LONGEST
652 max_of_type (struct type *t)
654 if (t->is_unsigned ())
655 return (LONGEST) umax_of_size (t->length ());
656 else
657 return max_of_size (t->length ());
660 /* Minimum value of integral type T, as a signed quantity. */
661 static LONGEST
662 min_of_type (struct type *t)
664 if (t->is_unsigned ())
665 return 0;
666 else
667 return min_of_size (t->length ());
670 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
671 LONGEST
672 ada_discrete_type_high_bound (struct type *type)
674 type = resolve_dynamic_type (type, {}, 0);
675 switch (type->code ())
677 case TYPE_CODE_RANGE:
679 const dynamic_prop &high = type->bounds ()->high;
681 if (high.is_constant ())
682 return high.const_val ();
683 else
685 gdb_assert (high.kind () == PROP_UNDEFINED);
687 /* This happens when trying to evaluate a type's dynamic bound
688 without a live target. There is nothing relevant for us to
689 return here, so return 0. */
690 return 0;
693 case TYPE_CODE_ENUM:
694 return type->field (type->num_fields () - 1).loc_enumval ();
695 case TYPE_CODE_BOOL:
696 return 1;
697 case TYPE_CODE_CHAR:
698 case TYPE_CODE_INT:
699 return max_of_type (type);
700 default:
701 error (_("Unexpected type in ada_discrete_type_high_bound."));
705 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
706 LONGEST
707 ada_discrete_type_low_bound (struct type *type)
709 type = resolve_dynamic_type (type, {}, 0);
710 switch (type->code ())
712 case TYPE_CODE_RANGE:
714 const dynamic_prop &low = type->bounds ()->low;
716 if (low.is_constant ())
717 return low.const_val ();
718 else
720 gdb_assert (low.kind () == PROP_UNDEFINED);
722 /* This happens when trying to evaluate a type's dynamic bound
723 without a live target. There is nothing relevant for us to
724 return here, so return 0. */
725 return 0;
728 case TYPE_CODE_ENUM:
729 return type->field (0).loc_enumval ();
730 case TYPE_CODE_BOOL:
731 return 0;
732 case TYPE_CODE_CHAR:
733 case TYPE_CODE_INT:
734 return min_of_type (type);
735 default:
736 error (_("Unexpected type in ada_discrete_type_low_bound."));
740 /* The identity on non-range types. For range types, the underlying
741 non-range scalar type. */
743 static struct type *
744 get_base_type (struct type *type)
746 while (type != NULL && type->code () == TYPE_CODE_RANGE)
748 if (type == type->target_type () || type->target_type () == NULL)
749 return type;
750 type = type->target_type ();
752 return type;
755 /* Return a decoded version of the given VALUE. This means returning
756 a value whose type is obtained by applying all the GNAT-specific
757 encodings, making the resulting type a static but standard description
758 of the initial type. */
760 struct value *
761 ada_get_decoded_value (struct value *value)
763 struct type *type = ada_check_typedef (value->type ());
765 if (ada_is_array_descriptor_type (type)
766 || (ada_is_constrained_packed_array_type (type)
767 && type->code () != TYPE_CODE_PTR))
769 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
770 value = ada_coerce_to_simple_array_ptr (value);
771 else
772 value = ada_coerce_to_simple_array (value);
774 else
775 value = ada_to_fixed_value (value);
777 return value;
780 /* Same as ada_get_decoded_value, but with the given TYPE.
781 Because there is no associated actual value for this type,
782 the resulting type might be a best-effort approximation in
783 the case of dynamic types. */
785 struct type *
786 ada_get_decoded_type (struct type *type)
788 type = to_static_fixed_type (type);
789 if (ada_is_constrained_packed_array_type (type))
790 type = ada_coerce_to_simple_array_type (type);
791 return type;
796 /* Language Selection */
798 /* If the main procedure is written in Ada, then return its name.
799 The result is good until the next call. Return NULL if the main
800 procedure doesn't appear to be in Ada. */
802 const char *
803 ada_main_name ()
805 struct bound_minimal_symbol msym;
806 static gdb::unique_xmalloc_ptr<char> main_program_name;
808 /* For Ada, the name of the main procedure is stored in a specific
809 string constant, generated by the binder. Look for that symbol,
810 extract its address, and then read that string. If we didn't find
811 that string, then most probably the main procedure is not written
812 in Ada. */
813 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
815 if (msym.minsym != NULL)
817 CORE_ADDR main_program_name_addr = msym.value_address ();
818 if (main_program_name_addr == 0)
819 error (_("Invalid address for Ada main program name."));
821 /* Force trust_readonly, because we always want to fetch this
822 string from the executable, not from inferior memory. If the
823 user changes the exec-file and invokes "start", we want to
824 pick the "main" from the new executable, not one that may
825 come from the still-live inferior. */
826 scoped_restore save_trust_readonly
827 = make_scoped_restore (&trust_readonly, true);
828 main_program_name = target_read_string (main_program_name_addr, 1024);
829 return main_program_name.get ();
832 /* The main procedure doesn't seem to be in Ada. */
833 return NULL;
836 /* Symbols */
838 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
839 of NULLs. */
841 const struct ada_opname_map ada_opname_table[] = {
842 {"Oadd", "\"+\"", BINOP_ADD},
843 {"Osubtract", "\"-\"", BINOP_SUB},
844 {"Omultiply", "\"*\"", BINOP_MUL},
845 {"Odivide", "\"/\"", BINOP_DIV},
846 {"Omod", "\"mod\"", BINOP_MOD},
847 {"Orem", "\"rem\"", BINOP_REM},
848 {"Oexpon", "\"**\"", BINOP_EXP},
849 {"Olt", "\"<\"", BINOP_LESS},
850 {"Ole", "\"<=\"", BINOP_LEQ},
851 {"Ogt", "\">\"", BINOP_GTR},
852 {"Oge", "\">=\"", BINOP_GEQ},
853 {"Oeq", "\"=\"", BINOP_EQUAL},
854 {"One", "\"/=\"", BINOP_NOTEQUAL},
855 {"Oand", "\"and\"", BINOP_BITWISE_AND},
856 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
857 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
858 {"Oconcat", "\"&\"", BINOP_CONCAT},
859 {"Oabs", "\"abs\"", UNOP_ABS},
860 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
861 {"Oadd", "\"+\"", UNOP_PLUS},
862 {"Osubtract", "\"-\"", UNOP_NEG},
863 {NULL, NULL}
866 /* If STR is a decoded version of a compiler-provided suffix (like the
867 "[cold]" in "symbol[cold]"), return true. Otherwise, return
868 false. */
870 static bool
871 is_compiler_suffix (const char *str)
873 gdb_assert (*str == '[');
874 ++str;
875 while (*str != '\0' && isalpha (*str))
876 ++str;
877 /* We accept a missing "]" in order to support completion. */
878 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
881 /* Append a non-ASCII character to RESULT. */
882 static void
883 append_hex_encoded (std::string &result, uint32_t one_char)
885 if (one_char <= 0xff)
887 result.append ("U");
888 result.append (phex (one_char, 1));
890 else if (one_char <= 0xffff)
892 result.append ("W");
893 result.append (phex (one_char, 2));
895 else
897 result.append ("WW");
898 result.append (phex (one_char, 4));
902 /* Return a string that is a copy of the data in STORAGE, with
903 non-ASCII characters replaced by the appropriate hex encoding. A
904 template is used because, for UTF-8, we actually want to work with
905 UTF-32 codepoints. */
906 template<typename T>
907 std::string
908 copy_and_hex_encode (struct obstack *storage)
910 const T *chars = (T *) obstack_base (storage);
911 int num_chars = obstack_object_size (storage) / sizeof (T);
912 std::string result;
913 for (int i = 0; i < num_chars; ++i)
915 if (chars[i] <= 0x7f)
917 /* The host character set has to be a superset of ASCII, as
918 are all the other character sets we can use. */
919 result.push_back (chars[i]);
921 else
922 append_hex_encoded (result, chars[i]);
924 return result;
927 /* The "encoded" form of DECODED, according to GNAT conventions. If
928 THROW_ERRORS, throw an error if invalid operator name is found.
929 Otherwise, return the empty string in that case. */
931 static std::string
932 ada_encode_1 (const char *decoded, bool throw_errors)
934 if (decoded == NULL)
935 return {};
937 std::string encoding_buffer;
938 bool saw_non_ascii = false;
939 for (const char *p = decoded; *p != '\0'; p += 1)
941 if ((*p & 0x80) != 0)
942 saw_non_ascii = true;
944 if (*p == '.')
945 encoding_buffer.append ("__");
946 else if (*p == '[' && is_compiler_suffix (p))
948 encoding_buffer = encoding_buffer + "." + (p + 1);
949 if (encoding_buffer.back () == ']')
950 encoding_buffer.pop_back ();
951 break;
953 else if (*p == '"')
955 const struct ada_opname_map *mapping;
957 for (mapping = ada_opname_table;
958 mapping->encoded != NULL
959 && !startswith (p, mapping->decoded); mapping += 1)
961 if (mapping->encoded == NULL)
963 if (throw_errors)
964 error (_("invalid Ada operator name: %s"), p);
965 else
966 return {};
968 encoding_buffer.append (mapping->encoded);
969 break;
971 else
972 encoding_buffer.push_back (*p);
975 /* If a non-ASCII character is seen, we must convert it to the
976 appropriate hex form. As this is more expensive, we keep track
977 of whether it is even necessary. */
978 if (saw_non_ascii)
980 auto_obstack storage;
981 bool is_utf8 = ada_source_charset == ada_utf8;
984 convert_between_encodings
985 (host_charset (),
986 is_utf8 ? HOST_UTF32 : ada_source_charset,
987 (const gdb_byte *) encoding_buffer.c_str (),
988 encoding_buffer.length (), 1,
989 &storage, translit_none);
991 catch (const gdb_exception &)
993 static bool warned = false;
995 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
996 might like to know why. */
997 if (!warned)
999 warned = true;
1000 warning (_("charset conversion failure for '%s'.\n"
1001 "You may have the wrong value for 'set ada source-charset'."),
1002 encoding_buffer.c_str ());
1005 /* We don't try to recover from errors. */
1006 return encoding_buffer;
1009 if (is_utf8)
1010 return copy_and_hex_encode<uint32_t> (&storage);
1011 return copy_and_hex_encode<gdb_byte> (&storage);
1014 return encoding_buffer;
1017 /* Find the entry for C in the case-folding table. Return nullptr if
1018 the entry does not cover C. */
1019 static const utf8_entry *
1020 find_case_fold_entry (uint32_t c)
1022 auto iter = std::lower_bound (std::begin (ada_case_fold),
1023 std::end (ada_case_fold),
1025 if (iter == std::end (ada_case_fold)
1026 || c < iter->start
1027 || c > iter->end)
1028 return nullptr;
1029 return &*iter;
1032 /* Return NAME folded to lower case, or, if surrounded by single
1033 quotes, unfolded, but with the quotes stripped away. If
1034 THROW_ON_ERROR is true, encoding failures will throw an exception
1035 rather than emitting a warning. Result good to next call. */
1037 static const char *
1038 ada_fold_name (gdb::string_view name, bool throw_on_error = false)
1040 static std::string fold_storage;
1042 if (!name.empty () && name[0] == '\'')
1043 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
1044 else
1046 /* Why convert to UTF-32 and implement our own case-folding,
1047 rather than convert to wchar_t and use the platform's
1048 functions? I'm glad you asked.
1050 The main problem is that GNAT implements an unusual rule for
1051 case folding. For ASCII letters, letters in single-byte
1052 encodings (such as ISO-8859-*), and Unicode letters that fit
1053 in a single byte (i.e., code point is <= 0xff), the letter is
1054 folded to lower case. Other Unicode letters are folded to
1055 upper case.
1057 This rule means that the code must be able to examine the
1058 value of the character. And, some hosts do not use Unicode
1059 for wchar_t, so examining the value of such characters is
1060 forbidden. */
1061 auto_obstack storage;
1064 convert_between_encodings
1065 (host_charset (), HOST_UTF32,
1066 (const gdb_byte *) name.data (),
1067 name.length (), 1,
1068 &storage, translit_none);
1070 catch (const gdb_exception &)
1072 if (throw_on_error)
1073 throw;
1075 static bool warned = false;
1077 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1078 might like to know why. */
1079 if (!warned)
1081 warned = true;
1082 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1083 "This normally should not happen, please file a bug report."),
1084 gdb::to_string (name).c_str (), host_charset ());
1087 /* We don't try to recover from errors; just return the
1088 original string. */
1089 fold_storage = gdb::to_string (name);
1090 return fold_storage.c_str ();
1093 bool is_utf8 = ada_source_charset == ada_utf8;
1094 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1095 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1096 for (int i = 0; i < num_chars; ++i)
1098 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1099 if (entry != nullptr)
1101 uint32_t low = chars[i] + entry->lower_delta;
1102 if (!is_utf8 || low <= 0xff)
1103 chars[i] = low;
1104 else
1105 chars[i] = chars[i] + entry->upper_delta;
1109 /* Now convert back to ordinary characters. */
1110 auto_obstack reconverted;
1113 convert_between_encodings (HOST_UTF32,
1114 host_charset (),
1115 (const gdb_byte *) chars,
1116 num_chars * sizeof (uint32_t),
1117 sizeof (uint32_t),
1118 &reconverted,
1119 translit_none);
1120 obstack_1grow (&reconverted, '\0');
1121 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1123 catch (const gdb_exception &)
1125 if (throw_on_error)
1126 throw;
1128 static bool warned = false;
1130 /* Converting back from UTF-32 shouldn't normally fail, but
1131 there are some host encodings without upper/lower
1132 equivalence. */
1133 if (!warned)
1135 warned = true;
1136 warning (_("could not convert the lower-cased variant of '%s'\n"
1137 "from UTF-32 to the host encoding (%s)."),
1138 gdb::to_string (name).c_str (), host_charset ());
1141 /* We don't try to recover from errors; just return the
1142 original string. */
1143 fold_storage = gdb::to_string (name);
1147 return fold_storage.c_str ();
1150 /* The "encoded" form of DECODED, according to GNAT conventions. If
1151 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1152 with <...> quoting are not folded in any case. */
1154 std::string
1155 ada_encode (const char *decoded, bool fold)
1157 if (fold && decoded[0] != '<')
1158 decoded = ada_fold_name (decoded);
1159 return ada_encode_1 (decoded, true);
1162 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1164 static int
1165 is_lower_alphanum (const char c)
1167 return (isdigit (c) || (isalpha (c) && islower (c)));
1170 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1171 This function saves in LEN the length of that same symbol name but
1172 without either of these suffixes:
1173 . .{DIGIT}+
1174 . ${DIGIT}+
1175 . ___{DIGIT}+
1176 . __{DIGIT}+.
1178 These are suffixes introduced by the compiler for entities such as
1179 nested subprogram for instance, in order to avoid name clashes.
1180 They do not serve any purpose for the debugger. */
1182 static void
1183 ada_remove_trailing_digits (const char *encoded, int *len)
1185 if (*len > 1 && isdigit (encoded[*len - 1]))
1187 int i = *len - 2;
1189 while (i > 0 && isdigit (encoded[i]))
1190 i--;
1191 if (i >= 0 && encoded[i] == '.')
1192 *len = i;
1193 else if (i >= 0 && encoded[i] == '$')
1194 *len = i;
1195 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1196 *len = i - 2;
1197 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1198 *len = i - 1;
1202 /* Remove the suffix introduced by the compiler for protected object
1203 subprograms. */
1205 static void
1206 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1208 /* Remove trailing N. */
1210 /* Protected entry subprograms are broken into two
1211 separate subprograms: The first one is unprotected, and has
1212 a 'N' suffix; the second is the protected version, and has
1213 the 'P' suffix. The second calls the first one after handling
1214 the protection. Since the P subprograms are internally generated,
1215 we leave these names undecoded, giving the user a clue that this
1216 entity is internal. */
1218 if (*len > 1
1219 && encoded[*len - 1] == 'N'
1220 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1221 *len = *len - 1;
1224 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1225 then update *LEN to remove the suffix and return the offset of the
1226 character just past the ".". Otherwise, return -1. */
1228 static int
1229 remove_compiler_suffix (const char *encoded, int *len)
1231 int offset = *len - 1;
1232 while (offset > 0 && isalpha (encoded[offset]))
1233 --offset;
1234 if (offset > 0 && encoded[offset] == '.')
1236 *len = offset;
1237 return offset + 1;
1239 return -1;
1242 /* Convert an ASCII hex string to a number. Reads exactly N
1243 characters from STR. Returns true on success, false if one of the
1244 digits was not a hex digit. */
1245 static bool
1246 convert_hex (const char *str, int n, uint32_t *out)
1248 uint32_t result = 0;
1250 for (int i = 0; i < n; ++i)
1252 if (!isxdigit (str[i]))
1253 return false;
1254 result <<= 4;
1255 result |= fromhex (str[i]);
1258 *out = result;
1259 return true;
1262 /* Convert a wide character from its ASCII hex representation in STR
1263 (consisting of exactly N characters) to the host encoding,
1264 appending the resulting bytes to OUT. If N==2 and the Ada source
1265 charset is not UTF-8, then hex refers to an encoding in the
1266 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1267 Return false and do not modify OUT on conversion failure. */
1268 static bool
1269 convert_from_hex_encoded (std::string &out, const char *str, int n)
1271 uint32_t value;
1273 if (!convert_hex (str, n, &value))
1274 return false;
1277 auto_obstack bytes;
1278 /* In the 'U' case, the hex digits encode the character in the
1279 Ada source charset. However, if the source charset is UTF-8,
1280 this really means it is a single-byte UTF-32 character. */
1281 if (n == 2 && ada_source_charset != ada_utf8)
1283 gdb_byte one_char = (gdb_byte) value;
1285 convert_between_encodings (ada_source_charset, host_charset (),
1286 &one_char,
1287 sizeof (one_char), sizeof (one_char),
1288 &bytes, translit_none);
1290 else
1291 convert_between_encodings (HOST_UTF32, host_charset (),
1292 (const gdb_byte *) &value,
1293 sizeof (value), sizeof (value),
1294 &bytes, translit_none);
1295 obstack_1grow (&bytes, '\0');
1296 out.append ((const char *) obstack_base (&bytes));
1298 catch (const gdb_exception &)
1300 /* On failure, the caller will just let the encoded form
1301 through, which seems basically reasonable. */
1302 return false;
1305 return true;
1308 /* See ada-lang.h. */
1310 std::string
1311 ada_decode (const char *encoded, bool wrap, bool operators)
1313 int i;
1314 int len0;
1315 const char *p;
1316 int at_start_name;
1317 std::string decoded;
1318 int suffix = -1;
1320 /* With function descriptors on PPC64, the value of a symbol named
1321 ".FN", if it exists, is the entry point of the function "FN". */
1322 if (encoded[0] == '.')
1323 encoded += 1;
1325 /* The name of the Ada main procedure starts with "_ada_".
1326 This prefix is not part of the decoded name, so skip this part
1327 if we see this prefix. */
1328 if (startswith (encoded, "_ada_"))
1329 encoded += 5;
1330 /* The "___ghost_" prefix is used for ghost entities. Normally
1331 these aren't preserved but when they are, it's useful to see
1332 them. */
1333 if (startswith (encoded, "___ghost_"))
1334 encoded += 9;
1336 /* If the name starts with '_', then it is not a properly encoded
1337 name, so do not attempt to decode it. Similarly, if the name
1338 starts with '<', the name should not be decoded. */
1339 if (encoded[0] == '_' || encoded[0] == '<')
1340 goto Suppress;
1342 len0 = strlen (encoded);
1344 suffix = remove_compiler_suffix (encoded, &len0);
1346 ada_remove_trailing_digits (encoded, &len0);
1347 ada_remove_po_subprogram_suffix (encoded, &len0);
1349 /* Remove the ___X.* suffix if present. Do not forget to verify that
1350 the suffix is located before the current "end" of ENCODED. We want
1351 to avoid re-matching parts of ENCODED that have previously been
1352 marked as discarded (by decrementing LEN0). */
1353 p = strstr (encoded, "___");
1354 if (p != NULL && p - encoded < len0 - 3)
1356 if (p[3] == 'X')
1357 len0 = p - encoded;
1358 else
1359 goto Suppress;
1362 /* Remove any trailing TKB suffix. It tells us that this symbol
1363 is for the body of a task, but that information does not actually
1364 appear in the decoded name. */
1366 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1367 len0 -= 3;
1369 /* Remove any trailing TB suffix. The TB suffix is slightly different
1370 from the TKB suffix because it is used for non-anonymous task
1371 bodies. */
1373 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1374 len0 -= 2;
1376 /* Remove trailing "B" suffixes. */
1377 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1379 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1380 len0 -= 1;
1382 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1384 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1386 i = len0 - 2;
1387 while ((i >= 0 && isdigit (encoded[i]))
1388 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1389 i -= 1;
1390 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1391 len0 = i - 1;
1392 else if (i >= 0 && encoded[i] == '$')
1393 len0 = i;
1396 /* The first few characters that are not alphabetic are not part
1397 of any encoding we use, so we can copy them over verbatim. */
1399 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1400 decoded.push_back (encoded[i]);
1402 at_start_name = 1;
1403 while (i < len0)
1405 /* Is this a symbol function? */
1406 if (operators && at_start_name && encoded[i] == 'O')
1408 int k;
1410 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1412 int op_len = strlen (ada_opname_table[k].encoded);
1413 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1414 op_len - 1) == 0)
1415 && !isalnum (encoded[i + op_len]))
1417 decoded.append (ada_opname_table[k].decoded);
1418 at_start_name = 0;
1419 i += op_len;
1420 break;
1423 if (ada_opname_table[k].encoded != NULL)
1424 continue;
1426 at_start_name = 0;
1428 /* Replace "TK__" with "__", which will eventually be translated
1429 into "." (just below). */
1431 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1432 i += 2;
1434 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1435 be translated into "." (just below). These are internal names
1436 generated for anonymous blocks inside which our symbol is nested. */
1438 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1439 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1440 && isdigit (encoded [i+4]))
1442 int k = i + 5;
1444 while (k < len0 && isdigit (encoded[k]))
1445 k++; /* Skip any extra digit. */
1447 /* Double-check that the "__B_{DIGITS}+" sequence we found
1448 is indeed followed by "__". */
1449 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1450 i = k;
1453 /* Remove _E{DIGITS}+[sb] */
1455 /* Just as for protected object subprograms, there are 2 categories
1456 of subprograms created by the compiler for each entry. The first
1457 one implements the actual entry code, and has a suffix following
1458 the convention above; the second one implements the barrier and
1459 uses the same convention as above, except that the 'E' is replaced
1460 by a 'B'.
1462 Just as above, we do not decode the name of barrier functions
1463 to give the user a clue that the code he is debugging has been
1464 internally generated. */
1466 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1467 && isdigit (encoded[i+2]))
1469 int k = i + 3;
1471 while (k < len0 && isdigit (encoded[k]))
1472 k++;
1474 if (k < len0
1475 && (encoded[k] == 'b' || encoded[k] == 's'))
1477 k++;
1478 /* Just as an extra precaution, make sure that if this
1479 suffix is followed by anything else, it is a '_'.
1480 Otherwise, we matched this sequence by accident. */
1481 if (k == len0
1482 || (k < len0 && encoded[k] == '_'))
1483 i = k;
1487 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1488 the GNAT front-end in protected object subprograms. */
1490 if (i < len0 + 3
1491 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1493 /* Backtrack a bit up until we reach either the begining of
1494 the encoded name, or "__". Make sure that we only find
1495 digits or lowercase characters. */
1496 const char *ptr = encoded + i - 1;
1498 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1499 ptr--;
1500 if (ptr < encoded
1501 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1502 i++;
1505 if (i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1507 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1509 i += 3;
1510 continue;
1513 else if (i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1515 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1517 i += 5;
1518 continue;
1521 else if (i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1522 && isxdigit (encoded[i + 2]))
1524 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1526 i += 10;
1527 continue;
1531 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1533 /* This is a X[bn]* sequence not separated from the previous
1534 part of the name with a non-alpha-numeric character (in other
1535 words, immediately following an alpha-numeric character), then
1536 verify that it is placed at the end of the encoded name. If
1537 not, then the encoding is not valid and we should abort the
1538 decoding. Otherwise, just skip it, it is used in body-nested
1539 package names. */
1541 i += 1;
1542 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1543 if (i < len0)
1544 goto Suppress;
1546 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1548 /* Replace '__' by '.'. */
1549 decoded.push_back ('.');
1550 at_start_name = 1;
1551 i += 2;
1553 else
1555 /* It's a character part of the decoded name, so just copy it
1556 over. */
1557 decoded.push_back (encoded[i]);
1558 i += 1;
1562 /* Decoded names should never contain any uppercase character.
1563 Double-check this, and abort the decoding if we find one. */
1565 if (operators)
1567 for (i = 0; i < decoded.length(); ++i)
1568 if (isupper (decoded[i]) || decoded[i] == ' ')
1569 goto Suppress;
1572 /* If the compiler added a suffix, append it now. */
1573 if (suffix >= 0)
1574 decoded = decoded + "[" + &encoded[suffix] + "]";
1576 return decoded;
1578 Suppress:
1579 if (!wrap)
1580 return {};
1582 if (encoded[0] == '<')
1583 decoded = encoded;
1584 else
1585 decoded = '<' + std::string(encoded) + '>';
1586 return decoded;
1589 #ifdef GDB_SELF_TEST
1591 static void
1592 ada_decode_tests ()
1594 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1595 result does not really matter very much. */
1596 SELF_CHECK (ada_decode ("44") == "44");
1599 #endif
1601 /* Table for keeping permanent unique copies of decoded names. Once
1602 allocated, names in this table are never released. While this is a
1603 storage leak, it should not be significant unless there are massive
1604 changes in the set of decoded names in successive versions of a
1605 symbol table loaded during a single session. */
1606 static struct htab *decoded_names_store;
1608 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1609 in the language-specific part of GSYMBOL, if it has not been
1610 previously computed. Tries to save the decoded name in the same
1611 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1612 in any case, the decoded symbol has a lifetime at least that of
1613 GSYMBOL).
1614 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1615 const, but nevertheless modified to a semantically equivalent form
1616 when a decoded name is cached in it. */
1618 const char *
1619 ada_decode_symbol (const struct general_symbol_info *arg)
1621 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1622 const char **resultp =
1623 &gsymbol->language_specific.demangled_name;
1625 if (!gsymbol->ada_mangled)
1627 std::string decoded = ada_decode (gsymbol->linkage_name ());
1628 struct obstack *obstack = gsymbol->language_specific.obstack;
1630 gsymbol->ada_mangled = 1;
1632 if (obstack != NULL)
1633 *resultp = obstack_strdup (obstack, decoded.c_str ());
1634 else
1636 /* Sometimes, we can't find a corresponding objfile, in
1637 which case, we put the result on the heap. Since we only
1638 decode when needed, we hope this usually does not cause a
1639 significant memory leak (FIXME). */
1641 char **slot = (char **) htab_find_slot (decoded_names_store,
1642 decoded.c_str (), INSERT);
1644 if (*slot == NULL)
1645 *slot = xstrdup (decoded.c_str ());
1646 *resultp = *slot;
1650 return *resultp;
1655 /* Arrays */
1657 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1658 generated by the GNAT compiler to describe the index type used
1659 for each dimension of an array, check whether it follows the latest
1660 known encoding. If not, fix it up to conform to the latest encoding.
1661 Otherwise, do nothing. This function also does nothing if
1662 INDEX_DESC_TYPE is NULL.
1664 The GNAT encoding used to describe the array index type evolved a bit.
1665 Initially, the information would be provided through the name of each
1666 field of the structure type only, while the type of these fields was
1667 described as unspecified and irrelevant. The debugger was then expected
1668 to perform a global type lookup using the name of that field in order
1669 to get access to the full index type description. Because these global
1670 lookups can be very expensive, the encoding was later enhanced to make
1671 the global lookup unnecessary by defining the field type as being
1672 the full index type description.
1674 The purpose of this routine is to allow us to support older versions
1675 of the compiler by detecting the use of the older encoding, and by
1676 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1677 we essentially replace each field's meaningless type by the associated
1678 index subtype). */
1680 void
1681 ada_fixup_array_indexes_type (struct type *index_desc_type)
1683 int i;
1685 if (index_desc_type == NULL)
1686 return;
1687 gdb_assert (index_desc_type->num_fields () > 0);
1689 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1690 to check one field only, no need to check them all). If not, return
1691 now.
1693 If our INDEX_DESC_TYPE was generated using the older encoding,
1694 the field type should be a meaningless integer type whose name
1695 is not equal to the field name. */
1696 if (index_desc_type->field (0).type ()->name () != NULL
1697 && strcmp (index_desc_type->field (0).type ()->name (),
1698 index_desc_type->field (0).name ()) == 0)
1699 return;
1701 /* Fixup each field of INDEX_DESC_TYPE. */
1702 for (i = 0; i < index_desc_type->num_fields (); i++)
1704 const char *name = index_desc_type->field (i).name ();
1705 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1707 if (raw_type)
1708 index_desc_type->field (i).set_type (raw_type);
1712 /* The desc_* routines return primitive portions of array descriptors
1713 (fat pointers). */
1715 /* The descriptor or array type, if any, indicated by TYPE; removes
1716 level of indirection, if needed. */
1718 static struct type *
1719 desc_base_type (struct type *type)
1721 if (type == NULL)
1722 return NULL;
1723 type = ada_check_typedef (type);
1724 if (type->code () == TYPE_CODE_TYPEDEF)
1725 type = ada_typedef_target_type (type);
1727 if (type != NULL
1728 && (type->code () == TYPE_CODE_PTR
1729 || type->code () == TYPE_CODE_REF))
1730 return ada_check_typedef (type->target_type ());
1731 else
1732 return type;
1735 /* True iff TYPE indicates a "thin" array pointer type. */
1737 static int
1738 is_thin_pntr (struct type *type)
1740 return
1741 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1742 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1745 /* The descriptor type for thin pointer type TYPE. */
1747 static struct type *
1748 thin_descriptor_type (struct type *type)
1750 struct type *base_type = desc_base_type (type);
1752 if (base_type == NULL)
1753 return NULL;
1754 if (is_suffix (ada_type_name (base_type), "___XVE"))
1755 return base_type;
1756 else
1758 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1760 if (alt_type == NULL)
1761 return base_type;
1762 else
1763 return alt_type;
1767 /* A pointer to the array data for thin-pointer value VAL. */
1769 static struct value *
1770 thin_data_pntr (struct value *val)
1772 struct type *type = ada_check_typedef (val->type ());
1773 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1775 data_type = lookup_pointer_type (data_type);
1777 if (type->code () == TYPE_CODE_PTR)
1778 return value_cast (data_type, val->copy ());
1779 else
1780 return value_from_longest (data_type, val->address ());
1783 /* True iff TYPE indicates a "thick" array pointer type. */
1785 static int
1786 is_thick_pntr (struct type *type)
1788 type = desc_base_type (type);
1789 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1790 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1793 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1794 pointer to one, the type of its bounds data; otherwise, NULL. */
1796 static struct type *
1797 desc_bounds_type (struct type *type)
1799 struct type *r;
1801 type = desc_base_type (type);
1803 if (type == NULL)
1804 return NULL;
1805 else if (is_thin_pntr (type))
1807 type = thin_descriptor_type (type);
1808 if (type == NULL)
1809 return NULL;
1810 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1811 if (r != NULL)
1812 return ada_check_typedef (r);
1814 else if (type->code () == TYPE_CODE_STRUCT)
1816 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1817 if (r != NULL)
1818 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1820 return NULL;
1823 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1824 one, a pointer to its bounds data. Otherwise NULL. */
1826 static struct value *
1827 desc_bounds (struct value *arr)
1829 struct type *type = ada_check_typedef (arr->type ());
1831 if (is_thin_pntr (type))
1833 struct type *bounds_type =
1834 desc_bounds_type (thin_descriptor_type (type));
1835 LONGEST addr;
1837 if (bounds_type == NULL)
1838 error (_("Bad GNAT array descriptor"));
1840 /* NOTE: The following calculation is not really kosher, but
1841 since desc_type is an XVE-encoded type (and shouldn't be),
1842 the correct calculation is a real pain. FIXME (and fix GCC). */
1843 if (type->code () == TYPE_CODE_PTR)
1844 addr = value_as_long (arr);
1845 else
1846 addr = arr->address ();
1848 return
1849 value_from_longest (lookup_pointer_type (bounds_type),
1850 addr - bounds_type->length ());
1853 else if (is_thick_pntr (type))
1855 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1856 _("Bad GNAT array descriptor"));
1857 struct type *p_bounds_type = p_bounds->type ();
1859 if (p_bounds_type
1860 && p_bounds_type->code () == TYPE_CODE_PTR)
1862 struct type *target_type = p_bounds_type->target_type ();
1864 if (target_type->is_stub ())
1865 p_bounds = value_cast (lookup_pointer_type
1866 (ada_check_typedef (target_type)),
1867 p_bounds);
1869 else
1870 error (_("Bad GNAT array descriptor"));
1872 return p_bounds;
1874 else
1875 return NULL;
1878 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1879 position of the field containing the address of the bounds data. */
1881 static int
1882 fat_pntr_bounds_bitpos (struct type *type)
1884 return desc_base_type (type)->field (1).loc_bitpos ();
1887 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1888 size of the field containing the address of the bounds data. */
1890 static int
1891 fat_pntr_bounds_bitsize (struct type *type)
1893 type = desc_base_type (type);
1895 if (type->field (1).bitsize () > 0)
1896 return type->field (1).bitsize ();
1897 else
1898 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1901 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1902 pointer to one, the type of its array data (a array-with-no-bounds type);
1903 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1904 data. */
1906 static struct type *
1907 desc_data_target_type (struct type *type)
1909 type = desc_base_type (type);
1911 /* NOTE: The following is bogus; see comment in desc_bounds. */
1912 if (is_thin_pntr (type))
1913 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1914 else if (is_thick_pntr (type))
1916 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1918 if (data_type
1919 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1920 return ada_check_typedef (data_type->target_type ());
1923 return NULL;
1926 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1927 its array data. */
1929 static struct value *
1930 desc_data (struct value *arr)
1932 struct type *type = arr->type ();
1934 if (is_thin_pntr (type))
1935 return thin_data_pntr (arr);
1936 else if (is_thick_pntr (type))
1937 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1938 _("Bad GNAT array descriptor"));
1939 else
1940 return NULL;
1944 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1945 position of the field containing the address of the data. */
1947 static int
1948 fat_pntr_data_bitpos (struct type *type)
1950 return desc_base_type (type)->field (0).loc_bitpos ();
1953 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1954 size of the field containing the address of the data. */
1956 static int
1957 fat_pntr_data_bitsize (struct type *type)
1959 type = desc_base_type (type);
1961 if (type->field (0).bitsize () > 0)
1962 return type->field (0).bitsize ();
1963 else
1964 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1967 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1968 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1969 bound, if WHICH is 1. The first bound is I=1. */
1971 static struct value *
1972 desc_one_bound (struct value *bounds, int i, int which)
1974 char bound_name[20];
1975 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1976 which ? 'U' : 'L', i - 1);
1977 return value_struct_elt (&bounds, {}, bound_name, NULL,
1978 _("Bad GNAT array descriptor bounds"));
1981 /* If BOUNDS is an array-bounds structure type, return the bit position
1982 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1983 bound, if WHICH is 1. The first bound is I=1. */
1985 static int
1986 desc_bound_bitpos (struct type *type, int i, int which)
1988 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1991 /* If BOUNDS is an array-bounds structure type, return the bit field size
1992 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1993 bound, if WHICH is 1. The first bound is I=1. */
1995 static int
1996 desc_bound_bitsize (struct type *type, int i, int which)
1998 type = desc_base_type (type);
2000 if (type->field (2 * i + which - 2).bitsize () > 0)
2001 return type->field (2 * i + which - 2).bitsize ();
2002 else
2003 return 8 * type->field (2 * i + which - 2).type ()->length ();
2006 /* If TYPE is the type of an array-bounds structure, the type of its
2007 Ith bound (numbering from 1). Otherwise, NULL. */
2009 static struct type *
2010 desc_index_type (struct type *type, int i)
2012 type = desc_base_type (type);
2014 if (type->code () == TYPE_CODE_STRUCT)
2016 char bound_name[20];
2017 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2018 return lookup_struct_elt_type (type, bound_name, 1);
2020 else
2021 return NULL;
2024 /* The number of index positions in the array-bounds type TYPE.
2025 Return 0 if TYPE is NULL. */
2027 static int
2028 desc_arity (struct type *type)
2030 type = desc_base_type (type);
2032 if (type != NULL)
2033 return type->num_fields () / 2;
2034 return 0;
2037 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2038 an array descriptor type (representing an unconstrained array
2039 type). */
2041 static int
2042 ada_is_direct_array_type (struct type *type)
2044 if (type == NULL)
2045 return 0;
2046 type = ada_check_typedef (type);
2047 return (type->code () == TYPE_CODE_ARRAY
2048 || ada_is_array_descriptor_type (type));
2051 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2052 * to one. */
2054 static int
2055 ada_is_array_type (struct type *type)
2057 while (type != NULL
2058 && (type->code () == TYPE_CODE_PTR
2059 || type->code () == TYPE_CODE_REF))
2060 type = type->target_type ();
2061 return ada_is_direct_array_type (type);
2064 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2067 ada_is_simple_array_type (struct type *type)
2069 if (type == NULL)
2070 return 0;
2071 type = ada_check_typedef (type);
2072 return (type->code () == TYPE_CODE_ARRAY
2073 || (type->code () == TYPE_CODE_PTR
2074 && (ada_check_typedef (type->target_type ())->code ()
2075 == TYPE_CODE_ARRAY)));
2078 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2081 ada_is_array_descriptor_type (struct type *type)
2083 struct type *data_type = desc_data_target_type (type);
2085 if (type == NULL)
2086 return 0;
2087 type = ada_check_typedef (type);
2088 return (data_type != NULL
2089 && data_type->code () == TYPE_CODE_ARRAY
2090 && desc_arity (desc_bounds_type (type)) > 0);
2093 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2094 (fat pointer) returns the type of the array data described---specifically,
2095 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2096 in from the descriptor; otherwise, they are left unspecified. If
2097 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2098 returns NULL. The result is simply the type of ARR if ARR is not
2099 a descriptor. */
2101 static struct type *
2102 ada_type_of_array (struct value *arr, int bounds)
2104 if (ada_is_constrained_packed_array_type (arr->type ()))
2105 return decode_constrained_packed_array_type (arr->type ());
2107 if (!ada_is_array_descriptor_type (arr->type ()))
2108 return arr->type ();
2110 if (!bounds)
2112 struct type *array_type =
2113 ada_check_typedef (desc_data_target_type (arr->type ()));
2115 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2116 array_type->field (0).set_bitsize
2117 (decode_packed_array_bitsize (arr->type ()));
2119 return array_type;
2121 else
2123 struct type *elt_type;
2124 int arity;
2125 struct value *descriptor;
2127 elt_type = ada_array_element_type (arr->type (), -1);
2128 arity = ada_array_arity (arr->type ());
2130 if (elt_type == NULL || arity == 0)
2131 return ada_check_typedef (arr->type ());
2133 descriptor = desc_bounds (arr);
2134 if (value_as_long (descriptor) == 0)
2135 return NULL;
2136 while (arity > 0)
2138 type_allocator alloc (arr->type ());
2139 struct value *low = desc_one_bound (descriptor, arity, 0);
2140 struct value *high = desc_one_bound (descriptor, arity, 1);
2142 arity -= 1;
2143 struct type *range_type
2144 = create_static_range_type (alloc, low->type (),
2145 longest_to_int (value_as_long (low)),
2146 longest_to_int (value_as_long (high)));
2147 elt_type = create_array_type (alloc, elt_type, range_type);
2148 INIT_GNAT_SPECIFIC (elt_type);
2150 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2152 /* We need to store the element packed bitsize, as well as
2153 recompute the array size, because it was previously
2154 computed based on the unpacked element size. */
2155 LONGEST lo = value_as_long (low);
2156 LONGEST hi = value_as_long (high);
2158 elt_type->field (0).set_bitsize
2159 (decode_packed_array_bitsize (arr->type ()));
2161 /* If the array has no element, then the size is already
2162 zero, and does not need to be recomputed. */
2163 if (lo < hi)
2165 int array_bitsize =
2166 (hi - lo + 1) * elt_type->field (0).bitsize ();
2168 elt_type->set_length ((array_bitsize + 7) / 8);
2173 return lookup_pointer_type (elt_type);
2177 /* If ARR does not represent an array, returns ARR unchanged.
2178 Otherwise, returns either a standard GDB array with bounds set
2179 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2180 GDB array. Returns NULL if ARR is a null fat pointer. */
2182 struct value *
2183 ada_coerce_to_simple_array_ptr (struct value *arr)
2185 if (ada_is_array_descriptor_type (arr->type ()))
2187 struct type *arrType = ada_type_of_array (arr, 1);
2189 if (arrType == NULL)
2190 return NULL;
2191 return value_cast (arrType, desc_data (arr)->copy ());
2193 else if (ada_is_constrained_packed_array_type (arr->type ()))
2194 return decode_constrained_packed_array (arr);
2195 else
2196 return arr;
2199 /* If ARR does not represent an array, returns ARR unchanged.
2200 Otherwise, returns a standard GDB array describing ARR (which may
2201 be ARR itself if it already is in the proper form). */
2203 struct value *
2204 ada_coerce_to_simple_array (struct value *arr)
2206 if (ada_is_array_descriptor_type (arr->type ()))
2208 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2210 if (arrVal == NULL)
2211 error (_("Bounds unavailable for null array pointer."));
2212 return value_ind (arrVal);
2214 else if (ada_is_constrained_packed_array_type (arr->type ()))
2215 return decode_constrained_packed_array (arr);
2216 else
2217 return arr;
2220 /* If TYPE represents a GNAT array type, return it translated to an
2221 ordinary GDB array type (possibly with BITSIZE fields indicating
2222 packing). For other types, is the identity. */
2224 struct type *
2225 ada_coerce_to_simple_array_type (struct type *type)
2227 if (ada_is_constrained_packed_array_type (type))
2228 return decode_constrained_packed_array_type (type);
2230 if (ada_is_array_descriptor_type (type))
2231 return ada_check_typedef (desc_data_target_type (type));
2233 return type;
2236 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2238 static int
2239 ada_is_gnat_encoded_packed_array_type (struct type *type)
2241 if (type == NULL)
2242 return 0;
2243 type = desc_base_type (type);
2244 type = ada_check_typedef (type);
2245 return
2246 ada_type_name (type) != NULL
2247 && strstr (ada_type_name (type), "___XP") != NULL;
2250 /* Non-zero iff TYPE represents a standard GNAT constrained
2251 packed-array type. */
2254 ada_is_constrained_packed_array_type (struct type *type)
2256 return ada_is_gnat_encoded_packed_array_type (type)
2257 && !ada_is_array_descriptor_type (type);
2260 /* Non-zero iff TYPE represents an array descriptor for a
2261 unconstrained packed-array type. */
2263 static int
2264 ada_is_unconstrained_packed_array_type (struct type *type)
2266 if (!ada_is_array_descriptor_type (type))
2267 return 0;
2269 if (ada_is_gnat_encoded_packed_array_type (type))
2270 return 1;
2272 /* If we saw GNAT encodings, then the above code is sufficient.
2273 However, with minimal encodings, we will just have a thick
2274 pointer instead. */
2275 if (is_thick_pntr (type))
2277 type = desc_base_type (type);
2278 /* The structure's first field is a pointer to an array, so this
2279 fetches the array type. */
2280 type = type->field (0).type ()->target_type ();
2281 if (type->code () == TYPE_CODE_TYPEDEF)
2282 type = ada_typedef_target_type (type);
2283 /* Now we can see if the array elements are packed. */
2284 return type->field (0).bitsize () > 0;
2287 return 0;
2290 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2291 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2293 static bool
2294 ada_is_any_packed_array_type (struct type *type)
2296 return (ada_is_constrained_packed_array_type (type)
2297 || (type->code () == TYPE_CODE_ARRAY
2298 && type->field (0).bitsize () % 8 != 0));
2301 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2302 return the size of its elements in bits. */
2304 static long
2305 decode_packed_array_bitsize (struct type *type)
2307 const char *raw_name;
2308 const char *tail;
2309 long bits;
2311 /* Access to arrays implemented as fat pointers are encoded as a typedef
2312 of the fat pointer type. We need the name of the fat pointer type
2313 to do the decoding, so strip the typedef layer. */
2314 if (type->code () == TYPE_CODE_TYPEDEF)
2315 type = ada_typedef_target_type (type);
2317 raw_name = ada_type_name (ada_check_typedef (type));
2318 if (!raw_name)
2319 raw_name = ada_type_name (desc_base_type (type));
2321 if (!raw_name)
2322 return 0;
2324 tail = strstr (raw_name, "___XP");
2325 if (tail == nullptr)
2327 gdb_assert (is_thick_pntr (type));
2328 /* The structure's first field is a pointer to an array, so this
2329 fetches the array type. */
2330 type = type->field (0).type ()->target_type ();
2331 /* Now we can see if the array elements are packed. */
2332 return type->field (0).bitsize ();
2335 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2337 lim_warning
2338 (_("could not understand bit size information on packed array"));
2339 return 0;
2342 return bits;
2345 /* Given that TYPE is a standard GDB array type with all bounds filled
2346 in, and that the element size of its ultimate scalar constituents
2347 (that is, either its elements, or, if it is an array of arrays, its
2348 elements' elements, etc.) is *ELT_BITS, return an identical type,
2349 but with the bit sizes of its elements (and those of any
2350 constituent arrays) recorded in the BITSIZE components of its
2351 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2352 in bits.
2354 Note that, for arrays whose index type has an XA encoding where
2355 a bound references a record discriminant, getting that discriminant,
2356 and therefore the actual value of that bound, is not possible
2357 because none of the given parameters gives us access to the record.
2358 This function assumes that it is OK in the context where it is being
2359 used to return an array whose bounds are still dynamic and where
2360 the length is arbitrary. */
2362 static struct type *
2363 constrained_packed_array_type (struct type *type, long *elt_bits)
2365 struct type *new_elt_type;
2366 struct type *new_type;
2367 struct type *index_type_desc;
2368 struct type *index_type;
2369 LONGEST low_bound, high_bound;
2371 type = ada_check_typedef (type);
2372 if (type->code () != TYPE_CODE_ARRAY)
2373 return type;
2375 index_type_desc = ada_find_parallel_type (type, "___XA");
2376 if (index_type_desc)
2377 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2378 NULL);
2379 else
2380 index_type = type->index_type ();
2382 type_allocator alloc (type);
2383 new_elt_type =
2384 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2385 elt_bits);
2386 new_type = create_array_type (alloc, new_elt_type, index_type);
2387 new_type->field (0).set_bitsize (*elt_bits);
2388 new_type->set_name (ada_type_name (type));
2390 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2391 && is_dynamic_type (check_typedef (index_type)))
2392 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2393 low_bound = high_bound = 0;
2394 if (high_bound < low_bound)
2396 *elt_bits = 0;
2397 new_type->set_length (0);
2399 else
2401 *elt_bits *= (high_bound - low_bound + 1);
2402 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2405 new_type->set_is_fixed_instance (true);
2406 return new_type;
2409 /* The array type encoded by TYPE, where
2410 ada_is_constrained_packed_array_type (TYPE). */
2412 static struct type *
2413 decode_constrained_packed_array_type (struct type *type)
2415 const char *raw_name = ada_type_name (ada_check_typedef (type));
2416 char *name;
2417 const char *tail;
2418 struct type *shadow_type;
2419 long bits;
2421 if (!raw_name)
2422 raw_name = ada_type_name (desc_base_type (type));
2424 if (!raw_name)
2425 return NULL;
2427 name = (char *) alloca (strlen (raw_name) + 1);
2428 tail = strstr (raw_name, "___XP");
2429 type = desc_base_type (type);
2431 memcpy (name, raw_name, tail - raw_name);
2432 name[tail - raw_name] = '\000';
2434 shadow_type = ada_find_parallel_type_with_name (type, name);
2436 if (shadow_type == NULL)
2438 lim_warning (_("could not find bounds information on packed array"));
2439 return NULL;
2441 shadow_type = check_typedef (shadow_type);
2443 if (shadow_type->code () != TYPE_CODE_ARRAY)
2445 lim_warning (_("could not understand bounds "
2446 "information on packed array"));
2447 return NULL;
2450 bits = decode_packed_array_bitsize (type);
2451 return constrained_packed_array_type (shadow_type, &bits);
2454 /* Helper function for decode_constrained_packed_array. Set the field
2455 bitsize on a series of packed arrays. Returns the number of
2456 elements in TYPE. */
2458 static LONGEST
2459 recursively_update_array_bitsize (struct type *type)
2461 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2463 LONGEST low, high;
2464 if (!get_discrete_bounds (type->index_type (), &low, &high)
2465 || low > high)
2466 return 0;
2467 LONGEST our_len = high - low + 1;
2469 struct type *elt_type = type->target_type ();
2470 if (elt_type->code () == TYPE_CODE_ARRAY)
2472 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2473 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
2474 type->field (0).set_bitsize (elt_bitsize);
2476 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2477 / HOST_CHAR_BIT));
2480 return our_len;
2483 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2484 array, returns a simple array that denotes that array. Its type is a
2485 standard GDB array type except that the BITSIZEs of the array
2486 target types are set to the number of bits in each element, and the
2487 type length is set appropriately. */
2489 static struct value *
2490 decode_constrained_packed_array (struct value *arr)
2492 struct type *type;
2494 /* If our value is a pointer, then dereference it. Likewise if
2495 the value is a reference. Make sure that this operation does not
2496 cause the target type to be fixed, as this would indirectly cause
2497 this array to be decoded. The rest of the routine assumes that
2498 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2499 and "value_ind" routines to perform the dereferencing, as opposed
2500 to using "ada_coerce_ref" or "ada_value_ind". */
2501 arr = coerce_ref (arr);
2502 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2503 arr = value_ind (arr);
2505 type = decode_constrained_packed_array_type (arr->type ());
2506 if (type == NULL)
2508 error (_("can't unpack array"));
2509 return NULL;
2512 /* Decoding the packed array type could not correctly set the field
2513 bitsizes for any dimension except the innermost, because the
2514 bounds may be variable and were not passed to that function. So,
2515 we further resolve the array bounds here and then update the
2516 sizes. */
2517 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2518 CORE_ADDR address = arr->address ();
2519 gdb::array_view<const gdb_byte> view
2520 = gdb::make_array_view (valaddr, type->length ());
2521 type = resolve_dynamic_type (type, view, address);
2522 recursively_update_array_bitsize (type);
2524 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2525 && ada_is_modular_type (arr->type ()))
2527 /* This is a (right-justified) modular type representing a packed
2528 array with no wrapper. In order to interpret the value through
2529 the (left-justified) packed array type we just built, we must
2530 first left-justify it. */
2531 int bit_size, bit_pos;
2532 ULONGEST mod;
2534 mod = ada_modulus (arr->type ()) - 1;
2535 bit_size = 0;
2536 while (mod > 0)
2538 bit_size += 1;
2539 mod >>= 1;
2541 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2542 arr = ada_value_primitive_packed_val (arr, NULL,
2543 bit_pos / HOST_CHAR_BIT,
2544 bit_pos % HOST_CHAR_BIT,
2545 bit_size,
2546 type);
2549 return coerce_unspec_val_to_type (arr, type);
2553 /* The value of the element of packed array ARR at the ARITY indices
2554 given in IND. ARR must be a simple array. */
2556 static struct value *
2557 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2559 int i;
2560 int bits, elt_off, bit_off;
2561 long elt_total_bit_offset;
2562 struct type *elt_type;
2563 struct value *v;
2565 bits = 0;
2566 elt_total_bit_offset = 0;
2567 elt_type = ada_check_typedef (arr->type ());
2568 for (i = 0; i < arity; i += 1)
2570 if (elt_type->code () != TYPE_CODE_ARRAY
2571 || elt_type->field (0).bitsize () == 0)
2572 error
2573 (_("attempt to do packed indexing of "
2574 "something other than a packed array"));
2575 else
2577 struct type *range_type = elt_type->index_type ();
2578 LONGEST lowerbound, upperbound;
2579 LONGEST idx;
2581 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2583 lim_warning (_("don't know bounds of array"));
2584 lowerbound = upperbound = 0;
2587 idx = pos_atr (ind[i]);
2588 if (idx < lowerbound || idx > upperbound)
2589 lim_warning (_("packed array index %ld out of bounds"),
2590 (long) idx);
2591 bits = elt_type->field (0).bitsize ();
2592 elt_total_bit_offset += (idx - lowerbound) * bits;
2593 elt_type = ada_check_typedef (elt_type->target_type ());
2596 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2597 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2599 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2600 bits, elt_type);
2601 return v;
2604 /* Non-zero iff TYPE includes negative integer values. */
2606 static int
2607 has_negatives (struct type *type)
2609 switch (type->code ())
2611 default:
2612 return 0;
2613 case TYPE_CODE_INT:
2614 return !type->is_unsigned ();
2615 case TYPE_CODE_RANGE:
2616 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2620 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2621 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2622 the unpacked buffer.
2624 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2625 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2627 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2628 zero otherwise.
2630 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2632 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2634 static void
2635 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2636 gdb_byte *unpacked, int unpacked_len,
2637 int is_big_endian, int is_signed_type,
2638 int is_scalar)
2640 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2641 int src_idx; /* Index into the source area */
2642 int src_bytes_left; /* Number of source bytes left to process. */
2643 int srcBitsLeft; /* Number of source bits left to move */
2644 int unusedLS; /* Number of bits in next significant
2645 byte of source that are unused */
2647 int unpacked_idx; /* Index into the unpacked buffer */
2648 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2650 unsigned long accum; /* Staging area for bits being transferred */
2651 int accumSize; /* Number of meaningful bits in accum */
2652 unsigned char sign;
2654 /* Transmit bytes from least to most significant; delta is the direction
2655 the indices move. */
2656 int delta = is_big_endian ? -1 : 1;
2658 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2659 bits from SRC. .*/
2660 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2661 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2662 bit_size, unpacked_len);
2664 srcBitsLeft = bit_size;
2665 src_bytes_left = src_len;
2666 unpacked_bytes_left = unpacked_len;
2667 sign = 0;
2669 if (is_big_endian)
2671 src_idx = src_len - 1;
2672 if (is_signed_type
2673 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2674 sign = ~0;
2676 unusedLS =
2677 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2678 % HOST_CHAR_BIT;
2680 if (is_scalar)
2682 accumSize = 0;
2683 unpacked_idx = unpacked_len - 1;
2685 else
2687 /* Non-scalar values must be aligned at a byte boundary... */
2688 accumSize =
2689 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2690 /* ... And are placed at the beginning (most-significant) bytes
2691 of the target. */
2692 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2693 unpacked_bytes_left = unpacked_idx + 1;
2696 else
2698 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2700 src_idx = unpacked_idx = 0;
2701 unusedLS = bit_offset;
2702 accumSize = 0;
2704 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2705 sign = ~0;
2708 accum = 0;
2709 while (src_bytes_left > 0)
2711 /* Mask for removing bits of the next source byte that are not
2712 part of the value. */
2713 unsigned int unusedMSMask =
2714 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2716 /* Sign-extend bits for this byte. */
2717 unsigned int signMask = sign & ~unusedMSMask;
2719 accum |=
2720 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2721 accumSize += HOST_CHAR_BIT - unusedLS;
2722 if (accumSize >= HOST_CHAR_BIT)
2724 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2725 accumSize -= HOST_CHAR_BIT;
2726 accum >>= HOST_CHAR_BIT;
2727 unpacked_bytes_left -= 1;
2728 unpacked_idx += delta;
2730 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2731 unusedLS = 0;
2732 src_bytes_left -= 1;
2733 src_idx += delta;
2735 while (unpacked_bytes_left > 0)
2737 accum |= sign << accumSize;
2738 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2739 accumSize -= HOST_CHAR_BIT;
2740 if (accumSize < 0)
2741 accumSize = 0;
2742 accum >>= HOST_CHAR_BIT;
2743 unpacked_bytes_left -= 1;
2744 unpacked_idx += delta;
2748 /* Create a new value of type TYPE from the contents of OBJ starting
2749 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2750 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2751 assigning through the result will set the field fetched from.
2752 VALADDR is ignored unless OBJ is NULL, in which case,
2753 VALADDR+OFFSET must address the start of storage containing the
2754 packed value. The value returned in this case is never an lval.
2755 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2757 struct value *
2758 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2759 long offset, int bit_offset, int bit_size,
2760 struct type *type)
2762 struct value *v;
2763 const gdb_byte *src; /* First byte containing data to unpack */
2764 gdb_byte *unpacked;
2765 const int is_scalar = is_scalar_type (type);
2766 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2767 gdb::byte_vector staging;
2769 type = ada_check_typedef (type);
2771 if (obj == NULL)
2772 src = valaddr + offset;
2773 else
2774 src = obj->contents ().data () + offset;
2776 if (is_dynamic_type (type))
2778 /* The length of TYPE might by dynamic, so we need to resolve
2779 TYPE in order to know its actual size, which we then use
2780 to create the contents buffer of the value we return.
2781 The difficulty is that the data containing our object is
2782 packed, and therefore maybe not at a byte boundary. So, what
2783 we do, is unpack the data into a byte-aligned buffer, and then
2784 use that buffer as our object's value for resolving the type. */
2785 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2786 staging.resize (staging_len);
2788 ada_unpack_from_contents (src, bit_offset, bit_size,
2789 staging.data (), staging.size (),
2790 is_big_endian, has_negatives (type),
2791 is_scalar);
2792 type = resolve_dynamic_type (type, staging, 0);
2793 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2795 /* This happens when the length of the object is dynamic,
2796 and is actually smaller than the space reserved for it.
2797 For instance, in an array of variant records, the bit_size
2798 we're given is the array stride, which is constant and
2799 normally equal to the maximum size of its element.
2800 But, in reality, each element only actually spans a portion
2801 of that stride. */
2802 bit_size = type->length () * HOST_CHAR_BIT;
2806 if (obj == NULL)
2808 v = value::allocate (type);
2809 src = valaddr + offset;
2811 else if (obj->lval () == lval_memory && obj->lazy ())
2813 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2814 gdb_byte *buf;
2816 v = value_at (type, obj->address () + offset);
2817 buf = (gdb_byte *) alloca (src_len);
2818 read_memory (v->address (), buf, src_len);
2819 src = buf;
2821 else
2823 v = value::allocate (type);
2824 src = obj->contents ().data () + offset;
2827 if (obj != NULL)
2829 long new_offset = offset;
2831 v->set_component_location (obj);
2832 v->set_bitpos (bit_offset + obj->bitpos ());
2833 v->set_bitsize (bit_size);
2834 if (v->bitpos () >= HOST_CHAR_BIT)
2836 ++new_offset;
2837 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2839 v->set_offset (new_offset);
2841 /* Also set the parent value. This is needed when trying to
2842 assign a new value (in inferior memory). */
2843 v->set_parent (obj);
2845 else
2846 v->set_bitsize (bit_size);
2847 unpacked = v->contents_writeable ().data ();
2849 if (bit_size == 0)
2851 memset (unpacked, 0, type->length ());
2852 return v;
2855 if (staging.size () == type->length ())
2857 /* Small short-cut: If we've unpacked the data into a buffer
2858 of the same size as TYPE's length, then we can reuse that,
2859 instead of doing the unpacking again. */
2860 memcpy (unpacked, staging.data (), staging.size ());
2862 else
2863 ada_unpack_from_contents (src, bit_offset, bit_size,
2864 unpacked, type->length (),
2865 is_big_endian, has_negatives (type), is_scalar);
2867 return v;
2870 /* Store the contents of FROMVAL into the location of TOVAL.
2871 Return a new value with the location of TOVAL and contents of
2872 FROMVAL. Handles assignment into packed fields that have
2873 floating-point or non-scalar types. */
2875 static struct value *
2876 ada_value_assign (struct value *toval, struct value *fromval)
2878 struct type *type = toval->type ();
2879 int bits = toval->bitsize ();
2881 toval = ada_coerce_ref (toval);
2882 fromval = ada_coerce_ref (fromval);
2884 if (ada_is_direct_array_type (toval->type ()))
2885 toval = ada_coerce_to_simple_array (toval);
2886 if (ada_is_direct_array_type (fromval->type ()))
2887 fromval = ada_coerce_to_simple_array (fromval);
2889 if (!toval->deprecated_modifiable ())
2890 error (_("Left operand of assignment is not a modifiable lvalue."));
2892 if (toval->lval () == lval_memory
2893 && bits > 0
2894 && (type->code () == TYPE_CODE_FLT
2895 || type->code () == TYPE_CODE_STRUCT))
2897 int len = (toval->bitpos ()
2898 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2899 int from_size;
2900 gdb_byte *buffer = (gdb_byte *) alloca (len);
2901 struct value *val;
2902 CORE_ADDR to_addr = toval->address ();
2904 if (type->code () == TYPE_CODE_FLT)
2905 fromval = value_cast (type, fromval);
2907 read_memory (to_addr, buffer, len);
2908 from_size = fromval->bitsize ();
2909 if (from_size == 0)
2910 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2912 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2913 ULONGEST from_offset = 0;
2914 if (is_big_endian && is_scalar_type (fromval->type ()))
2915 from_offset = from_size - bits;
2916 copy_bitwise (buffer, toval->bitpos (),
2917 fromval->contents ().data (), from_offset,
2918 bits, is_big_endian);
2919 write_memory_with_notification (to_addr, buffer, len);
2921 val = toval->copy ();
2922 memcpy (val->contents_raw ().data (),
2923 fromval->contents ().data (),
2924 type->length ());
2925 val->deprecated_set_type (type);
2927 return val;
2930 return value_assign (toval, fromval);
2934 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2935 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2936 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2937 COMPONENT, and not the inferior's memory. The current contents
2938 of COMPONENT are ignored.
2940 Although not part of the initial design, this function also works
2941 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2942 had a null address, and COMPONENT had an address which is equal to
2943 its offset inside CONTAINER. */
2945 static void
2946 value_assign_to_component (struct value *container, struct value *component,
2947 struct value *val)
2949 LONGEST offset_in_container =
2950 (LONGEST) (component->address () - container->address ());
2951 int bit_offset_in_container =
2952 component->bitpos () - container->bitpos ();
2953 int bits;
2955 val = value_cast (component->type (), val);
2957 if (component->bitsize () == 0)
2958 bits = TARGET_CHAR_BIT * component->type ()->length ();
2959 else
2960 bits = component->bitsize ();
2962 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2964 int src_offset;
2966 if (is_scalar_type (check_typedef (component->type ())))
2967 src_offset
2968 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2969 else
2970 src_offset = 0;
2971 copy_bitwise ((container->contents_writeable ().data ()
2972 + offset_in_container),
2973 container->bitpos () + bit_offset_in_container,
2974 val->contents ().data (), src_offset, bits, 1);
2976 else
2977 copy_bitwise ((container->contents_writeable ().data ()
2978 + offset_in_container),
2979 container->bitpos () + bit_offset_in_container,
2980 val->contents ().data (), 0, bits, 0);
2983 /* Determine if TYPE is an access to an unconstrained array. */
2985 bool
2986 ada_is_access_to_unconstrained_array (struct type *type)
2988 return (type->code () == TYPE_CODE_TYPEDEF
2989 && is_thick_pntr (ada_typedef_target_type (type)));
2992 /* The value of the element of array ARR at the ARITY indices given in IND.
2993 ARR may be either a simple array, GNAT array descriptor, or pointer
2994 thereto. */
2996 struct value *
2997 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2999 int k;
3000 struct value *elt;
3001 struct type *elt_type;
3003 elt = ada_coerce_to_simple_array (arr);
3005 elt_type = ada_check_typedef (elt->type ());
3006 if (elt_type->code () == TYPE_CODE_ARRAY
3007 && elt_type->field (0).bitsize () > 0)
3008 return value_subscript_packed (elt, arity, ind);
3010 for (k = 0; k < arity; k += 1)
3012 struct type *saved_elt_type = elt_type->target_type ();
3014 if (elt_type->code () != TYPE_CODE_ARRAY)
3015 error (_("too many subscripts (%d expected)"), k);
3017 elt = value_subscript (elt, pos_atr (ind[k]));
3019 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3020 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3022 /* The element is a typedef to an unconstrained array,
3023 except that the value_subscript call stripped the
3024 typedef layer. The typedef layer is GNAT's way to
3025 specify that the element is, at the source level, an
3026 access to the unconstrained array, rather than the
3027 unconstrained array. So, we need to restore that
3028 typedef layer, which we can do by forcing the element's
3029 type back to its original type. Otherwise, the returned
3030 value is going to be printed as the array, rather
3031 than as an access. Another symptom of the same issue
3032 would be that an expression trying to dereference the
3033 element would also be improperly rejected. */
3034 elt->deprecated_set_type (saved_elt_type);
3037 elt_type = ada_check_typedef (elt->type ());
3040 return elt;
3043 /* Assuming ARR is a pointer to a GDB array, the value of the element
3044 of *ARR at the ARITY indices given in IND.
3045 Does not read the entire array into memory.
3047 Note: Unlike what one would expect, this function is used instead of
3048 ada_value_subscript for basically all non-packed array types. The reason
3049 for this is that a side effect of doing our own pointer arithmetics instead
3050 of relying on value_subscript is that there is no implicit typedef peeling.
3051 This is important for arrays of array accesses, where it allows us to
3052 preserve the fact that the array's element is an array access, where the
3053 access part os encoded in a typedef layer. */
3055 static struct value *
3056 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3058 int k;
3059 struct value *array_ind = ada_value_ind (arr);
3060 struct type *type
3061 = check_typedef (array_ind->enclosing_type ());
3063 if (type->code () == TYPE_CODE_ARRAY
3064 && type->field (0).bitsize () > 0)
3065 return value_subscript_packed (array_ind, arity, ind);
3067 for (k = 0; k < arity; k += 1)
3069 LONGEST lwb, upb;
3071 if (type->code () != TYPE_CODE_ARRAY)
3072 error (_("too many subscripts (%d expected)"), k);
3073 arr = value_cast (lookup_pointer_type (type->target_type ()),
3074 arr->copy ());
3075 get_discrete_bounds (type->index_type (), &lwb, &upb);
3076 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3077 type = type->target_type ();
3080 return value_ind (arr);
3083 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3084 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3085 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3086 this array is LOW, as per Ada rules. */
3087 static struct value *
3088 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3089 int low, int high)
3091 struct type *type0 = ada_check_typedef (type);
3092 struct type *base_index_type = type0->index_type ()->target_type ();
3093 type_allocator alloc (base_index_type);
3094 struct type *index_type
3095 = create_static_range_type (alloc, base_index_type, low, high);
3096 struct type *slice_type = create_array_type_with_stride
3097 (alloc, type0->target_type (), index_type,
3098 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3099 type0->field (0).bitsize ());
3100 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3101 gdb::optional<LONGEST> base_low_pos, low_pos;
3102 CORE_ADDR base;
3104 low_pos = discrete_position (base_index_type, low);
3105 base_low_pos = discrete_position (base_index_type, base_low);
3107 if (!low_pos.has_value () || !base_low_pos.has_value ())
3109 warning (_("unable to get positions in slice, use bounds instead"));
3110 low_pos = low;
3111 base_low_pos = base_low;
3114 ULONGEST stride = slice_type->field (0).bitsize () / 8;
3115 if (stride == 0)
3116 stride = type0->target_type ()->length ();
3118 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3119 return value_at_lazy (slice_type, base);
3123 static struct value *
3124 ada_value_slice (struct value *array, int low, int high)
3126 struct type *type = ada_check_typedef (array->type ());
3127 struct type *base_index_type = type->index_type ()->target_type ();
3128 type_allocator alloc (type->index_type ());
3129 struct type *index_type
3130 = create_static_range_type (alloc, type->index_type (), low, high);
3131 struct type *slice_type = create_array_type_with_stride
3132 (alloc, type->target_type (), index_type,
3133 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3134 type->field (0).bitsize ());
3135 gdb::optional<LONGEST> low_pos, high_pos;
3138 low_pos = discrete_position (base_index_type, low);
3139 high_pos = discrete_position (base_index_type, high);
3141 if (!low_pos.has_value () || !high_pos.has_value ())
3143 warning (_("unable to get positions in slice, use bounds instead"));
3144 low_pos = low;
3145 high_pos = high;
3148 return value_cast (slice_type,
3149 value_slice (array, low, *high_pos - *low_pos + 1));
3152 /* If type is a record type in the form of a standard GNAT array
3153 descriptor, returns the number of dimensions for type. If arr is a
3154 simple array, returns the number of "array of"s that prefix its
3155 type designation. Otherwise, returns 0. */
3158 ada_array_arity (struct type *type)
3160 int arity;
3162 if (type == NULL)
3163 return 0;
3165 type = desc_base_type (type);
3167 arity = 0;
3168 if (type->code () == TYPE_CODE_STRUCT)
3169 return desc_arity (desc_bounds_type (type));
3170 else
3171 while (type->code () == TYPE_CODE_ARRAY)
3173 arity += 1;
3174 type = ada_check_typedef (type->target_type ());
3177 return arity;
3180 /* If TYPE is a record type in the form of a standard GNAT array
3181 descriptor or a simple array type, returns the element type for
3182 TYPE after indexing by NINDICES indices, or by all indices if
3183 NINDICES is -1. Otherwise, returns NULL. */
3185 struct type *
3186 ada_array_element_type (struct type *type, int nindices)
3188 type = desc_base_type (type);
3190 if (type->code () == TYPE_CODE_STRUCT)
3192 int k;
3193 struct type *p_array_type;
3195 p_array_type = desc_data_target_type (type);
3197 k = ada_array_arity (type);
3198 if (k == 0)
3199 return NULL;
3201 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3202 if (nindices >= 0 && k > nindices)
3203 k = nindices;
3204 while (k > 0 && p_array_type != NULL)
3206 p_array_type = ada_check_typedef (p_array_type->target_type ());
3207 k -= 1;
3209 return p_array_type;
3211 else if (type->code () == TYPE_CODE_ARRAY)
3213 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3215 type = type->target_type ();
3216 /* A multi-dimensional array is represented using a sequence
3217 of array types. If one of these types has a name, then
3218 it is not another dimension of the outer array, but
3219 rather the element type of the outermost array. */
3220 if (type->name () != nullptr)
3221 break;
3222 nindices -= 1;
3224 return type;
3227 return NULL;
3230 /* See ada-lang.h. */
3232 struct type *
3233 ada_index_type (struct type *type, int n, const char *name)
3235 struct type *result_type;
3237 type = desc_base_type (type);
3239 if (n < 0 || n > ada_array_arity (type))
3240 error (_("invalid dimension number to '%s"), name);
3242 if (ada_is_simple_array_type (type))
3244 int i;
3246 for (i = 1; i < n; i += 1)
3248 type = ada_check_typedef (type);
3249 type = type->target_type ();
3251 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3252 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3253 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3254 perhaps stabsread.c would make more sense. */
3255 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3256 result_type = NULL;
3258 else
3260 result_type = desc_index_type (desc_bounds_type (type), n);
3261 if (result_type == NULL)
3262 error (_("attempt to take bound of something that is not an array"));
3265 return result_type;
3268 /* Given that arr is an array type, returns the lower bound of the
3269 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3270 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3271 array-descriptor type. It works for other arrays with bounds supplied
3272 by run-time quantities other than discriminants. */
3274 static LONGEST
3275 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3277 struct type *type, *index_type_desc, *index_type;
3278 int i;
3280 gdb_assert (which == 0 || which == 1);
3282 if (ada_is_constrained_packed_array_type (arr_type))
3283 arr_type = decode_constrained_packed_array_type (arr_type);
3285 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3286 return - which;
3288 if (arr_type->code () == TYPE_CODE_PTR)
3289 type = arr_type->target_type ();
3290 else
3291 type = arr_type;
3293 if (type->is_fixed_instance ())
3295 /* The array has already been fixed, so we do not need to
3296 check the parallel ___XA type again. That encoding has
3297 already been applied, so ignore it now. */
3298 index_type_desc = NULL;
3300 else
3302 index_type_desc = ada_find_parallel_type (type, "___XA");
3303 ada_fixup_array_indexes_type (index_type_desc);
3306 if (index_type_desc != NULL)
3307 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3308 NULL);
3309 else
3311 struct type *elt_type = check_typedef (type);
3313 for (i = 1; i < n; i++)
3314 elt_type = check_typedef (elt_type->target_type ());
3316 index_type = elt_type->index_type ();
3319 return (which == 0
3320 ? ada_discrete_type_low_bound (index_type)
3321 : ada_discrete_type_high_bound (index_type));
3324 /* Given that arr is an array value, returns the lower bound of the
3325 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3326 WHICH is 1. This routine will also work for arrays with bounds
3327 supplied by run-time quantities other than discriminants. */
3329 static LONGEST
3330 ada_array_bound (struct value *arr, int n, int which)
3332 struct type *arr_type;
3334 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3335 arr = value_ind (arr);
3336 arr_type = arr->enclosing_type ();
3338 if (ada_is_constrained_packed_array_type (arr_type))
3339 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3340 else if (ada_is_simple_array_type (arr_type))
3341 return ada_array_bound_from_type (arr_type, n, which);
3342 else
3343 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3346 /* Given that arr is an array value, returns the length of the
3347 nth index. This routine will also work for arrays with bounds
3348 supplied by run-time quantities other than discriminants.
3349 Does not work for arrays indexed by enumeration types with representation
3350 clauses at the moment. */
3352 static LONGEST
3353 ada_array_length (struct value *arr, int n)
3355 struct type *arr_type, *index_type;
3356 int low, high;
3358 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3359 arr = value_ind (arr);
3360 arr_type = arr->enclosing_type ();
3362 if (ada_is_constrained_packed_array_type (arr_type))
3363 return ada_array_length (decode_constrained_packed_array (arr), n);
3365 if (ada_is_simple_array_type (arr_type))
3367 low = ada_array_bound_from_type (arr_type, n, 0);
3368 high = ada_array_bound_from_type (arr_type, n, 1);
3370 else
3372 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3373 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3376 arr_type = check_typedef (arr_type);
3377 index_type = ada_index_type (arr_type, n, "length");
3378 if (index_type != NULL)
3380 struct type *base_type;
3381 if (index_type->code () == TYPE_CODE_RANGE)
3382 base_type = index_type->target_type ();
3383 else
3384 base_type = index_type;
3386 low = pos_atr (value_from_longest (base_type, low));
3387 high = pos_atr (value_from_longest (base_type, high));
3389 return high - low + 1;
3392 /* An array whose type is that of ARR_TYPE (an array type), with
3393 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3394 less than LOW, then LOW-1 is used. */
3396 static struct value *
3397 empty_array (struct type *arr_type, int low, int high)
3399 struct type *arr_type0 = ada_check_typedef (arr_type);
3400 type_allocator alloc (arr_type0->index_type ()->target_type ());
3401 struct type *index_type
3402 = create_static_range_type
3403 (alloc, arr_type0->index_type ()->target_type (), low,
3404 high < low ? low - 1 : high);
3405 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3407 return value::allocate (create_array_type (alloc, elt_type, index_type));
3411 /* Name resolution */
3413 /* The "decoded" name for the user-definable Ada operator corresponding
3414 to OP. */
3416 static const char *
3417 ada_decoded_op_name (enum exp_opcode op)
3419 int i;
3421 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3423 if (ada_opname_table[i].op == op)
3424 return ada_opname_table[i].decoded;
3426 error (_("Could not find operator name for opcode"));
3429 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3430 in a listing of choices during disambiguation (see sort_choices, below).
3431 The idea is that overloadings of a subprogram name from the
3432 same package should sort in their source order. We settle for ordering
3433 such symbols by their trailing number (__N or $N). */
3435 static int
3436 encoded_ordered_before (const char *N0, const char *N1)
3438 if (N1 == NULL)
3439 return 0;
3440 else if (N0 == NULL)
3441 return 1;
3442 else
3444 int k0, k1;
3446 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3448 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3450 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3451 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3453 int n0, n1;
3455 n0 = k0;
3456 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3457 n0 -= 1;
3458 n1 = k1;
3459 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3460 n1 -= 1;
3461 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3462 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3464 return (strcmp (N0, N1) < 0);
3468 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3469 encoded names. */
3471 static void
3472 sort_choices (struct block_symbol syms[], int nsyms)
3474 int i;
3476 for (i = 1; i < nsyms; i += 1)
3478 struct block_symbol sym = syms[i];
3479 int j;
3481 for (j = i - 1; j >= 0; j -= 1)
3483 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3484 sym.symbol->linkage_name ()))
3485 break;
3486 syms[j + 1] = syms[j];
3488 syms[j + 1] = sym;
3492 /* Whether GDB should display formals and return types for functions in the
3493 overloads selection menu. */
3494 static bool print_signatures = true;
3496 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3497 all but functions, the signature is just the name of the symbol. For
3498 functions, this is the name of the function, the list of types for formals
3499 and the return type (if any). */
3501 static void
3502 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3503 const struct type_print_options *flags)
3505 struct type *type = sym->type ();
3507 gdb_printf (stream, "%s", sym->print_name ());
3508 if (!print_signatures
3509 || type == NULL
3510 || type->code () != TYPE_CODE_FUNC)
3511 return;
3513 if (type->num_fields () > 0)
3515 int i;
3517 gdb_printf (stream, " (");
3518 for (i = 0; i < type->num_fields (); ++i)
3520 if (i > 0)
3521 gdb_printf (stream, "; ");
3522 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3523 flags);
3525 gdb_printf (stream, ")");
3527 if (type->target_type () != NULL
3528 && type->target_type ()->code () != TYPE_CODE_VOID)
3530 gdb_printf (stream, " return ");
3531 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3535 /* Read and validate a set of numeric choices from the user in the
3536 range 0 .. N_CHOICES-1. Place the results in increasing
3537 order in CHOICES[0 .. N-1], and return N.
3539 The user types choices as a sequence of numbers on one line
3540 separated by blanks, encoding them as follows:
3542 + A choice of 0 means to cancel the selection, throwing an error.
3543 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3544 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3546 The user is not allowed to choose more than MAX_RESULTS values.
3548 ANNOTATION_SUFFIX, if present, is used to annotate the input
3549 prompts (for use with the -f switch). */
3551 static int
3552 get_selections (int *choices, int n_choices, int max_results,
3553 int is_all_choice, const char *annotation_suffix)
3555 const char *args;
3556 const char *prompt;
3557 int n_chosen;
3558 int first_choice = is_all_choice ? 2 : 1;
3560 prompt = getenv ("PS2");
3561 if (prompt == NULL)
3562 prompt = "> ";
3564 std::string buffer;
3565 args = command_line_input (buffer, prompt, annotation_suffix);
3567 if (args == NULL)
3568 error_no_arg (_("one or more choice numbers"));
3570 n_chosen = 0;
3572 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3573 order, as given in args. Choices are validated. */
3574 while (1)
3576 char *args2;
3577 int choice, j;
3579 args = skip_spaces (args);
3580 if (*args == '\0' && n_chosen == 0)
3581 error_no_arg (_("one or more choice numbers"));
3582 else if (*args == '\0')
3583 break;
3585 choice = strtol (args, &args2, 10);
3586 if (args == args2 || choice < 0
3587 || choice > n_choices + first_choice - 1)
3588 error (_("Argument must be choice number"));
3589 args = args2;
3591 if (choice == 0)
3592 error (_("cancelled"));
3594 if (choice < first_choice)
3596 n_chosen = n_choices;
3597 for (j = 0; j < n_choices; j += 1)
3598 choices[j] = j;
3599 break;
3601 choice -= first_choice;
3603 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3607 if (j < 0 || choice != choices[j])
3609 int k;
3611 for (k = n_chosen - 1; k > j; k -= 1)
3612 choices[k + 1] = choices[k];
3613 choices[j + 1] = choice;
3614 n_chosen += 1;
3618 if (n_chosen > max_results)
3619 error (_("Select no more than %d of the above"), max_results);
3621 return n_chosen;
3624 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3625 by asking the user (if necessary), returning the number selected,
3626 and setting the first elements of SYMS items. Error if no symbols
3627 selected. */
3629 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3630 to be re-integrated one of these days. */
3632 static int
3633 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3635 int i;
3636 int *chosen = XALLOCAVEC (int , nsyms);
3637 int n_chosen;
3638 int first_choice = (max_results == 1) ? 1 : 2;
3639 const char *select_mode = multiple_symbols_select_mode ();
3641 if (max_results < 1)
3642 error (_("Request to select 0 symbols!"));
3643 if (nsyms <= 1)
3644 return nsyms;
3646 if (select_mode == multiple_symbols_cancel)
3647 error (_("\
3648 canceled because the command is ambiguous\n\
3649 See set/show multiple-symbol."));
3651 /* If select_mode is "all", then return all possible symbols.
3652 Only do that if more than one symbol can be selected, of course.
3653 Otherwise, display the menu as usual. */
3654 if (select_mode == multiple_symbols_all && max_results > 1)
3655 return nsyms;
3657 gdb_printf (_("[0] cancel\n"));
3658 if (max_results > 1)
3659 gdb_printf (_("[1] all\n"));
3661 sort_choices (syms, nsyms);
3663 for (i = 0; i < nsyms; i += 1)
3665 if (syms[i].symbol == NULL)
3666 continue;
3668 if (syms[i].symbol->aclass () == LOC_BLOCK)
3670 struct symtab_and_line sal =
3671 find_function_start_sal (syms[i].symbol, 1);
3673 gdb_printf ("[%d] ", i + first_choice);
3674 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3675 &type_print_raw_options);
3676 if (sal.symtab == NULL)
3677 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3678 metadata_style.style ().ptr (), nullptr, sal.line);
3679 else
3680 gdb_printf
3681 (_(" at %ps:%d\n"),
3682 styled_string (file_name_style.style (),
3683 symtab_to_filename_for_display (sal.symtab)),
3684 sal.line);
3685 continue;
3687 else
3689 int is_enumeral =
3690 (syms[i].symbol->aclass () == LOC_CONST
3691 && syms[i].symbol->type () != NULL
3692 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3693 struct symtab *symtab = NULL;
3695 if (syms[i].symbol->is_objfile_owned ())
3696 symtab = syms[i].symbol->symtab ();
3698 if (syms[i].symbol->line () != 0 && symtab != NULL)
3700 gdb_printf ("[%d] ", i + first_choice);
3701 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3702 &type_print_raw_options);
3703 gdb_printf (_(" at %s:%d\n"),
3704 symtab_to_filename_for_display (symtab),
3705 syms[i].symbol->line ());
3707 else if (is_enumeral
3708 && syms[i].symbol->type ()->name () != NULL)
3710 gdb_printf (("[%d] "), i + first_choice);
3711 ada_print_type (syms[i].symbol->type (), NULL,
3712 gdb_stdout, -1, 0, &type_print_raw_options);
3713 gdb_printf (_("'(%s) (enumeral)\n"),
3714 syms[i].symbol->print_name ());
3716 else
3718 gdb_printf ("[%d] ", i + first_choice);
3719 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3720 &type_print_raw_options);
3722 if (symtab != NULL)
3723 gdb_printf (is_enumeral
3724 ? _(" in %s (enumeral)\n")
3725 : _(" at %s:?\n"),
3726 symtab_to_filename_for_display (symtab));
3727 else
3728 gdb_printf (is_enumeral
3729 ? _(" (enumeral)\n")
3730 : _(" at ?\n"));
3735 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3736 "overload-choice");
3738 for (i = 0; i < n_chosen; i += 1)
3739 syms[i] = syms[chosen[i]];
3741 return n_chosen;
3744 /* See ada-lang.h. */
3746 block_symbol
3747 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3748 int nargs, value *argvec[])
3750 if (possible_user_operator_p (op, argvec))
3752 std::vector<struct block_symbol> candidates
3753 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3754 NULL, VAR_DOMAIN);
3756 int i = ada_resolve_function (candidates, argvec,
3757 nargs, ada_decoded_op_name (op), NULL,
3758 parse_completion);
3759 if (i >= 0)
3760 return candidates[i];
3762 return {};
3765 /* See ada-lang.h. */
3767 block_symbol
3768 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3769 struct type *context_type,
3770 bool parse_completion,
3771 int nargs, value *argvec[],
3772 innermost_block_tracker *tracker)
3774 std::vector<struct block_symbol> candidates
3775 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3777 int i;
3778 if (candidates.size () == 1)
3779 i = 0;
3780 else
3782 i = ada_resolve_function
3783 (candidates,
3784 argvec, nargs,
3785 sym->linkage_name (),
3786 context_type, parse_completion);
3787 if (i < 0)
3788 error (_("Could not find a match for %s"), sym->print_name ());
3791 tracker->update (candidates[i]);
3792 return candidates[i];
3795 /* Resolve a mention of a name where the context type is an
3796 enumeration type. */
3798 static int
3799 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3800 const char *name, struct type *context_type,
3801 bool parse_completion)
3803 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3804 context_type = ada_check_typedef (context_type);
3806 /* We already know the name matches, so we're just looking for
3807 an element of the correct enum type. */
3808 struct type *type1 = context_type;
3809 for (int i = 0; i < syms.size (); ++i)
3811 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3812 if (type1 == type2)
3813 return i;
3816 for (int i = 0; i < syms.size (); ++i)
3818 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3819 if (type1->num_fields () != type2->num_fields ())
3820 continue;
3821 if (strcmp (type1->name (), type2->name ()) != 0)
3822 continue;
3823 if (ada_identical_enum_types_p (type1, type2))
3824 return i;
3827 error (_("No name '%s' in enumeration type '%s'"), name,
3828 ada_type_name (context_type));
3831 /* See ada-lang.h. */
3833 block_symbol
3834 ada_resolve_variable (struct symbol *sym, const struct block *block,
3835 struct type *context_type,
3836 bool parse_completion,
3837 int deprocedure_p,
3838 innermost_block_tracker *tracker)
3840 std::vector<struct block_symbol> candidates
3841 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3843 if (std::any_of (candidates.begin (),
3844 candidates.end (),
3845 [] (block_symbol &bsym)
3847 switch (bsym.symbol->aclass ())
3849 case LOC_REGISTER:
3850 case LOC_ARG:
3851 case LOC_REF_ARG:
3852 case LOC_REGPARM_ADDR:
3853 case LOC_LOCAL:
3854 case LOC_COMPUTED:
3855 return true;
3856 default:
3857 return false;
3861 /* Types tend to get re-introduced locally, so if there
3862 are any local symbols that are not types, first filter
3863 out all types. */
3864 candidates.erase
3865 (std::remove_if
3866 (candidates.begin (),
3867 candidates.end (),
3868 [] (block_symbol &bsym)
3870 return bsym.symbol->aclass () == LOC_TYPEDEF;
3872 candidates.end ());
3875 /* Filter out artificial symbols. */
3876 candidates.erase
3877 (std::remove_if
3878 (candidates.begin (),
3879 candidates.end (),
3880 [] (block_symbol &bsym)
3882 return bsym.symbol->is_artificial ();
3884 candidates.end ());
3886 int i;
3887 if (candidates.empty ())
3888 error (_("No definition found for %s"), sym->print_name ());
3889 else if (candidates.size () == 1)
3890 i = 0;
3891 else if (context_type != nullptr
3892 && context_type->code () == TYPE_CODE_ENUM)
3893 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3894 parse_completion);
3895 else if (context_type == nullptr
3896 && symbols_are_identical_enums (candidates))
3898 /* If all the remaining symbols are identical enumerals, then
3899 just keep the first one and discard the rest.
3901 Unlike what we did previously, we do not discard any entry
3902 unless they are ALL identical. This is because the symbol
3903 comparison is not a strict comparison, but rather a practical
3904 comparison. If all symbols are considered identical, then
3905 we can just go ahead and use the first one and discard the rest.
3906 But if we cannot reduce the list to a single element, we have
3907 to ask the user to disambiguate anyways. And if we have to
3908 present a multiple-choice menu, it's less confusing if the list
3909 isn't missing some choices that were identical and yet distinct. */
3910 candidates.resize (1);
3911 i = 0;
3913 else if (deprocedure_p && !is_nonfunction (candidates))
3915 i = ada_resolve_function
3916 (candidates, NULL, 0,
3917 sym->linkage_name (),
3918 context_type, parse_completion);
3919 if (i < 0)
3920 error (_("Could not find a match for %s"), sym->print_name ());
3922 else
3924 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3925 user_select_syms (candidates.data (), candidates.size (), 1);
3926 i = 0;
3929 tracker->update (candidates[i]);
3930 return candidates[i];
3933 /* Return non-zero if formal type FTYPE matches actual type ATYPE. */
3934 /* The term "match" here is rather loose. The match is heuristic and
3935 liberal. */
3937 static int
3938 ada_type_match (struct type *ftype, struct type *atype)
3940 ftype = ada_check_typedef (ftype);
3941 atype = ada_check_typedef (atype);
3943 if (ftype->code () == TYPE_CODE_REF)
3944 ftype = ftype->target_type ();
3945 if (atype->code () == TYPE_CODE_REF)
3946 atype = atype->target_type ();
3948 switch (ftype->code ())
3950 default:
3951 return ftype->code () == atype->code ();
3952 case TYPE_CODE_PTR:
3953 if (atype->code () != TYPE_CODE_PTR)
3954 return 0;
3955 atype = atype->target_type ();
3956 /* This can only happen if the actual argument is 'null'. */
3957 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3958 return 1;
3959 return ada_type_match (ftype->target_type (), atype);
3960 case TYPE_CODE_INT:
3961 case TYPE_CODE_ENUM:
3962 case TYPE_CODE_RANGE:
3963 switch (atype->code ())
3965 case TYPE_CODE_INT:
3966 case TYPE_CODE_ENUM:
3967 case TYPE_CODE_RANGE:
3968 return 1;
3969 default:
3970 return 0;
3973 case TYPE_CODE_ARRAY:
3974 return (atype->code () == TYPE_CODE_ARRAY
3975 || ada_is_array_descriptor_type (atype));
3977 case TYPE_CODE_STRUCT:
3978 if (ada_is_array_descriptor_type (ftype))
3979 return (atype->code () == TYPE_CODE_ARRAY
3980 || ada_is_array_descriptor_type (atype));
3981 else
3982 return (atype->code () == TYPE_CODE_STRUCT
3983 && !ada_is_array_descriptor_type (atype));
3985 case TYPE_CODE_UNION:
3986 case TYPE_CODE_FLT:
3987 return (atype->code () == ftype->code ());
3991 /* Return non-zero if the formals of FUNC "sufficiently match" the
3992 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3993 may also be an enumeral, in which case it is treated as a 0-
3994 argument function. */
3996 static int
3997 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3999 int i;
4000 struct type *func_type = func->type ();
4002 if (func->aclass () == LOC_CONST
4003 && func_type->code () == TYPE_CODE_ENUM)
4004 return (n_actuals == 0);
4005 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
4006 return 0;
4008 if (func_type->num_fields () != n_actuals)
4009 return 0;
4011 for (i = 0; i < n_actuals; i += 1)
4013 if (actuals[i] == NULL)
4014 return 0;
4015 else
4017 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
4018 struct type *atype = ada_check_typedef (actuals[i]->type ());
4020 if (!ada_type_match (ftype, atype))
4021 return 0;
4024 return 1;
4027 /* False iff function type FUNC_TYPE definitely does not produce a value
4028 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4029 FUNC_TYPE is not a valid function type with a non-null return type
4030 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4032 static int
4033 return_match (struct type *func_type, struct type *context_type)
4035 struct type *return_type;
4037 if (func_type == NULL)
4038 return 1;
4040 if (func_type->code () == TYPE_CODE_FUNC)
4041 return_type = get_base_type (func_type->target_type ());
4042 else
4043 return_type = get_base_type (func_type);
4044 if (return_type == NULL)
4045 return 1;
4047 context_type = get_base_type (context_type);
4049 if (return_type->code () == TYPE_CODE_ENUM)
4050 return context_type == NULL || return_type == context_type;
4051 else if (context_type == NULL)
4052 return return_type->code () != TYPE_CODE_VOID;
4053 else
4054 return return_type->code () == context_type->code ();
4058 /* Returns the index in SYMS that contains the symbol for the
4059 function (if any) that matches the types of the NARGS arguments in
4060 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4061 that returns that type, then eliminate matches that don't. If
4062 CONTEXT_TYPE is void and there is at least one match that does not
4063 return void, eliminate all matches that do.
4065 Asks the user if there is more than one match remaining. Returns -1
4066 if there is no such symbol or none is selected. NAME is used
4067 solely for messages. May re-arrange and modify SYMS in
4068 the process; the index returned is for the modified vector. */
4070 static int
4071 ada_resolve_function (std::vector<struct block_symbol> &syms,
4072 struct value **args, int nargs,
4073 const char *name, struct type *context_type,
4074 bool parse_completion)
4076 int fallback;
4077 int k;
4078 int m; /* Number of hits */
4080 m = 0;
4081 /* In the first pass of the loop, we only accept functions matching
4082 context_type. If none are found, we add a second pass of the loop
4083 where every function is accepted. */
4084 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4086 for (k = 0; k < syms.size (); k += 1)
4088 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4090 if (ada_args_match (syms[k].symbol, args, nargs)
4091 && (fallback || return_match (type, context_type)))
4093 syms[m] = syms[k];
4094 m += 1;
4099 /* If we got multiple matches, ask the user which one to use. Don't do this
4100 interactive thing during completion, though, as the purpose of the
4101 completion is providing a list of all possible matches. Prompting the
4102 user to filter it down would be completely unexpected in this case. */
4103 if (m == 0)
4104 return -1;
4105 else if (m > 1 && !parse_completion)
4107 gdb_printf (_("Multiple matches for %s\n"), name);
4108 user_select_syms (syms.data (), m, 1);
4109 return 0;
4111 return 0;
4114 /* Type-class predicates */
4116 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4117 or FLOAT). */
4119 static int
4120 numeric_type_p (struct type *type)
4122 if (type == NULL)
4123 return 0;
4124 else
4126 switch (type->code ())
4128 case TYPE_CODE_INT:
4129 case TYPE_CODE_FLT:
4130 case TYPE_CODE_FIXED_POINT:
4131 return 1;
4132 case TYPE_CODE_RANGE:
4133 return (type == type->target_type ()
4134 || numeric_type_p (type->target_type ()));
4135 default:
4136 return 0;
4141 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4143 static int
4144 integer_type_p (struct type *type)
4146 if (type == NULL)
4147 return 0;
4148 else
4150 switch (type->code ())
4152 case TYPE_CODE_INT:
4153 return 1;
4154 case TYPE_CODE_RANGE:
4155 return (type == type->target_type ()
4156 || integer_type_p (type->target_type ()));
4157 default:
4158 return 0;
4163 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4165 static int
4166 scalar_type_p (struct type *type)
4168 if (type == NULL)
4169 return 0;
4170 else
4172 switch (type->code ())
4174 case TYPE_CODE_INT:
4175 case TYPE_CODE_RANGE:
4176 case TYPE_CODE_ENUM:
4177 case TYPE_CODE_FLT:
4178 case TYPE_CODE_FIXED_POINT:
4179 return 1;
4180 default:
4181 return 0;
4186 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4187 This essentially means one of (INT, RANGE, ENUM) -- but note that
4188 "enum" includes character and boolean as well. */
4190 static int
4191 discrete_type_p (struct type *type)
4193 if (type == NULL)
4194 return 0;
4195 else
4197 switch (type->code ())
4199 case TYPE_CODE_INT:
4200 case TYPE_CODE_RANGE:
4201 case TYPE_CODE_ENUM:
4202 case TYPE_CODE_BOOL:
4203 case TYPE_CODE_CHAR:
4204 return 1;
4205 default:
4206 return 0;
4211 /* Returns non-zero if OP with operands in the vector ARGS could be
4212 a user-defined function. Errs on the side of pre-defined operators
4213 (i.e., result 0). */
4215 static int
4216 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4218 struct type *type0 =
4219 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4220 struct type *type1 =
4221 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4223 if (type0 == NULL)
4224 return 0;
4226 switch (op)
4228 default:
4229 return 0;
4231 case BINOP_ADD:
4232 case BINOP_SUB:
4233 case BINOP_MUL:
4234 case BINOP_DIV:
4235 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4237 case BINOP_REM:
4238 case BINOP_MOD:
4239 case BINOP_BITWISE_AND:
4240 case BINOP_BITWISE_IOR:
4241 case BINOP_BITWISE_XOR:
4242 return (!(integer_type_p (type0) && integer_type_p (type1)));
4244 case BINOP_EQUAL:
4245 case BINOP_NOTEQUAL:
4246 case BINOP_LESS:
4247 case BINOP_GTR:
4248 case BINOP_LEQ:
4249 case BINOP_GEQ:
4250 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4252 case BINOP_CONCAT:
4253 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4255 case BINOP_EXP:
4256 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4258 case UNOP_NEG:
4259 case UNOP_PLUS:
4260 case UNOP_LOGICAL_NOT:
4261 case UNOP_ABS:
4262 return (!numeric_type_p (type0));
4267 /* Renaming */
4269 /* NOTES:
4271 1. In the following, we assume that a renaming type's name may
4272 have an ___XD suffix. It would be nice if this went away at some
4273 point.
4274 2. We handle both the (old) purely type-based representation of
4275 renamings and the (new) variable-based encoding. At some point,
4276 it is devoutly to be hoped that the former goes away
4277 (FIXME: hilfinger-2007-07-09).
4278 3. Subprogram renamings are not implemented, although the XRS
4279 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4281 /* If SYM encodes a renaming,
4283 <renaming> renames <renamed entity>,
4285 sets *LEN to the length of the renamed entity's name,
4286 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4287 the string describing the subcomponent selected from the renamed
4288 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4289 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4290 are undefined). Otherwise, returns a value indicating the category
4291 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4292 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4293 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4294 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4295 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4296 may be NULL, in which case they are not assigned.
4298 [Currently, however, GCC does not generate subprogram renamings.] */
4300 enum ada_renaming_category
4301 ada_parse_renaming (struct symbol *sym,
4302 const char **renamed_entity, int *len,
4303 const char **renaming_expr)
4305 enum ada_renaming_category kind;
4306 const char *info;
4307 const char *suffix;
4309 if (sym == NULL)
4310 return ADA_NOT_RENAMING;
4311 switch (sym->aclass ())
4313 default:
4314 return ADA_NOT_RENAMING;
4315 case LOC_LOCAL:
4316 case LOC_STATIC:
4317 case LOC_COMPUTED:
4318 case LOC_OPTIMIZED_OUT:
4319 info = strstr (sym->linkage_name (), "___XR");
4320 if (info == NULL)
4321 return ADA_NOT_RENAMING;
4322 switch (info[5])
4324 case '_':
4325 kind = ADA_OBJECT_RENAMING;
4326 info += 6;
4327 break;
4328 case 'E':
4329 kind = ADA_EXCEPTION_RENAMING;
4330 info += 7;
4331 break;
4332 case 'P':
4333 kind = ADA_PACKAGE_RENAMING;
4334 info += 7;
4335 break;
4336 case 'S':
4337 kind = ADA_SUBPROGRAM_RENAMING;
4338 info += 7;
4339 break;
4340 default:
4341 return ADA_NOT_RENAMING;
4345 if (renamed_entity != NULL)
4346 *renamed_entity = info;
4347 suffix = strstr (info, "___XE");
4348 if (suffix == NULL || suffix == info)
4349 return ADA_NOT_RENAMING;
4350 if (len != NULL)
4351 *len = strlen (info) - strlen (suffix);
4352 suffix += 5;
4353 if (renaming_expr != NULL)
4354 *renaming_expr = suffix;
4355 return kind;
4358 /* Compute the value of the given RENAMING_SYM, which is expected to
4359 be a symbol encoding a renaming expression. BLOCK is the block
4360 used to evaluate the renaming. */
4362 static struct value *
4363 ada_read_renaming_var_value (struct symbol *renaming_sym,
4364 const struct block *block)
4366 const char *sym_name;
4368 sym_name = renaming_sym->linkage_name ();
4369 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4370 return expr->evaluate ();
4374 /* Evaluation: Function Calls */
4376 /* Return an lvalue containing the value VAL. This is the identity on
4377 lvalues, and otherwise has the side-effect of allocating memory
4378 in the inferior where a copy of the value contents is copied. */
4380 static struct value *
4381 ensure_lval (struct value *val)
4383 if (val->lval () == not_lval
4384 || val->lval () == lval_internalvar)
4386 int len = ada_check_typedef (val->type ())->length ();
4387 const CORE_ADDR addr =
4388 value_as_long (value_allocate_space_in_inferior (len));
4390 val->set_lval (lval_memory);
4391 val->set_address (addr);
4392 write_memory (addr, val->contents ().data (), len);
4395 return val;
4398 /* Given ARG, a value of type (pointer or reference to a)*
4399 structure/union, extract the component named NAME from the ultimate
4400 target structure/union and return it as a value with its
4401 appropriate type.
4403 The routine searches for NAME among all members of the structure itself
4404 and (recursively) among all members of any wrapper members
4405 (e.g., '_parent').
4407 If NO_ERR, then simply return NULL in case of error, rather than
4408 calling error. */
4410 static struct value *
4411 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4413 struct type *t, *t1;
4414 struct value *v;
4415 int check_tag;
4417 v = NULL;
4418 t1 = t = ada_check_typedef (arg->type ());
4419 if (t->code () == TYPE_CODE_REF)
4421 t1 = t->target_type ();
4422 if (t1 == NULL)
4423 goto BadValue;
4424 t1 = ada_check_typedef (t1);
4425 if (t1->code () == TYPE_CODE_PTR)
4427 arg = coerce_ref (arg);
4428 t = t1;
4432 while (t->code () == TYPE_CODE_PTR)
4434 t1 = t->target_type ();
4435 if (t1 == NULL)
4436 goto BadValue;
4437 t1 = ada_check_typedef (t1);
4438 if (t1->code () == TYPE_CODE_PTR)
4440 arg = value_ind (arg);
4441 t = t1;
4443 else
4444 break;
4447 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4448 goto BadValue;
4450 if (t1 == t)
4451 v = ada_search_struct_field (name, arg, 0, t);
4452 else
4454 int bit_offset, bit_size, byte_offset;
4455 struct type *field_type;
4456 CORE_ADDR address;
4458 if (t->code () == TYPE_CODE_PTR)
4459 address = ada_value_ind (arg)->address ();
4460 else
4461 address = ada_coerce_ref (arg)->address ();
4463 /* Check to see if this is a tagged type. We also need to handle
4464 the case where the type is a reference to a tagged type, but
4465 we have to be careful to exclude pointers to tagged types.
4466 The latter should be shown as usual (as a pointer), whereas
4467 a reference should mostly be transparent to the user. */
4469 if (ada_is_tagged_type (t1, 0)
4470 || (t1->code () == TYPE_CODE_REF
4471 && ada_is_tagged_type (t1->target_type (), 0)))
4473 /* We first try to find the searched field in the current type.
4474 If not found then let's look in the fixed type. */
4476 if (!find_struct_field (name, t1, 0,
4477 nullptr, nullptr, nullptr,
4478 nullptr, nullptr))
4479 check_tag = 1;
4480 else
4481 check_tag = 0;
4483 else
4484 check_tag = 0;
4486 /* Convert to fixed type in all cases, so that we have proper
4487 offsets to each field in unconstrained record types. */
4488 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4489 address, NULL, check_tag);
4491 /* Resolve the dynamic type as well. */
4492 arg = value_from_contents_and_address (t1, nullptr, address);
4493 t1 = arg->type ();
4495 if (find_struct_field (name, t1, 0,
4496 &field_type, &byte_offset, &bit_offset,
4497 &bit_size, NULL))
4499 if (bit_size != 0)
4501 if (t->code () == TYPE_CODE_REF)
4502 arg = ada_coerce_ref (arg);
4503 else
4504 arg = ada_value_ind (arg);
4505 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4506 bit_offset, bit_size,
4507 field_type);
4509 else
4510 v = value_at_lazy (field_type, address + byte_offset);
4514 if (v != NULL || no_err)
4515 return v;
4516 else
4517 error (_("There is no member named %s."), name);
4519 BadValue:
4520 if (no_err)
4521 return NULL;
4522 else
4523 error (_("Attempt to extract a component of "
4524 "a value that is not a record."));
4527 /* Return the value ACTUAL, converted to be an appropriate value for a
4528 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4529 allocating any necessary descriptors (fat pointers), or copies of
4530 values not residing in memory, updating it as needed. */
4532 struct value *
4533 ada_convert_actual (struct value *actual, struct type *formal_type0)
4535 struct type *actual_type = ada_check_typedef (actual->type ());
4536 struct type *formal_type = ada_check_typedef (formal_type0);
4537 struct type *formal_target =
4538 formal_type->code () == TYPE_CODE_PTR
4539 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4540 struct type *actual_target =
4541 actual_type->code () == TYPE_CODE_PTR
4542 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4544 if (ada_is_array_descriptor_type (formal_target)
4545 && actual_target->code () == TYPE_CODE_ARRAY)
4546 return make_array_descriptor (formal_type, actual);
4547 else if (formal_type->code () == TYPE_CODE_PTR
4548 || formal_type->code () == TYPE_CODE_REF)
4550 struct value *result;
4552 if (formal_target->code () == TYPE_CODE_ARRAY
4553 && ada_is_array_descriptor_type (actual_target))
4554 result = desc_data (actual);
4555 else if (formal_type->code () != TYPE_CODE_PTR)
4557 if (actual->lval () != lval_memory)
4559 struct value *val;
4561 actual_type = ada_check_typedef (actual->type ());
4562 val = value::allocate (actual_type);
4563 copy (actual->contents (), val->contents_raw ());
4564 actual = ensure_lval (val);
4566 result = value_addr (actual);
4568 else
4569 return actual;
4570 return value_cast_pointers (formal_type, result, 0);
4572 else if (actual_type->code () == TYPE_CODE_PTR)
4573 return ada_value_ind (actual);
4574 else if (ada_is_aligner_type (formal_type))
4576 /* We need to turn this parameter into an aligner type
4577 as well. */
4578 struct value *aligner = value::allocate (formal_type);
4579 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4581 value_assign_to_component (aligner, component, actual);
4582 return aligner;
4585 return actual;
4588 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4589 type TYPE. This is usually an inefficient no-op except on some targets
4590 (such as AVR) where the representation of a pointer and an address
4591 differs. */
4593 static CORE_ADDR
4594 value_pointer (struct value *value, struct type *type)
4596 unsigned len = type->length ();
4597 gdb_byte *buf = (gdb_byte *) alloca (len);
4598 CORE_ADDR addr;
4600 addr = value->address ();
4601 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4602 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4603 return addr;
4607 /* Push a descriptor of type TYPE for array value ARR on the stack at
4608 *SP, updating *SP to reflect the new descriptor. Return either
4609 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4610 to-descriptor type rather than a descriptor type), a struct value *
4611 representing a pointer to this descriptor. */
4613 static struct value *
4614 make_array_descriptor (struct type *type, struct value *arr)
4616 struct type *bounds_type = desc_bounds_type (type);
4617 struct type *desc_type = desc_base_type (type);
4618 struct value *descriptor = value::allocate (desc_type);
4619 struct value *bounds = value::allocate (bounds_type);
4620 int i;
4622 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4623 i > 0; i -= 1)
4625 modify_field (bounds->type (),
4626 bounds->contents_writeable ().data (),
4627 ada_array_bound (arr, i, 0),
4628 desc_bound_bitpos (bounds_type, i, 0),
4629 desc_bound_bitsize (bounds_type, i, 0));
4630 modify_field (bounds->type (),
4631 bounds->contents_writeable ().data (),
4632 ada_array_bound (arr, i, 1),
4633 desc_bound_bitpos (bounds_type, i, 1),
4634 desc_bound_bitsize (bounds_type, i, 1));
4637 bounds = ensure_lval (bounds);
4639 modify_field (descriptor->type (),
4640 descriptor->contents_writeable ().data (),
4641 value_pointer (ensure_lval (arr),
4642 desc_type->field (0).type ()),
4643 fat_pntr_data_bitpos (desc_type),
4644 fat_pntr_data_bitsize (desc_type));
4646 modify_field (descriptor->type (),
4647 descriptor->contents_writeable ().data (),
4648 value_pointer (bounds,
4649 desc_type->field (1).type ()),
4650 fat_pntr_bounds_bitpos (desc_type),
4651 fat_pntr_bounds_bitsize (desc_type));
4653 descriptor = ensure_lval (descriptor);
4655 if (type->code () == TYPE_CODE_PTR)
4656 return value_addr (descriptor);
4657 else
4658 return descriptor;
4661 /* Symbol Cache Module */
4663 /* Performance measurements made as of 2010-01-15 indicate that
4664 this cache does bring some noticeable improvements. Depending
4665 on the type of entity being printed, the cache can make it as much
4666 as an order of magnitude faster than without it.
4668 The descriptive type DWARF extension has significantly reduced
4669 the need for this cache, at least when DWARF is being used. However,
4670 even in this case, some expensive name-based symbol searches are still
4671 sometimes necessary - to find an XVZ variable, mostly. */
4673 /* Clear all entries from the symbol cache. */
4675 static void
4676 ada_clear_symbol_cache ()
4678 ada_pspace_data_handle.clear (current_program_space);
4681 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4682 Return 1 if found, 0 otherwise.
4684 If an entry was found and SYM is not NULL, set *SYM to the entry's
4685 SYM. Same principle for BLOCK if not NULL. */
4687 static int
4688 lookup_cached_symbol (const char *name, domain_enum domain,
4689 struct symbol **sym, const struct block **block)
4691 htab_t tab = get_ada_pspace_data (current_program_space);
4692 cache_entry_search search;
4693 search.name = name;
4694 search.domain = domain;
4696 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4697 search.hash ());
4698 if (e == nullptr)
4699 return 0;
4700 if (sym != nullptr)
4701 *sym = e->sym;
4702 if (block != nullptr)
4703 *block = e->block;
4704 return 1;
4707 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4708 in domain DOMAIN, save this result in our symbol cache. */
4710 static void
4711 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4712 const struct block *block)
4714 /* Symbols for builtin types don't have a block.
4715 For now don't cache such symbols. */
4716 if (sym != NULL && !sym->is_objfile_owned ())
4717 return;
4719 /* If the symbol is a local symbol, then do not cache it, as a search
4720 for that symbol depends on the context. To determine whether
4721 the symbol is local or not, we check the block where we found it
4722 against the global and static blocks of its associated symtab. */
4723 if (sym != nullptr)
4725 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4727 if (bv.global_block () != block && bv.static_block () != block)
4728 return;
4731 htab_t tab = get_ada_pspace_data (current_program_space);
4732 cache_entry_search search;
4733 search.name = name;
4734 search.domain = domain;
4736 void **slot = htab_find_slot_with_hash (tab, &search,
4737 search.hash (), INSERT);
4739 cache_entry *e = new cache_entry;
4740 e->name = name;
4741 e->domain = domain;
4742 e->sym = sym;
4743 e->block = block;
4745 *slot = e;
4748 /* Symbol Lookup */
4750 /* Return the symbol name match type that should be used used when
4751 searching for all symbols matching LOOKUP_NAME.
4753 LOOKUP_NAME is expected to be a symbol name after transformation
4754 for Ada lookups. */
4756 static symbol_name_match_type
4757 name_match_type_from_name (const char *lookup_name)
4759 return (strstr (lookup_name, "__") == NULL
4760 ? symbol_name_match_type::WILD
4761 : symbol_name_match_type::FULL);
4764 /* Return the result of a standard (literal, C-like) lookup of NAME in
4765 given DOMAIN, visible from lexical block BLOCK. */
4767 static struct symbol *
4768 standard_lookup (const char *name, const struct block *block,
4769 domain_enum domain)
4771 /* Initialize it just to avoid a GCC false warning. */
4772 struct block_symbol sym = {};
4774 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4775 return sym.symbol;
4776 ada_lookup_encoded_symbol (name, block, domain, &sym);
4777 cache_symbol (name, domain, sym.symbol, sym.block);
4778 return sym.symbol;
4782 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4783 in the symbol fields of SYMS. We treat enumerals as functions,
4784 since they contend in overloading in the same way. */
4785 static int
4786 is_nonfunction (const std::vector<struct block_symbol> &syms)
4788 for (const block_symbol &sym : syms)
4789 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4790 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4791 || sym.symbol->aclass () != LOC_CONST))
4792 return 1;
4794 return 0;
4797 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4798 struct types. Otherwise, they may not. */
4800 static int
4801 equiv_types (struct type *type0, struct type *type1)
4803 if (type0 == type1)
4804 return 1;
4805 if (type0 == NULL || type1 == NULL
4806 || type0->code () != type1->code ())
4807 return 0;
4808 if ((type0->code () == TYPE_CODE_STRUCT
4809 || type0->code () == TYPE_CODE_ENUM)
4810 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4811 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4812 return 1;
4814 return 0;
4817 /* True iff SYM0 represents the same entity as SYM1, or one that is
4818 no more defined than that of SYM1. */
4820 static int
4821 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4823 if (sym0 == sym1)
4824 return 1;
4825 if (sym0->domain () != sym1->domain ()
4826 || sym0->aclass () != sym1->aclass ())
4827 return 0;
4829 switch (sym0->aclass ())
4831 case LOC_UNDEF:
4832 return 1;
4833 case LOC_TYPEDEF:
4835 struct type *type0 = sym0->type ();
4836 struct type *type1 = sym1->type ();
4837 const char *name0 = sym0->linkage_name ();
4838 const char *name1 = sym1->linkage_name ();
4839 int len0 = strlen (name0);
4841 return
4842 type0->code () == type1->code ()
4843 && (equiv_types (type0, type1)
4844 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4845 && startswith (name1 + len0, "___XV")));
4847 case LOC_CONST:
4848 return sym0->value_longest () == sym1->value_longest ()
4849 && equiv_types (sym0->type (), sym1->type ());
4851 case LOC_STATIC:
4853 const char *name0 = sym0->linkage_name ();
4854 const char *name1 = sym1->linkage_name ();
4855 return (strcmp (name0, name1) == 0
4856 && sym0->value_address () == sym1->value_address ());
4859 default:
4860 return 0;
4864 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4865 records in RESULT. Do nothing if SYM is a duplicate. */
4867 static void
4868 add_defn_to_vec (std::vector<struct block_symbol> &result,
4869 struct symbol *sym,
4870 const struct block *block)
4872 /* Do not try to complete stub types, as the debugger is probably
4873 already scanning all symbols matching a certain name at the
4874 time when this function is called. Trying to replace the stub
4875 type by its associated full type will cause us to restart a scan
4876 which may lead to an infinite recursion. Instead, the client
4877 collecting the matching symbols will end up collecting several
4878 matches, with at least one of them complete. It can then filter
4879 out the stub ones if needed. */
4881 for (int i = result.size () - 1; i >= 0; i -= 1)
4883 if (lesseq_defined_than (sym, result[i].symbol))
4884 return;
4885 else if (lesseq_defined_than (result[i].symbol, sym))
4887 result[i].symbol = sym;
4888 result[i].block = block;
4889 return;
4893 struct block_symbol info;
4894 info.symbol = sym;
4895 info.block = block;
4896 result.push_back (info);
4899 /* Return a bound minimal symbol matching NAME according to Ada
4900 decoding rules. Returns an invalid symbol if there is no such
4901 minimal symbol. Names prefixed with "standard__" are handled
4902 specially: "standard__" is first stripped off, and only static and
4903 global symbols are searched. */
4905 struct bound_minimal_symbol
4906 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4908 struct bound_minimal_symbol result;
4910 symbol_name_match_type match_type = name_match_type_from_name (name);
4911 lookup_name_info lookup_name (name, match_type);
4913 symbol_name_matcher_ftype *match_name
4914 = ada_get_symbol_name_matcher (lookup_name);
4916 gdbarch_iterate_over_objfiles_in_search_order
4917 (objfile != NULL ? objfile->arch () : target_gdbarch (),
4918 [&result, lookup_name, match_name] (struct objfile *obj)
4920 for (minimal_symbol *msymbol : obj->msymbols ())
4922 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4923 && msymbol->type () != mst_solib_trampoline)
4925 result.minsym = msymbol;
4926 result.objfile = obj;
4927 return 1;
4931 return 0;
4932 }, objfile);
4934 return result;
4937 /* True if TYPE is definitely an artificial type supplied to a symbol
4938 for which no debugging information was given in the symbol file. */
4940 static int
4941 is_nondebugging_type (struct type *type)
4943 const char *name = ada_type_name (type);
4945 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4948 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4949 that are deemed "identical" for practical purposes.
4951 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4952 types and that their number of enumerals is identical (in other
4953 words, type1->num_fields () == type2->num_fields ()). */
4955 static int
4956 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4958 int i;
4960 /* The heuristic we use here is fairly conservative. We consider
4961 that 2 enumerate types are identical if they have the same
4962 number of enumerals and that all enumerals have the same
4963 underlying value and name. */
4965 /* All enums in the type should have an identical underlying value. */
4966 for (i = 0; i < type1->num_fields (); i++)
4967 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4968 return 0;
4970 /* All enumerals should also have the same name (modulo any numerical
4971 suffix). */
4972 for (i = 0; i < type1->num_fields (); i++)
4974 const char *name_1 = type1->field (i).name ();
4975 const char *name_2 = type2->field (i).name ();
4976 int len_1 = strlen (name_1);
4977 int len_2 = strlen (name_2);
4979 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4980 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4981 if (len_1 != len_2
4982 || strncmp (type1->field (i).name (),
4983 type2->field (i).name (),
4984 len_1) != 0)
4985 return 0;
4988 return 1;
4991 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4992 that are deemed "identical" for practical purposes. Sometimes,
4993 enumerals are not strictly identical, but their types are so similar
4994 that they can be considered identical.
4996 For instance, consider the following code:
4998 type Color is (Black, Red, Green, Blue, White);
4999 type RGB_Color is new Color range Red .. Blue;
5001 Type RGB_Color is a subrange of an implicit type which is a copy
5002 of type Color. If we call that implicit type RGB_ColorB ("B" is
5003 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5004 As a result, when an expression references any of the enumeral
5005 by name (Eg. "print green"), the expression is technically
5006 ambiguous and the user should be asked to disambiguate. But
5007 doing so would only hinder the user, since it wouldn't matter
5008 what choice he makes, the outcome would always be the same.
5009 So, for practical purposes, we consider them as the same. */
5011 static int
5012 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5014 int i;
5016 /* Before performing a thorough comparison check of each type,
5017 we perform a series of inexpensive checks. We expect that these
5018 checks will quickly fail in the vast majority of cases, and thus
5019 help prevent the unnecessary use of a more expensive comparison.
5020 Said comparison also expects us to make some of these checks
5021 (see ada_identical_enum_types_p). */
5023 /* Quick check: All symbols should have an enum type. */
5024 for (i = 0; i < syms.size (); i++)
5025 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5026 return 0;
5028 /* Quick check: They should all have the same value. */
5029 for (i = 1; i < syms.size (); i++)
5030 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5031 return 0;
5033 /* Quick check: They should all have the same number of enumerals. */
5034 for (i = 1; i < syms.size (); i++)
5035 if (syms[i].symbol->type ()->num_fields ()
5036 != syms[0].symbol->type ()->num_fields ())
5037 return 0;
5039 /* All the sanity checks passed, so we might have a set of
5040 identical enumeration types. Perform a more complete
5041 comparison of the type of each symbol. */
5042 for (i = 1; i < syms.size (); i++)
5043 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5044 syms[0].symbol->type ()))
5045 return 0;
5047 return 1;
5050 /* Remove any non-debugging symbols in SYMS that definitely
5051 duplicate other symbols in the list (The only case I know of where
5052 this happens is when object files containing stabs-in-ecoff are
5053 linked with files containing ordinary ecoff debugging symbols (or no
5054 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5056 static void
5057 remove_extra_symbols (std::vector<struct block_symbol> &syms)
5059 int i, j;
5061 /* We should never be called with less than 2 symbols, as there
5062 cannot be any extra symbol in that case. But it's easy to
5063 handle, since we have nothing to do in that case. */
5064 if (syms.size () < 2)
5065 return;
5067 i = 0;
5068 while (i < syms.size ())
5070 bool remove_p = false;
5072 /* If two symbols have the same name and one of them is a stub type,
5073 the get rid of the stub. */
5075 if (syms[i].symbol->type ()->is_stub ()
5076 && syms[i].symbol->linkage_name () != NULL)
5078 for (j = 0; !remove_p && j < syms.size (); j++)
5080 if (j != i
5081 && !syms[j].symbol->type ()->is_stub ()
5082 && syms[j].symbol->linkage_name () != NULL
5083 && strcmp (syms[i].symbol->linkage_name (),
5084 syms[j].symbol->linkage_name ()) == 0)
5085 remove_p = true;
5089 /* Two symbols with the same name, same class and same address
5090 should be identical. */
5092 else if (syms[i].symbol->linkage_name () != NULL
5093 && syms[i].symbol->aclass () == LOC_STATIC
5094 && is_nondebugging_type (syms[i].symbol->type ()))
5096 for (j = 0; !remove_p && j < syms.size (); j += 1)
5098 if (i != j
5099 && syms[j].symbol->linkage_name () != NULL
5100 && strcmp (syms[i].symbol->linkage_name (),
5101 syms[j].symbol->linkage_name ()) == 0
5102 && (syms[i].symbol->aclass ()
5103 == syms[j].symbol->aclass ())
5104 && syms[i].symbol->value_address ()
5105 == syms[j].symbol->value_address ())
5106 remove_p = true;
5110 /* Two functions with the same block are identical. */
5112 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5114 for (j = 0; !remove_p && j < syms.size (); j += 1)
5116 if (i != j
5117 && syms[j].symbol->aclass () == LOC_BLOCK
5118 && (syms[i].symbol->value_block ()
5119 == syms[j].symbol->value_block ()))
5120 remove_p = true;
5124 if (remove_p)
5125 syms.erase (syms.begin () + i);
5126 else
5127 i += 1;
5131 /* Given a type that corresponds to a renaming entity, use the type name
5132 to extract the scope (package name or function name, fully qualified,
5133 and following the GNAT encoding convention) where this renaming has been
5134 defined. */
5136 static std::string
5137 xget_renaming_scope (struct type *renaming_type)
5139 /* The renaming types adhere to the following convention:
5140 <scope>__<rename>___<XR extension>.
5141 So, to extract the scope, we search for the "___XR" extension,
5142 and then backtrack until we find the first "__". */
5144 const char *name = renaming_type->name ();
5145 const char *suffix = strstr (name, "___XR");
5146 const char *last;
5148 /* Now, backtrack a bit until we find the first "__". Start looking
5149 at suffix - 3, as the <rename> part is at least one character long. */
5151 for (last = suffix - 3; last > name; last--)
5152 if (last[0] == '_' && last[1] == '_')
5153 break;
5155 /* Make a copy of scope and return it. */
5156 return std::string (name, last);
5159 /* Return nonzero if NAME corresponds to a package name. */
5161 static int
5162 is_package_name (const char *name)
5164 /* Here, We take advantage of the fact that no symbols are generated
5165 for packages, while symbols are generated for each function.
5166 So the condition for NAME represent a package becomes equivalent
5167 to NAME not existing in our list of symbols. There is only one
5168 small complication with library-level functions (see below). */
5170 /* If it is a function that has not been defined at library level,
5171 then we should be able to look it up in the symbols. */
5172 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5173 return 0;
5175 /* Library-level function names start with "_ada_". See if function
5176 "_ada_" followed by NAME can be found. */
5178 /* Do a quick check that NAME does not contain "__", since library-level
5179 functions names cannot contain "__" in them. */
5180 if (strstr (name, "__") != NULL)
5181 return 0;
5183 std::string fun_name = string_printf ("_ada_%s", name);
5185 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5188 /* Return nonzero if SYM corresponds to a renaming entity that is
5189 not visible from FUNCTION_NAME. */
5191 static int
5192 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5194 if (sym->aclass () != LOC_TYPEDEF)
5195 return 0;
5197 std::string scope = xget_renaming_scope (sym->type ());
5199 /* If the rename has been defined in a package, then it is visible. */
5200 if (is_package_name (scope.c_str ()))
5201 return 0;
5203 /* Check that the rename is in the current function scope by checking
5204 that its name starts with SCOPE. */
5206 /* If the function name starts with "_ada_", it means that it is
5207 a library-level function. Strip this prefix before doing the
5208 comparison, as the encoding for the renaming does not contain
5209 this prefix. */
5210 if (startswith (function_name, "_ada_"))
5211 function_name += 5;
5213 return !startswith (function_name, scope.c_str ());
5216 /* Remove entries from SYMS that corresponds to a renaming entity that
5217 is not visible from the function associated with CURRENT_BLOCK or
5218 that is superfluous due to the presence of more specific renaming
5219 information. Places surviving symbols in the initial entries of
5220 SYMS.
5222 Rationale:
5223 First, in cases where an object renaming is implemented as a
5224 reference variable, GNAT may produce both the actual reference
5225 variable and the renaming encoding. In this case, we discard the
5226 latter.
5228 Second, GNAT emits a type following a specified encoding for each renaming
5229 entity. Unfortunately, STABS currently does not support the definition
5230 of types that are local to a given lexical block, so all renamings types
5231 are emitted at library level. As a consequence, if an application
5232 contains two renaming entities using the same name, and a user tries to
5233 print the value of one of these entities, the result of the ada symbol
5234 lookup will also contain the wrong renaming type.
5236 This function partially covers for this limitation by attempting to
5237 remove from the SYMS list renaming symbols that should be visible
5238 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5239 method with the current information available. The implementation
5240 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5242 - When the user tries to print a rename in a function while there
5243 is another rename entity defined in a package: Normally, the
5244 rename in the function has precedence over the rename in the
5245 package, so the latter should be removed from the list. This is
5246 currently not the case.
5248 - This function will incorrectly remove valid renames if
5249 the CURRENT_BLOCK corresponds to a function which symbol name
5250 has been changed by an "Export" pragma. As a consequence,
5251 the user will be unable to print such rename entities. */
5253 static void
5254 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5255 const struct block *current_block)
5257 struct symbol *current_function;
5258 const char *current_function_name;
5259 int i;
5260 int is_new_style_renaming;
5262 /* If there is both a renaming foo___XR... encoded as a variable and
5263 a simple variable foo in the same block, discard the latter.
5264 First, zero out such symbols, then compress. */
5265 is_new_style_renaming = 0;
5266 for (i = 0; i < syms->size (); i += 1)
5268 struct symbol *sym = (*syms)[i].symbol;
5269 const struct block *block = (*syms)[i].block;
5270 const char *name;
5271 const char *suffix;
5273 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5274 continue;
5275 name = sym->linkage_name ();
5276 suffix = strstr (name, "___XR");
5278 if (suffix != NULL)
5280 int name_len = suffix - name;
5281 int j;
5283 is_new_style_renaming = 1;
5284 for (j = 0; j < syms->size (); j += 1)
5285 if (i != j && (*syms)[j].symbol != NULL
5286 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5287 name_len) == 0
5288 && block == (*syms)[j].block)
5289 (*syms)[j].symbol = NULL;
5292 if (is_new_style_renaming)
5294 int j, k;
5296 for (j = k = 0; j < syms->size (); j += 1)
5297 if ((*syms)[j].symbol != NULL)
5299 (*syms)[k] = (*syms)[j];
5300 k += 1;
5302 syms->resize (k);
5303 return;
5306 /* Extract the function name associated to CURRENT_BLOCK.
5307 Abort if unable to do so. */
5309 if (current_block == NULL)
5310 return;
5312 current_function = current_block->linkage_function ();
5313 if (current_function == NULL)
5314 return;
5316 current_function_name = current_function->linkage_name ();
5317 if (current_function_name == NULL)
5318 return;
5320 /* Check each of the symbols, and remove it from the list if it is
5321 a type corresponding to a renaming that is out of the scope of
5322 the current block. */
5324 i = 0;
5325 while (i < syms->size ())
5327 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5328 == ADA_OBJECT_RENAMING
5329 && old_renaming_is_invisible ((*syms)[i].symbol,
5330 current_function_name))
5331 syms->erase (syms->begin () + i);
5332 else
5333 i += 1;
5337 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5338 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5340 Note: This function assumes that RESULT is empty. */
5342 static void
5343 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5344 const lookup_name_info &lookup_name,
5345 const struct block *block, domain_enum domain)
5347 while (block != NULL)
5349 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5351 /* If we found a non-function match, assume that's the one. We
5352 only check this when finding a function boundary, so that we
5353 can accumulate all results from intervening blocks first. */
5354 if (block->function () != nullptr && is_nonfunction (result))
5355 return;
5357 block = block->superblock ();
5361 /* An object of this type is used as the callback argument when
5362 calling the map_matching_symbols method. */
5364 struct match_data
5366 explicit match_data (std::vector<struct block_symbol> *rp)
5367 : resultp (rp)
5370 DISABLE_COPY_AND_ASSIGN (match_data);
5372 bool operator() (struct block_symbol *bsym);
5374 struct objfile *objfile = nullptr;
5375 std::vector<struct block_symbol> *resultp;
5376 struct symbol *arg_sym = nullptr;
5377 bool found_sym = false;
5380 /* A callback for add_nonlocal_symbols that adds symbol, found in
5381 BSYM, to a list of symbols. */
5383 bool
5384 match_data::operator() (struct block_symbol *bsym)
5386 const struct block *block = bsym->block;
5387 struct symbol *sym = bsym->symbol;
5389 if (sym == NULL)
5391 if (!found_sym && arg_sym != NULL)
5392 add_defn_to_vec (*resultp, arg_sym, block);
5393 found_sym = false;
5394 arg_sym = NULL;
5396 else
5398 if (sym->aclass () == LOC_UNRESOLVED)
5399 return true;
5400 else if (sym->is_argument ())
5401 arg_sym = sym;
5402 else
5404 found_sym = true;
5405 add_defn_to_vec (*resultp, sym, block);
5408 return true;
5411 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5412 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5413 symbols to RESULT. Return whether we found such symbols. */
5415 static int
5416 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5417 const struct block *block,
5418 const lookup_name_info &lookup_name,
5419 domain_enum domain)
5421 struct using_direct *renaming;
5422 int defns_mark = result.size ();
5424 symbol_name_matcher_ftype *name_match
5425 = ada_get_symbol_name_matcher (lookup_name);
5427 for (renaming = block->get_using ();
5428 renaming != NULL;
5429 renaming = renaming->next)
5431 const char *r_name;
5433 /* Avoid infinite recursions: skip this renaming if we are actually
5434 already traversing it.
5436 Currently, symbol lookup in Ada don't use the namespace machinery from
5437 C++/Fortran support: skip namespace imports that use them. */
5438 if (renaming->searched
5439 || (renaming->import_src != NULL
5440 && renaming->import_src[0] != '\0')
5441 || (renaming->import_dest != NULL
5442 && renaming->import_dest[0] != '\0'))
5443 continue;
5444 renaming->searched = 1;
5446 /* TODO: here, we perform another name-based symbol lookup, which can
5447 pull its own multiple overloads. In theory, we should be able to do
5448 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5449 not a simple name. But in order to do this, we would need to enhance
5450 the DWARF reader to associate a symbol to this renaming, instead of a
5451 name. So, for now, we do something simpler: re-use the C++/Fortran
5452 namespace machinery. */
5453 r_name = (renaming->alias != NULL
5454 ? renaming->alias
5455 : renaming->declaration);
5456 if (name_match (r_name, lookup_name, NULL))
5458 lookup_name_info decl_lookup_name (renaming->declaration,
5459 lookup_name.match_type ());
5460 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5461 1, NULL);
5463 renaming->searched = 0;
5465 return result.size () != defns_mark;
5468 /* Implements compare_names, but only applying the comparision using
5469 the given CASING. */
5471 static int
5472 compare_names_with_case (const char *string1, const char *string2,
5473 enum case_sensitivity casing)
5475 while (*string1 != '\0' && *string2 != '\0')
5477 char c1, c2;
5479 if (isspace (*string1) || isspace (*string2))
5480 return strcmp_iw_ordered (string1, string2);
5482 if (casing == case_sensitive_off)
5484 c1 = tolower (*string1);
5485 c2 = tolower (*string2);
5487 else
5489 c1 = *string1;
5490 c2 = *string2;
5492 if (c1 != c2)
5493 break;
5495 string1 += 1;
5496 string2 += 1;
5499 switch (*string1)
5501 case '(':
5502 return strcmp_iw_ordered (string1, string2);
5503 case '_':
5504 if (*string2 == '\0')
5506 if (is_name_suffix (string1))
5507 return 0;
5508 else
5509 return 1;
5511 /* FALLTHROUGH */
5512 default:
5513 if (*string2 == '(')
5514 return strcmp_iw_ordered (string1, string2);
5515 else
5517 if (casing == case_sensitive_off)
5518 return tolower (*string1) - tolower (*string2);
5519 else
5520 return *string1 - *string2;
5525 /* Compare STRING1 to STRING2, with results as for strcmp.
5526 Compatible with strcmp_iw_ordered in that...
5528 strcmp_iw_ordered (STRING1, STRING2) <= 0
5530 ... implies...
5532 compare_names (STRING1, STRING2) <= 0
5534 (they may differ as to what symbols compare equal). */
5536 static int
5537 compare_names (const char *string1, const char *string2)
5539 int result;
5541 /* Similar to what strcmp_iw_ordered does, we need to perform
5542 a case-insensitive comparison first, and only resort to
5543 a second, case-sensitive, comparison if the first one was
5544 not sufficient to differentiate the two strings. */
5546 result = compare_names_with_case (string1, string2, case_sensitive_off);
5547 if (result == 0)
5548 result = compare_names_with_case (string1, string2, case_sensitive_on);
5550 return result;
5553 /* Convenience function to get at the Ada encoded lookup name for
5554 LOOKUP_NAME, as a C string. */
5556 static const char *
5557 ada_lookup_name (const lookup_name_info &lookup_name)
5559 return lookup_name.ada ().lookup_name ().c_str ();
5562 /* A helper for add_nonlocal_symbols. Call expand_matching_symbols
5563 for OBJFILE, then walk the objfile's symtabs and update the
5564 results. */
5566 static void
5567 map_matching_symbols (struct objfile *objfile,
5568 const lookup_name_info &lookup_name,
5569 bool is_wild_match,
5570 domain_enum domain,
5571 int global,
5572 match_data &data)
5574 data.objfile = objfile;
5575 objfile->expand_matching_symbols (lookup_name, domain, global,
5576 is_wild_match ? nullptr : compare_names);
5578 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5579 for (compunit_symtab *symtab : objfile->compunits ())
5581 const struct block *block
5582 = symtab->blockvector ()->block (block_kind);
5583 if (!iterate_over_symbols_terminated (block, lookup_name,
5584 domain, data))
5585 break;
5589 /* Add to RESULT all non-local symbols whose name and domain match
5590 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5591 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5592 symbols otherwise. */
5594 static void
5595 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5596 const lookup_name_info &lookup_name,
5597 domain_enum domain, int global)
5599 struct match_data data (&result);
5601 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5603 for (objfile *objfile : current_program_space->objfiles ())
5605 map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5606 global, data);
5608 for (compunit_symtab *cu : objfile->compunits ())
5610 const struct block *global_block
5611 = cu->blockvector ()->global_block ();
5613 if (ada_add_block_renamings (result, global_block, lookup_name,
5614 domain))
5615 data.found_sym = true;
5619 if (result.empty () && global && !is_wild_match)
5621 const char *name = ada_lookup_name (lookup_name);
5622 std::string bracket_name = std::string ("<_ada_") + name + '>';
5623 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5625 for (objfile *objfile : current_program_space->objfiles ())
5626 map_matching_symbols (objfile, name1, false, domain, global, data);
5630 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5631 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5632 returning the number of matches. Add these to RESULT.
5634 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5635 symbol match within the nest of blocks whose innermost member is BLOCK,
5636 is the one match returned (no other matches in that or
5637 enclosing blocks is returned). If there are any matches in or
5638 surrounding BLOCK, then these alone are returned.
5640 Names prefixed with "standard__" are handled specially:
5641 "standard__" is first stripped off (by the lookup_name
5642 constructor), and only static and global symbols are searched.
5644 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5645 to lookup global symbols. */
5647 static void
5648 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5649 const struct block *block,
5650 const lookup_name_info &lookup_name,
5651 domain_enum domain,
5652 int full_search,
5653 int *made_global_lookup_p)
5655 struct symbol *sym;
5657 if (made_global_lookup_p)
5658 *made_global_lookup_p = 0;
5660 /* Special case: If the user specifies a symbol name inside package
5661 Standard, do a non-wild matching of the symbol name without
5662 the "standard__" prefix. This was primarily introduced in order
5663 to allow the user to specifically access the standard exceptions
5664 using, for instance, Standard.Constraint_Error when Constraint_Error
5665 is ambiguous (due to the user defining its own Constraint_Error
5666 entity inside its program). */
5667 if (lookup_name.ada ().standard_p ())
5668 block = NULL;
5670 /* Check the non-global symbols. If we have ANY match, then we're done. */
5672 if (block != NULL)
5674 if (full_search)
5675 ada_add_local_symbols (result, lookup_name, block, domain);
5676 else
5678 /* In the !full_search case we're are being called by
5679 iterate_over_symbols, and we don't want to search
5680 superblocks. */
5681 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5683 if (!result.empty () || !full_search)
5684 return;
5687 /* No non-global symbols found. Check our cache to see if we have
5688 already performed this search before. If we have, then return
5689 the same result. */
5691 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5692 domain, &sym, &block))
5694 if (sym != NULL)
5695 add_defn_to_vec (result, sym, block);
5696 return;
5699 if (made_global_lookup_p)
5700 *made_global_lookup_p = 1;
5702 /* Search symbols from all global blocks. */
5704 add_nonlocal_symbols (result, lookup_name, domain, 1);
5706 /* Now add symbols from all per-file blocks if we've gotten no hits
5707 (not strictly correct, but perhaps better than an error). */
5709 if (result.empty ())
5710 add_nonlocal_symbols (result, lookup_name, domain, 0);
5713 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5714 is non-zero, enclosing scope and in global scopes.
5716 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5717 blocks and symbol tables (if any) in which they were found.
5719 When full_search is non-zero, any non-function/non-enumeral
5720 symbol match within the nest of blocks whose innermost member is BLOCK,
5721 is the one match returned (no other matches in that or
5722 enclosing blocks is returned). If there are any matches in or
5723 surrounding BLOCK, then these alone are returned.
5725 Names prefixed with "standard__" are handled specially: "standard__"
5726 is first stripped off, and only static and global symbols are searched. */
5728 static std::vector<struct block_symbol>
5729 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5730 const struct block *block,
5731 domain_enum domain,
5732 int full_search)
5734 int syms_from_global_search;
5735 std::vector<struct block_symbol> results;
5737 ada_add_all_symbols (results, block, lookup_name,
5738 domain, full_search, &syms_from_global_search);
5740 remove_extra_symbols (results);
5742 if (results.empty () && full_search && syms_from_global_search)
5743 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5745 if (results.size () == 1 && full_search && syms_from_global_search)
5746 cache_symbol (ada_lookup_name (lookup_name), domain,
5747 results[0].symbol, results[0].block);
5749 remove_irrelevant_renamings (&results, block);
5750 return results;
5753 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5754 in global scopes, returning (SYM,BLOCK) tuples.
5756 See ada_lookup_symbol_list_worker for further details. */
5758 std::vector<struct block_symbol>
5759 ada_lookup_symbol_list (const char *name, const struct block *block,
5760 domain_enum domain)
5762 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5763 lookup_name_info lookup_name (name, name_match_type);
5765 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5768 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5769 to 1, but choosing the first symbol found if there are multiple
5770 choices.
5772 The result is stored in *INFO, which must be non-NULL.
5773 If no match is found, INFO->SYM is set to NULL. */
5775 void
5776 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5777 domain_enum domain,
5778 struct block_symbol *info)
5780 /* Since we already have an encoded name, wrap it in '<>' to force a
5781 verbatim match. Otherwise, if the name happens to not look like
5782 an encoded name (because it doesn't include a "__"),
5783 ada_lookup_name_info would re-encode/fold it again, and that
5784 would e.g., incorrectly lowercase object renaming names like
5785 "R28b" -> "r28b". */
5786 std::string verbatim = add_angle_brackets (name);
5788 gdb_assert (info != NULL);
5789 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5792 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5793 scope and in global scopes, or NULL if none. NAME is folded and
5794 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5795 choosing the first symbol if there are multiple choices. */
5797 struct block_symbol
5798 ada_lookup_symbol (const char *name, const struct block *block0,
5799 domain_enum domain)
5801 std::vector<struct block_symbol> candidates
5802 = ada_lookup_symbol_list (name, block0, domain);
5804 if (candidates.empty ())
5805 return {};
5807 return candidates[0];
5811 /* True iff STR is a possible encoded suffix of a normal Ada name
5812 that is to be ignored for matching purposes. Suffixes of parallel
5813 names (e.g., XVE) are not included here. Currently, the possible suffixes
5814 are given by any of the regular expressions:
5816 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5817 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5818 TKB [subprogram suffix for task bodies]
5819 _E[0-9]+[bs]$ [protected object entry suffixes]
5820 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5822 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5823 match is performed. This sequence is used to differentiate homonyms,
5824 is an optional part of a valid name suffix. */
5826 static int
5827 is_name_suffix (const char *str)
5829 int k;
5830 const char *matching;
5831 const int len = strlen (str);
5833 /* Skip optional leading __[0-9]+. */
5835 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5837 str += 3;
5838 while (isdigit (str[0]))
5839 str += 1;
5842 /* [.$][0-9]+ */
5844 if (str[0] == '.' || str[0] == '$')
5846 matching = str + 1;
5847 while (isdigit (matching[0]))
5848 matching += 1;
5849 if (matching[0] == '\0')
5850 return 1;
5853 /* ___[0-9]+ */
5855 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5857 matching = str + 3;
5858 while (isdigit (matching[0]))
5859 matching += 1;
5860 if (matching[0] == '\0')
5861 return 1;
5864 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5866 if (strcmp (str, "TKB") == 0)
5867 return 1;
5869 #if 0
5870 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5871 with a N at the end. Unfortunately, the compiler uses the same
5872 convention for other internal types it creates. So treating
5873 all entity names that end with an "N" as a name suffix causes
5874 some regressions. For instance, consider the case of an enumerated
5875 type. To support the 'Image attribute, it creates an array whose
5876 name ends with N.
5877 Having a single character like this as a suffix carrying some
5878 information is a bit risky. Perhaps we should change the encoding
5879 to be something like "_N" instead. In the meantime, do not do
5880 the following check. */
5881 /* Protected Object Subprograms */
5882 if (len == 1 && str [0] == 'N')
5883 return 1;
5884 #endif
5886 /* _E[0-9]+[bs]$ */
5887 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5889 matching = str + 3;
5890 while (isdigit (matching[0]))
5891 matching += 1;
5892 if ((matching[0] == 'b' || matching[0] == 's')
5893 && matching [1] == '\0')
5894 return 1;
5897 /* ??? We should not modify STR directly, as we are doing below. This
5898 is fine in this case, but may become problematic later if we find
5899 that this alternative did not work, and want to try matching
5900 another one from the begining of STR. Since we modified it, we
5901 won't be able to find the begining of the string anymore! */
5902 if (str[0] == 'X')
5904 str += 1;
5905 while (str[0] != '_' && str[0] != '\0')
5907 if (str[0] != 'n' && str[0] != 'b')
5908 return 0;
5909 str += 1;
5913 if (str[0] == '\000')
5914 return 1;
5916 if (str[0] == '_')
5918 if (str[1] != '_' || str[2] == '\000')
5919 return 0;
5920 if (str[2] == '_')
5922 if (strcmp (str + 3, "JM") == 0)
5923 return 1;
5924 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5925 the LJM suffix in favor of the JM one. But we will
5926 still accept LJM as a valid suffix for a reasonable
5927 amount of time, just to allow ourselves to debug programs
5928 compiled using an older version of GNAT. */
5929 if (strcmp (str + 3, "LJM") == 0)
5930 return 1;
5931 if (str[3] != 'X')
5932 return 0;
5933 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5934 || str[4] == 'U' || str[4] == 'P')
5935 return 1;
5936 if (str[4] == 'R' && str[5] != 'T')
5937 return 1;
5938 return 0;
5940 if (!isdigit (str[2]))
5941 return 0;
5942 for (k = 3; str[k] != '\0'; k += 1)
5943 if (!isdigit (str[k]) && str[k] != '_')
5944 return 0;
5945 return 1;
5947 if (str[0] == '$' && isdigit (str[1]))
5949 for (k = 2; str[k] != '\0'; k += 1)
5950 if (!isdigit (str[k]) && str[k] != '_')
5951 return 0;
5952 return 1;
5954 return 0;
5957 /* Return non-zero if the string starting at NAME and ending before
5958 NAME_END contains no capital letters. */
5960 static int
5961 is_valid_name_for_wild_match (const char *name0)
5963 std::string decoded_name = ada_decode (name0);
5964 int i;
5966 /* If the decoded name starts with an angle bracket, it means that
5967 NAME0 does not follow the GNAT encoding format. It should then
5968 not be allowed as a possible wild match. */
5969 if (decoded_name[0] == '<')
5970 return 0;
5972 for (i=0; decoded_name[i] != '\0'; i++)
5973 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5974 return 0;
5976 return 1;
5979 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5980 character which could start a simple name. Assumes that *NAMEP points
5981 somewhere inside the string beginning at NAME0. */
5983 static int
5984 advance_wild_match (const char **namep, const char *name0, char target0)
5986 const char *name = *namep;
5988 while (1)
5990 char t0, t1;
5992 t0 = *name;
5993 if (t0 == '_')
5995 t1 = name[1];
5996 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5998 name += 1;
5999 if (name == name0 + 5 && startswith (name0, "_ada"))
6000 break;
6001 else
6002 name += 1;
6004 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6005 || name[2] == target0))
6007 name += 2;
6008 break;
6010 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
6012 /* Names like "pkg__B_N__name", where N is a number, are
6013 block-local. We can handle these by simply skipping
6014 the "B_" here. */
6015 name += 4;
6017 else
6018 return 0;
6020 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6021 name += 1;
6022 else
6023 return 0;
6026 *namep = name;
6027 return 1;
6030 /* Return true iff NAME encodes a name of the form prefix.PATN.
6031 Ignores any informational suffixes of NAME (i.e., for which
6032 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6033 simple name. */
6035 static bool
6036 wild_match (const char *name, const char *patn)
6038 const char *p;
6039 const char *name0 = name;
6041 if (startswith (name, "___ghost_"))
6042 name += 9;
6044 while (1)
6046 const char *match = name;
6048 if (*name == *patn)
6050 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6051 if (*p != *name)
6052 break;
6053 if (*p == '\0' && is_name_suffix (name))
6054 return match == name0 || is_valid_name_for_wild_match (name0);
6056 if (name[-1] == '_')
6057 name -= 1;
6059 if (!advance_wild_match (&name, name0, *patn))
6060 return false;
6064 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6065 necessary). OBJFILE is the section containing BLOCK. */
6067 static void
6068 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6069 const struct block *block,
6070 const lookup_name_info &lookup_name,
6071 domain_enum domain, struct objfile *objfile)
6073 /* A matching argument symbol, if any. */
6074 struct symbol *arg_sym;
6075 /* Set true when we find a matching non-argument symbol. */
6076 bool found_sym;
6078 arg_sym = NULL;
6079 found_sym = false;
6080 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
6082 if (sym->matches (domain))
6084 if (sym->aclass () != LOC_UNRESOLVED)
6086 if (sym->is_argument ())
6087 arg_sym = sym;
6088 else
6090 found_sym = true;
6091 add_defn_to_vec (result, sym, block);
6097 /* Handle renamings. */
6099 if (ada_add_block_renamings (result, block, lookup_name, domain))
6100 found_sym = true;
6102 if (!found_sym && arg_sym != NULL)
6104 add_defn_to_vec (result, arg_sym, block);
6107 if (!lookup_name.ada ().wild_match_p ())
6109 arg_sym = NULL;
6110 found_sym = false;
6111 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6112 const char *name = ada_lookup_name.c_str ();
6113 size_t name_len = ada_lookup_name.size ();
6115 for (struct symbol *sym : block_iterator_range (block))
6117 if (sym->matches (domain))
6119 int cmp;
6121 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6122 if (cmp == 0)
6124 cmp = !startswith (sym->linkage_name (), "_ada_");
6125 if (cmp == 0)
6126 cmp = strncmp (name, sym->linkage_name () + 5,
6127 name_len);
6130 if (cmp == 0
6131 && is_name_suffix (sym->linkage_name () + name_len + 5))
6133 if (sym->aclass () != LOC_UNRESOLVED)
6135 if (sym->is_argument ())
6136 arg_sym = sym;
6137 else
6139 found_sym = true;
6140 add_defn_to_vec (result, sym, block);
6147 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6148 They aren't parameters, right? */
6149 if (!found_sym && arg_sym != NULL)
6151 add_defn_to_vec (result, arg_sym, block);
6157 /* Symbol Completion */
6159 /* See symtab.h. */
6161 bool
6162 ada_lookup_name_info::matches
6163 (const char *sym_name,
6164 symbol_name_match_type match_type,
6165 completion_match_result *comp_match_res) const
6167 bool match = false;
6168 const char *text = m_encoded_name.c_str ();
6169 size_t text_len = m_encoded_name.size ();
6171 /* First, test against the fully qualified name of the symbol. */
6173 if (strncmp (sym_name, text, text_len) == 0)
6174 match = true;
6176 std::string decoded_name = ada_decode (sym_name);
6177 if (match && !m_encoded_p)
6179 /* One needed check before declaring a positive match is to verify
6180 that iff we are doing a verbatim match, the decoded version
6181 of the symbol name starts with '<'. Otherwise, this symbol name
6182 is not a suitable completion. */
6184 bool has_angle_bracket = (decoded_name[0] == '<');
6185 match = (has_angle_bracket == m_verbatim_p);
6188 if (match && !m_verbatim_p)
6190 /* When doing non-verbatim match, another check that needs to
6191 be done is to verify that the potentially matching symbol name
6192 does not include capital letters, because the ada-mode would
6193 not be able to understand these symbol names without the
6194 angle bracket notation. */
6195 const char *tmp;
6197 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6198 if (*tmp != '\0')
6199 match = false;
6202 /* Second: Try wild matching... */
6204 if (!match && m_wild_match_p)
6206 /* Since we are doing wild matching, this means that TEXT
6207 may represent an unqualified symbol name. We therefore must
6208 also compare TEXT against the unqualified name of the symbol. */
6209 sym_name = ada_unqualified_name (decoded_name.c_str ());
6211 if (strncmp (sym_name, text, text_len) == 0)
6212 match = true;
6215 /* Finally: If we found a match, prepare the result to return. */
6217 if (!match)
6218 return false;
6220 if (comp_match_res != NULL)
6222 std::string &match_str = comp_match_res->match.storage ();
6224 if (!m_encoded_p)
6225 match_str = ada_decode (sym_name);
6226 else
6228 if (m_verbatim_p)
6229 match_str = add_angle_brackets (sym_name);
6230 else
6231 match_str = sym_name;
6235 comp_match_res->set_match (match_str.c_str ());
6238 return true;
6241 /* Field Access */
6243 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6244 for tagged types. */
6246 static int
6247 ada_is_dispatch_table_ptr_type (struct type *type)
6249 const char *name;
6251 if (type->code () != TYPE_CODE_PTR)
6252 return 0;
6254 name = type->target_type ()->name ();
6255 if (name == NULL)
6256 return 0;
6258 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6261 /* Return non-zero if TYPE is an interface tag. */
6263 static int
6264 ada_is_interface_tag (struct type *type)
6266 const char *name = type->name ();
6268 if (name == NULL)
6269 return 0;
6271 return (strcmp (name, "ada__tags__interface_tag") == 0);
6274 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6275 to be invisible to users. */
6278 ada_is_ignored_field (struct type *type, int field_num)
6280 if (field_num < 0 || field_num > type->num_fields ())
6281 return 1;
6283 /* Check the name of that field. */
6285 const char *name = type->field (field_num).name ();
6287 /* Anonymous field names should not be printed.
6288 brobecker/2007-02-20: I don't think this can actually happen
6289 but we don't want to print the value of anonymous fields anyway. */
6290 if (name == NULL)
6291 return 1;
6293 /* Normally, fields whose name start with an underscore ("_")
6294 are fields that have been internally generated by the compiler,
6295 and thus should not be printed. The "_parent" field is special,
6296 however: This is a field internally generated by the compiler
6297 for tagged types, and it contains the components inherited from
6298 the parent type. This field should not be printed as is, but
6299 should not be ignored either. */
6300 if (name[0] == '_' && !startswith (name, "_parent"))
6301 return 1;
6303 /* The compiler doesn't document this, but sometimes it emits
6304 a field whose name starts with a capital letter, like 'V148s'.
6305 These aren't marked as artificial in any way, but we know they
6306 should be ignored. However, wrapper fields should not be
6307 ignored. */
6308 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6310 /* Wrapper field. */
6312 else if (isupper (name[0]))
6313 return 1;
6316 /* If this is the dispatch table of a tagged type or an interface tag,
6317 then ignore. */
6318 if (ada_is_tagged_type (type, 1)
6319 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6320 || ada_is_interface_tag (type->field (field_num).type ())))
6321 return 1;
6323 /* Not a special field, so it should not be ignored. */
6324 return 0;
6327 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6328 pointer or reference type whose ultimate target has a tag field. */
6331 ada_is_tagged_type (struct type *type, int refok)
6333 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6336 /* True iff TYPE represents the type of X'Tag */
6339 ada_is_tag_type (struct type *type)
6341 type = ada_check_typedef (type);
6343 if (type == NULL || type->code () != TYPE_CODE_PTR)
6344 return 0;
6345 else
6347 const char *name = ada_type_name (type->target_type ());
6349 return (name != NULL
6350 && strcmp (name, "ada__tags__dispatch_table") == 0);
6354 /* The type of the tag on VAL. */
6356 static struct type *
6357 ada_tag_type (struct value *val)
6359 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6362 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6363 retired at Ada 05). */
6365 static int
6366 is_ada95_tag (struct value *tag)
6368 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6371 /* The value of the tag on VAL. */
6373 static struct value *
6374 ada_value_tag (struct value *val)
6376 return ada_value_struct_elt (val, "_tag", 0);
6379 /* The value of the tag on the object of type TYPE whose contents are
6380 saved at VALADDR, if it is non-null, or is at memory address
6381 ADDRESS. */
6383 static struct value *
6384 value_tag_from_contents_and_address (struct type *type,
6385 const gdb_byte *valaddr,
6386 CORE_ADDR address)
6388 int tag_byte_offset;
6389 struct type *tag_type;
6391 gdb::array_view<const gdb_byte> contents;
6392 if (valaddr != nullptr)
6393 contents = gdb::make_array_view (valaddr, type->length ());
6394 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6395 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6396 NULL, NULL, NULL))
6398 const gdb_byte *valaddr1 = ((valaddr == NULL)
6399 ? NULL
6400 : valaddr + tag_byte_offset);
6401 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6403 return value_from_contents_and_address (tag_type, valaddr1, address1);
6405 return NULL;
6408 static struct type *
6409 type_from_tag (struct value *tag)
6411 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6413 if (type_name != NULL)
6414 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6415 return NULL;
6418 /* Given a value OBJ of a tagged type, return a value of this
6419 type at the base address of the object. The base address, as
6420 defined in Ada.Tags, it is the address of the primary tag of
6421 the object, and therefore where the field values of its full
6422 view can be fetched. */
6424 struct value *
6425 ada_tag_value_at_base_address (struct value *obj)
6427 struct value *val;
6428 LONGEST offset_to_top = 0;
6429 struct type *ptr_type, *obj_type;
6430 struct value *tag;
6431 CORE_ADDR base_address;
6433 obj_type = obj->type ();
6435 /* It is the responsibility of the caller to deref pointers. */
6437 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6438 return obj;
6440 tag = ada_value_tag (obj);
6441 if (!tag)
6442 return obj;
6444 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6446 if (is_ada95_tag (tag))
6447 return obj;
6449 struct type *offset_type
6450 = language_lookup_primitive_type (language_def (language_ada),
6451 target_gdbarch(), "storage_offset");
6452 ptr_type = lookup_pointer_type (offset_type);
6453 val = value_cast (ptr_type, tag);
6454 if (!val)
6455 return obj;
6457 /* It is perfectly possible that an exception be raised while
6458 trying to determine the base address, just like for the tag;
6459 see ada_tag_name for more details. We do not print the error
6460 message for the same reason. */
6464 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6467 catch (const gdb_exception_error &e)
6469 return obj;
6472 /* If offset is null, nothing to do. */
6474 if (offset_to_top == 0)
6475 return obj;
6477 /* -1 is a special case in Ada.Tags; however, what should be done
6478 is not quite clear from the documentation. So do nothing for
6479 now. */
6481 if (offset_to_top == -1)
6482 return obj;
6484 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6485 top is used. In this situation the offset is stored just after
6486 the tag, in the object itself. */
6487 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6488 if (offset_to_top == last)
6490 struct value *tem = value_addr (tag);
6491 tem = value_ptradd (tem, 1);
6492 tem = value_cast (ptr_type, tem);
6493 offset_to_top = value_as_long (value_ind (tem));
6496 if (offset_to_top > 0)
6498 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6499 from the base address. This was however incompatible with
6500 C++ dispatch table: C++ uses a *negative* value to *add*
6501 to the base address. Ada's convention has therefore been
6502 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6503 use the same convention. Here, we support both cases by
6504 checking the sign of OFFSET_TO_TOP. */
6505 offset_to_top = -offset_to_top;
6508 base_address = obj->address () + offset_to_top;
6509 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6511 /* Make sure that we have a proper tag at the new address.
6512 Otherwise, offset_to_top is bogus (which can happen when
6513 the object is not initialized yet). */
6515 if (!tag)
6516 return obj;
6518 obj_type = type_from_tag (tag);
6520 if (!obj_type)
6521 return obj;
6523 return value_from_contents_and_address (obj_type, NULL, base_address);
6526 /* Return the "ada__tags__type_specific_data" type. */
6528 static struct type *
6529 ada_get_tsd_type (struct inferior *inf)
6531 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6533 if (data->tsd_type == 0)
6534 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6535 return data->tsd_type;
6538 /* Return the TSD (type-specific data) associated to the given TAG.
6539 TAG is assumed to be the tag of a tagged-type entity.
6541 May return NULL if we are unable to get the TSD. */
6543 static struct value *
6544 ada_get_tsd_from_tag (struct value *tag)
6546 struct value *val;
6547 struct type *type;
6549 /* First option: The TSD is simply stored as a field of our TAG.
6550 Only older versions of GNAT would use this format, but we have
6551 to test it first, because there are no visible markers for
6552 the current approach except the absence of that field. */
6554 val = ada_value_struct_elt (tag, "tsd", 1);
6555 if (val)
6556 return val;
6558 /* Try the second representation for the dispatch table (in which
6559 there is no explicit 'tsd' field in the referent of the tag pointer,
6560 and instead the tsd pointer is stored just before the dispatch
6561 table. */
6563 type = ada_get_tsd_type (current_inferior());
6564 if (type == NULL)
6565 return NULL;
6566 type = lookup_pointer_type (lookup_pointer_type (type));
6567 val = value_cast (type, tag);
6568 if (val == NULL)
6569 return NULL;
6570 return value_ind (value_ptradd (val, -1));
6573 /* Given the TSD of a tag (type-specific data), return a string
6574 containing the name of the associated type.
6576 May return NULL if we are unable to determine the tag name. */
6578 static gdb::unique_xmalloc_ptr<char>
6579 ada_tag_name_from_tsd (struct value *tsd)
6581 struct value *val;
6583 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6584 if (val == NULL)
6585 return NULL;
6586 gdb::unique_xmalloc_ptr<char> buffer
6587 = target_read_string (value_as_address (val), INT_MAX);
6588 if (buffer == nullptr)
6589 return nullptr;
6593 /* Let this throw an exception on error. If the data is
6594 uninitialized, we'd rather not have the user see a
6595 warning. */
6596 const char *folded = ada_fold_name (buffer.get (), true);
6597 return make_unique_xstrdup (folded);
6599 catch (const gdb_exception &)
6601 return nullptr;
6605 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6606 a C string.
6608 Return NULL if the TAG is not an Ada tag, or if we were unable to
6609 determine the name of that tag. */
6611 gdb::unique_xmalloc_ptr<char>
6612 ada_tag_name (struct value *tag)
6614 gdb::unique_xmalloc_ptr<char> name;
6616 if (!ada_is_tag_type (tag->type ()))
6617 return NULL;
6619 /* It is perfectly possible that an exception be raised while trying
6620 to determine the TAG's name, even under normal circumstances:
6621 The associated variable may be uninitialized or corrupted, for
6622 instance. We do not let any exception propagate past this point.
6623 instead we return NULL.
6625 We also do not print the error message either (which often is very
6626 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6627 the caller print a more meaningful message if necessary. */
6630 struct value *tsd = ada_get_tsd_from_tag (tag);
6632 if (tsd != NULL)
6633 name = ada_tag_name_from_tsd (tsd);
6635 catch (const gdb_exception_error &e)
6639 return name;
6642 /* The parent type of TYPE, or NULL if none. */
6644 struct type *
6645 ada_parent_type (struct type *type)
6647 int i;
6649 type = ada_check_typedef (type);
6651 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6652 return NULL;
6654 for (i = 0; i < type->num_fields (); i += 1)
6655 if (ada_is_parent_field (type, i))
6657 struct type *parent_type = type->field (i).type ();
6659 /* If the _parent field is a pointer, then dereference it. */
6660 if (parent_type->code () == TYPE_CODE_PTR)
6661 parent_type = parent_type->target_type ();
6662 /* If there is a parallel XVS type, get the actual base type. */
6663 parent_type = ada_get_base_type (parent_type);
6665 return ada_check_typedef (parent_type);
6668 return NULL;
6671 /* True iff field number FIELD_NUM of structure type TYPE contains the
6672 parent-type (inherited) fields of a derived type. Assumes TYPE is
6673 a structure type with at least FIELD_NUM+1 fields. */
6676 ada_is_parent_field (struct type *type, int field_num)
6678 const char *name = ada_check_typedef (type)->field (field_num).name ();
6680 return (name != NULL
6681 && (startswith (name, "PARENT")
6682 || startswith (name, "_parent")));
6685 /* True iff field number FIELD_NUM of structure type TYPE is a
6686 transparent wrapper field (which should be silently traversed when doing
6687 field selection and flattened when printing). Assumes TYPE is a
6688 structure type with at least FIELD_NUM+1 fields. Such fields are always
6689 structures. */
6692 ada_is_wrapper_field (struct type *type, int field_num)
6694 const char *name = type->field (field_num).name ();
6696 if (name != NULL && strcmp (name, "RETVAL") == 0)
6698 /* This happens in functions with "out" or "in out" parameters
6699 which are passed by copy. For such functions, GNAT describes
6700 the function's return type as being a struct where the return
6701 value is in a field called RETVAL, and where the other "out"
6702 or "in out" parameters are fields of that struct. This is not
6703 a wrapper. */
6704 return 0;
6707 return (name != NULL
6708 && (startswith (name, "PARENT")
6709 || strcmp (name, "REP") == 0
6710 || startswith (name, "_parent")
6711 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6714 /* True iff field number FIELD_NUM of structure or union type TYPE
6715 is a variant wrapper. Assumes TYPE is a structure type with at least
6716 FIELD_NUM+1 fields. */
6719 ada_is_variant_part (struct type *type, int field_num)
6721 /* Only Ada types are eligible. */
6722 if (!ADA_TYPE_P (type))
6723 return 0;
6725 struct type *field_type = type->field (field_num).type ();
6727 return (field_type->code () == TYPE_CODE_UNION
6728 || (is_dynamic_field (type, field_num)
6729 && (field_type->target_type ()->code ()
6730 == TYPE_CODE_UNION)));
6733 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6734 whose discriminants are contained in the record type OUTER_TYPE,
6735 returns the type of the controlling discriminant for the variant.
6736 May return NULL if the type could not be found. */
6738 struct type *
6739 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6741 const char *name = ada_variant_discrim_name (var_type);
6743 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6746 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6747 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6748 represents a 'when others' clause; otherwise 0. */
6750 static int
6751 ada_is_others_clause (struct type *type, int field_num)
6753 const char *name = type->field (field_num).name ();
6755 return (name != NULL && name[0] == 'O');
6758 /* Assuming that TYPE0 is the type of the variant part of a record,
6759 returns the name of the discriminant controlling the variant.
6760 The value is valid until the next call to ada_variant_discrim_name. */
6762 const char *
6763 ada_variant_discrim_name (struct type *type0)
6765 static std::string result;
6766 struct type *type;
6767 const char *name;
6768 const char *discrim_end;
6769 const char *discrim_start;
6771 if (type0->code () == TYPE_CODE_PTR)
6772 type = type0->target_type ();
6773 else
6774 type = type0;
6776 name = ada_type_name (type);
6778 if (name == NULL || name[0] == '\000')
6779 return "";
6781 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6782 discrim_end -= 1)
6784 if (startswith (discrim_end, "___XVN"))
6785 break;
6787 if (discrim_end == name)
6788 return "";
6790 for (discrim_start = discrim_end; discrim_start != name + 3;
6791 discrim_start -= 1)
6793 if (discrim_start == name + 1)
6794 return "";
6795 if ((discrim_start > name + 3
6796 && startswith (discrim_start - 3, "___"))
6797 || discrim_start[-1] == '.')
6798 break;
6801 result = std::string (discrim_start, discrim_end - discrim_start);
6802 return result.c_str ();
6805 /* Scan STR for a subtype-encoded number, beginning at position K.
6806 Put the position of the character just past the number scanned in
6807 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6808 Return 1 if there was a valid number at the given position, and 0
6809 otherwise. A "subtype-encoded" number consists of the absolute value
6810 in decimal, followed by the letter 'm' to indicate a negative number.
6811 Assumes 0m does not occur. */
6814 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6816 ULONGEST RU;
6818 if (!isdigit (str[k]))
6819 return 0;
6821 /* Do it the hard way so as not to make any assumption about
6822 the relationship of unsigned long (%lu scan format code) and
6823 LONGEST. */
6824 RU = 0;
6825 while (isdigit (str[k]))
6827 RU = RU * 10 + (str[k] - '0');
6828 k += 1;
6831 if (str[k] == 'm')
6833 if (R != NULL)
6834 *R = (-(LONGEST) (RU - 1)) - 1;
6835 k += 1;
6837 else if (R != NULL)
6838 *R = (LONGEST) RU;
6840 /* NOTE on the above: Technically, C does not say what the results of
6841 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6842 number representable as a LONGEST (although either would probably work
6843 in most implementations). When RU>0, the locution in the then branch
6844 above is always equivalent to the negative of RU. */
6846 if (new_k != NULL)
6847 *new_k = k;
6848 return 1;
6851 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6852 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6853 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6855 static int
6856 ada_in_variant (LONGEST val, struct type *type, int field_num)
6858 const char *name = type->field (field_num).name ();
6859 int p;
6861 p = 0;
6862 while (1)
6864 switch (name[p])
6866 case '\0':
6867 return 0;
6868 case 'S':
6870 LONGEST W;
6872 if (!ada_scan_number (name, p + 1, &W, &p))
6873 return 0;
6874 if (val == W)
6875 return 1;
6876 break;
6878 case 'R':
6880 LONGEST L, U;
6882 if (!ada_scan_number (name, p + 1, &L, &p)
6883 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6884 return 0;
6885 if (val >= L && val <= U)
6886 return 1;
6887 break;
6889 case 'O':
6890 return 1;
6891 default:
6892 return 0;
6897 /* FIXME: Lots of redundancy below. Try to consolidate. */
6899 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6900 ARG_TYPE, extract and return the value of one of its (non-static)
6901 fields. FIELDNO says which field. Differs from value_primitive_field
6902 only in that it can handle packed values of arbitrary type. */
6904 struct value *
6905 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6906 struct type *arg_type)
6908 struct type *type;
6910 arg_type = ada_check_typedef (arg_type);
6911 type = arg_type->field (fieldno).type ();
6913 /* Handle packed fields. It might be that the field is not packed
6914 relative to its containing structure, but the structure itself is
6915 packed; in this case we must take the bit-field path. */
6916 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
6918 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6919 int bit_size = arg_type->field (fieldno).bitsize ();
6921 return ada_value_primitive_packed_val (arg1,
6922 arg1->contents ().data (),
6923 offset + bit_pos / 8,
6924 bit_pos % 8, bit_size, type);
6926 else
6927 return arg1->primitive_field (offset, fieldno, arg_type);
6930 /* Find field with name NAME in object of type TYPE. If found,
6931 set the following for each argument that is non-null:
6932 - *FIELD_TYPE_P to the field's type;
6933 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6934 an object of that type;
6935 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6936 - *BIT_SIZE_P to its size in bits if the field is packed, and
6937 0 otherwise;
6938 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6939 fields up to but not including the desired field, or by the total
6940 number of fields if not found. A NULL value of NAME never
6941 matches; the function just counts visible fields in this case.
6943 Notice that we need to handle when a tagged record hierarchy
6944 has some components with the same name, like in this scenario:
6946 type Top_T is tagged record
6947 N : Integer := 1;
6948 U : Integer := 974;
6949 A : Integer := 48;
6950 end record;
6952 type Middle_T is new Top.Top_T with record
6953 N : Character := 'a';
6954 C : Integer := 3;
6955 end record;
6957 type Bottom_T is new Middle.Middle_T with record
6958 N : Float := 4.0;
6959 C : Character := '5';
6960 X : Integer := 6;
6961 A : Character := 'J';
6962 end record;
6964 Let's say we now have a variable declared and initialized as follow:
6966 TC : Top_A := new Bottom_T;
6968 And then we use this variable to call this function
6970 procedure Assign (Obj: in out Top_T; TV : Integer);
6972 as follow:
6974 Assign (Top_T (B), 12);
6976 Now, we're in the debugger, and we're inside that procedure
6977 then and we want to print the value of obj.c:
6979 Usually, the tagged record or one of the parent type owns the
6980 component to print and there's no issue but in this particular
6981 case, what does it mean to ask for Obj.C? Since the actual
6982 type for object is type Bottom_T, it could mean two things: type
6983 component C from the Middle_T view, but also component C from
6984 Bottom_T. So in that "undefined" case, when the component is
6985 not found in the non-resolved type (which includes all the
6986 components of the parent type), then resolve it and see if we
6987 get better luck once expanded.
6989 In the case of homonyms in the derived tagged type, we don't
6990 guaranty anything, and pick the one that's easiest for us
6991 to program.
6993 Returns 1 if found, 0 otherwise. */
6995 static int
6996 find_struct_field (const char *name, struct type *type, int offset,
6997 struct type **field_type_p,
6998 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6999 int *index_p)
7001 int i;
7002 int parent_offset = -1;
7004 type = ada_check_typedef (type);
7006 if (field_type_p != NULL)
7007 *field_type_p = NULL;
7008 if (byte_offset_p != NULL)
7009 *byte_offset_p = 0;
7010 if (bit_offset_p != NULL)
7011 *bit_offset_p = 0;
7012 if (bit_size_p != NULL)
7013 *bit_size_p = 0;
7015 for (i = 0; i < type->num_fields (); i += 1)
7017 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7018 type. However, we only need the values to be correct when
7019 the caller asks for them. */
7020 int bit_pos = 0, fld_offset = 0;
7021 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7023 bit_pos = type->field (i).loc_bitpos ();
7024 fld_offset = offset + bit_pos / 8;
7027 const char *t_field_name = type->field (i).name ();
7029 if (t_field_name == NULL)
7030 continue;
7032 else if (ada_is_parent_field (type, i))
7034 /* This is a field pointing us to the parent type of a tagged
7035 type. As hinted in this function's documentation, we give
7036 preference to fields in the current record first, so what
7037 we do here is just record the index of this field before
7038 we skip it. If it turns out we couldn't find our field
7039 in the current record, then we'll get back to it and search
7040 inside it whether the field might exist in the parent. */
7042 parent_offset = i;
7043 continue;
7046 else if (name != NULL && field_name_match (t_field_name, name))
7048 int bit_size = type->field (i).bitsize ();
7050 if (field_type_p != NULL)
7051 *field_type_p = type->field (i).type ();
7052 if (byte_offset_p != NULL)
7053 *byte_offset_p = fld_offset;
7054 if (bit_offset_p != NULL)
7055 *bit_offset_p = bit_pos % 8;
7056 if (bit_size_p != NULL)
7057 *bit_size_p = bit_size;
7058 return 1;
7060 else if (ada_is_wrapper_field (type, i))
7062 if (find_struct_field (name, type->field (i).type (), fld_offset,
7063 field_type_p, byte_offset_p, bit_offset_p,
7064 bit_size_p, index_p))
7065 return 1;
7067 else if (ada_is_variant_part (type, i))
7069 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7070 fixed type?? */
7071 int j;
7072 struct type *field_type
7073 = ada_check_typedef (type->field (i).type ());
7075 for (j = 0; j < field_type->num_fields (); j += 1)
7077 if (find_struct_field (name, field_type->field (j).type (),
7078 fld_offset
7079 + field_type->field (j).loc_bitpos () / 8,
7080 field_type_p, byte_offset_p,
7081 bit_offset_p, bit_size_p, index_p))
7082 return 1;
7085 else if (index_p != NULL)
7086 *index_p += 1;
7089 /* Field not found so far. If this is a tagged type which
7090 has a parent, try finding that field in the parent now. */
7092 if (parent_offset != -1)
7094 /* As above, only compute the offset when truly needed. */
7095 int fld_offset = offset;
7096 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7098 int bit_pos = type->field (parent_offset).loc_bitpos ();
7099 fld_offset += bit_pos / 8;
7102 if (find_struct_field (name, type->field (parent_offset).type (),
7103 fld_offset, field_type_p, byte_offset_p,
7104 bit_offset_p, bit_size_p, index_p))
7105 return 1;
7108 return 0;
7111 /* Number of user-visible fields in record type TYPE. */
7113 static int
7114 num_visible_fields (struct type *type)
7116 int n;
7118 n = 0;
7119 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7120 return n;
7123 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7124 and search in it assuming it has (class) type TYPE.
7125 If found, return value, else return NULL.
7127 Searches recursively through wrapper fields (e.g., '_parent').
7129 In the case of homonyms in the tagged types, please refer to the
7130 long explanation in find_struct_field's function documentation. */
7132 static struct value *
7133 ada_search_struct_field (const char *name, struct value *arg, int offset,
7134 struct type *type)
7136 int i;
7137 int parent_offset = -1;
7139 type = ada_check_typedef (type);
7140 for (i = 0; i < type->num_fields (); i += 1)
7142 const char *t_field_name = type->field (i).name ();
7144 if (t_field_name == NULL)
7145 continue;
7147 else if (ada_is_parent_field (type, i))
7149 /* This is a field pointing us to the parent type of a tagged
7150 type. As hinted in this function's documentation, we give
7151 preference to fields in the current record first, so what
7152 we do here is just record the index of this field before
7153 we skip it. If it turns out we couldn't find our field
7154 in the current record, then we'll get back to it and search
7155 inside it whether the field might exist in the parent. */
7157 parent_offset = i;
7158 continue;
7161 else if (field_name_match (t_field_name, name))
7162 return ada_value_primitive_field (arg, offset, i, type);
7164 else if (ada_is_wrapper_field (type, i))
7166 struct value *v = /* Do not let indent join lines here. */
7167 ada_search_struct_field (name, arg,
7168 offset + type->field (i).loc_bitpos () / 8,
7169 type->field (i).type ());
7171 if (v != NULL)
7172 return v;
7175 else if (ada_is_variant_part (type, i))
7177 /* PNH: Do we ever get here? See find_struct_field. */
7178 int j;
7179 struct type *field_type = ada_check_typedef (type->field (i).type ());
7180 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7182 for (j = 0; j < field_type->num_fields (); j += 1)
7184 struct value *v = ada_search_struct_field /* Force line
7185 break. */
7186 (name, arg,
7187 var_offset + field_type->field (j).loc_bitpos () / 8,
7188 field_type->field (j).type ());
7190 if (v != NULL)
7191 return v;
7196 /* Field not found so far. If this is a tagged type which
7197 has a parent, try finding that field in the parent now. */
7199 if (parent_offset != -1)
7201 struct value *v = ada_search_struct_field (
7202 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7203 type->field (parent_offset).type ());
7205 if (v != NULL)
7206 return v;
7209 return NULL;
7212 static struct value *ada_index_struct_field_1 (int *, struct value *,
7213 int, struct type *);
7216 /* Return field #INDEX in ARG, where the index is that returned by
7217 * find_struct_field through its INDEX_P argument. Adjust the address
7218 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7219 * If found, return value, else return NULL. */
7221 static struct value *
7222 ada_index_struct_field (int index, struct value *arg, int offset,
7223 struct type *type)
7225 return ada_index_struct_field_1 (&index, arg, offset, type);
7229 /* Auxiliary function for ada_index_struct_field. Like
7230 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7231 * *INDEX_P. */
7233 static struct value *
7234 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7235 struct type *type)
7237 int i;
7238 type = ada_check_typedef (type);
7240 for (i = 0; i < type->num_fields (); i += 1)
7242 if (type->field (i).name () == NULL)
7243 continue;
7244 else if (ada_is_wrapper_field (type, i))
7246 struct value *v = /* Do not let indent join lines here. */
7247 ada_index_struct_field_1 (index_p, arg,
7248 offset + type->field (i).loc_bitpos () / 8,
7249 type->field (i).type ());
7251 if (v != NULL)
7252 return v;
7255 else if (ada_is_variant_part (type, i))
7257 /* PNH: Do we ever get here? See ada_search_struct_field,
7258 find_struct_field. */
7259 error (_("Cannot assign this kind of variant record"));
7261 else if (*index_p == 0)
7262 return ada_value_primitive_field (arg, offset, i, type);
7263 else
7264 *index_p -= 1;
7266 return NULL;
7269 /* Return a string representation of type TYPE. */
7271 static std::string
7272 type_as_string (struct type *type)
7274 string_file tmp_stream;
7276 type_print (type, "", &tmp_stream, -1);
7278 return tmp_stream.release ();
7281 /* Given a type TYPE, look up the type of the component of type named NAME.
7283 Matches any field whose name has NAME as a prefix, possibly
7284 followed by "___".
7286 TYPE can be either a struct or union. If REFOK, TYPE may also
7287 be a (pointer or reference)+ to a struct or union, and the
7288 ultimate target type will be searched.
7290 Looks recursively into variant clauses and parent types.
7292 In the case of homonyms in the tagged types, please refer to the
7293 long explanation in find_struct_field's function documentation.
7295 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7296 TYPE is not a type of the right kind. */
7298 static struct type *
7299 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7300 int noerr)
7302 if (name == NULL)
7303 goto BadName;
7305 if (refok && type != NULL)
7306 while (1)
7308 type = ada_check_typedef (type);
7309 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7310 break;
7311 type = type->target_type ();
7314 if (type == NULL
7315 || (type->code () != TYPE_CODE_STRUCT
7316 && type->code () != TYPE_CODE_UNION))
7318 if (noerr)
7319 return NULL;
7321 error (_("Type %s is not a structure or union type"),
7322 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7325 type = to_static_fixed_type (type);
7327 struct type *result;
7328 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7329 nullptr);
7330 if (result != nullptr)
7331 return result;
7333 BadName:
7334 if (!noerr)
7336 const char *name_str = name != NULL ? name : _("<null>");
7338 error (_("Type %s has no component named %s"),
7339 type_as_string (type).c_str (), name_str);
7342 return NULL;
7345 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7346 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7347 represents an unchecked union (that is, the variant part of a
7348 record that is named in an Unchecked_Union pragma). */
7350 static int
7351 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7353 const char *discrim_name = ada_variant_discrim_name (var_type);
7355 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7359 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7360 within OUTER, determine which variant clause (field number in VAR_TYPE,
7361 numbering from 0) is applicable. Returns -1 if none are. */
7364 ada_which_variant_applies (struct type *var_type, struct value *outer)
7366 int others_clause;
7367 int i;
7368 const char *discrim_name = ada_variant_discrim_name (var_type);
7369 struct value *discrim;
7370 LONGEST discrim_val;
7372 /* Using plain value_from_contents_and_address here causes problems
7373 because we will end up trying to resolve a type that is currently
7374 being constructed. */
7375 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7376 if (discrim == NULL)
7377 return -1;
7378 discrim_val = value_as_long (discrim);
7380 others_clause = -1;
7381 for (i = 0; i < var_type->num_fields (); i += 1)
7383 if (ada_is_others_clause (var_type, i))
7384 others_clause = i;
7385 else if (ada_in_variant (discrim_val, var_type, i))
7386 return i;
7389 return others_clause;
7394 /* Dynamic-Sized Records */
7396 /* Strategy: The type ostensibly attached to a value with dynamic size
7397 (i.e., a size that is not statically recorded in the debugging
7398 data) does not accurately reflect the size or layout of the value.
7399 Our strategy is to convert these values to values with accurate,
7400 conventional types that are constructed on the fly. */
7402 /* There is a subtle and tricky problem here. In general, we cannot
7403 determine the size of dynamic records without its data. However,
7404 the 'struct value' data structure, which GDB uses to represent
7405 quantities in the inferior process (the target), requires the size
7406 of the type at the time of its allocation in order to reserve space
7407 for GDB's internal copy of the data. That's why the
7408 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7409 rather than struct value*s.
7411 However, GDB's internal history variables ($1, $2, etc.) are
7412 struct value*s containing internal copies of the data that are not, in
7413 general, the same as the data at their corresponding addresses in
7414 the target. Fortunately, the types we give to these values are all
7415 conventional, fixed-size types (as per the strategy described
7416 above), so that we don't usually have to perform the
7417 'to_fixed_xxx_type' conversions to look at their values.
7418 Unfortunately, there is one exception: if one of the internal
7419 history variables is an array whose elements are unconstrained
7420 records, then we will need to create distinct fixed types for each
7421 element selected. */
7423 /* The upshot of all of this is that many routines take a (type, host
7424 address, target address) triple as arguments to represent a value.
7425 The host address, if non-null, is supposed to contain an internal
7426 copy of the relevant data; otherwise, the program is to consult the
7427 target at the target address. */
7429 /* Assuming that VAL0 represents a pointer value, the result of
7430 dereferencing it. Differs from value_ind in its treatment of
7431 dynamic-sized types. */
7433 struct value *
7434 ada_value_ind (struct value *val0)
7436 struct value *val = value_ind (val0);
7438 if (ada_is_tagged_type (val->type (), 0))
7439 val = ada_tag_value_at_base_address (val);
7441 return ada_to_fixed_value (val);
7444 /* The value resulting from dereferencing any "reference to"
7445 qualifiers on VAL0. */
7447 static struct value *
7448 ada_coerce_ref (struct value *val0)
7450 if (val0->type ()->code () == TYPE_CODE_REF)
7452 struct value *val = val0;
7454 val = coerce_ref (val);
7456 if (ada_is_tagged_type (val->type (), 0))
7457 val = ada_tag_value_at_base_address (val);
7459 return ada_to_fixed_value (val);
7461 else
7462 return val0;
7465 /* Return the bit alignment required for field #F of template type TYPE. */
7467 static unsigned int
7468 field_alignment (struct type *type, int f)
7470 const char *name = type->field (f).name ();
7471 int len;
7472 int align_offset;
7474 /* The field name should never be null, unless the debugging information
7475 is somehow malformed. In this case, we assume the field does not
7476 require any alignment. */
7477 if (name == NULL)
7478 return 1;
7480 len = strlen (name);
7482 if (!isdigit (name[len - 1]))
7483 return 1;
7485 if (isdigit (name[len - 2]))
7486 align_offset = len - 2;
7487 else
7488 align_offset = len - 1;
7490 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7491 return TARGET_CHAR_BIT;
7493 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7496 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7498 static struct symbol *
7499 ada_find_any_type_symbol (const char *name)
7501 struct symbol *sym;
7503 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7504 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
7505 return sym;
7507 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7508 return sym;
7511 /* Find a type named NAME. Ignores ambiguity. This routine will look
7512 solely for types defined by debug info, it will not search the GDB
7513 primitive types. */
7515 static struct type *
7516 ada_find_any_type (const char *name)
7518 struct symbol *sym = ada_find_any_type_symbol (name);
7520 if (sym != NULL)
7521 return sym->type ();
7523 return NULL;
7526 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7527 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7528 symbol, in which case it is returned. Otherwise, this looks for
7529 symbols whose name is that of NAME_SYM suffixed with "___XR".
7530 Return symbol if found, and NULL otherwise. */
7532 static bool
7533 ada_is_renaming_symbol (struct symbol *name_sym)
7535 const char *name = name_sym->linkage_name ();
7536 return strstr (name, "___XR") != NULL;
7539 /* Because of GNAT encoding conventions, several GDB symbols may match a
7540 given type name. If the type denoted by TYPE0 is to be preferred to
7541 that of TYPE1 for purposes of type printing, return non-zero;
7542 otherwise return 0. */
7545 ada_prefer_type (struct type *type0, struct type *type1)
7547 if (type1 == NULL)
7548 return 1;
7549 else if (type0 == NULL)
7550 return 0;
7551 else if (type1->code () == TYPE_CODE_VOID)
7552 return 1;
7553 else if (type0->code () == TYPE_CODE_VOID)
7554 return 0;
7555 else if (type1->name () == NULL && type0->name () != NULL)
7556 return 1;
7557 else if (ada_is_constrained_packed_array_type (type0))
7558 return 1;
7559 else if (ada_is_array_descriptor_type (type0)
7560 && !ada_is_array_descriptor_type (type1))
7561 return 1;
7562 else
7564 const char *type0_name = type0->name ();
7565 const char *type1_name = type1->name ();
7567 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7568 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7569 return 1;
7571 return 0;
7574 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7575 null. */
7577 const char *
7578 ada_type_name (struct type *type)
7580 if (type == NULL)
7581 return NULL;
7582 return type->name ();
7585 /* Search the list of "descriptive" types associated to TYPE for a type
7586 whose name is NAME. */
7588 static struct type *
7589 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7591 struct type *result, *tmp;
7593 if (ada_ignore_descriptive_types_p)
7594 return NULL;
7596 /* If there no descriptive-type info, then there is no parallel type
7597 to be found. */
7598 if (!HAVE_GNAT_AUX_INFO (type))
7599 return NULL;
7601 result = TYPE_DESCRIPTIVE_TYPE (type);
7602 while (result != NULL)
7604 const char *result_name = ada_type_name (result);
7606 if (result_name == NULL)
7608 warning (_("unexpected null name on descriptive type"));
7609 return NULL;
7612 /* If the names match, stop. */
7613 if (strcmp (result_name, name) == 0)
7614 break;
7616 /* Otherwise, look at the next item on the list, if any. */
7617 if (HAVE_GNAT_AUX_INFO (result))
7618 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7619 else
7620 tmp = NULL;
7622 /* If not found either, try after having resolved the typedef. */
7623 if (tmp != NULL)
7624 result = tmp;
7625 else
7627 result = check_typedef (result);
7628 if (HAVE_GNAT_AUX_INFO (result))
7629 result = TYPE_DESCRIPTIVE_TYPE (result);
7630 else
7631 result = NULL;
7635 /* If we didn't find a match, see whether this is a packed array. With
7636 older compilers, the descriptive type information is either absent or
7637 irrelevant when it comes to packed arrays so the above lookup fails.
7638 Fall back to using a parallel lookup by name in this case. */
7639 if (result == NULL && ada_is_constrained_packed_array_type (type))
7640 return ada_find_any_type (name);
7642 return result;
7645 /* Find a parallel type to TYPE with the specified NAME, using the
7646 descriptive type taken from the debugging information, if available,
7647 and otherwise using the (slower) name-based method. */
7649 static struct type *
7650 ada_find_parallel_type_with_name (struct type *type, const char *name)
7652 struct type *result = NULL;
7654 if (HAVE_GNAT_AUX_INFO (type))
7655 result = find_parallel_type_by_descriptive_type (type, name);
7656 else
7657 result = ada_find_any_type (name);
7659 return result;
7662 /* Same as above, but specify the name of the parallel type by appending
7663 SUFFIX to the name of TYPE. */
7665 struct type *
7666 ada_find_parallel_type (struct type *type, const char *suffix)
7668 char *name;
7669 const char *type_name = ada_type_name (type);
7670 int len;
7672 if (type_name == NULL)
7673 return NULL;
7675 len = strlen (type_name);
7677 name = (char *) alloca (len + strlen (suffix) + 1);
7679 strcpy (name, type_name);
7680 strcpy (name + len, suffix);
7682 return ada_find_parallel_type_with_name (type, name);
7685 /* If TYPE is a variable-size record type, return the corresponding template
7686 type describing its fields. Otherwise, return NULL. */
7688 static struct type *
7689 dynamic_template_type (struct type *type)
7691 type = ada_check_typedef (type);
7693 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7694 || ada_type_name (type) == NULL)
7695 return NULL;
7696 else
7698 int len = strlen (ada_type_name (type));
7700 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7701 return type;
7702 else
7703 return ada_find_parallel_type (type, "___XVE");
7707 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7708 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7710 static int
7711 is_dynamic_field (struct type *templ_type, int field_num)
7713 const char *name = templ_type->field (field_num).name ();
7715 return name != NULL
7716 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7717 && strstr (name, "___XVL") != NULL;
7720 /* The index of the variant field of TYPE, or -1 if TYPE does not
7721 represent a variant record type. */
7723 static int
7724 variant_field_index (struct type *type)
7726 int f;
7728 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7729 return -1;
7731 for (f = 0; f < type->num_fields (); f += 1)
7733 if (ada_is_variant_part (type, f))
7734 return f;
7736 return -1;
7739 /* A record type with no fields. */
7741 static struct type *
7742 empty_record (struct type *templ)
7744 struct type *type = type_allocator (templ).new_type ();
7746 type->set_code (TYPE_CODE_STRUCT);
7747 INIT_NONE_SPECIFIC (type);
7748 type->set_name ("<empty>");
7749 type->set_length (0);
7750 return type;
7753 /* An ordinary record type (with fixed-length fields) that describes
7754 the value of type TYPE at VALADDR or ADDRESS (see comments at
7755 the beginning of this section) VAL according to GNAT conventions.
7756 DVAL0 should describe the (portion of a) record that contains any
7757 necessary discriminants. It should be NULL if VAL->type () is
7758 an outer-level type (i.e., as opposed to a branch of a variant.) A
7759 variant field (unless unchecked) is replaced by a particular branch
7760 of the variant.
7762 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7763 length are not statically known are discarded. As a consequence,
7764 VALADDR, ADDRESS and DVAL0 are ignored.
7766 NOTE: Limitations: For now, we assume that dynamic fields and
7767 variants occupy whole numbers of bytes. However, they need not be
7768 byte-aligned. */
7770 struct type *
7771 ada_template_to_fixed_record_type_1 (struct type *type,
7772 const gdb_byte *valaddr,
7773 CORE_ADDR address, struct value *dval0,
7774 int keep_dynamic_fields)
7776 struct value *dval;
7777 struct type *rtype;
7778 int nfields, bit_len;
7779 int variant_field;
7780 long off;
7781 int fld_bit_len;
7782 int f;
7784 scoped_value_mark mark;
7786 /* Compute the number of fields in this record type that are going
7787 to be processed: unless keep_dynamic_fields, this includes only
7788 fields whose position and length are static will be processed. */
7789 if (keep_dynamic_fields)
7790 nfields = type->num_fields ();
7791 else
7793 nfields = 0;
7794 while (nfields < type->num_fields ()
7795 && !ada_is_variant_part (type, nfields)
7796 && !is_dynamic_field (type, nfields))
7797 nfields++;
7800 rtype = type_allocator (type).new_type ();
7801 rtype->set_code (TYPE_CODE_STRUCT);
7802 INIT_NONE_SPECIFIC (rtype);
7803 rtype->alloc_fields (nfields);
7804 rtype->set_name (ada_type_name (type));
7805 rtype->set_is_fixed_instance (true);
7807 off = 0;
7808 bit_len = 0;
7809 variant_field = -1;
7811 for (f = 0; f < nfields; f += 1)
7813 off = align_up (off, field_alignment (type, f))
7814 + type->field (f).loc_bitpos ();
7815 rtype->field (f).set_loc_bitpos (off);
7816 rtype->field (f).set_bitsize (0);
7818 if (ada_is_variant_part (type, f))
7820 variant_field = f;
7821 fld_bit_len = 0;
7823 else if (is_dynamic_field (type, f))
7825 const gdb_byte *field_valaddr = valaddr;
7826 CORE_ADDR field_address = address;
7827 struct type *field_type = type->field (f).type ()->target_type ();
7829 if (dval0 == NULL)
7831 /* Using plain value_from_contents_and_address here
7832 causes problems because we will end up trying to
7833 resolve a type that is currently being
7834 constructed. */
7835 dval = value_from_contents_and_address_unresolved (rtype,
7836 valaddr,
7837 address);
7838 rtype = dval->type ();
7840 else
7841 dval = dval0;
7843 /* If the type referenced by this field is an aligner type, we need
7844 to unwrap that aligner type, because its size might not be set.
7845 Keeping the aligner type would cause us to compute the wrong
7846 size for this field, impacting the offset of the all the fields
7847 that follow this one. */
7848 if (ada_is_aligner_type (field_type))
7850 long field_offset = type->field (f).loc_bitpos ();
7852 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7853 field_address = cond_offset_target (field_address, field_offset);
7854 field_type = ada_aligned_type (field_type);
7857 field_valaddr = cond_offset_host (field_valaddr,
7858 off / TARGET_CHAR_BIT);
7859 field_address = cond_offset_target (field_address,
7860 off / TARGET_CHAR_BIT);
7862 /* Get the fixed type of the field. Note that, in this case,
7863 we do not want to get the real type out of the tag: if
7864 the current field is the parent part of a tagged record,
7865 we will get the tag of the object. Clearly wrong: the real
7866 type of the parent is not the real type of the child. We
7867 would end up in an infinite loop. */
7868 field_type = ada_get_base_type (field_type);
7869 field_type = ada_to_fixed_type (field_type, field_valaddr,
7870 field_address, dval, 0);
7872 rtype->field (f).set_type (field_type);
7873 rtype->field (f).set_name (type->field (f).name ());
7874 /* The multiplication can potentially overflow. But because
7875 the field length has been size-checked just above, and
7876 assuming that the maximum size is a reasonable value,
7877 an overflow should not happen in practice. So rather than
7878 adding overflow recovery code to this already complex code,
7879 we just assume that it's not going to happen. */
7880 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7882 else
7884 /* Note: If this field's type is a typedef, it is important
7885 to preserve the typedef layer.
7887 Otherwise, we might be transforming a typedef to a fat
7888 pointer (encoding a pointer to an unconstrained array),
7889 into a basic fat pointer (encoding an unconstrained
7890 array). As both types are implemented using the same
7891 structure, the typedef is the only clue which allows us
7892 to distinguish between the two options. Stripping it
7893 would prevent us from printing this field appropriately. */
7894 rtype->field (f).set_type (type->field (f).type ());
7895 rtype->field (f).set_name (type->field (f).name ());
7896 if (type->field (f).bitsize () > 0)
7898 fld_bit_len = type->field (f).bitsize ();
7899 rtype->field (f).set_bitsize (fld_bit_len);
7901 else
7903 struct type *field_type = type->field (f).type ();
7905 /* We need to be careful of typedefs when computing
7906 the length of our field. If this is a typedef,
7907 get the length of the target type, not the length
7908 of the typedef. */
7909 if (field_type->code () == TYPE_CODE_TYPEDEF)
7910 field_type = ada_typedef_target_type (field_type);
7912 fld_bit_len =
7913 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7916 if (off + fld_bit_len > bit_len)
7917 bit_len = off + fld_bit_len;
7918 off += fld_bit_len;
7919 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7922 /* We handle the variant part, if any, at the end because of certain
7923 odd cases in which it is re-ordered so as NOT to be the last field of
7924 the record. This can happen in the presence of representation
7925 clauses. */
7926 if (variant_field >= 0)
7928 struct type *branch_type;
7930 off = rtype->field (variant_field).loc_bitpos ();
7932 if (dval0 == NULL)
7934 /* Using plain value_from_contents_and_address here causes
7935 problems because we will end up trying to resolve a type
7936 that is currently being constructed. */
7937 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7938 address);
7939 rtype = dval->type ();
7941 else
7942 dval = dval0;
7944 branch_type =
7945 to_fixed_variant_branch_type
7946 (type->field (variant_field).type (),
7947 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7948 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7949 if (branch_type == NULL)
7951 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7952 rtype->field (f - 1) = rtype->field (f);
7953 rtype->set_num_fields (rtype->num_fields () - 1);
7955 else
7957 rtype->field (variant_field).set_type (branch_type);
7958 rtype->field (variant_field).set_name ("S");
7959 fld_bit_len =
7960 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
7961 if (off + fld_bit_len > bit_len)
7962 bit_len = off + fld_bit_len;
7964 rtype->set_length
7965 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7969 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7970 should contain the alignment of that record, which should be a strictly
7971 positive value. If null or negative, then something is wrong, most
7972 probably in the debug info. In that case, we don't round up the size
7973 of the resulting type. If this record is not part of another structure,
7974 the current RTYPE length might be good enough for our purposes. */
7975 if (type->length () <= 0)
7977 if (rtype->name ())
7978 warning (_("Invalid type size for `%s' detected: %s."),
7979 rtype->name (), pulongest (type->length ()));
7980 else
7981 warning (_("Invalid type size for <unnamed> detected: %s."),
7982 pulongest (type->length ()));
7984 else
7985 rtype->set_length (align_up (rtype->length (), type->length ()));
7987 return rtype;
7990 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7991 of 1. */
7993 static struct type *
7994 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7995 CORE_ADDR address, struct value *dval0)
7997 return ada_template_to_fixed_record_type_1 (type, valaddr,
7998 address, dval0, 1);
8001 /* An ordinary record type in which ___XVL-convention fields and
8002 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8003 static approximations, containing all possible fields. Uses
8004 no runtime values. Useless for use in values, but that's OK,
8005 since the results are used only for type determinations. Works on both
8006 structs and unions. Representation note: to save space, we memorize
8007 the result of this function in the type::target_type of the
8008 template type. */
8010 static struct type *
8011 template_to_static_fixed_type (struct type *type0)
8013 struct type *type;
8014 int nfields;
8015 int f;
8017 /* No need no do anything if the input type is already fixed. */
8018 if (type0->is_fixed_instance ())
8019 return type0;
8021 /* Likewise if we already have computed the static approximation. */
8022 if (type0->target_type () != NULL)
8023 return type0->target_type ();
8025 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8026 type = type0;
8027 nfields = type0->num_fields ();
8029 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8030 recompute all over next time. */
8031 type0->set_target_type (type);
8033 for (f = 0; f < nfields; f += 1)
8035 struct type *field_type = type0->field (f).type ();
8036 struct type *new_type;
8038 if (is_dynamic_field (type0, f))
8040 field_type = ada_check_typedef (field_type);
8041 new_type = to_static_fixed_type (field_type->target_type ());
8043 else
8044 new_type = static_unwrap_type (field_type);
8046 if (new_type != field_type)
8048 /* Clone TYPE0 only the first time we get a new field type. */
8049 if (type == type0)
8051 type = type_allocator (type0).new_type ();
8052 type0->set_target_type (type);
8053 type->set_code (type0->code ());
8054 INIT_NONE_SPECIFIC (type);
8056 type->copy_fields (type0);
8058 type->set_name (ada_type_name (type0));
8059 type->set_is_fixed_instance (true);
8060 type->set_length (0);
8062 type->field (f).set_type (new_type);
8063 type->field (f).set_name (type0->field (f).name ());
8067 return type;
8070 /* Given an object of type TYPE whose contents are at VALADDR and
8071 whose address in memory is ADDRESS, returns a revision of TYPE,
8072 which should be a non-dynamic-sized record, in which the variant
8073 part, if any, is replaced with the appropriate branch. Looks
8074 for discriminant values in DVAL0, which can be NULL if the record
8075 contains the necessary discriminant values. */
8077 static struct type *
8078 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8079 CORE_ADDR address, struct value *dval0)
8081 struct value *dval;
8082 struct type *rtype;
8083 struct type *branch_type;
8084 int nfields = type->num_fields ();
8085 int variant_field = variant_field_index (type);
8087 if (variant_field == -1)
8088 return type;
8090 scoped_value_mark mark;
8091 if (dval0 == NULL)
8093 dval = value_from_contents_and_address (type, valaddr, address);
8094 type = dval->type ();
8096 else
8097 dval = dval0;
8099 rtype = type_allocator (type).new_type ();
8100 rtype->set_code (TYPE_CODE_STRUCT);
8101 INIT_NONE_SPECIFIC (rtype);
8102 rtype->copy_fields (type);
8104 rtype->set_name (ada_type_name (type));
8105 rtype->set_is_fixed_instance (true);
8106 rtype->set_length (type->length ());
8108 branch_type = to_fixed_variant_branch_type
8109 (type->field (variant_field).type (),
8110 cond_offset_host (valaddr,
8111 type->field (variant_field).loc_bitpos ()
8112 / TARGET_CHAR_BIT),
8113 cond_offset_target (address,
8114 type->field (variant_field).loc_bitpos ()
8115 / TARGET_CHAR_BIT), dval);
8116 if (branch_type == NULL)
8118 int f;
8120 for (f = variant_field + 1; f < nfields; f += 1)
8121 rtype->field (f - 1) = rtype->field (f);
8122 rtype->set_num_fields (rtype->num_fields () - 1);
8124 else
8126 rtype->field (variant_field).set_type (branch_type);
8127 rtype->field (variant_field).set_name ("S");
8128 rtype->field (variant_field).set_bitsize (0);
8129 rtype->set_length (rtype->length () + branch_type->length ());
8132 rtype->set_length (rtype->length ()
8133 - type->field (variant_field).type ()->length ());
8135 return rtype;
8138 /* An ordinary record type (with fixed-length fields) that describes
8139 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8140 beginning of this section]. Any necessary discriminants' values
8141 should be in DVAL, a record value; it may be NULL if the object
8142 at ADDR itself contains any necessary discriminant values.
8143 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8144 values from the record are needed. Except in the case that DVAL,
8145 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8146 unchecked) is replaced by a particular branch of the variant.
8148 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8149 is questionable and may be removed. It can arise during the
8150 processing of an unconstrained-array-of-record type where all the
8151 variant branches have exactly the same size. This is because in
8152 such cases, the compiler does not bother to use the XVS convention
8153 when encoding the record. I am currently dubious of this
8154 shortcut and suspect the compiler should be altered. FIXME. */
8156 static struct type *
8157 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8158 CORE_ADDR address, struct value *dval)
8160 struct type *templ_type;
8162 if (type0->is_fixed_instance ())
8163 return type0;
8165 templ_type = dynamic_template_type (type0);
8167 if (templ_type != NULL)
8168 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8169 else if (variant_field_index (type0) >= 0)
8171 if (dval == NULL && valaddr == NULL && address == 0)
8172 return type0;
8173 return to_record_with_fixed_variant_part (type0, valaddr, address,
8174 dval);
8176 else
8178 type0->set_is_fixed_instance (true);
8179 return type0;
8184 /* An ordinary record type (with fixed-length fields) that describes
8185 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8186 union type. Any necessary discriminants' values should be in DVAL,
8187 a record value. That is, this routine selects the appropriate
8188 branch of the union at ADDR according to the discriminant value
8189 indicated in the union's type name. Returns VAR_TYPE0 itself if
8190 it represents a variant subject to a pragma Unchecked_Union. */
8192 static struct type *
8193 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8194 CORE_ADDR address, struct value *dval)
8196 int which;
8197 struct type *templ_type;
8198 struct type *var_type;
8200 if (var_type0->code () == TYPE_CODE_PTR)
8201 var_type = var_type0->target_type ();
8202 else
8203 var_type = var_type0;
8205 templ_type = ada_find_parallel_type (var_type, "___XVU");
8207 if (templ_type != NULL)
8208 var_type = templ_type;
8210 if (is_unchecked_variant (var_type, dval->type ()))
8211 return var_type0;
8212 which = ada_which_variant_applies (var_type, dval);
8214 if (which < 0)
8215 return empty_record (var_type);
8216 else if (is_dynamic_field (var_type, which))
8217 return to_fixed_record_type
8218 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8219 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8220 return
8221 to_fixed_record_type
8222 (var_type->field (which).type (), valaddr, address, dval);
8223 else
8224 return var_type->field (which).type ();
8227 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8228 ENCODING_TYPE, a type following the GNAT conventions for discrete
8229 type encodings, only carries redundant information. */
8231 static int
8232 ada_is_redundant_range_encoding (struct type *range_type,
8233 struct type *encoding_type)
8235 const char *bounds_str;
8236 int n;
8237 LONGEST lo, hi;
8239 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8241 if (get_base_type (range_type)->code ()
8242 != get_base_type (encoding_type)->code ())
8244 /* The compiler probably used a simple base type to describe
8245 the range type instead of the range's actual base type,
8246 expecting us to get the real base type from the encoding
8247 anyway. In this situation, the encoding cannot be ignored
8248 as redundant. */
8249 return 0;
8252 if (is_dynamic_type (range_type))
8253 return 0;
8255 if (encoding_type->name () == NULL)
8256 return 0;
8258 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8259 if (bounds_str == NULL)
8260 return 0;
8262 n = 8; /* Skip "___XDLU_". */
8263 if (!ada_scan_number (bounds_str, n, &lo, &n))
8264 return 0;
8265 if (range_type->bounds ()->low.const_val () != lo)
8266 return 0;
8268 n += 2; /* Skip the "__" separator between the two bounds. */
8269 if (!ada_scan_number (bounds_str, n, &hi, &n))
8270 return 0;
8271 if (range_type->bounds ()->high.const_val () != hi)
8272 return 0;
8274 return 1;
8277 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8278 a type following the GNAT encoding for describing array type
8279 indices, only carries redundant information. */
8281 static int
8282 ada_is_redundant_index_type_desc (struct type *array_type,
8283 struct type *desc_type)
8285 struct type *this_layer = check_typedef (array_type);
8286 int i;
8288 for (i = 0; i < desc_type->num_fields (); i++)
8290 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8291 desc_type->field (i).type ()))
8292 return 0;
8293 this_layer = check_typedef (this_layer->target_type ());
8296 return 1;
8299 /* Assuming that TYPE0 is an array type describing the type of a value
8300 at ADDR, and that DVAL describes a record containing any
8301 discriminants used in TYPE0, returns a type for the value that
8302 contains no dynamic components (that is, no components whose sizes
8303 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8304 true, gives an error message if the resulting type's size is over
8305 varsize_limit. */
8307 static struct type *
8308 to_fixed_array_type (struct type *type0, struct value *dval,
8309 int ignore_too_big)
8311 struct type *index_type_desc;
8312 struct type *result;
8313 int constrained_packed_array_p;
8314 static const char *xa_suffix = "___XA";
8316 type0 = ada_check_typedef (type0);
8317 if (type0->is_fixed_instance ())
8318 return type0;
8320 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8321 if (constrained_packed_array_p)
8323 type0 = decode_constrained_packed_array_type (type0);
8324 if (type0 == nullptr)
8325 error (_("could not decode constrained packed array type"));
8328 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8330 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8331 encoding suffixed with 'P' may still be generated. If so,
8332 it should be used to find the XA type. */
8334 if (index_type_desc == NULL)
8336 const char *type_name = ada_type_name (type0);
8338 if (type_name != NULL)
8340 const int len = strlen (type_name);
8341 char *name = (char *) alloca (len + strlen (xa_suffix));
8343 if (type_name[len - 1] == 'P')
8345 strcpy (name, type_name);
8346 strcpy (name + len - 1, xa_suffix);
8347 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8352 ada_fixup_array_indexes_type (index_type_desc);
8353 if (index_type_desc != NULL
8354 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8356 /* Ignore this ___XA parallel type, as it does not bring any
8357 useful information. This allows us to avoid creating fixed
8358 versions of the array's index types, which would be identical
8359 to the original ones. This, in turn, can also help avoid
8360 the creation of fixed versions of the array itself. */
8361 index_type_desc = NULL;
8364 if (index_type_desc == NULL)
8366 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8368 /* NOTE: elt_type---the fixed version of elt_type0---should never
8369 depend on the contents of the array in properly constructed
8370 debugging data. */
8371 /* Create a fixed version of the array element type.
8372 We're not providing the address of an element here,
8373 and thus the actual object value cannot be inspected to do
8374 the conversion. This should not be a problem, since arrays of
8375 unconstrained objects are not allowed. In particular, all
8376 the elements of an array of a tagged type should all be of
8377 the same type specified in the debugging info. No need to
8378 consult the object tag. */
8379 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8381 /* Make sure we always create a new array type when dealing with
8382 packed array types, since we're going to fix-up the array
8383 type length and element bitsize a little further down. */
8384 if (elt_type0 == elt_type && !constrained_packed_array_p)
8385 result = type0;
8386 else
8388 type_allocator alloc (type0);
8389 result = create_array_type (alloc, elt_type, type0->index_type ());
8392 else
8394 int i;
8395 struct type *elt_type0;
8397 elt_type0 = type0;
8398 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8399 elt_type0 = elt_type0->target_type ();
8401 /* NOTE: result---the fixed version of elt_type0---should never
8402 depend on the contents of the array in properly constructed
8403 debugging data. */
8404 /* Create a fixed version of the array element type.
8405 We're not providing the address of an element here,
8406 and thus the actual object value cannot be inspected to do
8407 the conversion. This should not be a problem, since arrays of
8408 unconstrained objects are not allowed. In particular, all
8409 the elements of an array of a tagged type should all be of
8410 the same type specified in the debugging info. No need to
8411 consult the object tag. */
8412 result =
8413 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8415 elt_type0 = type0;
8416 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8418 struct type *range_type =
8419 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8421 type_allocator alloc (elt_type0);
8422 result = create_array_type (alloc, result, range_type);
8423 elt_type0 = elt_type0->target_type ();
8427 /* We want to preserve the type name. This can be useful when
8428 trying to get the type name of a value that has already been
8429 printed (for instance, if the user did "print VAR; whatis $". */
8430 result->set_name (type0->name ());
8432 if (constrained_packed_array_p)
8434 /* So far, the resulting type has been created as if the original
8435 type was a regular (non-packed) array type. As a result, the
8436 bitsize of the array elements needs to be set again, and the array
8437 length needs to be recomputed based on that bitsize. */
8438 int len = result->length () / result->target_type ()->length ();
8439 int elt_bitsize = type0->field (0).bitsize ();
8441 result->field (0).set_bitsize (elt_bitsize);
8442 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8443 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8444 result->set_length (result->length () + 1);
8447 result->set_is_fixed_instance (true);
8448 return result;
8452 /* A standard type (containing no dynamically sized components)
8453 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8454 DVAL describes a record containing any discriminants used in TYPE0,
8455 and may be NULL if there are none, or if the object of type TYPE at
8456 ADDRESS or in VALADDR contains these discriminants.
8458 If CHECK_TAG is not null, in the case of tagged types, this function
8459 attempts to locate the object's tag and use it to compute the actual
8460 type. However, when ADDRESS is null, we cannot use it to determine the
8461 location of the tag, and therefore compute the tagged type's actual type.
8462 So we return the tagged type without consulting the tag. */
8464 static struct type *
8465 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8466 CORE_ADDR address, struct value *dval, int check_tag)
8468 type = ada_check_typedef (type);
8470 /* Only un-fixed types need to be handled here. */
8471 if (!HAVE_GNAT_AUX_INFO (type))
8472 return type;
8474 switch (type->code ())
8476 default:
8477 return type;
8478 case TYPE_CODE_STRUCT:
8480 struct type *static_type = to_static_fixed_type (type);
8481 struct type *fixed_record_type =
8482 to_fixed_record_type (type, valaddr, address, NULL);
8484 /* If STATIC_TYPE is a tagged type and we know the object's address,
8485 then we can determine its tag, and compute the object's actual
8486 type from there. Note that we have to use the fixed record
8487 type (the parent part of the record may have dynamic fields
8488 and the way the location of _tag is expressed may depend on
8489 them). */
8491 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8493 struct value *tag =
8494 value_tag_from_contents_and_address
8495 (fixed_record_type,
8496 valaddr,
8497 address);
8498 struct type *real_type = type_from_tag (tag);
8499 struct value *obj =
8500 value_from_contents_and_address (fixed_record_type,
8501 valaddr,
8502 address);
8503 fixed_record_type = obj->type ();
8504 if (real_type != NULL)
8505 return to_fixed_record_type
8506 (real_type, NULL,
8507 ada_tag_value_at_base_address (obj)->address (), NULL);
8510 /* Check to see if there is a parallel ___XVZ variable.
8511 If there is, then it provides the actual size of our type. */
8512 else if (ada_type_name (fixed_record_type) != NULL)
8514 const char *name = ada_type_name (fixed_record_type);
8515 char *xvz_name
8516 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8517 bool xvz_found = false;
8518 LONGEST size;
8520 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8523 xvz_found = get_int_var_value (xvz_name, size);
8525 catch (const gdb_exception_error &except)
8527 /* We found the variable, but somehow failed to read
8528 its value. Rethrow the same error, but with a little
8529 bit more information, to help the user understand
8530 what went wrong (Eg: the variable might have been
8531 optimized out). */
8532 throw_error (except.error,
8533 _("unable to read value of %s (%s)"),
8534 xvz_name, except.what ());
8537 if (xvz_found && fixed_record_type->length () != size)
8539 fixed_record_type = copy_type (fixed_record_type);
8540 fixed_record_type->set_length (size);
8542 /* The FIXED_RECORD_TYPE may have be a stub. We have
8543 observed this when the debugging info is STABS, and
8544 apparently it is something that is hard to fix.
8546 In practice, we don't need the actual type definition
8547 at all, because the presence of the XVZ variable allows us
8548 to assume that there must be a XVS type as well, which we
8549 should be able to use later, when we need the actual type
8550 definition.
8552 In the meantime, pretend that the "fixed" type we are
8553 returning is NOT a stub, because this can cause trouble
8554 when using this type to create new types targeting it.
8555 Indeed, the associated creation routines often check
8556 whether the target type is a stub and will try to replace
8557 it, thus using a type with the wrong size. This, in turn,
8558 might cause the new type to have the wrong size too.
8559 Consider the case of an array, for instance, where the size
8560 of the array is computed from the number of elements in
8561 our array multiplied by the size of its element. */
8562 fixed_record_type->set_is_stub (false);
8565 return fixed_record_type;
8567 case TYPE_CODE_ARRAY:
8568 return to_fixed_array_type (type, dval, 1);
8569 case TYPE_CODE_UNION:
8570 if (dval == NULL)
8571 return type;
8572 else
8573 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8577 /* The same as ada_to_fixed_type_1, except that it preserves the type
8578 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8580 The typedef layer needs be preserved in order to differentiate between
8581 arrays and array pointers when both types are implemented using the same
8582 fat pointer. In the array pointer case, the pointer is encoded as
8583 a typedef of the pointer type. For instance, considering:
8585 type String_Access is access String;
8586 S1 : String_Access := null;
8588 To the debugger, S1 is defined as a typedef of type String. But
8589 to the user, it is a pointer. So if the user tries to print S1,
8590 we should not dereference the array, but print the array address
8591 instead.
8593 If we didn't preserve the typedef layer, we would lose the fact that
8594 the type is to be presented as a pointer (needs de-reference before
8595 being printed). And we would also use the source-level type name. */
8597 struct type *
8598 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8599 CORE_ADDR address, struct value *dval, int check_tag)
8602 struct type *fixed_type =
8603 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8605 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8606 then preserve the typedef layer.
8608 Implementation note: We can only check the main-type portion of
8609 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8610 from TYPE now returns a type that has the same instance flags
8611 as TYPE. For instance, if TYPE is a "typedef const", and its
8612 target type is a "struct", then the typedef elimination will return
8613 a "const" version of the target type. See check_typedef for more
8614 details about how the typedef layer elimination is done.
8616 brobecker/2010-11-19: It seems to me that the only case where it is
8617 useful to preserve the typedef layer is when dealing with fat pointers.
8618 Perhaps, we could add a check for that and preserve the typedef layer
8619 only in that situation. But this seems unnecessary so far, probably
8620 because we call check_typedef/ada_check_typedef pretty much everywhere.
8622 if (type->code () == TYPE_CODE_TYPEDEF
8623 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8624 == TYPE_MAIN_TYPE (fixed_type)))
8625 return type;
8627 return fixed_type;
8630 /* A standard (static-sized) type corresponding as well as possible to
8631 TYPE0, but based on no runtime data. */
8633 static struct type *
8634 to_static_fixed_type (struct type *type0)
8636 struct type *type;
8638 if (type0 == NULL)
8639 return NULL;
8641 if (type0->is_fixed_instance ())
8642 return type0;
8644 type0 = ada_check_typedef (type0);
8646 switch (type0->code ())
8648 default:
8649 return type0;
8650 case TYPE_CODE_STRUCT:
8651 type = dynamic_template_type (type0);
8652 if (type != NULL)
8653 return template_to_static_fixed_type (type);
8654 else
8655 return template_to_static_fixed_type (type0);
8656 case TYPE_CODE_UNION:
8657 type = ada_find_parallel_type (type0, "___XVU");
8658 if (type != NULL)
8659 return template_to_static_fixed_type (type);
8660 else
8661 return template_to_static_fixed_type (type0);
8665 /* A static approximation of TYPE with all type wrappers removed. */
8667 static struct type *
8668 static_unwrap_type (struct type *type)
8670 if (ada_is_aligner_type (type))
8672 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8673 if (ada_type_name (type1) == NULL)
8674 type1->set_name (ada_type_name (type));
8676 return static_unwrap_type (type1);
8678 else
8680 struct type *raw_real_type = ada_get_base_type (type);
8682 if (raw_real_type == type)
8683 return type;
8684 else
8685 return to_static_fixed_type (raw_real_type);
8689 /* In some cases, incomplete and private types require
8690 cross-references that are not resolved as records (for example,
8691 type Foo;
8692 type FooP is access Foo;
8693 V: FooP;
8694 type Foo is array ...;
8695 ). In these cases, since there is no mechanism for producing
8696 cross-references to such types, we instead substitute for FooP a
8697 stub enumeration type that is nowhere resolved, and whose tag is
8698 the name of the actual type. Call these types "non-record stubs". */
8700 /* A type equivalent to TYPE that is not a non-record stub, if one
8701 exists, otherwise TYPE. */
8703 struct type *
8704 ada_check_typedef (struct type *type)
8706 if (type == NULL)
8707 return NULL;
8709 /* If our type is an access to an unconstrained array, which is encoded
8710 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8711 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8712 what allows us to distinguish between fat pointers that represent
8713 array types, and fat pointers that represent array access types
8714 (in both cases, the compiler implements them as fat pointers). */
8715 if (ada_is_access_to_unconstrained_array (type))
8716 return type;
8718 type = check_typedef (type);
8719 if (type == NULL || type->code () != TYPE_CODE_ENUM
8720 || !type->is_stub ()
8721 || type->name () == NULL)
8722 return type;
8723 else
8725 const char *name = type->name ();
8726 struct type *type1 = ada_find_any_type (name);
8728 if (type1 == NULL)
8729 return type;
8731 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8732 stubs pointing to arrays, as we don't create symbols for array
8733 types, only for the typedef-to-array types). If that's the case,
8734 strip the typedef layer. */
8735 if (type1->code () == TYPE_CODE_TYPEDEF)
8736 type1 = ada_check_typedef (type1);
8738 return type1;
8742 /* A value representing the data at VALADDR/ADDRESS as described by
8743 type TYPE0, but with a standard (static-sized) type that correctly
8744 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8745 type, then return VAL0 [this feature is simply to avoid redundant
8746 creation of struct values]. */
8748 static struct value *
8749 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8750 struct value *val0)
8752 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8754 if (type == type0 && val0 != NULL)
8755 return val0;
8757 if (val0->lval () != lval_memory)
8759 /* Our value does not live in memory; it could be a convenience
8760 variable, for instance. Create a not_lval value using val0's
8761 contents. */
8762 return value_from_contents (type, val0->contents ().data ());
8765 return value_from_contents_and_address (type, 0, address);
8768 /* A value representing VAL, but with a standard (static-sized) type
8769 that correctly describes it. Does not necessarily create a new
8770 value. */
8772 struct value *
8773 ada_to_fixed_value (struct value *val)
8775 val = unwrap_value (val);
8776 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8777 return val;
8781 /* Attributes */
8783 /* Evaluate the 'POS attribute applied to ARG. */
8785 static LONGEST
8786 pos_atr (struct value *arg)
8788 struct value *val = coerce_ref (arg);
8789 struct type *type = val->type ();
8791 if (!discrete_type_p (type))
8792 error (_("'POS only defined on discrete types"));
8794 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8795 if (!result.has_value ())
8796 error (_("enumeration value is invalid: can't find 'POS"));
8798 return *result;
8801 struct value *
8802 ada_pos_atr (struct type *expect_type,
8803 struct expression *exp,
8804 enum noside noside, enum exp_opcode op,
8805 struct value *arg)
8807 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8808 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8809 return value::zero (type, not_lval);
8810 return value_from_longest (type, pos_atr (arg));
8813 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8815 static struct value *
8816 val_atr (struct type *type, LONGEST val)
8818 gdb_assert (discrete_type_p (type));
8819 if (type->code () == TYPE_CODE_RANGE)
8820 type = type->target_type ();
8821 if (type->code () == TYPE_CODE_ENUM)
8823 if (val < 0 || val >= type->num_fields ())
8824 error (_("argument to 'VAL out of range"));
8825 val = type->field (val).loc_enumval ();
8827 return value_from_longest (type, val);
8830 struct value *
8831 ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8832 struct value *arg)
8834 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8835 return value::zero (type, not_lval);
8837 if (!discrete_type_p (type))
8838 error (_("'VAL only defined on discrete types"));
8839 if (!integer_type_p (arg->type ()))
8840 error (_("'VAL requires integral argument"));
8842 return val_atr (type, value_as_long (arg));
8845 /* Implementation of the enum_rep attribute. */
8846 struct value *
8847 ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8848 struct value *arg)
8850 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8851 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8852 return value::zero (inttype, not_lval);
8854 if (type->code () == TYPE_CODE_RANGE)
8855 type = type->target_type ();
8856 if (type->code () != TYPE_CODE_ENUM)
8857 error (_("'Enum_Rep only defined on enum types"));
8858 if (!types_equal (type, arg->type ()))
8859 error (_("'Enum_Rep requires argument to have same type as enum"));
8861 return value_cast (inttype, arg);
8864 /* Implementation of the enum_val attribute. */
8865 struct value *
8866 ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8867 struct value *arg)
8869 struct type *original_type = type;
8870 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8871 return value::zero (original_type, not_lval);
8873 if (type->code () == TYPE_CODE_RANGE)
8874 type = type->target_type ();
8875 if (type->code () != TYPE_CODE_ENUM)
8876 error (_("'Enum_Val only defined on enum types"));
8877 if (!integer_type_p (arg->type ()))
8878 error (_("'Enum_Val requires integral argument"));
8880 LONGEST value = value_as_long (arg);
8881 for (int i = 0; i < type->num_fields (); ++i)
8883 if (type->field (i).loc_enumval () == value)
8884 return value_from_longest (original_type, value);
8887 error (_("value %s not found in enum"), plongest (value));
8892 /* Evaluation */
8894 /* True if TYPE appears to be an Ada character type.
8895 [At the moment, this is true only for Character and Wide_Character;
8896 It is a heuristic test that could stand improvement]. */
8898 bool
8899 ada_is_character_type (struct type *type)
8901 const char *name;
8903 /* If the type code says it's a character, then assume it really is,
8904 and don't check any further. */
8905 if (type->code () == TYPE_CODE_CHAR)
8906 return true;
8908 /* Otherwise, assume it's a character type iff it is a discrete type
8909 with a known character type name. */
8910 name = ada_type_name (type);
8911 return (name != NULL
8912 && (type->code () == TYPE_CODE_INT
8913 || type->code () == TYPE_CODE_RANGE)
8914 && (strcmp (name, "character") == 0
8915 || strcmp (name, "wide_character") == 0
8916 || strcmp (name, "wide_wide_character") == 0
8917 || strcmp (name, "unsigned char") == 0));
8920 /* True if TYPE appears to be an Ada string type. */
8922 bool
8923 ada_is_string_type (struct type *type)
8925 type = ada_check_typedef (type);
8926 if (type != NULL
8927 && type->code () != TYPE_CODE_PTR
8928 && (ada_is_simple_array_type (type)
8929 || ada_is_array_descriptor_type (type))
8930 && ada_array_arity (type) == 1)
8932 struct type *elttype = ada_array_element_type (type, 1);
8934 return ada_is_character_type (elttype);
8936 else
8937 return false;
8940 /* The compiler sometimes provides a parallel XVS type for a given
8941 PAD type. Normally, it is safe to follow the PAD type directly,
8942 but older versions of the compiler have a bug that causes the offset
8943 of its "F" field to be wrong. Following that field in that case
8944 would lead to incorrect results, but this can be worked around
8945 by ignoring the PAD type and using the associated XVS type instead.
8947 Set to True if the debugger should trust the contents of PAD types.
8948 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8949 static bool trust_pad_over_xvs = true;
8951 /* True if TYPE is a struct type introduced by the compiler to force the
8952 alignment of a value. Such types have a single field with a
8953 distinctive name. */
8956 ada_is_aligner_type (struct type *type)
8958 type = ada_check_typedef (type);
8960 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8961 return 0;
8963 return (type->code () == TYPE_CODE_STRUCT
8964 && type->num_fields () == 1
8965 && strcmp (type->field (0).name (), "F") == 0);
8968 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8969 the parallel type. */
8971 struct type *
8972 ada_get_base_type (struct type *raw_type)
8974 struct type *real_type_namer;
8975 struct type *raw_real_type;
8977 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8978 return raw_type;
8980 if (ada_is_aligner_type (raw_type))
8981 /* The encoding specifies that we should always use the aligner type.
8982 So, even if this aligner type has an associated XVS type, we should
8983 simply ignore it.
8985 According to the compiler gurus, an XVS type parallel to an aligner
8986 type may exist because of a stabs limitation. In stabs, aligner
8987 types are empty because the field has a variable-sized type, and
8988 thus cannot actually be used as an aligner type. As a result,
8989 we need the associated parallel XVS type to decode the type.
8990 Since the policy in the compiler is to not change the internal
8991 representation based on the debugging info format, we sometimes
8992 end up having a redundant XVS type parallel to the aligner type. */
8993 return raw_type;
8995 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8996 if (real_type_namer == NULL
8997 || real_type_namer->code () != TYPE_CODE_STRUCT
8998 || real_type_namer->num_fields () != 1)
8999 return raw_type;
9001 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
9003 /* This is an older encoding form where the base type needs to be
9004 looked up by name. We prefer the newer encoding because it is
9005 more efficient. */
9006 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
9007 if (raw_real_type == NULL)
9008 return raw_type;
9009 else
9010 return raw_real_type;
9013 /* The field in our XVS type is a reference to the base type. */
9014 return real_type_namer->field (0).type ()->target_type ();
9017 /* The type of value designated by TYPE, with all aligners removed. */
9019 struct type *
9020 ada_aligned_type (struct type *type)
9022 if (ada_is_aligner_type (type))
9023 return ada_aligned_type (type->field (0).type ());
9024 else
9025 return ada_get_base_type (type);
9029 /* The address of the aligned value in an object at address VALADDR
9030 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9032 const gdb_byte *
9033 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9035 if (ada_is_aligner_type (type))
9036 return ada_aligned_value_addr
9037 (type->field (0).type (),
9038 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
9039 else
9040 return valaddr;
9045 /* The printed representation of an enumeration literal with encoded
9046 name NAME. The value is good to the next call of ada_enum_name. */
9047 const char *
9048 ada_enum_name (const char *name)
9050 static std::string storage;
9051 const char *tmp;
9053 /* First, unqualify the enumeration name:
9054 1. Search for the last '.' character. If we find one, then skip
9055 all the preceding characters, the unqualified name starts
9056 right after that dot.
9057 2. Otherwise, we may be debugging on a target where the compiler
9058 translates dots into "__". Search forward for double underscores,
9059 but stop searching when we hit an overloading suffix, which is
9060 of the form "__" followed by digits. */
9062 tmp = strrchr (name, '.');
9063 if (tmp != NULL)
9064 name = tmp + 1;
9065 else
9067 while ((tmp = strstr (name, "__")) != NULL)
9069 if (isdigit (tmp[2]))
9070 break;
9071 else
9072 name = tmp + 2;
9076 if (name[0] == 'Q')
9078 int v;
9080 if (name[1] == 'U' || name[1] == 'W')
9082 int offset = 2;
9083 if (name[1] == 'W' && name[2] == 'W')
9085 /* Also handle the QWW case. */
9086 ++offset;
9088 if (sscanf (name + offset, "%x", &v) != 1)
9089 return name;
9091 else if (((name[1] >= '0' && name[1] <= '9')
9092 || (name[1] >= 'a' && name[1] <= 'z'))
9093 && name[2] == '\0')
9095 storage = string_printf ("'%c'", name[1]);
9096 return storage.c_str ();
9098 else
9099 return name;
9101 if (isascii (v) && isprint (v))
9102 storage = string_printf ("'%c'", v);
9103 else if (name[1] == 'U')
9104 storage = string_printf ("'[\"%02x\"]'", v);
9105 else if (name[2] != 'W')
9106 storage = string_printf ("'[\"%04x\"]'", v);
9107 else
9108 storage = string_printf ("'[\"%06x\"]'", v);
9110 return storage.c_str ();
9112 else
9114 tmp = strstr (name, "__");
9115 if (tmp == NULL)
9116 tmp = strstr (name, "$");
9117 if (tmp != NULL)
9119 storage = std::string (name, tmp - name);
9120 return storage.c_str ();
9123 return name;
9127 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9128 there is no parallel type, return nullptr. */
9130 static struct type *
9131 find_base_type (struct type *type)
9133 struct type *raw_real_type
9134 = ada_check_typedef (ada_get_base_type (type));
9136 /* No parallel XVS or XVE type. */
9137 if (type == raw_real_type
9138 && ada_find_parallel_type (type, "___XVE") == nullptr)
9139 return nullptr;
9141 return raw_real_type;
9144 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9145 value it wraps. */
9147 static struct value *
9148 unwrap_value (struct value *val)
9150 struct type *type = ada_check_typedef (val->type ());
9152 if (ada_is_aligner_type (type))
9154 struct value *v = ada_value_struct_elt (val, "F", 0);
9155 struct type *val_type = ada_check_typedef (v->type ());
9157 if (ada_type_name (val_type) == NULL)
9158 val_type->set_name (ada_type_name (type));
9160 return unwrap_value (v);
9162 else
9164 struct type *raw_real_type = find_base_type (type);
9165 if (raw_real_type == nullptr)
9166 return val;
9168 return
9169 coerce_unspec_val_to_type
9170 (val, ada_to_fixed_type (raw_real_type, 0,
9171 val->address (),
9172 NULL, 1));
9176 /* Given two array types T1 and T2, return nonzero iff both arrays
9177 contain the same number of elements. */
9179 static int
9180 ada_same_array_size_p (struct type *t1, struct type *t2)
9182 LONGEST lo1, hi1, lo2, hi2;
9184 /* Get the array bounds in order to verify that the size of
9185 the two arrays match. */
9186 if (!get_array_bounds (t1, &lo1, &hi1)
9187 || !get_array_bounds (t2, &lo2, &hi2))
9188 error (_("unable to determine array bounds"));
9190 /* To make things easier for size comparison, normalize a bit
9191 the case of empty arrays by making sure that the difference
9192 between upper bound and lower bound is always -1. */
9193 if (lo1 > hi1)
9194 hi1 = lo1 - 1;
9195 if (lo2 > hi2)
9196 hi2 = lo2 - 1;
9198 return (hi1 - lo1 == hi2 - lo2);
9201 /* Assuming that VAL is an array of integrals, and TYPE represents
9202 an array with the same number of elements, but with wider integral
9203 elements, return an array "casted" to TYPE. In practice, this
9204 means that the returned array is built by casting each element
9205 of the original array into TYPE's (wider) element type. */
9207 static struct value *
9208 ada_promote_array_of_integrals (struct type *type, struct value *val)
9210 struct type *elt_type = type->target_type ();
9211 LONGEST lo, hi;
9212 LONGEST i;
9214 /* Verify that both val and type are arrays of scalars, and
9215 that the size of val's elements is smaller than the size
9216 of type's element. */
9217 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9218 gdb_assert (is_integral_type (type->target_type ()));
9219 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9220 gdb_assert (is_integral_type (val->type ()->target_type ()));
9221 gdb_assert (type->target_type ()->length ()
9222 > val->type ()->target_type ()->length ());
9224 if (!get_array_bounds (type, &lo, &hi))
9225 error (_("unable to determine array bounds"));
9227 value *res = value::allocate (type);
9228 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9230 /* Promote each array element. */
9231 for (i = 0; i < hi - lo + 1; i++)
9233 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9234 int elt_len = elt_type->length ();
9236 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9239 return res;
9242 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9243 return the converted value. */
9245 static struct value *
9246 coerce_for_assign (struct type *type, struct value *val)
9248 struct type *type2 = val->type ();
9250 if (type == type2)
9251 return val;
9253 type2 = ada_check_typedef (type2);
9254 type = ada_check_typedef (type);
9256 if (type2->code () == TYPE_CODE_PTR
9257 && type->code () == TYPE_CODE_ARRAY)
9259 val = ada_value_ind (val);
9260 type2 = val->type ();
9263 if (type2->code () == TYPE_CODE_ARRAY
9264 && type->code () == TYPE_CODE_ARRAY)
9266 if (!ada_same_array_size_p (type, type2))
9267 error (_("cannot assign arrays of different length"));
9269 if (is_integral_type (type->target_type ())
9270 && is_integral_type (type2->target_type ())
9271 && type2->target_type ()->length () < type->target_type ()->length ())
9273 /* Allow implicit promotion of the array elements to
9274 a wider type. */
9275 return ada_promote_array_of_integrals (type, val);
9278 if (type2->target_type ()->length () != type->target_type ()->length ())
9279 error (_("Incompatible types in assignment"));
9280 val->deprecated_set_type (type);
9282 return val;
9285 static struct value *
9286 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9288 struct type *type1, *type2;
9290 arg1 = coerce_ref (arg1);
9291 arg2 = coerce_ref (arg2);
9292 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9293 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9295 if (type1->code () != TYPE_CODE_INT
9296 || type2->code () != TYPE_CODE_INT)
9297 return value_binop (arg1, arg2, op);
9299 switch (op)
9301 case BINOP_MOD:
9302 case BINOP_DIV:
9303 case BINOP_REM:
9304 break;
9305 default:
9306 return value_binop (arg1, arg2, op);
9309 gdb_mpz v2 = value_as_mpz (arg2);
9310 if (v2.sgn () == 0)
9312 const char *name;
9313 if (op == BINOP_MOD)
9314 name = "mod";
9315 else if (op == BINOP_DIV)
9316 name = "/";
9317 else
9319 gdb_assert (op == BINOP_REM);
9320 name = "rem";
9323 error (_("second operand of %s must not be zero."), name);
9326 if (type1->is_unsigned () || op == BINOP_MOD)
9327 return value_binop (arg1, arg2, op);
9329 gdb_mpz v1 = value_as_mpz (arg1);
9330 gdb_mpz v;
9331 switch (op)
9333 case BINOP_DIV:
9334 v = v1 / v2;
9335 break;
9336 case BINOP_REM:
9337 v = v1 % v2;
9338 if (v * v1 < 0)
9339 v -= v2;
9340 break;
9341 default:
9342 /* Should not reach this point. */
9343 gdb_assert_not_reached ("invalid operator");
9346 return value_from_mpz (type1, v);
9349 static int
9350 ada_value_equal (struct value *arg1, struct value *arg2)
9352 if (ada_is_direct_array_type (arg1->type ())
9353 || ada_is_direct_array_type (arg2->type ()))
9355 struct type *arg1_type, *arg2_type;
9357 /* Automatically dereference any array reference before
9358 we attempt to perform the comparison. */
9359 arg1 = ada_coerce_ref (arg1);
9360 arg2 = ada_coerce_ref (arg2);
9362 arg1 = ada_coerce_to_simple_array (arg1);
9363 arg2 = ada_coerce_to_simple_array (arg2);
9365 arg1_type = ada_check_typedef (arg1->type ());
9366 arg2_type = ada_check_typedef (arg2->type ());
9368 if (arg1_type->code () != TYPE_CODE_ARRAY
9369 || arg2_type->code () != TYPE_CODE_ARRAY)
9370 error (_("Attempt to compare array with non-array"));
9371 /* FIXME: The following works only for types whose
9372 representations use all bits (no padding or undefined bits)
9373 and do not have user-defined equality. */
9374 return (arg1_type->length () == arg2_type->length ()
9375 && memcmp (arg1->contents ().data (),
9376 arg2->contents ().data (),
9377 arg1_type->length ()) == 0);
9379 return value_equal (arg1, arg2);
9382 namespace expr
9385 bool
9386 check_objfile (const std::unique_ptr<ada_component> &comp,
9387 struct objfile *objfile)
9389 return comp->uses_objfile (objfile);
9392 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9393 component of LHS (a simple array or a record). Does not modify the
9394 inferior's memory, nor does it modify LHS (unless LHS ==
9395 CONTAINER). */
9397 static void
9398 assign_component (struct value *container, struct value *lhs, LONGEST index,
9399 struct expression *exp, operation_up &arg)
9401 scoped_value_mark mark;
9403 struct value *elt;
9404 struct type *lhs_type = check_typedef (lhs->type ());
9406 if (lhs_type->code () == TYPE_CODE_ARRAY)
9408 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9409 struct value *index_val = value_from_longest (index_type, index);
9411 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9413 else
9415 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9416 elt = ada_to_fixed_value (elt);
9419 ada_aggregate_operation *ag_op
9420 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9421 if (ag_op != nullptr)
9422 ag_op->assign_aggregate (container, elt, exp);
9423 else
9424 value_assign_to_component (container, elt,
9425 arg->evaluate (nullptr, exp,
9426 EVAL_NORMAL));
9429 bool
9430 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9432 for (const auto &item : m_components)
9433 if (item->uses_objfile (objfile))
9434 return true;
9435 return false;
9438 void
9439 ada_aggregate_component::dump (ui_file *stream, int depth)
9441 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9442 for (const auto &item : m_components)
9443 item->dump (stream, depth + 1);
9446 void
9447 ada_aggregate_component::assign (struct value *container,
9448 struct value *lhs, struct expression *exp,
9449 std::vector<LONGEST> &indices,
9450 LONGEST low, LONGEST high)
9452 for (auto &item : m_components)
9453 item->assign (container, lhs, exp, indices, low, high);
9456 /* See ada-exp.h. */
9458 value *
9459 ada_aggregate_operation::assign_aggregate (struct value *container,
9460 struct value *lhs,
9461 struct expression *exp)
9463 struct type *lhs_type;
9464 LONGEST low_index, high_index;
9466 container = ada_coerce_ref (container);
9467 if (ada_is_direct_array_type (container->type ()))
9468 container = ada_coerce_to_simple_array (container);
9469 lhs = ada_coerce_ref (lhs);
9470 if (!lhs->deprecated_modifiable ())
9471 error (_("Left operand of assignment is not a modifiable lvalue."));
9473 lhs_type = check_typedef (lhs->type ());
9474 if (ada_is_direct_array_type (lhs_type))
9476 lhs = ada_coerce_to_simple_array (lhs);
9477 lhs_type = check_typedef (lhs->type ());
9478 low_index = lhs_type->bounds ()->low.const_val ();
9479 high_index = lhs_type->bounds ()->high.const_val ();
9481 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9483 low_index = 0;
9484 high_index = num_visible_fields (lhs_type) - 1;
9486 else
9487 error (_("Left-hand side must be array or record."));
9489 std::vector<LONGEST> indices (4);
9490 indices[0] = indices[1] = low_index - 1;
9491 indices[2] = indices[3] = high_index + 1;
9493 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9494 low_index, high_index);
9496 return container;
9499 bool
9500 ada_positional_component::uses_objfile (struct objfile *objfile)
9502 return m_op->uses_objfile (objfile);
9505 void
9506 ada_positional_component::dump (ui_file *stream, int depth)
9508 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9509 depth, "", m_index);
9510 m_op->dump (stream, depth + 1);
9513 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9514 construct, given that the positions are relative to lower bound
9515 LOW, where HIGH is the upper bound. Record the position in
9516 INDICES. CONTAINER is as for assign_aggregate. */
9517 void
9518 ada_positional_component::assign (struct value *container,
9519 struct value *lhs, struct expression *exp,
9520 std::vector<LONGEST> &indices,
9521 LONGEST low, LONGEST high)
9523 LONGEST ind = m_index + low;
9525 if (ind - 1 == high)
9526 warning (_("Extra components in aggregate ignored."));
9527 if (ind <= high)
9529 add_component_interval (ind, ind, indices);
9530 assign_component (container, lhs, ind, exp, m_op);
9534 bool
9535 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9537 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9540 void
9541 ada_discrete_range_association::dump (ui_file *stream, int depth)
9543 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9544 m_low->dump (stream, depth + 1);
9545 m_high->dump (stream, depth + 1);
9548 void
9549 ada_discrete_range_association::assign (struct value *container,
9550 struct value *lhs,
9551 struct expression *exp,
9552 std::vector<LONGEST> &indices,
9553 LONGEST low, LONGEST high,
9554 operation_up &op)
9556 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9557 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9559 if (lower <= upper && (lower < low || upper > high))
9560 error (_("Index in component association out of bounds."));
9562 add_component_interval (lower, upper, indices);
9563 while (lower <= upper)
9565 assign_component (container, lhs, lower, exp, op);
9566 lower += 1;
9570 bool
9571 ada_name_association::uses_objfile (struct objfile *objfile)
9573 return m_val->uses_objfile (objfile);
9576 void
9577 ada_name_association::dump (ui_file *stream, int depth)
9579 gdb_printf (stream, _("%*sName:\n"), depth, "");
9580 m_val->dump (stream, depth + 1);
9583 void
9584 ada_name_association::assign (struct value *container,
9585 struct value *lhs,
9586 struct expression *exp,
9587 std::vector<LONGEST> &indices,
9588 LONGEST low, LONGEST high,
9589 operation_up &op)
9591 int index;
9593 if (ada_is_direct_array_type (lhs->type ()))
9594 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9595 EVAL_NORMAL)));
9596 else
9598 ada_string_operation *strop
9599 = dynamic_cast<ada_string_operation *> (m_val.get ());
9601 const char *name;
9602 if (strop != nullptr)
9603 name = strop->get_name ();
9604 else
9606 ada_var_value_operation *vvo
9607 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9608 if (vvo == nullptr)
9609 error (_("Invalid record component association."));
9610 name = vvo->get_symbol ()->natural_name ();
9611 /* In this scenario, the user wrote (name => expr), but
9612 write_name_assoc found some fully-qualified name and
9613 substituted it. This happens because, at parse time, the
9614 meaning of the expression isn't known; but here we know
9615 that just the base name was supplied and it refers to the
9616 name of a field. */
9617 name = ada_unqualified_name (name);
9620 index = 0;
9621 if (! find_struct_field (name, lhs->type (), 0,
9622 NULL, NULL, NULL, NULL, &index))
9623 error (_("Unknown component name: %s."), name);
9626 add_component_interval (index, index, indices);
9627 assign_component (container, lhs, index, exp, op);
9630 bool
9631 ada_choices_component::uses_objfile (struct objfile *objfile)
9633 if (m_op->uses_objfile (objfile))
9634 return true;
9635 for (const auto &item : m_assocs)
9636 if (item->uses_objfile (objfile))
9637 return true;
9638 return false;
9641 void
9642 ada_choices_component::dump (ui_file *stream, int depth)
9644 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9645 m_op->dump (stream, depth + 1);
9646 for (const auto &item : m_assocs)
9647 item->dump (stream, depth + 1);
9650 /* Assign into the components of LHS indexed by the OP_CHOICES
9651 construct at *POS, updating *POS past the construct, given that
9652 the allowable indices are LOW..HIGH. Record the indices assigned
9653 to in INDICES. CONTAINER is as for assign_aggregate. */
9654 void
9655 ada_choices_component::assign (struct value *container,
9656 struct value *lhs, struct expression *exp,
9657 std::vector<LONGEST> &indices,
9658 LONGEST low, LONGEST high)
9660 for (auto &item : m_assocs)
9661 item->assign (container, lhs, exp, indices, low, high, m_op);
9664 bool
9665 ada_others_component::uses_objfile (struct objfile *objfile)
9667 return m_op->uses_objfile (objfile);
9670 void
9671 ada_others_component::dump (ui_file *stream, int depth)
9673 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9674 m_op->dump (stream, depth + 1);
9677 /* Assign the value of the expression in the OP_OTHERS construct in
9678 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9679 have not been previously assigned. The index intervals already assigned
9680 are in INDICES. CONTAINER is as for assign_aggregate. */
9681 void
9682 ada_others_component::assign (struct value *container,
9683 struct value *lhs, struct expression *exp,
9684 std::vector<LONGEST> &indices,
9685 LONGEST low, LONGEST high)
9687 int num_indices = indices.size ();
9688 for (int i = 0; i < num_indices - 2; i += 2)
9690 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9691 assign_component (container, lhs, ind, exp, m_op);
9695 struct value *
9696 ada_assign_operation::evaluate (struct type *expect_type,
9697 struct expression *exp,
9698 enum noside noside)
9700 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9701 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
9703 ada_aggregate_operation *ag_op
9704 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9705 if (ag_op != nullptr)
9707 if (noside != EVAL_NORMAL)
9708 return arg1;
9710 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9711 return ada_value_assign (arg1, arg1);
9713 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9714 except if the lhs of our assignment is a convenience variable.
9715 In the case of assigning to a convenience variable, the lhs
9716 should be exactly the result of the evaluation of the rhs. */
9717 struct type *type = arg1->type ();
9718 if (arg1->lval () == lval_internalvar)
9719 type = NULL;
9720 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9721 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9722 return arg1;
9723 if (arg1->lval () == lval_internalvar)
9725 /* Nothing. */
9727 else
9728 arg2 = coerce_for_assign (arg1->type (), arg2);
9729 return ada_value_assign (arg1, arg2);
9732 } /* namespace expr */
9734 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9735 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9736 overlap. */
9737 static void
9738 add_component_interval (LONGEST low, LONGEST high,
9739 std::vector<LONGEST> &indices)
9741 int i, j;
9743 int size = indices.size ();
9744 for (i = 0; i < size; i += 2) {
9745 if (high >= indices[i] && low <= indices[i + 1])
9747 int kh;
9749 for (kh = i + 2; kh < size; kh += 2)
9750 if (high < indices[kh])
9751 break;
9752 if (low < indices[i])
9753 indices[i] = low;
9754 indices[i + 1] = indices[kh - 1];
9755 if (high > indices[i + 1])
9756 indices[i + 1] = high;
9757 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9758 indices.resize (kh - i - 2);
9759 return;
9761 else if (high < indices[i])
9762 break;
9765 indices.resize (indices.size () + 2);
9766 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9767 indices[j] = indices[j - 2];
9768 indices[i] = low;
9769 indices[i + 1] = high;
9772 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9773 is different. */
9775 static struct value *
9776 ada_value_cast (struct type *type, struct value *arg2)
9778 if (type == ada_check_typedef (arg2->type ()))
9779 return arg2;
9781 return value_cast (type, arg2);
9784 /* Evaluating Ada expressions, and printing their result.
9785 ------------------------------------------------------
9787 1. Introduction:
9788 ----------------
9790 We usually evaluate an Ada expression in order to print its value.
9791 We also evaluate an expression in order to print its type, which
9792 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9793 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9794 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9795 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9796 similar.
9798 Evaluating expressions is a little more complicated for Ada entities
9799 than it is for entities in languages such as C. The main reason for
9800 this is that Ada provides types whose definition might be dynamic.
9801 One example of such types is variant records. Or another example
9802 would be an array whose bounds can only be known at run time.
9804 The following description is a general guide as to what should be
9805 done (and what should NOT be done) in order to evaluate an expression
9806 involving such types, and when. This does not cover how the semantic
9807 information is encoded by GNAT as this is covered separatly. For the
9808 document used as the reference for the GNAT encoding, see exp_dbug.ads
9809 in the GNAT sources.
9811 Ideally, we should embed each part of this description next to its
9812 associated code. Unfortunately, the amount of code is so vast right
9813 now that it's hard to see whether the code handling a particular
9814 situation might be duplicated or not. One day, when the code is
9815 cleaned up, this guide might become redundant with the comments
9816 inserted in the code, and we might want to remove it.
9818 2. ``Fixing'' an Entity, the Simple Case:
9819 -----------------------------------------
9821 When evaluating Ada expressions, the tricky issue is that they may
9822 reference entities whose type contents and size are not statically
9823 known. Consider for instance a variant record:
9825 type Rec (Empty : Boolean := True) is record
9826 case Empty is
9827 when True => null;
9828 when False => Value : Integer;
9829 end case;
9830 end record;
9831 Yes : Rec := (Empty => False, Value => 1);
9832 No : Rec := (empty => True);
9834 The size and contents of that record depends on the value of the
9835 discriminant (Rec.Empty). At this point, neither the debugging
9836 information nor the associated type structure in GDB are able to
9837 express such dynamic types. So what the debugger does is to create
9838 "fixed" versions of the type that applies to the specific object.
9839 We also informally refer to this operation as "fixing" an object,
9840 which means creating its associated fixed type.
9842 Example: when printing the value of variable "Yes" above, its fixed
9843 type would look like this:
9845 type Rec is record
9846 Empty : Boolean;
9847 Value : Integer;
9848 end record;
9850 On the other hand, if we printed the value of "No", its fixed type
9851 would become:
9853 type Rec is record
9854 Empty : Boolean;
9855 end record;
9857 Things become a little more complicated when trying to fix an entity
9858 with a dynamic type that directly contains another dynamic type,
9859 such as an array of variant records, for instance. There are
9860 two possible cases: Arrays, and records.
9862 3. ``Fixing'' Arrays:
9863 ---------------------
9865 The type structure in GDB describes an array in terms of its bounds,
9866 and the type of its elements. By design, all elements in the array
9867 have the same type and we cannot represent an array of variant elements
9868 using the current type structure in GDB. When fixing an array,
9869 we cannot fix the array element, as we would potentially need one
9870 fixed type per element of the array. As a result, the best we can do
9871 when fixing an array is to produce an array whose bounds and size
9872 are correct (allowing us to read it from memory), but without having
9873 touched its element type. Fixing each element will be done later,
9874 when (if) necessary.
9876 Arrays are a little simpler to handle than records, because the same
9877 amount of memory is allocated for each element of the array, even if
9878 the amount of space actually used by each element differs from element
9879 to element. Consider for instance the following array of type Rec:
9881 type Rec_Array is array (1 .. 2) of Rec;
9883 The actual amount of memory occupied by each element might be different
9884 from element to element, depending on the value of their discriminant.
9885 But the amount of space reserved for each element in the array remains
9886 fixed regardless. So we simply need to compute that size using
9887 the debugging information available, from which we can then determine
9888 the array size (we multiply the number of elements of the array by
9889 the size of each element).
9891 The simplest case is when we have an array of a constrained element
9892 type. For instance, consider the following type declarations:
9894 type Bounded_String (Max_Size : Integer) is
9895 Length : Integer;
9896 Buffer : String (1 .. Max_Size);
9897 end record;
9898 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9900 In this case, the compiler describes the array as an array of
9901 variable-size elements (identified by its XVS suffix) for which
9902 the size can be read in the parallel XVZ variable.
9904 In the case of an array of an unconstrained element type, the compiler
9905 wraps the array element inside a private PAD type. This type should not
9906 be shown to the user, and must be "unwrap"'ed before printing. Note
9907 that we also use the adjective "aligner" in our code to designate
9908 these wrapper types.
9910 In some cases, the size allocated for each element is statically
9911 known. In that case, the PAD type already has the correct size,
9912 and the array element should remain unfixed.
9914 But there are cases when this size is not statically known.
9915 For instance, assuming that "Five" is an integer variable:
9917 type Dynamic is array (1 .. Five) of Integer;
9918 type Wrapper (Has_Length : Boolean := False) is record
9919 Data : Dynamic;
9920 case Has_Length is
9921 when True => Length : Integer;
9922 when False => null;
9923 end case;
9924 end record;
9925 type Wrapper_Array is array (1 .. 2) of Wrapper;
9927 Hello : Wrapper_Array := (others => (Has_Length => True,
9928 Data => (others => 17),
9929 Length => 1));
9932 The debugging info would describe variable Hello as being an
9933 array of a PAD type. The size of that PAD type is not statically
9934 known, but can be determined using a parallel XVZ variable.
9935 In that case, a copy of the PAD type with the correct size should
9936 be used for the fixed array.
9938 3. ``Fixing'' record type objects:
9939 ----------------------------------
9941 Things are slightly different from arrays in the case of dynamic
9942 record types. In this case, in order to compute the associated
9943 fixed type, we need to determine the size and offset of each of
9944 its components. This, in turn, requires us to compute the fixed
9945 type of each of these components.
9947 Consider for instance the example:
9949 type Bounded_String (Max_Size : Natural) is record
9950 Str : String (1 .. Max_Size);
9951 Length : Natural;
9952 end record;
9953 My_String : Bounded_String (Max_Size => 10);
9955 In that case, the position of field "Length" depends on the size
9956 of field Str, which itself depends on the value of the Max_Size
9957 discriminant. In order to fix the type of variable My_String,
9958 we need to fix the type of field Str. Therefore, fixing a variant
9959 record requires us to fix each of its components.
9961 However, if a component does not have a dynamic size, the component
9962 should not be fixed. In particular, fields that use a PAD type
9963 should not fixed. Here is an example where this might happen
9964 (assuming type Rec above):
9966 type Container (Big : Boolean) is record
9967 First : Rec;
9968 After : Integer;
9969 case Big is
9970 when True => Another : Integer;
9971 when False => null;
9972 end case;
9973 end record;
9974 My_Container : Container := (Big => False,
9975 First => (Empty => True),
9976 After => 42);
9978 In that example, the compiler creates a PAD type for component First,
9979 whose size is constant, and then positions the component After just
9980 right after it. The offset of component After is therefore constant
9981 in this case.
9983 The debugger computes the position of each field based on an algorithm
9984 that uses, among other things, the actual position and size of the field
9985 preceding it. Let's now imagine that the user is trying to print
9986 the value of My_Container. If the type fixing was recursive, we would
9987 end up computing the offset of field After based on the size of the
9988 fixed version of field First. And since in our example First has
9989 only one actual field, the size of the fixed type is actually smaller
9990 than the amount of space allocated to that field, and thus we would
9991 compute the wrong offset of field After.
9993 To make things more complicated, we need to watch out for dynamic
9994 components of variant records (identified by the ___XVL suffix in
9995 the component name). Even if the target type is a PAD type, the size
9996 of that type might not be statically known. So the PAD type needs
9997 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9998 we might end up with the wrong size for our component. This can be
9999 observed with the following type declarations:
10001 type Octal is new Integer range 0 .. 7;
10002 type Octal_Array is array (Positive range <>) of Octal;
10003 pragma Pack (Octal_Array);
10005 type Octal_Buffer (Size : Positive) is record
10006 Buffer : Octal_Array (1 .. Size);
10007 Length : Integer;
10008 end record;
10010 In that case, Buffer is a PAD type whose size is unset and needs
10011 to be computed by fixing the unwrapped type.
10013 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10014 ----------------------------------------------------------
10016 Lastly, when should the sub-elements of an entity that remained unfixed
10017 thus far, be actually fixed?
10019 The answer is: Only when referencing that element. For instance
10020 when selecting one component of a record, this specific component
10021 should be fixed at that point in time. Or when printing the value
10022 of a record, each component should be fixed before its value gets
10023 printed. Similarly for arrays, the element of the array should be
10024 fixed when printing each element of the array, or when extracting
10025 one element out of that array. On the other hand, fixing should
10026 not be performed on the elements when taking a slice of an array!
10028 Note that one of the side effects of miscomputing the offset and
10029 size of each field is that we end up also miscomputing the size
10030 of the containing type. This can have adverse results when computing
10031 the value of an entity. GDB fetches the value of an entity based
10032 on the size of its type, and thus a wrong size causes GDB to fetch
10033 the wrong amount of memory. In the case where the computed size is
10034 too small, GDB fetches too little data to print the value of our
10035 entity. Results in this case are unpredictable, as we usually read
10036 past the buffer containing the data =:-o. */
10038 /* A helper function for TERNOP_IN_RANGE. */
10040 static value *
10041 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10042 enum noside noside,
10043 value *arg1, value *arg2, value *arg3)
10045 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10046 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10047 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10048 return
10049 value_from_longest (type,
10050 (value_less (arg1, arg3)
10051 || value_equal (arg1, arg3))
10052 && (value_less (arg2, arg1)
10053 || value_equal (arg2, arg1)));
10056 /* A helper function for UNOP_NEG. */
10058 value *
10059 ada_unop_neg (struct type *expect_type,
10060 struct expression *exp,
10061 enum noside noside, enum exp_opcode op,
10062 struct value *arg1)
10064 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10065 return value_neg (arg1);
10068 /* A helper function for UNOP_IN_RANGE. */
10070 value *
10071 ada_unop_in_range (struct type *expect_type,
10072 struct expression *exp,
10073 enum noside noside, enum exp_opcode op,
10074 struct value *arg1, struct type *type)
10076 struct value *arg2, *arg3;
10077 switch (type->code ())
10079 default:
10080 lim_warning (_("Membership test incompletely implemented; "
10081 "always returns true"));
10082 type = language_bool_type (exp->language_defn, exp->gdbarch);
10083 return value_from_longest (type, 1);
10085 case TYPE_CODE_RANGE:
10086 arg2 = value_from_longest (type,
10087 type->bounds ()->low.const_val ());
10088 arg3 = value_from_longest (type,
10089 type->bounds ()->high.const_val ());
10090 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10091 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10092 type = language_bool_type (exp->language_defn, exp->gdbarch);
10093 return
10094 value_from_longest (type,
10095 (value_less (arg1, arg3)
10096 || value_equal (arg1, arg3))
10097 && (value_less (arg2, arg1)
10098 || value_equal (arg2, arg1)));
10102 /* A helper function for OP_ATR_TAG. */
10104 value *
10105 ada_atr_tag (struct type *expect_type,
10106 struct expression *exp,
10107 enum noside noside, enum exp_opcode op,
10108 struct value *arg1)
10110 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10111 return value::zero (ada_tag_type (arg1), not_lval);
10113 return ada_value_tag (arg1);
10116 /* A helper function for OP_ATR_SIZE. */
10118 value *
10119 ada_atr_size (struct type *expect_type,
10120 struct expression *exp,
10121 enum noside noside, enum exp_opcode op,
10122 struct value *arg1)
10124 struct type *type = arg1->type ();
10126 /* If the argument is a reference, then dereference its type, since
10127 the user is really asking for the size of the actual object,
10128 not the size of the pointer. */
10129 if (type->code () == TYPE_CODE_REF)
10130 type = type->target_type ();
10132 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10133 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10134 else
10135 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10136 TARGET_CHAR_BIT * type->length ());
10139 /* A helper function for UNOP_ABS. */
10141 value *
10142 ada_abs (struct type *expect_type,
10143 struct expression *exp,
10144 enum noside noside, enum exp_opcode op,
10145 struct value *arg1)
10147 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10148 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10149 return value_neg (arg1);
10150 else
10151 return arg1;
10154 /* A helper function for BINOP_MUL. */
10156 value *
10157 ada_mult_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 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10164 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10165 return value::zero (arg1->type (), not_lval);
10167 else
10169 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10170 return ada_value_binop (arg1, arg2, op);
10174 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10176 value *
10177 ada_equal_binop (struct type *expect_type,
10178 struct expression *exp,
10179 enum noside noside, enum exp_opcode op,
10180 struct value *arg1, struct value *arg2)
10182 int tem;
10183 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10184 tem = 0;
10185 else
10187 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10188 tem = ada_value_equal (arg1, arg2);
10190 if (op == BINOP_NOTEQUAL)
10191 tem = !tem;
10192 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10193 return value_from_longest (type, tem);
10196 /* A helper function for TERNOP_SLICE. */
10198 value *
10199 ada_ternop_slice (struct expression *exp,
10200 enum noside noside,
10201 struct value *array, struct value *low_bound_val,
10202 struct value *high_bound_val)
10204 LONGEST low_bound;
10205 LONGEST high_bound;
10207 low_bound_val = coerce_ref (low_bound_val);
10208 high_bound_val = coerce_ref (high_bound_val);
10209 low_bound = value_as_long (low_bound_val);
10210 high_bound = value_as_long (high_bound_val);
10212 /* If this is a reference to an aligner type, then remove all
10213 the aligners. */
10214 if (array->type ()->code () == TYPE_CODE_REF
10215 && ada_is_aligner_type (array->type ()->target_type ()))
10216 array->type ()->set_target_type
10217 (ada_aligned_type (array->type ()->target_type ()));
10219 if (ada_is_any_packed_array_type (array->type ()))
10220 error (_("cannot slice a packed array"));
10222 /* If this is a reference to an array or an array lvalue,
10223 convert to a pointer. */
10224 if (array->type ()->code () == TYPE_CODE_REF
10225 || (array->type ()->code () == TYPE_CODE_ARRAY
10226 && array->lval () == lval_memory))
10227 array = value_addr (array);
10229 if (noside == EVAL_AVOID_SIDE_EFFECTS
10230 && ada_is_array_descriptor_type (ada_check_typedef
10231 (array->type ())))
10232 return empty_array (ada_type_of_array (array, 0), low_bound,
10233 high_bound);
10235 array = ada_coerce_to_simple_array_ptr (array);
10237 /* If we have more than one level of pointer indirection,
10238 dereference the value until we get only one level. */
10239 while (array->type ()->code () == TYPE_CODE_PTR
10240 && (array->type ()->target_type ()->code ()
10241 == TYPE_CODE_PTR))
10242 array = value_ind (array);
10244 /* Make sure we really do have an array type before going further,
10245 to avoid a SEGV when trying to get the index type or the target
10246 type later down the road if the debug info generated by
10247 the compiler is incorrect or incomplete. */
10248 if (!ada_is_simple_array_type (array->type ()))
10249 error (_("cannot take slice of non-array"));
10251 if (ada_check_typedef (array->type ())->code ()
10252 == TYPE_CODE_PTR)
10254 struct type *type0 = ada_check_typedef (array->type ());
10256 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10257 return empty_array (type0->target_type (), low_bound, high_bound);
10258 else
10260 struct type *arr_type0 =
10261 to_fixed_array_type (type0->target_type (), NULL, 1);
10263 return ada_value_slice_from_ptr (array, arr_type0,
10264 longest_to_int (low_bound),
10265 longest_to_int (high_bound));
10268 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10269 return array;
10270 else if (high_bound < low_bound)
10271 return empty_array (array->type (), low_bound, high_bound);
10272 else
10273 return ada_value_slice (array, longest_to_int (low_bound),
10274 longest_to_int (high_bound));
10277 /* A helper function for BINOP_IN_BOUNDS. */
10279 value *
10280 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10281 struct value *arg1, struct value *arg2, int n)
10283 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10285 struct type *type = language_bool_type (exp->language_defn,
10286 exp->gdbarch);
10287 return value::zero (type, not_lval);
10290 struct type *type = ada_index_type (arg2->type (), n, "range");
10291 if (!type)
10292 type = arg1->type ();
10294 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10295 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10297 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10298 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10299 type = language_bool_type (exp->language_defn, exp->gdbarch);
10300 return value_from_longest (type,
10301 (value_less (arg1, arg3)
10302 || value_equal (arg1, arg3))
10303 && (value_less (arg2, arg1)
10304 || value_equal (arg2, arg1)));
10307 /* A helper function for some attribute operations. */
10309 static value *
10310 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10311 struct value *arg1, struct type *type_arg, int tem)
10313 const char *attr_name = nullptr;
10314 if (op == OP_ATR_FIRST)
10315 attr_name = "first";
10316 else if (op == OP_ATR_LAST)
10317 attr_name = "last";
10319 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10321 if (type_arg == NULL)
10322 type_arg = arg1->type ();
10324 if (ada_is_constrained_packed_array_type (type_arg))
10325 type_arg = decode_constrained_packed_array_type (type_arg);
10327 if (!discrete_type_p (type_arg))
10329 switch (op)
10331 default: /* Should never happen. */
10332 error (_("unexpected attribute encountered"));
10333 case OP_ATR_FIRST:
10334 case OP_ATR_LAST:
10335 type_arg = ada_index_type (type_arg, tem,
10336 attr_name);
10337 break;
10338 case OP_ATR_LENGTH:
10339 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10340 break;
10344 return value::zero (type_arg, not_lval);
10346 else if (type_arg == NULL)
10348 arg1 = ada_coerce_ref (arg1);
10350 if (ada_is_constrained_packed_array_type (arg1->type ()))
10351 arg1 = ada_coerce_to_simple_array (arg1);
10353 struct type *type;
10354 if (op == OP_ATR_LENGTH)
10355 type = builtin_type (exp->gdbarch)->builtin_int;
10356 else
10358 type = ada_index_type (arg1->type (), tem,
10359 attr_name);
10360 if (type == NULL)
10361 type = builtin_type (exp->gdbarch)->builtin_int;
10364 switch (op)
10366 default: /* Should never happen. */
10367 error (_("unexpected attribute encountered"));
10368 case OP_ATR_FIRST:
10369 return value_from_longest
10370 (type, ada_array_bound (arg1, tem, 0));
10371 case OP_ATR_LAST:
10372 return value_from_longest
10373 (type, ada_array_bound (arg1, tem, 1));
10374 case OP_ATR_LENGTH:
10375 return value_from_longest
10376 (type, ada_array_length (arg1, tem));
10379 else if (discrete_type_p (type_arg))
10381 struct type *range_type;
10382 const char *name = ada_type_name (type_arg);
10384 range_type = NULL;
10385 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10386 range_type = to_fixed_range_type (type_arg, NULL);
10387 if (range_type == NULL)
10388 range_type = type_arg;
10389 switch (op)
10391 default:
10392 error (_("unexpected attribute encountered"));
10393 case OP_ATR_FIRST:
10394 return value_from_longest
10395 (range_type, ada_discrete_type_low_bound (range_type));
10396 case OP_ATR_LAST:
10397 return value_from_longest
10398 (range_type, ada_discrete_type_high_bound (range_type));
10399 case OP_ATR_LENGTH:
10400 error (_("the 'length attribute applies only to array types"));
10403 else if (type_arg->code () == TYPE_CODE_FLT)
10404 error (_("unimplemented type attribute"));
10405 else
10407 LONGEST low, high;
10409 if (ada_is_constrained_packed_array_type (type_arg))
10410 type_arg = decode_constrained_packed_array_type (type_arg);
10412 struct type *type;
10413 if (op == OP_ATR_LENGTH)
10414 type = builtin_type (exp->gdbarch)->builtin_int;
10415 else
10417 type = ada_index_type (type_arg, tem, attr_name);
10418 if (type == NULL)
10419 type = builtin_type (exp->gdbarch)->builtin_int;
10422 switch (op)
10424 default:
10425 error (_("unexpected attribute encountered"));
10426 case OP_ATR_FIRST:
10427 low = ada_array_bound_from_type (type_arg, tem, 0);
10428 return value_from_longest (type, low);
10429 case OP_ATR_LAST:
10430 high = ada_array_bound_from_type (type_arg, tem, 1);
10431 return value_from_longest (type, high);
10432 case OP_ATR_LENGTH:
10433 low = ada_array_bound_from_type (type_arg, tem, 0);
10434 high = ada_array_bound_from_type (type_arg, tem, 1);
10435 return value_from_longest (type, high - low + 1);
10440 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10442 struct value *
10443 ada_binop_minmax (struct type *expect_type,
10444 struct expression *exp,
10445 enum noside noside, enum exp_opcode op,
10446 struct value *arg1, struct value *arg2)
10448 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10449 return value::zero (arg1->type (), not_lval);
10450 else
10452 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10453 return value_binop (arg1, arg2, op);
10457 /* A helper function for BINOP_EXP. */
10459 struct value *
10460 ada_binop_exp (struct type *expect_type,
10461 struct expression *exp,
10462 enum noside noside, enum exp_opcode op,
10463 struct value *arg1, struct value *arg2)
10465 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10466 return value::zero (arg1->type (), not_lval);
10467 else
10469 /* For integer exponentiation operations,
10470 only promote the first argument. */
10471 if (is_integral_type (arg2->type ()))
10472 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10473 else
10474 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10476 return value_binop (arg1, arg2, op);
10480 namespace expr
10483 /* See ada-exp.h. */
10485 operation_up
10486 ada_resolvable::replace (operation_up &&owner,
10487 struct expression *exp,
10488 bool deprocedure_p,
10489 bool parse_completion,
10490 innermost_block_tracker *tracker,
10491 struct type *context_type)
10493 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10494 return (make_operation<ada_funcall_operation>
10495 (std::move (owner),
10496 std::vector<operation_up> ()));
10497 return std::move (owner);
10500 /* Convert the character literal whose value would be VAL to the
10501 appropriate value of type TYPE, if there is a translation.
10502 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10503 the literal 'A' (VAL == 65), returns 0. */
10505 static LONGEST
10506 convert_char_literal (struct type *type, LONGEST val)
10508 char name[12];
10509 int f;
10511 if (type == NULL)
10512 return val;
10513 type = check_typedef (type);
10514 if (type->code () != TYPE_CODE_ENUM)
10515 return val;
10517 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10518 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10519 else if (val >= 0 && val < 256)
10520 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10521 else if (val >= 0 && val < 0x10000)
10522 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10523 else
10524 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10525 size_t len = strlen (name);
10526 for (f = 0; f < type->num_fields (); f += 1)
10528 /* Check the suffix because an enum constant in a package will
10529 have a name like "pkg__QUxx". This is safe enough because we
10530 already have the correct type, and because mangling means
10531 there can't be clashes. */
10532 const char *ename = type->field (f).name ();
10533 size_t elen = strlen (ename);
10535 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10536 return type->field (f).loc_enumval ();
10538 return val;
10541 value *
10542 ada_char_operation::evaluate (struct type *expect_type,
10543 struct expression *exp,
10544 enum noside noside)
10546 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10547 if (expect_type != nullptr)
10548 result = ada_value_cast (expect_type, result);
10549 return result;
10552 /* See ada-exp.h. */
10554 operation_up
10555 ada_char_operation::replace (operation_up &&owner,
10556 struct expression *exp,
10557 bool deprocedure_p,
10558 bool parse_completion,
10559 innermost_block_tracker *tracker,
10560 struct type *context_type)
10562 operation_up result = std::move (owner);
10564 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10566 LONGEST val = as_longest ();
10567 gdb_assert (result.get () == this);
10568 std::get<0> (m_storage) = context_type;
10569 std::get<1> (m_storage) = convert_char_literal (context_type, val);
10572 return result;
10575 value *
10576 ada_wrapped_operation::evaluate (struct type *expect_type,
10577 struct expression *exp,
10578 enum noside noside)
10580 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10581 if (noside == EVAL_NORMAL)
10582 result = unwrap_value (result);
10584 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10585 then we need to perform the conversion manually, because
10586 evaluate_subexp_standard doesn't do it. This conversion is
10587 necessary in Ada because the different kinds of float/fixed
10588 types in Ada have different representations.
10590 Similarly, we need to perform the conversion from OP_LONG
10591 ourselves. */
10592 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10593 result = ada_value_cast (expect_type, result);
10595 return result;
10598 void
10599 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10600 struct agent_expr *ax,
10601 struct axs_value *value,
10602 struct type *cast_type)
10604 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10606 struct type *type = value->type;
10607 if (ada_is_aligner_type (type))
10608 error (_("Aligner types cannot be handled in agent expressions"));
10609 else if (find_base_type (type) != nullptr)
10610 error (_("Dynamic types cannot be handled in agent expressions"));
10613 value *
10614 ada_string_operation::evaluate (struct type *expect_type,
10615 struct expression *exp,
10616 enum noside noside)
10618 struct type *char_type;
10619 if (expect_type != nullptr && ada_is_string_type (expect_type))
10620 char_type = ada_array_element_type (expect_type, 1);
10621 else
10622 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10624 const std::string &str = std::get<0> (m_storage);
10625 const char *encoding;
10626 switch (char_type->length ())
10628 case 1:
10630 /* Simply copy over the data -- this isn't perhaps strictly
10631 correct according to the encodings, but it is gdb's
10632 historical behavior. */
10633 struct type *stringtype
10634 = lookup_array_range_type (char_type, 1, str.length ());
10635 struct value *val = value::allocate (stringtype);
10636 memcpy (val->contents_raw ().data (), str.c_str (),
10637 str.length ());
10638 return val;
10641 case 2:
10642 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10643 encoding = "UTF-16BE";
10644 else
10645 encoding = "UTF-16LE";
10646 break;
10648 case 4:
10649 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10650 encoding = "UTF-32BE";
10651 else
10652 encoding = "UTF-32LE";
10653 break;
10655 default:
10656 error (_("unexpected character type size %s"),
10657 pulongest (char_type->length ()));
10660 auto_obstack converted;
10661 convert_between_encodings (host_charset (), encoding,
10662 (const gdb_byte *) str.c_str (),
10663 str.length (), 1,
10664 &converted, translit_none);
10666 struct type *stringtype
10667 = lookup_array_range_type (char_type, 1,
10668 obstack_object_size (&converted)
10669 / char_type->length ());
10670 struct value *val = value::allocate (stringtype);
10671 memcpy (val->contents_raw ().data (),
10672 obstack_base (&converted),
10673 obstack_object_size (&converted));
10674 return val;
10677 value *
10678 ada_concat_operation::evaluate (struct type *expect_type,
10679 struct expression *exp,
10680 enum noside noside)
10682 /* If one side is a literal, evaluate the other side first so that
10683 the expected type can be set properly. */
10684 const operation_up &lhs_expr = std::get<0> (m_storage);
10685 const operation_up &rhs_expr = std::get<1> (m_storage);
10687 value *lhs, *rhs;
10688 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10690 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10691 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10693 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10695 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10696 struct type *rhs_type = check_typedef (rhs->type ());
10697 struct type *elt_type = nullptr;
10698 if (rhs_type->code () == TYPE_CODE_ARRAY)
10699 elt_type = rhs_type->target_type ();
10700 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10702 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10704 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10705 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10707 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10709 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10710 struct type *lhs_type = check_typedef (lhs->type ());
10711 struct type *elt_type = nullptr;
10712 if (lhs_type->code () == TYPE_CODE_ARRAY)
10713 elt_type = lhs_type->target_type ();
10714 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10716 else
10717 return concat_operation::evaluate (expect_type, exp, noside);
10719 return value_concat (lhs, rhs);
10722 value *
10723 ada_qual_operation::evaluate (struct type *expect_type,
10724 struct expression *exp,
10725 enum noside noside)
10727 struct type *type = std::get<1> (m_storage);
10728 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10731 value *
10732 ada_ternop_range_operation::evaluate (struct type *expect_type,
10733 struct expression *exp,
10734 enum noside noside)
10736 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10737 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10738 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10739 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10742 value *
10743 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10744 struct expression *exp,
10745 enum noside noside)
10747 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10748 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10750 auto do_op = [this] (LONGEST x, LONGEST y)
10752 if (std::get<0> (m_storage) == BINOP_ADD)
10753 return x + y;
10754 return x - y;
10757 if (arg1->type ()->code () == TYPE_CODE_PTR)
10758 return (value_from_longest
10759 (arg1->type (),
10760 do_op (value_as_long (arg1), value_as_long (arg2))));
10761 if (arg2->type ()->code () == TYPE_CODE_PTR)
10762 return (value_from_longest
10763 (arg2->type (),
10764 do_op (value_as_long (arg1), value_as_long (arg2))));
10765 /* Preserve the original type for use by the range case below.
10766 We cannot cast the result to a reference type, so if ARG1 is
10767 a reference type, find its underlying type. */
10768 struct type *type = arg1->type ();
10769 while (type->code () == TYPE_CODE_REF)
10770 type = type->target_type ();
10771 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10772 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10773 /* We need to special-case the result with a range.
10774 This is done for the benefit of "ptype". gdb's Ada support
10775 historically used the LHS to set the result type here, so
10776 preserve this behavior. */
10777 if (type->code () == TYPE_CODE_RANGE)
10778 arg1 = value_cast (type, arg1);
10779 return arg1;
10782 value *
10783 ada_unop_atr_operation::evaluate (struct type *expect_type,
10784 struct expression *exp,
10785 enum noside noside)
10787 struct type *type_arg = nullptr;
10788 value *val = nullptr;
10790 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10792 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10793 EVAL_AVOID_SIDE_EFFECTS);
10794 type_arg = tem->type ();
10796 else
10797 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10799 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10800 val, type_arg, std::get<2> (m_storage));
10803 value *
10804 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10805 struct expression *exp,
10806 enum noside noside)
10808 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10809 return value::zero (expect_type, not_lval);
10811 const bound_minimal_symbol &b = std::get<0> (m_storage);
10812 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10814 val = ada_value_cast (expect_type, val);
10816 /* Follow the Ada language semantics that do not allow taking
10817 an address of the result of a cast (view conversion in Ada). */
10818 if (val->lval () == lval_memory)
10820 if (val->lazy ())
10821 val->fetch_lazy ();
10822 val->set_lval (not_lval);
10824 return val;
10827 value *
10828 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10829 struct expression *exp,
10830 enum noside noside)
10832 value *val = evaluate_var_value (noside,
10833 std::get<0> (m_storage).block,
10834 std::get<0> (m_storage).symbol);
10836 val = ada_value_cast (expect_type, val);
10838 /* Follow the Ada language semantics that do not allow taking
10839 an address of the result of a cast (view conversion in Ada). */
10840 if (val->lval () == lval_memory)
10842 if (val->lazy ())
10843 val->fetch_lazy ();
10844 val->set_lval (not_lval);
10846 return val;
10849 value *
10850 ada_var_value_operation::evaluate (struct type *expect_type,
10851 struct expression *exp,
10852 enum noside noside)
10854 symbol *sym = std::get<0> (m_storage).symbol;
10856 if (sym->domain () == UNDEF_DOMAIN)
10857 /* Only encountered when an unresolved symbol occurs in a
10858 context other than a function call, in which case, it is
10859 invalid. */
10860 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10861 sym->print_name ());
10863 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10865 struct type *type = static_unwrap_type (sym->type ());
10866 /* Check to see if this is a tagged type. We also need to handle
10867 the case where the type is a reference to a tagged type, but
10868 we have to be careful to exclude pointers to tagged types.
10869 The latter should be shown as usual (as a pointer), whereas
10870 a reference should mostly be transparent to the user. */
10871 if (ada_is_tagged_type (type, 0)
10872 || (type->code () == TYPE_CODE_REF
10873 && ada_is_tagged_type (type->target_type (), 0)))
10875 /* Tagged types are a little special in the fact that the real
10876 type is dynamic and can only be determined by inspecting the
10877 object's tag. This means that we need to get the object's
10878 value first (EVAL_NORMAL) and then extract the actual object
10879 type from its tag.
10881 Note that we cannot skip the final step where we extract
10882 the object type from its tag, because the EVAL_NORMAL phase
10883 results in dynamic components being resolved into fixed ones.
10884 This can cause problems when trying to print the type
10885 description of tagged types whose parent has a dynamic size:
10886 We use the type name of the "_parent" component in order
10887 to print the name of the ancestor type in the type description.
10888 If that component had a dynamic size, the resolution into
10889 a fixed type would result in the loss of that type name,
10890 thus preventing us from printing the name of the ancestor
10891 type in the type description. */
10892 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10894 if (type->code () != TYPE_CODE_REF)
10896 struct type *actual_type;
10898 actual_type = type_from_tag (ada_value_tag (arg1));
10899 if (actual_type == NULL)
10900 /* If, for some reason, we were unable to determine
10901 the actual type from the tag, then use the static
10902 approximation that we just computed as a fallback.
10903 This can happen if the debugging information is
10904 incomplete, for instance. */
10905 actual_type = type;
10906 return value::zero (actual_type, not_lval);
10908 else
10910 /* In the case of a ref, ada_coerce_ref takes care
10911 of determining the actual type. But the evaluation
10912 should return a ref as it should be valid to ask
10913 for its address; so rebuild a ref after coerce. */
10914 arg1 = ada_coerce_ref (arg1);
10915 return value_ref (arg1, TYPE_CODE_REF);
10919 /* Records and unions for which GNAT encodings have been
10920 generated need to be statically fixed as well.
10921 Otherwise, non-static fixing produces a type where
10922 all dynamic properties are removed, which prevents "ptype"
10923 from being able to completely describe the type.
10924 For instance, a case statement in a variant record would be
10925 replaced by the relevant components based on the actual
10926 value of the discriminants. */
10927 if ((type->code () == TYPE_CODE_STRUCT
10928 && dynamic_template_type (type) != NULL)
10929 || (type->code () == TYPE_CODE_UNION
10930 && ada_find_parallel_type (type, "___XVU") != NULL))
10931 return value::zero (to_static_fixed_type (type), not_lval);
10934 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10935 return ada_to_fixed_value (arg1);
10938 bool
10939 ada_var_value_operation::resolve (struct expression *exp,
10940 bool deprocedure_p,
10941 bool parse_completion,
10942 innermost_block_tracker *tracker,
10943 struct type *context_type)
10945 symbol *sym = std::get<0> (m_storage).symbol;
10946 if (sym->domain () == UNDEF_DOMAIN)
10948 block_symbol resolved
10949 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10950 context_type, parse_completion,
10951 deprocedure_p, tracker);
10952 std::get<0> (m_storage) = resolved;
10955 if (deprocedure_p
10956 && (std::get<0> (m_storage).symbol->type ()->code ()
10957 == TYPE_CODE_FUNC))
10958 return true;
10960 return false;
10963 void
10964 ada_var_value_operation::do_generate_ax (struct expression *exp,
10965 struct agent_expr *ax,
10966 struct axs_value *value,
10967 struct type *cast_type)
10969 symbol *sym = std::get<0> (m_storage).symbol;
10971 if (sym->domain () == UNDEF_DOMAIN)
10972 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10973 sym->print_name ());
10975 struct type *type = static_unwrap_type (sym->type ());
10976 if (ada_is_tagged_type (type, 0)
10977 || (type->code () == TYPE_CODE_REF
10978 && ada_is_tagged_type (type->target_type (), 0)))
10979 error (_("Tagged types cannot be handled in agent expressions"));
10981 if ((type->code () == TYPE_CODE_STRUCT
10982 && dynamic_template_type (type) != NULL)
10983 || (type->code () == TYPE_CODE_UNION
10984 && ada_find_parallel_type (type, "___XVU") != NULL))
10985 error (_("Dynamic types cannot be handled in agent expressions"));
10987 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10990 value *
10991 ada_unop_ind_operation::evaluate (struct type *expect_type,
10992 struct expression *exp,
10993 enum noside noside)
10995 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10997 struct type *type = ada_check_typedef (arg1->type ());
10998 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11000 if (ada_is_array_descriptor_type (type))
11001 /* GDB allows dereferencing GNAT array descriptors. */
11003 struct type *arrType = ada_type_of_array (arg1, 0);
11005 if (arrType == NULL)
11006 error (_("Attempt to dereference null array pointer."));
11007 return value_at_lazy (arrType, 0);
11009 else if (type->code () == TYPE_CODE_PTR
11010 || type->code () == TYPE_CODE_REF
11011 /* In C you can dereference an array to get the 1st elt. */
11012 || type->code () == TYPE_CODE_ARRAY)
11014 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11015 only be determined by inspecting the object's tag.
11016 This means that we need to evaluate completely the
11017 expression in order to get its type. */
11019 if ((type->code () == TYPE_CODE_REF
11020 || type->code () == TYPE_CODE_PTR)
11021 && ada_is_tagged_type (type->target_type (), 0))
11023 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11024 EVAL_NORMAL);
11025 type = ada_value_ind (arg1)->type ();
11027 else
11029 type = to_static_fixed_type
11030 (ada_aligned_type
11031 (ada_check_typedef (type->target_type ())));
11033 return value::zero (type, lval_memory);
11035 else if (type->code () == TYPE_CODE_INT)
11037 /* GDB allows dereferencing an int. */
11038 if (expect_type == NULL)
11039 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11040 lval_memory);
11041 else
11043 expect_type =
11044 to_static_fixed_type (ada_aligned_type (expect_type));
11045 return value::zero (expect_type, lval_memory);
11048 else
11049 error (_("Attempt to take contents of a non-pointer value."));
11051 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11052 type = ada_check_typedef (arg1->type ());
11054 if (type->code () == TYPE_CODE_INT)
11055 /* GDB allows dereferencing an int. If we were given
11056 the expect_type, then use that as the target type.
11057 Otherwise, assume that the target type is an int. */
11059 if (expect_type != NULL)
11060 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11061 arg1));
11062 else
11063 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11064 (CORE_ADDR) value_as_address (arg1));
11067 if (ada_is_array_descriptor_type (type))
11068 /* GDB allows dereferencing GNAT array descriptors. */
11069 return ada_coerce_to_simple_array (arg1);
11070 else
11071 return ada_value_ind (arg1);
11074 value *
11075 ada_structop_operation::evaluate (struct type *expect_type,
11076 struct expression *exp,
11077 enum noside noside)
11079 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11080 const char *str = std::get<1> (m_storage).c_str ();
11081 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11083 struct type *type;
11084 struct type *type1 = arg1->type ();
11086 if (ada_is_tagged_type (type1, 1))
11088 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11090 /* If the field is not found, check if it exists in the
11091 extension of this object's type. This means that we
11092 need to evaluate completely the expression. */
11094 if (type == NULL)
11096 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11097 EVAL_NORMAL);
11098 arg1 = ada_value_struct_elt (arg1, str, 0);
11099 arg1 = unwrap_value (arg1);
11100 type = ada_to_fixed_value (arg1)->type ();
11103 else
11104 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11106 return value::zero (ada_aligned_type (type), lval_memory);
11108 else
11110 arg1 = ada_value_struct_elt (arg1, str, 0);
11111 arg1 = unwrap_value (arg1);
11112 return ada_to_fixed_value (arg1);
11116 value *
11117 ada_funcall_operation::evaluate (struct type *expect_type,
11118 struct expression *exp,
11119 enum noside noside)
11121 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11122 int nargs = args_up.size ();
11123 std::vector<value *> argvec (nargs);
11124 operation_up &callee_op = std::get<0> (m_storage);
11126 ada_var_value_operation *avv
11127 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11128 if (avv != nullptr
11129 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11130 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11131 avv->get_symbol ()->print_name ());
11133 value *callee = callee_op->evaluate (nullptr, exp, noside);
11134 for (int i = 0; i < args_up.size (); ++i)
11135 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11137 if (ada_is_constrained_packed_array_type
11138 (desc_base_type (callee->type ())))
11139 callee = ada_coerce_to_simple_array (callee);
11140 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11141 && callee->type ()->field (0).bitsize () != 0)
11142 /* This is a packed array that has already been fixed, and
11143 therefore already coerced to a simple array. Nothing further
11144 to do. */
11146 else if (callee->type ()->code () == TYPE_CODE_REF)
11148 /* Make sure we dereference references so that all the code below
11149 feels like it's really handling the referenced value. Wrapping
11150 types (for alignment) may be there, so make sure we strip them as
11151 well. */
11152 callee = ada_to_fixed_value (coerce_ref (callee));
11154 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11155 && callee->lval () == lval_memory)
11156 callee = value_addr (callee);
11158 struct type *type = ada_check_typedef (callee->type ());
11160 /* Ada allows us to implicitly dereference arrays when subscripting
11161 them. So, if this is an array typedef (encoding use for array
11162 access types encoded as fat pointers), strip it now. */
11163 if (type->code () == TYPE_CODE_TYPEDEF)
11164 type = ada_typedef_target_type (type);
11166 if (type->code () == TYPE_CODE_PTR)
11168 switch (ada_check_typedef (type->target_type ())->code ())
11170 case TYPE_CODE_FUNC:
11171 type = ada_check_typedef (type->target_type ());
11172 break;
11173 case TYPE_CODE_ARRAY:
11174 break;
11175 case TYPE_CODE_STRUCT:
11176 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11177 callee = ada_value_ind (callee);
11178 type = ada_check_typedef (type->target_type ());
11179 break;
11180 default:
11181 error (_("cannot subscript or call something of type `%s'"),
11182 ada_type_name (callee->type ()));
11183 break;
11187 switch (type->code ())
11189 case TYPE_CODE_FUNC:
11190 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11192 if (type->target_type () == NULL)
11193 error_call_unknown_return_type (NULL);
11194 return value::allocate (type->target_type ());
11196 return call_function_by_hand (callee, expect_type, argvec);
11197 case TYPE_CODE_INTERNAL_FUNCTION:
11198 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11199 /* We don't know anything about what the internal
11200 function might return, but we have to return
11201 something. */
11202 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11203 not_lval);
11204 else
11205 return call_internal_function (exp->gdbarch, exp->language_defn,
11206 callee, nargs,
11207 argvec.data ());
11209 case TYPE_CODE_STRUCT:
11211 int arity;
11213 arity = ada_array_arity (type);
11214 type = ada_array_element_type (type, nargs);
11215 if (type == NULL)
11216 error (_("cannot subscript or call a record"));
11217 if (arity != nargs)
11218 error (_("wrong number of subscripts; expecting %d"), arity);
11219 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11220 return value::zero (ada_aligned_type (type), lval_memory);
11221 return
11222 unwrap_value (ada_value_subscript
11223 (callee, nargs, argvec.data ()));
11225 case TYPE_CODE_ARRAY:
11226 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11228 type = ada_array_element_type (type, nargs);
11229 if (type == NULL)
11230 error (_("element type of array unknown"));
11231 else
11232 return value::zero (ada_aligned_type (type), lval_memory);
11234 return
11235 unwrap_value (ada_value_subscript
11236 (ada_coerce_to_simple_array (callee),
11237 nargs, argvec.data ()));
11238 case TYPE_CODE_PTR: /* Pointer to array */
11239 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11241 type = to_fixed_array_type (type->target_type (), NULL, 1);
11242 type = ada_array_element_type (type, nargs);
11243 if (type == NULL)
11244 error (_("element type of array unknown"));
11245 else
11246 return value::zero (ada_aligned_type (type), lval_memory);
11248 return
11249 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11250 argvec.data ()));
11252 default:
11253 error (_("Attempt to index or call something other than an "
11254 "array or function"));
11258 bool
11259 ada_funcall_operation::resolve (struct expression *exp,
11260 bool deprocedure_p,
11261 bool parse_completion,
11262 innermost_block_tracker *tracker,
11263 struct type *context_type)
11265 operation_up &callee_op = std::get<0> (m_storage);
11267 ada_var_value_operation *avv
11268 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11269 if (avv == nullptr)
11270 return false;
11272 symbol *sym = avv->get_symbol ();
11273 if (sym->domain () != UNDEF_DOMAIN)
11274 return false;
11276 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11277 int nargs = args_up.size ();
11278 std::vector<value *> argvec (nargs);
11280 for (int i = 0; i < args_up.size (); ++i)
11281 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11283 const block *block = avv->get_block ();
11284 block_symbol resolved
11285 = ada_resolve_funcall (sym, block,
11286 context_type, parse_completion,
11287 nargs, argvec.data (),
11288 tracker);
11290 std::get<0> (m_storage)
11291 = make_operation<ada_var_value_operation> (resolved);
11292 return false;
11295 bool
11296 ada_ternop_slice_operation::resolve (struct expression *exp,
11297 bool deprocedure_p,
11298 bool parse_completion,
11299 innermost_block_tracker *tracker,
11300 struct type *context_type)
11302 /* Historically this check was done during resolution, so we
11303 continue that here. */
11304 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11305 EVAL_AVOID_SIDE_EFFECTS);
11306 if (ada_is_any_packed_array_type (v->type ()))
11307 error (_("cannot slice a packed array"));
11308 return false;
11315 /* Return non-zero iff TYPE represents a System.Address type. */
11318 ada_is_system_address_type (struct type *type)
11320 return (type->name () && strcmp (type->name (), "system__address") == 0);
11325 /* Range types */
11327 /* Scan STR beginning at position K for a discriminant name, and
11328 return the value of that discriminant field of DVAL in *PX. If
11329 PNEW_K is not null, put the position of the character beyond the
11330 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11331 not alter *PX and *PNEW_K if unsuccessful. */
11333 static int
11334 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11335 int *pnew_k)
11337 static std::string storage;
11338 const char *pstart, *pend, *bound;
11339 struct value *bound_val;
11341 if (dval == NULL || str == NULL || str[k] == '\0')
11342 return 0;
11344 pstart = str + k;
11345 pend = strstr (pstart, "__");
11346 if (pend == NULL)
11348 bound = pstart;
11349 k += strlen (bound);
11351 else
11353 int len = pend - pstart;
11355 /* Strip __ and beyond. */
11356 storage = std::string (pstart, len);
11357 bound = storage.c_str ();
11358 k = pend - str;
11361 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11362 if (bound_val == NULL)
11363 return 0;
11365 *px = value_as_long (bound_val);
11366 if (pnew_k != NULL)
11367 *pnew_k = k;
11368 return 1;
11371 /* Value of variable named NAME. Only exact matches are considered.
11372 If no such variable found, then if ERR_MSG is null, returns 0, and
11373 otherwise causes an error with message ERR_MSG. */
11375 static struct value *
11376 get_var_value (const char *name, const char *err_msg)
11378 std::string quoted_name = add_angle_brackets (name);
11380 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11382 std::vector<struct block_symbol> syms
11383 = ada_lookup_symbol_list_worker (lookup_name,
11384 get_selected_block (0),
11385 VAR_DOMAIN, 1);
11387 if (syms.size () != 1)
11389 if (err_msg == NULL)
11390 return 0;
11391 else
11392 error (("%s"), err_msg);
11395 return value_of_variable (syms[0].symbol, syms[0].block);
11398 /* Value of integer variable named NAME in the current environment.
11399 If no such variable is found, returns false. Otherwise, sets VALUE
11400 to the variable's value and returns true. */
11402 bool
11403 get_int_var_value (const char *name, LONGEST &value)
11405 struct value *var_val = get_var_value (name, 0);
11407 if (var_val == 0)
11408 return false;
11410 value = value_as_long (var_val);
11411 return true;
11415 /* Return a range type whose base type is that of the range type named
11416 NAME in the current environment, and whose bounds are calculated
11417 from NAME according to the GNAT range encoding conventions.
11418 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11419 corresponding range type from debug information; fall back to using it
11420 if symbol lookup fails. If a new type must be created, allocate it
11421 like ORIG_TYPE was. The bounds information, in general, is encoded
11422 in NAME, the base type given in the named range type. */
11424 static struct type *
11425 to_fixed_range_type (struct type *raw_type, struct value *dval)
11427 const char *name;
11428 struct type *base_type;
11429 const char *subtype_info;
11431 gdb_assert (raw_type != NULL);
11432 gdb_assert (raw_type->name () != NULL);
11434 if (raw_type->code () == TYPE_CODE_RANGE)
11435 base_type = raw_type->target_type ();
11436 else
11437 base_type = raw_type;
11439 name = raw_type->name ();
11440 subtype_info = strstr (name, "___XD");
11441 if (subtype_info == NULL)
11443 LONGEST L = ada_discrete_type_low_bound (raw_type);
11444 LONGEST U = ada_discrete_type_high_bound (raw_type);
11446 if (L < INT_MIN || U > INT_MAX)
11447 return raw_type;
11448 else
11450 type_allocator alloc (raw_type);
11451 return create_static_range_type (alloc, raw_type, L, U);
11454 else
11456 int prefix_len = subtype_info - name;
11457 LONGEST L, U;
11458 struct type *type;
11459 const char *bounds_str;
11460 int n;
11462 subtype_info += 5;
11463 bounds_str = strchr (subtype_info, '_');
11464 n = 1;
11466 if (*subtype_info == 'L')
11468 if (!ada_scan_number (bounds_str, n, &L, &n)
11469 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11470 return raw_type;
11471 if (bounds_str[n] == '_')
11472 n += 2;
11473 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11474 n += 1;
11475 subtype_info += 1;
11477 else
11479 std::string name_buf = std::string (name, prefix_len) + "___L";
11480 if (!get_int_var_value (name_buf.c_str (), L))
11482 lim_warning (_("Unknown lower bound, using 1."));
11483 L = 1;
11487 if (*subtype_info == 'U')
11489 if (!ada_scan_number (bounds_str, n, &U, &n)
11490 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11491 return raw_type;
11493 else
11495 std::string name_buf = std::string (name, prefix_len) + "___U";
11496 if (!get_int_var_value (name_buf.c_str (), U))
11498 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11499 U = L;
11503 type_allocator alloc (raw_type);
11504 type = create_static_range_type (alloc, base_type, L, U);
11505 /* create_static_range_type alters the resulting type's length
11506 to match the size of the base_type, which is not what we want.
11507 Set it back to the original range type's length. */
11508 type->set_length (raw_type->length ());
11509 type->set_name (name);
11510 return type;
11514 /* True iff NAME is the name of a range type. */
11517 ada_is_range_type_name (const char *name)
11519 return (name != NULL && strstr (name, "___XD"));
11523 /* Modular types */
11525 /* True iff TYPE is an Ada modular type. */
11528 ada_is_modular_type (struct type *type)
11530 struct type *subranged_type = get_base_type (type);
11532 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11533 && subranged_type->code () == TYPE_CODE_INT
11534 && subranged_type->is_unsigned ());
11537 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11539 ULONGEST
11540 ada_modulus (struct type *type)
11542 const dynamic_prop &high = type->bounds ()->high;
11544 if (high.is_constant ())
11545 return (ULONGEST) high.const_val () + 1;
11547 /* If TYPE is unresolved, the high bound might be a location list. Return
11548 0, for lack of a better value to return. */
11549 return 0;
11553 /* Ada exception catchpoint support:
11554 ---------------------------------
11556 We support 3 kinds of exception catchpoints:
11557 . catchpoints on Ada exceptions
11558 . catchpoints on unhandled Ada exceptions
11559 . catchpoints on failed assertions
11561 Exceptions raised during failed assertions, or unhandled exceptions
11562 could perfectly be caught with the general catchpoint on Ada exceptions.
11563 However, we can easily differentiate these two special cases, and having
11564 the option to distinguish these two cases from the rest can be useful
11565 to zero-in on certain situations.
11567 Exception catchpoints are a specialized form of breakpoint,
11568 since they rely on inserting breakpoints inside known routines
11569 of the GNAT runtime. The implementation therefore uses a standard
11570 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11571 of breakpoint_ops.
11573 Support in the runtime for exception catchpoints have been changed
11574 a few times already, and these changes affect the implementation
11575 of these catchpoints. In order to be able to support several
11576 variants of the runtime, we use a sniffer that will determine
11577 the runtime variant used by the program being debugged. */
11579 /* Ada's standard exceptions.
11581 The Ada 83 standard also defined Numeric_Error. But there so many
11582 situations where it was unclear from the Ada 83 Reference Manual
11583 (RM) whether Constraint_Error or Numeric_Error should be raised,
11584 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11585 Interpretation saying that anytime the RM says that Numeric_Error
11586 should be raised, the implementation may raise Constraint_Error.
11587 Ada 95 went one step further and pretty much removed Numeric_Error
11588 from the list of standard exceptions (it made it a renaming of
11589 Constraint_Error, to help preserve compatibility when compiling
11590 an Ada83 compiler). As such, we do not include Numeric_Error from
11591 this list of standard exceptions. */
11593 static const char * const standard_exc[] = {
11594 "constraint_error",
11595 "program_error",
11596 "storage_error",
11597 "tasking_error"
11600 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11602 /* A structure that describes how to support exception catchpoints
11603 for a given executable. */
11605 struct exception_support_info
11607 /* The name of the symbol to break on in order to insert
11608 a catchpoint on exceptions. */
11609 const char *catch_exception_sym;
11611 /* The name of the symbol to break on in order to insert
11612 a catchpoint on unhandled exceptions. */
11613 const char *catch_exception_unhandled_sym;
11615 /* The name of the symbol to break on in order to insert
11616 a catchpoint on failed assertions. */
11617 const char *catch_assert_sym;
11619 /* The name of the symbol to break on in order to insert
11620 a catchpoint on exception handling. */
11621 const char *catch_handlers_sym;
11623 /* Assuming that the inferior just triggered an unhandled exception
11624 catchpoint, this function is responsible for returning the address
11625 in inferior memory where the name of that exception is stored.
11626 Return zero if the address could not be computed. */
11627 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11630 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11631 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11633 /* The following exception support info structure describes how to
11634 implement exception catchpoints with the latest version of the
11635 Ada runtime (as of 2019-08-??). */
11637 static const struct exception_support_info default_exception_support_info =
11639 "__gnat_debug_raise_exception", /* catch_exception_sym */
11640 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11641 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11642 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11643 ada_unhandled_exception_name_addr
11646 /* The following exception support info structure describes how to
11647 implement exception catchpoints with an earlier version of the
11648 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11650 static const struct exception_support_info exception_support_info_v0 =
11652 "__gnat_debug_raise_exception", /* catch_exception_sym */
11653 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11654 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11655 "__gnat_begin_handler", /* catch_handlers_sym */
11656 ada_unhandled_exception_name_addr
11659 /* The following exception support info structure describes how to
11660 implement exception catchpoints with a slightly older version
11661 of the Ada runtime. */
11663 static const struct exception_support_info exception_support_info_fallback =
11665 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11666 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11667 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11668 "__gnat_begin_handler", /* catch_handlers_sym */
11669 ada_unhandled_exception_name_addr_from_raise
11672 /* Return nonzero if we can detect the exception support routines
11673 described in EINFO.
11675 This function errors out if an abnormal situation is detected
11676 (for instance, if we find the exception support routines, but
11677 that support is found to be incomplete). */
11679 static int
11680 ada_has_this_exception_support (const struct exception_support_info *einfo)
11682 struct symbol *sym;
11684 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11685 that should be compiled with debugging information. As a result, we
11686 expect to find that symbol in the symtabs. */
11688 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11689 if (sym == NULL)
11691 /* Perhaps we did not find our symbol because the Ada runtime was
11692 compiled without debugging info, or simply stripped of it.
11693 It happens on some GNU/Linux distributions for instance, where
11694 users have to install a separate debug package in order to get
11695 the runtime's debugging info. In that situation, let the user
11696 know why we cannot insert an Ada exception catchpoint.
11698 Note: Just for the purpose of inserting our Ada exception
11699 catchpoint, we could rely purely on the associated minimal symbol.
11700 But we would be operating in degraded mode anyway, since we are
11701 still lacking the debugging info needed later on to extract
11702 the name of the exception being raised (this name is printed in
11703 the catchpoint message, and is also used when trying to catch
11704 a specific exception). We do not handle this case for now. */
11705 struct bound_minimal_symbol msym
11706 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11708 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11709 error (_("Your Ada runtime appears to be missing some debugging "
11710 "information.\nCannot insert Ada exception catchpoint "
11711 "in this configuration."));
11713 return 0;
11716 /* Make sure that the symbol we found corresponds to a function. */
11718 if (sym->aclass () != LOC_BLOCK)
11719 error (_("Symbol \"%s\" is not a function (class = %d)"),
11720 sym->linkage_name (), sym->aclass ());
11722 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11723 if (sym == NULL)
11725 struct bound_minimal_symbol msym
11726 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11728 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11729 error (_("Your Ada runtime appears to be missing some debugging "
11730 "information.\nCannot insert Ada exception catchpoint "
11731 "in this configuration."));
11733 return 0;
11736 /* Make sure that the symbol we found corresponds to a function. */
11738 if (sym->aclass () != LOC_BLOCK)
11739 error (_("Symbol \"%s\" is not a function (class = %d)"),
11740 sym->linkage_name (), sym->aclass ());
11742 return 1;
11745 /* Inspect the Ada runtime and determine which exception info structure
11746 should be used to provide support for exception catchpoints.
11748 This function will always set the per-inferior exception_info,
11749 or raise an error. */
11751 static void
11752 ada_exception_support_info_sniffer (void)
11754 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11756 /* If the exception info is already known, then no need to recompute it. */
11757 if (data->exception_info != NULL)
11758 return;
11760 /* Check the latest (default) exception support info. */
11761 if (ada_has_this_exception_support (&default_exception_support_info))
11763 data->exception_info = &default_exception_support_info;
11764 return;
11767 /* Try the v0 exception suport info. */
11768 if (ada_has_this_exception_support (&exception_support_info_v0))
11770 data->exception_info = &exception_support_info_v0;
11771 return;
11774 /* Try our fallback exception suport info. */
11775 if (ada_has_this_exception_support (&exception_support_info_fallback))
11777 data->exception_info = &exception_support_info_fallback;
11778 return;
11781 throw_error (NOT_FOUND_ERROR,
11782 _("Could not find Ada runtime exception support"));
11785 /* True iff FRAME is very likely to be that of a function that is
11786 part of the runtime system. This is all very heuristic, but is
11787 intended to be used as advice as to what frames are uninteresting
11788 to most users. */
11790 static int
11791 is_known_support_routine (frame_info_ptr frame)
11793 enum language func_lang;
11794 int i;
11795 const char *fullname;
11797 /* If this code does not have any debugging information (no symtab),
11798 This cannot be any user code. */
11800 symtab_and_line sal = find_frame_sal (frame);
11801 if (sal.symtab == NULL)
11802 return 1;
11804 /* If there is a symtab, but the associated source file cannot be
11805 located, then assume this is not user code: Selecting a frame
11806 for which we cannot display the code would not be very helpful
11807 for the user. This should also take care of case such as VxWorks
11808 where the kernel has some debugging info provided for a few units. */
11810 fullname = symtab_to_fullname (sal.symtab);
11811 if (access (fullname, R_OK) != 0)
11812 return 1;
11814 /* Check the unit filename against the Ada runtime file naming.
11815 We also check the name of the objfile against the name of some
11816 known system libraries that sometimes come with debugging info
11817 too. */
11819 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11821 re_comp (known_runtime_file_name_patterns[i]);
11822 if (re_exec (lbasename (sal.symtab->filename)))
11823 return 1;
11824 if (sal.symtab->compunit ()->objfile () != NULL
11825 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11826 return 1;
11829 /* Check whether the function is a GNAT-generated entity. */
11831 gdb::unique_xmalloc_ptr<char> func_name
11832 = find_frame_funname (frame, &func_lang, NULL);
11833 if (func_name == NULL)
11834 return 1;
11836 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11838 re_comp (known_auxiliary_function_name_patterns[i]);
11839 if (re_exec (func_name.get ()))
11840 return 1;
11843 return 0;
11846 /* Find the first frame that contains debugging information and that is not
11847 part of the Ada run-time, starting from FI and moving upward. */
11849 void
11850 ada_find_printable_frame (frame_info_ptr fi)
11852 for (; fi != NULL; fi = get_prev_frame (fi))
11854 if (!is_known_support_routine (fi))
11856 select_frame (fi);
11857 break;
11863 /* Assuming that the inferior just triggered an unhandled exception
11864 catchpoint, return the address in inferior memory where the name
11865 of the exception is stored.
11867 Return zero if the address could not be computed. */
11869 static CORE_ADDR
11870 ada_unhandled_exception_name_addr (void)
11872 return parse_and_eval_address ("e.full_name");
11875 /* Same as ada_unhandled_exception_name_addr, except that this function
11876 should be used when the inferior uses an older version of the runtime,
11877 where the exception name needs to be extracted from a specific frame
11878 several frames up in the callstack. */
11880 static CORE_ADDR
11881 ada_unhandled_exception_name_addr_from_raise (void)
11883 int frame_level;
11884 frame_info_ptr fi;
11885 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11887 /* To determine the name of this exception, we need to select
11888 the frame corresponding to RAISE_SYM_NAME. This frame is
11889 at least 3 levels up, so we simply skip the first 3 frames
11890 without checking the name of their associated function. */
11891 fi = get_current_frame ();
11892 for (frame_level = 0; frame_level < 3; frame_level += 1)
11893 if (fi != NULL)
11894 fi = get_prev_frame (fi);
11896 while (fi != NULL)
11898 enum language func_lang;
11900 gdb::unique_xmalloc_ptr<char> func_name
11901 = find_frame_funname (fi, &func_lang, NULL);
11902 if (func_name != NULL)
11904 if (strcmp (func_name.get (),
11905 data->exception_info->catch_exception_sym) == 0)
11906 break; /* We found the frame we were looking for... */
11908 fi = get_prev_frame (fi);
11911 if (fi == NULL)
11912 return 0;
11914 select_frame (fi);
11915 return parse_and_eval_address ("id.full_name");
11918 /* Assuming the inferior just triggered an Ada exception catchpoint
11919 (of any type), return the address in inferior memory where the name
11920 of the exception is stored, if applicable.
11922 Assumes the selected frame is the current frame.
11924 Return zero if the address could not be computed, or if not relevant. */
11926 static CORE_ADDR
11927 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11929 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11931 switch (ex)
11933 case ada_catch_exception:
11934 return (parse_and_eval_address ("e.full_name"));
11935 break;
11937 case ada_catch_exception_unhandled:
11938 return data->exception_info->unhandled_exception_name_addr ();
11939 break;
11941 case ada_catch_handlers:
11942 return 0; /* The runtimes does not provide access to the exception
11943 name. */
11944 break;
11946 case ada_catch_assert:
11947 return 0; /* Exception name is not relevant in this case. */
11948 break;
11950 default:
11951 internal_error (_("unexpected catchpoint type"));
11952 break;
11955 return 0; /* Should never be reached. */
11958 /* Assuming the inferior is stopped at an exception catchpoint,
11959 return the message which was associated to the exception, if
11960 available. Return NULL if the message could not be retrieved.
11962 Note: The exception message can be associated to an exception
11963 either through the use of the Raise_Exception function, or
11964 more simply (Ada 2005 and later), via:
11966 raise Exception_Name with "exception message";
11970 static gdb::unique_xmalloc_ptr<char>
11971 ada_exception_message_1 (void)
11973 struct value *e_msg_val;
11974 int e_msg_len;
11976 /* For runtimes that support this feature, the exception message
11977 is passed as an unbounded string argument called "message". */
11978 e_msg_val = parse_and_eval ("message");
11979 if (e_msg_val == NULL)
11980 return NULL; /* Exception message not supported. */
11982 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11983 gdb_assert (e_msg_val != NULL);
11984 e_msg_len = e_msg_val->type ()->length ();
11986 /* If the message string is empty, then treat it as if there was
11987 no exception message. */
11988 if (e_msg_len <= 0)
11989 return NULL;
11991 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11992 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
11993 e_msg_len);
11994 e_msg.get ()[e_msg_len] = '\0';
11996 return e_msg;
11999 /* Same as ada_exception_message_1, except that all exceptions are
12000 contained here (returning NULL instead). */
12002 static gdb::unique_xmalloc_ptr<char>
12003 ada_exception_message (void)
12005 gdb::unique_xmalloc_ptr<char> e_msg;
12009 e_msg = ada_exception_message_1 ();
12011 catch (const gdb_exception_error &e)
12013 e_msg.reset (nullptr);
12016 return e_msg;
12019 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12020 any error that ada_exception_name_addr_1 might cause to be thrown.
12021 When an error is intercepted, a warning with the error message is printed,
12022 and zero is returned. */
12024 static CORE_ADDR
12025 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12027 CORE_ADDR result = 0;
12031 result = ada_exception_name_addr_1 (ex);
12034 catch (const gdb_exception_error &e)
12036 warning (_("failed to get exception name: %s"), e.what ());
12037 return 0;
12040 return result;
12043 static std::string ada_exception_catchpoint_cond_string
12044 (const char *excep_string,
12045 enum ada_exception_catchpoint_kind ex);
12047 /* Ada catchpoints.
12049 In the case of catchpoints on Ada exceptions, the catchpoint will
12050 stop the target on every exception the program throws. When a user
12051 specifies the name of a specific exception, we translate this
12052 request into a condition expression (in text form), and then parse
12053 it into an expression stored in each of the catchpoint's locations.
12054 We then use this condition to check whether the exception that was
12055 raised is the one the user is interested in. If not, then the
12056 target is resumed again. We store the name of the requested
12057 exception, in order to be able to re-set the condition expression
12058 when symbols change. */
12060 /* An instance of this type is used to represent an Ada catchpoint. */
12062 struct ada_catchpoint : public code_breakpoint
12064 ada_catchpoint (struct gdbarch *gdbarch_,
12065 enum ada_exception_catchpoint_kind kind,
12066 const char *cond_string,
12067 bool tempflag,
12068 bool enabled,
12069 bool from_tty,
12070 std::string &&excep_string_)
12071 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
12072 m_excep_string (std::move (excep_string_)),
12073 m_kind (kind)
12075 /* Unlike most code_breakpoint types, Ada catchpoints are
12076 pspace-specific. */
12077 pspace = current_program_space;
12078 enable_state = enabled ? bp_enabled : bp_disabled;
12079 language = language_ada;
12081 re_set ();
12084 struct bp_location *allocate_location () override;
12085 void re_set () override;
12086 void check_status (struct bpstat *bs) override;
12087 enum print_stop_action print_it (const bpstat *bs) const override;
12088 bool print_one (const bp_location **) const override;
12089 void print_mention () const override;
12090 void print_recreate (struct ui_file *fp) const override;
12092 private:
12094 /* A helper function for check_status. Returns true if we should
12095 stop for this breakpoint hit. If the user specified a specific
12096 exception, we only want to cause a stop if the program thrown
12097 that exception. */
12098 bool should_stop_exception (const struct bp_location *bl) const;
12100 /* The name of the specific exception the user specified. */
12101 std::string m_excep_string;
12103 /* What kind of catchpoint this is. */
12104 enum ada_exception_catchpoint_kind m_kind;
12107 /* An instance of this type is used to represent an Ada catchpoint
12108 breakpoint location. */
12110 class ada_catchpoint_location : public bp_location
12112 public:
12113 explicit ada_catchpoint_location (ada_catchpoint *owner)
12114 : bp_location (owner, bp_loc_software_breakpoint)
12117 /* The condition that checks whether the exception that was raised
12118 is the specific exception the user specified on catchpoint
12119 creation. */
12120 expression_up excep_cond_expr;
12123 static struct symtab_and_line ada_exception_sal
12124 (enum ada_exception_catchpoint_kind ex);
12126 /* Implement the RE_SET method in the structure for all exception
12127 catchpoint kinds. */
12129 void
12130 ada_catchpoint::re_set ()
12132 std::vector<symtab_and_line> sals;
12135 struct symtab_and_line sal = ada_exception_sal (m_kind);
12136 sals.push_back (sal);
12138 catch (const gdb_exception_error &ex)
12140 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12141 if (ex.error != NOT_FOUND_ERROR)
12142 throw;
12145 update_breakpoint_locations (this, pspace, sals, {});
12147 /* Reparse the exception conditional expressions. One for each
12148 location. */
12150 /* Nothing to do if there's no specific exception to catch. */
12151 if (m_excep_string.empty ())
12152 return;
12154 /* Same if there are no locations... */
12155 if (!has_locations ())
12156 return;
12158 /* Compute the condition expression in text form, from the specific
12159 exception we want to catch. */
12160 std::string cond_string
12161 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
12163 /* Iterate over all the catchpoint's locations, and parse an
12164 expression for each. */
12165 for (bp_location &bl : locations ())
12167 ada_catchpoint_location &ada_loc
12168 = static_cast<ada_catchpoint_location &> (bl);
12169 expression_up exp;
12171 if (!bl.shlib_disabled)
12173 const char *s;
12175 s = cond_string.c_str ();
12178 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
12180 catch (const gdb_exception_error &e)
12182 warning (_("failed to reevaluate internal exception condition "
12183 "for catchpoint %d: %s"),
12184 number, e.what ());
12188 ada_loc.excep_cond_expr = std::move (exp);
12192 /* Implement the ALLOCATE_LOCATION method in the structure for all
12193 exception catchpoint kinds. */
12195 struct bp_location *
12196 ada_catchpoint::allocate_location ()
12198 return new ada_catchpoint_location (this);
12201 /* See declaration. */
12203 bool
12204 ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
12206 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
12207 const struct ada_catchpoint_location *ada_loc
12208 = (const struct ada_catchpoint_location *) bl;
12209 bool stop;
12211 struct internalvar *var = lookup_internalvar ("_ada_exception");
12212 if (c->m_kind == ada_catch_assert)
12213 clear_internalvar (var);
12214 else
12218 const char *expr;
12220 if (c->m_kind == ada_catch_handlers)
12221 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12222 ".all.occurrence.id");
12223 else
12224 expr = "e";
12226 struct value *exc = parse_and_eval (expr);
12227 set_internalvar (var, exc);
12229 catch (const gdb_exception_error &ex)
12231 clear_internalvar (var);
12235 /* With no specific exception, should always stop. */
12236 if (c->m_excep_string.empty ())
12237 return true;
12239 if (ada_loc->excep_cond_expr == NULL)
12241 /* We will have a NULL expression if back when we were creating
12242 the expressions, this location's had failed to parse. */
12243 return true;
12246 stop = true;
12249 scoped_value_mark mark;
12250 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
12252 catch (const gdb_exception_error &ex)
12254 exception_fprintf (gdb_stderr, ex,
12255 _("Error in testing exception condition:\n"));
12258 return stop;
12261 /* Implement the CHECK_STATUS method in the structure for all
12262 exception catchpoint kinds. */
12264 void
12265 ada_catchpoint::check_status (bpstat *bs)
12267 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12270 /* Implement the PRINT_IT method in the structure for all exception
12271 catchpoint kinds. */
12273 enum print_stop_action
12274 ada_catchpoint::print_it (const bpstat *bs) const
12276 struct ui_out *uiout = current_uiout;
12278 annotate_catchpoint (number);
12280 if (uiout->is_mi_like_p ())
12282 uiout->field_string ("reason",
12283 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12284 uiout->field_string ("disp", bpdisp_text (disposition));
12287 uiout->text (disposition == disp_del
12288 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12289 print_num_locno (bs, uiout);
12290 uiout->text (", ");
12292 /* ada_exception_name_addr relies on the selected frame being the
12293 current frame. Need to do this here because this function may be
12294 called more than once when printing a stop, and below, we'll
12295 select the first frame past the Ada run-time (see
12296 ada_find_printable_frame). */
12297 select_frame (get_current_frame ());
12299 switch (m_kind)
12301 case ada_catch_exception:
12302 case ada_catch_exception_unhandled:
12303 case ada_catch_handlers:
12305 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12306 char exception_name[256];
12308 if (addr != 0)
12310 read_memory (addr, (gdb_byte *) exception_name,
12311 sizeof (exception_name) - 1);
12312 exception_name [sizeof (exception_name) - 1] = '\0';
12314 else
12316 /* For some reason, we were unable to read the exception
12317 name. This could happen if the Runtime was compiled
12318 without debugging info, for instance. In that case,
12319 just replace the exception name by the generic string
12320 "exception" - it will read as "an exception" in the
12321 notification we are about to print. */
12322 memcpy (exception_name, "exception", sizeof ("exception"));
12324 /* In the case of unhandled exception breakpoints, we print
12325 the exception name as "unhandled EXCEPTION_NAME", to make
12326 it clearer to the user which kind of catchpoint just got
12327 hit. We used ui_out_text to make sure that this extra
12328 info does not pollute the exception name in the MI case. */
12329 if (m_kind == ada_catch_exception_unhandled)
12330 uiout->text ("unhandled ");
12331 uiout->field_string ("exception-name", exception_name);
12333 break;
12334 case ada_catch_assert:
12335 /* In this case, the name of the exception is not really
12336 important. Just print "failed assertion" to make it clearer
12337 that his program just hit an assertion-failure catchpoint.
12338 We used ui_out_text because this info does not belong in
12339 the MI output. */
12340 uiout->text ("failed assertion");
12341 break;
12344 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12345 if (exception_message != NULL)
12347 uiout->text (" (");
12348 uiout->field_string ("exception-message", exception_message.get ());
12349 uiout->text (")");
12352 uiout->text (" at ");
12353 ada_find_printable_frame (get_current_frame ());
12355 return PRINT_SRC_AND_LOC;
12358 /* Implement the PRINT_ONE method in the structure for all exception
12359 catchpoint kinds. */
12361 bool
12362 ada_catchpoint::print_one (const bp_location **last_loc) const
12364 struct ui_out *uiout = current_uiout;
12365 struct value_print_options opts;
12367 get_user_print_options (&opts);
12369 if (opts.addressprint)
12370 uiout->field_skip ("addr");
12372 annotate_field (5);
12373 switch (m_kind)
12375 case ada_catch_exception:
12376 if (!m_excep_string.empty ())
12378 std::string msg = string_printf (_("`%s' Ada exception"),
12379 m_excep_string.c_str ());
12381 uiout->field_string ("what", msg);
12383 else
12384 uiout->field_string ("what", "all Ada exceptions");
12386 break;
12388 case ada_catch_exception_unhandled:
12389 uiout->field_string ("what", "unhandled Ada exceptions");
12390 break;
12392 case ada_catch_handlers:
12393 if (!m_excep_string.empty ())
12395 uiout->field_fmt ("what",
12396 _("`%s' Ada exception handlers"),
12397 m_excep_string.c_str ());
12399 else
12400 uiout->field_string ("what", "all Ada exceptions handlers");
12401 break;
12403 case ada_catch_assert:
12404 uiout->field_string ("what", "failed Ada assertions");
12405 break;
12407 default:
12408 internal_error (_("unexpected catchpoint type"));
12409 break;
12412 return true;
12415 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12416 for all exception catchpoint kinds. */
12418 void
12419 ada_catchpoint::print_mention () const
12421 struct ui_out *uiout = current_uiout;
12423 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12424 : _("Catchpoint "));
12425 uiout->field_signed ("bkptno", number);
12426 uiout->text (": ");
12428 switch (m_kind)
12430 case ada_catch_exception:
12431 if (!m_excep_string.empty ())
12433 std::string info = string_printf (_("`%s' Ada exception"),
12434 m_excep_string.c_str ());
12435 uiout->text (info);
12437 else
12438 uiout->text (_("all Ada exceptions"));
12439 break;
12441 case ada_catch_exception_unhandled:
12442 uiout->text (_("unhandled Ada exceptions"));
12443 break;
12445 case ada_catch_handlers:
12446 if (!m_excep_string.empty ())
12448 std::string info
12449 = string_printf (_("`%s' Ada exception handlers"),
12450 m_excep_string.c_str ());
12451 uiout->text (info);
12453 else
12454 uiout->text (_("all Ada exceptions handlers"));
12455 break;
12457 case ada_catch_assert:
12458 uiout->text (_("failed Ada assertions"));
12459 break;
12461 default:
12462 internal_error (_("unexpected catchpoint type"));
12463 break;
12467 /* Implement the PRINT_RECREATE method in the structure for all
12468 exception catchpoint kinds. */
12470 void
12471 ada_catchpoint::print_recreate (struct ui_file *fp) const
12473 switch (m_kind)
12475 case ada_catch_exception:
12476 gdb_printf (fp, "catch exception");
12477 if (!m_excep_string.empty ())
12478 gdb_printf (fp, " %s", m_excep_string.c_str ());
12479 break;
12481 case ada_catch_exception_unhandled:
12482 gdb_printf (fp, "catch exception unhandled");
12483 break;
12485 case ada_catch_handlers:
12486 gdb_printf (fp, "catch handlers");
12487 break;
12489 case ada_catch_assert:
12490 gdb_printf (fp, "catch assert");
12491 break;
12493 default:
12494 internal_error (_("unexpected catchpoint type"));
12496 print_recreate_thread (fp);
12499 /* See ada-lang.h. */
12501 bool
12502 is_ada_exception_catchpoint (breakpoint *bp)
12504 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12507 /* Split the arguments specified in a "catch exception" command.
12508 Set EX to the appropriate catchpoint type.
12509 Set EXCEP_STRING to the name of the specific exception if
12510 specified by the user.
12511 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12512 "catch handlers" command. False otherwise.
12513 If a condition is found at the end of the arguments, the condition
12514 expression is stored in COND_STRING (memory must be deallocated
12515 after use). Otherwise COND_STRING is set to NULL. */
12517 static void
12518 catch_ada_exception_command_split (const char *args,
12519 bool is_catch_handlers_cmd,
12520 enum ada_exception_catchpoint_kind *ex,
12521 std::string *excep_string,
12522 std::string *cond_string)
12524 std::string exception_name;
12526 exception_name = extract_arg (&args);
12527 if (exception_name == "if")
12529 /* This is not an exception name; this is the start of a condition
12530 expression for a catchpoint on all exceptions. So, "un-get"
12531 this token, and set exception_name to NULL. */
12532 exception_name.clear ();
12533 args -= 2;
12536 /* Check to see if we have a condition. */
12538 args = skip_spaces (args);
12539 if (startswith (args, "if")
12540 && (isspace (args[2]) || args[2] == '\0'))
12542 args += 2;
12543 args = skip_spaces (args);
12545 if (args[0] == '\0')
12546 error (_("Condition missing after `if' keyword"));
12547 *cond_string = args;
12549 args += strlen (args);
12552 /* Check that we do not have any more arguments. Anything else
12553 is unexpected. */
12555 if (args[0] != '\0')
12556 error (_("Junk at end of expression"));
12558 if (is_catch_handlers_cmd)
12560 /* Catch handling of exceptions. */
12561 *ex = ada_catch_handlers;
12562 *excep_string = exception_name;
12564 else if (exception_name.empty ())
12566 /* Catch all exceptions. */
12567 *ex = ada_catch_exception;
12568 excep_string->clear ();
12570 else if (exception_name == "unhandled")
12572 /* Catch unhandled exceptions. */
12573 *ex = ada_catch_exception_unhandled;
12574 excep_string->clear ();
12576 else
12578 /* Catch a specific exception. */
12579 *ex = ada_catch_exception;
12580 *excep_string = exception_name;
12584 /* Return the name of the symbol on which we should break in order to
12585 implement a catchpoint of the EX kind. */
12587 static const char *
12588 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12590 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12592 gdb_assert (data->exception_info != NULL);
12594 switch (ex)
12596 case ada_catch_exception:
12597 return (data->exception_info->catch_exception_sym);
12598 break;
12599 case ada_catch_exception_unhandled:
12600 return (data->exception_info->catch_exception_unhandled_sym);
12601 break;
12602 case ada_catch_assert:
12603 return (data->exception_info->catch_assert_sym);
12604 break;
12605 case ada_catch_handlers:
12606 return (data->exception_info->catch_handlers_sym);
12607 break;
12608 default:
12609 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12613 /* Return the condition that will be used to match the current exception
12614 being raised with the exception that the user wants to catch. This
12615 assumes that this condition is used when the inferior just triggered
12616 an exception catchpoint.
12617 EX: the type of catchpoints used for catching Ada exceptions. */
12619 static std::string
12620 ada_exception_catchpoint_cond_string (const char *excep_string,
12621 enum ada_exception_catchpoint_kind ex)
12623 bool is_standard_exc = false;
12624 std::string result;
12626 if (ex == ada_catch_handlers)
12628 /* For exception handlers catchpoints, the condition string does
12629 not use the same parameter as for the other exceptions. */
12630 result = ("long_integer (GNAT_GCC_exception_Access"
12631 "(gcc_exception).all.occurrence.id)");
12633 else
12634 result = "long_integer (e)";
12636 /* The standard exceptions are a special case. They are defined in
12637 runtime units that have been compiled without debugging info; if
12638 EXCEP_STRING is the not-fully-qualified name of a standard
12639 exception (e.g. "constraint_error") then, during the evaluation
12640 of the condition expression, the symbol lookup on this name would
12641 *not* return this standard exception. The catchpoint condition
12642 may then be set only on user-defined exceptions which have the
12643 same not-fully-qualified name (e.g. my_package.constraint_error).
12645 To avoid this unexcepted behavior, these standard exceptions are
12646 systematically prefixed by "standard". This means that "catch
12647 exception constraint_error" is rewritten into "catch exception
12648 standard.constraint_error".
12650 If an exception named constraint_error is defined in another package of
12651 the inferior program, then the only way to specify this exception as a
12652 breakpoint condition is to use its fully-qualified named:
12653 e.g. my_package.constraint_error. */
12655 for (const char *name : standard_exc)
12657 if (strcmp (name, excep_string) == 0)
12659 is_standard_exc = true;
12660 break;
12664 result += " = ";
12666 if (is_standard_exc)
12667 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12668 else
12669 string_appendf (result, "long_integer (&%s)", excep_string);
12671 return result;
12674 /* Return the symtab_and_line that should be used to insert an
12675 exception catchpoint of the TYPE kind. */
12677 static struct symtab_and_line
12678 ada_exception_sal (enum ada_exception_catchpoint_kind ex)
12680 const char *sym_name;
12681 struct symbol *sym;
12683 /* First, find out which exception support info to use. */
12684 ada_exception_support_info_sniffer ();
12686 /* Then lookup the function on which we will break in order to catch
12687 the Ada exceptions requested by the user. */
12688 sym_name = ada_exception_sym_name (ex);
12689 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12691 if (sym == NULL)
12692 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12693 sym_name);
12695 if (sym->aclass () != LOC_BLOCK)
12696 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12698 return find_function_start_sal (sym, 1);
12701 /* Create an Ada exception catchpoint.
12703 EX_KIND is the kind of exception catchpoint to be created.
12705 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12706 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12707 of the exception to which this catchpoint applies.
12709 COND_STRING, if not empty, is the catchpoint condition.
12711 TEMPFLAG, if nonzero, means that the underlying breakpoint
12712 should be temporary.
12714 FROM_TTY is the usual argument passed to all commands implementations. */
12716 void
12717 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12718 enum ada_exception_catchpoint_kind ex_kind,
12719 std::string &&excep_string,
12720 const std::string &cond_string,
12721 int tempflag,
12722 int enabled,
12723 int from_tty)
12725 std::unique_ptr<ada_catchpoint> c
12726 (new ada_catchpoint (gdbarch, ex_kind,
12727 cond_string.empty () ? nullptr : cond_string.c_str (),
12728 tempflag, enabled, from_tty,
12729 std::move (excep_string)));
12730 install_breakpoint (0, std::move (c), 1);
12733 /* Implement the "catch exception" command. */
12735 static void
12736 catch_ada_exception_command (const char *arg_entry, int from_tty,
12737 struct cmd_list_element *command)
12739 const char *arg = arg_entry;
12740 struct gdbarch *gdbarch = get_current_arch ();
12741 int tempflag;
12742 enum ada_exception_catchpoint_kind ex_kind;
12743 std::string excep_string;
12744 std::string cond_string;
12746 tempflag = command->context () == CATCH_TEMPORARY;
12748 if (!arg)
12749 arg = "";
12750 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12751 &cond_string);
12752 create_ada_exception_catchpoint (gdbarch, ex_kind,
12753 std::move (excep_string), cond_string,
12754 tempflag, 1 /* enabled */,
12755 from_tty);
12758 /* Implement the "catch handlers" command. */
12760 static void
12761 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12762 struct cmd_list_element *command)
12764 const char *arg = arg_entry;
12765 struct gdbarch *gdbarch = get_current_arch ();
12766 int tempflag;
12767 enum ada_exception_catchpoint_kind ex_kind;
12768 std::string excep_string;
12769 std::string cond_string;
12771 tempflag = command->context () == CATCH_TEMPORARY;
12773 if (!arg)
12774 arg = "";
12775 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12776 &cond_string);
12777 create_ada_exception_catchpoint (gdbarch, ex_kind,
12778 std::move (excep_string), cond_string,
12779 tempflag, 1 /* enabled */,
12780 from_tty);
12783 /* Completion function for the Ada "catch" commands. */
12785 static void
12786 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12787 const char *text, const char *word)
12789 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12791 for (const ada_exc_info &info : exceptions)
12793 if (startswith (info.name, word))
12794 tracker.add_completion (make_unique_xstrdup (info.name));
12798 /* Split the arguments specified in a "catch assert" command.
12800 ARGS contains the command's arguments (or the empty string if
12801 no arguments were passed).
12803 If ARGS contains a condition, set COND_STRING to that condition
12804 (the memory needs to be deallocated after use). */
12806 static void
12807 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12809 args = skip_spaces (args);
12811 /* Check whether a condition was provided. */
12812 if (startswith (args, "if")
12813 && (isspace (args[2]) || args[2] == '\0'))
12815 args += 2;
12816 args = skip_spaces (args);
12817 if (args[0] == '\0')
12818 error (_("condition missing after `if' keyword"));
12819 cond_string.assign (args);
12822 /* Otherwise, there should be no other argument at the end of
12823 the command. */
12824 else if (args[0] != '\0')
12825 error (_("Junk at end of arguments."));
12828 /* Implement the "catch assert" command. */
12830 static void
12831 catch_assert_command (const char *arg_entry, int from_tty,
12832 struct cmd_list_element *command)
12834 const char *arg = arg_entry;
12835 struct gdbarch *gdbarch = get_current_arch ();
12836 int tempflag;
12837 std::string cond_string;
12839 tempflag = command->context () == CATCH_TEMPORARY;
12841 if (!arg)
12842 arg = "";
12843 catch_ada_assert_command_split (arg, cond_string);
12844 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12845 {}, cond_string,
12846 tempflag, 1 /* enabled */,
12847 from_tty);
12850 /* Return non-zero if the symbol SYM is an Ada exception object. */
12852 static int
12853 ada_is_exception_sym (struct symbol *sym)
12855 const char *type_name = sym->type ()->name ();
12857 return (sym->aclass () != LOC_TYPEDEF
12858 && sym->aclass () != LOC_BLOCK
12859 && sym->aclass () != LOC_CONST
12860 && sym->aclass () != LOC_UNRESOLVED
12861 && type_name != NULL && strcmp (type_name, "exception") == 0);
12864 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12865 Ada exception object. This matches all exceptions except the ones
12866 defined by the Ada language. */
12868 static int
12869 ada_is_non_standard_exception_sym (struct symbol *sym)
12871 if (!ada_is_exception_sym (sym))
12872 return 0;
12874 for (const char *name : standard_exc)
12875 if (strcmp (sym->linkage_name (), name) == 0)
12876 return 0; /* A standard exception. */
12878 /* Numeric_Error is also a standard exception, so exclude it.
12879 See the STANDARD_EXC description for more details as to why
12880 this exception is not listed in that array. */
12881 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12882 return 0;
12884 return 1;
12887 /* A helper function for std::sort, comparing two struct ada_exc_info
12888 objects.
12890 The comparison is determined first by exception name, and then
12891 by exception address. */
12893 bool
12894 ada_exc_info::operator< (const ada_exc_info &other) const
12896 int result;
12898 result = strcmp (name, other.name);
12899 if (result < 0)
12900 return true;
12901 if (result == 0 && addr < other.addr)
12902 return true;
12903 return false;
12906 bool
12907 ada_exc_info::operator== (const ada_exc_info &other) const
12909 return addr == other.addr && strcmp (name, other.name) == 0;
12912 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12913 routine, but keeping the first SKIP elements untouched.
12915 All duplicates are also removed. */
12917 static void
12918 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12919 int skip)
12921 std::sort (exceptions->begin () + skip, exceptions->end ());
12922 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12923 exceptions->end ());
12926 /* Add all exceptions defined by the Ada standard whose name match
12927 a regular expression.
12929 If PREG is not NULL, then this regexp_t object is used to
12930 perform the symbol name matching. Otherwise, no name-based
12931 filtering is performed.
12933 EXCEPTIONS is a vector of exceptions to which matching exceptions
12934 gets pushed. */
12936 static void
12937 ada_add_standard_exceptions (compiled_regex *preg,
12938 std::vector<ada_exc_info> *exceptions)
12940 for (const char *name : standard_exc)
12942 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12944 symbol_name_match_type match_type = name_match_type_from_name (name);
12945 lookup_name_info lookup_name (name, match_type);
12947 symbol_name_matcher_ftype *match_name
12948 = ada_get_symbol_name_matcher (lookup_name);
12950 /* Iterate over all objfiles irrespective of scope or linker
12951 namespaces so we get all exceptions anywhere in the
12952 progspace. */
12953 for (objfile *objfile : current_program_space->objfiles ())
12955 for (minimal_symbol *msymbol : objfile->msymbols ())
12957 if (match_name (msymbol->linkage_name (), lookup_name,
12958 nullptr)
12959 && msymbol->type () != mst_solib_trampoline)
12961 ada_exc_info info
12962 = {name, msymbol->value_address (objfile)};
12964 exceptions->push_back (info);
12972 /* Add all Ada exceptions defined locally and accessible from the given
12973 FRAME.
12975 If PREG is not NULL, then this regexp_t object is used to
12976 perform the symbol name matching. Otherwise, no name-based
12977 filtering is performed.
12979 EXCEPTIONS is a vector of exceptions to which matching exceptions
12980 gets pushed. */
12982 static void
12983 ada_add_exceptions_from_frame (compiled_regex *preg,
12984 frame_info_ptr frame,
12985 std::vector<ada_exc_info> *exceptions)
12987 const struct block *block = get_frame_block (frame, 0);
12989 while (block != 0)
12991 for (struct symbol *sym : block_iterator_range (block))
12993 switch (sym->aclass ())
12995 case LOC_TYPEDEF:
12996 case LOC_BLOCK:
12997 case LOC_CONST:
12998 break;
12999 default:
13000 if (ada_is_exception_sym (sym))
13002 struct ada_exc_info info = {sym->print_name (),
13003 sym->value_address ()};
13005 exceptions->push_back (info);
13009 if (block->function () != NULL)
13010 break;
13011 block = block->superblock ();
13015 /* Return true if NAME matches PREG or if PREG is NULL. */
13017 static bool
13018 name_matches_regex (const char *name, compiled_regex *preg)
13020 return (preg == NULL
13021 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13024 /* Add all exceptions defined globally whose name name match
13025 a regular expression, excluding standard exceptions.
13027 The reason we exclude standard exceptions is that they need
13028 to be handled separately: Standard exceptions are defined inside
13029 a runtime unit which is normally not compiled with debugging info,
13030 and thus usually do not show up in our symbol search. However,
13031 if the unit was in fact built with debugging info, we need to
13032 exclude them because they would duplicate the entry we found
13033 during the special loop that specifically searches for those
13034 standard exceptions.
13036 If PREG is not NULL, then this regexp_t object is used to
13037 perform the symbol name matching. Otherwise, no name-based
13038 filtering is performed.
13040 EXCEPTIONS is a vector of exceptions to which matching exceptions
13041 gets pushed. */
13043 static void
13044 ada_add_global_exceptions (compiled_regex *preg,
13045 std::vector<ada_exc_info> *exceptions)
13047 /* In Ada, the symbol "search name" is a linkage name, whereas the
13048 regular expression used to do the matching refers to the natural
13049 name. So match against the decoded name. */
13050 expand_symtabs_matching (NULL,
13051 lookup_name_info::match_any (),
13052 [&] (const char *search_name)
13054 std::string decoded = ada_decode (search_name);
13055 return name_matches_regex (decoded.c_str (), preg);
13057 NULL,
13058 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13059 VARIABLES_DOMAIN);
13061 /* Iterate over all objfiles irrespective of scope or linker namespaces
13062 so we get all exceptions anywhere in the progspace. */
13063 for (objfile *objfile : current_program_space->objfiles ())
13065 for (compunit_symtab *s : objfile->compunits ())
13067 const struct blockvector *bv = s->blockvector ();
13068 int i;
13070 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13072 const struct block *b = bv->block (i);
13074 for (struct symbol *sym : block_iterator_range (b))
13075 if (ada_is_non_standard_exception_sym (sym)
13076 && name_matches_regex (sym->natural_name (), preg))
13078 struct ada_exc_info info
13079 = {sym->print_name (), sym->value_address ()};
13081 exceptions->push_back (info);
13088 /* Implements ada_exceptions_list with the regular expression passed
13089 as a regex_t, rather than a string.
13091 If not NULL, PREG is used to filter out exceptions whose names
13092 do not match. Otherwise, all exceptions are listed. */
13094 static std::vector<ada_exc_info>
13095 ada_exceptions_list_1 (compiled_regex *preg)
13097 std::vector<ada_exc_info> result;
13098 int prev_len;
13100 /* First, list the known standard exceptions. These exceptions
13101 need to be handled separately, as they are usually defined in
13102 runtime units that have been compiled without debugging info. */
13104 ada_add_standard_exceptions (preg, &result);
13106 /* Next, find all exceptions whose scope is local and accessible
13107 from the currently selected frame. */
13109 if (has_stack_frames ())
13111 prev_len = result.size ();
13112 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13113 &result);
13114 if (result.size () > prev_len)
13115 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13118 /* Add all exceptions whose scope is global. */
13120 prev_len = result.size ();
13121 ada_add_global_exceptions (preg, &result);
13122 if (result.size () > prev_len)
13123 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13125 return result;
13128 /* Return a vector of ada_exc_info.
13130 If REGEXP is NULL, all exceptions are included in the result.
13131 Otherwise, it should contain a valid regular expression,
13132 and only the exceptions whose names match that regular expression
13133 are included in the result.
13135 The exceptions are sorted in the following order:
13136 - Standard exceptions (defined by the Ada language), in
13137 alphabetical order;
13138 - Exceptions only visible from the current frame, in
13139 alphabetical order;
13140 - Exceptions whose scope is global, in alphabetical order. */
13142 std::vector<ada_exc_info>
13143 ada_exceptions_list (const char *regexp)
13145 if (regexp == NULL)
13146 return ada_exceptions_list_1 (NULL);
13148 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13149 return ada_exceptions_list_1 (&reg);
13152 /* Implement the "info exceptions" command. */
13154 static void
13155 info_exceptions_command (const char *regexp, int from_tty)
13157 struct gdbarch *gdbarch = get_current_arch ();
13159 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13161 if (regexp != NULL)
13162 gdb_printf
13163 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13164 else
13165 gdb_printf (_("All defined Ada exceptions:\n"));
13167 for (const ada_exc_info &info : exceptions)
13168 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13172 /* Language vector */
13174 /* symbol_name_matcher_ftype adapter for wild_match. */
13176 static bool
13177 do_wild_match (const char *symbol_search_name,
13178 const lookup_name_info &lookup_name,
13179 completion_match_result *comp_match_res)
13181 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13184 /* symbol_name_matcher_ftype adapter for full_match. */
13186 static bool
13187 do_full_match (const char *symbol_search_name,
13188 const lookup_name_info &lookup_name,
13189 completion_match_result *comp_match_res)
13191 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13193 /* If both symbols start with "_ada_", just let the loop below
13194 handle the comparison. However, if only the symbol name starts
13195 with "_ada_", skip the prefix and let the match proceed as
13196 usual. */
13197 if (startswith (symbol_search_name, "_ada_")
13198 && !startswith (lname, "_ada"))
13199 symbol_search_name += 5;
13200 /* Likewise for ghost entities. */
13201 if (startswith (symbol_search_name, "___ghost_")
13202 && !startswith (lname, "___ghost_"))
13203 symbol_search_name += 9;
13205 int uscore_count = 0;
13206 while (*lname != '\0')
13208 if (*symbol_search_name != *lname)
13210 if (*symbol_search_name == 'B' && uscore_count == 2
13211 && symbol_search_name[1] == '_')
13213 symbol_search_name += 2;
13214 while (isdigit (*symbol_search_name))
13215 ++symbol_search_name;
13216 if (symbol_search_name[0] == '_'
13217 && symbol_search_name[1] == '_')
13219 symbol_search_name += 2;
13220 continue;
13223 return false;
13226 if (*symbol_search_name == '_')
13227 ++uscore_count;
13228 else
13229 uscore_count = 0;
13231 ++symbol_search_name;
13232 ++lname;
13235 return is_name_suffix (symbol_search_name);
13238 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13240 static bool
13241 do_exact_match (const char *symbol_search_name,
13242 const lookup_name_info &lookup_name,
13243 completion_match_result *comp_match_res)
13245 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13248 /* Build the Ada lookup name for LOOKUP_NAME. */
13250 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13252 gdb::string_view user_name = lookup_name.name ();
13254 if (!user_name.empty () && user_name[0] == '<')
13256 if (user_name.back () == '>')
13257 m_encoded_name
13258 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
13259 else
13260 m_encoded_name
13261 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
13262 m_encoded_p = true;
13263 m_verbatim_p = true;
13264 m_wild_match_p = false;
13265 m_standard_p = false;
13267 else
13269 m_verbatim_p = false;
13271 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
13273 if (!m_encoded_p)
13275 const char *folded = ada_fold_name (user_name);
13276 m_encoded_name = ada_encode_1 (folded, false);
13277 if (m_encoded_name.empty ())
13278 m_encoded_name = gdb::to_string (user_name);
13280 else
13281 m_encoded_name = gdb::to_string (user_name);
13283 /* Handle the 'package Standard' special case. See description
13284 of m_standard_p. */
13285 if (startswith (m_encoded_name.c_str (), "standard__"))
13287 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13288 m_standard_p = true;
13290 else
13291 m_standard_p = false;
13293 /* If the name contains a ".", then the user is entering a fully
13294 qualified entity name, and the match must not be done in wild
13295 mode. Similarly, if the user wants to complete what looks
13296 like an encoded name, the match must not be done in wild
13297 mode. Also, in the standard__ special case always do
13298 non-wild matching. */
13299 m_wild_match_p
13300 = (lookup_name.match_type () != symbol_name_match_type::FULL
13301 && !m_encoded_p
13302 && !m_standard_p
13303 && user_name.find ('.') == std::string::npos);
13307 /* symbol_name_matcher_ftype method for Ada. This only handles
13308 completion mode. */
13310 static bool
13311 ada_symbol_name_matches (const char *symbol_search_name,
13312 const lookup_name_info &lookup_name,
13313 completion_match_result *comp_match_res)
13315 return lookup_name.ada ().matches (symbol_search_name,
13316 lookup_name.match_type (),
13317 comp_match_res);
13320 /* A name matcher that matches the symbol name exactly, with
13321 strcmp. */
13323 static bool
13324 literal_symbol_name_matcher (const char *symbol_search_name,
13325 const lookup_name_info &lookup_name,
13326 completion_match_result *comp_match_res)
13328 gdb::string_view name_view = lookup_name.name ();
13330 if (lookup_name.completion_mode ()
13331 ? (strncmp (symbol_search_name, name_view.data (),
13332 name_view.size ()) == 0)
13333 : symbol_search_name == name_view)
13335 if (comp_match_res != NULL)
13336 comp_match_res->set_match (symbol_search_name);
13337 return true;
13339 else
13340 return false;
13343 /* Implement the "get_symbol_name_matcher" language_defn method for
13344 Ada. */
13346 static symbol_name_matcher_ftype *
13347 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13349 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13350 return literal_symbol_name_matcher;
13352 if (lookup_name.completion_mode ())
13353 return ada_symbol_name_matches;
13354 else
13356 if (lookup_name.ada ().wild_match_p ())
13357 return do_wild_match;
13358 else if (lookup_name.ada ().verbatim_p ())
13359 return do_exact_match;
13360 else
13361 return do_full_match;
13365 /* Class representing the Ada language. */
13367 class ada_language : public language_defn
13369 public:
13370 ada_language ()
13371 : language_defn (language_ada)
13372 { /* Nothing. */ }
13374 /* See language.h. */
13376 const char *name () const override
13377 { return "ada"; }
13379 /* See language.h. */
13381 const char *natural_name () const override
13382 { return "Ada"; }
13384 /* See language.h. */
13386 const std::vector<const char *> &filename_extensions () const override
13388 static const std::vector<const char *> extensions
13389 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13390 return extensions;
13393 /* Print an array element index using the Ada syntax. */
13395 void print_array_index (struct type *index_type,
13396 LONGEST index,
13397 struct ui_file *stream,
13398 const value_print_options *options) const override
13400 struct value *index_value = val_atr (index_type, index);
13402 value_print (index_value, stream, options);
13403 gdb_printf (stream, " => ");
13406 /* Implement the "read_var_value" language_defn method for Ada. */
13408 struct value *read_var_value (struct symbol *var,
13409 const struct block *var_block,
13410 frame_info_ptr frame) const override
13412 /* The only case where default_read_var_value is not sufficient
13413 is when VAR is a renaming... */
13414 if (frame != nullptr)
13416 const struct block *frame_block = get_frame_block (frame, NULL);
13417 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13418 return ada_read_renaming_var_value (var, frame_block);
13421 /* This is a typical case where we expect the default_read_var_value
13422 function to work. */
13423 return language_defn::read_var_value (var, var_block, frame);
13426 /* See language.h. */
13427 bool symbol_printing_suppressed (struct symbol *symbol) const override
13429 return symbol->is_artificial ();
13432 /* See language.h. */
13433 struct value *value_string (struct gdbarch *gdbarch,
13434 const char *ptr, ssize_t len) const override
13436 struct type *type = language_string_char_type (this, gdbarch);
13437 value *val = ::value_string (ptr, len, type);
13438 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13439 strings that are arrays of characters, so fix the type now. */
13440 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13441 val->type ()->set_code (TYPE_CODE_ARRAY);
13442 return val;
13445 /* See language.h. */
13446 void language_arch_info (struct gdbarch *gdbarch,
13447 struct language_arch_info *lai) const override
13449 const struct builtin_type *builtin = builtin_type (gdbarch);
13451 /* Helper function to allow shorter lines below. */
13452 auto add = [&] (struct type *t)
13454 lai->add_primitive_type (t);
13457 type_allocator alloc (gdbarch);
13458 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13459 0, "integer"));
13460 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13461 0, "long_integer"));
13462 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13463 0, "short_integer"));
13464 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13465 1, "character");
13466 lai->set_string_char_type (char_type);
13467 add (char_type);
13468 add (init_character_type (alloc, 16, 1, "wide_character"));
13469 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13470 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13471 "float", gdbarch_float_format (gdbarch)));
13472 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13473 "long_float", gdbarch_double_format (gdbarch)));
13474 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13475 0, "long_long_integer"));
13476 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13477 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
13478 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13479 "long_long_float",
13480 gdbarch_long_double_format (gdbarch)));
13481 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13482 0, "natural"));
13483 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13484 0, "positive"));
13485 add (builtin->builtin_void);
13487 struct type *system_addr_ptr
13488 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13489 "void"));
13490 system_addr_ptr->set_name ("system__address");
13491 add (system_addr_ptr);
13493 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13494 type. This is a signed integral type whose size is the same as
13495 the size of addresses. */
13496 unsigned int addr_length = system_addr_ptr->length ();
13497 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13498 "storage_offset"));
13500 lai->set_bool_type (builtin->builtin_bool);
13503 /* See language.h. */
13505 bool iterate_over_symbols
13506 (const struct block *block, const lookup_name_info &name,
13507 domain_enum domain,
13508 gdb::function_view<symbol_found_callback_ftype> callback) const override
13510 std::vector<struct block_symbol> results
13511 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13512 for (block_symbol &sym : results)
13514 if (!callback (&sym))
13515 return false;
13518 return true;
13521 /* See language.h. */
13522 bool sniff_from_mangled_name
13523 (const char *mangled,
13524 gdb::unique_xmalloc_ptr<char> *out) const override
13526 std::string demangled = ada_decode (mangled);
13528 *out = NULL;
13530 if (demangled != mangled && demangled[0] != '<')
13532 /* Set the gsymbol language to Ada, but still return 0.
13533 Two reasons for that:
13535 1. For Ada, we prefer computing the symbol's decoded name
13536 on the fly rather than pre-compute it, in order to save
13537 memory (Ada projects are typically very large).
13539 2. There are some areas in the definition of the GNAT
13540 encoding where, with a bit of bad luck, we might be able
13541 to decode a non-Ada symbol, generating an incorrect
13542 demangled name (Eg: names ending with "TB" for instance
13543 are identified as task bodies and so stripped from
13544 the decoded name returned).
13546 Returning true, here, but not setting *DEMANGLED, helps us get
13547 a little bit of the best of both worlds. Because we're last,
13548 we should not affect any of the other languages that were
13549 able to demangle the symbol before us; we get to correctly
13550 tag Ada symbols as such; and even if we incorrectly tagged a
13551 non-Ada symbol, which should be rare, any routing through the
13552 Ada language should be transparent (Ada tries to behave much
13553 like C/C++ with non-Ada symbols). */
13554 return true;
13557 return false;
13560 /* See language.h. */
13562 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13563 int options) const override
13565 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13568 /* See language.h. */
13570 void print_type (struct type *type, const char *varstring,
13571 struct ui_file *stream, int show, int level,
13572 const struct type_print_options *flags) const override
13574 ada_print_type (type, varstring, stream, show, level, flags);
13577 /* See language.h. */
13579 const char *word_break_characters (void) const override
13581 return ada_completer_word_break_characters;
13584 /* See language.h. */
13586 void collect_symbol_completion_matches (completion_tracker &tracker,
13587 complete_symbol_mode mode,
13588 symbol_name_match_type name_match_type,
13589 const char *text, const char *word,
13590 enum type_code code) const override
13592 const struct block *b, *surrounding_static_block = 0;
13594 gdb_assert (code == TYPE_CODE_UNDEF);
13596 lookup_name_info lookup_name (text, name_match_type, true);
13598 /* First, look at the partial symtab symbols. */
13599 expand_symtabs_matching (NULL,
13600 lookup_name,
13601 NULL,
13602 NULL,
13603 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13604 ALL_DOMAIN);
13606 /* At this point scan through the misc symbol vectors and add each
13607 symbol you find to the list. Eventually we want to ignore
13608 anything that isn't a text symbol (everything else will be
13609 handled by the psymtab code above). */
13611 for (objfile *objfile : current_program_space->objfiles ())
13613 for (minimal_symbol *msymbol : objfile->msymbols ())
13615 QUIT;
13617 if (completion_skip_symbol (mode, msymbol))
13618 continue;
13620 language symbol_language = msymbol->language ();
13622 /* Ada minimal symbols won't have their language set to Ada. If
13623 we let completion_list_add_name compare using the
13624 default/C-like matcher, then when completing e.g., symbols in a
13625 package named "pck", we'd match internal Ada symbols like
13626 "pckS", which are invalid in an Ada expression, unless you wrap
13627 them in '<' '>' to request a verbatim match.
13629 Unfortunately, some Ada encoded names successfully demangle as
13630 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13631 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13632 with the wrong language set. Paper over that issue here. */
13633 if (symbol_language == language_unknown
13634 || symbol_language == language_cplus)
13635 symbol_language = language_ada;
13637 completion_list_add_name (tracker,
13638 symbol_language,
13639 msymbol->linkage_name (),
13640 lookup_name, text, word);
13644 /* Search upwards from currently selected frame (so that we can
13645 complete on local vars. */
13647 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13649 if (!b->superblock ())
13650 surrounding_static_block = b; /* For elmin of dups */
13652 for (struct symbol *sym : block_iterator_range (b))
13654 if (completion_skip_symbol (mode, sym))
13655 continue;
13657 completion_list_add_name (tracker,
13658 sym->language (),
13659 sym->linkage_name (),
13660 lookup_name, text, word);
13664 /* Go through the symtabs and check the externs and statics for
13665 symbols which match. */
13667 for (objfile *objfile : current_program_space->objfiles ())
13669 for (compunit_symtab *s : objfile->compunits ())
13671 QUIT;
13672 b = s->blockvector ()->global_block ();
13673 for (struct symbol *sym : block_iterator_range (b))
13675 if (completion_skip_symbol (mode, sym))
13676 continue;
13678 completion_list_add_name (tracker,
13679 sym->language (),
13680 sym->linkage_name (),
13681 lookup_name, text, word);
13686 for (objfile *objfile : current_program_space->objfiles ())
13688 for (compunit_symtab *s : objfile->compunits ())
13690 QUIT;
13691 b = s->blockvector ()->static_block ();
13692 /* Don't do this block twice. */
13693 if (b == surrounding_static_block)
13694 continue;
13695 for (struct symbol *sym : block_iterator_range (b))
13697 if (completion_skip_symbol (mode, sym))
13698 continue;
13700 completion_list_add_name (tracker,
13701 sym->language (),
13702 sym->linkage_name (),
13703 lookup_name, text, word);
13709 /* See language.h. */
13711 gdb::unique_xmalloc_ptr<char> watch_location_expression
13712 (struct type *type, CORE_ADDR addr) const override
13714 type = check_typedef (check_typedef (type)->target_type ());
13715 std::string name = type_to_string (type);
13716 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13719 /* See language.h. */
13721 void value_print (struct value *val, struct ui_file *stream,
13722 const struct value_print_options *options) const override
13724 return ada_value_print (val, stream, options);
13727 /* See language.h. */
13729 void value_print_inner
13730 (struct value *val, struct ui_file *stream, int recurse,
13731 const struct value_print_options *options) const override
13733 return ada_value_print_inner (val, stream, recurse, options);
13736 /* See language.h. */
13738 struct block_symbol lookup_symbol_nonlocal
13739 (const char *name, const struct block *block,
13740 const domain_enum domain) const override
13742 struct block_symbol sym;
13744 sym = ada_lookup_symbol (name,
13745 (block == nullptr
13746 ? nullptr
13747 : block->static_block ()),
13748 domain);
13749 if (sym.symbol != NULL)
13750 return sym;
13752 /* If we haven't found a match at this point, try the primitive
13753 types. In other languages, this search is performed before
13754 searching for global symbols in order to short-circuit that
13755 global-symbol search if it happens that the name corresponds
13756 to a primitive type. But we cannot do the same in Ada, because
13757 it is perfectly legitimate for a program to declare a type which
13758 has the same name as a standard type. If looking up a type in
13759 that situation, we have traditionally ignored the primitive type
13760 in favor of user-defined types. This is why, unlike most other
13761 languages, we search the primitive types this late and only after
13762 having searched the global symbols without success. */
13764 if (domain == VAR_DOMAIN)
13766 struct gdbarch *gdbarch;
13768 if (block == NULL)
13769 gdbarch = target_gdbarch ();
13770 else
13771 gdbarch = block->gdbarch ();
13772 sym.symbol
13773 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13774 if (sym.symbol != NULL)
13775 return sym;
13778 return {};
13781 /* See language.h. */
13783 int parser (struct parser_state *ps) const override
13785 warnings_issued = 0;
13786 return ada_parse (ps);
13789 /* See language.h. */
13791 void emitchar (int ch, struct type *chtype,
13792 struct ui_file *stream, int quoter) const override
13794 ada_emit_char (ch, chtype, stream, quoter, 1);
13797 /* See language.h. */
13799 void printchar (int ch, struct type *chtype,
13800 struct ui_file *stream) const override
13802 ada_printchar (ch, chtype, stream);
13805 /* See language.h. */
13807 void printstr (struct ui_file *stream, struct type *elttype,
13808 const gdb_byte *string, unsigned int length,
13809 const char *encoding, int force_ellipses,
13810 const struct value_print_options *options) const override
13812 ada_printstr (stream, elttype, string, length, encoding,
13813 force_ellipses, options);
13816 /* See language.h. */
13818 void print_typedef (struct type *type, struct symbol *new_symbol,
13819 struct ui_file *stream) const override
13821 ada_print_typedef (type, new_symbol, stream);
13824 /* See language.h. */
13826 bool is_string_type_p (struct type *type) const override
13828 return ada_is_string_type (type);
13831 /* See language.h. */
13833 bool is_array_like (struct type *type) const override
13835 return (ada_is_constrained_packed_array_type (type)
13836 || ada_is_array_descriptor_type (type));
13839 /* See language.h. */
13841 struct value *to_array (struct value *val) const override
13842 { return ada_coerce_to_simple_array (val); }
13844 /* See language.h. */
13846 const char *struct_too_deep_ellipsis () const override
13847 { return "(...)"; }
13849 /* See language.h. */
13851 bool c_style_arrays_p () const override
13852 { return false; }
13854 /* See language.h. */
13856 bool store_sym_names_in_linkage_form_p () const override
13857 { return true; }
13859 /* See language.h. */
13861 const struct lang_varobj_ops *varobj_ops () const override
13862 { return &ada_varobj_ops; }
13864 protected:
13865 /* See language.h. */
13867 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13868 (const lookup_name_info &lookup_name) const override
13870 return ada_get_symbol_name_matcher (lookup_name);
13874 /* Single instance of the Ada language class. */
13876 static ada_language ada_language_defn;
13878 /* Command-list for the "set/show ada" prefix command. */
13879 static struct cmd_list_element *set_ada_list;
13880 static struct cmd_list_element *show_ada_list;
13882 /* This module's 'new_objfile' observer. */
13884 static void
13885 ada_new_objfile_observer (struct objfile *objfile)
13887 ada_clear_symbol_cache ();
13890 /* This module's 'free_objfile' observer. */
13892 static void
13893 ada_free_objfile_observer (struct objfile *objfile)
13895 ada_clear_symbol_cache ();
13898 /* Charsets known to GNAT. */
13899 static const char * const gnat_source_charsets[] =
13901 /* Note that code below assumes that the default comes first.
13902 Latin-1 is the default here, because that is also GNAT's
13903 default. */
13904 "ISO-8859-1",
13905 "ISO-8859-2",
13906 "ISO-8859-3",
13907 "ISO-8859-4",
13908 "ISO-8859-5",
13909 "ISO-8859-15",
13910 "CP437",
13911 "CP850",
13912 /* Note that this value is special-cased in the encoder and
13913 decoder. */
13914 ada_utf8,
13915 nullptr
13918 void _initialize_ada_language ();
13919 void
13920 _initialize_ada_language ()
13922 add_setshow_prefix_cmd
13923 ("ada", no_class,
13924 _("Prefix command for changing Ada-specific settings."),
13925 _("Generic command for showing Ada-specific settings."),
13926 &set_ada_list, &show_ada_list,
13927 &setlist, &showlist);
13929 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13930 &trust_pad_over_xvs, _("\
13931 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13932 Show whether an optimization trusting PAD types over XVS types is activated."),
13933 _("\
13934 This is related to the encoding used by the GNAT compiler. The debugger\n\
13935 should normally trust the contents of PAD types, but certain older versions\n\
13936 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13937 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13938 work around this bug. It is always safe to turn this option \"off\", but\n\
13939 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13940 this option to \"off\" unless necessary."),
13941 NULL, NULL, &set_ada_list, &show_ada_list);
13943 add_setshow_boolean_cmd ("print-signatures", class_vars,
13944 &print_signatures, _("\
13945 Enable or disable the output of formal and return types for functions in the \
13946 overloads selection menu."), _("\
13947 Show whether the output of formal and return types for functions in the \
13948 overloads selection menu is activated."),
13949 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13951 ada_source_charset = gnat_source_charsets[0];
13952 add_setshow_enum_cmd ("source-charset", class_files,
13953 gnat_source_charsets,
13954 &ada_source_charset, _("\
13955 Set the Ada source character set."), _("\
13956 Show the Ada source character set."), _("\
13957 The character set used for Ada source files.\n\
13958 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13959 nullptr, nullptr,
13960 &set_ada_list, &show_ada_list);
13962 add_catch_command ("exception", _("\
13963 Catch Ada exceptions, when raised.\n\
13964 Usage: catch exception [ARG] [if CONDITION]\n\
13965 Without any argument, stop when any Ada exception is raised.\n\
13966 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13967 being raised does not have a handler (and will therefore lead to the task's\n\
13968 termination).\n\
13969 Otherwise, the catchpoint only stops when the name of the exception being\n\
13970 raised is the same as ARG.\n\
13971 CONDITION is a boolean expression that is evaluated to see whether the\n\
13972 exception should cause a stop."),
13973 catch_ada_exception_command,
13974 catch_ada_completer,
13975 CATCH_PERMANENT,
13976 CATCH_TEMPORARY);
13978 add_catch_command ("handlers", _("\
13979 Catch Ada exceptions, when handled.\n\
13980 Usage: catch handlers [ARG] [if CONDITION]\n\
13981 Without any argument, stop when any Ada exception is handled.\n\
13982 With an argument, catch only exceptions with the given name.\n\
13983 CONDITION is a boolean expression that is evaluated to see whether the\n\
13984 exception should cause a stop."),
13985 catch_ada_handlers_command,
13986 catch_ada_completer,
13987 CATCH_PERMANENT,
13988 CATCH_TEMPORARY);
13989 add_catch_command ("assert", _("\
13990 Catch failed Ada assertions, when raised.\n\
13991 Usage: catch assert [if CONDITION]\n\
13992 CONDITION is a boolean expression that is evaluated to see whether the\n\
13993 exception should cause a stop."),
13994 catch_assert_command,
13995 NULL,
13996 CATCH_PERMANENT,
13997 CATCH_TEMPORARY);
13999 add_info ("exceptions", info_exceptions_command,
14000 _("\
14001 List all Ada exception names.\n\
14002 Usage: info exceptions [REGEXP]\n\
14003 If a regular expression is passed as an argument, only those matching\n\
14004 the regular expression are listed."));
14006 add_setshow_prefix_cmd ("ada", class_maintenance,
14007 _("Set Ada maintenance-related variables."),
14008 _("Show Ada maintenance-related variables."),
14009 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14010 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14012 add_setshow_boolean_cmd
14013 ("ignore-descriptive-types", class_maintenance,
14014 &ada_ignore_descriptive_types_p,
14015 _("Set whether descriptive types generated by GNAT should be ignored."),
14016 _("Show whether descriptive types generated by GNAT should be ignored."),
14017 _("\
14018 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14019 DWARF attribute."),
14020 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14022 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14023 htab_eq_string,
14024 NULL, xcalloc, xfree);
14026 /* The ada-lang observers. */
14027 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14028 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14029 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14031 #ifdef GDB_SELF_TEST
14032 selftests::register_test ("ada-decode", ada_decode_tests);
14033 #endif