Ensure that libbacktrace/allocfail.sh is not deleted when creating release tarballs.
[binutils-gdb.git] / gdb / ada-lang.c
blobd59a5ae576e92a0a27c5afe8b2bb27c787ebb6eb
1 /* Ada language support routines for GDB, the GNU debugger.
3 Copyright (C) 1992-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
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 <algorithm>
61 #include "ada-exp.h"
62 #include "charset.h"
64 /* Define whether or not the C operator '/' truncates towards zero for
65 differently signed operands (truncation direction is undefined in C).
66 Copied from valarith.c. */
68 #ifndef TRUNCATION_TOWARDS_ZERO
69 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
70 #endif
72 static struct type *desc_base_type (struct type *);
74 static struct type *desc_bounds_type (struct type *);
76 static struct value *desc_bounds (struct value *);
78 static int fat_pntr_bounds_bitpos (struct type *);
80 static int fat_pntr_bounds_bitsize (struct type *);
82 static struct type *desc_data_target_type (struct type *);
84 static struct value *desc_data (struct value *);
86 static int fat_pntr_data_bitpos (struct type *);
88 static int fat_pntr_data_bitsize (struct type *);
90 static struct value *desc_one_bound (struct value *, int, int);
92 static int desc_bound_bitpos (struct type *, int, int);
94 static int desc_bound_bitsize (struct type *, int, int);
96 static struct type *desc_index_type (struct type *, int);
98 static int desc_arity (struct type *);
100 static int ada_args_match (struct symbol *, struct value **, int);
102 static struct value *make_array_descriptor (struct type *, struct value *);
104 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
106 const lookup_name_info &lookup_name,
107 domain_enum, struct objfile *);
109 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
110 const struct block *,
111 const lookup_name_info &lookup_name,
112 domain_enum, int, int *);
114 static int is_nonfunction (const std::vector<struct block_symbol> &);
116 static void add_defn_to_vec (std::vector<struct block_symbol> &,
117 struct symbol *,
118 const struct block *);
120 static int possible_user_operator_p (enum exp_opcode, struct value **);
122 static const char *ada_decoded_op_name (enum exp_opcode);
124 static int numeric_type_p (struct type *);
126 static int integer_type_p (struct type *);
128 static int scalar_type_p (struct type *);
130 static int discrete_type_p (struct type *);
132 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
133 int, int);
135 static struct type *ada_find_parallel_type_with_name (struct type *,
136 const char *);
138 static int is_dynamic_field (struct type *, int);
140 static struct type *to_fixed_variant_branch_type (struct type *,
141 const gdb_byte *,
142 CORE_ADDR, struct value *);
144 static struct type *to_fixed_array_type (struct type *, struct value *, int);
146 static struct type *to_fixed_range_type (struct type *, struct value *);
148 static struct type *to_static_fixed_type (struct type *);
149 static struct type *static_unwrap_type (struct type *type);
151 static struct value *unwrap_value (struct value *);
153 static struct type *constrained_packed_array_type (struct type *, long *);
155 static struct type *decode_constrained_packed_array_type (struct type *);
157 static long decode_packed_array_bitsize (struct type *);
159 static struct value *decode_constrained_packed_array (struct value *);
161 static int ada_is_unconstrained_packed_array_type (struct type *);
163 static struct value *value_subscript_packed (struct value *, int,
164 struct value **);
166 static struct value *coerce_unspec_val_to_type (struct value *,
167 struct type *);
169 static int lesseq_defined_than (struct symbol *, struct symbol *);
171 static int equiv_types (struct type *, struct type *);
173 static int is_name_suffix (const char *);
175 static int advance_wild_match (const char **, const char *, char);
177 static bool wild_match (const char *name, const char *patn);
179 static struct value *ada_coerce_ref (struct value *);
181 static LONGEST pos_atr (struct value *);
183 static struct value *val_atr (struct type *, LONGEST);
185 static struct symbol *standard_lookup (const char *, const struct block *,
186 domain_enum);
188 static struct value *ada_search_struct_field (const char *, struct value *, int,
189 struct type *);
191 static int find_struct_field (const char *, struct type *, int,
192 struct type **, int *, int *, int *, int *);
194 static int ada_resolve_function (std::vector<struct block_symbol> &,
195 struct value **, int, const char *,
196 struct type *, bool);
198 static int ada_is_direct_array_type (struct type *);
200 static struct value *ada_index_struct_field (int, struct value *, int,
201 struct type *);
203 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
206 static struct type *ada_find_any_type (const char *name);
208 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
209 (const lookup_name_info &lookup_name);
213 /* The character set used for source files. */
214 static const char *ada_source_charset;
216 /* The string "UTF-8". This is here so we can check for the UTF-8
217 charset using == rather than strcmp. */
218 static const char ada_utf8[] = "UTF-8";
220 /* Each entry in the UTF-32 case-folding table is of this form. */
221 struct utf8_entry
223 /* The start and end, inclusive, of this range of codepoints. */
224 uint32_t start, end;
225 /* The delta to apply to get the upper-case form. 0 if this is
226 already upper-case. */
227 int upper_delta;
228 /* The delta to apply to get the lower-case form. 0 if this is
229 already lower-case. */
230 int lower_delta;
232 bool operator< (uint32_t val) const
234 return end < val;
238 static const utf8_entry ada_case_fold[] =
240 #include "ada-casefold.h"
245 /* The result of a symbol lookup to be stored in our symbol cache. */
247 struct cache_entry
249 /* The name used to perform the lookup. */
250 const char *name;
251 /* The namespace used during the lookup. */
252 domain_enum domain;
253 /* The symbol returned by the lookup, or NULL if no matching symbol
254 was found. */
255 struct symbol *sym;
256 /* The block where the symbol was found, or NULL if no matching
257 symbol was found. */
258 const struct block *block;
259 /* A pointer to the next entry with the same hash. */
260 struct cache_entry *next;
263 /* The Ada symbol cache, used to store the result of Ada-mode symbol
264 lookups in the course of executing the user's commands.
266 The cache is implemented using a simple, fixed-sized hash.
267 The size is fixed on the grounds that there are not likely to be
268 all that many symbols looked up during any given session, regardless
269 of the size of the symbol table. If we decide to go to a resizable
270 table, let's just use the stuff from libiberty instead. */
272 #define HASH_SIZE 1009
274 struct ada_symbol_cache
276 /* An obstack used to store the entries in our cache. */
277 struct auto_obstack cache_space;
279 /* The root of the hash table used to implement our symbol cache. */
280 struct cache_entry *root[HASH_SIZE] {};
283 static const char ada_completer_word_break_characters[] =
284 #ifdef VMS
285 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
286 #else
287 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
288 #endif
290 /* The name of the symbol to use to get the name of the main subprogram. */
291 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
292 = "__gnat_ada_main_program_name";
294 /* Limit on the number of warnings to raise per expression evaluation. */
295 static int warning_limit = 2;
297 /* Number of warning messages issued; reset to 0 by cleanups after
298 expression evaluation. */
299 static int warnings_issued = 0;
301 static const char * const known_runtime_file_name_patterns[] = {
302 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
305 static const char * const known_auxiliary_function_name_patterns[] = {
306 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
309 /* Maintenance-related settings for this module. */
311 static struct cmd_list_element *maint_set_ada_cmdlist;
312 static struct cmd_list_element *maint_show_ada_cmdlist;
314 /* The "maintenance ada set/show ignore-descriptive-type" value. */
316 static bool ada_ignore_descriptive_types_p = false;
318 /* Inferior-specific data. */
320 /* Per-inferior data for this module. */
322 struct ada_inferior_data
324 /* The ada__tags__type_specific_data type, which is used when decoding
325 tagged types. With older versions of GNAT, this type was directly
326 accessible through a component ("tsd") in the object tag. But this
327 is no longer the case, so we cache it for each inferior. */
328 struct type *tsd_type = nullptr;
330 /* The exception_support_info data. This data is used to determine
331 how to implement support for Ada exception catchpoints in a given
332 inferior. */
333 const struct exception_support_info *exception_info = nullptr;
336 /* Our key to this module's inferior data. */
337 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
339 /* Return our inferior data for the given inferior (INF).
341 This function always returns a valid pointer to an allocated
342 ada_inferior_data structure. If INF's inferior data has not
343 been previously set, this functions creates a new one with all
344 fields set to zero, sets INF's inferior to it, and then returns
345 a pointer to that newly allocated ada_inferior_data. */
347 static struct ada_inferior_data *
348 get_ada_inferior_data (struct inferior *inf)
350 struct ada_inferior_data *data;
352 data = ada_inferior_data.get (inf);
353 if (data == NULL)
354 data = ada_inferior_data.emplace (inf);
356 return data;
359 /* Perform all necessary cleanups regarding our module's inferior data
360 that is required after the inferior INF just exited. */
362 static void
363 ada_inferior_exit (struct inferior *inf)
365 ada_inferior_data.clear (inf);
369 /* program-space-specific data. */
371 /* This module's per-program-space data. */
372 struct ada_pspace_data
374 /* The Ada symbol cache. */
375 std::unique_ptr<ada_symbol_cache> sym_cache;
378 /* Key to our per-program-space data. */
379 static const registry<program_space>::key<ada_pspace_data>
380 ada_pspace_data_handle;
382 /* Return this module's data for the given program space (PSPACE).
383 If not is found, add a zero'ed one now.
385 This function always returns a valid object. */
387 static struct ada_pspace_data *
388 get_ada_pspace_data (struct program_space *pspace)
390 struct ada_pspace_data *data;
392 data = ada_pspace_data_handle.get (pspace);
393 if (data == NULL)
394 data = ada_pspace_data_handle.emplace (pspace);
396 return data;
399 /* Utilities */
401 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
402 all typedef layers have been peeled. Otherwise, return TYPE.
404 Normally, we really expect a typedef type to only have 1 typedef layer.
405 In other words, we really expect the target type of a typedef type to be
406 a non-typedef type. This is particularly true for Ada units, because
407 the language does not have a typedef vs not-typedef distinction.
408 In that respect, the Ada compiler has been trying to eliminate as many
409 typedef definitions in the debugging information, since they generally
410 do not bring any extra information (we still use typedef under certain
411 circumstances related mostly to the GNAT encoding).
413 Unfortunately, we have seen situations where the debugging information
414 generated by the compiler leads to such multiple typedef layers. For
415 instance, consider the following example with stabs:
417 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
418 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
420 This is an error in the debugging information which causes type
421 pck__float_array___XUP to be defined twice, and the second time,
422 it is defined as a typedef of a typedef.
424 This is on the fringe of legality as far as debugging information is
425 concerned, and certainly unexpected. But it is easy to handle these
426 situations correctly, so we can afford to be lenient in this case. */
428 static struct type *
429 ada_typedef_target_type (struct type *type)
431 while (type->code () == TYPE_CODE_TYPEDEF)
432 type = type->target_type ();
433 return type;
436 /* Given DECODED_NAME a string holding a symbol name in its
437 decoded form (ie using the Ada dotted notation), returns
438 its unqualified name. */
440 static const char *
441 ada_unqualified_name (const char *decoded_name)
443 const char *result;
445 /* If the decoded name starts with '<', it means that the encoded
446 name does not follow standard naming conventions, and thus that
447 it is not your typical Ada symbol name. Trying to unqualify it
448 is therefore pointless and possibly erroneous. */
449 if (decoded_name[0] == '<')
450 return decoded_name;
452 result = strrchr (decoded_name, '.');
453 if (result != NULL)
454 result++; /* Skip the dot... */
455 else
456 result = decoded_name;
458 return result;
461 /* Return a string starting with '<', followed by STR, and '>'. */
463 static std::string
464 add_angle_brackets (const char *str)
466 return string_printf ("<%s>", str);
469 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
470 suffix of FIELD_NAME beginning "___". */
472 static int
473 field_name_match (const char *field_name, const char *target)
475 int len = strlen (target);
477 return
478 (strncmp (field_name, target, len) == 0
479 && (field_name[len] == '\0'
480 || (startswith (field_name + len, "___")
481 && strcmp (field_name + strlen (field_name) - 6,
482 "___XVN") != 0)));
486 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
487 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
488 and return its index. This function also handles fields whose name
489 have ___ suffixes because the compiler sometimes alters their name
490 by adding such a suffix to represent fields with certain constraints.
491 If the field could not be found, return a negative number if
492 MAYBE_MISSING is set. Otherwise raise an error. */
495 ada_get_field_index (const struct type *type, const char *field_name,
496 int maybe_missing)
498 int fieldno;
499 struct type *struct_type = check_typedef ((struct type *) type);
501 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
502 if (field_name_match (struct_type->field (fieldno).name (), field_name))
503 return fieldno;
505 if (!maybe_missing)
506 error (_("Unable to find field %s in struct %s. Aborting"),
507 field_name, struct_type->name ());
509 return -1;
512 /* The length of the prefix of NAME prior to any "___" suffix. */
515 ada_name_prefix_len (const char *name)
517 if (name == NULL)
518 return 0;
519 else
521 const char *p = strstr (name, "___");
523 if (p == NULL)
524 return strlen (name);
525 else
526 return p - name;
530 /* Return non-zero if SUFFIX is a suffix of STR.
531 Return zero if STR is null. */
533 static int
534 is_suffix (const char *str, const char *suffix)
536 int len1, len2;
538 if (str == NULL)
539 return 0;
540 len1 = strlen (str);
541 len2 = strlen (suffix);
542 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
545 /* The contents of value VAL, treated as a value of type TYPE. The
546 result is an lval in memory if VAL is. */
548 static struct value *
549 coerce_unspec_val_to_type (struct value *val, struct type *type)
551 type = ada_check_typedef (type);
552 if (value_type (val) == type)
553 return val;
554 else
556 struct value *result;
558 if (value_optimized_out (val))
559 result = allocate_optimized_out_value (type);
560 else if (value_lazy (val)
561 /* Be careful not to make a lazy not_lval value. */
562 || (VALUE_LVAL (val) != not_lval
563 && type->length () > value_type (val)->length ()))
564 result = allocate_value_lazy (type);
565 else
567 result = allocate_value (type);
568 value_contents_copy (result, 0, val, 0, type->length ());
570 set_value_component_location (result, val);
571 set_value_bitsize (result, value_bitsize (val));
572 set_value_bitpos (result, value_bitpos (val));
573 if (VALUE_LVAL (result) == lval_memory)
574 set_value_address (result, value_address (val));
575 return result;
579 static const gdb_byte *
580 cond_offset_host (const gdb_byte *valaddr, long offset)
582 if (valaddr == NULL)
583 return NULL;
584 else
585 return valaddr + offset;
588 static CORE_ADDR
589 cond_offset_target (CORE_ADDR address, long offset)
591 if (address == 0)
592 return 0;
593 else
594 return address + offset;
597 /* Issue a warning (as for the definition of warning in utils.c, but
598 with exactly one argument rather than ...), unless the limit on the
599 number of warnings has passed during the evaluation of the current
600 expression. */
602 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
603 provided by "complaint". */
604 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
606 static void
607 lim_warning (const char *format, ...)
609 va_list args;
611 va_start (args, format);
612 warnings_issued += 1;
613 if (warnings_issued <= warning_limit)
614 vwarning (format, args);
616 va_end (args);
619 /* Maximum value of a SIZE-byte signed integer type. */
620 static LONGEST
621 max_of_size (int size)
623 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
625 return top_bit | (top_bit - 1);
628 /* Minimum value of a SIZE-byte signed integer type. */
629 static LONGEST
630 min_of_size (int size)
632 return -max_of_size (size) - 1;
635 /* Maximum value of a SIZE-byte unsigned integer type. */
636 static ULONGEST
637 umax_of_size (int size)
639 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
641 return top_bit | (top_bit - 1);
644 /* Maximum value of integral type T, as a signed quantity. */
645 static LONGEST
646 max_of_type (struct type *t)
648 if (t->is_unsigned ())
649 return (LONGEST) umax_of_size (t->length ());
650 else
651 return max_of_size (t->length ());
654 /* Minimum value of integral type T, as a signed quantity. */
655 static LONGEST
656 min_of_type (struct type *t)
658 if (t->is_unsigned ())
659 return 0;
660 else
661 return min_of_size (t->length ());
664 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
665 LONGEST
666 ada_discrete_type_high_bound (struct type *type)
668 type = resolve_dynamic_type (type, {}, 0);
669 switch (type->code ())
671 case TYPE_CODE_RANGE:
673 const dynamic_prop &high = type->bounds ()->high;
675 if (high.kind () == PROP_CONST)
676 return high.const_val ();
677 else
679 gdb_assert (high.kind () == PROP_UNDEFINED);
681 /* This happens when trying to evaluate a type's dynamic bound
682 without a live target. There is nothing relevant for us to
683 return here, so return 0. */
684 return 0;
687 case TYPE_CODE_ENUM:
688 return type->field (type->num_fields () - 1).loc_enumval ();
689 case TYPE_CODE_BOOL:
690 return 1;
691 case TYPE_CODE_CHAR:
692 case TYPE_CODE_INT:
693 return max_of_type (type);
694 default:
695 error (_("Unexpected type in ada_discrete_type_high_bound."));
699 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
700 LONGEST
701 ada_discrete_type_low_bound (struct type *type)
703 type = resolve_dynamic_type (type, {}, 0);
704 switch (type->code ())
706 case TYPE_CODE_RANGE:
708 const dynamic_prop &low = type->bounds ()->low;
710 if (low.kind () == PROP_CONST)
711 return low.const_val ();
712 else
714 gdb_assert (low.kind () == PROP_UNDEFINED);
716 /* This happens when trying to evaluate a type's dynamic bound
717 without a live target. There is nothing relevant for us to
718 return here, so return 0. */
719 return 0;
722 case TYPE_CODE_ENUM:
723 return type->field (0).loc_enumval ();
724 case TYPE_CODE_BOOL:
725 return 0;
726 case TYPE_CODE_CHAR:
727 case TYPE_CODE_INT:
728 return min_of_type (type);
729 default:
730 error (_("Unexpected type in ada_discrete_type_low_bound."));
734 /* The identity on non-range types. For range types, the underlying
735 non-range scalar type. */
737 static struct type *
738 get_base_type (struct type *type)
740 while (type != NULL && type->code () == TYPE_CODE_RANGE)
742 if (type == type->target_type () || type->target_type () == NULL)
743 return type;
744 type = type->target_type ();
746 return type;
749 /* Return a decoded version of the given VALUE. This means returning
750 a value whose type is obtained by applying all the GNAT-specific
751 encodings, making the resulting type a static but standard description
752 of the initial type. */
754 struct value *
755 ada_get_decoded_value (struct value *value)
757 struct type *type = ada_check_typedef (value_type (value));
759 if (ada_is_array_descriptor_type (type)
760 || (ada_is_constrained_packed_array_type (type)
761 && type->code () != TYPE_CODE_PTR))
763 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
764 value = ada_coerce_to_simple_array_ptr (value);
765 else
766 value = ada_coerce_to_simple_array (value);
768 else
769 value = ada_to_fixed_value (value);
771 return value;
774 /* Same as ada_get_decoded_value, but with the given TYPE.
775 Because there is no associated actual value for this type,
776 the resulting type might be a best-effort approximation in
777 the case of dynamic types. */
779 struct type *
780 ada_get_decoded_type (struct type *type)
782 type = to_static_fixed_type (type);
783 if (ada_is_constrained_packed_array_type (type))
784 type = ada_coerce_to_simple_array_type (type);
785 return type;
790 /* Language Selection */
792 /* If the main program is in Ada, return language_ada, otherwise return LANG
793 (the main program is in Ada iif the adainit symbol is found). */
795 static enum language
796 ada_update_initial_language (enum language lang)
798 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
799 return language_ada;
801 return lang;
804 /* If the main procedure is written in Ada, then return its name.
805 The result is good until the next call. Return NULL if the main
806 procedure doesn't appear to be in Ada. */
808 char *
809 ada_main_name (void)
811 struct bound_minimal_symbol msym;
812 static gdb::unique_xmalloc_ptr<char> main_program_name;
814 /* For Ada, the name of the main procedure is stored in a specific
815 string constant, generated by the binder. Look for that symbol,
816 extract its address, and then read that string. If we didn't find
817 that string, then most probably the main procedure is not written
818 in Ada. */
819 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
821 if (msym.minsym != NULL)
823 CORE_ADDR main_program_name_addr = msym.value_address ();
824 if (main_program_name_addr == 0)
825 error (_("Invalid address for Ada main program name."));
827 main_program_name = target_read_string (main_program_name_addr, 1024);
828 return main_program_name.get ();
831 /* The main procedure doesn't seem to be in Ada. */
832 return NULL;
835 /* Symbols */
837 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
838 of NULLs. */
840 const struct ada_opname_map ada_opname_table[] = {
841 {"Oadd", "\"+\"", BINOP_ADD},
842 {"Osubtract", "\"-\"", BINOP_SUB},
843 {"Omultiply", "\"*\"", BINOP_MUL},
844 {"Odivide", "\"/\"", BINOP_DIV},
845 {"Omod", "\"mod\"", BINOP_MOD},
846 {"Orem", "\"rem\"", BINOP_REM},
847 {"Oexpon", "\"**\"", BINOP_EXP},
848 {"Olt", "\"<\"", BINOP_LESS},
849 {"Ole", "\"<=\"", BINOP_LEQ},
850 {"Ogt", "\">\"", BINOP_GTR},
851 {"Oge", "\">=\"", BINOP_GEQ},
852 {"Oeq", "\"=\"", BINOP_EQUAL},
853 {"One", "\"/=\"", BINOP_NOTEQUAL},
854 {"Oand", "\"and\"", BINOP_BITWISE_AND},
855 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
856 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
857 {"Oconcat", "\"&\"", BINOP_CONCAT},
858 {"Oabs", "\"abs\"", UNOP_ABS},
859 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
860 {"Oadd", "\"+\"", UNOP_PLUS},
861 {"Osubtract", "\"-\"", UNOP_NEG},
862 {NULL, NULL}
865 /* If STR is a decoded version of a compiler-provided suffix (like the
866 "[cold]" in "symbol[cold]"), return true. Otherwise, return
867 false. */
869 static bool
870 is_compiler_suffix (const char *str)
872 gdb_assert (*str == '[');
873 ++str;
874 while (*str != '\0' && isalpha (*str))
875 ++str;
876 /* We accept a missing "]" in order to support completion. */
877 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
880 /* Append a non-ASCII character to RESULT. */
881 static void
882 append_hex_encoded (std::string &result, uint32_t one_char)
884 if (one_char <= 0xff)
886 result.append ("U");
887 result.append (phex (one_char, 1));
889 else if (one_char <= 0xffff)
891 result.append ("W");
892 result.append (phex (one_char, 2));
894 else
896 result.append ("WW");
897 result.append (phex (one_char, 4));
901 /* Return a string that is a copy of the data in STORAGE, with
902 non-ASCII characters replaced by the appropriate hex encoding. A
903 template is used because, for UTF-8, we actually want to work with
904 UTF-32 codepoints. */
905 template<typename T>
906 std::string
907 copy_and_hex_encode (struct obstack *storage)
909 const T *chars = (T *) obstack_base (storage);
910 int num_chars = obstack_object_size (storage) / sizeof (T);
911 std::string result;
912 for (int i = 0; i < num_chars; ++i)
914 if (chars[i] <= 0x7f)
916 /* The host character set has to be a superset of ASCII, as
917 are all the other character sets we can use. */
918 result.push_back (chars[i]);
920 else
921 append_hex_encoded (result, chars[i]);
923 return result;
926 /* The "encoded" form of DECODED, according to GNAT conventions. If
927 THROW_ERRORS, throw an error if invalid operator name is found.
928 Otherwise, return the empty string in that case. */
930 static std::string
931 ada_encode_1 (const char *decoded, bool throw_errors)
933 if (decoded == NULL)
934 return {};
936 std::string encoding_buffer;
937 bool saw_non_ascii = false;
938 for (const char *p = decoded; *p != '\0'; p += 1)
940 if ((*p & 0x80) != 0)
941 saw_non_ascii = true;
943 if (*p == '.')
944 encoding_buffer.append ("__");
945 else if (*p == '[' && is_compiler_suffix (p))
947 encoding_buffer = encoding_buffer + "." + (p + 1);
948 if (encoding_buffer.back () == ']')
949 encoding_buffer.pop_back ();
950 break;
952 else if (*p == '"')
954 const struct ada_opname_map *mapping;
956 for (mapping = ada_opname_table;
957 mapping->encoded != NULL
958 && !startswith (p, mapping->decoded); mapping += 1)
960 if (mapping->encoded == NULL)
962 if (throw_errors)
963 error (_("invalid Ada operator name: %s"), p);
964 else
965 return {};
967 encoding_buffer.append (mapping->encoded);
968 break;
970 else
971 encoding_buffer.push_back (*p);
974 /* If a non-ASCII character is seen, we must convert it to the
975 appropriate hex form. As this is more expensive, we keep track
976 of whether it is even necessary. */
977 if (saw_non_ascii)
979 auto_obstack storage;
980 bool is_utf8 = ada_source_charset == ada_utf8;
983 convert_between_encodings
984 (host_charset (),
985 is_utf8 ? HOST_UTF32 : ada_source_charset,
986 (const gdb_byte *) encoding_buffer.c_str (),
987 encoding_buffer.length (), 1,
988 &storage, translit_none);
990 catch (const gdb_exception &)
992 static bool warned = false;
994 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
995 might like to know why. */
996 if (!warned)
998 warned = true;
999 warning (_("charset conversion failure for '%s'.\n"
1000 "You may have the wrong value for 'set ada source-charset'."),
1001 encoding_buffer.c_str ());
1004 /* We don't try to recover from errors. */
1005 return encoding_buffer;
1008 if (is_utf8)
1009 return copy_and_hex_encode<uint32_t> (&storage);
1010 return copy_and_hex_encode<gdb_byte> (&storage);
1013 return encoding_buffer;
1016 /* Find the entry for C in the case-folding table. Return nullptr if
1017 the entry does not cover C. */
1018 static const utf8_entry *
1019 find_case_fold_entry (uint32_t c)
1021 auto iter = std::lower_bound (std::begin (ada_case_fold),
1022 std::end (ada_case_fold),
1024 if (iter == std::end (ada_case_fold)
1025 || c < iter->start
1026 || c > iter->end)
1027 return nullptr;
1028 return &*iter;
1031 /* Return NAME folded to lower case, or, if surrounded by single
1032 quotes, unfolded, but with the quotes stripped away. If
1033 THROW_ON_ERROR is true, encoding failures will throw an exception
1034 rather than emitting a warning. Result good to next call. */
1036 static const char *
1037 ada_fold_name (gdb::string_view name, bool throw_on_error = false)
1039 static std::string fold_storage;
1041 if (!name.empty () && name[0] == '\'')
1042 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
1043 else
1045 /* Why convert to UTF-32 and implement our own case-folding,
1046 rather than convert to wchar_t and use the platform's
1047 functions? I'm glad you asked.
1049 The main problem is that GNAT implements an unusual rule for
1050 case folding. For ASCII letters, letters in single-byte
1051 encodings (such as ISO-8859-*), and Unicode letters that fit
1052 in a single byte (i.e., code point is <= 0xff), the letter is
1053 folded to lower case. Other Unicode letters are folded to
1054 upper case.
1056 This rule means that the code must be able to examine the
1057 value of the character. And, some hosts do not use Unicode
1058 for wchar_t, so examining the value of such characters is
1059 forbidden. */
1060 auto_obstack storage;
1063 convert_between_encodings
1064 (host_charset (), HOST_UTF32,
1065 (const gdb_byte *) name.data (),
1066 name.length (), 1,
1067 &storage, translit_none);
1069 catch (const gdb_exception &)
1071 if (throw_on_error)
1072 throw;
1074 static bool warned = false;
1076 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1077 might like to know why. */
1078 if (!warned)
1080 warned = true;
1081 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1082 "This normally should not happen, please file a bug report."),
1083 gdb::to_string (name).c_str (), host_charset ());
1086 /* We don't try to recover from errors; just return the
1087 original string. */
1088 fold_storage = gdb::to_string (name);
1089 return fold_storage.c_str ();
1092 bool is_utf8 = ada_source_charset == ada_utf8;
1093 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1094 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1095 for (int i = 0; i < num_chars; ++i)
1097 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1098 if (entry != nullptr)
1100 uint32_t low = chars[i] + entry->lower_delta;
1101 if (!is_utf8 || low <= 0xff)
1102 chars[i] = low;
1103 else
1104 chars[i] = chars[i] + entry->upper_delta;
1108 /* Now convert back to ordinary characters. */
1109 auto_obstack reconverted;
1112 convert_between_encodings (HOST_UTF32,
1113 host_charset (),
1114 (const gdb_byte *) chars,
1115 num_chars * sizeof (uint32_t),
1116 sizeof (uint32_t),
1117 &reconverted,
1118 translit_none);
1119 obstack_1grow (&reconverted, '\0');
1120 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1122 catch (const gdb_exception &)
1124 if (throw_on_error)
1125 throw;
1127 static bool warned = false;
1129 /* Converting back from UTF-32 shouldn't normally fail, but
1130 there are some host encodings without upper/lower
1131 equivalence. */
1132 if (!warned)
1134 warned = true;
1135 warning (_("could not convert the lower-cased variant of '%s'\n"
1136 "from UTF-32 to the host encoding (%s)."),
1137 gdb::to_string (name).c_str (), host_charset ());
1140 /* We don't try to recover from errors; just return the
1141 original string. */
1142 fold_storage = gdb::to_string (name);
1146 return fold_storage.c_str ();
1149 /* The "encoded" form of DECODED, according to GNAT conventions. If
1150 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1151 with <...> quoting are not folded in any case. */
1153 std::string
1154 ada_encode (const char *decoded, bool fold)
1156 if (fold && decoded[0] != '<')
1157 decoded = ada_fold_name (decoded);
1158 return ada_encode_1 (decoded, true);
1161 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1163 static int
1164 is_lower_alphanum (const char c)
1166 return (isdigit (c) || (isalpha (c) && islower (c)));
1169 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1170 This function saves in LEN the length of that same symbol name but
1171 without either of these suffixes:
1172 . .{DIGIT}+
1173 . ${DIGIT}+
1174 . ___{DIGIT}+
1175 . __{DIGIT}+.
1177 These are suffixes introduced by the compiler for entities such as
1178 nested subprogram for instance, in order to avoid name clashes.
1179 They do not serve any purpose for the debugger. */
1181 static void
1182 ada_remove_trailing_digits (const char *encoded, int *len)
1184 if (*len > 1 && isdigit (encoded[*len - 1]))
1186 int i = *len - 2;
1188 while (i > 0 && isdigit (encoded[i]))
1189 i--;
1190 if (i >= 0 && encoded[i] == '.')
1191 *len = i;
1192 else if (i >= 0 && encoded[i] == '$')
1193 *len = i;
1194 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1195 *len = i - 2;
1196 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1197 *len = i - 1;
1201 /* Remove the suffix introduced by the compiler for protected object
1202 subprograms. */
1204 static void
1205 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1207 /* Remove trailing N. */
1209 /* Protected entry subprograms are broken into two
1210 separate subprograms: The first one is unprotected, and has
1211 a 'N' suffix; the second is the protected version, and has
1212 the 'P' suffix. The second calls the first one after handling
1213 the protection. Since the P subprograms are internally generated,
1214 we leave these names undecoded, giving the user a clue that this
1215 entity is internal. */
1217 if (*len > 1
1218 && encoded[*len - 1] == 'N'
1219 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1220 *len = *len - 1;
1223 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1224 then update *LEN to remove the suffix and return the offset of the
1225 character just past the ".". Otherwise, return -1. */
1227 static int
1228 remove_compiler_suffix (const char *encoded, int *len)
1230 int offset = *len - 1;
1231 while (offset > 0 && isalpha (encoded[offset]))
1232 --offset;
1233 if (offset > 0 && encoded[offset] == '.')
1235 *len = offset;
1236 return offset + 1;
1238 return -1;
1241 /* Convert an ASCII hex string to a number. Reads exactly N
1242 characters from STR. Returns true on success, false if one of the
1243 digits was not a hex digit. */
1244 static bool
1245 convert_hex (const char *str, int n, uint32_t *out)
1247 uint32_t result = 0;
1249 for (int i = 0; i < n; ++i)
1251 if (!isxdigit (str[i]))
1252 return false;
1253 result <<= 4;
1254 result |= fromhex (str[i]);
1257 *out = result;
1258 return true;
1261 /* Convert a wide character from its ASCII hex representation in STR
1262 (consisting of exactly N characters) to the host encoding,
1263 appending the resulting bytes to OUT. If N==2 and the Ada source
1264 charset is not UTF-8, then hex refers to an encoding in the
1265 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1266 Return false and do not modify OUT on conversion failure. */
1267 static bool
1268 convert_from_hex_encoded (std::string &out, const char *str, int n)
1270 uint32_t value;
1272 if (!convert_hex (str, n, &value))
1273 return false;
1276 auto_obstack bytes;
1277 /* In the 'U' case, the hex digits encode the character in the
1278 Ada source charset. However, if the source charset is UTF-8,
1279 this really means it is a single-byte UTF-32 character. */
1280 if (n == 2 && ada_source_charset != ada_utf8)
1282 gdb_byte one_char = (gdb_byte) value;
1284 convert_between_encodings (ada_source_charset, host_charset (),
1285 &one_char,
1286 sizeof (one_char), sizeof (one_char),
1287 &bytes, translit_none);
1289 else
1290 convert_between_encodings (HOST_UTF32, host_charset (),
1291 (const gdb_byte *) &value,
1292 sizeof (value), sizeof (value),
1293 &bytes, translit_none);
1294 obstack_1grow (&bytes, '\0');
1295 out.append ((const char *) obstack_base (&bytes));
1297 catch (const gdb_exception &)
1299 /* On failure, the caller will just let the encoded form
1300 through, which seems basically reasonable. */
1301 return false;
1304 return true;
1307 /* See ada-lang.h. */
1309 std::string
1310 ada_decode (const char *encoded, bool wrap, bool operators)
1312 int i;
1313 int len0;
1314 const char *p;
1315 int at_start_name;
1316 std::string decoded;
1317 int suffix = -1;
1319 /* With function descriptors on PPC64, the value of a symbol named
1320 ".FN", if it exists, is the entry point of the function "FN". */
1321 if (encoded[0] == '.')
1322 encoded += 1;
1324 /* The name of the Ada main procedure starts with "_ada_".
1325 This prefix is not part of the decoded name, so skip this part
1326 if we see this prefix. */
1327 if (startswith (encoded, "_ada_"))
1328 encoded += 5;
1329 /* The "___ghost_" prefix is used for ghost entities. Normally
1330 these aren't preserved but when they are, it's useful to see
1331 them. */
1332 if (startswith (encoded, "___ghost_"))
1333 encoded += 9;
1335 /* If the name starts with '_', then it is not a properly encoded
1336 name, so do not attempt to decode it. Similarly, if the name
1337 starts with '<', the name should not be decoded. */
1338 if (encoded[0] == '_' || encoded[0] == '<')
1339 goto Suppress;
1341 len0 = strlen (encoded);
1343 suffix = remove_compiler_suffix (encoded, &len0);
1345 ada_remove_trailing_digits (encoded, &len0);
1346 ada_remove_po_subprogram_suffix (encoded, &len0);
1348 /* Remove the ___X.* suffix if present. Do not forget to verify that
1349 the suffix is located before the current "end" of ENCODED. We want
1350 to avoid re-matching parts of ENCODED that have previously been
1351 marked as discarded (by decrementing LEN0). */
1352 p = strstr (encoded, "___");
1353 if (p != NULL && p - encoded < len0 - 3)
1355 if (p[3] == 'X')
1356 len0 = p - encoded;
1357 else
1358 goto Suppress;
1361 /* Remove any trailing TKB suffix. It tells us that this symbol
1362 is for the body of a task, but that information does not actually
1363 appear in the decoded name. */
1365 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1366 len0 -= 3;
1368 /* Remove any trailing TB suffix. The TB suffix is slightly different
1369 from the TKB suffix because it is used for non-anonymous task
1370 bodies. */
1372 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1373 len0 -= 2;
1375 /* Remove trailing "B" suffixes. */
1376 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1378 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1379 len0 -= 1;
1381 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1383 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1385 i = len0 - 2;
1386 while ((i >= 0 && isdigit (encoded[i]))
1387 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1388 i -= 1;
1389 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1390 len0 = i - 1;
1391 else if (encoded[i] == '$')
1392 len0 = i;
1395 /* The first few characters that are not alphabetic are not part
1396 of any encoding we use, so we can copy them over verbatim. */
1398 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1399 decoded.push_back (encoded[i]);
1401 at_start_name = 1;
1402 while (i < len0)
1404 /* Is this a symbol function? */
1405 if (operators && at_start_name && encoded[i] == 'O')
1407 int k;
1409 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1411 int op_len = strlen (ada_opname_table[k].encoded);
1412 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1413 op_len - 1) == 0)
1414 && !isalnum (encoded[i + op_len]))
1416 decoded.append (ada_opname_table[k].decoded);
1417 at_start_name = 0;
1418 i += op_len;
1419 break;
1422 if (ada_opname_table[k].encoded != NULL)
1423 continue;
1425 at_start_name = 0;
1427 /* Replace "TK__" with "__", which will eventually be translated
1428 into "." (just below). */
1430 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1431 i += 2;
1433 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1434 be translated into "." (just below). These are internal names
1435 generated for anonymous blocks inside which our symbol is nested. */
1437 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1438 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1439 && isdigit (encoded [i+4]))
1441 int k = i + 5;
1443 while (k < len0 && isdigit (encoded[k]))
1444 k++; /* Skip any extra digit. */
1446 /* Double-check that the "__B_{DIGITS}+" sequence we found
1447 is indeed followed by "__". */
1448 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1449 i = k;
1452 /* Remove _E{DIGITS}+[sb] */
1454 /* Just as for protected object subprograms, there are 2 categories
1455 of subprograms created by the compiler for each entry. The first
1456 one implements the actual entry code, and has a suffix following
1457 the convention above; the second one implements the barrier and
1458 uses the same convention as above, except that the 'E' is replaced
1459 by a 'B'.
1461 Just as above, we do not decode the name of barrier functions
1462 to give the user a clue that the code he is debugging has been
1463 internally generated. */
1465 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1466 && isdigit (encoded[i+2]))
1468 int k = i + 3;
1470 while (k < len0 && isdigit (encoded[k]))
1471 k++;
1473 if (k < len0
1474 && (encoded[k] == 'b' || encoded[k] == 's'))
1476 k++;
1477 /* Just as an extra precaution, make sure that if this
1478 suffix is followed by anything else, it is a '_'.
1479 Otherwise, we matched this sequence by accident. */
1480 if (k == len0
1481 || (k < len0 && encoded[k] == '_'))
1482 i = k;
1486 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1487 the GNAT front-end in protected object subprograms. */
1489 if (i < len0 + 3
1490 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1492 /* Backtrack a bit up until we reach either the begining of
1493 the encoded name, or "__". Make sure that we only find
1494 digits or lowercase characters. */
1495 const char *ptr = encoded + i - 1;
1497 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1498 ptr--;
1499 if (ptr < encoded
1500 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1501 i++;
1504 if (i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1506 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1508 i += 3;
1509 continue;
1512 else if (i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1514 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1516 i += 5;
1517 continue;
1520 else if (i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1521 && isxdigit (encoded[i + 2]))
1523 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1525 i += 10;
1526 continue;
1530 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1532 /* This is a X[bn]* sequence not separated from the previous
1533 part of the name with a non-alpha-numeric character (in other
1534 words, immediately following an alpha-numeric character), then
1535 verify that it is placed at the end of the encoded name. If
1536 not, then the encoding is not valid and we should abort the
1537 decoding. Otherwise, just skip it, it is used in body-nested
1538 package names. */
1540 i += 1;
1541 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1542 if (i < len0)
1543 goto Suppress;
1545 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1547 /* Replace '__' by '.'. */
1548 decoded.push_back ('.');
1549 at_start_name = 1;
1550 i += 2;
1552 else
1554 /* It's a character part of the decoded name, so just copy it
1555 over. */
1556 decoded.push_back (encoded[i]);
1557 i += 1;
1561 /* Decoded names should never contain any uppercase character.
1562 Double-check this, and abort the decoding if we find one. */
1564 if (operators)
1566 for (i = 0; i < decoded.length(); ++i)
1567 if (isupper (decoded[i]) || decoded[i] == ' ')
1568 goto Suppress;
1571 /* If the compiler added a suffix, append it now. */
1572 if (suffix >= 0)
1573 decoded = decoded + "[" + &encoded[suffix] + "]";
1575 return decoded;
1577 Suppress:
1578 if (!wrap)
1579 return {};
1581 if (encoded[0] == '<')
1582 decoded = encoded;
1583 else
1584 decoded = '<' + std::string(encoded) + '>';
1585 return decoded;
1588 /* Table for keeping permanent unique copies of decoded names. Once
1589 allocated, names in this table are never released. While this is a
1590 storage leak, it should not be significant unless there are massive
1591 changes in the set of decoded names in successive versions of a
1592 symbol table loaded during a single session. */
1593 static struct htab *decoded_names_store;
1595 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1596 in the language-specific part of GSYMBOL, if it has not been
1597 previously computed. Tries to save the decoded name in the same
1598 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1599 in any case, the decoded symbol has a lifetime at least that of
1600 GSYMBOL).
1601 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1602 const, but nevertheless modified to a semantically equivalent form
1603 when a decoded name is cached in it. */
1605 const char *
1606 ada_decode_symbol (const struct general_symbol_info *arg)
1608 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1609 const char **resultp =
1610 &gsymbol->language_specific.demangled_name;
1612 if (!gsymbol->ada_mangled)
1614 std::string decoded = ada_decode (gsymbol->linkage_name ());
1615 struct obstack *obstack = gsymbol->language_specific.obstack;
1617 gsymbol->ada_mangled = 1;
1619 if (obstack != NULL)
1620 *resultp = obstack_strdup (obstack, decoded.c_str ());
1621 else
1623 /* Sometimes, we can't find a corresponding objfile, in
1624 which case, we put the result on the heap. Since we only
1625 decode when needed, we hope this usually does not cause a
1626 significant memory leak (FIXME). */
1628 char **slot = (char **) htab_find_slot (decoded_names_store,
1629 decoded.c_str (), INSERT);
1631 if (*slot == NULL)
1632 *slot = xstrdup (decoded.c_str ());
1633 *resultp = *slot;
1637 return *resultp;
1642 /* Arrays */
1644 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1645 generated by the GNAT compiler to describe the index type used
1646 for each dimension of an array, check whether it follows the latest
1647 known encoding. If not, fix it up to conform to the latest encoding.
1648 Otherwise, do nothing. This function also does nothing if
1649 INDEX_DESC_TYPE is NULL.
1651 The GNAT encoding used to describe the array index type evolved a bit.
1652 Initially, the information would be provided through the name of each
1653 field of the structure type only, while the type of these fields was
1654 described as unspecified and irrelevant. The debugger was then expected
1655 to perform a global type lookup using the name of that field in order
1656 to get access to the full index type description. Because these global
1657 lookups can be very expensive, the encoding was later enhanced to make
1658 the global lookup unnecessary by defining the field type as being
1659 the full index type description.
1661 The purpose of this routine is to allow us to support older versions
1662 of the compiler by detecting the use of the older encoding, and by
1663 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1664 we essentially replace each field's meaningless type by the associated
1665 index subtype). */
1667 void
1668 ada_fixup_array_indexes_type (struct type *index_desc_type)
1670 int i;
1672 if (index_desc_type == NULL)
1673 return;
1674 gdb_assert (index_desc_type->num_fields () > 0);
1676 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1677 to check one field only, no need to check them all). If not, return
1678 now.
1680 If our INDEX_DESC_TYPE was generated using the older encoding,
1681 the field type should be a meaningless integer type whose name
1682 is not equal to the field name. */
1683 if (index_desc_type->field (0).type ()->name () != NULL
1684 && strcmp (index_desc_type->field (0).type ()->name (),
1685 index_desc_type->field (0).name ()) == 0)
1686 return;
1688 /* Fixup each field of INDEX_DESC_TYPE. */
1689 for (i = 0; i < index_desc_type->num_fields (); i++)
1691 const char *name = index_desc_type->field (i).name ();
1692 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1694 if (raw_type)
1695 index_desc_type->field (i).set_type (raw_type);
1699 /* The desc_* routines return primitive portions of array descriptors
1700 (fat pointers). */
1702 /* The descriptor or array type, if any, indicated by TYPE; removes
1703 level of indirection, if needed. */
1705 static struct type *
1706 desc_base_type (struct type *type)
1708 if (type == NULL)
1709 return NULL;
1710 type = ada_check_typedef (type);
1711 if (type->code () == TYPE_CODE_TYPEDEF)
1712 type = ada_typedef_target_type (type);
1714 if (type != NULL
1715 && (type->code () == TYPE_CODE_PTR
1716 || type->code () == TYPE_CODE_REF))
1717 return ada_check_typedef (type->target_type ());
1718 else
1719 return type;
1722 /* True iff TYPE indicates a "thin" array pointer type. */
1724 static int
1725 is_thin_pntr (struct type *type)
1727 return
1728 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1729 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1732 /* The descriptor type for thin pointer type TYPE. */
1734 static struct type *
1735 thin_descriptor_type (struct type *type)
1737 struct type *base_type = desc_base_type (type);
1739 if (base_type == NULL)
1740 return NULL;
1741 if (is_suffix (ada_type_name (base_type), "___XVE"))
1742 return base_type;
1743 else
1745 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1747 if (alt_type == NULL)
1748 return base_type;
1749 else
1750 return alt_type;
1754 /* A pointer to the array data for thin-pointer value VAL. */
1756 static struct value *
1757 thin_data_pntr (struct value *val)
1759 struct type *type = ada_check_typedef (value_type (val));
1760 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1762 data_type = lookup_pointer_type (data_type);
1764 if (type->code () == TYPE_CODE_PTR)
1765 return value_cast (data_type, value_copy (val));
1766 else
1767 return value_from_longest (data_type, value_address (val));
1770 /* True iff TYPE indicates a "thick" array pointer type. */
1772 static int
1773 is_thick_pntr (struct type *type)
1775 type = desc_base_type (type);
1776 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1777 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1780 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1781 pointer to one, the type of its bounds data; otherwise, NULL. */
1783 static struct type *
1784 desc_bounds_type (struct type *type)
1786 struct type *r;
1788 type = desc_base_type (type);
1790 if (type == NULL)
1791 return NULL;
1792 else if (is_thin_pntr (type))
1794 type = thin_descriptor_type (type);
1795 if (type == NULL)
1796 return NULL;
1797 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1798 if (r != NULL)
1799 return ada_check_typedef (r);
1801 else if (type->code () == TYPE_CODE_STRUCT)
1803 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1804 if (r != NULL)
1805 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1807 return NULL;
1810 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1811 one, a pointer to its bounds data. Otherwise NULL. */
1813 static struct value *
1814 desc_bounds (struct value *arr)
1816 struct type *type = ada_check_typedef (value_type (arr));
1818 if (is_thin_pntr (type))
1820 struct type *bounds_type =
1821 desc_bounds_type (thin_descriptor_type (type));
1822 LONGEST addr;
1824 if (bounds_type == NULL)
1825 error (_("Bad GNAT array descriptor"));
1827 /* NOTE: The following calculation is not really kosher, but
1828 since desc_type is an XVE-encoded type (and shouldn't be),
1829 the correct calculation is a real pain. FIXME (and fix GCC). */
1830 if (type->code () == TYPE_CODE_PTR)
1831 addr = value_as_long (arr);
1832 else
1833 addr = value_address (arr);
1835 return
1836 value_from_longest (lookup_pointer_type (bounds_type),
1837 addr - bounds_type->length ());
1840 else if (is_thick_pntr (type))
1842 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1843 _("Bad GNAT array descriptor"));
1844 struct type *p_bounds_type = value_type (p_bounds);
1846 if (p_bounds_type
1847 && p_bounds_type->code () == TYPE_CODE_PTR)
1849 struct type *target_type = p_bounds_type->target_type ();
1851 if (target_type->is_stub ())
1852 p_bounds = value_cast (lookup_pointer_type
1853 (ada_check_typedef (target_type)),
1854 p_bounds);
1856 else
1857 error (_("Bad GNAT array descriptor"));
1859 return p_bounds;
1861 else
1862 return NULL;
1865 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1866 position of the field containing the address of the bounds data. */
1868 static int
1869 fat_pntr_bounds_bitpos (struct type *type)
1871 return desc_base_type (type)->field (1).loc_bitpos ();
1874 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1875 size of the field containing the address of the bounds data. */
1877 static int
1878 fat_pntr_bounds_bitsize (struct type *type)
1880 type = desc_base_type (type);
1882 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1883 return TYPE_FIELD_BITSIZE (type, 1);
1884 else
1885 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1888 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1889 pointer to one, the type of its array data (a array-with-no-bounds type);
1890 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1891 data. */
1893 static struct type *
1894 desc_data_target_type (struct type *type)
1896 type = desc_base_type (type);
1898 /* NOTE: The following is bogus; see comment in desc_bounds. */
1899 if (is_thin_pntr (type))
1900 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1901 else if (is_thick_pntr (type))
1903 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1905 if (data_type
1906 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1907 return ada_check_typedef (data_type->target_type ());
1910 return NULL;
1913 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1914 its array data. */
1916 static struct value *
1917 desc_data (struct value *arr)
1919 struct type *type = value_type (arr);
1921 if (is_thin_pntr (type))
1922 return thin_data_pntr (arr);
1923 else if (is_thick_pntr (type))
1924 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1925 _("Bad GNAT array descriptor"));
1926 else
1927 return NULL;
1931 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1932 position of the field containing the address of the data. */
1934 static int
1935 fat_pntr_data_bitpos (struct type *type)
1937 return desc_base_type (type)->field (0).loc_bitpos ();
1940 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1941 size of the field containing the address of the data. */
1943 static int
1944 fat_pntr_data_bitsize (struct type *type)
1946 type = desc_base_type (type);
1948 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1949 return TYPE_FIELD_BITSIZE (type, 0);
1950 else
1951 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1954 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1955 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1956 bound, if WHICH is 1. The first bound is I=1. */
1958 static struct value *
1959 desc_one_bound (struct value *bounds, int i, int which)
1961 char bound_name[20];
1962 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1963 which ? 'U' : 'L', i - 1);
1964 return value_struct_elt (&bounds, {}, bound_name, NULL,
1965 _("Bad GNAT array descriptor bounds"));
1968 /* If BOUNDS is an array-bounds structure type, return the bit position
1969 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1970 bound, if WHICH is 1. The first bound is I=1. */
1972 static int
1973 desc_bound_bitpos (struct type *type, int i, int which)
1975 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1978 /* If BOUNDS is an array-bounds structure type, return the bit field size
1979 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1980 bound, if WHICH is 1. The first bound is I=1. */
1982 static int
1983 desc_bound_bitsize (struct type *type, int i, int which)
1985 type = desc_base_type (type);
1987 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1988 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1989 else
1990 return 8 * type->field (2 * i + which - 2).type ()->length ();
1993 /* If TYPE is the type of an array-bounds structure, the type of its
1994 Ith bound (numbering from 1). Otherwise, NULL. */
1996 static struct type *
1997 desc_index_type (struct type *type, int i)
1999 type = desc_base_type (type);
2001 if (type->code () == TYPE_CODE_STRUCT)
2003 char bound_name[20];
2004 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2005 return lookup_struct_elt_type (type, bound_name, 1);
2007 else
2008 return NULL;
2011 /* The number of index positions in the array-bounds type TYPE.
2012 Return 0 if TYPE is NULL. */
2014 static int
2015 desc_arity (struct type *type)
2017 type = desc_base_type (type);
2019 if (type != NULL)
2020 return type->num_fields () / 2;
2021 return 0;
2024 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2025 an array descriptor type (representing an unconstrained array
2026 type). */
2028 static int
2029 ada_is_direct_array_type (struct type *type)
2031 if (type == NULL)
2032 return 0;
2033 type = ada_check_typedef (type);
2034 return (type->code () == TYPE_CODE_ARRAY
2035 || ada_is_array_descriptor_type (type));
2038 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2039 * to one. */
2041 static int
2042 ada_is_array_type (struct type *type)
2044 while (type != NULL
2045 && (type->code () == TYPE_CODE_PTR
2046 || type->code () == TYPE_CODE_REF))
2047 type = type->target_type ();
2048 return ada_is_direct_array_type (type);
2051 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2054 ada_is_simple_array_type (struct type *type)
2056 if (type == NULL)
2057 return 0;
2058 type = ada_check_typedef (type);
2059 return (type->code () == TYPE_CODE_ARRAY
2060 || (type->code () == TYPE_CODE_PTR
2061 && (ada_check_typedef (type->target_type ())->code ()
2062 == TYPE_CODE_ARRAY)));
2065 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2068 ada_is_array_descriptor_type (struct type *type)
2070 struct type *data_type = desc_data_target_type (type);
2072 if (type == NULL)
2073 return 0;
2074 type = ada_check_typedef (type);
2075 return (data_type != NULL
2076 && data_type->code () == TYPE_CODE_ARRAY
2077 && desc_arity (desc_bounds_type (type)) > 0);
2080 /* Non-zero iff type is a partially mal-formed GNAT array
2081 descriptor. FIXME: This is to compensate for some problems with
2082 debugging output from GNAT. Re-examine periodically to see if it
2083 is still needed. */
2086 ada_is_bogus_array_descriptor (struct type *type)
2088 return
2089 type != NULL
2090 && type->code () == TYPE_CODE_STRUCT
2091 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
2092 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
2093 && !ada_is_array_descriptor_type (type);
2097 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2098 (fat pointer) returns the type of the array data described---specifically,
2099 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2100 in from the descriptor; otherwise, they are left unspecified. If
2101 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2102 returns NULL. The result is simply the type of ARR if ARR is not
2103 a descriptor. */
2105 static struct type *
2106 ada_type_of_array (struct value *arr, int bounds)
2108 if (ada_is_constrained_packed_array_type (value_type (arr)))
2109 return decode_constrained_packed_array_type (value_type (arr));
2111 if (!ada_is_array_descriptor_type (value_type (arr)))
2112 return value_type (arr);
2114 if (!bounds)
2116 struct type *array_type =
2117 ada_check_typedef (desc_data_target_type (value_type (arr)));
2119 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
2120 TYPE_FIELD_BITSIZE (array_type, 0) =
2121 decode_packed_array_bitsize (value_type (arr));
2123 return array_type;
2125 else
2127 struct type *elt_type;
2128 int arity;
2129 struct value *descriptor;
2131 elt_type = ada_array_element_type (value_type (arr), -1);
2132 arity = ada_array_arity (value_type (arr));
2134 if (elt_type == NULL || arity == 0)
2135 return ada_check_typedef (value_type (arr));
2137 descriptor = desc_bounds (arr);
2138 if (value_as_long (descriptor) == 0)
2139 return NULL;
2140 while (arity > 0)
2142 struct type *range_type = alloc_type_copy (value_type (arr));
2143 struct type *array_type = alloc_type_copy (value_type (arr));
2144 struct value *low = desc_one_bound (descriptor, arity, 0);
2145 struct value *high = desc_one_bound (descriptor, arity, 1);
2147 arity -= 1;
2148 create_static_range_type (range_type, value_type (low),
2149 longest_to_int (value_as_long (low)),
2150 longest_to_int (value_as_long (high)));
2151 elt_type = create_array_type (array_type, elt_type, range_type);
2153 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
2155 /* We need to store the element packed bitsize, as well as
2156 recompute the array size, because it was previously
2157 computed based on the unpacked element size. */
2158 LONGEST lo = value_as_long (low);
2159 LONGEST hi = value_as_long (high);
2161 TYPE_FIELD_BITSIZE (elt_type, 0) =
2162 decode_packed_array_bitsize (value_type (arr));
2163 /* If the array has no element, then the size is already
2164 zero, and does not need to be recomputed. */
2165 if (lo < hi)
2167 int array_bitsize =
2168 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
2170 array_type->set_length ((array_bitsize + 7) / 8);
2175 return lookup_pointer_type (elt_type);
2179 /* If ARR does not represent an array, returns ARR unchanged.
2180 Otherwise, returns either a standard GDB array with bounds set
2181 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2182 GDB array. Returns NULL if ARR is a null fat pointer. */
2184 struct value *
2185 ada_coerce_to_simple_array_ptr (struct value *arr)
2187 if (ada_is_array_descriptor_type (value_type (arr)))
2189 struct type *arrType = ada_type_of_array (arr, 1);
2191 if (arrType == NULL)
2192 return NULL;
2193 return value_cast (arrType, value_copy (desc_data (arr)));
2195 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2196 return decode_constrained_packed_array (arr);
2197 else
2198 return arr;
2201 /* If ARR does not represent an array, returns ARR unchanged.
2202 Otherwise, returns a standard GDB array describing ARR (which may
2203 be ARR itself if it already is in the proper form). */
2205 struct value *
2206 ada_coerce_to_simple_array (struct value *arr)
2208 if (ada_is_array_descriptor_type (value_type (arr)))
2210 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2212 if (arrVal == NULL)
2213 error (_("Bounds unavailable for null array pointer."));
2214 return value_ind (arrVal);
2216 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2217 return decode_constrained_packed_array (arr);
2218 else
2219 return arr;
2222 /* If TYPE represents a GNAT array type, return it translated to an
2223 ordinary GDB array type (possibly with BITSIZE fields indicating
2224 packing). For other types, is the identity. */
2226 struct type *
2227 ada_coerce_to_simple_array_type (struct type *type)
2229 if (ada_is_constrained_packed_array_type (type))
2230 return decode_constrained_packed_array_type (type);
2232 if (ada_is_array_descriptor_type (type))
2233 return ada_check_typedef (desc_data_target_type (type));
2235 return type;
2238 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2240 static int
2241 ada_is_gnat_encoded_packed_array_type (struct type *type)
2243 if (type == NULL)
2244 return 0;
2245 type = desc_base_type (type);
2246 type = ada_check_typedef (type);
2247 return
2248 ada_type_name (type) != NULL
2249 && strstr (ada_type_name (type), "___XP") != NULL;
2252 /* Non-zero iff TYPE represents a standard GNAT constrained
2253 packed-array type. */
2256 ada_is_constrained_packed_array_type (struct type *type)
2258 return ada_is_gnat_encoded_packed_array_type (type)
2259 && !ada_is_array_descriptor_type (type);
2262 /* Non-zero iff TYPE represents an array descriptor for a
2263 unconstrained packed-array type. */
2265 static int
2266 ada_is_unconstrained_packed_array_type (struct type *type)
2268 if (!ada_is_array_descriptor_type (type))
2269 return 0;
2271 if (ada_is_gnat_encoded_packed_array_type (type))
2272 return 1;
2274 /* If we saw GNAT encodings, then the above code is sufficient.
2275 However, with minimal encodings, we will just have a thick
2276 pointer instead. */
2277 if (is_thick_pntr (type))
2279 type = desc_base_type (type);
2280 /* The structure's first field is a pointer to an array, so this
2281 fetches the array type. */
2282 type = type->field (0).type ()->target_type ();
2283 if (type->code () == TYPE_CODE_TYPEDEF)
2284 type = ada_typedef_target_type (type);
2285 /* Now we can see if the array elements are packed. */
2286 return TYPE_FIELD_BITSIZE (type, 0) > 0;
2289 return 0;
2292 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2293 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2295 static bool
2296 ada_is_any_packed_array_type (struct type *type)
2298 return (ada_is_constrained_packed_array_type (type)
2299 || (type->code () == TYPE_CODE_ARRAY
2300 && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
2303 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2304 return the size of its elements in bits. */
2306 static long
2307 decode_packed_array_bitsize (struct type *type)
2309 const char *raw_name;
2310 const char *tail;
2311 long bits;
2313 /* Access to arrays implemented as fat pointers are encoded as a typedef
2314 of the fat pointer type. We need the name of the fat pointer type
2315 to do the decoding, so strip the typedef layer. */
2316 if (type->code () == TYPE_CODE_TYPEDEF)
2317 type = ada_typedef_target_type (type);
2319 raw_name = ada_type_name (ada_check_typedef (type));
2320 if (!raw_name)
2321 raw_name = ada_type_name (desc_base_type (type));
2323 if (!raw_name)
2324 return 0;
2326 tail = strstr (raw_name, "___XP");
2327 if (tail == nullptr)
2329 gdb_assert (is_thick_pntr (type));
2330 /* The structure's first field is a pointer to an array, so this
2331 fetches the array type. */
2332 type = type->field (0).type ()->target_type ();
2333 /* Now we can see if the array elements are packed. */
2334 return TYPE_FIELD_BITSIZE (type, 0);
2337 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2339 lim_warning
2340 (_("could not understand bit size information on packed array"));
2341 return 0;
2344 return bits;
2347 /* Given that TYPE is a standard GDB array type with all bounds filled
2348 in, and that the element size of its ultimate scalar constituents
2349 (that is, either its elements, or, if it is an array of arrays, its
2350 elements' elements, etc.) is *ELT_BITS, return an identical type,
2351 but with the bit sizes of its elements (and those of any
2352 constituent arrays) recorded in the BITSIZE components of its
2353 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2354 in bits.
2356 Note that, for arrays whose index type has an XA encoding where
2357 a bound references a record discriminant, getting that discriminant,
2358 and therefore the actual value of that bound, is not possible
2359 because none of the given parameters gives us access to the record.
2360 This function assumes that it is OK in the context where it is being
2361 used to return an array whose bounds are still dynamic and where
2362 the length is arbitrary. */
2364 static struct type *
2365 constrained_packed_array_type (struct type *type, long *elt_bits)
2367 struct type *new_elt_type;
2368 struct type *new_type;
2369 struct type *index_type_desc;
2370 struct type *index_type;
2371 LONGEST low_bound, high_bound;
2373 type = ada_check_typedef (type);
2374 if (type->code () != TYPE_CODE_ARRAY)
2375 return type;
2377 index_type_desc = ada_find_parallel_type (type, "___XA");
2378 if (index_type_desc)
2379 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2380 NULL);
2381 else
2382 index_type = type->index_type ();
2384 new_type = alloc_type_copy (type);
2385 new_elt_type =
2386 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2387 elt_bits);
2388 create_array_type (new_type, new_elt_type, index_type);
2389 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2390 new_type->set_name (ada_type_name (type));
2392 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2393 && is_dynamic_type (check_typedef (index_type)))
2394 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2395 low_bound = high_bound = 0;
2396 if (high_bound < low_bound)
2398 *elt_bits = 0;
2399 new_type->set_length (0);
2401 else
2403 *elt_bits *= (high_bound - low_bound + 1);
2404 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2407 new_type->set_is_fixed_instance (true);
2408 return new_type;
2411 /* The array type encoded by TYPE, where
2412 ada_is_constrained_packed_array_type (TYPE). */
2414 static struct type *
2415 decode_constrained_packed_array_type (struct type *type)
2417 const char *raw_name = ada_type_name (ada_check_typedef (type));
2418 char *name;
2419 const char *tail;
2420 struct type *shadow_type;
2421 long bits;
2423 if (!raw_name)
2424 raw_name = ada_type_name (desc_base_type (type));
2426 if (!raw_name)
2427 return NULL;
2429 name = (char *) alloca (strlen (raw_name) + 1);
2430 tail = strstr (raw_name, "___XP");
2431 type = desc_base_type (type);
2433 memcpy (name, raw_name, tail - raw_name);
2434 name[tail - raw_name] = '\000';
2436 shadow_type = ada_find_parallel_type_with_name (type, name);
2438 if (shadow_type == NULL)
2440 lim_warning (_("could not find bounds information on packed array"));
2441 return NULL;
2443 shadow_type = check_typedef (shadow_type);
2445 if (shadow_type->code () != TYPE_CODE_ARRAY)
2447 lim_warning (_("could not understand bounds "
2448 "information on packed array"));
2449 return NULL;
2452 bits = decode_packed_array_bitsize (type);
2453 return constrained_packed_array_type (shadow_type, &bits);
2456 /* Helper function for decode_constrained_packed_array. Set the field
2457 bitsize on a series of packed arrays. Returns the number of
2458 elements in TYPE. */
2460 static LONGEST
2461 recursively_update_array_bitsize (struct type *type)
2463 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2465 LONGEST low, high;
2466 if (!get_discrete_bounds (type->index_type (), &low, &high)
2467 || low > high)
2468 return 0;
2469 LONGEST our_len = high - low + 1;
2471 struct type *elt_type = type->target_type ();
2472 if (elt_type->code () == TYPE_CODE_ARRAY)
2474 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2475 LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2476 TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2478 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2479 / HOST_CHAR_BIT));
2482 return our_len;
2485 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2486 array, returns a simple array that denotes that array. Its type is a
2487 standard GDB array type except that the BITSIZEs of the array
2488 target types are set to the number of bits in each element, and the
2489 type length is set appropriately. */
2491 static struct value *
2492 decode_constrained_packed_array (struct value *arr)
2494 struct type *type;
2496 /* If our value is a pointer, then dereference it. Likewise if
2497 the value is a reference. Make sure that this operation does not
2498 cause the target type to be fixed, as this would indirectly cause
2499 this array to be decoded. The rest of the routine assumes that
2500 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2501 and "value_ind" routines to perform the dereferencing, as opposed
2502 to using "ada_coerce_ref" or "ada_value_ind". */
2503 arr = coerce_ref (arr);
2504 if (ada_check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2505 arr = value_ind (arr);
2507 type = decode_constrained_packed_array_type (value_type (arr));
2508 if (type == NULL)
2510 error (_("can't unpack array"));
2511 return NULL;
2514 /* Decoding the packed array type could not correctly set the field
2515 bitsizes for any dimension except the innermost, because the
2516 bounds may be variable and were not passed to that function. So,
2517 we further resolve the array bounds here and then update the
2518 sizes. */
2519 const gdb_byte *valaddr = value_contents_for_printing (arr).data ();
2520 CORE_ADDR address = value_address (arr);
2521 gdb::array_view<const gdb_byte> view
2522 = gdb::make_array_view (valaddr, type->length ());
2523 type = resolve_dynamic_type (type, view, address);
2524 recursively_update_array_bitsize (type);
2526 if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2527 && ada_is_modular_type (value_type (arr)))
2529 /* This is a (right-justified) modular type representing a packed
2530 array with no wrapper. In order to interpret the value through
2531 the (left-justified) packed array type we just built, we must
2532 first left-justify it. */
2533 int bit_size, bit_pos;
2534 ULONGEST mod;
2536 mod = ada_modulus (value_type (arr)) - 1;
2537 bit_size = 0;
2538 while (mod > 0)
2540 bit_size += 1;
2541 mod >>= 1;
2543 bit_pos = HOST_CHAR_BIT * value_type (arr)->length () - bit_size;
2544 arr = ada_value_primitive_packed_val (arr, NULL,
2545 bit_pos / HOST_CHAR_BIT,
2546 bit_pos % HOST_CHAR_BIT,
2547 bit_size,
2548 type);
2551 return coerce_unspec_val_to_type (arr, type);
2555 /* The value of the element of packed array ARR at the ARITY indices
2556 given in IND. ARR must be a simple array. */
2558 static struct value *
2559 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2561 int i;
2562 int bits, elt_off, bit_off;
2563 long elt_total_bit_offset;
2564 struct type *elt_type;
2565 struct value *v;
2567 bits = 0;
2568 elt_total_bit_offset = 0;
2569 elt_type = ada_check_typedef (value_type (arr));
2570 for (i = 0; i < arity; i += 1)
2572 if (elt_type->code () != TYPE_CODE_ARRAY
2573 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2574 error
2575 (_("attempt to do packed indexing of "
2576 "something other than a packed array"));
2577 else
2579 struct type *range_type = elt_type->index_type ();
2580 LONGEST lowerbound, upperbound;
2581 LONGEST idx;
2583 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2585 lim_warning (_("don't know bounds of array"));
2586 lowerbound = upperbound = 0;
2589 idx = pos_atr (ind[i]);
2590 if (idx < lowerbound || idx > upperbound)
2591 lim_warning (_("packed array index %ld out of bounds"),
2592 (long) idx);
2593 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2594 elt_total_bit_offset += (idx - lowerbound) * bits;
2595 elt_type = ada_check_typedef (elt_type->target_type ());
2598 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2599 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2601 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2602 bits, elt_type);
2603 return v;
2606 /* Non-zero iff TYPE includes negative integer values. */
2608 static int
2609 has_negatives (struct type *type)
2611 switch (type->code ())
2613 default:
2614 return 0;
2615 case TYPE_CODE_INT:
2616 return !type->is_unsigned ();
2617 case TYPE_CODE_RANGE:
2618 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2622 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2623 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2624 the unpacked buffer.
2626 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2627 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2629 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2630 zero otherwise.
2632 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2634 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2636 static void
2637 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2638 gdb_byte *unpacked, int unpacked_len,
2639 int is_big_endian, int is_signed_type,
2640 int is_scalar)
2642 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2643 int src_idx; /* Index into the source area */
2644 int src_bytes_left; /* Number of source bytes left to process. */
2645 int srcBitsLeft; /* Number of source bits left to move */
2646 int unusedLS; /* Number of bits in next significant
2647 byte of source that are unused */
2649 int unpacked_idx; /* Index into the unpacked buffer */
2650 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2652 unsigned long accum; /* Staging area for bits being transferred */
2653 int accumSize; /* Number of meaningful bits in accum */
2654 unsigned char sign;
2656 /* Transmit bytes from least to most significant; delta is the direction
2657 the indices move. */
2658 int delta = is_big_endian ? -1 : 1;
2660 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2661 bits from SRC. .*/
2662 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2663 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2664 bit_size, unpacked_len);
2666 srcBitsLeft = bit_size;
2667 src_bytes_left = src_len;
2668 unpacked_bytes_left = unpacked_len;
2669 sign = 0;
2671 if (is_big_endian)
2673 src_idx = src_len - 1;
2674 if (is_signed_type
2675 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2676 sign = ~0;
2678 unusedLS =
2679 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2680 % HOST_CHAR_BIT;
2682 if (is_scalar)
2684 accumSize = 0;
2685 unpacked_idx = unpacked_len - 1;
2687 else
2689 /* Non-scalar values must be aligned at a byte boundary... */
2690 accumSize =
2691 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2692 /* ... And are placed at the beginning (most-significant) bytes
2693 of the target. */
2694 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2695 unpacked_bytes_left = unpacked_idx + 1;
2698 else
2700 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2702 src_idx = unpacked_idx = 0;
2703 unusedLS = bit_offset;
2704 accumSize = 0;
2706 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2707 sign = ~0;
2710 accum = 0;
2711 while (src_bytes_left > 0)
2713 /* Mask for removing bits of the next source byte that are not
2714 part of the value. */
2715 unsigned int unusedMSMask =
2716 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2718 /* Sign-extend bits for this byte. */
2719 unsigned int signMask = sign & ~unusedMSMask;
2721 accum |=
2722 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2723 accumSize += HOST_CHAR_BIT - unusedLS;
2724 if (accumSize >= HOST_CHAR_BIT)
2726 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2727 accumSize -= HOST_CHAR_BIT;
2728 accum >>= HOST_CHAR_BIT;
2729 unpacked_bytes_left -= 1;
2730 unpacked_idx += delta;
2732 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2733 unusedLS = 0;
2734 src_bytes_left -= 1;
2735 src_idx += delta;
2737 while (unpacked_bytes_left > 0)
2739 accum |= sign << accumSize;
2740 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2741 accumSize -= HOST_CHAR_BIT;
2742 if (accumSize < 0)
2743 accumSize = 0;
2744 accum >>= HOST_CHAR_BIT;
2745 unpacked_bytes_left -= 1;
2746 unpacked_idx += delta;
2750 /* Create a new value of type TYPE from the contents of OBJ starting
2751 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2752 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2753 assigning through the result will set the field fetched from.
2754 VALADDR is ignored unless OBJ is NULL, in which case,
2755 VALADDR+OFFSET must address the start of storage containing the
2756 packed value. The value returned in this case is never an lval.
2757 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2759 struct value *
2760 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2761 long offset, int bit_offset, int bit_size,
2762 struct type *type)
2764 struct value *v;
2765 const gdb_byte *src; /* First byte containing data to unpack */
2766 gdb_byte *unpacked;
2767 const int is_scalar = is_scalar_type (type);
2768 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2769 gdb::byte_vector staging;
2771 type = ada_check_typedef (type);
2773 if (obj == NULL)
2774 src = valaddr + offset;
2775 else
2776 src = value_contents (obj).data () + offset;
2778 if (is_dynamic_type (type))
2780 /* The length of TYPE might by dynamic, so we need to resolve
2781 TYPE in order to know its actual size, which we then use
2782 to create the contents buffer of the value we return.
2783 The difficulty is that the data containing our object is
2784 packed, and therefore maybe not at a byte boundary. So, what
2785 we do, is unpack the data into a byte-aligned buffer, and then
2786 use that buffer as our object's value for resolving the type. */
2787 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2788 staging.resize (staging_len);
2790 ada_unpack_from_contents (src, bit_offset, bit_size,
2791 staging.data (), staging.size (),
2792 is_big_endian, has_negatives (type),
2793 is_scalar);
2794 type = resolve_dynamic_type (type, staging, 0);
2795 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2797 /* This happens when the length of the object is dynamic,
2798 and is actually smaller than the space reserved for it.
2799 For instance, in an array of variant records, the bit_size
2800 we're given is the array stride, which is constant and
2801 normally equal to the maximum size of its element.
2802 But, in reality, each element only actually spans a portion
2803 of that stride. */
2804 bit_size = type->length () * HOST_CHAR_BIT;
2808 if (obj == NULL)
2810 v = allocate_value (type);
2811 src = valaddr + offset;
2813 else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2815 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2816 gdb_byte *buf;
2818 v = value_at (type, value_address (obj) + offset);
2819 buf = (gdb_byte *) alloca (src_len);
2820 read_memory (value_address (v), buf, src_len);
2821 src = buf;
2823 else
2825 v = allocate_value (type);
2826 src = value_contents (obj).data () + offset;
2829 if (obj != NULL)
2831 long new_offset = offset;
2833 set_value_component_location (v, obj);
2834 set_value_bitpos (v, bit_offset + value_bitpos (obj));
2835 set_value_bitsize (v, bit_size);
2836 if (value_bitpos (v) >= HOST_CHAR_BIT)
2838 ++new_offset;
2839 set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2841 set_value_offset (v, new_offset);
2843 /* Also set the parent value. This is needed when trying to
2844 assign a new value (in inferior memory). */
2845 set_value_parent (v, obj);
2847 else
2848 set_value_bitsize (v, bit_size);
2849 unpacked = value_contents_writeable (v).data ();
2851 if (bit_size == 0)
2853 memset (unpacked, 0, type->length ());
2854 return v;
2857 if (staging.size () == type->length ())
2859 /* Small short-cut: If we've unpacked the data into a buffer
2860 of the same size as TYPE's length, then we can reuse that,
2861 instead of doing the unpacking again. */
2862 memcpy (unpacked, staging.data (), staging.size ());
2864 else
2865 ada_unpack_from_contents (src, bit_offset, bit_size,
2866 unpacked, type->length (),
2867 is_big_endian, has_negatives (type), is_scalar);
2869 return v;
2872 /* Store the contents of FROMVAL into the location of TOVAL.
2873 Return a new value with the location of TOVAL and contents of
2874 FROMVAL. Handles assignment into packed fields that have
2875 floating-point or non-scalar types. */
2877 static struct value *
2878 ada_value_assign (struct value *toval, struct value *fromval)
2880 struct type *type = value_type (toval);
2881 int bits = value_bitsize (toval);
2883 toval = ada_coerce_ref (toval);
2884 fromval = ada_coerce_ref (fromval);
2886 if (ada_is_direct_array_type (value_type (toval)))
2887 toval = ada_coerce_to_simple_array (toval);
2888 if (ada_is_direct_array_type (value_type (fromval)))
2889 fromval = ada_coerce_to_simple_array (fromval);
2891 if (!deprecated_value_modifiable (toval))
2892 error (_("Left operand of assignment is not a modifiable lvalue."));
2894 if (VALUE_LVAL (toval) == lval_memory
2895 && bits > 0
2896 && (type->code () == TYPE_CODE_FLT
2897 || type->code () == TYPE_CODE_STRUCT))
2899 int len = (value_bitpos (toval)
2900 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2901 int from_size;
2902 gdb_byte *buffer = (gdb_byte *) alloca (len);
2903 struct value *val;
2904 CORE_ADDR to_addr = value_address (toval);
2906 if (type->code () == TYPE_CODE_FLT)
2907 fromval = value_cast (type, fromval);
2909 read_memory (to_addr, buffer, len);
2910 from_size = value_bitsize (fromval);
2911 if (from_size == 0)
2912 from_size = value_type (fromval)->length () * TARGET_CHAR_BIT;
2914 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2915 ULONGEST from_offset = 0;
2916 if (is_big_endian && is_scalar_type (value_type (fromval)))
2917 from_offset = from_size - bits;
2918 copy_bitwise (buffer, value_bitpos (toval),
2919 value_contents (fromval).data (), from_offset,
2920 bits, is_big_endian);
2921 write_memory_with_notification (to_addr, buffer, len);
2923 val = value_copy (toval);
2924 memcpy (value_contents_raw (val).data (),
2925 value_contents (fromval).data (),
2926 type->length ());
2927 deprecated_set_value_type (val, type);
2929 return val;
2932 return value_assign (toval, fromval);
2936 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2937 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2938 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2939 COMPONENT, and not the inferior's memory. The current contents
2940 of COMPONENT are ignored.
2942 Although not part of the initial design, this function also works
2943 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2944 had a null address, and COMPONENT had an address which is equal to
2945 its offset inside CONTAINER. */
2947 static void
2948 value_assign_to_component (struct value *container, struct value *component,
2949 struct value *val)
2951 LONGEST offset_in_container =
2952 (LONGEST) (value_address (component) - value_address (container));
2953 int bit_offset_in_container =
2954 value_bitpos (component) - value_bitpos (container);
2955 int bits;
2957 val = value_cast (value_type (component), val);
2959 if (value_bitsize (component) == 0)
2960 bits = TARGET_CHAR_BIT * value_type (component)->length ();
2961 else
2962 bits = value_bitsize (component);
2964 if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2966 int src_offset;
2968 if (is_scalar_type (check_typedef (value_type (component))))
2969 src_offset
2970 = value_type (component)->length () * TARGET_CHAR_BIT - bits;
2971 else
2972 src_offset = 0;
2973 copy_bitwise ((value_contents_writeable (container).data ()
2974 + offset_in_container),
2975 value_bitpos (container) + bit_offset_in_container,
2976 value_contents (val).data (), src_offset, bits, 1);
2978 else
2979 copy_bitwise ((value_contents_writeable (container).data ()
2980 + offset_in_container),
2981 value_bitpos (container) + bit_offset_in_container,
2982 value_contents (val).data (), 0, bits, 0);
2985 /* Determine if TYPE is an access to an unconstrained array. */
2987 bool
2988 ada_is_access_to_unconstrained_array (struct type *type)
2990 return (type->code () == TYPE_CODE_TYPEDEF
2991 && is_thick_pntr (ada_typedef_target_type (type)));
2994 /* The value of the element of array ARR at the ARITY indices given in IND.
2995 ARR may be either a simple array, GNAT array descriptor, or pointer
2996 thereto. */
2998 struct value *
2999 ada_value_subscript (struct value *arr, int arity, struct value **ind)
3001 int k;
3002 struct value *elt;
3003 struct type *elt_type;
3005 elt = ada_coerce_to_simple_array (arr);
3007 elt_type = ada_check_typedef (value_type (elt));
3008 if (elt_type->code () == TYPE_CODE_ARRAY
3009 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
3010 return value_subscript_packed (elt, arity, ind);
3012 for (k = 0; k < arity; k += 1)
3014 struct type *saved_elt_type = elt_type->target_type ();
3016 if (elt_type->code () != TYPE_CODE_ARRAY)
3017 error (_("too many subscripts (%d expected)"), k);
3019 elt = value_subscript (elt, pos_atr (ind[k]));
3021 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3022 && value_type (elt)->code () != TYPE_CODE_TYPEDEF)
3024 /* The element is a typedef to an unconstrained array,
3025 except that the value_subscript call stripped the
3026 typedef layer. The typedef layer is GNAT's way to
3027 specify that the element is, at the source level, an
3028 access to the unconstrained array, rather than the
3029 unconstrained array. So, we need to restore that
3030 typedef layer, which we can do by forcing the element's
3031 type back to its original type. Otherwise, the returned
3032 value is going to be printed as the array, rather
3033 than as an access. Another symptom of the same issue
3034 would be that an expression trying to dereference the
3035 element would also be improperly rejected. */
3036 deprecated_set_value_type (elt, saved_elt_type);
3039 elt_type = ada_check_typedef (value_type (elt));
3042 return elt;
3045 /* Assuming ARR is a pointer to a GDB array, the value of the element
3046 of *ARR at the ARITY indices given in IND.
3047 Does not read the entire array into memory.
3049 Note: Unlike what one would expect, this function is used instead of
3050 ada_value_subscript for basically all non-packed array types. The reason
3051 for this is that a side effect of doing our own pointer arithmetics instead
3052 of relying on value_subscript is that there is no implicit typedef peeling.
3053 This is important for arrays of array accesses, where it allows us to
3054 preserve the fact that the array's element is an array access, where the
3055 access part os encoded in a typedef layer. */
3057 static struct value *
3058 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3060 int k;
3061 struct value *array_ind = ada_value_ind (arr);
3062 struct type *type
3063 = check_typedef (value_enclosing_type (array_ind));
3065 if (type->code () == TYPE_CODE_ARRAY
3066 && TYPE_FIELD_BITSIZE (type, 0) > 0)
3067 return value_subscript_packed (array_ind, arity, ind);
3069 for (k = 0; k < arity; k += 1)
3071 LONGEST lwb, upb;
3073 if (type->code () != TYPE_CODE_ARRAY)
3074 error (_("too many subscripts (%d expected)"), k);
3075 arr = value_cast (lookup_pointer_type (type->target_type ()),
3076 value_copy (arr));
3077 get_discrete_bounds (type->index_type (), &lwb, &upb);
3078 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3079 type = type->target_type ();
3082 return value_ind (arr);
3085 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3086 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3087 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3088 this array is LOW, as per Ada rules. */
3089 static struct value *
3090 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3091 int low, int high)
3093 struct type *type0 = ada_check_typedef (type);
3094 struct type *base_index_type = type0->index_type ()->target_type ();
3095 struct type *index_type
3096 = create_static_range_type (NULL, base_index_type, low, high);
3097 struct type *slice_type = create_array_type_with_stride
3098 (NULL, type0->target_type (), index_type,
3099 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3100 TYPE_FIELD_BITSIZE (type0, 0));
3101 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3102 gdb::optional<LONGEST> base_low_pos, low_pos;
3103 CORE_ADDR base;
3105 low_pos = discrete_position (base_index_type, low);
3106 base_low_pos = discrete_position (base_index_type, base_low);
3108 if (!low_pos.has_value () || !base_low_pos.has_value ())
3110 warning (_("unable to get positions in slice, use bounds instead"));
3111 low_pos = low;
3112 base_low_pos = base_low;
3115 ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
3116 if (stride == 0)
3117 stride = type0->target_type ()->length ();
3119 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3120 return value_at_lazy (slice_type, base);
3124 static struct value *
3125 ada_value_slice (struct value *array, int low, int high)
3127 struct type *type = ada_check_typedef (value_type (array));
3128 struct type *base_index_type = type->index_type ()->target_type ();
3129 struct type *index_type
3130 = create_static_range_type (NULL, type->index_type (), low, high);
3131 struct type *slice_type = create_array_type_with_stride
3132 (NULL, type->target_type (), index_type,
3133 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3134 TYPE_FIELD_BITSIZE (type, 0));
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 (LONGEST) - 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
3320 (LONGEST) (which == 0
3321 ? ada_discrete_type_low_bound (index_type)
3322 : ada_discrete_type_high_bound (index_type));
3325 /* Given that arr is an array value, returns the lower bound of the
3326 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3327 WHICH is 1. This routine will also work for arrays with bounds
3328 supplied by run-time quantities other than discriminants. */
3330 static LONGEST
3331 ada_array_bound (struct value *arr, int n, int which)
3333 struct type *arr_type;
3335 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3336 arr = value_ind (arr);
3337 arr_type = value_enclosing_type (arr);
3339 if (ada_is_constrained_packed_array_type (arr_type))
3340 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3341 else if (ada_is_simple_array_type (arr_type))
3342 return ada_array_bound_from_type (arr_type, n, which);
3343 else
3344 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3347 /* Given that arr is an array value, returns the length of the
3348 nth index. This routine will also work for arrays with bounds
3349 supplied by run-time quantities other than discriminants.
3350 Does not work for arrays indexed by enumeration types with representation
3351 clauses at the moment. */
3353 static LONGEST
3354 ada_array_length (struct value *arr, int n)
3356 struct type *arr_type, *index_type;
3357 int low, high;
3359 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3360 arr = value_ind (arr);
3361 arr_type = value_enclosing_type (arr);
3363 if (ada_is_constrained_packed_array_type (arr_type))
3364 return ada_array_length (decode_constrained_packed_array (arr), n);
3366 if (ada_is_simple_array_type (arr_type))
3368 low = ada_array_bound_from_type (arr_type, n, 0);
3369 high = ada_array_bound_from_type (arr_type, n, 1);
3371 else
3373 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3374 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3377 arr_type = check_typedef (arr_type);
3378 index_type = ada_index_type (arr_type, n, "length");
3379 if (index_type != NULL)
3381 struct type *base_type;
3382 if (index_type->code () == TYPE_CODE_RANGE)
3383 base_type = index_type->target_type ();
3384 else
3385 base_type = index_type;
3387 low = pos_atr (value_from_longest (base_type, low));
3388 high = pos_atr (value_from_longest (base_type, high));
3390 return high - low + 1;
3393 /* An array whose type is that of ARR_TYPE (an array type), with
3394 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3395 less than LOW, then LOW-1 is used. */
3397 static struct value *
3398 empty_array (struct type *arr_type, int low, int high)
3400 struct type *arr_type0 = ada_check_typedef (arr_type);
3401 struct type *index_type
3402 = create_static_range_type
3403 (NULL, 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 allocate_value (create_array_type (NULL, 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 for (int i = 0; i < syms.size (); ++i)
3808 /* We already know the name matches, so we're just looking for
3809 an element of the correct enum type. */
3810 if (ada_check_typedef (syms[i].symbol->type ()) == context_type)
3811 return i;
3814 error (_("No name '%s' in enumeration type '%s'"), name,
3815 ada_type_name (context_type));
3818 /* See ada-lang.h. */
3820 block_symbol
3821 ada_resolve_variable (struct symbol *sym, const struct block *block,
3822 struct type *context_type,
3823 bool parse_completion,
3824 int deprocedure_p,
3825 innermost_block_tracker *tracker)
3827 std::vector<struct block_symbol> candidates
3828 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3830 if (std::any_of (candidates.begin (),
3831 candidates.end (),
3832 [] (block_symbol &bsym)
3834 switch (bsym.symbol->aclass ())
3836 case LOC_REGISTER:
3837 case LOC_ARG:
3838 case LOC_REF_ARG:
3839 case LOC_REGPARM_ADDR:
3840 case LOC_LOCAL:
3841 case LOC_COMPUTED:
3842 return true;
3843 default:
3844 return false;
3848 /* Types tend to get re-introduced locally, so if there
3849 are any local symbols that are not types, first filter
3850 out all types. */
3851 candidates.erase
3852 (std::remove_if
3853 (candidates.begin (),
3854 candidates.end (),
3855 [] (block_symbol &bsym)
3857 return bsym.symbol->aclass () == LOC_TYPEDEF;
3859 candidates.end ());
3862 /* Filter out artificial symbols. */
3863 candidates.erase
3864 (std::remove_if
3865 (candidates.begin (),
3866 candidates.end (),
3867 [] (block_symbol &bsym)
3869 return bsym.symbol->is_artificial ();
3871 candidates.end ());
3873 int i;
3874 if (candidates.empty ())
3875 error (_("No definition found for %s"), sym->print_name ());
3876 else if (candidates.size () == 1)
3877 i = 0;
3878 else if (context_type != nullptr
3879 && context_type->code () == TYPE_CODE_ENUM)
3880 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3881 parse_completion);
3882 else if (deprocedure_p && !is_nonfunction (candidates))
3884 i = ada_resolve_function
3885 (candidates, NULL, 0,
3886 sym->linkage_name (),
3887 context_type, parse_completion);
3888 if (i < 0)
3889 error (_("Could not find a match for %s"), sym->print_name ());
3891 else
3893 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3894 user_select_syms (candidates.data (), candidates.size (), 1);
3895 i = 0;
3898 tracker->update (candidates[i]);
3899 return candidates[i];
3902 /* Return non-zero if formal type FTYPE matches actual type ATYPE. */
3903 /* The term "match" here is rather loose. The match is heuristic and
3904 liberal. */
3906 static int
3907 ada_type_match (struct type *ftype, struct type *atype)
3909 ftype = ada_check_typedef (ftype);
3910 atype = ada_check_typedef (atype);
3912 if (ftype->code () == TYPE_CODE_REF)
3913 ftype = ftype->target_type ();
3914 if (atype->code () == TYPE_CODE_REF)
3915 atype = atype->target_type ();
3917 switch (ftype->code ())
3919 default:
3920 return ftype->code () == atype->code ();
3921 case TYPE_CODE_PTR:
3922 if (atype->code () != TYPE_CODE_PTR)
3923 return 0;
3924 atype = atype->target_type ();
3925 /* This can only happen if the actual argument is 'null'. */
3926 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3927 return 1;
3928 return ada_type_match (ftype->target_type (), atype);
3929 case TYPE_CODE_INT:
3930 case TYPE_CODE_ENUM:
3931 case TYPE_CODE_RANGE:
3932 switch (atype->code ())
3934 case TYPE_CODE_INT:
3935 case TYPE_CODE_ENUM:
3936 case TYPE_CODE_RANGE:
3937 return 1;
3938 default:
3939 return 0;
3942 case TYPE_CODE_ARRAY:
3943 return (atype->code () == TYPE_CODE_ARRAY
3944 || ada_is_array_descriptor_type (atype));
3946 case TYPE_CODE_STRUCT:
3947 if (ada_is_array_descriptor_type (ftype))
3948 return (atype->code () == TYPE_CODE_ARRAY
3949 || ada_is_array_descriptor_type (atype));
3950 else
3951 return (atype->code () == TYPE_CODE_STRUCT
3952 && !ada_is_array_descriptor_type (atype));
3954 case TYPE_CODE_UNION:
3955 case TYPE_CODE_FLT:
3956 return (atype->code () == ftype->code ());
3960 /* Return non-zero if the formals of FUNC "sufficiently match" the
3961 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3962 may also be an enumeral, in which case it is treated as a 0-
3963 argument function. */
3965 static int
3966 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3968 int i;
3969 struct type *func_type = func->type ();
3971 if (func->aclass () == LOC_CONST
3972 && func_type->code () == TYPE_CODE_ENUM)
3973 return (n_actuals == 0);
3974 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3975 return 0;
3977 if (func_type->num_fields () != n_actuals)
3978 return 0;
3980 for (i = 0; i < n_actuals; i += 1)
3982 if (actuals[i] == NULL)
3983 return 0;
3984 else
3986 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3987 struct type *atype = ada_check_typedef (value_type (actuals[i]));
3989 if (!ada_type_match (ftype, atype))
3990 return 0;
3993 return 1;
3996 /* False iff function type FUNC_TYPE definitely does not produce a value
3997 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
3998 FUNC_TYPE is not a valid function type with a non-null return type
3999 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4001 static int
4002 return_match (struct type *func_type, struct type *context_type)
4004 struct type *return_type;
4006 if (func_type == NULL)
4007 return 1;
4009 if (func_type->code () == TYPE_CODE_FUNC)
4010 return_type = get_base_type (func_type->target_type ());
4011 else
4012 return_type = get_base_type (func_type);
4013 if (return_type == NULL)
4014 return 1;
4016 context_type = get_base_type (context_type);
4018 if (return_type->code () == TYPE_CODE_ENUM)
4019 return context_type == NULL || return_type == context_type;
4020 else if (context_type == NULL)
4021 return return_type->code () != TYPE_CODE_VOID;
4022 else
4023 return return_type->code () == context_type->code ();
4027 /* Returns the index in SYMS that contains the symbol for the
4028 function (if any) that matches the types of the NARGS arguments in
4029 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4030 that returns that type, then eliminate matches that don't. If
4031 CONTEXT_TYPE is void and there is at least one match that does not
4032 return void, eliminate all matches that do.
4034 Asks the user if there is more than one match remaining. Returns -1
4035 if there is no such symbol or none is selected. NAME is used
4036 solely for messages. May re-arrange and modify SYMS in
4037 the process; the index returned is for the modified vector. */
4039 static int
4040 ada_resolve_function (std::vector<struct block_symbol> &syms,
4041 struct value **args, int nargs,
4042 const char *name, struct type *context_type,
4043 bool parse_completion)
4045 int fallback;
4046 int k;
4047 int m; /* Number of hits */
4049 m = 0;
4050 /* In the first pass of the loop, we only accept functions matching
4051 context_type. If none are found, we add a second pass of the loop
4052 where every function is accepted. */
4053 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4055 for (k = 0; k < syms.size (); k += 1)
4057 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4059 if (ada_args_match (syms[k].symbol, args, nargs)
4060 && (fallback || return_match (type, context_type)))
4062 syms[m] = syms[k];
4063 m += 1;
4068 /* If we got multiple matches, ask the user which one to use. Don't do this
4069 interactive thing during completion, though, as the purpose of the
4070 completion is providing a list of all possible matches. Prompting the
4071 user to filter it down would be completely unexpected in this case. */
4072 if (m == 0)
4073 return -1;
4074 else if (m > 1 && !parse_completion)
4076 gdb_printf (_("Multiple matches for %s\n"), name);
4077 user_select_syms (syms.data (), m, 1);
4078 return 0;
4080 return 0;
4083 /* Type-class predicates */
4085 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4086 or FLOAT). */
4088 static int
4089 numeric_type_p (struct type *type)
4091 if (type == NULL)
4092 return 0;
4093 else
4095 switch (type->code ())
4097 case TYPE_CODE_INT:
4098 case TYPE_CODE_FLT:
4099 case TYPE_CODE_FIXED_POINT:
4100 return 1;
4101 case TYPE_CODE_RANGE:
4102 return (type == type->target_type ()
4103 || numeric_type_p (type->target_type ()));
4104 default:
4105 return 0;
4110 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4112 static int
4113 integer_type_p (struct type *type)
4115 if (type == NULL)
4116 return 0;
4117 else
4119 switch (type->code ())
4121 case TYPE_CODE_INT:
4122 return 1;
4123 case TYPE_CODE_RANGE:
4124 return (type == type->target_type ()
4125 || integer_type_p (type->target_type ()));
4126 default:
4127 return 0;
4132 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4134 static int
4135 scalar_type_p (struct type *type)
4137 if (type == NULL)
4138 return 0;
4139 else
4141 switch (type->code ())
4143 case TYPE_CODE_INT:
4144 case TYPE_CODE_RANGE:
4145 case TYPE_CODE_ENUM:
4146 case TYPE_CODE_FLT:
4147 case TYPE_CODE_FIXED_POINT:
4148 return 1;
4149 default:
4150 return 0;
4155 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4156 This essentially means one of (INT, RANGE, ENUM) -- but note that
4157 "enum" includes character and boolean as well. */
4159 static int
4160 discrete_type_p (struct type *type)
4162 if (type == NULL)
4163 return 0;
4164 else
4166 switch (type->code ())
4168 case TYPE_CODE_INT:
4169 case TYPE_CODE_RANGE:
4170 case TYPE_CODE_ENUM:
4171 case TYPE_CODE_BOOL:
4172 case TYPE_CODE_CHAR:
4173 return 1;
4174 default:
4175 return 0;
4180 /* Returns non-zero if OP with operands in the vector ARGS could be
4181 a user-defined function. Errs on the side of pre-defined operators
4182 (i.e., result 0). */
4184 static int
4185 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4187 struct type *type0 =
4188 (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
4189 struct type *type1 =
4190 (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
4192 if (type0 == NULL)
4193 return 0;
4195 switch (op)
4197 default:
4198 return 0;
4200 case BINOP_ADD:
4201 case BINOP_SUB:
4202 case BINOP_MUL:
4203 case BINOP_DIV:
4204 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4206 case BINOP_REM:
4207 case BINOP_MOD:
4208 case BINOP_BITWISE_AND:
4209 case BINOP_BITWISE_IOR:
4210 case BINOP_BITWISE_XOR:
4211 return (!(integer_type_p (type0) && integer_type_p (type1)));
4213 case BINOP_EQUAL:
4214 case BINOP_NOTEQUAL:
4215 case BINOP_LESS:
4216 case BINOP_GTR:
4217 case BINOP_LEQ:
4218 case BINOP_GEQ:
4219 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4221 case BINOP_CONCAT:
4222 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4224 case BINOP_EXP:
4225 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4227 case UNOP_NEG:
4228 case UNOP_PLUS:
4229 case UNOP_LOGICAL_NOT:
4230 case UNOP_ABS:
4231 return (!numeric_type_p (type0));
4236 /* Renaming */
4238 /* NOTES:
4240 1. In the following, we assume that a renaming type's name may
4241 have an ___XD suffix. It would be nice if this went away at some
4242 point.
4243 2. We handle both the (old) purely type-based representation of
4244 renamings and the (new) variable-based encoding. At some point,
4245 it is devoutly to be hoped that the former goes away
4246 (FIXME: hilfinger-2007-07-09).
4247 3. Subprogram renamings are not implemented, although the XRS
4248 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4250 /* If SYM encodes a renaming,
4252 <renaming> renames <renamed entity>,
4254 sets *LEN to the length of the renamed entity's name,
4255 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4256 the string describing the subcomponent selected from the renamed
4257 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4258 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4259 are undefined). Otherwise, returns a value indicating the category
4260 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4261 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4262 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4263 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4264 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4265 may be NULL, in which case they are not assigned.
4267 [Currently, however, GCC does not generate subprogram renamings.] */
4269 enum ada_renaming_category
4270 ada_parse_renaming (struct symbol *sym,
4271 const char **renamed_entity, int *len,
4272 const char **renaming_expr)
4274 enum ada_renaming_category kind;
4275 const char *info;
4276 const char *suffix;
4278 if (sym == NULL)
4279 return ADA_NOT_RENAMING;
4280 switch (sym->aclass ())
4282 default:
4283 return ADA_NOT_RENAMING;
4284 case LOC_LOCAL:
4285 case LOC_STATIC:
4286 case LOC_COMPUTED:
4287 case LOC_OPTIMIZED_OUT:
4288 info = strstr (sym->linkage_name (), "___XR");
4289 if (info == NULL)
4290 return ADA_NOT_RENAMING;
4291 switch (info[5])
4293 case '_':
4294 kind = ADA_OBJECT_RENAMING;
4295 info += 6;
4296 break;
4297 case 'E':
4298 kind = ADA_EXCEPTION_RENAMING;
4299 info += 7;
4300 break;
4301 case 'P':
4302 kind = ADA_PACKAGE_RENAMING;
4303 info += 7;
4304 break;
4305 case 'S':
4306 kind = ADA_SUBPROGRAM_RENAMING;
4307 info += 7;
4308 break;
4309 default:
4310 return ADA_NOT_RENAMING;
4314 if (renamed_entity != NULL)
4315 *renamed_entity = info;
4316 suffix = strstr (info, "___XE");
4317 if (suffix == NULL || suffix == info)
4318 return ADA_NOT_RENAMING;
4319 if (len != NULL)
4320 *len = strlen (info) - strlen (suffix);
4321 suffix += 5;
4322 if (renaming_expr != NULL)
4323 *renaming_expr = suffix;
4324 return kind;
4327 /* Compute the value of the given RENAMING_SYM, which is expected to
4328 be a symbol encoding a renaming expression. BLOCK is the block
4329 used to evaluate the renaming. */
4331 static struct value *
4332 ada_read_renaming_var_value (struct symbol *renaming_sym,
4333 const struct block *block)
4335 const char *sym_name;
4337 sym_name = renaming_sym->linkage_name ();
4338 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4339 return evaluate_expression (expr.get ());
4343 /* Evaluation: Function Calls */
4345 /* Return an lvalue containing the value VAL. This is the identity on
4346 lvalues, and otherwise has the side-effect of allocating memory
4347 in the inferior where a copy of the value contents is copied. */
4349 static struct value *
4350 ensure_lval (struct value *val)
4352 if (VALUE_LVAL (val) == not_lval
4353 || VALUE_LVAL (val) == lval_internalvar)
4355 int len = ada_check_typedef (value_type (val))->length ();
4356 const CORE_ADDR addr =
4357 value_as_long (value_allocate_space_in_inferior (len));
4359 VALUE_LVAL (val) = lval_memory;
4360 set_value_address (val, addr);
4361 write_memory (addr, value_contents (val).data (), len);
4364 return val;
4367 /* Given ARG, a value of type (pointer or reference to a)*
4368 structure/union, extract the component named NAME from the ultimate
4369 target structure/union and return it as a value with its
4370 appropriate type.
4372 The routine searches for NAME among all members of the structure itself
4373 and (recursively) among all members of any wrapper members
4374 (e.g., '_parent').
4376 If NO_ERR, then simply return NULL in case of error, rather than
4377 calling error. */
4379 static struct value *
4380 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4382 struct type *t, *t1;
4383 struct value *v;
4384 int check_tag;
4386 v = NULL;
4387 t1 = t = ada_check_typedef (value_type (arg));
4388 if (t->code () == TYPE_CODE_REF)
4390 t1 = t->target_type ();
4391 if (t1 == NULL)
4392 goto BadValue;
4393 t1 = ada_check_typedef (t1);
4394 if (t1->code () == TYPE_CODE_PTR)
4396 arg = coerce_ref (arg);
4397 t = t1;
4401 while (t->code () == TYPE_CODE_PTR)
4403 t1 = t->target_type ();
4404 if (t1 == NULL)
4405 goto BadValue;
4406 t1 = ada_check_typedef (t1);
4407 if (t1->code () == TYPE_CODE_PTR)
4409 arg = value_ind (arg);
4410 t = t1;
4412 else
4413 break;
4416 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4417 goto BadValue;
4419 if (t1 == t)
4420 v = ada_search_struct_field (name, arg, 0, t);
4421 else
4423 int bit_offset, bit_size, byte_offset;
4424 struct type *field_type;
4425 CORE_ADDR address;
4427 if (t->code () == TYPE_CODE_PTR)
4428 address = value_address (ada_value_ind (arg));
4429 else
4430 address = value_address (ada_coerce_ref (arg));
4432 /* Check to see if this is a tagged type. We also need to handle
4433 the case where the type is a reference to a tagged type, but
4434 we have to be careful to exclude pointers to tagged types.
4435 The latter should be shown as usual (as a pointer), whereas
4436 a reference should mostly be transparent to the user. */
4438 if (ada_is_tagged_type (t1, 0)
4439 || (t1->code () == TYPE_CODE_REF
4440 && ada_is_tagged_type (t1->target_type (), 0)))
4442 /* We first try to find the searched field in the current type.
4443 If not found then let's look in the fixed type. */
4445 if (!find_struct_field (name, t1, 0,
4446 nullptr, nullptr, nullptr,
4447 nullptr, nullptr))
4448 check_tag = 1;
4449 else
4450 check_tag = 0;
4452 else
4453 check_tag = 0;
4455 /* Convert to fixed type in all cases, so that we have proper
4456 offsets to each field in unconstrained record types. */
4457 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4458 address, NULL, check_tag);
4460 /* Resolve the dynamic type as well. */
4461 arg = value_from_contents_and_address (t1, nullptr, address);
4462 t1 = value_type (arg);
4464 if (find_struct_field (name, t1, 0,
4465 &field_type, &byte_offset, &bit_offset,
4466 &bit_size, NULL))
4468 if (bit_size != 0)
4470 if (t->code () == TYPE_CODE_REF)
4471 arg = ada_coerce_ref (arg);
4472 else
4473 arg = ada_value_ind (arg);
4474 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4475 bit_offset, bit_size,
4476 field_type);
4478 else
4479 v = value_at_lazy (field_type, address + byte_offset);
4483 if (v != NULL || no_err)
4484 return v;
4485 else
4486 error (_("There is no member named %s."), name);
4488 BadValue:
4489 if (no_err)
4490 return NULL;
4491 else
4492 error (_("Attempt to extract a component of "
4493 "a value that is not a record."));
4496 /* Return the value ACTUAL, converted to be an appropriate value for a
4497 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4498 allocating any necessary descriptors (fat pointers), or copies of
4499 values not residing in memory, updating it as needed. */
4501 struct value *
4502 ada_convert_actual (struct value *actual, struct type *formal_type0)
4504 struct type *actual_type = ada_check_typedef (value_type (actual));
4505 struct type *formal_type = ada_check_typedef (formal_type0);
4506 struct type *formal_target =
4507 formal_type->code () == TYPE_CODE_PTR
4508 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4509 struct type *actual_target =
4510 actual_type->code () == TYPE_CODE_PTR
4511 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4513 if (ada_is_array_descriptor_type (formal_target)
4514 && actual_target->code () == TYPE_CODE_ARRAY)
4515 return make_array_descriptor (formal_type, actual);
4516 else if (formal_type->code () == TYPE_CODE_PTR
4517 || formal_type->code () == TYPE_CODE_REF)
4519 struct value *result;
4521 if (formal_target->code () == TYPE_CODE_ARRAY
4522 && ada_is_array_descriptor_type (actual_target))
4523 result = desc_data (actual);
4524 else if (formal_type->code () != TYPE_CODE_PTR)
4526 if (VALUE_LVAL (actual) != lval_memory)
4528 struct value *val;
4530 actual_type = ada_check_typedef (value_type (actual));
4531 val = allocate_value (actual_type);
4532 copy (value_contents (actual), value_contents_raw (val));
4533 actual = ensure_lval (val);
4535 result = value_addr (actual);
4537 else
4538 return actual;
4539 return value_cast_pointers (formal_type, result, 0);
4541 else if (actual_type->code () == TYPE_CODE_PTR)
4542 return ada_value_ind (actual);
4543 else if (ada_is_aligner_type (formal_type))
4545 /* We need to turn this parameter into an aligner type
4546 as well. */
4547 struct value *aligner = allocate_value (formal_type);
4548 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4550 value_assign_to_component (aligner, component, actual);
4551 return aligner;
4554 return actual;
4557 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4558 type TYPE. This is usually an inefficient no-op except on some targets
4559 (such as AVR) where the representation of a pointer and an address
4560 differs. */
4562 static CORE_ADDR
4563 value_pointer (struct value *value, struct type *type)
4565 unsigned len = type->length ();
4566 gdb_byte *buf = (gdb_byte *) alloca (len);
4567 CORE_ADDR addr;
4569 addr = value_address (value);
4570 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4571 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4572 return addr;
4576 /* Push a descriptor of type TYPE for array value ARR on the stack at
4577 *SP, updating *SP to reflect the new descriptor. Return either
4578 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4579 to-descriptor type rather than a descriptor type), a struct value *
4580 representing a pointer to this descriptor. */
4582 static struct value *
4583 make_array_descriptor (struct type *type, struct value *arr)
4585 struct type *bounds_type = desc_bounds_type (type);
4586 struct type *desc_type = desc_base_type (type);
4587 struct value *descriptor = allocate_value (desc_type);
4588 struct value *bounds = allocate_value (bounds_type);
4589 int i;
4591 for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4592 i > 0; i -= 1)
4594 modify_field (value_type (bounds),
4595 value_contents_writeable (bounds).data (),
4596 ada_array_bound (arr, i, 0),
4597 desc_bound_bitpos (bounds_type, i, 0),
4598 desc_bound_bitsize (bounds_type, i, 0));
4599 modify_field (value_type (bounds),
4600 value_contents_writeable (bounds).data (),
4601 ada_array_bound (arr, i, 1),
4602 desc_bound_bitpos (bounds_type, i, 1),
4603 desc_bound_bitsize (bounds_type, i, 1));
4606 bounds = ensure_lval (bounds);
4608 modify_field (value_type (descriptor),
4609 value_contents_writeable (descriptor).data (),
4610 value_pointer (ensure_lval (arr),
4611 desc_type->field (0).type ()),
4612 fat_pntr_data_bitpos (desc_type),
4613 fat_pntr_data_bitsize (desc_type));
4615 modify_field (value_type (descriptor),
4616 value_contents_writeable (descriptor).data (),
4617 value_pointer (bounds,
4618 desc_type->field (1).type ()),
4619 fat_pntr_bounds_bitpos (desc_type),
4620 fat_pntr_bounds_bitsize (desc_type));
4622 descriptor = ensure_lval (descriptor);
4624 if (type->code () == TYPE_CODE_PTR)
4625 return value_addr (descriptor);
4626 else
4627 return descriptor;
4630 /* Symbol Cache Module */
4632 /* Performance measurements made as of 2010-01-15 indicate that
4633 this cache does bring some noticeable improvements. Depending
4634 on the type of entity being printed, the cache can make it as much
4635 as an order of magnitude faster than without it.
4637 The descriptive type DWARF extension has significantly reduced
4638 the need for this cache, at least when DWARF is being used. However,
4639 even in this case, some expensive name-based symbol searches are still
4640 sometimes necessary - to find an XVZ variable, mostly. */
4642 /* Return the symbol cache associated to the given program space PSPACE.
4643 If not allocated for this PSPACE yet, allocate and initialize one. */
4645 static struct ada_symbol_cache *
4646 ada_get_symbol_cache (struct program_space *pspace)
4648 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4650 if (pspace_data->sym_cache == nullptr)
4651 pspace_data->sym_cache.reset (new ada_symbol_cache);
4653 return pspace_data->sym_cache.get ();
4656 /* Clear all entries from the symbol cache. */
4658 static void
4659 ada_clear_symbol_cache ()
4661 struct ada_pspace_data *pspace_data
4662 = get_ada_pspace_data (current_program_space);
4664 if (pspace_data->sym_cache != nullptr)
4665 pspace_data->sym_cache.reset ();
4668 /* Search our cache for an entry matching NAME and DOMAIN.
4669 Return it if found, or NULL otherwise. */
4671 static struct cache_entry **
4672 find_entry (const char *name, domain_enum domain)
4674 struct ada_symbol_cache *sym_cache
4675 = ada_get_symbol_cache (current_program_space);
4676 int h = msymbol_hash (name) % HASH_SIZE;
4677 struct cache_entry **e;
4679 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4681 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4682 return e;
4684 return NULL;
4687 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4688 Return 1 if found, 0 otherwise.
4690 If an entry was found and SYM is not NULL, set *SYM to the entry's
4691 SYM. Same principle for BLOCK if not NULL. */
4693 static int
4694 lookup_cached_symbol (const char *name, domain_enum domain,
4695 struct symbol **sym, const struct block **block)
4697 struct cache_entry **e = find_entry (name, domain);
4699 if (e == NULL)
4700 return 0;
4701 if (sym != NULL)
4702 *sym = (*e)->sym;
4703 if (block != NULL)
4704 *block = (*e)->block;
4705 return 1;
4708 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4709 in domain DOMAIN, save this result in our symbol cache. */
4711 static void
4712 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4713 const struct block *block)
4715 struct ada_symbol_cache *sym_cache
4716 = ada_get_symbol_cache (current_program_space);
4717 int h;
4718 struct cache_entry *e;
4720 /* Symbols for builtin types don't have a block.
4721 For now don't cache such symbols. */
4722 if (sym != NULL && !sym->is_objfile_owned ())
4723 return;
4725 /* If the symbol is a local symbol, then do not cache it, as a search
4726 for that symbol depends on the context. To determine whether
4727 the symbol is local or not, we check the block where we found it
4728 against the global and static blocks of its associated symtab. */
4729 if (sym != nullptr)
4731 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4733 if (bv.global_block () != block && bv.static_block () != block)
4734 return;
4737 h = msymbol_hash (name) % HASH_SIZE;
4738 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4739 e->next = sym_cache->root[h];
4740 sym_cache->root[h] = e;
4741 e->name = obstack_strdup (&sym_cache->cache_space, name);
4742 e->sym = sym;
4743 e->domain = domain;
4744 e->block = block;
4747 /* Symbol Lookup */
4749 /* Return the symbol name match type that should be used used when
4750 searching for all symbols matching LOOKUP_NAME.
4752 LOOKUP_NAME is expected to be a symbol name after transformation
4753 for Ada lookups. */
4755 static symbol_name_match_type
4756 name_match_type_from_name (const char *lookup_name)
4758 return (strstr (lookup_name, "__") == NULL
4759 ? symbol_name_match_type::WILD
4760 : symbol_name_match_type::FULL);
4763 /* Return the result of a standard (literal, C-like) lookup of NAME in
4764 given DOMAIN, visible from lexical block BLOCK. */
4766 static struct symbol *
4767 standard_lookup (const char *name, const struct block *block,
4768 domain_enum domain)
4770 /* Initialize it just to avoid a GCC false warning. */
4771 struct block_symbol sym = {};
4773 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4774 return sym.symbol;
4775 ada_lookup_encoded_symbol (name, block, domain, &sym);
4776 cache_symbol (name, domain, sym.symbol, sym.block);
4777 return sym.symbol;
4781 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4782 in the symbol fields of SYMS. We treat enumerals as functions,
4783 since they contend in overloading in the same way. */
4784 static int
4785 is_nonfunction (const std::vector<struct block_symbol> &syms)
4787 for (const block_symbol &sym : syms)
4788 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4789 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4790 || sym.symbol->aclass () != LOC_CONST))
4791 return 1;
4793 return 0;
4796 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4797 struct types. Otherwise, they may not. */
4799 static int
4800 equiv_types (struct type *type0, struct type *type1)
4802 if (type0 == type1)
4803 return 1;
4804 if (type0 == NULL || type1 == NULL
4805 || type0->code () != type1->code ())
4806 return 0;
4807 if ((type0->code () == TYPE_CODE_STRUCT
4808 || type0->code () == TYPE_CODE_ENUM)
4809 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4810 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4811 return 1;
4813 return 0;
4816 /* True iff SYM0 represents the same entity as SYM1, or one that is
4817 no more defined than that of SYM1. */
4819 static int
4820 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4822 if (sym0 == sym1)
4823 return 1;
4824 if (sym0->domain () != sym1->domain ()
4825 || sym0->aclass () != sym1->aclass ())
4826 return 0;
4828 switch (sym0->aclass ())
4830 case LOC_UNDEF:
4831 return 1;
4832 case LOC_TYPEDEF:
4834 struct type *type0 = sym0->type ();
4835 struct type *type1 = sym1->type ();
4836 const char *name0 = sym0->linkage_name ();
4837 const char *name1 = sym1->linkage_name ();
4838 int len0 = strlen (name0);
4840 return
4841 type0->code () == type1->code ()
4842 && (equiv_types (type0, type1)
4843 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4844 && startswith (name1 + len0, "___XV")));
4846 case LOC_CONST:
4847 return sym0->value_longest () == sym1->value_longest ()
4848 && equiv_types (sym0->type (), sym1->type ());
4850 case LOC_STATIC:
4852 const char *name0 = sym0->linkage_name ();
4853 const char *name1 = sym1->linkage_name ();
4854 return (strcmp (name0, name1) == 0
4855 && sym0->value_address () == sym1->value_address ());
4858 default:
4859 return 0;
4863 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4864 records in RESULT. Do nothing if SYM is a duplicate. */
4866 static void
4867 add_defn_to_vec (std::vector<struct block_symbol> &result,
4868 struct symbol *sym,
4869 const struct block *block)
4871 /* Do not try to complete stub types, as the debugger is probably
4872 already scanning all symbols matching a certain name at the
4873 time when this function is called. Trying to replace the stub
4874 type by its associated full type will cause us to restart a scan
4875 which may lead to an infinite recursion. Instead, the client
4876 collecting the matching symbols will end up collecting several
4877 matches, with at least one of them complete. It can then filter
4878 out the stub ones if needed. */
4880 for (int i = result.size () - 1; i >= 0; i -= 1)
4882 if (lesseq_defined_than (sym, result[i].symbol))
4883 return;
4884 else if (lesseq_defined_than (result[i].symbol, sym))
4886 result[i].symbol = sym;
4887 result[i].block = block;
4888 return;
4892 struct block_symbol info;
4893 info.symbol = sym;
4894 info.block = block;
4895 result.push_back (info);
4898 /* Return a bound minimal symbol matching NAME according to Ada
4899 decoding rules. Returns an invalid symbol if there is no such
4900 minimal symbol. Names prefixed with "standard__" are handled
4901 specially: "standard__" is first stripped off, and only static and
4902 global symbols are searched. */
4904 struct bound_minimal_symbol
4905 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4907 struct bound_minimal_symbol result;
4909 symbol_name_match_type match_type = name_match_type_from_name (name);
4910 lookup_name_info lookup_name (name, match_type);
4912 symbol_name_matcher_ftype *match_name
4913 = ada_get_symbol_name_matcher (lookup_name);
4915 gdbarch_iterate_over_objfiles_in_search_order
4916 (objfile != NULL ? objfile->arch () : target_gdbarch (),
4917 [&result, lookup_name, match_name] (struct objfile *obj)
4919 for (minimal_symbol *msymbol : obj->msymbols ())
4921 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4922 && msymbol->type () != mst_solib_trampoline)
4924 result.minsym = msymbol;
4925 result.objfile = obj;
4926 return 1;
4930 return 0;
4931 }, objfile);
4933 return result;
4936 /* True if TYPE is definitely an artificial type supplied to a symbol
4937 for which no debugging information was given in the symbol file. */
4939 static int
4940 is_nondebugging_type (struct type *type)
4942 const char *name = ada_type_name (type);
4944 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4947 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4948 that are deemed "identical" for practical purposes.
4950 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4951 types and that their number of enumerals is identical (in other
4952 words, type1->num_fields () == type2->num_fields ()). */
4954 static int
4955 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4957 int i;
4959 /* The heuristic we use here is fairly conservative. We consider
4960 that 2 enumerate types are identical if they have the same
4961 number of enumerals and that all enumerals have the same
4962 underlying value and name. */
4964 /* All enums in the type should have an identical underlying value. */
4965 for (i = 0; i < type1->num_fields (); i++)
4966 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4967 return 0;
4969 /* All enumerals should also have the same name (modulo any numerical
4970 suffix). */
4971 for (i = 0; i < type1->num_fields (); i++)
4973 const char *name_1 = type1->field (i).name ();
4974 const char *name_2 = type2->field (i).name ();
4975 int len_1 = strlen (name_1);
4976 int len_2 = strlen (name_2);
4978 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4979 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4980 if (len_1 != len_2
4981 || strncmp (type1->field (i).name (),
4982 type2->field (i).name (),
4983 len_1) != 0)
4984 return 0;
4987 return 1;
4990 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4991 that are deemed "identical" for practical purposes. Sometimes,
4992 enumerals are not strictly identical, but their types are so similar
4993 that they can be considered identical.
4995 For instance, consider the following code:
4997 type Color is (Black, Red, Green, Blue, White);
4998 type RGB_Color is new Color range Red .. Blue;
5000 Type RGB_Color is a subrange of an implicit type which is a copy
5001 of type Color. If we call that implicit type RGB_ColorB ("B" is
5002 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5003 As a result, when an expression references any of the enumeral
5004 by name (Eg. "print green"), the expression is technically
5005 ambiguous and the user should be asked to disambiguate. But
5006 doing so would only hinder the user, since it wouldn't matter
5007 what choice he makes, the outcome would always be the same.
5008 So, for practical purposes, we consider them as the same. */
5010 static int
5011 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5013 int i;
5015 /* Before performing a thorough comparison check of each type,
5016 we perform a series of inexpensive checks. We expect that these
5017 checks will quickly fail in the vast majority of cases, and thus
5018 help prevent the unnecessary use of a more expensive comparison.
5019 Said comparison also expects us to make some of these checks
5020 (see ada_identical_enum_types_p). */
5022 /* Quick check: All symbols should have an enum type. */
5023 for (i = 0; i < syms.size (); i++)
5024 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5025 return 0;
5027 /* Quick check: They should all have the same value. */
5028 for (i = 1; i < syms.size (); i++)
5029 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5030 return 0;
5032 /* Quick check: They should all have the same number of enumerals. */
5033 for (i = 1; i < syms.size (); i++)
5034 if (syms[i].symbol->type ()->num_fields ()
5035 != syms[0].symbol->type ()->num_fields ())
5036 return 0;
5038 /* All the sanity checks passed, so we might have a set of
5039 identical enumeration types. Perform a more complete
5040 comparison of the type of each symbol. */
5041 for (i = 1; i < syms.size (); i++)
5042 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5043 syms[0].symbol->type ()))
5044 return 0;
5046 return 1;
5049 /* Remove any non-debugging symbols in SYMS that definitely
5050 duplicate other symbols in the list (The only case I know of where
5051 this happens is when object files containing stabs-in-ecoff are
5052 linked with files containing ordinary ecoff debugging symbols (or no
5053 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5055 static void
5056 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5058 int i, j;
5060 /* We should never be called with less than 2 symbols, as there
5061 cannot be any extra symbol in that case. But it's easy to
5062 handle, since we have nothing to do in that case. */
5063 if (syms->size () < 2)
5064 return;
5066 i = 0;
5067 while (i < syms->size ())
5069 int remove_p = 0;
5071 /* If two symbols have the same name and one of them is a stub type,
5072 the get rid of the stub. */
5074 if ((*syms)[i].symbol->type ()->is_stub ()
5075 && (*syms)[i].symbol->linkage_name () != NULL)
5077 for (j = 0; j < syms->size (); j++)
5079 if (j != i
5080 && !(*syms)[j].symbol->type ()->is_stub ()
5081 && (*syms)[j].symbol->linkage_name () != NULL
5082 && strcmp ((*syms)[i].symbol->linkage_name (),
5083 (*syms)[j].symbol->linkage_name ()) == 0)
5084 remove_p = 1;
5088 /* Two symbols with the same name, same class and same address
5089 should be identical. */
5091 else if ((*syms)[i].symbol->linkage_name () != NULL
5092 && (*syms)[i].symbol->aclass () == LOC_STATIC
5093 && is_nondebugging_type ((*syms)[i].symbol->type ()))
5095 for (j = 0; j < syms->size (); j += 1)
5097 if (i != j
5098 && (*syms)[j].symbol->linkage_name () != NULL
5099 && strcmp ((*syms)[i].symbol->linkage_name (),
5100 (*syms)[j].symbol->linkage_name ()) == 0
5101 && ((*syms)[i].symbol->aclass ()
5102 == (*syms)[j].symbol->aclass ())
5103 && (*syms)[i].symbol->value_address ()
5104 == (*syms)[j].symbol->value_address ())
5105 remove_p = 1;
5109 if (remove_p)
5110 syms->erase (syms->begin () + i);
5111 else
5112 i += 1;
5115 /* If all the remaining symbols are identical enumerals, then
5116 just keep the first one and discard the rest.
5118 Unlike what we did previously, we do not discard any entry
5119 unless they are ALL identical. This is because the symbol
5120 comparison is not a strict comparison, but rather a practical
5121 comparison. If all symbols are considered identical, then
5122 we can just go ahead and use the first one and discard the rest.
5123 But if we cannot reduce the list to a single element, we have
5124 to ask the user to disambiguate anyways. And if we have to
5125 present a multiple-choice menu, it's less confusing if the list
5126 isn't missing some choices that were identical and yet distinct. */
5127 if (symbols_are_identical_enums (*syms))
5128 syms->resize (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 = block_linkage_function (current_block);
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,
5393 fixup_symbol_section (arg_sym, objfile),
5394 block);
5395 found_sym = false;
5396 arg_sym = NULL;
5398 else
5400 if (sym->aclass () == LOC_UNRESOLVED)
5401 return true;
5402 else if (sym->is_argument ())
5403 arg_sym = sym;
5404 else
5406 found_sym = true;
5407 add_defn_to_vec (*resultp,
5408 fixup_symbol_section (sym, objfile),
5409 block);
5412 return true;
5415 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5416 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5417 symbols to RESULT. Return whether we found such symbols. */
5419 static int
5420 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5421 const struct block *block,
5422 const lookup_name_info &lookup_name,
5423 domain_enum domain)
5425 struct using_direct *renaming;
5426 int defns_mark = result.size ();
5428 symbol_name_matcher_ftype *name_match
5429 = ada_get_symbol_name_matcher (lookup_name);
5431 for (renaming = block_using (block);
5432 renaming != NULL;
5433 renaming = renaming->next)
5435 const char *r_name;
5437 /* Avoid infinite recursions: skip this renaming if we are actually
5438 already traversing it.
5440 Currently, symbol lookup in Ada don't use the namespace machinery from
5441 C++/Fortran support: skip namespace imports that use them. */
5442 if (renaming->searched
5443 || (renaming->import_src != NULL
5444 && renaming->import_src[0] != '\0')
5445 || (renaming->import_dest != NULL
5446 && renaming->import_dest[0] != '\0'))
5447 continue;
5448 renaming->searched = 1;
5450 /* TODO: here, we perform another name-based symbol lookup, which can
5451 pull its own multiple overloads. In theory, we should be able to do
5452 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5453 not a simple name. But in order to do this, we would need to enhance
5454 the DWARF reader to associate a symbol to this renaming, instead of a
5455 name. So, for now, we do something simpler: re-use the C++/Fortran
5456 namespace machinery. */
5457 r_name = (renaming->alias != NULL
5458 ? renaming->alias
5459 : renaming->declaration);
5460 if (name_match (r_name, lookup_name, NULL))
5462 lookup_name_info decl_lookup_name (renaming->declaration,
5463 lookup_name.match_type ());
5464 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5465 1, NULL);
5467 renaming->searched = 0;
5469 return result.size () != defns_mark;
5472 /* Implements compare_names, but only applying the comparision using
5473 the given CASING. */
5475 static int
5476 compare_names_with_case (const char *string1, const char *string2,
5477 enum case_sensitivity casing)
5479 while (*string1 != '\0' && *string2 != '\0')
5481 char c1, c2;
5483 if (isspace (*string1) || isspace (*string2))
5484 return strcmp_iw_ordered (string1, string2);
5486 if (casing == case_sensitive_off)
5488 c1 = tolower (*string1);
5489 c2 = tolower (*string2);
5491 else
5493 c1 = *string1;
5494 c2 = *string2;
5496 if (c1 != c2)
5497 break;
5499 string1 += 1;
5500 string2 += 1;
5503 switch (*string1)
5505 case '(':
5506 return strcmp_iw_ordered (string1, string2);
5507 case '_':
5508 if (*string2 == '\0')
5510 if (is_name_suffix (string1))
5511 return 0;
5512 else
5513 return 1;
5515 /* FALLTHROUGH */
5516 default:
5517 if (*string2 == '(')
5518 return strcmp_iw_ordered (string1, string2);
5519 else
5521 if (casing == case_sensitive_off)
5522 return tolower (*string1) - tolower (*string2);
5523 else
5524 return *string1 - *string2;
5529 /* Compare STRING1 to STRING2, with results as for strcmp.
5530 Compatible with strcmp_iw_ordered in that...
5532 strcmp_iw_ordered (STRING1, STRING2) <= 0
5534 ... implies...
5536 compare_names (STRING1, STRING2) <= 0
5538 (they may differ as to what symbols compare equal). */
5540 static int
5541 compare_names (const char *string1, const char *string2)
5543 int result;
5545 /* Similar to what strcmp_iw_ordered does, we need to perform
5546 a case-insensitive comparison first, and only resort to
5547 a second, case-sensitive, comparison if the first one was
5548 not sufficient to differentiate the two strings. */
5550 result = compare_names_with_case (string1, string2, case_sensitive_off);
5551 if (result == 0)
5552 result = compare_names_with_case (string1, string2, case_sensitive_on);
5554 return result;
5557 /* Convenience function to get at the Ada encoded lookup name for
5558 LOOKUP_NAME, as a C string. */
5560 static const char *
5561 ada_lookup_name (const lookup_name_info &lookup_name)
5563 return lookup_name.ada ().lookup_name ().c_str ();
5566 /* A helper for add_nonlocal_symbols. Call expand_matching_symbols
5567 for OBJFILE, then walk the objfile's symtabs and update the
5568 results. */
5570 static void
5571 map_matching_symbols (struct objfile *objfile,
5572 const lookup_name_info &lookup_name,
5573 bool is_wild_match,
5574 domain_enum domain,
5575 int global,
5576 match_data &data)
5578 data.objfile = objfile;
5579 objfile->expand_matching_symbols (lookup_name, domain, global,
5580 is_wild_match ? nullptr : compare_names);
5582 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5583 for (compunit_symtab *symtab : objfile->compunits ())
5585 const struct block *block
5586 = symtab->blockvector ()->block (block_kind);
5587 if (!iterate_over_symbols_terminated (block, lookup_name,
5588 domain, data))
5589 break;
5593 /* Add to RESULT all non-local symbols whose name and domain match
5594 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5595 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5596 symbols otherwise. */
5598 static void
5599 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5600 const lookup_name_info &lookup_name,
5601 domain_enum domain, int global)
5603 struct match_data data (&result);
5605 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5607 for (objfile *objfile : current_program_space->objfiles ())
5609 map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5610 global, data);
5612 for (compunit_symtab *cu : objfile->compunits ())
5614 const struct block *global_block
5615 = cu->blockvector ()->global_block ();
5617 if (ada_add_block_renamings (result, global_block, lookup_name,
5618 domain))
5619 data.found_sym = true;
5623 if (result.empty () && global && !is_wild_match)
5625 const char *name = ada_lookup_name (lookup_name);
5626 std::string bracket_name = std::string ("<_ada_") + name + '>';
5627 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5629 for (objfile *objfile : current_program_space->objfiles ())
5630 map_matching_symbols (objfile, name1, false, domain, global, data);
5634 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5635 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5636 returning the number of matches. Add these to RESULT.
5638 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5639 symbol match within the nest of blocks whose innermost member is BLOCK,
5640 is the one match returned (no other matches in that or
5641 enclosing blocks is returned). If there are any matches in or
5642 surrounding BLOCK, then these alone are returned.
5644 Names prefixed with "standard__" are handled specially:
5645 "standard__" is first stripped off (by the lookup_name
5646 constructor), and only static and global symbols are searched.
5648 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5649 to lookup global symbols. */
5651 static void
5652 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5653 const struct block *block,
5654 const lookup_name_info &lookup_name,
5655 domain_enum domain,
5656 int full_search,
5657 int *made_global_lookup_p)
5659 struct symbol *sym;
5661 if (made_global_lookup_p)
5662 *made_global_lookup_p = 0;
5664 /* Special case: If the user specifies a symbol name inside package
5665 Standard, do a non-wild matching of the symbol name without
5666 the "standard__" prefix. This was primarily introduced in order
5667 to allow the user to specifically access the standard exceptions
5668 using, for instance, Standard.Constraint_Error when Constraint_Error
5669 is ambiguous (due to the user defining its own Constraint_Error
5670 entity inside its program). */
5671 if (lookup_name.ada ().standard_p ())
5672 block = NULL;
5674 /* Check the non-global symbols. If we have ANY match, then we're done. */
5676 if (block != NULL)
5678 if (full_search)
5679 ada_add_local_symbols (result, lookup_name, block, domain);
5680 else
5682 /* In the !full_search case we're are being called by
5683 iterate_over_symbols, and we don't want to search
5684 superblocks. */
5685 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5687 if (!result.empty () || !full_search)
5688 return;
5691 /* No non-global symbols found. Check our cache to see if we have
5692 already performed this search before. If we have, then return
5693 the same result. */
5695 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5696 domain, &sym, &block))
5698 if (sym != NULL)
5699 add_defn_to_vec (result, sym, block);
5700 return;
5703 if (made_global_lookup_p)
5704 *made_global_lookup_p = 1;
5706 /* Search symbols from all global blocks. */
5708 add_nonlocal_symbols (result, lookup_name, domain, 1);
5710 /* Now add symbols from all per-file blocks if we've gotten no hits
5711 (not strictly correct, but perhaps better than an error). */
5713 if (result.empty ())
5714 add_nonlocal_symbols (result, lookup_name, domain, 0);
5717 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5718 is non-zero, enclosing scope and in global scopes.
5720 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5721 blocks and symbol tables (if any) in which they were found.
5723 When full_search is non-zero, any non-function/non-enumeral
5724 symbol match within the nest of blocks whose innermost member is BLOCK,
5725 is the one match returned (no other matches in that or
5726 enclosing blocks is returned). If there are any matches in or
5727 surrounding BLOCK, then these alone are returned.
5729 Names prefixed with "standard__" are handled specially: "standard__"
5730 is first stripped off, and only static and global symbols are searched. */
5732 static std::vector<struct block_symbol>
5733 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5734 const struct block *block,
5735 domain_enum domain,
5736 int full_search)
5738 int syms_from_global_search;
5739 std::vector<struct block_symbol> results;
5741 ada_add_all_symbols (results, block, lookup_name,
5742 domain, full_search, &syms_from_global_search);
5744 remove_extra_symbols (&results);
5746 if (results.empty () && full_search && syms_from_global_search)
5747 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5749 if (results.size () == 1 && full_search && syms_from_global_search)
5750 cache_symbol (ada_lookup_name (lookup_name), domain,
5751 results[0].symbol, results[0].block);
5753 remove_irrelevant_renamings (&results, block);
5754 return results;
5757 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5758 in global scopes, returning (SYM,BLOCK) tuples.
5760 See ada_lookup_symbol_list_worker for further details. */
5762 std::vector<struct block_symbol>
5763 ada_lookup_symbol_list (const char *name, const struct block *block,
5764 domain_enum domain)
5766 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5767 lookup_name_info lookup_name (name, name_match_type);
5769 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5772 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5773 to 1, but choosing the first symbol found if there are multiple
5774 choices.
5776 The result is stored in *INFO, which must be non-NULL.
5777 If no match is found, INFO->SYM is set to NULL. */
5779 void
5780 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5781 domain_enum domain,
5782 struct block_symbol *info)
5784 /* Since we already have an encoded name, wrap it in '<>' to force a
5785 verbatim match. Otherwise, if the name happens to not look like
5786 an encoded name (because it doesn't include a "__"),
5787 ada_lookup_name_info would re-encode/fold it again, and that
5788 would e.g., incorrectly lowercase object renaming names like
5789 "R28b" -> "r28b". */
5790 std::string verbatim = add_angle_brackets (name);
5792 gdb_assert (info != NULL);
5793 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5796 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5797 scope and in global scopes, or NULL if none. NAME is folded and
5798 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5799 choosing the first symbol if there are multiple choices. */
5801 struct block_symbol
5802 ada_lookup_symbol (const char *name, const struct block *block0,
5803 domain_enum domain)
5805 std::vector<struct block_symbol> candidates
5806 = ada_lookup_symbol_list (name, block0, domain);
5808 if (candidates.empty ())
5809 return {};
5811 block_symbol info = candidates[0];
5812 info.symbol = fixup_symbol_section (info.symbol, NULL);
5813 return info;
5817 /* True iff STR is a possible encoded suffix of a normal Ada name
5818 that is to be ignored for matching purposes. Suffixes of parallel
5819 names (e.g., XVE) are not included here. Currently, the possible suffixes
5820 are given by any of the regular expressions:
5822 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5823 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5824 TKB [subprogram suffix for task bodies]
5825 _E[0-9]+[bs]$ [protected object entry suffixes]
5826 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5828 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5829 match is performed. This sequence is used to differentiate homonyms,
5830 is an optional part of a valid name suffix. */
5832 static int
5833 is_name_suffix (const char *str)
5835 int k;
5836 const char *matching;
5837 const int len = strlen (str);
5839 /* Skip optional leading __[0-9]+. */
5841 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5843 str += 3;
5844 while (isdigit (str[0]))
5845 str += 1;
5848 /* [.$][0-9]+ */
5850 if (str[0] == '.' || str[0] == '$')
5852 matching = str + 1;
5853 while (isdigit (matching[0]))
5854 matching += 1;
5855 if (matching[0] == '\0')
5856 return 1;
5859 /* ___[0-9]+ */
5861 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5863 matching = str + 3;
5864 while (isdigit (matching[0]))
5865 matching += 1;
5866 if (matching[0] == '\0')
5867 return 1;
5870 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5872 if (strcmp (str, "TKB") == 0)
5873 return 1;
5875 #if 0
5876 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5877 with a N at the end. Unfortunately, the compiler uses the same
5878 convention for other internal types it creates. So treating
5879 all entity names that end with an "N" as a name suffix causes
5880 some regressions. For instance, consider the case of an enumerated
5881 type. To support the 'Image attribute, it creates an array whose
5882 name ends with N.
5883 Having a single character like this as a suffix carrying some
5884 information is a bit risky. Perhaps we should change the encoding
5885 to be something like "_N" instead. In the meantime, do not do
5886 the following check. */
5887 /* Protected Object Subprograms */
5888 if (len == 1 && str [0] == 'N')
5889 return 1;
5890 #endif
5892 /* _E[0-9]+[bs]$ */
5893 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5895 matching = str + 3;
5896 while (isdigit (matching[0]))
5897 matching += 1;
5898 if ((matching[0] == 'b' || matching[0] == 's')
5899 && matching [1] == '\0')
5900 return 1;
5903 /* ??? We should not modify STR directly, as we are doing below. This
5904 is fine in this case, but may become problematic later if we find
5905 that this alternative did not work, and want to try matching
5906 another one from the begining of STR. Since we modified it, we
5907 won't be able to find the begining of the string anymore! */
5908 if (str[0] == 'X')
5910 str += 1;
5911 while (str[0] != '_' && str[0] != '\0')
5913 if (str[0] != 'n' && str[0] != 'b')
5914 return 0;
5915 str += 1;
5919 if (str[0] == '\000')
5920 return 1;
5922 if (str[0] == '_')
5924 if (str[1] != '_' || str[2] == '\000')
5925 return 0;
5926 if (str[2] == '_')
5928 if (strcmp (str + 3, "JM") == 0)
5929 return 1;
5930 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5931 the LJM suffix in favor of the JM one. But we will
5932 still accept LJM as a valid suffix for a reasonable
5933 amount of time, just to allow ourselves to debug programs
5934 compiled using an older version of GNAT. */
5935 if (strcmp (str + 3, "LJM") == 0)
5936 return 1;
5937 if (str[3] != 'X')
5938 return 0;
5939 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5940 || str[4] == 'U' || str[4] == 'P')
5941 return 1;
5942 if (str[4] == 'R' && str[5] != 'T')
5943 return 1;
5944 return 0;
5946 if (!isdigit (str[2]))
5947 return 0;
5948 for (k = 3; str[k] != '\0'; k += 1)
5949 if (!isdigit (str[k]) && str[k] != '_')
5950 return 0;
5951 return 1;
5953 if (str[0] == '$' && isdigit (str[1]))
5955 for (k = 2; str[k] != '\0'; k += 1)
5956 if (!isdigit (str[k]) && str[k] != '_')
5957 return 0;
5958 return 1;
5960 return 0;
5963 /* Return non-zero if the string starting at NAME and ending before
5964 NAME_END contains no capital letters. */
5966 static int
5967 is_valid_name_for_wild_match (const char *name0)
5969 std::string decoded_name = ada_decode (name0);
5970 int i;
5972 /* If the decoded name starts with an angle bracket, it means that
5973 NAME0 does not follow the GNAT encoding format. It should then
5974 not be allowed as a possible wild match. */
5975 if (decoded_name[0] == '<')
5976 return 0;
5978 for (i=0; decoded_name[i] != '\0'; i++)
5979 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5980 return 0;
5982 return 1;
5985 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5986 character which could start a simple name. Assumes that *NAMEP points
5987 somewhere inside the string beginning at NAME0. */
5989 static int
5990 advance_wild_match (const char **namep, const char *name0, char target0)
5992 const char *name = *namep;
5994 while (1)
5996 char t0, t1;
5998 t0 = *name;
5999 if (t0 == '_')
6001 t1 = name[1];
6002 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
6004 name += 1;
6005 if (name == name0 + 5 && startswith (name0, "_ada"))
6006 break;
6007 else
6008 name += 1;
6010 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6011 || name[2] == target0))
6013 name += 2;
6014 break;
6016 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
6018 /* Names like "pkg__B_N__name", where N is a number, are
6019 block-local. We can handle these by simply skipping
6020 the "B_" here. */
6021 name += 4;
6023 else
6024 return 0;
6026 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6027 name += 1;
6028 else
6029 return 0;
6032 *namep = name;
6033 return 1;
6036 /* Return true iff NAME encodes a name of the form prefix.PATN.
6037 Ignores any informational suffixes of NAME (i.e., for which
6038 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6039 simple name. */
6041 static bool
6042 wild_match (const char *name, const char *patn)
6044 const char *p;
6045 const char *name0 = name;
6047 if (startswith (name, "___ghost_"))
6048 name += 9;
6050 while (1)
6052 const char *match = name;
6054 if (*name == *patn)
6056 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6057 if (*p != *name)
6058 break;
6059 if (*p == '\0' && is_name_suffix (name))
6060 return match == name0 || is_valid_name_for_wild_match (name0);
6062 if (name[-1] == '_')
6063 name -= 1;
6065 if (!advance_wild_match (&name, name0, *patn))
6066 return false;
6070 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6071 necessary). OBJFILE is the section containing BLOCK. */
6073 static void
6074 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6075 const struct block *block,
6076 const lookup_name_info &lookup_name,
6077 domain_enum domain, struct objfile *objfile)
6079 struct block_iterator iter;
6080 /* A matching argument symbol, if any. */
6081 struct symbol *arg_sym;
6082 /* Set true when we find a matching non-argument symbol. */
6083 bool found_sym;
6084 struct symbol *sym;
6086 arg_sym = NULL;
6087 found_sym = false;
6088 for (sym = block_iter_match_first (block, lookup_name, &iter);
6089 sym != NULL;
6090 sym = block_iter_match_next (lookup_name, &iter))
6092 if (symbol_matches_domain (sym->language (), sym->domain (), domain))
6094 if (sym->aclass () != LOC_UNRESOLVED)
6096 if (sym->is_argument ())
6097 arg_sym = sym;
6098 else
6100 found_sym = true;
6101 add_defn_to_vec (result,
6102 fixup_symbol_section (sym, objfile),
6103 block);
6109 /* Handle renamings. */
6111 if (ada_add_block_renamings (result, block, lookup_name, domain))
6112 found_sym = true;
6114 if (!found_sym && arg_sym != NULL)
6116 add_defn_to_vec (result,
6117 fixup_symbol_section (arg_sym, objfile),
6118 block);
6121 if (!lookup_name.ada ().wild_match_p ())
6123 arg_sym = NULL;
6124 found_sym = false;
6125 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6126 const char *name = ada_lookup_name.c_str ();
6127 size_t name_len = ada_lookup_name.size ();
6129 ALL_BLOCK_SYMBOLS (block, iter, sym)
6131 if (symbol_matches_domain (sym->language (),
6132 sym->domain (), domain))
6134 int cmp;
6136 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6137 if (cmp == 0)
6139 cmp = !startswith (sym->linkage_name (), "_ada_");
6140 if (cmp == 0)
6141 cmp = strncmp (name, sym->linkage_name () + 5,
6142 name_len);
6145 if (cmp == 0
6146 && is_name_suffix (sym->linkage_name () + name_len + 5))
6148 if (sym->aclass () != LOC_UNRESOLVED)
6150 if (sym->is_argument ())
6151 arg_sym = sym;
6152 else
6154 found_sym = true;
6155 add_defn_to_vec (result,
6156 fixup_symbol_section (sym, objfile),
6157 block);
6164 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6165 They aren't parameters, right? */
6166 if (!found_sym && arg_sym != NULL)
6168 add_defn_to_vec (result,
6169 fixup_symbol_section (arg_sym, objfile),
6170 block);
6176 /* Symbol Completion */
6178 /* See symtab.h. */
6180 bool
6181 ada_lookup_name_info::matches
6182 (const char *sym_name,
6183 symbol_name_match_type match_type,
6184 completion_match_result *comp_match_res) const
6186 bool match = false;
6187 const char *text = m_encoded_name.c_str ();
6188 size_t text_len = m_encoded_name.size ();
6190 /* First, test against the fully qualified name of the symbol. */
6192 if (strncmp (sym_name, text, text_len) == 0)
6193 match = true;
6195 std::string decoded_name = ada_decode (sym_name);
6196 if (match && !m_encoded_p)
6198 /* One needed check before declaring a positive match is to verify
6199 that iff we are doing a verbatim match, the decoded version
6200 of the symbol name starts with '<'. Otherwise, this symbol name
6201 is not a suitable completion. */
6203 bool has_angle_bracket = (decoded_name[0] == '<');
6204 match = (has_angle_bracket == m_verbatim_p);
6207 if (match && !m_verbatim_p)
6209 /* When doing non-verbatim match, another check that needs to
6210 be done is to verify that the potentially matching symbol name
6211 does not include capital letters, because the ada-mode would
6212 not be able to understand these symbol names without the
6213 angle bracket notation. */
6214 const char *tmp;
6216 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6217 if (*tmp != '\0')
6218 match = false;
6221 /* Second: Try wild matching... */
6223 if (!match && m_wild_match_p)
6225 /* Since we are doing wild matching, this means that TEXT
6226 may represent an unqualified symbol name. We therefore must
6227 also compare TEXT against the unqualified name of the symbol. */
6228 sym_name = ada_unqualified_name (decoded_name.c_str ());
6230 if (strncmp (sym_name, text, text_len) == 0)
6231 match = true;
6234 /* Finally: If we found a match, prepare the result to return. */
6236 if (!match)
6237 return false;
6239 if (comp_match_res != NULL)
6241 std::string &match_str = comp_match_res->match.storage ();
6243 if (!m_encoded_p)
6244 match_str = ada_decode (sym_name);
6245 else
6247 if (m_verbatim_p)
6248 match_str = add_angle_brackets (sym_name);
6249 else
6250 match_str = sym_name;
6254 comp_match_res->set_match (match_str.c_str ());
6257 return true;
6260 /* Field Access */
6262 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6263 for tagged types. */
6265 static int
6266 ada_is_dispatch_table_ptr_type (struct type *type)
6268 const char *name;
6270 if (type->code () != TYPE_CODE_PTR)
6271 return 0;
6273 name = type->target_type ()->name ();
6274 if (name == NULL)
6275 return 0;
6277 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6280 /* Return non-zero if TYPE is an interface tag. */
6282 static int
6283 ada_is_interface_tag (struct type *type)
6285 const char *name = type->name ();
6287 if (name == NULL)
6288 return 0;
6290 return (strcmp (name, "ada__tags__interface_tag") == 0);
6293 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6294 to be invisible to users. */
6297 ada_is_ignored_field (struct type *type, int field_num)
6299 if (field_num < 0 || field_num > type->num_fields ())
6300 return 1;
6302 /* Check the name of that field. */
6304 const char *name = type->field (field_num).name ();
6306 /* Anonymous field names should not be printed.
6307 brobecker/2007-02-20: I don't think this can actually happen
6308 but we don't want to print the value of anonymous fields anyway. */
6309 if (name == NULL)
6310 return 1;
6312 /* Normally, fields whose name start with an underscore ("_")
6313 are fields that have been internally generated by the compiler,
6314 and thus should not be printed. The "_parent" field is special,
6315 however: This is a field internally generated by the compiler
6316 for tagged types, and it contains the components inherited from
6317 the parent type. This field should not be printed as is, but
6318 should not be ignored either. */
6319 if (name[0] == '_' && !startswith (name, "_parent"))
6320 return 1;
6322 /* The compiler doesn't document this, but sometimes it emits
6323 a field whose name starts with a capital letter, like 'V148s'.
6324 These aren't marked as artificial in any way, but we know they
6325 should be ignored. However, wrapper fields should not be
6326 ignored. */
6327 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6329 /* Wrapper field. */
6331 else if (isupper (name[0]))
6332 return 1;
6335 /* If this is the dispatch table of a tagged type or an interface tag,
6336 then ignore. */
6337 if (ada_is_tagged_type (type, 1)
6338 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6339 || ada_is_interface_tag (type->field (field_num).type ())))
6340 return 1;
6342 /* Not a special field, so it should not be ignored. */
6343 return 0;
6346 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6347 pointer or reference type whose ultimate target has a tag field. */
6350 ada_is_tagged_type (struct type *type, int refok)
6352 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6355 /* True iff TYPE represents the type of X'Tag */
6358 ada_is_tag_type (struct type *type)
6360 type = ada_check_typedef (type);
6362 if (type == NULL || type->code () != TYPE_CODE_PTR)
6363 return 0;
6364 else
6366 const char *name = ada_type_name (type->target_type ());
6368 return (name != NULL
6369 && strcmp (name, "ada__tags__dispatch_table") == 0);
6373 /* The type of the tag on VAL. */
6375 static struct type *
6376 ada_tag_type (struct value *val)
6378 return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6381 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6382 retired at Ada 05). */
6384 static int
6385 is_ada95_tag (struct value *tag)
6387 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6390 /* The value of the tag on VAL. */
6392 static struct value *
6393 ada_value_tag (struct value *val)
6395 return ada_value_struct_elt (val, "_tag", 0);
6398 /* The value of the tag on the object of type TYPE whose contents are
6399 saved at VALADDR, if it is non-null, or is at memory address
6400 ADDRESS. */
6402 static struct value *
6403 value_tag_from_contents_and_address (struct type *type,
6404 const gdb_byte *valaddr,
6405 CORE_ADDR address)
6407 int tag_byte_offset;
6408 struct type *tag_type;
6410 gdb::array_view<const gdb_byte> contents;
6411 if (valaddr != nullptr)
6412 contents = gdb::make_array_view (valaddr, type->length ());
6413 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6414 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6415 NULL, NULL, NULL))
6417 const gdb_byte *valaddr1 = ((valaddr == NULL)
6418 ? NULL
6419 : valaddr + tag_byte_offset);
6420 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6422 return value_from_contents_and_address (tag_type, valaddr1, address1);
6424 return NULL;
6427 static struct type *
6428 type_from_tag (struct value *tag)
6430 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6432 if (type_name != NULL)
6433 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6434 return NULL;
6437 /* Given a value OBJ of a tagged type, return a value of this
6438 type at the base address of the object. The base address, as
6439 defined in Ada.Tags, it is the address of the primary tag of
6440 the object, and therefore where the field values of its full
6441 view can be fetched. */
6443 struct value *
6444 ada_tag_value_at_base_address (struct value *obj)
6446 struct value *val;
6447 LONGEST offset_to_top = 0;
6448 struct type *ptr_type, *obj_type;
6449 struct value *tag;
6450 CORE_ADDR base_address;
6452 obj_type = value_type (obj);
6454 /* It is the responsability of the caller to deref pointers. */
6456 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6457 return obj;
6459 tag = ada_value_tag (obj);
6460 if (!tag)
6461 return obj;
6463 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6465 if (is_ada95_tag (tag))
6466 return obj;
6468 struct type *offset_type
6469 = language_lookup_primitive_type (language_def (language_ada),
6470 target_gdbarch(), "storage_offset");
6471 ptr_type = lookup_pointer_type (offset_type);
6472 val = value_cast (ptr_type, tag);
6473 if (!val)
6474 return obj;
6476 /* It is perfectly possible that an exception be raised while
6477 trying to determine the base address, just like for the tag;
6478 see ada_tag_name for more details. We do not print the error
6479 message for the same reason. */
6483 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6486 catch (const gdb_exception_error &e)
6488 return obj;
6491 /* If offset is null, nothing to do. */
6493 if (offset_to_top == 0)
6494 return obj;
6496 /* -1 is a special case in Ada.Tags; however, what should be done
6497 is not quite clear from the documentation. So do nothing for
6498 now. */
6500 if (offset_to_top == -1)
6501 return obj;
6503 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6504 top is used. In this situation the offset is stored just after
6505 the tag, in the object itself. */
6506 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6507 if (offset_to_top == last)
6509 struct value *tem = value_addr (tag);
6510 tem = value_ptradd (tem, 1);
6511 tem = value_cast (ptr_type, tem);
6512 offset_to_top = value_as_long (value_ind (tem));
6515 if (offset_to_top > 0)
6517 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6518 from the base address. This was however incompatible with
6519 C++ dispatch table: C++ uses a *negative* value to *add*
6520 to the base address. Ada's convention has therefore been
6521 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6522 use the same convention. Here, we support both cases by
6523 checking the sign of OFFSET_TO_TOP. */
6524 offset_to_top = -offset_to_top;
6527 base_address = value_address (obj) + offset_to_top;
6528 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6530 /* Make sure that we have a proper tag at the new address.
6531 Otherwise, offset_to_top is bogus (which can happen when
6532 the object is not initialized yet). */
6534 if (!tag)
6535 return obj;
6537 obj_type = type_from_tag (tag);
6539 if (!obj_type)
6540 return obj;
6542 return value_from_contents_and_address (obj_type, NULL, base_address);
6545 /* Return the "ada__tags__type_specific_data" type. */
6547 static struct type *
6548 ada_get_tsd_type (struct inferior *inf)
6550 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6552 if (data->tsd_type == 0)
6553 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6554 return data->tsd_type;
6557 /* Return the TSD (type-specific data) associated to the given TAG.
6558 TAG is assumed to be the tag of a tagged-type entity.
6560 May return NULL if we are unable to get the TSD. */
6562 static struct value *
6563 ada_get_tsd_from_tag (struct value *tag)
6565 struct value *val;
6566 struct type *type;
6568 /* First option: The TSD is simply stored as a field of our TAG.
6569 Only older versions of GNAT would use this format, but we have
6570 to test it first, because there are no visible markers for
6571 the current approach except the absence of that field. */
6573 val = ada_value_struct_elt (tag, "tsd", 1);
6574 if (val)
6575 return val;
6577 /* Try the second representation for the dispatch table (in which
6578 there is no explicit 'tsd' field in the referent of the tag pointer,
6579 and instead the tsd pointer is stored just before the dispatch
6580 table. */
6582 type = ada_get_tsd_type (current_inferior());
6583 if (type == NULL)
6584 return NULL;
6585 type = lookup_pointer_type (lookup_pointer_type (type));
6586 val = value_cast (type, tag);
6587 if (val == NULL)
6588 return NULL;
6589 return value_ind (value_ptradd (val, -1));
6592 /* Given the TSD of a tag (type-specific data), return a string
6593 containing the name of the associated type.
6595 May return NULL if we are unable to determine the tag name. */
6597 static gdb::unique_xmalloc_ptr<char>
6598 ada_tag_name_from_tsd (struct value *tsd)
6600 struct value *val;
6602 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6603 if (val == NULL)
6604 return NULL;
6605 gdb::unique_xmalloc_ptr<char> buffer
6606 = target_read_string (value_as_address (val), INT_MAX);
6607 if (buffer == nullptr)
6608 return nullptr;
6612 /* Let this throw an exception on error. If the data is
6613 uninitialized, we'd rather not have the user see a
6614 warning. */
6615 const char *folded = ada_fold_name (buffer.get (), true);
6616 return make_unique_xstrdup (folded);
6618 catch (const gdb_exception &)
6620 return nullptr;
6624 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6625 a C string.
6627 Return NULL if the TAG is not an Ada tag, or if we were unable to
6628 determine the name of that tag. */
6630 gdb::unique_xmalloc_ptr<char>
6631 ada_tag_name (struct value *tag)
6633 gdb::unique_xmalloc_ptr<char> name;
6635 if (!ada_is_tag_type (value_type (tag)))
6636 return NULL;
6638 /* It is perfectly possible that an exception be raised while trying
6639 to determine the TAG's name, even under normal circumstances:
6640 The associated variable may be uninitialized or corrupted, for
6641 instance. We do not let any exception propagate past this point.
6642 instead we return NULL.
6644 We also do not print the error message either (which often is very
6645 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6646 the caller print a more meaningful message if necessary. */
6649 struct value *tsd = ada_get_tsd_from_tag (tag);
6651 if (tsd != NULL)
6652 name = ada_tag_name_from_tsd (tsd);
6654 catch (const gdb_exception_error &e)
6658 return name;
6661 /* The parent type of TYPE, or NULL if none. */
6663 struct type *
6664 ada_parent_type (struct type *type)
6666 int i;
6668 type = ada_check_typedef (type);
6670 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6671 return NULL;
6673 for (i = 0; i < type->num_fields (); i += 1)
6674 if (ada_is_parent_field (type, i))
6676 struct type *parent_type = type->field (i).type ();
6678 /* If the _parent field is a pointer, then dereference it. */
6679 if (parent_type->code () == TYPE_CODE_PTR)
6680 parent_type = parent_type->target_type ();
6681 /* If there is a parallel XVS type, get the actual base type. */
6682 parent_type = ada_get_base_type (parent_type);
6684 return ada_check_typedef (parent_type);
6687 return NULL;
6690 /* True iff field number FIELD_NUM of structure type TYPE contains the
6691 parent-type (inherited) fields of a derived type. Assumes TYPE is
6692 a structure type with at least FIELD_NUM+1 fields. */
6695 ada_is_parent_field (struct type *type, int field_num)
6697 const char *name = ada_check_typedef (type)->field (field_num).name ();
6699 return (name != NULL
6700 && (startswith (name, "PARENT")
6701 || startswith (name, "_parent")));
6704 /* True iff field number FIELD_NUM of structure type TYPE is a
6705 transparent wrapper field (which should be silently traversed when doing
6706 field selection and flattened when printing). Assumes TYPE is a
6707 structure type with at least FIELD_NUM+1 fields. Such fields are always
6708 structures. */
6711 ada_is_wrapper_field (struct type *type, int field_num)
6713 const char *name = type->field (field_num).name ();
6715 if (name != NULL && strcmp (name, "RETVAL") == 0)
6717 /* This happens in functions with "out" or "in out" parameters
6718 which are passed by copy. For such functions, GNAT describes
6719 the function's return type as being a struct where the return
6720 value is in a field called RETVAL, and where the other "out"
6721 or "in out" parameters are fields of that struct. This is not
6722 a wrapper. */
6723 return 0;
6726 return (name != NULL
6727 && (startswith (name, "PARENT")
6728 || strcmp (name, "REP") == 0
6729 || startswith (name, "_parent")
6730 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6733 /* True iff field number FIELD_NUM of structure or union type TYPE
6734 is a variant wrapper. Assumes TYPE is a structure type with at least
6735 FIELD_NUM+1 fields. */
6738 ada_is_variant_part (struct type *type, int field_num)
6740 /* Only Ada types are eligible. */
6741 if (!ADA_TYPE_P (type))
6742 return 0;
6744 struct type *field_type = type->field (field_num).type ();
6746 return (field_type->code () == TYPE_CODE_UNION
6747 || (is_dynamic_field (type, field_num)
6748 && (field_type->target_type ()->code ()
6749 == TYPE_CODE_UNION)));
6752 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6753 whose discriminants are contained in the record type OUTER_TYPE,
6754 returns the type of the controlling discriminant for the variant.
6755 May return NULL if the type could not be found. */
6757 struct type *
6758 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6760 const char *name = ada_variant_discrim_name (var_type);
6762 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6765 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6766 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6767 represents a 'when others' clause; otherwise 0. */
6769 static int
6770 ada_is_others_clause (struct type *type, int field_num)
6772 const char *name = type->field (field_num).name ();
6774 return (name != NULL && name[0] == 'O');
6777 /* Assuming that TYPE0 is the type of the variant part of a record,
6778 returns the name of the discriminant controlling the variant.
6779 The value is valid until the next call to ada_variant_discrim_name. */
6781 const char *
6782 ada_variant_discrim_name (struct type *type0)
6784 static std::string result;
6785 struct type *type;
6786 const char *name;
6787 const char *discrim_end;
6788 const char *discrim_start;
6790 if (type0->code () == TYPE_CODE_PTR)
6791 type = type0->target_type ();
6792 else
6793 type = type0;
6795 name = ada_type_name (type);
6797 if (name == NULL || name[0] == '\000')
6798 return "";
6800 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6801 discrim_end -= 1)
6803 if (startswith (discrim_end, "___XVN"))
6804 break;
6806 if (discrim_end == name)
6807 return "";
6809 for (discrim_start = discrim_end; discrim_start != name + 3;
6810 discrim_start -= 1)
6812 if (discrim_start == name + 1)
6813 return "";
6814 if ((discrim_start > name + 3
6815 && startswith (discrim_start - 3, "___"))
6816 || discrim_start[-1] == '.')
6817 break;
6820 result = std::string (discrim_start, discrim_end - discrim_start);
6821 return result.c_str ();
6824 /* Scan STR for a subtype-encoded number, beginning at position K.
6825 Put the position of the character just past the number scanned in
6826 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6827 Return 1 if there was a valid number at the given position, and 0
6828 otherwise. A "subtype-encoded" number consists of the absolute value
6829 in decimal, followed by the letter 'm' to indicate a negative number.
6830 Assumes 0m does not occur. */
6833 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6835 ULONGEST RU;
6837 if (!isdigit (str[k]))
6838 return 0;
6840 /* Do it the hard way so as not to make any assumption about
6841 the relationship of unsigned long (%lu scan format code) and
6842 LONGEST. */
6843 RU = 0;
6844 while (isdigit (str[k]))
6846 RU = RU * 10 + (str[k] - '0');
6847 k += 1;
6850 if (str[k] == 'm')
6852 if (R != NULL)
6853 *R = (-(LONGEST) (RU - 1)) - 1;
6854 k += 1;
6856 else if (R != NULL)
6857 *R = (LONGEST) RU;
6859 /* NOTE on the above: Technically, C does not say what the results of
6860 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6861 number representable as a LONGEST (although either would probably work
6862 in most implementations). When RU>0, the locution in the then branch
6863 above is always equivalent to the negative of RU. */
6865 if (new_k != NULL)
6866 *new_k = k;
6867 return 1;
6870 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6871 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6872 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6874 static int
6875 ada_in_variant (LONGEST val, struct type *type, int field_num)
6877 const char *name = type->field (field_num).name ();
6878 int p;
6880 p = 0;
6881 while (1)
6883 switch (name[p])
6885 case '\0':
6886 return 0;
6887 case 'S':
6889 LONGEST W;
6891 if (!ada_scan_number (name, p + 1, &W, &p))
6892 return 0;
6893 if (val == W)
6894 return 1;
6895 break;
6897 case 'R':
6899 LONGEST L, U;
6901 if (!ada_scan_number (name, p + 1, &L, &p)
6902 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6903 return 0;
6904 if (val >= L && val <= U)
6905 return 1;
6906 break;
6908 case 'O':
6909 return 1;
6910 default:
6911 return 0;
6916 /* FIXME: Lots of redundancy below. Try to consolidate. */
6918 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6919 ARG_TYPE, extract and return the value of one of its (non-static)
6920 fields. FIELDNO says which field. Differs from value_primitive_field
6921 only in that it can handle packed values of arbitrary type. */
6923 struct value *
6924 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6925 struct type *arg_type)
6927 struct type *type;
6929 arg_type = ada_check_typedef (arg_type);
6930 type = arg_type->field (fieldno).type ();
6932 /* Handle packed fields. It might be that the field is not packed
6933 relative to its containing structure, but the structure itself is
6934 packed; in this case we must take the bit-field path. */
6935 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
6937 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6938 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6940 return ada_value_primitive_packed_val (arg1,
6941 value_contents (arg1).data (),
6942 offset + bit_pos / 8,
6943 bit_pos % 8, bit_size, type);
6945 else
6946 return value_primitive_field (arg1, offset, fieldno, arg_type);
6949 /* Find field with name NAME in object of type TYPE. If found,
6950 set the following for each argument that is non-null:
6951 - *FIELD_TYPE_P to the field's type;
6952 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6953 an object of that type;
6954 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6955 - *BIT_SIZE_P to its size in bits if the field is packed, and
6956 0 otherwise;
6957 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6958 fields up to but not including the desired field, or by the total
6959 number of fields if not found. A NULL value of NAME never
6960 matches; the function just counts visible fields in this case.
6962 Notice that we need to handle when a tagged record hierarchy
6963 has some components with the same name, like in this scenario:
6965 type Top_T is tagged record
6966 N : Integer := 1;
6967 U : Integer := 974;
6968 A : Integer := 48;
6969 end record;
6971 type Middle_T is new Top.Top_T with record
6972 N : Character := 'a';
6973 C : Integer := 3;
6974 end record;
6976 type Bottom_T is new Middle.Middle_T with record
6977 N : Float := 4.0;
6978 C : Character := '5';
6979 X : Integer := 6;
6980 A : Character := 'J';
6981 end record;
6983 Let's say we now have a variable declared and initialized as follow:
6985 TC : Top_A := new Bottom_T;
6987 And then we use this variable to call this function
6989 procedure Assign (Obj: in out Top_T; TV : Integer);
6991 as follow:
6993 Assign (Top_T (B), 12);
6995 Now, we're in the debugger, and we're inside that procedure
6996 then and we want to print the value of obj.c:
6998 Usually, the tagged record or one of the parent type owns the
6999 component to print and there's no issue but in this particular
7000 case, what does it mean to ask for Obj.C? Since the actual
7001 type for object is type Bottom_T, it could mean two things: type
7002 component C from the Middle_T view, but also component C from
7003 Bottom_T. So in that "undefined" case, when the component is
7004 not found in the non-resolved type (which includes all the
7005 components of the parent type), then resolve it and see if we
7006 get better luck once expanded.
7008 In the case of homonyms in the derived tagged type, we don't
7009 guaranty anything, and pick the one that's easiest for us
7010 to program.
7012 Returns 1 if found, 0 otherwise. */
7014 static int
7015 find_struct_field (const char *name, struct type *type, int offset,
7016 struct type **field_type_p,
7017 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
7018 int *index_p)
7020 int i;
7021 int parent_offset = -1;
7023 type = ada_check_typedef (type);
7025 if (field_type_p != NULL)
7026 *field_type_p = NULL;
7027 if (byte_offset_p != NULL)
7028 *byte_offset_p = 0;
7029 if (bit_offset_p != NULL)
7030 *bit_offset_p = 0;
7031 if (bit_size_p != NULL)
7032 *bit_size_p = 0;
7034 for (i = 0; i < type->num_fields (); i += 1)
7036 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7037 type. However, we only need the values to be correct when
7038 the caller asks for them. */
7039 int bit_pos = 0, fld_offset = 0;
7040 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7042 bit_pos = type->field (i).loc_bitpos ();
7043 fld_offset = offset + bit_pos / 8;
7046 const char *t_field_name = type->field (i).name ();
7048 if (t_field_name == NULL)
7049 continue;
7051 else if (ada_is_parent_field (type, i))
7053 /* This is a field pointing us to the parent type of a tagged
7054 type. As hinted in this function's documentation, we give
7055 preference to fields in the current record first, so what
7056 we do here is just record the index of this field before
7057 we skip it. If it turns out we couldn't find our field
7058 in the current record, then we'll get back to it and search
7059 inside it whether the field might exist in the parent. */
7061 parent_offset = i;
7062 continue;
7065 else if (name != NULL && field_name_match (t_field_name, name))
7067 int bit_size = TYPE_FIELD_BITSIZE (type, i);
7069 if (field_type_p != NULL)
7070 *field_type_p = type->field (i).type ();
7071 if (byte_offset_p != NULL)
7072 *byte_offset_p = fld_offset;
7073 if (bit_offset_p != NULL)
7074 *bit_offset_p = bit_pos % 8;
7075 if (bit_size_p != NULL)
7076 *bit_size_p = bit_size;
7077 return 1;
7079 else if (ada_is_wrapper_field (type, i))
7081 if (find_struct_field (name, type->field (i).type (), fld_offset,
7082 field_type_p, byte_offset_p, bit_offset_p,
7083 bit_size_p, index_p))
7084 return 1;
7086 else if (ada_is_variant_part (type, i))
7088 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7089 fixed type?? */
7090 int j;
7091 struct type *field_type
7092 = ada_check_typedef (type->field (i).type ());
7094 for (j = 0; j < field_type->num_fields (); j += 1)
7096 if (find_struct_field (name, field_type->field (j).type (),
7097 fld_offset
7098 + field_type->field (j).loc_bitpos () / 8,
7099 field_type_p, byte_offset_p,
7100 bit_offset_p, bit_size_p, index_p))
7101 return 1;
7104 else if (index_p != NULL)
7105 *index_p += 1;
7108 /* Field not found so far. If this is a tagged type which
7109 has a parent, try finding that field in the parent now. */
7111 if (parent_offset != -1)
7113 /* As above, only compute the offset when truly needed. */
7114 int fld_offset = offset;
7115 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7117 int bit_pos = type->field (parent_offset).loc_bitpos ();
7118 fld_offset += bit_pos / 8;
7121 if (find_struct_field (name, type->field (parent_offset).type (),
7122 fld_offset, field_type_p, byte_offset_p,
7123 bit_offset_p, bit_size_p, index_p))
7124 return 1;
7127 return 0;
7130 /* Number of user-visible fields in record type TYPE. */
7132 static int
7133 num_visible_fields (struct type *type)
7135 int n;
7137 n = 0;
7138 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7139 return n;
7142 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7143 and search in it assuming it has (class) type TYPE.
7144 If found, return value, else return NULL.
7146 Searches recursively through wrapper fields (e.g., '_parent').
7148 In the case of homonyms in the tagged types, please refer to the
7149 long explanation in find_struct_field's function documentation. */
7151 static struct value *
7152 ada_search_struct_field (const char *name, struct value *arg, int offset,
7153 struct type *type)
7155 int i;
7156 int parent_offset = -1;
7158 type = ada_check_typedef (type);
7159 for (i = 0; i < type->num_fields (); i += 1)
7161 const char *t_field_name = type->field (i).name ();
7163 if (t_field_name == NULL)
7164 continue;
7166 else if (ada_is_parent_field (type, i))
7168 /* This is a field pointing us to the parent type of a tagged
7169 type. As hinted in this function's documentation, we give
7170 preference to fields in the current record first, so what
7171 we do here is just record the index of this field before
7172 we skip it. If it turns out we couldn't find our field
7173 in the current record, then we'll get back to it and search
7174 inside it whether the field might exist in the parent. */
7176 parent_offset = i;
7177 continue;
7180 else if (field_name_match (t_field_name, name))
7181 return ada_value_primitive_field (arg, offset, i, type);
7183 else if (ada_is_wrapper_field (type, i))
7185 struct value *v = /* Do not let indent join lines here. */
7186 ada_search_struct_field (name, arg,
7187 offset + type->field (i).loc_bitpos () / 8,
7188 type->field (i).type ());
7190 if (v != NULL)
7191 return v;
7194 else if (ada_is_variant_part (type, i))
7196 /* PNH: Do we ever get here? See find_struct_field. */
7197 int j;
7198 struct type *field_type = ada_check_typedef (type->field (i).type ());
7199 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7201 for (j = 0; j < field_type->num_fields (); j += 1)
7203 struct value *v = ada_search_struct_field /* Force line
7204 break. */
7205 (name, arg,
7206 var_offset + field_type->field (j).loc_bitpos () / 8,
7207 field_type->field (j).type ());
7209 if (v != NULL)
7210 return v;
7215 /* Field not found so far. If this is a tagged type which
7216 has a parent, try finding that field in the parent now. */
7218 if (parent_offset != -1)
7220 struct value *v = ada_search_struct_field (
7221 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7222 type->field (parent_offset).type ());
7224 if (v != NULL)
7225 return v;
7228 return NULL;
7231 static struct value *ada_index_struct_field_1 (int *, struct value *,
7232 int, struct type *);
7235 /* Return field #INDEX in ARG, where the index is that returned by
7236 * find_struct_field through its INDEX_P argument. Adjust the address
7237 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7238 * If found, return value, else return NULL. */
7240 static struct value *
7241 ada_index_struct_field (int index, struct value *arg, int offset,
7242 struct type *type)
7244 return ada_index_struct_field_1 (&index, arg, offset, type);
7248 /* Auxiliary function for ada_index_struct_field. Like
7249 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7250 * *INDEX_P. */
7252 static struct value *
7253 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7254 struct type *type)
7256 int i;
7257 type = ada_check_typedef (type);
7259 for (i = 0; i < type->num_fields (); i += 1)
7261 if (type->field (i).name () == NULL)
7262 continue;
7263 else if (ada_is_wrapper_field (type, i))
7265 struct value *v = /* Do not let indent join lines here. */
7266 ada_index_struct_field_1 (index_p, arg,
7267 offset + type->field (i).loc_bitpos () / 8,
7268 type->field (i).type ());
7270 if (v != NULL)
7271 return v;
7274 else if (ada_is_variant_part (type, i))
7276 /* PNH: Do we ever get here? See ada_search_struct_field,
7277 find_struct_field. */
7278 error (_("Cannot assign this kind of variant record"));
7280 else if (*index_p == 0)
7281 return ada_value_primitive_field (arg, offset, i, type);
7282 else
7283 *index_p -= 1;
7285 return NULL;
7288 /* Return a string representation of type TYPE. */
7290 static std::string
7291 type_as_string (struct type *type)
7293 string_file tmp_stream;
7295 type_print (type, "", &tmp_stream, -1);
7297 return tmp_stream.release ();
7300 /* Given a type TYPE, look up the type of the component of type named NAME.
7301 If DISPP is non-null, add its byte displacement from the beginning of a
7302 structure (pointed to by a value) of type TYPE to *DISPP (does not
7303 work for packed fields).
7305 Matches any field whose name has NAME as a prefix, possibly
7306 followed by "___".
7308 TYPE can be either a struct or union. If REFOK, TYPE may also
7309 be a (pointer or reference)+ to a struct or union, and the
7310 ultimate target type will be searched.
7312 Looks recursively into variant clauses and parent types.
7314 In the case of homonyms in the tagged types, please refer to the
7315 long explanation in find_struct_field's function documentation.
7317 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7318 TYPE is not a type of the right kind. */
7320 static struct type *
7321 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7322 int noerr)
7324 int i;
7325 int parent_offset = -1;
7327 if (name == NULL)
7328 goto BadName;
7330 if (refok && type != NULL)
7331 while (1)
7333 type = ada_check_typedef (type);
7334 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7335 break;
7336 type = type->target_type ();
7339 if (type == NULL
7340 || (type->code () != TYPE_CODE_STRUCT
7341 && type->code () != TYPE_CODE_UNION))
7343 if (noerr)
7344 return NULL;
7346 error (_("Type %s is not a structure or union type"),
7347 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7350 type = to_static_fixed_type (type);
7352 for (i = 0; i < type->num_fields (); i += 1)
7354 const char *t_field_name = type->field (i).name ();
7355 struct type *t;
7357 if (t_field_name == NULL)
7358 continue;
7360 else if (ada_is_parent_field (type, i))
7362 /* This is a field pointing us to the parent type of a tagged
7363 type. As hinted in this function's documentation, we give
7364 preference to fields in the current record first, so what
7365 we do here is just record the index of this field before
7366 we skip it. If it turns out we couldn't find our field
7367 in the current record, then we'll get back to it and search
7368 inside it whether the field might exist in the parent. */
7370 parent_offset = i;
7371 continue;
7374 else if (field_name_match (t_field_name, name))
7375 return type->field (i).type ();
7377 else if (ada_is_wrapper_field (type, i))
7379 t = ada_lookup_struct_elt_type (type->field (i).type (), name,
7380 0, 1);
7381 if (t != NULL)
7382 return t;
7385 else if (ada_is_variant_part (type, i))
7387 int j;
7388 struct type *field_type = ada_check_typedef (type->field (i).type ());
7390 for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7392 /* FIXME pnh 2008/01/26: We check for a field that is
7393 NOT wrapped in a struct, since the compiler sometimes
7394 generates these for unchecked variant types. Revisit
7395 if the compiler changes this practice. */
7396 const char *v_field_name = field_type->field (j).name ();
7398 if (v_field_name != NULL
7399 && field_name_match (v_field_name, name))
7400 t = field_type->field (j).type ();
7401 else
7402 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
7403 name, 0, 1);
7405 if (t != NULL)
7406 return t;
7412 /* Field not found so far. If this is a tagged type which
7413 has a parent, try finding that field in the parent now. */
7415 if (parent_offset != -1)
7417 struct type *t;
7419 t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7420 name, 0, 1);
7421 if (t != NULL)
7422 return t;
7425 BadName:
7426 if (!noerr)
7428 const char *name_str = name != NULL ? name : _("<null>");
7430 error (_("Type %s has no component named %s"),
7431 type_as_string (type).c_str (), name_str);
7434 return NULL;
7437 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7438 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7439 represents an unchecked union (that is, the variant part of a
7440 record that is named in an Unchecked_Union pragma). */
7442 static int
7443 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7445 const char *discrim_name = ada_variant_discrim_name (var_type);
7447 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7451 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7452 within OUTER, determine which variant clause (field number in VAR_TYPE,
7453 numbering from 0) is applicable. Returns -1 if none are. */
7456 ada_which_variant_applies (struct type *var_type, struct value *outer)
7458 int others_clause;
7459 int i;
7460 const char *discrim_name = ada_variant_discrim_name (var_type);
7461 struct value *discrim;
7462 LONGEST discrim_val;
7464 /* Using plain value_from_contents_and_address here causes problems
7465 because we will end up trying to resolve a type that is currently
7466 being constructed. */
7467 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7468 if (discrim == NULL)
7469 return -1;
7470 discrim_val = value_as_long (discrim);
7472 others_clause = -1;
7473 for (i = 0; i < var_type->num_fields (); i += 1)
7475 if (ada_is_others_clause (var_type, i))
7476 others_clause = i;
7477 else if (ada_in_variant (discrim_val, var_type, i))
7478 return i;
7481 return others_clause;
7486 /* Dynamic-Sized Records */
7488 /* Strategy: The type ostensibly attached to a value with dynamic size
7489 (i.e., a size that is not statically recorded in the debugging
7490 data) does not accurately reflect the size or layout of the value.
7491 Our strategy is to convert these values to values with accurate,
7492 conventional types that are constructed on the fly. */
7494 /* There is a subtle and tricky problem here. In general, we cannot
7495 determine the size of dynamic records without its data. However,
7496 the 'struct value' data structure, which GDB uses to represent
7497 quantities in the inferior process (the target), requires the size
7498 of the type at the time of its allocation in order to reserve space
7499 for GDB's internal copy of the data. That's why the
7500 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7501 rather than struct value*s.
7503 However, GDB's internal history variables ($1, $2, etc.) are
7504 struct value*s containing internal copies of the data that are not, in
7505 general, the same as the data at their corresponding addresses in
7506 the target. Fortunately, the types we give to these values are all
7507 conventional, fixed-size types (as per the strategy described
7508 above), so that we don't usually have to perform the
7509 'to_fixed_xxx_type' conversions to look at their values.
7510 Unfortunately, there is one exception: if one of the internal
7511 history variables is an array whose elements are unconstrained
7512 records, then we will need to create distinct fixed types for each
7513 element selected. */
7515 /* The upshot of all of this is that many routines take a (type, host
7516 address, target address) triple as arguments to represent a value.
7517 The host address, if non-null, is supposed to contain an internal
7518 copy of the relevant data; otherwise, the program is to consult the
7519 target at the target address. */
7521 /* Assuming that VAL0 represents a pointer value, the result of
7522 dereferencing it. Differs from value_ind in its treatment of
7523 dynamic-sized types. */
7525 struct value *
7526 ada_value_ind (struct value *val0)
7528 struct value *val = value_ind (val0);
7530 if (ada_is_tagged_type (value_type (val), 0))
7531 val = ada_tag_value_at_base_address (val);
7533 return ada_to_fixed_value (val);
7536 /* The value resulting from dereferencing any "reference to"
7537 qualifiers on VAL0. */
7539 static struct value *
7540 ada_coerce_ref (struct value *val0)
7542 if (value_type (val0)->code () == TYPE_CODE_REF)
7544 struct value *val = val0;
7546 val = coerce_ref (val);
7548 if (ada_is_tagged_type (value_type (val), 0))
7549 val = ada_tag_value_at_base_address (val);
7551 return ada_to_fixed_value (val);
7553 else
7554 return val0;
7557 /* Return the bit alignment required for field #F of template type TYPE. */
7559 static unsigned int
7560 field_alignment (struct type *type, int f)
7562 const char *name = type->field (f).name ();
7563 int len;
7564 int align_offset;
7566 /* The field name should never be null, unless the debugging information
7567 is somehow malformed. In this case, we assume the field does not
7568 require any alignment. */
7569 if (name == NULL)
7570 return 1;
7572 len = strlen (name);
7574 if (!isdigit (name[len - 1]))
7575 return 1;
7577 if (isdigit (name[len - 2]))
7578 align_offset = len - 2;
7579 else
7580 align_offset = len - 1;
7582 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7583 return TARGET_CHAR_BIT;
7585 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7588 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7590 static struct symbol *
7591 ada_find_any_type_symbol (const char *name)
7593 struct symbol *sym;
7595 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7596 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
7597 return sym;
7599 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7600 return sym;
7603 /* Find a type named NAME. Ignores ambiguity. This routine will look
7604 solely for types defined by debug info, it will not search the GDB
7605 primitive types. */
7607 static struct type *
7608 ada_find_any_type (const char *name)
7610 struct symbol *sym = ada_find_any_type_symbol (name);
7612 if (sym != NULL)
7613 return sym->type ();
7615 return NULL;
7618 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7619 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7620 symbol, in which case it is returned. Otherwise, this looks for
7621 symbols whose name is that of NAME_SYM suffixed with "___XR".
7622 Return symbol if found, and NULL otherwise. */
7624 static bool
7625 ada_is_renaming_symbol (struct symbol *name_sym)
7627 const char *name = name_sym->linkage_name ();
7628 return strstr (name, "___XR") != NULL;
7631 /* Because of GNAT encoding conventions, several GDB symbols may match a
7632 given type name. If the type denoted by TYPE0 is to be preferred to
7633 that of TYPE1 for purposes of type printing, return non-zero;
7634 otherwise return 0. */
7637 ada_prefer_type (struct type *type0, struct type *type1)
7639 if (type1 == NULL)
7640 return 1;
7641 else if (type0 == NULL)
7642 return 0;
7643 else if (type1->code () == TYPE_CODE_VOID)
7644 return 1;
7645 else if (type0->code () == TYPE_CODE_VOID)
7646 return 0;
7647 else if (type1->name () == NULL && type0->name () != NULL)
7648 return 1;
7649 else if (ada_is_constrained_packed_array_type (type0))
7650 return 1;
7651 else if (ada_is_array_descriptor_type (type0)
7652 && !ada_is_array_descriptor_type (type1))
7653 return 1;
7654 else
7656 const char *type0_name = type0->name ();
7657 const char *type1_name = type1->name ();
7659 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7660 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7661 return 1;
7663 return 0;
7666 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7667 null. */
7669 const char *
7670 ada_type_name (struct type *type)
7672 if (type == NULL)
7673 return NULL;
7674 return type->name ();
7677 /* Search the list of "descriptive" types associated to TYPE for a type
7678 whose name is NAME. */
7680 static struct type *
7681 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7683 struct type *result, *tmp;
7685 if (ada_ignore_descriptive_types_p)
7686 return NULL;
7688 /* If there no descriptive-type info, then there is no parallel type
7689 to be found. */
7690 if (!HAVE_GNAT_AUX_INFO (type))
7691 return NULL;
7693 result = TYPE_DESCRIPTIVE_TYPE (type);
7694 while (result != NULL)
7696 const char *result_name = ada_type_name (result);
7698 if (result_name == NULL)
7700 warning (_("unexpected null name on descriptive type"));
7701 return NULL;
7704 /* If the names match, stop. */
7705 if (strcmp (result_name, name) == 0)
7706 break;
7708 /* Otherwise, look at the next item on the list, if any. */
7709 if (HAVE_GNAT_AUX_INFO (result))
7710 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7711 else
7712 tmp = NULL;
7714 /* If not found either, try after having resolved the typedef. */
7715 if (tmp != NULL)
7716 result = tmp;
7717 else
7719 result = check_typedef (result);
7720 if (HAVE_GNAT_AUX_INFO (result))
7721 result = TYPE_DESCRIPTIVE_TYPE (result);
7722 else
7723 result = NULL;
7727 /* If we didn't find a match, see whether this is a packed array. With
7728 older compilers, the descriptive type information is either absent or
7729 irrelevant when it comes to packed arrays so the above lookup fails.
7730 Fall back to using a parallel lookup by name in this case. */
7731 if (result == NULL && ada_is_constrained_packed_array_type (type))
7732 return ada_find_any_type (name);
7734 return result;
7737 /* Find a parallel type to TYPE with the specified NAME, using the
7738 descriptive type taken from the debugging information, if available,
7739 and otherwise using the (slower) name-based method. */
7741 static struct type *
7742 ada_find_parallel_type_with_name (struct type *type, const char *name)
7744 struct type *result = NULL;
7746 if (HAVE_GNAT_AUX_INFO (type))
7747 result = find_parallel_type_by_descriptive_type (type, name);
7748 else
7749 result = ada_find_any_type (name);
7751 return result;
7754 /* Same as above, but specify the name of the parallel type by appending
7755 SUFFIX to the name of TYPE. */
7757 struct type *
7758 ada_find_parallel_type (struct type *type, const char *suffix)
7760 char *name;
7761 const char *type_name = ada_type_name (type);
7762 int len;
7764 if (type_name == NULL)
7765 return NULL;
7767 len = strlen (type_name);
7769 name = (char *) alloca (len + strlen (suffix) + 1);
7771 strcpy (name, type_name);
7772 strcpy (name + len, suffix);
7774 return ada_find_parallel_type_with_name (type, name);
7777 /* If TYPE is a variable-size record type, return the corresponding template
7778 type describing its fields. Otherwise, return NULL. */
7780 static struct type *
7781 dynamic_template_type (struct type *type)
7783 type = ada_check_typedef (type);
7785 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7786 || ada_type_name (type) == NULL)
7787 return NULL;
7788 else
7790 int len = strlen (ada_type_name (type));
7792 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7793 return type;
7794 else
7795 return ada_find_parallel_type (type, "___XVE");
7799 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7800 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7802 static int
7803 is_dynamic_field (struct type *templ_type, int field_num)
7805 const char *name = templ_type->field (field_num).name ();
7807 return name != NULL
7808 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7809 && strstr (name, "___XVL") != NULL;
7812 /* The index of the variant field of TYPE, or -1 if TYPE does not
7813 represent a variant record type. */
7815 static int
7816 variant_field_index (struct type *type)
7818 int f;
7820 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7821 return -1;
7823 for (f = 0; f < type->num_fields (); f += 1)
7825 if (ada_is_variant_part (type, f))
7826 return f;
7828 return -1;
7831 /* A record type with no fields. */
7833 static struct type *
7834 empty_record (struct type *templ)
7836 struct type *type = alloc_type_copy (templ);
7838 type->set_code (TYPE_CODE_STRUCT);
7839 INIT_NONE_SPECIFIC (type);
7840 type->set_name ("<empty>");
7841 type->set_length (0);
7842 return type;
7845 /* An ordinary record type (with fixed-length fields) that describes
7846 the value of type TYPE at VALADDR or ADDRESS (see comments at
7847 the beginning of this section) VAL according to GNAT conventions.
7848 DVAL0 should describe the (portion of a) record that contains any
7849 necessary discriminants. It should be NULL if value_type (VAL) is
7850 an outer-level type (i.e., as opposed to a branch of a variant.) A
7851 variant field (unless unchecked) is replaced by a particular branch
7852 of the variant.
7854 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7855 length are not statically known are discarded. As a consequence,
7856 VALADDR, ADDRESS and DVAL0 are ignored.
7858 NOTE: Limitations: For now, we assume that dynamic fields and
7859 variants occupy whole numbers of bytes. However, they need not be
7860 byte-aligned. */
7862 struct type *
7863 ada_template_to_fixed_record_type_1 (struct type *type,
7864 const gdb_byte *valaddr,
7865 CORE_ADDR address, struct value *dval0,
7866 int keep_dynamic_fields)
7868 struct value *dval;
7869 struct type *rtype;
7870 int nfields, bit_len;
7871 int variant_field;
7872 long off;
7873 int fld_bit_len;
7874 int f;
7876 scoped_value_mark mark;
7878 /* Compute the number of fields in this record type that are going
7879 to be processed: unless keep_dynamic_fields, this includes only
7880 fields whose position and length are static will be processed. */
7881 if (keep_dynamic_fields)
7882 nfields = type->num_fields ();
7883 else
7885 nfields = 0;
7886 while (nfields < type->num_fields ()
7887 && !ada_is_variant_part (type, nfields)
7888 && !is_dynamic_field (type, nfields))
7889 nfields++;
7892 rtype = alloc_type_copy (type);
7893 rtype->set_code (TYPE_CODE_STRUCT);
7894 INIT_NONE_SPECIFIC (rtype);
7895 rtype->set_num_fields (nfields);
7896 rtype->set_fields
7897 ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7898 rtype->set_name (ada_type_name (type));
7899 rtype->set_is_fixed_instance (true);
7901 off = 0;
7902 bit_len = 0;
7903 variant_field = -1;
7905 for (f = 0; f < nfields; f += 1)
7907 off = align_up (off, field_alignment (type, f))
7908 + type->field (f).loc_bitpos ();
7909 rtype->field (f).set_loc_bitpos (off);
7910 TYPE_FIELD_BITSIZE (rtype, f) = 0;
7912 if (ada_is_variant_part (type, f))
7914 variant_field = f;
7915 fld_bit_len = 0;
7917 else if (is_dynamic_field (type, f))
7919 const gdb_byte *field_valaddr = valaddr;
7920 CORE_ADDR field_address = address;
7921 struct type *field_type = type->field (f).type ()->target_type ();
7923 if (dval0 == NULL)
7925 /* Using plain value_from_contents_and_address here
7926 causes problems because we will end up trying to
7927 resolve a type that is currently being
7928 constructed. */
7929 dval = value_from_contents_and_address_unresolved (rtype,
7930 valaddr,
7931 address);
7932 rtype = value_type (dval);
7934 else
7935 dval = dval0;
7937 /* If the type referenced by this field is an aligner type, we need
7938 to unwrap that aligner type, because its size might not be set.
7939 Keeping the aligner type would cause us to compute the wrong
7940 size for this field, impacting the offset of the all the fields
7941 that follow this one. */
7942 if (ada_is_aligner_type (field_type))
7944 long field_offset = type->field (f).loc_bitpos ();
7946 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7947 field_address = cond_offset_target (field_address, field_offset);
7948 field_type = ada_aligned_type (field_type);
7951 field_valaddr = cond_offset_host (field_valaddr,
7952 off / TARGET_CHAR_BIT);
7953 field_address = cond_offset_target (field_address,
7954 off / TARGET_CHAR_BIT);
7956 /* Get the fixed type of the field. Note that, in this case,
7957 we do not want to get the real type out of the tag: if
7958 the current field is the parent part of a tagged record,
7959 we will get the tag of the object. Clearly wrong: the real
7960 type of the parent is not the real type of the child. We
7961 would end up in an infinite loop. */
7962 field_type = ada_get_base_type (field_type);
7963 field_type = ada_to_fixed_type (field_type, field_valaddr,
7964 field_address, dval, 0);
7966 rtype->field (f).set_type (field_type);
7967 rtype->field (f).set_name (type->field (f).name ());
7968 /* The multiplication can potentially overflow. But because
7969 the field length has been size-checked just above, and
7970 assuming that the maximum size is a reasonable value,
7971 an overflow should not happen in practice. So rather than
7972 adding overflow recovery code to this already complex code,
7973 we just assume that it's not going to happen. */
7974 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7976 else
7978 /* Note: If this field's type is a typedef, it is important
7979 to preserve the typedef layer.
7981 Otherwise, we might be transforming a typedef to a fat
7982 pointer (encoding a pointer to an unconstrained array),
7983 into a basic fat pointer (encoding an unconstrained
7984 array). As both types are implemented using the same
7985 structure, the typedef is the only clue which allows us
7986 to distinguish between the two options. Stripping it
7987 would prevent us from printing this field appropriately. */
7988 rtype->field (f).set_type (type->field (f).type ());
7989 rtype->field (f).set_name (type->field (f).name ());
7990 if (TYPE_FIELD_BITSIZE (type, f) > 0)
7991 fld_bit_len =
7992 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7993 else
7995 struct type *field_type = type->field (f).type ();
7997 /* We need to be careful of typedefs when computing
7998 the length of our field. If this is a typedef,
7999 get the length of the target type, not the length
8000 of the typedef. */
8001 if (field_type->code () == TYPE_CODE_TYPEDEF)
8002 field_type = ada_typedef_target_type (field_type);
8004 fld_bit_len =
8005 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
8008 if (off + fld_bit_len > bit_len)
8009 bit_len = off + fld_bit_len;
8010 off += fld_bit_len;
8011 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
8014 /* We handle the variant part, if any, at the end because of certain
8015 odd cases in which it is re-ordered so as NOT to be the last field of
8016 the record. This can happen in the presence of representation
8017 clauses. */
8018 if (variant_field >= 0)
8020 struct type *branch_type;
8022 off = rtype->field (variant_field).loc_bitpos ();
8024 if (dval0 == NULL)
8026 /* Using plain value_from_contents_and_address here causes
8027 problems because we will end up trying to resolve a type
8028 that is currently being constructed. */
8029 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
8030 address);
8031 rtype = value_type (dval);
8033 else
8034 dval = dval0;
8036 branch_type =
8037 to_fixed_variant_branch_type
8038 (type->field (variant_field).type (),
8039 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
8040 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
8041 if (branch_type == NULL)
8043 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
8044 rtype->field (f - 1) = rtype->field (f);
8045 rtype->set_num_fields (rtype->num_fields () - 1);
8047 else
8049 rtype->field (variant_field).set_type (branch_type);
8050 rtype->field (variant_field).set_name ("S");
8051 fld_bit_len =
8052 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
8053 if (off + fld_bit_len > bit_len)
8054 bit_len = off + fld_bit_len;
8056 rtype->set_length
8057 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
8061 /* According to exp_dbug.ads, the size of TYPE for variable-size records
8062 should contain the alignment of that record, which should be a strictly
8063 positive value. If null or negative, then something is wrong, most
8064 probably in the debug info. In that case, we don't round up the size
8065 of the resulting type. If this record is not part of another structure,
8066 the current RTYPE length might be good enough for our purposes. */
8067 if (type->length () <= 0)
8069 if (rtype->name ())
8070 warning (_("Invalid type size for `%s' detected: %s."),
8071 rtype->name (), pulongest (type->length ()));
8072 else
8073 warning (_("Invalid type size for <unnamed> detected: %s."),
8074 pulongest (type->length ()));
8076 else
8077 rtype->set_length (align_up (rtype->length (), type->length ()));
8079 return rtype;
8082 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8083 of 1. */
8085 static struct type *
8086 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8087 CORE_ADDR address, struct value *dval0)
8089 return ada_template_to_fixed_record_type_1 (type, valaddr,
8090 address, dval0, 1);
8093 /* An ordinary record type in which ___XVL-convention fields and
8094 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8095 static approximations, containing all possible fields. Uses
8096 no runtime values. Useless for use in values, but that's OK,
8097 since the results are used only for type determinations. Works on both
8098 structs and unions. Representation note: to save space, we memorize
8099 the result of this function in the type::target_type of the
8100 template type. */
8102 static struct type *
8103 template_to_static_fixed_type (struct type *type0)
8105 struct type *type;
8106 int nfields;
8107 int f;
8109 /* No need no do anything if the input type is already fixed. */
8110 if (type0->is_fixed_instance ())
8111 return type0;
8113 /* Likewise if we already have computed the static approximation. */
8114 if (type0->target_type () != NULL)
8115 return type0->target_type ();
8117 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8118 type = type0;
8119 nfields = type0->num_fields ();
8121 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8122 recompute all over next time. */
8123 type0->set_target_type (type);
8125 for (f = 0; f < nfields; f += 1)
8127 struct type *field_type = type0->field (f).type ();
8128 struct type *new_type;
8130 if (is_dynamic_field (type0, f))
8132 field_type = ada_check_typedef (field_type);
8133 new_type = to_static_fixed_type (field_type->target_type ());
8135 else
8136 new_type = static_unwrap_type (field_type);
8138 if (new_type != field_type)
8140 /* Clone TYPE0 only the first time we get a new field type. */
8141 if (type == type0)
8143 type = alloc_type_copy (type0);
8144 type0->set_target_type (type);
8145 type->set_code (type0->code ());
8146 INIT_NONE_SPECIFIC (type);
8147 type->set_num_fields (nfields);
8149 field *fields =
8150 ((struct field *)
8151 TYPE_ALLOC (type, nfields * sizeof (struct field)));
8152 memcpy (fields, type0->fields (),
8153 sizeof (struct field) * nfields);
8154 type->set_fields (fields);
8156 type->set_name (ada_type_name (type0));
8157 type->set_is_fixed_instance (true);
8158 type->set_length (0);
8160 type->field (f).set_type (new_type);
8161 type->field (f).set_name (type0->field (f).name ());
8165 return type;
8168 /* Given an object of type TYPE whose contents are at VALADDR and
8169 whose address in memory is ADDRESS, returns a revision of TYPE,
8170 which should be a non-dynamic-sized record, in which the variant
8171 part, if any, is replaced with the appropriate branch. Looks
8172 for discriminant values in DVAL0, which can be NULL if the record
8173 contains the necessary discriminant values. */
8175 static struct type *
8176 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8177 CORE_ADDR address, struct value *dval0)
8179 struct value *dval;
8180 struct type *rtype;
8181 struct type *branch_type;
8182 int nfields = type->num_fields ();
8183 int variant_field = variant_field_index (type);
8185 if (variant_field == -1)
8186 return type;
8188 scoped_value_mark mark;
8189 if (dval0 == NULL)
8191 dval = value_from_contents_and_address (type, valaddr, address);
8192 type = value_type (dval);
8194 else
8195 dval = dval0;
8197 rtype = alloc_type_copy (type);
8198 rtype->set_code (TYPE_CODE_STRUCT);
8199 INIT_NONE_SPECIFIC (rtype);
8200 rtype->set_num_fields (nfields);
8202 field *fields =
8203 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8204 memcpy (fields, type->fields (), sizeof (struct field) * nfields);
8205 rtype->set_fields (fields);
8207 rtype->set_name (ada_type_name (type));
8208 rtype->set_is_fixed_instance (true);
8209 rtype->set_length (type->length ());
8211 branch_type = to_fixed_variant_branch_type
8212 (type->field (variant_field).type (),
8213 cond_offset_host (valaddr,
8214 type->field (variant_field).loc_bitpos ()
8215 / TARGET_CHAR_BIT),
8216 cond_offset_target (address,
8217 type->field (variant_field).loc_bitpos ()
8218 / TARGET_CHAR_BIT), dval);
8219 if (branch_type == NULL)
8221 int f;
8223 for (f = variant_field + 1; f < nfields; f += 1)
8224 rtype->field (f - 1) = rtype->field (f);
8225 rtype->set_num_fields (rtype->num_fields () - 1);
8227 else
8229 rtype->field (variant_field).set_type (branch_type);
8230 rtype->field (variant_field).set_name ("S");
8231 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8232 rtype->set_length (rtype->length () + branch_type->length ());
8235 rtype->set_length (rtype->length ()
8236 - type->field (variant_field).type ()->length ());
8238 return rtype;
8241 /* An ordinary record type (with fixed-length fields) that describes
8242 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8243 beginning of this section]. Any necessary discriminants' values
8244 should be in DVAL, a record value; it may be NULL if the object
8245 at ADDR itself contains any necessary discriminant values.
8246 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8247 values from the record are needed. Except in the case that DVAL,
8248 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8249 unchecked) is replaced by a particular branch of the variant.
8251 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8252 is questionable and may be removed. It can arise during the
8253 processing of an unconstrained-array-of-record type where all the
8254 variant branches have exactly the same size. This is because in
8255 such cases, the compiler does not bother to use the XVS convention
8256 when encoding the record. I am currently dubious of this
8257 shortcut and suspect the compiler should be altered. FIXME. */
8259 static struct type *
8260 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8261 CORE_ADDR address, struct value *dval)
8263 struct type *templ_type;
8265 if (type0->is_fixed_instance ())
8266 return type0;
8268 templ_type = dynamic_template_type (type0);
8270 if (templ_type != NULL)
8271 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8272 else if (variant_field_index (type0) >= 0)
8274 if (dval == NULL && valaddr == NULL && address == 0)
8275 return type0;
8276 return to_record_with_fixed_variant_part (type0, valaddr, address,
8277 dval);
8279 else
8281 type0->set_is_fixed_instance (true);
8282 return type0;
8287 /* An ordinary record type (with fixed-length fields) that describes
8288 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8289 union type. Any necessary discriminants' values should be in DVAL,
8290 a record value. That is, this routine selects the appropriate
8291 branch of the union at ADDR according to the discriminant value
8292 indicated in the union's type name. Returns VAR_TYPE0 itself if
8293 it represents a variant subject to a pragma Unchecked_Union. */
8295 static struct type *
8296 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8297 CORE_ADDR address, struct value *dval)
8299 int which;
8300 struct type *templ_type;
8301 struct type *var_type;
8303 if (var_type0->code () == TYPE_CODE_PTR)
8304 var_type = var_type0->target_type ();
8305 else
8306 var_type = var_type0;
8308 templ_type = ada_find_parallel_type (var_type, "___XVU");
8310 if (templ_type != NULL)
8311 var_type = templ_type;
8313 if (is_unchecked_variant (var_type, value_type (dval)))
8314 return var_type0;
8315 which = ada_which_variant_applies (var_type, dval);
8317 if (which < 0)
8318 return empty_record (var_type);
8319 else if (is_dynamic_field (var_type, which))
8320 return to_fixed_record_type
8321 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8322 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8323 return
8324 to_fixed_record_type
8325 (var_type->field (which).type (), valaddr, address, dval);
8326 else
8327 return var_type->field (which).type ();
8330 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8331 ENCODING_TYPE, a type following the GNAT conventions for discrete
8332 type encodings, only carries redundant information. */
8334 static int
8335 ada_is_redundant_range_encoding (struct type *range_type,
8336 struct type *encoding_type)
8338 const char *bounds_str;
8339 int n;
8340 LONGEST lo, hi;
8342 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8344 if (get_base_type (range_type)->code ()
8345 != get_base_type (encoding_type)->code ())
8347 /* The compiler probably used a simple base type to describe
8348 the range type instead of the range's actual base type,
8349 expecting us to get the real base type from the encoding
8350 anyway. In this situation, the encoding cannot be ignored
8351 as redundant. */
8352 return 0;
8355 if (is_dynamic_type (range_type))
8356 return 0;
8358 if (encoding_type->name () == NULL)
8359 return 0;
8361 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8362 if (bounds_str == NULL)
8363 return 0;
8365 n = 8; /* Skip "___XDLU_". */
8366 if (!ada_scan_number (bounds_str, n, &lo, &n))
8367 return 0;
8368 if (range_type->bounds ()->low.const_val () != lo)
8369 return 0;
8371 n += 2; /* Skip the "__" separator between the two bounds. */
8372 if (!ada_scan_number (bounds_str, n, &hi, &n))
8373 return 0;
8374 if (range_type->bounds ()->high.const_val () != hi)
8375 return 0;
8377 return 1;
8380 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8381 a type following the GNAT encoding for describing array type
8382 indices, only carries redundant information. */
8384 static int
8385 ada_is_redundant_index_type_desc (struct type *array_type,
8386 struct type *desc_type)
8388 struct type *this_layer = check_typedef (array_type);
8389 int i;
8391 for (i = 0; i < desc_type->num_fields (); i++)
8393 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8394 desc_type->field (i).type ()))
8395 return 0;
8396 this_layer = check_typedef (this_layer->target_type ());
8399 return 1;
8402 /* Assuming that TYPE0 is an array type describing the type of a value
8403 at ADDR, and that DVAL describes a record containing any
8404 discriminants used in TYPE0, returns a type for the value that
8405 contains no dynamic components (that is, no components whose sizes
8406 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8407 true, gives an error message if the resulting type's size is over
8408 varsize_limit. */
8410 static struct type *
8411 to_fixed_array_type (struct type *type0, struct value *dval,
8412 int ignore_too_big)
8414 struct type *index_type_desc;
8415 struct type *result;
8416 int constrained_packed_array_p;
8417 static const char *xa_suffix = "___XA";
8419 type0 = ada_check_typedef (type0);
8420 if (type0->is_fixed_instance ())
8421 return type0;
8423 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8424 if (constrained_packed_array_p)
8426 type0 = decode_constrained_packed_array_type (type0);
8427 if (type0 == nullptr)
8428 error (_("could not decode constrained packed array type"));
8431 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8433 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8434 encoding suffixed with 'P' may still be generated. If so,
8435 it should be used to find the XA type. */
8437 if (index_type_desc == NULL)
8439 const char *type_name = ada_type_name (type0);
8441 if (type_name != NULL)
8443 const int len = strlen (type_name);
8444 char *name = (char *) alloca (len + strlen (xa_suffix));
8446 if (type_name[len - 1] == 'P')
8448 strcpy (name, type_name);
8449 strcpy (name + len - 1, xa_suffix);
8450 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8455 ada_fixup_array_indexes_type (index_type_desc);
8456 if (index_type_desc != NULL
8457 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8459 /* Ignore this ___XA parallel type, as it does not bring any
8460 useful information. This allows us to avoid creating fixed
8461 versions of the array's index types, which would be identical
8462 to the original ones. This, in turn, can also help avoid
8463 the creation of fixed versions of the array itself. */
8464 index_type_desc = NULL;
8467 if (index_type_desc == NULL)
8469 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8471 /* NOTE: elt_type---the fixed version of elt_type0---should never
8472 depend on the contents of the array in properly constructed
8473 debugging data. */
8474 /* Create a fixed version of the array element type.
8475 We're not providing the address of an element here,
8476 and thus the actual object value cannot be inspected to do
8477 the conversion. This should not be a problem, since arrays of
8478 unconstrained objects are not allowed. In particular, all
8479 the elements of an array of a tagged type should all be of
8480 the same type specified in the debugging info. No need to
8481 consult the object tag. */
8482 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8484 /* Make sure we always create a new array type when dealing with
8485 packed array types, since we're going to fix-up the array
8486 type length and element bitsize a little further down. */
8487 if (elt_type0 == elt_type && !constrained_packed_array_p)
8488 result = type0;
8489 else
8490 result = create_array_type (alloc_type_copy (type0),
8491 elt_type, type0->index_type ());
8493 else
8495 int i;
8496 struct type *elt_type0;
8498 elt_type0 = type0;
8499 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8500 elt_type0 = elt_type0->target_type ();
8502 /* NOTE: result---the fixed version of elt_type0---should never
8503 depend on the contents of the array in properly constructed
8504 debugging data. */
8505 /* Create a fixed version of the array element type.
8506 We're not providing the address of an element here,
8507 and thus the actual object value cannot be inspected to do
8508 the conversion. This should not be a problem, since arrays of
8509 unconstrained objects are not allowed. In particular, all
8510 the elements of an array of a tagged type should all be of
8511 the same type specified in the debugging info. No need to
8512 consult the object tag. */
8513 result =
8514 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8516 elt_type0 = type0;
8517 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8519 struct type *range_type =
8520 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8522 result = create_array_type (alloc_type_copy (elt_type0),
8523 result, range_type);
8524 elt_type0 = elt_type0->target_type ();
8528 /* We want to preserve the type name. This can be useful when
8529 trying to get the type name of a value that has already been
8530 printed (for instance, if the user did "print VAR; whatis $". */
8531 result->set_name (type0->name ());
8533 if (constrained_packed_array_p)
8535 /* So far, the resulting type has been created as if the original
8536 type was a regular (non-packed) array type. As a result, the
8537 bitsize of the array elements needs to be set again, and the array
8538 length needs to be recomputed based on that bitsize. */
8539 int len = result->length () / result->target_type ()->length ();
8540 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8542 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8543 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8544 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8545 result->set_length (result->length () + 1);
8548 result->set_is_fixed_instance (true);
8549 return result;
8553 /* A standard type (containing no dynamically sized components)
8554 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8555 DVAL describes a record containing any discriminants used in TYPE0,
8556 and may be NULL if there are none, or if the object of type TYPE at
8557 ADDRESS or in VALADDR contains these discriminants.
8559 If CHECK_TAG is not null, in the case of tagged types, this function
8560 attempts to locate the object's tag and use it to compute the actual
8561 type. However, when ADDRESS is null, we cannot use it to determine the
8562 location of the tag, and therefore compute the tagged type's actual type.
8563 So we return the tagged type without consulting the tag. */
8565 static struct type *
8566 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8567 CORE_ADDR address, struct value *dval, int check_tag)
8569 type = ada_check_typedef (type);
8571 /* Only un-fixed types need to be handled here. */
8572 if (!HAVE_GNAT_AUX_INFO (type))
8573 return type;
8575 switch (type->code ())
8577 default:
8578 return type;
8579 case TYPE_CODE_STRUCT:
8581 struct type *static_type = to_static_fixed_type (type);
8582 struct type *fixed_record_type =
8583 to_fixed_record_type (type, valaddr, address, NULL);
8585 /* If STATIC_TYPE is a tagged type and we know the object's address,
8586 then we can determine its tag, and compute the object's actual
8587 type from there. Note that we have to use the fixed record
8588 type (the parent part of the record may have dynamic fields
8589 and the way the location of _tag is expressed may depend on
8590 them). */
8592 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8594 struct value *tag =
8595 value_tag_from_contents_and_address
8596 (fixed_record_type,
8597 valaddr,
8598 address);
8599 struct type *real_type = type_from_tag (tag);
8600 struct value *obj =
8601 value_from_contents_and_address (fixed_record_type,
8602 valaddr,
8603 address);
8604 fixed_record_type = value_type (obj);
8605 if (real_type != NULL)
8606 return to_fixed_record_type
8607 (real_type, NULL,
8608 value_address (ada_tag_value_at_base_address (obj)), NULL);
8611 /* Check to see if there is a parallel ___XVZ variable.
8612 If there is, then it provides the actual size of our type. */
8613 else if (ada_type_name (fixed_record_type) != NULL)
8615 const char *name = ada_type_name (fixed_record_type);
8616 char *xvz_name
8617 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8618 bool xvz_found = false;
8619 LONGEST size;
8621 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8624 xvz_found = get_int_var_value (xvz_name, size);
8626 catch (const gdb_exception_error &except)
8628 /* We found the variable, but somehow failed to read
8629 its value. Rethrow the same error, but with a little
8630 bit more information, to help the user understand
8631 what went wrong (Eg: the variable might have been
8632 optimized out). */
8633 throw_error (except.error,
8634 _("unable to read value of %s (%s)"),
8635 xvz_name, except.what ());
8638 if (xvz_found && fixed_record_type->length () != size)
8640 fixed_record_type = copy_type (fixed_record_type);
8641 fixed_record_type->set_length (size);
8643 /* The FIXED_RECORD_TYPE may have be a stub. We have
8644 observed this when the debugging info is STABS, and
8645 apparently it is something that is hard to fix.
8647 In practice, we don't need the actual type definition
8648 at all, because the presence of the XVZ variable allows us
8649 to assume that there must be a XVS type as well, which we
8650 should be able to use later, when we need the actual type
8651 definition.
8653 In the meantime, pretend that the "fixed" type we are
8654 returning is NOT a stub, because this can cause trouble
8655 when using this type to create new types targeting it.
8656 Indeed, the associated creation routines often check
8657 whether the target type is a stub and will try to replace
8658 it, thus using a type with the wrong size. This, in turn,
8659 might cause the new type to have the wrong size too.
8660 Consider the case of an array, for instance, where the size
8661 of the array is computed from the number of elements in
8662 our array multiplied by the size of its element. */
8663 fixed_record_type->set_is_stub (false);
8666 return fixed_record_type;
8668 case TYPE_CODE_ARRAY:
8669 return to_fixed_array_type (type, dval, 1);
8670 case TYPE_CODE_UNION:
8671 if (dval == NULL)
8672 return type;
8673 else
8674 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8678 /* The same as ada_to_fixed_type_1, except that it preserves the type
8679 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8681 The typedef layer needs be preserved in order to differentiate between
8682 arrays and array pointers when both types are implemented using the same
8683 fat pointer. In the array pointer case, the pointer is encoded as
8684 a typedef of the pointer type. For instance, considering:
8686 type String_Access is access String;
8687 S1 : String_Access := null;
8689 To the debugger, S1 is defined as a typedef of type String. But
8690 to the user, it is a pointer. So if the user tries to print S1,
8691 we should not dereference the array, but print the array address
8692 instead.
8694 If we didn't preserve the typedef layer, we would lose the fact that
8695 the type is to be presented as a pointer (needs de-reference before
8696 being printed). And we would also use the source-level type name. */
8698 struct type *
8699 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8700 CORE_ADDR address, struct value *dval, int check_tag)
8703 struct type *fixed_type =
8704 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8706 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8707 then preserve the typedef layer.
8709 Implementation note: We can only check the main-type portion of
8710 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8711 from TYPE now returns a type that has the same instance flags
8712 as TYPE. For instance, if TYPE is a "typedef const", and its
8713 target type is a "struct", then the typedef elimination will return
8714 a "const" version of the target type. See check_typedef for more
8715 details about how the typedef layer elimination is done.
8717 brobecker/2010-11-19: It seems to me that the only case where it is
8718 useful to preserve the typedef layer is when dealing with fat pointers.
8719 Perhaps, we could add a check for that and preserve the typedef layer
8720 only in that situation. But this seems unnecessary so far, probably
8721 because we call check_typedef/ada_check_typedef pretty much everywhere.
8723 if (type->code () == TYPE_CODE_TYPEDEF
8724 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8725 == TYPE_MAIN_TYPE (fixed_type)))
8726 return type;
8728 return fixed_type;
8731 /* A standard (static-sized) type corresponding as well as possible to
8732 TYPE0, but based on no runtime data. */
8734 static struct type *
8735 to_static_fixed_type (struct type *type0)
8737 struct type *type;
8739 if (type0 == NULL)
8740 return NULL;
8742 if (type0->is_fixed_instance ())
8743 return type0;
8745 type0 = ada_check_typedef (type0);
8747 switch (type0->code ())
8749 default:
8750 return type0;
8751 case TYPE_CODE_STRUCT:
8752 type = dynamic_template_type (type0);
8753 if (type != NULL)
8754 return template_to_static_fixed_type (type);
8755 else
8756 return template_to_static_fixed_type (type0);
8757 case TYPE_CODE_UNION:
8758 type = ada_find_parallel_type (type0, "___XVU");
8759 if (type != NULL)
8760 return template_to_static_fixed_type (type);
8761 else
8762 return template_to_static_fixed_type (type0);
8766 /* A static approximation of TYPE with all type wrappers removed. */
8768 static struct type *
8769 static_unwrap_type (struct type *type)
8771 if (ada_is_aligner_type (type))
8773 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8774 if (ada_type_name (type1) == NULL)
8775 type1->set_name (ada_type_name (type));
8777 return static_unwrap_type (type1);
8779 else
8781 struct type *raw_real_type = ada_get_base_type (type);
8783 if (raw_real_type == type)
8784 return type;
8785 else
8786 return to_static_fixed_type (raw_real_type);
8790 /* In some cases, incomplete and private types require
8791 cross-references that are not resolved as records (for example,
8792 type Foo;
8793 type FooP is access Foo;
8794 V: FooP;
8795 type Foo is array ...;
8796 ). In these cases, since there is no mechanism for producing
8797 cross-references to such types, we instead substitute for FooP a
8798 stub enumeration type that is nowhere resolved, and whose tag is
8799 the name of the actual type. Call these types "non-record stubs". */
8801 /* A type equivalent to TYPE that is not a non-record stub, if one
8802 exists, otherwise TYPE. */
8804 struct type *
8805 ada_check_typedef (struct type *type)
8807 if (type == NULL)
8808 return NULL;
8810 /* If our type is an access to an unconstrained array, which is encoded
8811 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8812 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8813 what allows us to distinguish between fat pointers that represent
8814 array types, and fat pointers that represent array access types
8815 (in both cases, the compiler implements them as fat pointers). */
8816 if (ada_is_access_to_unconstrained_array (type))
8817 return type;
8819 type = check_typedef (type);
8820 if (type == NULL || type->code () != TYPE_CODE_ENUM
8821 || !type->is_stub ()
8822 || type->name () == NULL)
8823 return type;
8824 else
8826 const char *name = type->name ();
8827 struct type *type1 = ada_find_any_type (name);
8829 if (type1 == NULL)
8830 return type;
8832 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8833 stubs pointing to arrays, as we don't create symbols for array
8834 types, only for the typedef-to-array types). If that's the case,
8835 strip the typedef layer. */
8836 if (type1->code () == TYPE_CODE_TYPEDEF)
8837 type1 = ada_check_typedef (type1);
8839 return type1;
8843 /* A value representing the data at VALADDR/ADDRESS as described by
8844 type TYPE0, but with a standard (static-sized) type that correctly
8845 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8846 type, then return VAL0 [this feature is simply to avoid redundant
8847 creation of struct values]. */
8849 static struct value *
8850 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8851 struct value *val0)
8853 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8855 if (type == type0 && val0 != NULL)
8856 return val0;
8858 if (VALUE_LVAL (val0) != lval_memory)
8860 /* Our value does not live in memory; it could be a convenience
8861 variable, for instance. Create a not_lval value using val0's
8862 contents. */
8863 return value_from_contents (type, value_contents (val0).data ());
8866 return value_from_contents_and_address (type, 0, address);
8869 /* A value representing VAL, but with a standard (static-sized) type
8870 that correctly describes it. Does not necessarily create a new
8871 value. */
8873 struct value *
8874 ada_to_fixed_value (struct value *val)
8876 val = unwrap_value (val);
8877 val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
8878 return val;
8882 /* Attributes */
8884 /* Table mapping attribute numbers to names.
8885 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
8887 static const char * const attribute_names[] = {
8888 "<?>",
8890 "first",
8891 "last",
8892 "length",
8893 "image",
8894 "max",
8895 "min",
8896 "modulus",
8897 "pos",
8898 "size",
8899 "tag",
8900 "val",
8904 static const char *
8905 ada_attribute_name (enum exp_opcode n)
8907 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8908 return attribute_names[n - OP_ATR_FIRST + 1];
8909 else
8910 return attribute_names[0];
8913 /* Evaluate the 'POS attribute applied to ARG. */
8915 static LONGEST
8916 pos_atr (struct value *arg)
8918 struct value *val = coerce_ref (arg);
8919 struct type *type = value_type (val);
8921 if (!discrete_type_p (type))
8922 error (_("'POS only defined on discrete types"));
8924 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8925 if (!result.has_value ())
8926 error (_("enumeration value is invalid: can't find 'POS"));
8928 return *result;
8931 struct value *
8932 ada_pos_atr (struct type *expect_type,
8933 struct expression *exp,
8934 enum noside noside, enum exp_opcode op,
8935 struct value *arg)
8937 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8938 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8939 return value_zero (type, not_lval);
8940 return value_from_longest (type, pos_atr (arg));
8943 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8945 static struct value *
8946 val_atr (struct type *type, LONGEST val)
8948 gdb_assert (discrete_type_p (type));
8949 if (type->code () == TYPE_CODE_RANGE)
8950 type = type->target_type ();
8951 if (type->code () == TYPE_CODE_ENUM)
8953 if (val < 0 || val >= type->num_fields ())
8954 error (_("argument to 'VAL out of range"));
8955 val = type->field (val).loc_enumval ();
8957 return value_from_longest (type, val);
8960 struct value *
8961 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8963 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8964 return value_zero (type, not_lval);
8966 if (!discrete_type_p (type))
8967 error (_("'VAL only defined on discrete types"));
8968 if (!integer_type_p (value_type (arg)))
8969 error (_("'VAL requires integral argument"));
8971 return val_atr (type, value_as_long (arg));
8975 /* Evaluation */
8977 /* True if TYPE appears to be an Ada character type.
8978 [At the moment, this is true only for Character and Wide_Character;
8979 It is a heuristic test that could stand improvement]. */
8981 bool
8982 ada_is_character_type (struct type *type)
8984 const char *name;
8986 /* If the type code says it's a character, then assume it really is,
8987 and don't check any further. */
8988 if (type->code () == TYPE_CODE_CHAR)
8989 return true;
8991 /* Otherwise, assume it's a character type iff it is a discrete type
8992 with a known character type name. */
8993 name = ada_type_name (type);
8994 return (name != NULL
8995 && (type->code () == TYPE_CODE_INT
8996 || type->code () == TYPE_CODE_RANGE)
8997 && (strcmp (name, "character") == 0
8998 || strcmp (name, "wide_character") == 0
8999 || strcmp (name, "wide_wide_character") == 0
9000 || strcmp (name, "unsigned char") == 0));
9003 /* True if TYPE appears to be an Ada string type. */
9005 bool
9006 ada_is_string_type (struct type *type)
9008 type = ada_check_typedef (type);
9009 if (type != NULL
9010 && type->code () != TYPE_CODE_PTR
9011 && (ada_is_simple_array_type (type)
9012 || ada_is_array_descriptor_type (type))
9013 && ada_array_arity (type) == 1)
9015 struct type *elttype = ada_array_element_type (type, 1);
9017 return ada_is_character_type (elttype);
9019 else
9020 return false;
9023 /* The compiler sometimes provides a parallel XVS type for a given
9024 PAD type. Normally, it is safe to follow the PAD type directly,
9025 but older versions of the compiler have a bug that causes the offset
9026 of its "F" field to be wrong. Following that field in that case
9027 would lead to incorrect results, but this can be worked around
9028 by ignoring the PAD type and using the associated XVS type instead.
9030 Set to True if the debugger should trust the contents of PAD types.
9031 Otherwise, ignore the PAD type if there is a parallel XVS type. */
9032 static bool trust_pad_over_xvs = true;
9034 /* True if TYPE is a struct type introduced by the compiler to force the
9035 alignment of a value. Such types have a single field with a
9036 distinctive name. */
9039 ada_is_aligner_type (struct type *type)
9041 type = ada_check_typedef (type);
9043 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
9044 return 0;
9046 return (type->code () == TYPE_CODE_STRUCT
9047 && type->num_fields () == 1
9048 && strcmp (type->field (0).name (), "F") == 0);
9051 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
9052 the parallel type. */
9054 struct type *
9055 ada_get_base_type (struct type *raw_type)
9057 struct type *real_type_namer;
9058 struct type *raw_real_type;
9060 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
9061 return raw_type;
9063 if (ada_is_aligner_type (raw_type))
9064 /* The encoding specifies that we should always use the aligner type.
9065 So, even if this aligner type has an associated XVS type, we should
9066 simply ignore it.
9068 According to the compiler gurus, an XVS type parallel to an aligner
9069 type may exist because of a stabs limitation. In stabs, aligner
9070 types are empty because the field has a variable-sized type, and
9071 thus cannot actually be used as an aligner type. As a result,
9072 we need the associated parallel XVS type to decode the type.
9073 Since the policy in the compiler is to not change the internal
9074 representation based on the debugging info format, we sometimes
9075 end up having a redundant XVS type parallel to the aligner type. */
9076 return raw_type;
9078 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9079 if (real_type_namer == NULL
9080 || real_type_namer->code () != TYPE_CODE_STRUCT
9081 || real_type_namer->num_fields () != 1)
9082 return raw_type;
9084 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
9086 /* This is an older encoding form where the base type needs to be
9087 looked up by name. We prefer the newer encoding because it is
9088 more efficient. */
9089 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
9090 if (raw_real_type == NULL)
9091 return raw_type;
9092 else
9093 return raw_real_type;
9096 /* The field in our XVS type is a reference to the base type. */
9097 return real_type_namer->field (0).type ()->target_type ();
9100 /* The type of value designated by TYPE, with all aligners removed. */
9102 struct type *
9103 ada_aligned_type (struct type *type)
9105 if (ada_is_aligner_type (type))
9106 return ada_aligned_type (type->field (0).type ());
9107 else
9108 return ada_get_base_type (type);
9112 /* The address of the aligned value in an object at address VALADDR
9113 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9115 const gdb_byte *
9116 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9118 if (ada_is_aligner_type (type))
9119 return ada_aligned_value_addr
9120 (type->field (0).type (),
9121 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
9122 else
9123 return valaddr;
9128 /* The printed representation of an enumeration literal with encoded
9129 name NAME. The value is good to the next call of ada_enum_name. */
9130 const char *
9131 ada_enum_name (const char *name)
9133 static std::string storage;
9134 const char *tmp;
9136 /* First, unqualify the enumeration name:
9137 1. Search for the last '.' character. If we find one, then skip
9138 all the preceding characters, the unqualified name starts
9139 right after that dot.
9140 2. Otherwise, we may be debugging on a target where the compiler
9141 translates dots into "__". Search forward for double underscores,
9142 but stop searching when we hit an overloading suffix, which is
9143 of the form "__" followed by digits. */
9145 tmp = strrchr (name, '.');
9146 if (tmp != NULL)
9147 name = tmp + 1;
9148 else
9150 while ((tmp = strstr (name, "__")) != NULL)
9152 if (isdigit (tmp[2]))
9153 break;
9154 else
9155 name = tmp + 2;
9159 if (name[0] == 'Q')
9161 int v;
9163 if (name[1] == 'U' || name[1] == 'W')
9165 int offset = 2;
9166 if (name[1] == 'W' && name[2] == 'W')
9168 /* Also handle the QWW case. */
9169 ++offset;
9171 if (sscanf (name + offset, "%x", &v) != 1)
9172 return name;
9174 else if (((name[1] >= '0' && name[1] <= '9')
9175 || (name[1] >= 'a' && name[1] <= 'z'))
9176 && name[2] == '\0')
9178 storage = string_printf ("'%c'", name[1]);
9179 return storage.c_str ();
9181 else
9182 return name;
9184 if (isascii (v) && isprint (v))
9185 storage = string_printf ("'%c'", v);
9186 else if (name[1] == 'U')
9187 storage = string_printf ("'[\"%02x\"]'", v);
9188 else if (name[2] != 'W')
9189 storage = string_printf ("'[\"%04x\"]'", v);
9190 else
9191 storage = string_printf ("'[\"%06x\"]'", v);
9193 return storage.c_str ();
9195 else
9197 tmp = strstr (name, "__");
9198 if (tmp == NULL)
9199 tmp = strstr (name, "$");
9200 if (tmp != NULL)
9202 storage = std::string (name, tmp - name);
9203 return storage.c_str ();
9206 return name;
9210 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9211 value it wraps. */
9213 static struct value *
9214 unwrap_value (struct value *val)
9216 struct type *type = ada_check_typedef (value_type (val));
9218 if (ada_is_aligner_type (type))
9220 struct value *v = ada_value_struct_elt (val, "F", 0);
9221 struct type *val_type = ada_check_typedef (value_type (v));
9223 if (ada_type_name (val_type) == NULL)
9224 val_type->set_name (ada_type_name (type));
9226 return unwrap_value (v);
9228 else
9230 struct type *raw_real_type =
9231 ada_check_typedef (ada_get_base_type (type));
9233 /* If there is no parallel XVS or XVE type, then the value is
9234 already unwrapped. Return it without further modification. */
9235 if ((type == raw_real_type)
9236 && ada_find_parallel_type (type, "___XVE") == NULL)
9237 return val;
9239 return
9240 coerce_unspec_val_to_type
9241 (val, ada_to_fixed_type (raw_real_type, 0,
9242 value_address (val),
9243 NULL, 1));
9247 /* Given two array types T1 and T2, return nonzero iff both arrays
9248 contain the same number of elements. */
9250 static int
9251 ada_same_array_size_p (struct type *t1, struct type *t2)
9253 LONGEST lo1, hi1, lo2, hi2;
9255 /* Get the array bounds in order to verify that the size of
9256 the two arrays match. */
9257 if (!get_array_bounds (t1, &lo1, &hi1)
9258 || !get_array_bounds (t2, &lo2, &hi2))
9259 error (_("unable to determine array bounds"));
9261 /* To make things easier for size comparison, normalize a bit
9262 the case of empty arrays by making sure that the difference
9263 between upper bound and lower bound is always -1. */
9264 if (lo1 > hi1)
9265 hi1 = lo1 - 1;
9266 if (lo2 > hi2)
9267 hi2 = lo2 - 1;
9269 return (hi1 - lo1 == hi2 - lo2);
9272 /* Assuming that VAL is an array of integrals, and TYPE represents
9273 an array with the same number of elements, but with wider integral
9274 elements, return an array "casted" to TYPE. In practice, this
9275 means that the returned array is built by casting each element
9276 of the original array into TYPE's (wider) element type. */
9278 static struct value *
9279 ada_promote_array_of_integrals (struct type *type, struct value *val)
9281 struct type *elt_type = type->target_type ();
9282 LONGEST lo, hi;
9283 LONGEST i;
9285 /* Verify that both val and type are arrays of scalars, and
9286 that the size of val's elements is smaller than the size
9287 of type's element. */
9288 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9289 gdb_assert (is_integral_type (type->target_type ()));
9290 gdb_assert (value_type (val)->code () == TYPE_CODE_ARRAY);
9291 gdb_assert (is_integral_type (value_type (val)->target_type ()));
9292 gdb_assert (type->target_type ()->length ()
9293 > value_type (val)->target_type ()->length ());
9295 if (!get_array_bounds (type, &lo, &hi))
9296 error (_("unable to determine array bounds"));
9298 value *res = allocate_value (type);
9299 gdb::array_view<gdb_byte> res_contents = value_contents_writeable (res);
9301 /* Promote each array element. */
9302 for (i = 0; i < hi - lo + 1; i++)
9304 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9305 int elt_len = elt_type->length ();
9307 copy (value_contents_all (elt), res_contents.slice (elt_len * i, elt_len));
9310 return res;
9313 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9314 return the converted value. */
9316 static struct value *
9317 coerce_for_assign (struct type *type, struct value *val)
9319 struct type *type2 = value_type (val);
9321 if (type == type2)
9322 return val;
9324 type2 = ada_check_typedef (type2);
9325 type = ada_check_typedef (type);
9327 if (type2->code () == TYPE_CODE_PTR
9328 && type->code () == TYPE_CODE_ARRAY)
9330 val = ada_value_ind (val);
9331 type2 = value_type (val);
9334 if (type2->code () == TYPE_CODE_ARRAY
9335 && type->code () == TYPE_CODE_ARRAY)
9337 if (!ada_same_array_size_p (type, type2))
9338 error (_("cannot assign arrays of different length"));
9340 if (is_integral_type (type->target_type ())
9341 && is_integral_type (type2->target_type ())
9342 && type2->target_type ()->length () < type->target_type ()->length ())
9344 /* Allow implicit promotion of the array elements to
9345 a wider type. */
9346 return ada_promote_array_of_integrals (type, val);
9349 if (type2->target_type ()->length () != type->target_type ()->length ())
9350 error (_("Incompatible types in assignment"));
9351 deprecated_set_value_type (val, type);
9353 return val;
9356 static struct value *
9357 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9359 struct value *val;
9360 struct type *type1, *type2;
9361 LONGEST v, v1, v2;
9363 arg1 = coerce_ref (arg1);
9364 arg2 = coerce_ref (arg2);
9365 type1 = get_base_type (ada_check_typedef (value_type (arg1)));
9366 type2 = get_base_type (ada_check_typedef (value_type (arg2)));
9368 if (type1->code () != TYPE_CODE_INT
9369 || type2->code () != TYPE_CODE_INT)
9370 return value_binop (arg1, arg2, op);
9372 switch (op)
9374 case BINOP_MOD:
9375 case BINOP_DIV:
9376 case BINOP_REM:
9377 break;
9378 default:
9379 return value_binop (arg1, arg2, op);
9382 v2 = value_as_long (arg2);
9383 if (v2 == 0)
9385 const char *name;
9386 if (op == BINOP_MOD)
9387 name = "mod";
9388 else if (op == BINOP_DIV)
9389 name = "/";
9390 else
9392 gdb_assert (op == BINOP_REM);
9393 name = "rem";
9396 error (_("second operand of %s must not be zero."), name);
9399 if (type1->is_unsigned () || op == BINOP_MOD)
9400 return value_binop (arg1, arg2, op);
9402 v1 = value_as_long (arg1);
9403 switch (op)
9405 case BINOP_DIV:
9406 v = v1 / v2;
9407 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9408 v += v > 0 ? -1 : 1;
9409 break;
9410 case BINOP_REM:
9411 v = v1 % v2;
9412 if (v * v1 < 0)
9413 v -= v2;
9414 break;
9415 default:
9416 /* Should not reach this point. */
9417 v = 0;
9420 val = allocate_value (type1);
9421 store_unsigned_integer (value_contents_raw (val).data (),
9422 value_type (val)->length (),
9423 type_byte_order (type1), v);
9424 return val;
9427 static int
9428 ada_value_equal (struct value *arg1, struct value *arg2)
9430 if (ada_is_direct_array_type (value_type (arg1))
9431 || ada_is_direct_array_type (value_type (arg2)))
9433 struct type *arg1_type, *arg2_type;
9435 /* Automatically dereference any array reference before
9436 we attempt to perform the comparison. */
9437 arg1 = ada_coerce_ref (arg1);
9438 arg2 = ada_coerce_ref (arg2);
9440 arg1 = ada_coerce_to_simple_array (arg1);
9441 arg2 = ada_coerce_to_simple_array (arg2);
9443 arg1_type = ada_check_typedef (value_type (arg1));
9444 arg2_type = ada_check_typedef (value_type (arg2));
9446 if (arg1_type->code () != TYPE_CODE_ARRAY
9447 || arg2_type->code () != TYPE_CODE_ARRAY)
9448 error (_("Attempt to compare array with non-array"));
9449 /* FIXME: The following works only for types whose
9450 representations use all bits (no padding or undefined bits)
9451 and do not have user-defined equality. */
9452 return (arg1_type->length () == arg2_type->length ()
9453 && memcmp (value_contents (arg1).data (),
9454 value_contents (arg2).data (),
9455 arg1_type->length ()) == 0);
9457 return value_equal (arg1, arg2);
9460 namespace expr
9463 bool
9464 check_objfile (const std::unique_ptr<ada_component> &comp,
9465 struct objfile *objfile)
9467 return comp->uses_objfile (objfile);
9470 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9471 component of LHS (a simple array or a record). Does not modify the
9472 inferior's memory, nor does it modify LHS (unless LHS ==
9473 CONTAINER). */
9475 static void
9476 assign_component (struct value *container, struct value *lhs, LONGEST index,
9477 struct expression *exp, operation_up &arg)
9479 scoped_value_mark mark;
9481 struct value *elt;
9482 struct type *lhs_type = check_typedef (value_type (lhs));
9484 if (lhs_type->code () == TYPE_CODE_ARRAY)
9486 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9487 struct value *index_val = value_from_longest (index_type, index);
9489 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9491 else
9493 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9494 elt = ada_to_fixed_value (elt);
9497 ada_aggregate_operation *ag_op
9498 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9499 if (ag_op != nullptr)
9500 ag_op->assign_aggregate (container, elt, exp);
9501 else
9502 value_assign_to_component (container, elt,
9503 arg->evaluate (nullptr, exp,
9504 EVAL_NORMAL));
9507 bool
9508 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9510 for (const auto &item : m_components)
9511 if (item->uses_objfile (objfile))
9512 return true;
9513 return false;
9516 void
9517 ada_aggregate_component::dump (ui_file *stream, int depth)
9519 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9520 for (const auto &item : m_components)
9521 item->dump (stream, depth + 1);
9524 void
9525 ada_aggregate_component::assign (struct value *container,
9526 struct value *lhs, struct expression *exp,
9527 std::vector<LONGEST> &indices,
9528 LONGEST low, LONGEST high)
9530 for (auto &item : m_components)
9531 item->assign (container, lhs, exp, indices, low, high);
9534 /* See ada-exp.h. */
9536 value *
9537 ada_aggregate_operation::assign_aggregate (struct value *container,
9538 struct value *lhs,
9539 struct expression *exp)
9541 struct type *lhs_type;
9542 LONGEST low_index, high_index;
9544 container = ada_coerce_ref (container);
9545 if (ada_is_direct_array_type (value_type (container)))
9546 container = ada_coerce_to_simple_array (container);
9547 lhs = ada_coerce_ref (lhs);
9548 if (!deprecated_value_modifiable (lhs))
9549 error (_("Left operand of assignment is not a modifiable lvalue."));
9551 lhs_type = check_typedef (value_type (lhs));
9552 if (ada_is_direct_array_type (lhs_type))
9554 lhs = ada_coerce_to_simple_array (lhs);
9555 lhs_type = check_typedef (value_type (lhs));
9556 low_index = lhs_type->bounds ()->low.const_val ();
9557 high_index = lhs_type->bounds ()->high.const_val ();
9559 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9561 low_index = 0;
9562 high_index = num_visible_fields (lhs_type) - 1;
9564 else
9565 error (_("Left-hand side must be array or record."));
9567 std::vector<LONGEST> indices (4);
9568 indices[0] = indices[1] = low_index - 1;
9569 indices[2] = indices[3] = high_index + 1;
9571 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9572 low_index, high_index);
9574 return container;
9577 bool
9578 ada_positional_component::uses_objfile (struct objfile *objfile)
9580 return m_op->uses_objfile (objfile);
9583 void
9584 ada_positional_component::dump (ui_file *stream, int depth)
9586 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9587 depth, "", m_index);
9588 m_op->dump (stream, depth + 1);
9591 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9592 construct, given that the positions are relative to lower bound
9593 LOW, where HIGH is the upper bound. Record the position in
9594 INDICES. CONTAINER is as for assign_aggregate. */
9595 void
9596 ada_positional_component::assign (struct value *container,
9597 struct value *lhs, struct expression *exp,
9598 std::vector<LONGEST> &indices,
9599 LONGEST low, LONGEST high)
9601 LONGEST ind = m_index + low;
9603 if (ind - 1 == high)
9604 warning (_("Extra components in aggregate ignored."));
9605 if (ind <= high)
9607 add_component_interval (ind, ind, indices);
9608 assign_component (container, lhs, ind, exp, m_op);
9612 bool
9613 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9615 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9618 void
9619 ada_discrete_range_association::dump (ui_file *stream, int depth)
9621 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9622 m_low->dump (stream, depth + 1);
9623 m_high->dump (stream, depth + 1);
9626 void
9627 ada_discrete_range_association::assign (struct value *container,
9628 struct value *lhs,
9629 struct expression *exp,
9630 std::vector<LONGEST> &indices,
9631 LONGEST low, LONGEST high,
9632 operation_up &op)
9634 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9635 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9637 if (lower <= upper && (lower < low || upper > high))
9638 error (_("Index in component association out of bounds."));
9640 add_component_interval (lower, upper, indices);
9641 while (lower <= upper)
9643 assign_component (container, lhs, lower, exp, op);
9644 lower += 1;
9648 bool
9649 ada_name_association::uses_objfile (struct objfile *objfile)
9651 return m_val->uses_objfile (objfile);
9654 void
9655 ada_name_association::dump (ui_file *stream, int depth)
9657 gdb_printf (stream, _("%*sName:\n"), depth, "");
9658 m_val->dump (stream, depth + 1);
9661 void
9662 ada_name_association::assign (struct value *container,
9663 struct value *lhs,
9664 struct expression *exp,
9665 std::vector<LONGEST> &indices,
9666 LONGEST low, LONGEST high,
9667 operation_up &op)
9669 int index;
9671 if (ada_is_direct_array_type (value_type (lhs)))
9672 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9673 EVAL_NORMAL)));
9674 else
9676 ada_string_operation *strop
9677 = dynamic_cast<ada_string_operation *> (m_val.get ());
9679 const char *name;
9680 if (strop != nullptr)
9681 name = strop->get_name ();
9682 else
9684 ada_var_value_operation *vvo
9685 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9686 if (vvo != nullptr)
9687 error (_("Invalid record component association."));
9688 name = vvo->get_symbol ()->natural_name ();
9691 index = 0;
9692 if (! find_struct_field (name, value_type (lhs), 0,
9693 NULL, NULL, NULL, NULL, &index))
9694 error (_("Unknown component name: %s."), name);
9697 add_component_interval (index, index, indices);
9698 assign_component (container, lhs, index, exp, op);
9701 bool
9702 ada_choices_component::uses_objfile (struct objfile *objfile)
9704 if (m_op->uses_objfile (objfile))
9705 return true;
9706 for (const auto &item : m_assocs)
9707 if (item->uses_objfile (objfile))
9708 return true;
9709 return false;
9712 void
9713 ada_choices_component::dump (ui_file *stream, int depth)
9715 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9716 m_op->dump (stream, depth + 1);
9717 for (const auto &item : m_assocs)
9718 item->dump (stream, depth + 1);
9721 /* Assign into the components of LHS indexed by the OP_CHOICES
9722 construct at *POS, updating *POS past the construct, given that
9723 the allowable indices are LOW..HIGH. Record the indices assigned
9724 to in INDICES. CONTAINER is as for assign_aggregate. */
9725 void
9726 ada_choices_component::assign (struct value *container,
9727 struct value *lhs, struct expression *exp,
9728 std::vector<LONGEST> &indices,
9729 LONGEST low, LONGEST high)
9731 for (auto &item : m_assocs)
9732 item->assign (container, lhs, exp, indices, low, high, m_op);
9735 bool
9736 ada_others_component::uses_objfile (struct objfile *objfile)
9738 return m_op->uses_objfile (objfile);
9741 void
9742 ada_others_component::dump (ui_file *stream, int depth)
9744 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9745 m_op->dump (stream, depth + 1);
9748 /* Assign the value of the expression in the OP_OTHERS construct in
9749 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9750 have not been previously assigned. The index intervals already assigned
9751 are in INDICES. CONTAINER is as for assign_aggregate. */
9752 void
9753 ada_others_component::assign (struct value *container,
9754 struct value *lhs, struct expression *exp,
9755 std::vector<LONGEST> &indices,
9756 LONGEST low, LONGEST high)
9758 int num_indices = indices.size ();
9759 for (int i = 0; i < num_indices - 2; i += 2)
9761 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9762 assign_component (container, lhs, ind, exp, m_op);
9766 struct value *
9767 ada_assign_operation::evaluate (struct type *expect_type,
9768 struct expression *exp,
9769 enum noside noside)
9771 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9773 ada_aggregate_operation *ag_op
9774 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9775 if (ag_op != nullptr)
9777 if (noside != EVAL_NORMAL)
9778 return arg1;
9780 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9781 return ada_value_assign (arg1, arg1);
9783 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9784 except if the lhs of our assignment is a convenience variable.
9785 In the case of assigning to a convenience variable, the lhs
9786 should be exactly the result of the evaluation of the rhs. */
9787 struct type *type = value_type (arg1);
9788 if (VALUE_LVAL (arg1) == lval_internalvar)
9789 type = NULL;
9790 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9791 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9792 return arg1;
9793 if (VALUE_LVAL (arg1) == lval_internalvar)
9795 /* Nothing. */
9797 else
9798 arg2 = coerce_for_assign (value_type (arg1), arg2);
9799 return ada_value_assign (arg1, arg2);
9802 } /* namespace expr */
9804 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9805 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9806 overlap. */
9807 static void
9808 add_component_interval (LONGEST low, LONGEST high,
9809 std::vector<LONGEST> &indices)
9811 int i, j;
9813 int size = indices.size ();
9814 for (i = 0; i < size; i += 2) {
9815 if (high >= indices[i] && low <= indices[i + 1])
9817 int kh;
9819 for (kh = i + 2; kh < size; kh += 2)
9820 if (high < indices[kh])
9821 break;
9822 if (low < indices[i])
9823 indices[i] = low;
9824 indices[i + 1] = indices[kh - 1];
9825 if (high > indices[i + 1])
9826 indices[i + 1] = high;
9827 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9828 indices.resize (kh - i - 2);
9829 return;
9831 else if (high < indices[i])
9832 break;
9835 indices.resize (indices.size () + 2);
9836 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9837 indices[j] = indices[j - 2];
9838 indices[i] = low;
9839 indices[i + 1] = high;
9842 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9843 is different. */
9845 static struct value *
9846 ada_value_cast (struct type *type, struct value *arg2)
9848 if (type == ada_check_typedef (value_type (arg2)))
9849 return arg2;
9851 return value_cast (type, arg2);
9854 /* Evaluating Ada expressions, and printing their result.
9855 ------------------------------------------------------
9857 1. Introduction:
9858 ----------------
9860 We usually evaluate an Ada expression in order to print its value.
9861 We also evaluate an expression in order to print its type, which
9862 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9863 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9864 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9865 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9866 similar.
9868 Evaluating expressions is a little more complicated for Ada entities
9869 than it is for entities in languages such as C. The main reason for
9870 this is that Ada provides types whose definition might be dynamic.
9871 One example of such types is variant records. Or another example
9872 would be an array whose bounds can only be known at run time.
9874 The following description is a general guide as to what should be
9875 done (and what should NOT be done) in order to evaluate an expression
9876 involving such types, and when. This does not cover how the semantic
9877 information is encoded by GNAT as this is covered separatly. For the
9878 document used as the reference for the GNAT encoding, see exp_dbug.ads
9879 in the GNAT sources.
9881 Ideally, we should embed each part of this description next to its
9882 associated code. Unfortunately, the amount of code is so vast right
9883 now that it's hard to see whether the code handling a particular
9884 situation might be duplicated or not. One day, when the code is
9885 cleaned up, this guide might become redundant with the comments
9886 inserted in the code, and we might want to remove it.
9888 2. ``Fixing'' an Entity, the Simple Case:
9889 -----------------------------------------
9891 When evaluating Ada expressions, the tricky issue is that they may
9892 reference entities whose type contents and size are not statically
9893 known. Consider for instance a variant record:
9895 type Rec (Empty : Boolean := True) is record
9896 case Empty is
9897 when True => null;
9898 when False => Value : Integer;
9899 end case;
9900 end record;
9901 Yes : Rec := (Empty => False, Value => 1);
9902 No : Rec := (empty => True);
9904 The size and contents of that record depends on the value of the
9905 descriminant (Rec.Empty). At this point, neither the debugging
9906 information nor the associated type structure in GDB are able to
9907 express such dynamic types. So what the debugger does is to create
9908 "fixed" versions of the type that applies to the specific object.
9909 We also informally refer to this operation as "fixing" an object,
9910 which means creating its associated fixed type.
9912 Example: when printing the value of variable "Yes" above, its fixed
9913 type would look like this:
9915 type Rec is record
9916 Empty : Boolean;
9917 Value : Integer;
9918 end record;
9920 On the other hand, if we printed the value of "No", its fixed type
9921 would become:
9923 type Rec is record
9924 Empty : Boolean;
9925 end record;
9927 Things become a little more complicated when trying to fix an entity
9928 with a dynamic type that directly contains another dynamic type,
9929 such as an array of variant records, for instance. There are
9930 two possible cases: Arrays, and records.
9932 3. ``Fixing'' Arrays:
9933 ---------------------
9935 The type structure in GDB describes an array in terms of its bounds,
9936 and the type of its elements. By design, all elements in the array
9937 have the same type and we cannot represent an array of variant elements
9938 using the current type structure in GDB. When fixing an array,
9939 we cannot fix the array element, as we would potentially need one
9940 fixed type per element of the array. As a result, the best we can do
9941 when fixing an array is to produce an array whose bounds and size
9942 are correct (allowing us to read it from memory), but without having
9943 touched its element type. Fixing each element will be done later,
9944 when (if) necessary.
9946 Arrays are a little simpler to handle than records, because the same
9947 amount of memory is allocated for each element of the array, even if
9948 the amount of space actually used by each element differs from element
9949 to element. Consider for instance the following array of type Rec:
9951 type Rec_Array is array (1 .. 2) of Rec;
9953 The actual amount of memory occupied by each element might be different
9954 from element to element, depending on the value of their discriminant.
9955 But the amount of space reserved for each element in the array remains
9956 fixed regardless. So we simply need to compute that size using
9957 the debugging information available, from which we can then determine
9958 the array size (we multiply the number of elements of the array by
9959 the size of each element).
9961 The simplest case is when we have an array of a constrained element
9962 type. For instance, consider the following type declarations:
9964 type Bounded_String (Max_Size : Integer) is
9965 Length : Integer;
9966 Buffer : String (1 .. Max_Size);
9967 end record;
9968 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9970 In this case, the compiler describes the array as an array of
9971 variable-size elements (identified by its XVS suffix) for which
9972 the size can be read in the parallel XVZ variable.
9974 In the case of an array of an unconstrained element type, the compiler
9975 wraps the array element inside a private PAD type. This type should not
9976 be shown to the user, and must be "unwrap"'ed before printing. Note
9977 that we also use the adjective "aligner" in our code to designate
9978 these wrapper types.
9980 In some cases, the size allocated for each element is statically
9981 known. In that case, the PAD type already has the correct size,
9982 and the array element should remain unfixed.
9984 But there are cases when this size is not statically known.
9985 For instance, assuming that "Five" is an integer variable:
9987 type Dynamic is array (1 .. Five) of Integer;
9988 type Wrapper (Has_Length : Boolean := False) is record
9989 Data : Dynamic;
9990 case Has_Length is
9991 when True => Length : Integer;
9992 when False => null;
9993 end case;
9994 end record;
9995 type Wrapper_Array is array (1 .. 2) of Wrapper;
9997 Hello : Wrapper_Array := (others => (Has_Length => True,
9998 Data => (others => 17),
9999 Length => 1));
10002 The debugging info would describe variable Hello as being an
10003 array of a PAD type. The size of that PAD type is not statically
10004 known, but can be determined using a parallel XVZ variable.
10005 In that case, a copy of the PAD type with the correct size should
10006 be used for the fixed array.
10008 3. ``Fixing'' record type objects:
10009 ----------------------------------
10011 Things are slightly different from arrays in the case of dynamic
10012 record types. In this case, in order to compute the associated
10013 fixed type, we need to determine the size and offset of each of
10014 its components. This, in turn, requires us to compute the fixed
10015 type of each of these components.
10017 Consider for instance the example:
10019 type Bounded_String (Max_Size : Natural) is record
10020 Str : String (1 .. Max_Size);
10021 Length : Natural;
10022 end record;
10023 My_String : Bounded_String (Max_Size => 10);
10025 In that case, the position of field "Length" depends on the size
10026 of field Str, which itself depends on the value of the Max_Size
10027 discriminant. In order to fix the type of variable My_String,
10028 we need to fix the type of field Str. Therefore, fixing a variant
10029 record requires us to fix each of its components.
10031 However, if a component does not have a dynamic size, the component
10032 should not be fixed. In particular, fields that use a PAD type
10033 should not fixed. Here is an example where this might happen
10034 (assuming type Rec above):
10036 type Container (Big : Boolean) is record
10037 First : Rec;
10038 After : Integer;
10039 case Big is
10040 when True => Another : Integer;
10041 when False => null;
10042 end case;
10043 end record;
10044 My_Container : Container := (Big => False,
10045 First => (Empty => True),
10046 After => 42);
10048 In that example, the compiler creates a PAD type for component First,
10049 whose size is constant, and then positions the component After just
10050 right after it. The offset of component After is therefore constant
10051 in this case.
10053 The debugger computes the position of each field based on an algorithm
10054 that uses, among other things, the actual position and size of the field
10055 preceding it. Let's now imagine that the user is trying to print
10056 the value of My_Container. If the type fixing was recursive, we would
10057 end up computing the offset of field After based on the size of the
10058 fixed version of field First. And since in our example First has
10059 only one actual field, the size of the fixed type is actually smaller
10060 than the amount of space allocated to that field, and thus we would
10061 compute the wrong offset of field After.
10063 To make things more complicated, we need to watch out for dynamic
10064 components of variant records (identified by the ___XVL suffix in
10065 the component name). Even if the target type is a PAD type, the size
10066 of that type might not be statically known. So the PAD type needs
10067 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10068 we might end up with the wrong size for our component. This can be
10069 observed with the following type declarations:
10071 type Octal is new Integer range 0 .. 7;
10072 type Octal_Array is array (Positive range <>) of Octal;
10073 pragma Pack (Octal_Array);
10075 type Octal_Buffer (Size : Positive) is record
10076 Buffer : Octal_Array (1 .. Size);
10077 Length : Integer;
10078 end record;
10080 In that case, Buffer is a PAD type whose size is unset and needs
10081 to be computed by fixing the unwrapped type.
10083 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10084 ----------------------------------------------------------
10086 Lastly, when should the sub-elements of an entity that remained unfixed
10087 thus far, be actually fixed?
10089 The answer is: Only when referencing that element. For instance
10090 when selecting one component of a record, this specific component
10091 should be fixed at that point in time. Or when printing the value
10092 of a record, each component should be fixed before its value gets
10093 printed. Similarly for arrays, the element of the array should be
10094 fixed when printing each element of the array, or when extracting
10095 one element out of that array. On the other hand, fixing should
10096 not be performed on the elements when taking a slice of an array!
10098 Note that one of the side effects of miscomputing the offset and
10099 size of each field is that we end up also miscomputing the size
10100 of the containing type. This can have adverse results when computing
10101 the value of an entity. GDB fetches the value of an entity based
10102 on the size of its type, and thus a wrong size causes GDB to fetch
10103 the wrong amount of memory. In the case where the computed size is
10104 too small, GDB fetches too little data to print the value of our
10105 entity. Results in this case are unpredictable, as we usually read
10106 past the buffer containing the data =:-o. */
10108 /* A helper function for TERNOP_IN_RANGE. */
10110 static value *
10111 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10112 enum noside noside,
10113 value *arg1, value *arg2, value *arg3)
10115 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10116 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10117 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10118 return
10119 value_from_longest (type,
10120 (value_less (arg1, arg3)
10121 || value_equal (arg1, arg3))
10122 && (value_less (arg2, arg1)
10123 || value_equal (arg2, arg1)));
10126 /* A helper function for UNOP_NEG. */
10128 value *
10129 ada_unop_neg (struct type *expect_type,
10130 struct expression *exp,
10131 enum noside noside, enum exp_opcode op,
10132 struct value *arg1)
10134 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10135 return value_neg (arg1);
10138 /* A helper function for UNOP_IN_RANGE. */
10140 value *
10141 ada_unop_in_range (struct type *expect_type,
10142 struct expression *exp,
10143 enum noside noside, enum exp_opcode op,
10144 struct value *arg1, struct type *type)
10146 struct value *arg2, *arg3;
10147 switch (type->code ())
10149 default:
10150 lim_warning (_("Membership test incompletely implemented; "
10151 "always returns true"));
10152 type = language_bool_type (exp->language_defn, exp->gdbarch);
10153 return value_from_longest (type, (LONGEST) 1);
10155 case TYPE_CODE_RANGE:
10156 arg2 = value_from_longest (type,
10157 type->bounds ()->low.const_val ());
10158 arg3 = value_from_longest (type,
10159 type->bounds ()->high.const_val ());
10160 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10161 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10162 type = language_bool_type (exp->language_defn, exp->gdbarch);
10163 return
10164 value_from_longest (type,
10165 (value_less (arg1, arg3)
10166 || value_equal (arg1, arg3))
10167 && (value_less (arg2, arg1)
10168 || value_equal (arg2, arg1)));
10172 /* A helper function for OP_ATR_TAG. */
10174 value *
10175 ada_atr_tag (struct type *expect_type,
10176 struct expression *exp,
10177 enum noside noside, enum exp_opcode op,
10178 struct value *arg1)
10180 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10181 return value_zero (ada_tag_type (arg1), not_lval);
10183 return ada_value_tag (arg1);
10186 /* A helper function for OP_ATR_SIZE. */
10188 value *
10189 ada_atr_size (struct type *expect_type,
10190 struct expression *exp,
10191 enum noside noside, enum exp_opcode op,
10192 struct value *arg1)
10194 struct type *type = value_type (arg1);
10196 /* If the argument is a reference, then dereference its type, since
10197 the user is really asking for the size of the actual object,
10198 not the size of the pointer. */
10199 if (type->code () == TYPE_CODE_REF)
10200 type = type->target_type ();
10202 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10203 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10204 else
10205 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10206 TARGET_CHAR_BIT * type->length ());
10209 /* A helper function for UNOP_ABS. */
10211 value *
10212 ada_abs (struct type *expect_type,
10213 struct expression *exp,
10214 enum noside noside, enum exp_opcode op,
10215 struct value *arg1)
10217 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10218 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10219 return value_neg (arg1);
10220 else
10221 return arg1;
10224 /* A helper function for BINOP_MUL. */
10226 value *
10227 ada_mult_binop (struct type *expect_type,
10228 struct expression *exp,
10229 enum noside noside, enum exp_opcode op,
10230 struct value *arg1, struct value *arg2)
10232 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10234 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10235 return value_zero (value_type (arg1), not_lval);
10237 else
10239 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10240 return ada_value_binop (arg1, arg2, op);
10244 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10246 value *
10247 ada_equal_binop (struct type *expect_type,
10248 struct expression *exp,
10249 enum noside noside, enum exp_opcode op,
10250 struct value *arg1, struct value *arg2)
10252 int tem;
10253 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10254 tem = 0;
10255 else
10257 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10258 tem = ada_value_equal (arg1, arg2);
10260 if (op == BINOP_NOTEQUAL)
10261 tem = !tem;
10262 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10263 return value_from_longest (type, (LONGEST) tem);
10266 /* A helper function for TERNOP_SLICE. */
10268 value *
10269 ada_ternop_slice (struct expression *exp,
10270 enum noside noside,
10271 struct value *array, struct value *low_bound_val,
10272 struct value *high_bound_val)
10274 LONGEST low_bound;
10275 LONGEST high_bound;
10277 low_bound_val = coerce_ref (low_bound_val);
10278 high_bound_val = coerce_ref (high_bound_val);
10279 low_bound = value_as_long (low_bound_val);
10280 high_bound = value_as_long (high_bound_val);
10282 /* If this is a reference to an aligner type, then remove all
10283 the aligners. */
10284 if (value_type (array)->code () == TYPE_CODE_REF
10285 && ada_is_aligner_type (value_type (array)->target_type ()))
10286 value_type (array)->set_target_type
10287 (ada_aligned_type (value_type (array)->target_type ()));
10289 if (ada_is_any_packed_array_type (value_type (array)))
10290 error (_("cannot slice a packed array"));
10292 /* If this is a reference to an array or an array lvalue,
10293 convert to a pointer. */
10294 if (value_type (array)->code () == TYPE_CODE_REF
10295 || (value_type (array)->code () == TYPE_CODE_ARRAY
10296 && VALUE_LVAL (array) == lval_memory))
10297 array = value_addr (array);
10299 if (noside == EVAL_AVOID_SIDE_EFFECTS
10300 && ada_is_array_descriptor_type (ada_check_typedef
10301 (value_type (array))))
10302 return empty_array (ada_type_of_array (array, 0), low_bound,
10303 high_bound);
10305 array = ada_coerce_to_simple_array_ptr (array);
10307 /* If we have more than one level of pointer indirection,
10308 dereference the value until we get only one level. */
10309 while (value_type (array)->code () == TYPE_CODE_PTR
10310 && (value_type (array)->target_type ()->code ()
10311 == TYPE_CODE_PTR))
10312 array = value_ind (array);
10314 /* Make sure we really do have an array type before going further,
10315 to avoid a SEGV when trying to get the index type or the target
10316 type later down the road if the debug info generated by
10317 the compiler is incorrect or incomplete. */
10318 if (!ada_is_simple_array_type (value_type (array)))
10319 error (_("cannot take slice of non-array"));
10321 if (ada_check_typedef (value_type (array))->code ()
10322 == TYPE_CODE_PTR)
10324 struct type *type0 = ada_check_typedef (value_type (array));
10326 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10327 return empty_array (type0->target_type (), low_bound, high_bound);
10328 else
10330 struct type *arr_type0 =
10331 to_fixed_array_type (type0->target_type (), NULL, 1);
10333 return ada_value_slice_from_ptr (array, arr_type0,
10334 longest_to_int (low_bound),
10335 longest_to_int (high_bound));
10338 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10339 return array;
10340 else if (high_bound < low_bound)
10341 return empty_array (value_type (array), low_bound, high_bound);
10342 else
10343 return ada_value_slice (array, longest_to_int (low_bound),
10344 longest_to_int (high_bound));
10347 /* A helper function for BINOP_IN_BOUNDS. */
10349 value *
10350 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10351 struct value *arg1, struct value *arg2, int n)
10353 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10355 struct type *type = language_bool_type (exp->language_defn,
10356 exp->gdbarch);
10357 return value_zero (type, not_lval);
10360 struct type *type = ada_index_type (value_type (arg2), n, "range");
10361 if (!type)
10362 type = value_type (arg1);
10364 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10365 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10367 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10368 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10369 type = language_bool_type (exp->language_defn, exp->gdbarch);
10370 return value_from_longest (type,
10371 (value_less (arg1, arg3)
10372 || value_equal (arg1, arg3))
10373 && (value_less (arg2, arg1)
10374 || value_equal (arg2, arg1)));
10377 /* A helper function for some attribute operations. */
10379 static value *
10380 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10381 struct value *arg1, struct type *type_arg, int tem)
10383 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10385 if (type_arg == NULL)
10386 type_arg = value_type (arg1);
10388 if (ada_is_constrained_packed_array_type (type_arg))
10389 type_arg = decode_constrained_packed_array_type (type_arg);
10391 if (!discrete_type_p (type_arg))
10393 switch (op)
10395 default: /* Should never happen. */
10396 error (_("unexpected attribute encountered"));
10397 case OP_ATR_FIRST:
10398 case OP_ATR_LAST:
10399 type_arg = ada_index_type (type_arg, tem,
10400 ada_attribute_name (op));
10401 break;
10402 case OP_ATR_LENGTH:
10403 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10404 break;
10408 return value_zero (type_arg, not_lval);
10410 else if (type_arg == NULL)
10412 arg1 = ada_coerce_ref (arg1);
10414 if (ada_is_constrained_packed_array_type (value_type (arg1)))
10415 arg1 = ada_coerce_to_simple_array (arg1);
10417 struct type *type;
10418 if (op == OP_ATR_LENGTH)
10419 type = builtin_type (exp->gdbarch)->builtin_int;
10420 else
10422 type = ada_index_type (value_type (arg1), tem,
10423 ada_attribute_name (op));
10424 if (type == NULL)
10425 type = builtin_type (exp->gdbarch)->builtin_int;
10428 switch (op)
10430 default: /* Should never happen. */
10431 error (_("unexpected attribute encountered"));
10432 case OP_ATR_FIRST:
10433 return value_from_longest
10434 (type, ada_array_bound (arg1, tem, 0));
10435 case OP_ATR_LAST:
10436 return value_from_longest
10437 (type, ada_array_bound (arg1, tem, 1));
10438 case OP_ATR_LENGTH:
10439 return value_from_longest
10440 (type, ada_array_length (arg1, tem));
10443 else if (discrete_type_p (type_arg))
10445 struct type *range_type;
10446 const char *name = ada_type_name (type_arg);
10448 range_type = NULL;
10449 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10450 range_type = to_fixed_range_type (type_arg, NULL);
10451 if (range_type == NULL)
10452 range_type = type_arg;
10453 switch (op)
10455 default:
10456 error (_("unexpected attribute encountered"));
10457 case OP_ATR_FIRST:
10458 return value_from_longest
10459 (range_type, ada_discrete_type_low_bound (range_type));
10460 case OP_ATR_LAST:
10461 return value_from_longest
10462 (range_type, ada_discrete_type_high_bound (range_type));
10463 case OP_ATR_LENGTH:
10464 error (_("the 'length attribute applies only to array types"));
10467 else if (type_arg->code () == TYPE_CODE_FLT)
10468 error (_("unimplemented type attribute"));
10469 else
10471 LONGEST low, high;
10473 if (ada_is_constrained_packed_array_type (type_arg))
10474 type_arg = decode_constrained_packed_array_type (type_arg);
10476 struct type *type;
10477 if (op == OP_ATR_LENGTH)
10478 type = builtin_type (exp->gdbarch)->builtin_int;
10479 else
10481 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10482 if (type == NULL)
10483 type = builtin_type (exp->gdbarch)->builtin_int;
10486 switch (op)
10488 default:
10489 error (_("unexpected attribute encountered"));
10490 case OP_ATR_FIRST:
10491 low = ada_array_bound_from_type (type_arg, tem, 0);
10492 return value_from_longest (type, low);
10493 case OP_ATR_LAST:
10494 high = ada_array_bound_from_type (type_arg, tem, 1);
10495 return value_from_longest (type, high);
10496 case OP_ATR_LENGTH:
10497 low = ada_array_bound_from_type (type_arg, tem, 0);
10498 high = ada_array_bound_from_type (type_arg, tem, 1);
10499 return value_from_longest (type, high - low + 1);
10504 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10506 struct value *
10507 ada_binop_minmax (struct type *expect_type,
10508 struct expression *exp,
10509 enum noside noside, enum exp_opcode op,
10510 struct value *arg1, struct value *arg2)
10512 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10513 return value_zero (value_type (arg1), not_lval);
10514 else
10516 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10517 return value_binop (arg1, arg2, op);
10521 /* A helper function for BINOP_EXP. */
10523 struct value *
10524 ada_binop_exp (struct type *expect_type,
10525 struct expression *exp,
10526 enum noside noside, enum exp_opcode op,
10527 struct value *arg1, struct value *arg2)
10529 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10530 return value_zero (value_type (arg1), not_lval);
10531 else
10533 /* For integer exponentiation operations,
10534 only promote the first argument. */
10535 if (is_integral_type (value_type (arg2)))
10536 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10537 else
10538 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10540 return value_binop (arg1, arg2, op);
10544 namespace expr
10547 /* See ada-exp.h. */
10549 operation_up
10550 ada_resolvable::replace (operation_up &&owner,
10551 struct expression *exp,
10552 bool deprocedure_p,
10553 bool parse_completion,
10554 innermost_block_tracker *tracker,
10555 struct type *context_type)
10557 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10558 return (make_operation<ada_funcall_operation>
10559 (std::move (owner),
10560 std::vector<operation_up> ()));
10561 return std::move (owner);
10564 /* Convert the character literal whose value would be VAL to the
10565 appropriate value of type TYPE, if there is a translation.
10566 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10567 the literal 'A' (VAL == 65), returns 0. */
10569 static LONGEST
10570 convert_char_literal (struct type *type, LONGEST val)
10572 char name[12];
10573 int f;
10575 if (type == NULL)
10576 return val;
10577 type = check_typedef (type);
10578 if (type->code () != TYPE_CODE_ENUM)
10579 return val;
10581 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10582 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10583 else if (val >= 0 && val < 256)
10584 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10585 else if (val >= 0 && val < 0x10000)
10586 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10587 else
10588 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10589 size_t len = strlen (name);
10590 for (f = 0; f < type->num_fields (); f += 1)
10592 /* Check the suffix because an enum constant in a package will
10593 have a name like "pkg__QUxx". This is safe enough because we
10594 already have the correct type, and because mangling means
10595 there can't be clashes. */
10596 const char *ename = type->field (f).name ();
10597 size_t elen = strlen (ename);
10599 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10600 return type->field (f).loc_enumval ();
10602 return val;
10605 value *
10606 ada_char_operation::evaluate (struct type *expect_type,
10607 struct expression *exp,
10608 enum noside noside)
10610 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10611 if (expect_type != nullptr)
10612 result = ada_value_cast (expect_type, result);
10613 return result;
10616 /* See ada-exp.h. */
10618 operation_up
10619 ada_char_operation::replace (operation_up &&owner,
10620 struct expression *exp,
10621 bool deprocedure_p,
10622 bool parse_completion,
10623 innermost_block_tracker *tracker,
10624 struct type *context_type)
10626 operation_up result = std::move (owner);
10628 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10630 gdb_assert (result.get () == this);
10631 std::get<0> (m_storage) = context_type;
10632 std::get<1> (m_storage)
10633 = convert_char_literal (context_type, std::get<1> (m_storage));
10636 return result;
10639 value *
10640 ada_wrapped_operation::evaluate (struct type *expect_type,
10641 struct expression *exp,
10642 enum noside noside)
10644 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10645 if (noside == EVAL_NORMAL)
10646 result = unwrap_value (result);
10648 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10649 then we need to perform the conversion manually, because
10650 evaluate_subexp_standard doesn't do it. This conversion is
10651 necessary in Ada because the different kinds of float/fixed
10652 types in Ada have different representations.
10654 Similarly, we need to perform the conversion from OP_LONG
10655 ourselves. */
10656 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10657 result = ada_value_cast (expect_type, result);
10659 return result;
10662 value *
10663 ada_string_operation::evaluate (struct type *expect_type,
10664 struct expression *exp,
10665 enum noside noside)
10667 struct type *char_type;
10668 if (expect_type != nullptr && ada_is_string_type (expect_type))
10669 char_type = ada_array_element_type (expect_type, 1);
10670 else
10671 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10673 const std::string &str = std::get<0> (m_storage);
10674 const char *encoding;
10675 switch (char_type->length ())
10677 case 1:
10679 /* Simply copy over the data -- this isn't perhaps strictly
10680 correct according to the encodings, but it is gdb's
10681 historical behavior. */
10682 struct type *stringtype
10683 = lookup_array_range_type (char_type, 1, str.length ());
10684 struct value *val = allocate_value (stringtype);
10685 memcpy (value_contents_raw (val).data (), str.c_str (),
10686 str.length ());
10687 return val;
10690 case 2:
10691 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10692 encoding = "UTF-16BE";
10693 else
10694 encoding = "UTF-16LE";
10695 break;
10697 case 4:
10698 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10699 encoding = "UTF-32BE";
10700 else
10701 encoding = "UTF-32LE";
10702 break;
10704 default:
10705 error (_("unexpected character type size %s"),
10706 pulongest (char_type->length ()));
10709 auto_obstack converted;
10710 convert_between_encodings (host_charset (), encoding,
10711 (const gdb_byte *) str.c_str (),
10712 str.length (), 1,
10713 &converted, translit_none);
10715 struct type *stringtype
10716 = lookup_array_range_type (char_type, 1,
10717 obstack_object_size (&converted)
10718 / char_type->length ());
10719 struct value *val = allocate_value (stringtype);
10720 memcpy (value_contents_raw (val).data (),
10721 obstack_base (&converted),
10722 obstack_object_size (&converted));
10723 return val;
10726 value *
10727 ada_concat_operation::evaluate (struct type *expect_type,
10728 struct expression *exp,
10729 enum noside noside)
10731 /* If one side is a literal, evaluate the other side first so that
10732 the expected type can be set properly. */
10733 const operation_up &lhs_expr = std::get<0> (m_storage);
10734 const operation_up &rhs_expr = std::get<1> (m_storage);
10736 value *lhs, *rhs;
10737 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10739 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10740 lhs = lhs_expr->evaluate (value_type (rhs), exp, noside);
10742 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10744 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10745 struct type *rhs_type = check_typedef (value_type (rhs));
10746 struct type *elt_type = nullptr;
10747 if (rhs_type->code () == TYPE_CODE_ARRAY)
10748 elt_type = rhs_type->target_type ();
10749 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10751 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10753 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10754 rhs = rhs_expr->evaluate (value_type (lhs), exp, noside);
10756 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10758 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10759 struct type *lhs_type = check_typedef (value_type (lhs));
10760 struct type *elt_type = nullptr;
10761 if (lhs_type->code () == TYPE_CODE_ARRAY)
10762 elt_type = lhs_type->target_type ();
10763 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10765 else
10766 return concat_operation::evaluate (expect_type, exp, noside);
10768 return value_concat (lhs, rhs);
10771 value *
10772 ada_qual_operation::evaluate (struct type *expect_type,
10773 struct expression *exp,
10774 enum noside noside)
10776 struct type *type = std::get<1> (m_storage);
10777 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10780 value *
10781 ada_ternop_range_operation::evaluate (struct type *expect_type,
10782 struct expression *exp,
10783 enum noside noside)
10785 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10786 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10787 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10788 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10791 value *
10792 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10793 struct expression *exp,
10794 enum noside noside)
10796 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10797 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10799 auto do_op = [=] (LONGEST x, LONGEST y)
10801 if (std::get<0> (m_storage) == BINOP_ADD)
10802 return x + y;
10803 return x - y;
10806 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10807 return (value_from_longest
10808 (value_type (arg1),
10809 do_op (value_as_long (arg1), value_as_long (arg2))));
10810 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10811 return (value_from_longest
10812 (value_type (arg2),
10813 do_op (value_as_long (arg1), value_as_long (arg2))));
10814 /* Preserve the original type for use by the range case below.
10815 We cannot cast the result to a reference type, so if ARG1 is
10816 a reference type, find its underlying type. */
10817 struct type *type = value_type (arg1);
10818 while (type->code () == TYPE_CODE_REF)
10819 type = type->target_type ();
10820 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10821 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10822 /* We need to special-case the result with a range.
10823 This is done for the benefit of "ptype". gdb's Ada support
10824 historically used the LHS to set the result type here, so
10825 preserve this behavior. */
10826 if (type->code () == TYPE_CODE_RANGE)
10827 arg1 = value_cast (type, arg1);
10828 return arg1;
10831 value *
10832 ada_unop_atr_operation::evaluate (struct type *expect_type,
10833 struct expression *exp,
10834 enum noside noside)
10836 struct type *type_arg = nullptr;
10837 value *val = nullptr;
10839 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10841 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10842 EVAL_AVOID_SIDE_EFFECTS);
10843 type_arg = value_type (tem);
10845 else
10846 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10848 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10849 val, type_arg, std::get<2> (m_storage));
10852 value *
10853 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10854 struct expression *exp,
10855 enum noside noside)
10857 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10858 return value_zero (expect_type, not_lval);
10860 const bound_minimal_symbol &b = std::get<0> (m_storage);
10861 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10863 val = ada_value_cast (expect_type, val);
10865 /* Follow the Ada language semantics that do not allow taking
10866 an address of the result of a cast (view conversion in Ada). */
10867 if (VALUE_LVAL (val) == lval_memory)
10869 if (value_lazy (val))
10870 value_fetch_lazy (val);
10871 VALUE_LVAL (val) = not_lval;
10873 return val;
10876 value *
10877 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10878 struct expression *exp,
10879 enum noside noside)
10881 value *val = evaluate_var_value (noside,
10882 std::get<0> (m_storage).block,
10883 std::get<0> (m_storage).symbol);
10885 val = ada_value_cast (expect_type, val);
10887 /* Follow the Ada language semantics that do not allow taking
10888 an address of the result of a cast (view conversion in Ada). */
10889 if (VALUE_LVAL (val) == lval_memory)
10891 if (value_lazy (val))
10892 value_fetch_lazy (val);
10893 VALUE_LVAL (val) = not_lval;
10895 return val;
10898 value *
10899 ada_var_value_operation::evaluate (struct type *expect_type,
10900 struct expression *exp,
10901 enum noside noside)
10903 symbol *sym = std::get<0> (m_storage).symbol;
10905 if (sym->domain () == UNDEF_DOMAIN)
10906 /* Only encountered when an unresolved symbol occurs in a
10907 context other than a function call, in which case, it is
10908 invalid. */
10909 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10910 sym->print_name ());
10912 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10914 struct type *type = static_unwrap_type (sym->type ());
10915 /* Check to see if this is a tagged type. We also need to handle
10916 the case where the type is a reference to a tagged type, but
10917 we have to be careful to exclude pointers to tagged types.
10918 The latter should be shown as usual (as a pointer), whereas
10919 a reference should mostly be transparent to the user. */
10920 if (ada_is_tagged_type (type, 0)
10921 || (type->code () == TYPE_CODE_REF
10922 && ada_is_tagged_type (type->target_type (), 0)))
10924 /* Tagged types are a little special in the fact that the real
10925 type is dynamic and can only be determined by inspecting the
10926 object's tag. This means that we need to get the object's
10927 value first (EVAL_NORMAL) and then extract the actual object
10928 type from its tag.
10930 Note that we cannot skip the final step where we extract
10931 the object type from its tag, because the EVAL_NORMAL phase
10932 results in dynamic components being resolved into fixed ones.
10933 This can cause problems when trying to print the type
10934 description of tagged types whose parent has a dynamic size:
10935 We use the type name of the "_parent" component in order
10936 to print the name of the ancestor type in the type description.
10937 If that component had a dynamic size, the resolution into
10938 a fixed type would result in the loss of that type name,
10939 thus preventing us from printing the name of the ancestor
10940 type in the type description. */
10941 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10943 if (type->code () != TYPE_CODE_REF)
10945 struct type *actual_type;
10947 actual_type = type_from_tag (ada_value_tag (arg1));
10948 if (actual_type == NULL)
10949 /* If, for some reason, we were unable to determine
10950 the actual type from the tag, then use the static
10951 approximation that we just computed as a fallback.
10952 This can happen if the debugging information is
10953 incomplete, for instance. */
10954 actual_type = type;
10955 return value_zero (actual_type, not_lval);
10957 else
10959 /* In the case of a ref, ada_coerce_ref takes care
10960 of determining the actual type. But the evaluation
10961 should return a ref as it should be valid to ask
10962 for its address; so rebuild a ref after coerce. */
10963 arg1 = ada_coerce_ref (arg1);
10964 return value_ref (arg1, TYPE_CODE_REF);
10968 /* Records and unions for which GNAT encodings have been
10969 generated need to be statically fixed as well.
10970 Otherwise, non-static fixing produces a type where
10971 all dynamic properties are removed, which prevents "ptype"
10972 from being able to completely describe the type.
10973 For instance, a case statement in a variant record would be
10974 replaced by the relevant components based on the actual
10975 value of the discriminants. */
10976 if ((type->code () == TYPE_CODE_STRUCT
10977 && dynamic_template_type (type) != NULL)
10978 || (type->code () == TYPE_CODE_UNION
10979 && ada_find_parallel_type (type, "___XVU") != NULL))
10980 return value_zero (to_static_fixed_type (type), not_lval);
10983 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10984 return ada_to_fixed_value (arg1);
10987 bool
10988 ada_var_value_operation::resolve (struct expression *exp,
10989 bool deprocedure_p,
10990 bool parse_completion,
10991 innermost_block_tracker *tracker,
10992 struct type *context_type)
10994 symbol *sym = std::get<0> (m_storage).symbol;
10995 if (sym->domain () == UNDEF_DOMAIN)
10997 block_symbol resolved
10998 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10999 context_type, parse_completion,
11000 deprocedure_p, tracker);
11001 std::get<0> (m_storage) = resolved;
11004 if (deprocedure_p
11005 && (std::get<0> (m_storage).symbol->type ()->code ()
11006 == TYPE_CODE_FUNC))
11007 return true;
11009 return false;
11012 value *
11013 ada_atr_val_operation::evaluate (struct type *expect_type,
11014 struct expression *exp,
11015 enum noside noside)
11017 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
11018 return ada_val_atr (noside, std::get<0> (m_storage), arg);
11021 value *
11022 ada_unop_ind_operation::evaluate (struct type *expect_type,
11023 struct expression *exp,
11024 enum noside noside)
11026 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11028 struct type *type = ada_check_typedef (value_type (arg1));
11029 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11031 if (ada_is_array_descriptor_type (type))
11032 /* GDB allows dereferencing GNAT array descriptors. */
11034 struct type *arrType = ada_type_of_array (arg1, 0);
11036 if (arrType == NULL)
11037 error (_("Attempt to dereference null array pointer."));
11038 return value_at_lazy (arrType, 0);
11040 else if (type->code () == TYPE_CODE_PTR
11041 || type->code () == TYPE_CODE_REF
11042 /* In C you can dereference an array to get the 1st elt. */
11043 || type->code () == TYPE_CODE_ARRAY)
11045 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11046 only be determined by inspecting the object's tag.
11047 This means that we need to evaluate completely the
11048 expression in order to get its type. */
11050 if ((type->code () == TYPE_CODE_REF
11051 || type->code () == TYPE_CODE_PTR)
11052 && ada_is_tagged_type (type->target_type (), 0))
11054 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11055 EVAL_NORMAL);
11056 type = value_type (ada_value_ind (arg1));
11058 else
11060 type = to_static_fixed_type
11061 (ada_aligned_type
11062 (ada_check_typedef (type->target_type ())));
11064 return value_zero (type, lval_memory);
11066 else if (type->code () == TYPE_CODE_INT)
11068 /* GDB allows dereferencing an int. */
11069 if (expect_type == NULL)
11070 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11071 lval_memory);
11072 else
11074 expect_type =
11075 to_static_fixed_type (ada_aligned_type (expect_type));
11076 return value_zero (expect_type, lval_memory);
11079 else
11080 error (_("Attempt to take contents of a non-pointer value."));
11082 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11083 type = ada_check_typedef (value_type (arg1));
11085 if (type->code () == TYPE_CODE_INT)
11086 /* GDB allows dereferencing an int. If we were given
11087 the expect_type, then use that as the target type.
11088 Otherwise, assume that the target type is an int. */
11090 if (expect_type != NULL)
11091 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11092 arg1));
11093 else
11094 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11095 (CORE_ADDR) value_as_address (arg1));
11098 if (ada_is_array_descriptor_type (type))
11099 /* GDB allows dereferencing GNAT array descriptors. */
11100 return ada_coerce_to_simple_array (arg1);
11101 else
11102 return ada_value_ind (arg1);
11105 value *
11106 ada_structop_operation::evaluate (struct type *expect_type,
11107 struct expression *exp,
11108 enum noside noside)
11110 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11111 const char *str = std::get<1> (m_storage).c_str ();
11112 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11114 struct type *type;
11115 struct type *type1 = value_type (arg1);
11117 if (ada_is_tagged_type (type1, 1))
11119 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11121 /* If the field is not found, check if it exists in the
11122 extension of this object's type. This means that we
11123 need to evaluate completely the expression. */
11125 if (type == NULL)
11127 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11128 EVAL_NORMAL);
11129 arg1 = ada_value_struct_elt (arg1, str, 0);
11130 arg1 = unwrap_value (arg1);
11131 type = value_type (ada_to_fixed_value (arg1));
11134 else
11135 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11137 return value_zero (ada_aligned_type (type), lval_memory);
11139 else
11141 arg1 = ada_value_struct_elt (arg1, str, 0);
11142 arg1 = unwrap_value (arg1);
11143 return ada_to_fixed_value (arg1);
11147 value *
11148 ada_funcall_operation::evaluate (struct type *expect_type,
11149 struct expression *exp,
11150 enum noside noside)
11152 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11153 int nargs = args_up.size ();
11154 std::vector<value *> argvec (nargs);
11155 operation_up &callee_op = std::get<0> (m_storage);
11157 ada_var_value_operation *avv
11158 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11159 if (avv != nullptr
11160 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11161 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11162 avv->get_symbol ()->print_name ());
11164 value *callee = callee_op->evaluate (nullptr, exp, noside);
11165 for (int i = 0; i < args_up.size (); ++i)
11166 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11168 if (ada_is_constrained_packed_array_type
11169 (desc_base_type (value_type (callee))))
11170 callee = ada_coerce_to_simple_array (callee);
11171 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11172 && TYPE_FIELD_BITSIZE (value_type (callee), 0) != 0)
11173 /* This is a packed array that has already been fixed, and
11174 therefore already coerced to a simple array. Nothing further
11175 to do. */
11177 else if (value_type (callee)->code () == TYPE_CODE_REF)
11179 /* Make sure we dereference references so that all the code below
11180 feels like it's really handling the referenced value. Wrapping
11181 types (for alignment) may be there, so make sure we strip them as
11182 well. */
11183 callee = ada_to_fixed_value (coerce_ref (callee));
11185 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11186 && VALUE_LVAL (callee) == lval_memory)
11187 callee = value_addr (callee);
11189 struct type *type = ada_check_typedef (value_type (callee));
11191 /* Ada allows us to implicitly dereference arrays when subscripting
11192 them. So, if this is an array typedef (encoding use for array
11193 access types encoded as fat pointers), strip it now. */
11194 if (type->code () == TYPE_CODE_TYPEDEF)
11195 type = ada_typedef_target_type (type);
11197 if (type->code () == TYPE_CODE_PTR)
11199 switch (ada_check_typedef (type->target_type ())->code ())
11201 case TYPE_CODE_FUNC:
11202 type = ada_check_typedef (type->target_type ());
11203 break;
11204 case TYPE_CODE_ARRAY:
11205 break;
11206 case TYPE_CODE_STRUCT:
11207 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11208 callee = ada_value_ind (callee);
11209 type = ada_check_typedef (type->target_type ());
11210 break;
11211 default:
11212 error (_("cannot subscript or call something of type `%s'"),
11213 ada_type_name (value_type (callee)));
11214 break;
11218 switch (type->code ())
11220 case TYPE_CODE_FUNC:
11221 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11223 if (type->target_type () == NULL)
11224 error_call_unknown_return_type (NULL);
11225 return allocate_value (type->target_type ());
11227 return call_function_by_hand (callee, NULL, argvec);
11228 case TYPE_CODE_INTERNAL_FUNCTION:
11229 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11230 /* We don't know anything about what the internal
11231 function might return, but we have to return
11232 something. */
11233 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11234 not_lval);
11235 else
11236 return call_internal_function (exp->gdbarch, exp->language_defn,
11237 callee, nargs,
11238 argvec.data ());
11240 case TYPE_CODE_STRUCT:
11242 int arity;
11244 arity = ada_array_arity (type);
11245 type = ada_array_element_type (type, nargs);
11246 if (type == NULL)
11247 error (_("cannot subscript or call a record"));
11248 if (arity != nargs)
11249 error (_("wrong number of subscripts; expecting %d"), arity);
11250 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11251 return value_zero (ada_aligned_type (type), lval_memory);
11252 return
11253 unwrap_value (ada_value_subscript
11254 (callee, nargs, argvec.data ()));
11256 case TYPE_CODE_ARRAY:
11257 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11259 type = ada_array_element_type (type, nargs);
11260 if (type == NULL)
11261 error (_("element type of array unknown"));
11262 else
11263 return value_zero (ada_aligned_type (type), lval_memory);
11265 return
11266 unwrap_value (ada_value_subscript
11267 (ada_coerce_to_simple_array (callee),
11268 nargs, argvec.data ()));
11269 case TYPE_CODE_PTR: /* Pointer to array */
11270 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11272 type = to_fixed_array_type (type->target_type (), NULL, 1);
11273 type = ada_array_element_type (type, nargs);
11274 if (type == NULL)
11275 error (_("element type of array unknown"));
11276 else
11277 return value_zero (ada_aligned_type (type), lval_memory);
11279 return
11280 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11281 argvec.data ()));
11283 default:
11284 error (_("Attempt to index or call something other than an "
11285 "array or function"));
11289 bool
11290 ada_funcall_operation::resolve (struct expression *exp,
11291 bool deprocedure_p,
11292 bool parse_completion,
11293 innermost_block_tracker *tracker,
11294 struct type *context_type)
11296 operation_up &callee_op = std::get<0> (m_storage);
11298 ada_var_value_operation *avv
11299 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11300 if (avv == nullptr)
11301 return false;
11303 symbol *sym = avv->get_symbol ();
11304 if (sym->domain () != UNDEF_DOMAIN)
11305 return false;
11307 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11308 int nargs = args_up.size ();
11309 std::vector<value *> argvec (nargs);
11311 for (int i = 0; i < args_up.size (); ++i)
11312 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11314 const block *block = avv->get_block ();
11315 block_symbol resolved
11316 = ada_resolve_funcall (sym, block,
11317 context_type, parse_completion,
11318 nargs, argvec.data (),
11319 tracker);
11321 std::get<0> (m_storage)
11322 = make_operation<ada_var_value_operation> (resolved);
11323 return false;
11326 bool
11327 ada_ternop_slice_operation::resolve (struct expression *exp,
11328 bool deprocedure_p,
11329 bool parse_completion,
11330 innermost_block_tracker *tracker,
11331 struct type *context_type)
11333 /* Historically this check was done during resolution, so we
11334 continue that here. */
11335 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11336 EVAL_AVOID_SIDE_EFFECTS);
11337 if (ada_is_any_packed_array_type (value_type (v)))
11338 error (_("cannot slice a packed array"));
11339 return false;
11346 /* Return non-zero iff TYPE represents a System.Address type. */
11349 ada_is_system_address_type (struct type *type)
11351 return (type->name () && strcmp (type->name (), "system__address") == 0);
11356 /* Range types */
11358 /* Scan STR beginning at position K for a discriminant name, and
11359 return the value of that discriminant field of DVAL in *PX. If
11360 PNEW_K is not null, put the position of the character beyond the
11361 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11362 not alter *PX and *PNEW_K if unsuccessful. */
11364 static int
11365 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11366 int *pnew_k)
11368 static std::string storage;
11369 const char *pstart, *pend, *bound;
11370 struct value *bound_val;
11372 if (dval == NULL || str == NULL || str[k] == '\0')
11373 return 0;
11375 pstart = str + k;
11376 pend = strstr (pstart, "__");
11377 if (pend == NULL)
11379 bound = pstart;
11380 k += strlen (bound);
11382 else
11384 int len = pend - pstart;
11386 /* Strip __ and beyond. */
11387 storage = std::string (pstart, len);
11388 bound = storage.c_str ();
11389 k = pend - str;
11392 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
11393 if (bound_val == NULL)
11394 return 0;
11396 *px = value_as_long (bound_val);
11397 if (pnew_k != NULL)
11398 *pnew_k = k;
11399 return 1;
11402 /* Value of variable named NAME. Only exact matches are considered.
11403 If no such variable found, then if ERR_MSG is null, returns 0, and
11404 otherwise causes an error with message ERR_MSG. */
11406 static struct value *
11407 get_var_value (const char *name, const char *err_msg)
11409 std::string quoted_name = add_angle_brackets (name);
11411 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11413 std::vector<struct block_symbol> syms
11414 = ada_lookup_symbol_list_worker (lookup_name,
11415 get_selected_block (0),
11416 VAR_DOMAIN, 1);
11418 if (syms.size () != 1)
11420 if (err_msg == NULL)
11421 return 0;
11422 else
11423 error (("%s"), err_msg);
11426 return value_of_variable (syms[0].symbol, syms[0].block);
11429 /* Value of integer variable named NAME in the current environment.
11430 If no such variable is found, returns false. Otherwise, sets VALUE
11431 to the variable's value and returns true. */
11433 bool
11434 get_int_var_value (const char *name, LONGEST &value)
11436 struct value *var_val = get_var_value (name, 0);
11438 if (var_val == 0)
11439 return false;
11441 value = value_as_long (var_val);
11442 return true;
11446 /* Return a range type whose base type is that of the range type named
11447 NAME in the current environment, and whose bounds are calculated
11448 from NAME according to the GNAT range encoding conventions.
11449 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11450 corresponding range type from debug information; fall back to using it
11451 if symbol lookup fails. If a new type must be created, allocate it
11452 like ORIG_TYPE was. The bounds information, in general, is encoded
11453 in NAME, the base type given in the named range type. */
11455 static struct type *
11456 to_fixed_range_type (struct type *raw_type, struct value *dval)
11458 const char *name;
11459 struct type *base_type;
11460 const char *subtype_info;
11462 gdb_assert (raw_type != NULL);
11463 gdb_assert (raw_type->name () != NULL);
11465 if (raw_type->code () == TYPE_CODE_RANGE)
11466 base_type = raw_type->target_type ();
11467 else
11468 base_type = raw_type;
11470 name = raw_type->name ();
11471 subtype_info = strstr (name, "___XD");
11472 if (subtype_info == NULL)
11474 LONGEST L = ada_discrete_type_low_bound (raw_type);
11475 LONGEST U = ada_discrete_type_high_bound (raw_type);
11477 if (L < INT_MIN || U > INT_MAX)
11478 return raw_type;
11479 else
11480 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
11481 L, U);
11483 else
11485 int prefix_len = subtype_info - name;
11486 LONGEST L, U;
11487 struct type *type;
11488 const char *bounds_str;
11489 int n;
11491 subtype_info += 5;
11492 bounds_str = strchr (subtype_info, '_');
11493 n = 1;
11495 if (*subtype_info == 'L')
11497 if (!ada_scan_number (bounds_str, n, &L, &n)
11498 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11499 return raw_type;
11500 if (bounds_str[n] == '_')
11501 n += 2;
11502 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11503 n += 1;
11504 subtype_info += 1;
11506 else
11508 std::string name_buf = std::string (name, prefix_len) + "___L";
11509 if (!get_int_var_value (name_buf.c_str (), L))
11511 lim_warning (_("Unknown lower bound, using 1."));
11512 L = 1;
11516 if (*subtype_info == 'U')
11518 if (!ada_scan_number (bounds_str, n, &U, &n)
11519 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11520 return raw_type;
11522 else
11524 std::string name_buf = std::string (name, prefix_len) + "___U";
11525 if (!get_int_var_value (name_buf.c_str (), U))
11527 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11528 U = L;
11532 type = create_static_range_type (alloc_type_copy (raw_type),
11533 base_type, L, U);
11534 /* create_static_range_type alters the resulting type's length
11535 to match the size of the base_type, which is not what we want.
11536 Set it back to the original range type's length. */
11537 type->set_length (raw_type->length ());
11538 type->set_name (name);
11539 return type;
11543 /* True iff NAME is the name of a range type. */
11546 ada_is_range_type_name (const char *name)
11548 return (name != NULL && strstr (name, "___XD"));
11552 /* Modular types */
11554 /* True iff TYPE is an Ada modular type. */
11557 ada_is_modular_type (struct type *type)
11559 struct type *subranged_type = get_base_type (type);
11561 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11562 && subranged_type->code () == TYPE_CODE_INT
11563 && subranged_type->is_unsigned ());
11566 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11568 ULONGEST
11569 ada_modulus (struct type *type)
11571 const dynamic_prop &high = type->bounds ()->high;
11573 if (high.kind () == PROP_CONST)
11574 return (ULONGEST) high.const_val () + 1;
11576 /* If TYPE is unresolved, the high bound might be a location list. Return
11577 0, for lack of a better value to return. */
11578 return 0;
11582 /* Ada exception catchpoint support:
11583 ---------------------------------
11585 We support 3 kinds of exception catchpoints:
11586 . catchpoints on Ada exceptions
11587 . catchpoints on unhandled Ada exceptions
11588 . catchpoints on failed assertions
11590 Exceptions raised during failed assertions, or unhandled exceptions
11591 could perfectly be caught with the general catchpoint on Ada exceptions.
11592 However, we can easily differentiate these two special cases, and having
11593 the option to distinguish these two cases from the rest can be useful
11594 to zero-in on certain situations.
11596 Exception catchpoints are a specialized form of breakpoint,
11597 since they rely on inserting breakpoints inside known routines
11598 of the GNAT runtime. The implementation therefore uses a standard
11599 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11600 of breakpoint_ops.
11602 Support in the runtime for exception catchpoints have been changed
11603 a few times already, and these changes affect the implementation
11604 of these catchpoints. In order to be able to support several
11605 variants of the runtime, we use a sniffer that will determine
11606 the runtime variant used by the program being debugged. */
11608 /* Ada's standard exceptions.
11610 The Ada 83 standard also defined Numeric_Error. But there so many
11611 situations where it was unclear from the Ada 83 Reference Manual
11612 (RM) whether Constraint_Error or Numeric_Error should be raised,
11613 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11614 Interpretation saying that anytime the RM says that Numeric_Error
11615 should be raised, the implementation may raise Constraint_Error.
11616 Ada 95 went one step further and pretty much removed Numeric_Error
11617 from the list of standard exceptions (it made it a renaming of
11618 Constraint_Error, to help preserve compatibility when compiling
11619 an Ada83 compiler). As such, we do not include Numeric_Error from
11620 this list of standard exceptions. */
11622 static const char * const standard_exc[] = {
11623 "constraint_error",
11624 "program_error",
11625 "storage_error",
11626 "tasking_error"
11629 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11631 /* A structure that describes how to support exception catchpoints
11632 for a given executable. */
11634 struct exception_support_info
11636 /* The name of the symbol to break on in order to insert
11637 a catchpoint on exceptions. */
11638 const char *catch_exception_sym;
11640 /* The name of the symbol to break on in order to insert
11641 a catchpoint on unhandled exceptions. */
11642 const char *catch_exception_unhandled_sym;
11644 /* The name of the symbol to break on in order to insert
11645 a catchpoint on failed assertions. */
11646 const char *catch_assert_sym;
11648 /* The name of the symbol to break on in order to insert
11649 a catchpoint on exception handling. */
11650 const char *catch_handlers_sym;
11652 /* Assuming that the inferior just triggered an unhandled exception
11653 catchpoint, this function is responsible for returning the address
11654 in inferior memory where the name of that exception is stored.
11655 Return zero if the address could not be computed. */
11656 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11659 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11660 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11662 /* The following exception support info structure describes how to
11663 implement exception catchpoints with the latest version of the
11664 Ada runtime (as of 2019-08-??). */
11666 static const struct exception_support_info default_exception_support_info =
11668 "__gnat_debug_raise_exception", /* catch_exception_sym */
11669 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11670 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11671 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11672 ada_unhandled_exception_name_addr
11675 /* The following exception support info structure describes how to
11676 implement exception catchpoints with an earlier version of the
11677 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11679 static const struct exception_support_info exception_support_info_v0 =
11681 "__gnat_debug_raise_exception", /* catch_exception_sym */
11682 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11683 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11684 "__gnat_begin_handler", /* catch_handlers_sym */
11685 ada_unhandled_exception_name_addr
11688 /* The following exception support info structure describes how to
11689 implement exception catchpoints with a slightly older version
11690 of the Ada runtime. */
11692 static const struct exception_support_info exception_support_info_fallback =
11694 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11695 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11696 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11697 "__gnat_begin_handler", /* catch_handlers_sym */
11698 ada_unhandled_exception_name_addr_from_raise
11701 /* Return nonzero if we can detect the exception support routines
11702 described in EINFO.
11704 This function errors out if an abnormal situation is detected
11705 (for instance, if we find the exception support routines, but
11706 that support is found to be incomplete). */
11708 static int
11709 ada_has_this_exception_support (const struct exception_support_info *einfo)
11711 struct symbol *sym;
11713 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11714 that should be compiled with debugging information. As a result, we
11715 expect to find that symbol in the symtabs. */
11717 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11718 if (sym == NULL)
11720 /* Perhaps we did not find our symbol because the Ada runtime was
11721 compiled without debugging info, or simply stripped of it.
11722 It happens on some GNU/Linux distributions for instance, where
11723 users have to install a separate debug package in order to get
11724 the runtime's debugging info. In that situation, let the user
11725 know why we cannot insert an Ada exception catchpoint.
11727 Note: Just for the purpose of inserting our Ada exception
11728 catchpoint, we could rely purely on the associated minimal symbol.
11729 But we would be operating in degraded mode anyway, since we are
11730 still lacking the debugging info needed later on to extract
11731 the name of the exception being raised (this name is printed in
11732 the catchpoint message, and is also used when trying to catch
11733 a specific exception). We do not handle this case for now. */
11734 struct bound_minimal_symbol msym
11735 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11737 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11738 error (_("Your Ada runtime appears to be missing some debugging "
11739 "information.\nCannot insert Ada exception catchpoint "
11740 "in this configuration."));
11742 return 0;
11745 /* Make sure that the symbol we found corresponds to a function. */
11747 if (sym->aclass () != LOC_BLOCK)
11749 error (_("Symbol \"%s\" is not a function (class = %d)"),
11750 sym->linkage_name (), sym->aclass ());
11751 return 0;
11754 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11755 if (sym == NULL)
11757 struct bound_minimal_symbol msym
11758 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11760 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11761 error (_("Your Ada runtime appears to be missing some debugging "
11762 "information.\nCannot insert Ada exception catchpoint "
11763 "in this configuration."));
11765 return 0;
11768 /* Make sure that the symbol we found corresponds to a function. */
11770 if (sym->aclass () != LOC_BLOCK)
11772 error (_("Symbol \"%s\" is not a function (class = %d)"),
11773 sym->linkage_name (), sym->aclass ());
11774 return 0;
11777 return 1;
11780 /* Inspect the Ada runtime and determine which exception info structure
11781 should be used to provide support for exception catchpoints.
11783 This function will always set the per-inferior exception_info,
11784 or raise an error. */
11786 static void
11787 ada_exception_support_info_sniffer (void)
11789 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11791 /* If the exception info is already known, then no need to recompute it. */
11792 if (data->exception_info != NULL)
11793 return;
11795 /* Check the latest (default) exception support info. */
11796 if (ada_has_this_exception_support (&default_exception_support_info))
11798 data->exception_info = &default_exception_support_info;
11799 return;
11802 /* Try the v0 exception suport info. */
11803 if (ada_has_this_exception_support (&exception_support_info_v0))
11805 data->exception_info = &exception_support_info_v0;
11806 return;
11809 /* Try our fallback exception suport info. */
11810 if (ada_has_this_exception_support (&exception_support_info_fallback))
11812 data->exception_info = &exception_support_info_fallback;
11813 return;
11816 /* Sometimes, it is normal for us to not be able to find the routine
11817 we are looking for. This happens when the program is linked with
11818 the shared version of the GNAT runtime, and the program has not been
11819 started yet. Inform the user of these two possible causes if
11820 applicable. */
11822 if (ada_update_initial_language (language_unknown) != language_ada)
11823 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
11825 /* If the symbol does not exist, then check that the program is
11826 already started, to make sure that shared libraries have been
11827 loaded. If it is not started, this may mean that the symbol is
11828 in a shared library. */
11830 if (inferior_ptid.pid () == 0)
11831 error (_("Unable to insert catchpoint. Try to start the program first."));
11833 /* At this point, we know that we are debugging an Ada program and
11834 that the inferior has been started, but we still are not able to
11835 find the run-time symbols. That can mean that we are in
11836 configurable run time mode, or that a-except as been optimized
11837 out by the linker... In any case, at this point it is not worth
11838 supporting this feature. */
11840 error (_("Cannot insert Ada exception catchpoints in this configuration."));
11843 /* True iff FRAME is very likely to be that of a function that is
11844 part of the runtime system. This is all very heuristic, but is
11845 intended to be used as advice as to what frames are uninteresting
11846 to most users. */
11848 static int
11849 is_known_support_routine (frame_info_ptr frame)
11851 enum language func_lang;
11852 int i;
11853 const char *fullname;
11855 /* If this code does not have any debugging information (no symtab),
11856 This cannot be any user code. */
11858 symtab_and_line sal = find_frame_sal (frame);
11859 if (sal.symtab == NULL)
11860 return 1;
11862 /* If there is a symtab, but the associated source file cannot be
11863 located, then assume this is not user code: Selecting a frame
11864 for which we cannot display the code would not be very helpful
11865 for the user. This should also take care of case such as VxWorks
11866 where the kernel has some debugging info provided for a few units. */
11868 fullname = symtab_to_fullname (sal.symtab);
11869 if (access (fullname, R_OK) != 0)
11870 return 1;
11872 /* Check the unit filename against the Ada runtime file naming.
11873 We also check the name of the objfile against the name of some
11874 known system libraries that sometimes come with debugging info
11875 too. */
11877 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11879 re_comp (known_runtime_file_name_patterns[i]);
11880 if (re_exec (lbasename (sal.symtab->filename)))
11881 return 1;
11882 if (sal.symtab->compunit ()->objfile () != NULL
11883 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11884 return 1;
11887 /* Check whether the function is a GNAT-generated entity. */
11889 gdb::unique_xmalloc_ptr<char> func_name
11890 = find_frame_funname (frame, &func_lang, NULL);
11891 if (func_name == NULL)
11892 return 1;
11894 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11896 re_comp (known_auxiliary_function_name_patterns[i]);
11897 if (re_exec (func_name.get ()))
11898 return 1;
11901 return 0;
11904 /* Find the first frame that contains debugging information and that is not
11905 part of the Ada run-time, starting from FI and moving upward. */
11907 void
11908 ada_find_printable_frame (frame_info_ptr fi)
11910 for (; fi != NULL; fi = get_prev_frame (fi))
11912 if (!is_known_support_routine (fi))
11914 select_frame (fi);
11915 break;
11921 /* Assuming that the inferior just triggered an unhandled exception
11922 catchpoint, return the address in inferior memory where the name
11923 of the exception is stored.
11925 Return zero if the address could not be computed. */
11927 static CORE_ADDR
11928 ada_unhandled_exception_name_addr (void)
11930 return parse_and_eval_address ("e.full_name");
11933 /* Same as ada_unhandled_exception_name_addr, except that this function
11934 should be used when the inferior uses an older version of the runtime,
11935 where the exception name needs to be extracted from a specific frame
11936 several frames up in the callstack. */
11938 static CORE_ADDR
11939 ada_unhandled_exception_name_addr_from_raise (void)
11941 int frame_level;
11942 frame_info_ptr fi;
11943 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11945 /* To determine the name of this exception, we need to select
11946 the frame corresponding to RAISE_SYM_NAME. This frame is
11947 at least 3 levels up, so we simply skip the first 3 frames
11948 without checking the name of their associated function. */
11949 fi = get_current_frame ();
11950 for (frame_level = 0; frame_level < 3; frame_level += 1)
11951 if (fi != NULL)
11952 fi = get_prev_frame (fi);
11954 while (fi != NULL)
11956 enum language func_lang;
11958 gdb::unique_xmalloc_ptr<char> func_name
11959 = find_frame_funname (fi, &func_lang, NULL);
11960 if (func_name != NULL)
11962 if (strcmp (func_name.get (),
11963 data->exception_info->catch_exception_sym) == 0)
11964 break; /* We found the frame we were looking for... */
11966 fi = get_prev_frame (fi);
11969 if (fi == NULL)
11970 return 0;
11972 select_frame (fi);
11973 return parse_and_eval_address ("id.full_name");
11976 /* Assuming the inferior just triggered an Ada exception catchpoint
11977 (of any type), return the address in inferior memory where the name
11978 of the exception is stored, if applicable.
11980 Assumes the selected frame is the current frame.
11982 Return zero if the address could not be computed, or if not relevant. */
11984 static CORE_ADDR
11985 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11987 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11989 switch (ex)
11991 case ada_catch_exception:
11992 return (parse_and_eval_address ("e.full_name"));
11993 break;
11995 case ada_catch_exception_unhandled:
11996 return data->exception_info->unhandled_exception_name_addr ();
11997 break;
11999 case ada_catch_handlers:
12000 return 0; /* The runtimes does not provide access to the exception
12001 name. */
12002 break;
12004 case ada_catch_assert:
12005 return 0; /* Exception name is not relevant in this case. */
12006 break;
12008 default:
12009 internal_error (_("unexpected catchpoint type"));
12010 break;
12013 return 0; /* Should never be reached. */
12016 /* Assuming the inferior is stopped at an exception catchpoint,
12017 return the message which was associated to the exception, if
12018 available. Return NULL if the message could not be retrieved.
12020 Note: The exception message can be associated to an exception
12021 either through the use of the Raise_Exception function, or
12022 more simply (Ada 2005 and later), via:
12024 raise Exception_Name with "exception message";
12028 static gdb::unique_xmalloc_ptr<char>
12029 ada_exception_message_1 (void)
12031 struct value *e_msg_val;
12032 int e_msg_len;
12034 /* For runtimes that support this feature, the exception message
12035 is passed as an unbounded string argument called "message". */
12036 e_msg_val = parse_and_eval ("message");
12037 if (e_msg_val == NULL)
12038 return NULL; /* Exception message not supported. */
12040 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12041 gdb_assert (e_msg_val != NULL);
12042 e_msg_len = value_type (e_msg_val)->length ();
12044 /* If the message string is empty, then treat it as if there was
12045 no exception message. */
12046 if (e_msg_len <= 0)
12047 return NULL;
12049 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12050 read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
12051 e_msg_len);
12052 e_msg.get ()[e_msg_len] = '\0';
12054 return e_msg;
12057 /* Same as ada_exception_message_1, except that all exceptions are
12058 contained here (returning NULL instead). */
12060 static gdb::unique_xmalloc_ptr<char>
12061 ada_exception_message (void)
12063 gdb::unique_xmalloc_ptr<char> e_msg;
12067 e_msg = ada_exception_message_1 ();
12069 catch (const gdb_exception_error &e)
12071 e_msg.reset (nullptr);
12074 return e_msg;
12077 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12078 any error that ada_exception_name_addr_1 might cause to be thrown.
12079 When an error is intercepted, a warning with the error message is printed,
12080 and zero is returned. */
12082 static CORE_ADDR
12083 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12085 CORE_ADDR result = 0;
12089 result = ada_exception_name_addr_1 (ex);
12092 catch (const gdb_exception_error &e)
12094 warning (_("failed to get exception name: %s"), e.what ());
12095 return 0;
12098 return result;
12101 static std::string ada_exception_catchpoint_cond_string
12102 (const char *excep_string,
12103 enum ada_exception_catchpoint_kind ex);
12105 /* Ada catchpoints.
12107 In the case of catchpoints on Ada exceptions, the catchpoint will
12108 stop the target on every exception the program throws. When a user
12109 specifies the name of a specific exception, we translate this
12110 request into a condition expression (in text form), and then parse
12111 it into an expression stored in each of the catchpoint's locations.
12112 We then use this condition to check whether the exception that was
12113 raised is the one the user is interested in. If not, then the
12114 target is resumed again. We store the name of the requested
12115 exception, in order to be able to re-set the condition expression
12116 when symbols change. */
12118 /* An instance of this type is used to represent an Ada catchpoint. */
12120 struct ada_catchpoint : public code_breakpoint
12122 ada_catchpoint (struct gdbarch *gdbarch_,
12123 enum ada_exception_catchpoint_kind kind,
12124 struct symtab_and_line sal,
12125 const char *addr_string_,
12126 bool tempflag,
12127 bool enabled,
12128 bool from_tty)
12129 : code_breakpoint (gdbarch_, bp_catchpoint),
12130 m_kind (kind)
12132 add_location (sal);
12134 /* Unlike most code_breakpoint types, Ada catchpoints are
12135 pspace-specific. */
12136 gdb_assert (sal.pspace != nullptr);
12137 this->pspace = sal.pspace;
12139 if (from_tty)
12141 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12142 if (!loc_gdbarch)
12143 loc_gdbarch = gdbarch;
12145 describe_other_breakpoints (loc_gdbarch,
12146 sal.pspace, sal.pc, sal.section, -1);
12147 /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12148 version for exception catchpoints, because two catchpoints
12149 used for different exception names will use the same address.
12150 In this case, a "breakpoint ... also set at..." warning is
12151 unproductive. Besides, the warning phrasing is also a bit
12152 inappropriate, we should use the word catchpoint, and tell
12153 the user what type of catchpoint it is. The above is good
12154 enough for now, though. */
12157 enable_state = enabled ? bp_enabled : bp_disabled;
12158 disposition = tempflag ? disp_del : disp_donttouch;
12159 locspec = string_to_location_spec (&addr_string_,
12160 language_def (language_ada));
12161 language = language_ada;
12164 struct bp_location *allocate_location () override;
12165 void re_set () override;
12166 void check_status (struct bpstat *bs) override;
12167 enum print_stop_action print_it (const bpstat *bs) const override;
12168 bool print_one (bp_location **) const override;
12169 void print_mention () const override;
12170 void print_recreate (struct ui_file *fp) const override;
12172 /* The name of the specific exception the user specified. */
12173 std::string excep_string;
12175 /* What kind of catchpoint this is. */
12176 enum ada_exception_catchpoint_kind m_kind;
12179 /* An instance of this type is used to represent an Ada catchpoint
12180 breakpoint location. */
12182 class ada_catchpoint_location : public bp_location
12184 public:
12185 explicit ada_catchpoint_location (ada_catchpoint *owner)
12186 : bp_location (owner, bp_loc_software_breakpoint)
12189 /* The condition that checks whether the exception that was raised
12190 is the specific exception the user specified on catchpoint
12191 creation. */
12192 expression_up excep_cond_expr;
12195 /* Parse the exception condition string in the context of each of the
12196 catchpoint's locations, and store them for later evaluation. */
12198 static void
12199 create_excep_cond_exprs (struct ada_catchpoint *c,
12200 enum ada_exception_catchpoint_kind ex)
12202 /* Nothing to do if there's no specific exception to catch. */
12203 if (c->excep_string.empty ())
12204 return;
12206 /* Same if there are no locations... */
12207 if (c->loc == NULL)
12208 return;
12210 /* Compute the condition expression in text form, from the specific
12211 expection we want to catch. */
12212 std::string cond_string
12213 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12215 /* Iterate over all the catchpoint's locations, and parse an
12216 expression for each. */
12217 for (bp_location *bl : c->locations ())
12219 struct ada_catchpoint_location *ada_loc
12220 = (struct ada_catchpoint_location *) bl;
12221 expression_up exp;
12223 if (!bl->shlib_disabled)
12225 const char *s;
12227 s = cond_string.c_str ();
12230 exp = parse_exp_1 (&s, bl->address,
12231 block_for_pc (bl->address),
12234 catch (const gdb_exception_error &e)
12236 warning (_("failed to reevaluate internal exception condition "
12237 "for catchpoint %d: %s"),
12238 c->number, e.what ());
12242 ada_loc->excep_cond_expr = std::move (exp);
12246 /* Implement the ALLOCATE_LOCATION method in the structure for all
12247 exception catchpoint kinds. */
12249 struct bp_location *
12250 ada_catchpoint::allocate_location ()
12252 return new ada_catchpoint_location (this);
12255 /* Implement the RE_SET method in the structure for all exception
12256 catchpoint kinds. */
12258 void
12259 ada_catchpoint::re_set ()
12261 /* Call the base class's method. This updates the catchpoint's
12262 locations. */
12263 this->code_breakpoint::re_set ();
12265 /* Reparse the exception conditional expressions. One for each
12266 location. */
12267 create_excep_cond_exprs (this, m_kind);
12270 /* Returns true if we should stop for this breakpoint hit. If the
12271 user specified a specific exception, we only want to cause a stop
12272 if the program thrown that exception. */
12274 static bool
12275 should_stop_exception (const struct bp_location *bl)
12277 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12278 const struct ada_catchpoint_location *ada_loc
12279 = (const struct ada_catchpoint_location *) bl;
12280 bool stop;
12282 struct internalvar *var = lookup_internalvar ("_ada_exception");
12283 if (c->m_kind == ada_catch_assert)
12284 clear_internalvar (var);
12285 else
12289 const char *expr;
12291 if (c->m_kind == ada_catch_handlers)
12292 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12293 ".all.occurrence.id");
12294 else
12295 expr = "e";
12297 struct value *exc = parse_and_eval (expr);
12298 set_internalvar (var, exc);
12300 catch (const gdb_exception_error &ex)
12302 clear_internalvar (var);
12306 /* With no specific exception, should always stop. */
12307 if (c->excep_string.empty ())
12308 return true;
12310 if (ada_loc->excep_cond_expr == NULL)
12312 /* We will have a NULL expression if back when we were creating
12313 the expressions, this location's had failed to parse. */
12314 return true;
12317 stop = true;
12320 scoped_value_mark mark;
12321 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
12323 catch (const gdb_exception &ex)
12325 exception_fprintf (gdb_stderr, ex,
12326 _("Error in testing exception condition:\n"));
12329 return stop;
12332 /* Implement the CHECK_STATUS method in the structure for all
12333 exception catchpoint kinds. */
12335 void
12336 ada_catchpoint::check_status (bpstat *bs)
12338 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12341 /* Implement the PRINT_IT method in the structure for all exception
12342 catchpoint kinds. */
12344 enum print_stop_action
12345 ada_catchpoint::print_it (const bpstat *bs) const
12347 struct ui_out *uiout = current_uiout;
12349 annotate_catchpoint (number);
12351 if (uiout->is_mi_like_p ())
12353 uiout->field_string ("reason",
12354 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12355 uiout->field_string ("disp", bpdisp_text (disposition));
12358 uiout->text (disposition == disp_del
12359 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12360 print_num_locno (bs, uiout);
12361 uiout->text (", ");
12363 /* ada_exception_name_addr relies on the selected frame being the
12364 current frame. Need to do this here because this function may be
12365 called more than once when printing a stop, and below, we'll
12366 select the first frame past the Ada run-time (see
12367 ada_find_printable_frame). */
12368 select_frame (get_current_frame ());
12370 switch (m_kind)
12372 case ada_catch_exception:
12373 case ada_catch_exception_unhandled:
12374 case ada_catch_handlers:
12376 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12377 char exception_name[256];
12379 if (addr != 0)
12381 read_memory (addr, (gdb_byte *) exception_name,
12382 sizeof (exception_name) - 1);
12383 exception_name [sizeof (exception_name) - 1] = '\0';
12385 else
12387 /* For some reason, we were unable to read the exception
12388 name. This could happen if the Runtime was compiled
12389 without debugging info, for instance. In that case,
12390 just replace the exception name by the generic string
12391 "exception" - it will read as "an exception" in the
12392 notification we are about to print. */
12393 memcpy (exception_name, "exception", sizeof ("exception"));
12395 /* In the case of unhandled exception breakpoints, we print
12396 the exception name as "unhandled EXCEPTION_NAME", to make
12397 it clearer to the user which kind of catchpoint just got
12398 hit. We used ui_out_text to make sure that this extra
12399 info does not pollute the exception name in the MI case. */
12400 if (m_kind == ada_catch_exception_unhandled)
12401 uiout->text ("unhandled ");
12402 uiout->field_string ("exception-name", exception_name);
12404 break;
12405 case ada_catch_assert:
12406 /* In this case, the name of the exception is not really
12407 important. Just print "failed assertion" to make it clearer
12408 that his program just hit an assertion-failure catchpoint.
12409 We used ui_out_text because this info does not belong in
12410 the MI output. */
12411 uiout->text ("failed assertion");
12412 break;
12415 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12416 if (exception_message != NULL)
12418 uiout->text (" (");
12419 uiout->field_string ("exception-message", exception_message.get ());
12420 uiout->text (")");
12423 uiout->text (" at ");
12424 ada_find_printable_frame (get_current_frame ());
12426 return PRINT_SRC_AND_LOC;
12429 /* Implement the PRINT_ONE method in the structure for all exception
12430 catchpoint kinds. */
12432 bool
12433 ada_catchpoint::print_one (bp_location **last_loc) const
12435 struct ui_out *uiout = current_uiout;
12436 struct value_print_options opts;
12438 get_user_print_options (&opts);
12440 if (opts.addressprint)
12441 uiout->field_skip ("addr");
12443 annotate_field (5);
12444 switch (m_kind)
12446 case ada_catch_exception:
12447 if (!excep_string.empty ())
12449 std::string msg = string_printf (_("`%s' Ada exception"),
12450 excep_string.c_str ());
12452 uiout->field_string ("what", msg);
12454 else
12455 uiout->field_string ("what", "all Ada exceptions");
12457 break;
12459 case ada_catch_exception_unhandled:
12460 uiout->field_string ("what", "unhandled Ada exceptions");
12461 break;
12463 case ada_catch_handlers:
12464 if (!excep_string.empty ())
12466 uiout->field_fmt ("what",
12467 _("`%s' Ada exception handlers"),
12468 excep_string.c_str ());
12470 else
12471 uiout->field_string ("what", "all Ada exceptions handlers");
12472 break;
12474 case ada_catch_assert:
12475 uiout->field_string ("what", "failed Ada assertions");
12476 break;
12478 default:
12479 internal_error (_("unexpected catchpoint type"));
12480 break;
12483 return true;
12486 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12487 for all exception catchpoint kinds. */
12489 void
12490 ada_catchpoint::print_mention () const
12492 struct ui_out *uiout = current_uiout;
12494 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12495 : _("Catchpoint "));
12496 uiout->field_signed ("bkptno", number);
12497 uiout->text (": ");
12499 switch (m_kind)
12501 case ada_catch_exception:
12502 if (!excep_string.empty ())
12504 std::string info = string_printf (_("`%s' Ada exception"),
12505 excep_string.c_str ());
12506 uiout->text (info);
12508 else
12509 uiout->text (_("all Ada exceptions"));
12510 break;
12512 case ada_catch_exception_unhandled:
12513 uiout->text (_("unhandled Ada exceptions"));
12514 break;
12516 case ada_catch_handlers:
12517 if (!excep_string.empty ())
12519 std::string info
12520 = string_printf (_("`%s' Ada exception handlers"),
12521 excep_string.c_str ());
12522 uiout->text (info);
12524 else
12525 uiout->text (_("all Ada exceptions handlers"));
12526 break;
12528 case ada_catch_assert:
12529 uiout->text (_("failed Ada assertions"));
12530 break;
12532 default:
12533 internal_error (_("unexpected catchpoint type"));
12534 break;
12538 /* Implement the PRINT_RECREATE method in the structure for all
12539 exception catchpoint kinds. */
12541 void
12542 ada_catchpoint::print_recreate (struct ui_file *fp) const
12544 switch (m_kind)
12546 case ada_catch_exception:
12547 gdb_printf (fp, "catch exception");
12548 if (!excep_string.empty ())
12549 gdb_printf (fp, " %s", excep_string.c_str ());
12550 break;
12552 case ada_catch_exception_unhandled:
12553 gdb_printf (fp, "catch exception unhandled");
12554 break;
12556 case ada_catch_handlers:
12557 gdb_printf (fp, "catch handlers");
12558 break;
12560 case ada_catch_assert:
12561 gdb_printf (fp, "catch assert");
12562 break;
12564 default:
12565 internal_error (_("unexpected catchpoint type"));
12567 print_recreate_thread (fp);
12570 /* See ada-lang.h. */
12572 bool
12573 is_ada_exception_catchpoint (breakpoint *bp)
12575 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12578 /* Split the arguments specified in a "catch exception" command.
12579 Set EX to the appropriate catchpoint type.
12580 Set EXCEP_STRING to the name of the specific exception if
12581 specified by the user.
12582 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12583 "catch handlers" command. False otherwise.
12584 If a condition is found at the end of the arguments, the condition
12585 expression is stored in COND_STRING (memory must be deallocated
12586 after use). Otherwise COND_STRING is set to NULL. */
12588 static void
12589 catch_ada_exception_command_split (const char *args,
12590 bool is_catch_handlers_cmd,
12591 enum ada_exception_catchpoint_kind *ex,
12592 std::string *excep_string,
12593 std::string *cond_string)
12595 std::string exception_name;
12597 exception_name = extract_arg (&args);
12598 if (exception_name == "if")
12600 /* This is not an exception name; this is the start of a condition
12601 expression for a catchpoint on all exceptions. So, "un-get"
12602 this token, and set exception_name to NULL. */
12603 exception_name.clear ();
12604 args -= 2;
12607 /* Check to see if we have a condition. */
12609 args = skip_spaces (args);
12610 if (startswith (args, "if")
12611 && (isspace (args[2]) || args[2] == '\0'))
12613 args += 2;
12614 args = skip_spaces (args);
12616 if (args[0] == '\0')
12617 error (_("Condition missing after `if' keyword"));
12618 *cond_string = args;
12620 args += strlen (args);
12623 /* Check that we do not have any more arguments. Anything else
12624 is unexpected. */
12626 if (args[0] != '\0')
12627 error (_("Junk at end of expression"));
12629 if (is_catch_handlers_cmd)
12631 /* Catch handling of exceptions. */
12632 *ex = ada_catch_handlers;
12633 *excep_string = exception_name;
12635 else if (exception_name.empty ())
12637 /* Catch all exceptions. */
12638 *ex = ada_catch_exception;
12639 excep_string->clear ();
12641 else if (exception_name == "unhandled")
12643 /* Catch unhandled exceptions. */
12644 *ex = ada_catch_exception_unhandled;
12645 excep_string->clear ();
12647 else
12649 /* Catch a specific exception. */
12650 *ex = ada_catch_exception;
12651 *excep_string = exception_name;
12655 /* Return the name of the symbol on which we should break in order to
12656 implement a catchpoint of the EX kind. */
12658 static const char *
12659 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12661 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12663 gdb_assert (data->exception_info != NULL);
12665 switch (ex)
12667 case ada_catch_exception:
12668 return (data->exception_info->catch_exception_sym);
12669 break;
12670 case ada_catch_exception_unhandled:
12671 return (data->exception_info->catch_exception_unhandled_sym);
12672 break;
12673 case ada_catch_assert:
12674 return (data->exception_info->catch_assert_sym);
12675 break;
12676 case ada_catch_handlers:
12677 return (data->exception_info->catch_handlers_sym);
12678 break;
12679 default:
12680 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12684 /* Return the condition that will be used to match the current exception
12685 being raised with the exception that the user wants to catch. This
12686 assumes that this condition is used when the inferior just triggered
12687 an exception catchpoint.
12688 EX: the type of catchpoints used for catching Ada exceptions. */
12690 static std::string
12691 ada_exception_catchpoint_cond_string (const char *excep_string,
12692 enum ada_exception_catchpoint_kind ex)
12694 bool is_standard_exc = false;
12695 std::string result;
12697 if (ex == ada_catch_handlers)
12699 /* For exception handlers catchpoints, the condition string does
12700 not use the same parameter as for the other exceptions. */
12701 result = ("long_integer (GNAT_GCC_exception_Access"
12702 "(gcc_exception).all.occurrence.id)");
12704 else
12705 result = "long_integer (e)";
12707 /* The standard exceptions are a special case. They are defined in
12708 runtime units that have been compiled without debugging info; if
12709 EXCEP_STRING is the not-fully-qualified name of a standard
12710 exception (e.g. "constraint_error") then, during the evaluation
12711 of the condition expression, the symbol lookup on this name would
12712 *not* return this standard exception. The catchpoint condition
12713 may then be set only on user-defined exceptions which have the
12714 same not-fully-qualified name (e.g. my_package.constraint_error).
12716 To avoid this unexcepted behavior, these standard exceptions are
12717 systematically prefixed by "standard". This means that "catch
12718 exception constraint_error" is rewritten into "catch exception
12719 standard.constraint_error".
12721 If an exception named constraint_error is defined in another package of
12722 the inferior program, then the only way to specify this exception as a
12723 breakpoint condition is to use its fully-qualified named:
12724 e.g. my_package.constraint_error. */
12726 for (const char *name : standard_exc)
12728 if (strcmp (name, excep_string) == 0)
12730 is_standard_exc = true;
12731 break;
12735 result += " = ";
12737 if (is_standard_exc)
12738 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12739 else
12740 string_appendf (result, "long_integer (&%s)", excep_string);
12742 return result;
12745 /* Return the symtab_and_line that should be used to insert an exception
12746 catchpoint of the TYPE kind.
12748 ADDR_STRING returns the name of the function where the real
12749 breakpoint that implements the catchpoints is set, depending on the
12750 type of catchpoint we need to create. */
12752 static struct symtab_and_line
12753 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12754 std::string *addr_string)
12756 const char *sym_name;
12757 struct symbol *sym;
12759 /* First, find out which exception support info to use. */
12760 ada_exception_support_info_sniffer ();
12762 /* Then lookup the function on which we will break in order to catch
12763 the Ada exceptions requested by the user. */
12764 sym_name = ada_exception_sym_name (ex);
12765 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12767 if (sym == NULL)
12768 error (_("Catchpoint symbol not found: %s"), sym_name);
12770 if (sym->aclass () != LOC_BLOCK)
12771 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12773 /* Set ADDR_STRING. */
12774 *addr_string = sym_name;
12776 return find_function_start_sal (sym, 1);
12779 /* Create an Ada exception catchpoint.
12781 EX_KIND is the kind of exception catchpoint to be created.
12783 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12784 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12785 of the exception to which this catchpoint applies.
12787 COND_STRING, if not empty, is the catchpoint condition.
12789 TEMPFLAG, if nonzero, means that the underlying breakpoint
12790 should be temporary.
12792 FROM_TTY is the usual argument passed to all commands implementations. */
12794 void
12795 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12796 enum ada_exception_catchpoint_kind ex_kind,
12797 const std::string &excep_string,
12798 const std::string &cond_string,
12799 int tempflag,
12800 int disabled,
12801 int from_tty)
12803 std::string addr_string;
12804 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string);
12806 std::unique_ptr<ada_catchpoint> c
12807 (new ada_catchpoint (gdbarch, ex_kind, sal, addr_string.c_str (),
12808 tempflag, disabled, from_tty));
12809 c->excep_string = excep_string;
12810 create_excep_cond_exprs (c.get (), ex_kind);
12811 if (!cond_string.empty ())
12812 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
12813 install_breakpoint (0, std::move (c), 1);
12816 /* Implement the "catch exception" command. */
12818 static void
12819 catch_ada_exception_command (const char *arg_entry, int from_tty,
12820 struct cmd_list_element *command)
12822 const char *arg = arg_entry;
12823 struct gdbarch *gdbarch = get_current_arch ();
12824 int tempflag;
12825 enum ada_exception_catchpoint_kind ex_kind;
12826 std::string excep_string;
12827 std::string cond_string;
12829 tempflag = command->context () == CATCH_TEMPORARY;
12831 if (!arg)
12832 arg = "";
12833 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12834 &cond_string);
12835 create_ada_exception_catchpoint (gdbarch, ex_kind,
12836 excep_string, cond_string,
12837 tempflag, 1 /* enabled */,
12838 from_tty);
12841 /* Implement the "catch handlers" command. */
12843 static void
12844 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12845 struct cmd_list_element *command)
12847 const char *arg = arg_entry;
12848 struct gdbarch *gdbarch = get_current_arch ();
12849 int tempflag;
12850 enum ada_exception_catchpoint_kind ex_kind;
12851 std::string excep_string;
12852 std::string cond_string;
12854 tempflag = command->context () == CATCH_TEMPORARY;
12856 if (!arg)
12857 arg = "";
12858 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12859 &cond_string);
12860 create_ada_exception_catchpoint (gdbarch, ex_kind,
12861 excep_string, cond_string,
12862 tempflag, 1 /* enabled */,
12863 from_tty);
12866 /* Completion function for the Ada "catch" commands. */
12868 static void
12869 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12870 const char *text, const char *word)
12872 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12874 for (const ada_exc_info &info : exceptions)
12876 if (startswith (info.name, word))
12877 tracker.add_completion (make_unique_xstrdup (info.name));
12881 /* Split the arguments specified in a "catch assert" command.
12883 ARGS contains the command's arguments (or the empty string if
12884 no arguments were passed).
12886 If ARGS contains a condition, set COND_STRING to that condition
12887 (the memory needs to be deallocated after use). */
12889 static void
12890 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12892 args = skip_spaces (args);
12894 /* Check whether a condition was provided. */
12895 if (startswith (args, "if")
12896 && (isspace (args[2]) || args[2] == '\0'))
12898 args += 2;
12899 args = skip_spaces (args);
12900 if (args[0] == '\0')
12901 error (_("condition missing after `if' keyword"));
12902 cond_string.assign (args);
12905 /* Otherwise, there should be no other argument at the end of
12906 the command. */
12907 else if (args[0] != '\0')
12908 error (_("Junk at end of arguments."));
12911 /* Implement the "catch assert" command. */
12913 static void
12914 catch_assert_command (const char *arg_entry, int from_tty,
12915 struct cmd_list_element *command)
12917 const char *arg = arg_entry;
12918 struct gdbarch *gdbarch = get_current_arch ();
12919 int tempflag;
12920 std::string cond_string;
12922 tempflag = command->context () == CATCH_TEMPORARY;
12924 if (!arg)
12925 arg = "";
12926 catch_ada_assert_command_split (arg, cond_string);
12927 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12928 "", cond_string,
12929 tempflag, 1 /* enabled */,
12930 from_tty);
12933 /* Return non-zero if the symbol SYM is an Ada exception object. */
12935 static int
12936 ada_is_exception_sym (struct symbol *sym)
12938 const char *type_name = sym->type ()->name ();
12940 return (sym->aclass () != LOC_TYPEDEF
12941 && sym->aclass () != LOC_BLOCK
12942 && sym->aclass () != LOC_CONST
12943 && sym->aclass () != LOC_UNRESOLVED
12944 && type_name != NULL && strcmp (type_name, "exception") == 0);
12947 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12948 Ada exception object. This matches all exceptions except the ones
12949 defined by the Ada language. */
12951 static int
12952 ada_is_non_standard_exception_sym (struct symbol *sym)
12954 if (!ada_is_exception_sym (sym))
12955 return 0;
12957 for (const char *name : standard_exc)
12958 if (strcmp (sym->linkage_name (), name) == 0)
12959 return 0; /* A standard exception. */
12961 /* Numeric_Error is also a standard exception, so exclude it.
12962 See the STANDARD_EXC description for more details as to why
12963 this exception is not listed in that array. */
12964 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12965 return 0;
12967 return 1;
12970 /* A helper function for std::sort, comparing two struct ada_exc_info
12971 objects.
12973 The comparison is determined first by exception name, and then
12974 by exception address. */
12976 bool
12977 ada_exc_info::operator< (const ada_exc_info &other) const
12979 int result;
12981 result = strcmp (name, other.name);
12982 if (result < 0)
12983 return true;
12984 if (result == 0 && addr < other.addr)
12985 return true;
12986 return false;
12989 bool
12990 ada_exc_info::operator== (const ada_exc_info &other) const
12992 return addr == other.addr && strcmp (name, other.name) == 0;
12995 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12996 routine, but keeping the first SKIP elements untouched.
12998 All duplicates are also removed. */
13000 static void
13001 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13002 int skip)
13004 std::sort (exceptions->begin () + skip, exceptions->end ());
13005 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13006 exceptions->end ());
13009 /* Add all exceptions defined by the Ada standard whose name match
13010 a regular expression.
13012 If PREG is not NULL, then this regexp_t object is used to
13013 perform the symbol name matching. Otherwise, no name-based
13014 filtering is performed.
13016 EXCEPTIONS is a vector of exceptions to which matching exceptions
13017 gets pushed. */
13019 static void
13020 ada_add_standard_exceptions (compiled_regex *preg,
13021 std::vector<ada_exc_info> *exceptions)
13023 for (const char *name : standard_exc)
13025 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
13027 symbol_name_match_type match_type = name_match_type_from_name (name);
13028 lookup_name_info lookup_name (name, match_type);
13030 symbol_name_matcher_ftype *match_name
13031 = ada_get_symbol_name_matcher (lookup_name);
13033 /* Iterate over all objfiles irrespective of scope or linker
13034 namespaces so we get all exceptions anywhere in the
13035 progspace. */
13036 for (objfile *objfile : current_program_space->objfiles ())
13038 for (minimal_symbol *msymbol : objfile->msymbols ())
13040 if (match_name (msymbol->linkage_name (), lookup_name,
13041 nullptr)
13042 && msymbol->type () != mst_solib_trampoline)
13044 ada_exc_info info
13045 = {name, msymbol->value_address (objfile)};
13047 exceptions->push_back (info);
13055 /* Add all Ada exceptions defined locally and accessible from the given
13056 FRAME.
13058 If PREG is not NULL, then this regexp_t object is used to
13059 perform the symbol name matching. Otherwise, no name-based
13060 filtering is performed.
13062 EXCEPTIONS is a vector of exceptions to which matching exceptions
13063 gets pushed. */
13065 static void
13066 ada_add_exceptions_from_frame (compiled_regex *preg,
13067 frame_info_ptr frame,
13068 std::vector<ada_exc_info> *exceptions)
13070 const struct block *block = get_frame_block (frame, 0);
13072 while (block != 0)
13074 struct block_iterator iter;
13075 struct symbol *sym;
13077 ALL_BLOCK_SYMBOLS (block, iter, sym)
13079 switch (sym->aclass ())
13081 case LOC_TYPEDEF:
13082 case LOC_BLOCK:
13083 case LOC_CONST:
13084 break;
13085 default:
13086 if (ada_is_exception_sym (sym))
13088 struct ada_exc_info info = {sym->print_name (),
13089 sym->value_address ()};
13091 exceptions->push_back (info);
13095 if (block->function () != NULL)
13096 break;
13097 block = block->superblock ();
13101 /* Return true if NAME matches PREG or if PREG is NULL. */
13103 static bool
13104 name_matches_regex (const char *name, compiled_regex *preg)
13106 return (preg == NULL
13107 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13110 /* Add all exceptions defined globally whose name name match
13111 a regular expression, excluding standard exceptions.
13113 The reason we exclude standard exceptions is that they need
13114 to be handled separately: Standard exceptions are defined inside
13115 a runtime unit which is normally not compiled with debugging info,
13116 and thus usually do not show up in our symbol search. However,
13117 if the unit was in fact built with debugging info, we need to
13118 exclude them because they would duplicate the entry we found
13119 during the special loop that specifically searches for those
13120 standard exceptions.
13122 If PREG is not NULL, then this regexp_t object is used to
13123 perform the symbol name matching. Otherwise, no name-based
13124 filtering is performed.
13126 EXCEPTIONS is a vector of exceptions to which matching exceptions
13127 gets pushed. */
13129 static void
13130 ada_add_global_exceptions (compiled_regex *preg,
13131 std::vector<ada_exc_info> *exceptions)
13133 /* In Ada, the symbol "search name" is a linkage name, whereas the
13134 regular expression used to do the matching refers to the natural
13135 name. So match against the decoded name. */
13136 expand_symtabs_matching (NULL,
13137 lookup_name_info::match_any (),
13138 [&] (const char *search_name)
13140 std::string decoded = ada_decode (search_name);
13141 return name_matches_regex (decoded.c_str (), preg);
13143 NULL,
13144 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13145 VARIABLES_DOMAIN);
13147 /* Iterate over all objfiles irrespective of scope or linker namespaces
13148 so we get all exceptions anywhere in the progspace. */
13149 for (objfile *objfile : current_program_space->objfiles ())
13151 for (compunit_symtab *s : objfile->compunits ())
13153 const struct blockvector *bv = s->blockvector ();
13154 int i;
13156 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13158 const struct block *b = bv->block (i);
13159 struct block_iterator iter;
13160 struct symbol *sym;
13162 ALL_BLOCK_SYMBOLS (b, iter, sym)
13163 if (ada_is_non_standard_exception_sym (sym)
13164 && name_matches_regex (sym->natural_name (), preg))
13166 struct ada_exc_info info
13167 = {sym->print_name (), sym->value_address ()};
13169 exceptions->push_back (info);
13176 /* Implements ada_exceptions_list with the regular expression passed
13177 as a regex_t, rather than a string.
13179 If not NULL, PREG is used to filter out exceptions whose names
13180 do not match. Otherwise, all exceptions are listed. */
13182 static std::vector<ada_exc_info>
13183 ada_exceptions_list_1 (compiled_regex *preg)
13185 std::vector<ada_exc_info> result;
13186 int prev_len;
13188 /* First, list the known standard exceptions. These exceptions
13189 need to be handled separately, as they are usually defined in
13190 runtime units that have been compiled without debugging info. */
13192 ada_add_standard_exceptions (preg, &result);
13194 /* Next, find all exceptions whose scope is local and accessible
13195 from the currently selected frame. */
13197 if (has_stack_frames ())
13199 prev_len = result.size ();
13200 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13201 &result);
13202 if (result.size () > prev_len)
13203 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13206 /* Add all exceptions whose scope is global. */
13208 prev_len = result.size ();
13209 ada_add_global_exceptions (preg, &result);
13210 if (result.size () > prev_len)
13211 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13213 return result;
13216 /* Return a vector of ada_exc_info.
13218 If REGEXP is NULL, all exceptions are included in the result.
13219 Otherwise, it should contain a valid regular expression,
13220 and only the exceptions whose names match that regular expression
13221 are included in the result.
13223 The exceptions are sorted in the following order:
13224 - Standard exceptions (defined by the Ada language), in
13225 alphabetical order;
13226 - Exceptions only visible from the current frame, in
13227 alphabetical order;
13228 - Exceptions whose scope is global, in alphabetical order. */
13230 std::vector<ada_exc_info>
13231 ada_exceptions_list (const char *regexp)
13233 if (regexp == NULL)
13234 return ada_exceptions_list_1 (NULL);
13236 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13237 return ada_exceptions_list_1 (&reg);
13240 /* Implement the "info exceptions" command. */
13242 static void
13243 info_exceptions_command (const char *regexp, int from_tty)
13245 struct gdbarch *gdbarch = get_current_arch ();
13247 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13249 if (regexp != NULL)
13250 gdb_printf
13251 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13252 else
13253 gdb_printf (_("All defined Ada exceptions:\n"));
13255 for (const ada_exc_info &info : exceptions)
13256 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13260 /* Language vector */
13262 /* symbol_name_matcher_ftype adapter for wild_match. */
13264 static bool
13265 do_wild_match (const char *symbol_search_name,
13266 const lookup_name_info &lookup_name,
13267 completion_match_result *comp_match_res)
13269 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13272 /* symbol_name_matcher_ftype adapter for full_match. */
13274 static bool
13275 do_full_match (const char *symbol_search_name,
13276 const lookup_name_info &lookup_name,
13277 completion_match_result *comp_match_res)
13279 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13281 /* If both symbols start with "_ada_", just let the loop below
13282 handle the comparison. However, if only the symbol name starts
13283 with "_ada_", skip the prefix and let the match proceed as
13284 usual. */
13285 if (startswith (symbol_search_name, "_ada_")
13286 && !startswith (lname, "_ada"))
13287 symbol_search_name += 5;
13288 /* Likewise for ghost entities. */
13289 if (startswith (symbol_search_name, "___ghost_")
13290 && !startswith (lname, "___ghost_"))
13291 symbol_search_name += 9;
13293 int uscore_count = 0;
13294 while (*lname != '\0')
13296 if (*symbol_search_name != *lname)
13298 if (*symbol_search_name == 'B' && uscore_count == 2
13299 && symbol_search_name[1] == '_')
13301 symbol_search_name += 2;
13302 while (isdigit (*symbol_search_name))
13303 ++symbol_search_name;
13304 if (symbol_search_name[0] == '_'
13305 && symbol_search_name[1] == '_')
13307 symbol_search_name += 2;
13308 continue;
13311 return false;
13314 if (*symbol_search_name == '_')
13315 ++uscore_count;
13316 else
13317 uscore_count = 0;
13319 ++symbol_search_name;
13320 ++lname;
13323 return is_name_suffix (symbol_search_name);
13326 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13328 static bool
13329 do_exact_match (const char *symbol_search_name,
13330 const lookup_name_info &lookup_name,
13331 completion_match_result *comp_match_res)
13333 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13336 /* Build the Ada lookup name for LOOKUP_NAME. */
13338 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13340 gdb::string_view user_name = lookup_name.name ();
13342 if (!user_name.empty () && user_name[0] == '<')
13344 if (user_name.back () == '>')
13345 m_encoded_name
13346 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
13347 else
13348 m_encoded_name
13349 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
13350 m_encoded_p = true;
13351 m_verbatim_p = true;
13352 m_wild_match_p = false;
13353 m_standard_p = false;
13355 else
13357 m_verbatim_p = false;
13359 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
13361 if (!m_encoded_p)
13363 const char *folded = ada_fold_name (user_name);
13364 m_encoded_name = ada_encode_1 (folded, false);
13365 if (m_encoded_name.empty ())
13366 m_encoded_name = gdb::to_string (user_name);
13368 else
13369 m_encoded_name = gdb::to_string (user_name);
13371 /* Handle the 'package Standard' special case. See description
13372 of m_standard_p. */
13373 if (startswith (m_encoded_name.c_str (), "standard__"))
13375 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13376 m_standard_p = true;
13378 else
13379 m_standard_p = false;
13381 /* If the name contains a ".", then the user is entering a fully
13382 qualified entity name, and the match must not be done in wild
13383 mode. Similarly, if the user wants to complete what looks
13384 like an encoded name, the match must not be done in wild
13385 mode. Also, in the standard__ special case always do
13386 non-wild matching. */
13387 m_wild_match_p
13388 = (lookup_name.match_type () != symbol_name_match_type::FULL
13389 && !m_encoded_p
13390 && !m_standard_p
13391 && user_name.find ('.') == std::string::npos);
13395 /* symbol_name_matcher_ftype method for Ada. This only handles
13396 completion mode. */
13398 static bool
13399 ada_symbol_name_matches (const char *symbol_search_name,
13400 const lookup_name_info &lookup_name,
13401 completion_match_result *comp_match_res)
13403 return lookup_name.ada ().matches (symbol_search_name,
13404 lookup_name.match_type (),
13405 comp_match_res);
13408 /* A name matcher that matches the symbol name exactly, with
13409 strcmp. */
13411 static bool
13412 literal_symbol_name_matcher (const char *symbol_search_name,
13413 const lookup_name_info &lookup_name,
13414 completion_match_result *comp_match_res)
13416 gdb::string_view name_view = lookup_name.name ();
13418 if (lookup_name.completion_mode ()
13419 ? (strncmp (symbol_search_name, name_view.data (),
13420 name_view.size ()) == 0)
13421 : symbol_search_name == name_view)
13423 if (comp_match_res != NULL)
13424 comp_match_res->set_match (symbol_search_name);
13425 return true;
13427 else
13428 return false;
13431 /* Implement the "get_symbol_name_matcher" language_defn method for
13432 Ada. */
13434 static symbol_name_matcher_ftype *
13435 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13437 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13438 return literal_symbol_name_matcher;
13440 if (lookup_name.completion_mode ())
13441 return ada_symbol_name_matches;
13442 else
13444 if (lookup_name.ada ().wild_match_p ())
13445 return do_wild_match;
13446 else if (lookup_name.ada ().verbatim_p ())
13447 return do_exact_match;
13448 else
13449 return do_full_match;
13453 /* Class representing the Ada language. */
13455 class ada_language : public language_defn
13457 public:
13458 ada_language ()
13459 : language_defn (language_ada)
13460 { /* Nothing. */ }
13462 /* See language.h. */
13464 const char *name () const override
13465 { return "ada"; }
13467 /* See language.h. */
13469 const char *natural_name () const override
13470 { return "Ada"; }
13472 /* See language.h. */
13474 const std::vector<const char *> &filename_extensions () const override
13476 static const std::vector<const char *> extensions
13477 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13478 return extensions;
13481 /* Print an array element index using the Ada syntax. */
13483 void print_array_index (struct type *index_type,
13484 LONGEST index,
13485 struct ui_file *stream,
13486 const value_print_options *options) const override
13488 struct value *index_value = val_atr (index_type, index);
13490 value_print (index_value, stream, options);
13491 gdb_printf (stream, " => ");
13494 /* Implement the "read_var_value" language_defn method for Ada. */
13496 struct value *read_var_value (struct symbol *var,
13497 const struct block *var_block,
13498 frame_info_ptr frame) const override
13500 /* The only case where default_read_var_value is not sufficient
13501 is when VAR is a renaming... */
13502 if (frame != nullptr)
13504 const struct block *frame_block = get_frame_block (frame, NULL);
13505 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13506 return ada_read_renaming_var_value (var, frame_block);
13509 /* This is a typical case where we expect the default_read_var_value
13510 function to work. */
13511 return language_defn::read_var_value (var, var_block, frame);
13514 /* See language.h. */
13515 bool symbol_printing_suppressed (struct symbol *symbol) const override
13517 return symbol->is_artificial ();
13520 /* See language.h. */
13521 void language_arch_info (struct gdbarch *gdbarch,
13522 struct language_arch_info *lai) const override
13524 const struct builtin_type *builtin = builtin_type (gdbarch);
13526 /* Helper function to allow shorter lines below. */
13527 auto add = [&] (struct type *t)
13529 lai->add_primitive_type (t);
13532 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13533 0, "integer"));
13534 add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
13535 0, "long_integer"));
13536 add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
13537 0, "short_integer"));
13538 struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
13539 1, "character");
13540 lai->set_string_char_type (char_type);
13541 add (char_type);
13542 add (arch_character_type (gdbarch, 16, 1, "wide_character"));
13543 add (arch_character_type (gdbarch, 32, 1, "wide_wide_character"));
13544 add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
13545 "float", gdbarch_float_format (gdbarch)));
13546 add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
13547 "long_float", gdbarch_double_format (gdbarch)));
13548 add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
13549 0, "long_long_integer"));
13550 add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
13551 "long_long_float",
13552 gdbarch_long_double_format (gdbarch)));
13553 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13554 0, "natural"));
13555 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13556 0, "positive"));
13557 add (builtin->builtin_void);
13559 struct type *system_addr_ptr
13560 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
13561 "void"));
13562 system_addr_ptr->set_name ("system__address");
13563 add (system_addr_ptr);
13565 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13566 type. This is a signed integral type whose size is the same as
13567 the size of addresses. */
13568 unsigned int addr_length = system_addr_ptr->length ();
13569 add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
13570 "storage_offset"));
13572 lai->set_bool_type (builtin->builtin_bool);
13575 /* See language.h. */
13577 bool iterate_over_symbols
13578 (const struct block *block, const lookup_name_info &name,
13579 domain_enum domain,
13580 gdb::function_view<symbol_found_callback_ftype> callback) const override
13582 std::vector<struct block_symbol> results
13583 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13584 for (block_symbol &sym : results)
13586 if (!callback (&sym))
13587 return false;
13590 return true;
13593 /* See language.h. */
13594 bool sniff_from_mangled_name
13595 (const char *mangled,
13596 gdb::unique_xmalloc_ptr<char> *out) const override
13598 std::string demangled = ada_decode (mangled);
13600 *out = NULL;
13602 if (demangled != mangled && demangled[0] != '<')
13604 /* Set the gsymbol language to Ada, but still return 0.
13605 Two reasons for that:
13607 1. For Ada, we prefer computing the symbol's decoded name
13608 on the fly rather than pre-compute it, in order to save
13609 memory (Ada projects are typically very large).
13611 2. There are some areas in the definition of the GNAT
13612 encoding where, with a bit of bad luck, we might be able
13613 to decode a non-Ada symbol, generating an incorrect
13614 demangled name (Eg: names ending with "TB" for instance
13615 are identified as task bodies and so stripped from
13616 the decoded name returned).
13618 Returning true, here, but not setting *DEMANGLED, helps us get
13619 a little bit of the best of both worlds. Because we're last,
13620 we should not affect any of the other languages that were
13621 able to demangle the symbol before us; we get to correctly
13622 tag Ada symbols as such; and even if we incorrectly tagged a
13623 non-Ada symbol, which should be rare, any routing through the
13624 Ada language should be transparent (Ada tries to behave much
13625 like C/C++ with non-Ada symbols). */
13626 return true;
13629 return false;
13632 /* See language.h. */
13634 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13635 int options) const override
13637 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13640 /* See language.h. */
13642 void print_type (struct type *type, const char *varstring,
13643 struct ui_file *stream, int show, int level,
13644 const struct type_print_options *flags) const override
13646 ada_print_type (type, varstring, stream, show, level, flags);
13649 /* See language.h. */
13651 const char *word_break_characters (void) const override
13653 return ada_completer_word_break_characters;
13656 /* See language.h. */
13658 void collect_symbol_completion_matches (completion_tracker &tracker,
13659 complete_symbol_mode mode,
13660 symbol_name_match_type name_match_type,
13661 const char *text, const char *word,
13662 enum type_code code) const override
13664 struct symbol *sym;
13665 const struct block *b, *surrounding_static_block = 0;
13666 struct block_iterator iter;
13668 gdb_assert (code == TYPE_CODE_UNDEF);
13670 lookup_name_info lookup_name (text, name_match_type, true);
13672 /* First, look at the partial symtab symbols. */
13673 expand_symtabs_matching (NULL,
13674 lookup_name,
13675 NULL,
13676 NULL,
13677 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13678 ALL_DOMAIN);
13680 /* At this point scan through the misc symbol vectors and add each
13681 symbol you find to the list. Eventually we want to ignore
13682 anything that isn't a text symbol (everything else will be
13683 handled by the psymtab code above). */
13685 for (objfile *objfile : current_program_space->objfiles ())
13687 for (minimal_symbol *msymbol : objfile->msymbols ())
13689 QUIT;
13691 if (completion_skip_symbol (mode, msymbol))
13692 continue;
13694 language symbol_language = msymbol->language ();
13696 /* Ada minimal symbols won't have their language set to Ada. If
13697 we let completion_list_add_name compare using the
13698 default/C-like matcher, then when completing e.g., symbols in a
13699 package named "pck", we'd match internal Ada symbols like
13700 "pckS", which are invalid in an Ada expression, unless you wrap
13701 them in '<' '>' to request a verbatim match.
13703 Unfortunately, some Ada encoded names successfully demangle as
13704 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13705 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13706 with the wrong language set. Paper over that issue here. */
13707 if (symbol_language == language_auto
13708 || symbol_language == language_cplus)
13709 symbol_language = language_ada;
13711 completion_list_add_name (tracker,
13712 symbol_language,
13713 msymbol->linkage_name (),
13714 lookup_name, text, word);
13718 /* Search upwards from currently selected frame (so that we can
13719 complete on local vars. */
13721 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13723 if (!b->superblock ())
13724 surrounding_static_block = b; /* For elmin of dups */
13726 ALL_BLOCK_SYMBOLS (b, iter, sym)
13728 if (completion_skip_symbol (mode, sym))
13729 continue;
13731 completion_list_add_name (tracker,
13732 sym->language (),
13733 sym->linkage_name (),
13734 lookup_name, text, word);
13738 /* Go through the symtabs and check the externs and statics for
13739 symbols which match. */
13741 for (objfile *objfile : current_program_space->objfiles ())
13743 for (compunit_symtab *s : objfile->compunits ())
13745 QUIT;
13746 b = s->blockvector ()->global_block ();
13747 ALL_BLOCK_SYMBOLS (b, iter, sym)
13749 if (completion_skip_symbol (mode, sym))
13750 continue;
13752 completion_list_add_name (tracker,
13753 sym->language (),
13754 sym->linkage_name (),
13755 lookup_name, text, word);
13760 for (objfile *objfile : current_program_space->objfiles ())
13762 for (compunit_symtab *s : objfile->compunits ())
13764 QUIT;
13765 b = s->blockvector ()->static_block ();
13766 /* Don't do this block twice. */
13767 if (b == surrounding_static_block)
13768 continue;
13769 ALL_BLOCK_SYMBOLS (b, iter, sym)
13771 if (completion_skip_symbol (mode, sym))
13772 continue;
13774 completion_list_add_name (tracker,
13775 sym->language (),
13776 sym->linkage_name (),
13777 lookup_name, text, word);
13783 /* See language.h. */
13785 gdb::unique_xmalloc_ptr<char> watch_location_expression
13786 (struct type *type, CORE_ADDR addr) const override
13788 type = check_typedef (check_typedef (type)->target_type ());
13789 std::string name = type_to_string (type);
13790 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13793 /* See language.h. */
13795 void value_print (struct value *val, struct ui_file *stream,
13796 const struct value_print_options *options) const override
13798 return ada_value_print (val, stream, options);
13801 /* See language.h. */
13803 void value_print_inner
13804 (struct value *val, struct ui_file *stream, int recurse,
13805 const struct value_print_options *options) const override
13807 return ada_value_print_inner (val, stream, recurse, options);
13810 /* See language.h. */
13812 struct block_symbol lookup_symbol_nonlocal
13813 (const char *name, const struct block *block,
13814 const domain_enum domain) const override
13816 struct block_symbol sym;
13818 sym = ada_lookup_symbol (name, block_static_block (block), domain);
13819 if (sym.symbol != NULL)
13820 return sym;
13822 /* If we haven't found a match at this point, try the primitive
13823 types. In other languages, this search is performed before
13824 searching for global symbols in order to short-circuit that
13825 global-symbol search if it happens that the name corresponds
13826 to a primitive type. But we cannot do the same in Ada, because
13827 it is perfectly legitimate for a program to declare a type which
13828 has the same name as a standard type. If looking up a type in
13829 that situation, we have traditionally ignored the primitive type
13830 in favor of user-defined types. This is why, unlike most other
13831 languages, we search the primitive types this late and only after
13832 having searched the global symbols without success. */
13834 if (domain == VAR_DOMAIN)
13836 struct gdbarch *gdbarch;
13838 if (block == NULL)
13839 gdbarch = target_gdbarch ();
13840 else
13841 gdbarch = block_gdbarch (block);
13842 sym.symbol
13843 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13844 if (sym.symbol != NULL)
13845 return sym;
13848 return {};
13851 /* See language.h. */
13853 int parser (struct parser_state *ps) const override
13855 warnings_issued = 0;
13856 return ada_parse (ps);
13859 /* See language.h. */
13861 void emitchar (int ch, struct type *chtype,
13862 struct ui_file *stream, int quoter) const override
13864 ada_emit_char (ch, chtype, stream, quoter, 1);
13867 /* See language.h. */
13869 void printchar (int ch, struct type *chtype,
13870 struct ui_file *stream) const override
13872 ada_printchar (ch, chtype, stream);
13875 /* See language.h. */
13877 void printstr (struct ui_file *stream, struct type *elttype,
13878 const gdb_byte *string, unsigned int length,
13879 const char *encoding, int force_ellipses,
13880 const struct value_print_options *options) const override
13882 ada_printstr (stream, elttype, string, length, encoding,
13883 force_ellipses, options);
13886 /* See language.h. */
13888 void print_typedef (struct type *type, struct symbol *new_symbol,
13889 struct ui_file *stream) const override
13891 ada_print_typedef (type, new_symbol, stream);
13894 /* See language.h. */
13896 bool is_string_type_p (struct type *type) const override
13898 return ada_is_string_type (type);
13901 /* See language.h. */
13903 const char *struct_too_deep_ellipsis () const override
13904 { return "(...)"; }
13906 /* See language.h. */
13908 bool c_style_arrays_p () const override
13909 { return false; }
13911 /* See language.h. */
13913 bool store_sym_names_in_linkage_form_p () const override
13914 { return true; }
13916 /* See language.h. */
13918 const struct lang_varobj_ops *varobj_ops () const override
13919 { return &ada_varobj_ops; }
13921 protected:
13922 /* See language.h. */
13924 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13925 (const lookup_name_info &lookup_name) const override
13927 return ada_get_symbol_name_matcher (lookup_name);
13931 /* Single instance of the Ada language class. */
13933 static ada_language ada_language_defn;
13935 /* Command-list for the "set/show ada" prefix command. */
13936 static struct cmd_list_element *set_ada_list;
13937 static struct cmd_list_element *show_ada_list;
13939 /* This module's 'new_objfile' observer. */
13941 static void
13942 ada_new_objfile_observer (struct objfile *objfile)
13944 ada_clear_symbol_cache ();
13947 /* This module's 'free_objfile' observer. */
13949 static void
13950 ada_free_objfile_observer (struct objfile *objfile)
13952 ada_clear_symbol_cache ();
13955 /* Charsets known to GNAT. */
13956 static const char * const gnat_source_charsets[] =
13958 /* Note that code below assumes that the default comes first.
13959 Latin-1 is the default here, because that is also GNAT's
13960 default. */
13961 "ISO-8859-1",
13962 "ISO-8859-2",
13963 "ISO-8859-3",
13964 "ISO-8859-4",
13965 "ISO-8859-5",
13966 "ISO-8859-15",
13967 "CP437",
13968 "CP850",
13969 /* Note that this value is special-cased in the encoder and
13970 decoder. */
13971 ada_utf8,
13972 nullptr
13975 void _initialize_ada_language ();
13976 void
13977 _initialize_ada_language ()
13979 add_setshow_prefix_cmd
13980 ("ada", no_class,
13981 _("Prefix command for changing Ada-specific settings."),
13982 _("Generic command for showing Ada-specific settings."),
13983 &set_ada_list, &show_ada_list,
13984 &setlist, &showlist);
13986 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13987 &trust_pad_over_xvs, _("\
13988 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13989 Show whether an optimization trusting PAD types over XVS types is activated."),
13990 _("\
13991 This is related to the encoding used by the GNAT compiler. The debugger\n\
13992 should normally trust the contents of PAD types, but certain older versions\n\
13993 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13994 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13995 work around this bug. It is always safe to turn this option \"off\", but\n\
13996 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13997 this option to \"off\" unless necessary."),
13998 NULL, NULL, &set_ada_list, &show_ada_list);
14000 add_setshow_boolean_cmd ("print-signatures", class_vars,
14001 &print_signatures, _("\
14002 Enable or disable the output of formal and return types for functions in the \
14003 overloads selection menu."), _("\
14004 Show whether the output of formal and return types for functions in the \
14005 overloads selection menu is activated."),
14006 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
14008 ada_source_charset = gnat_source_charsets[0];
14009 add_setshow_enum_cmd ("source-charset", class_files,
14010 gnat_source_charsets,
14011 &ada_source_charset, _("\
14012 Set the Ada source character set."), _("\
14013 Show the Ada source character set."), _("\
14014 The character set used for Ada source files.\n\
14015 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
14016 nullptr, nullptr,
14017 &set_ada_list, &show_ada_list);
14019 add_catch_command ("exception", _("\
14020 Catch Ada exceptions, when raised.\n\
14021 Usage: catch exception [ARG] [if CONDITION]\n\
14022 Without any argument, stop when any Ada exception is raised.\n\
14023 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14024 being raised does not have a handler (and will therefore lead to the task's\n\
14025 termination).\n\
14026 Otherwise, the catchpoint only stops when the name of the exception being\n\
14027 raised is the same as ARG.\n\
14028 CONDITION is a boolean expression that is evaluated to see whether the\n\
14029 exception should cause a stop."),
14030 catch_ada_exception_command,
14031 catch_ada_completer,
14032 CATCH_PERMANENT,
14033 CATCH_TEMPORARY);
14035 add_catch_command ("handlers", _("\
14036 Catch Ada exceptions, when handled.\n\
14037 Usage: catch handlers [ARG] [if CONDITION]\n\
14038 Without any argument, stop when any Ada exception is handled.\n\
14039 With an argument, catch only exceptions with the given name.\n\
14040 CONDITION is a boolean expression that is evaluated to see whether the\n\
14041 exception should cause a stop."),
14042 catch_ada_handlers_command,
14043 catch_ada_completer,
14044 CATCH_PERMANENT,
14045 CATCH_TEMPORARY);
14046 add_catch_command ("assert", _("\
14047 Catch failed Ada assertions, when raised.\n\
14048 Usage: catch assert [if CONDITION]\n\
14049 CONDITION is a boolean expression that is evaluated to see whether the\n\
14050 exception should cause a stop."),
14051 catch_assert_command,
14052 NULL,
14053 CATCH_PERMANENT,
14054 CATCH_TEMPORARY);
14056 add_info ("exceptions", info_exceptions_command,
14057 _("\
14058 List all Ada exception names.\n\
14059 Usage: info exceptions [REGEXP]\n\
14060 If a regular expression is passed as an argument, only those matching\n\
14061 the regular expression are listed."));
14063 add_setshow_prefix_cmd ("ada", class_maintenance,
14064 _("Set Ada maintenance-related variables."),
14065 _("Show Ada maintenance-related variables."),
14066 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14067 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14069 add_setshow_boolean_cmd
14070 ("ignore-descriptive-types", class_maintenance,
14071 &ada_ignore_descriptive_types_p,
14072 _("Set whether descriptive types generated by GNAT should be ignored."),
14073 _("Show whether descriptive types generated by GNAT should be ignored."),
14074 _("\
14075 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14076 DWARF attribute."),
14077 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14079 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14080 htab_eq_string,
14081 NULL, xcalloc, xfree);
14083 /* The ada-lang observers. */
14084 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14085 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14086 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");