1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20
21 #include <ctype.h>
22 #include "event-top.h"
23 #include "extract-store-integer.h"
24 #include "gdbsupport/gdb_regex.h"
25 #include "frame.h"
26 #include "symtab.h"
27 #include "gdbtypes.h"
28 #include "cli/cli-cmds.h"
29 #include "expression.h"
30 #include "parser-defs.h"
31 #include "language.h"
32 #include "varobj.h"
33 #include "inferior.h"
34 #include "symfile.h"
35 #include "objfiles.h"
36 #include "breakpoint.h"
37 #include "gdbcore.h"
38 #include "hashtab.h"
39 #include "gdbsupport/gdb_obstack.h"
40 #include "ada-lang.h"
41 #include "completer.h"
42 #include "ui-out.h"
43 #include "block.h"
44 #include "infcall.h"
45 #include "annotate.h"
46 #include "valprint.h"
47 #include "source.h"
48 #include "observable.h"
49 #include "stack.h"
50 #include "typeprint.h"
51 #include "namespace.h"
52 #include "cli/cli-style.h"
53 #include "cli/cli-decode.h"
54
55 #include "value.h"
56 #include "mi/mi-common.h"
57 #include "arch-utils.h"
58 #include "cli/cli-utils.h"
59 #include "gdbsupport/function-view.h"
60 #include "gdbsupport/byte-vector.h"
61 #include "gdbsupport/selftest.h"
62 #include <algorithm>
63 #include "ada-exp.h"
64 #include "charset.h"
65 #include "ax-gdb.h"
66
67 static struct type *desc_base_type (struct type *);
68
69 static struct type *desc_bounds_type (struct type *);
70
71 static struct value *desc_bounds (struct value *);
72
73 static int fat_pntr_bounds_bitpos (struct type *);
74
75 static int fat_pntr_bounds_bitsize (struct type *);
76
77 static struct type *desc_data_target_type (struct type *);
78
79 static struct value *desc_data (struct value *);
80
81 static int fat_pntr_data_bitpos (struct type *);
82
83 static int fat_pntr_data_bitsize (struct type *);
84
85 static struct value *desc_one_bound (struct value *, int, int);
86
87 static int desc_bound_bitpos (struct type *, int, int);
88
89 static int desc_bound_bitsize (struct type *, int, int);
90
91 static struct type *desc_index_type (struct type *, int);
92
93 static int desc_arity (struct type *);
94
95 static int ada_args_match (struct symbol *, struct value **, int);
96
97 static struct value *make_array_descriptor (struct type *, struct value *);
98
99 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
100 const struct block *,
101 const lookup_name_info &lookup_name,
102 domain_search_flags, struct objfile *);
103
104 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
106 const lookup_name_info &lookup_name,
107 domain_search_flags, int, int *);
108
109 static int is_nonfunction (const std::vector<struct block_symbol> &);
110
111 static void add_defn_to_vec (std::vector<struct block_symbol> &,
112 struct symbol *,
113 const struct block *);
114
115 static int possible_user_operator_p (enum exp_opcode, struct value **);
116
117 static const char *ada_decoded_op_name (enum exp_opcode);
118
119 static int numeric_type_p (struct type *);
120
121 static int integer_type_p (struct type *);
122
123 static int scalar_type_p (struct type *);
124
125 static int discrete_type_p (struct type *);
126
127 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
128 int, int);
129
130 static struct type *ada_find_parallel_type_with_name (struct type *,
131 const char *);
132
133 static int is_dynamic_field (struct type *, int);
134
135 static struct type *to_fixed_variant_branch_type (struct type *,
136 const gdb_byte *,
137 CORE_ADDR, struct value *);
138
139 static struct type *to_fixed_array_type (struct type *, struct value *, int);
140
141 static struct type *to_fixed_range_type (struct type *, struct value *);
142
143 static struct type *to_static_fixed_type (struct type *);
144 static struct type *static_unwrap_type (struct type *type);
145
146 static struct value *unwrap_value (struct value *);
147
148 static struct type *constrained_packed_array_type (struct type *, long *);
149
150 static struct type *decode_constrained_packed_array_type (struct type *);
151
152 static long decode_packed_array_bitsize (struct type *);
153
154 static struct value *decode_constrained_packed_array (struct value *);
155
156 static int ada_is_unconstrained_packed_array_type (struct type *);
157
158 static struct value *value_subscript_packed (struct value *, int,
159 struct value **);
160
161 static struct value *coerce_unspec_val_to_type (struct value *,
162 struct type *);
163
164 static int lesseq_defined_than (struct symbol *, struct symbol *);
165
166 static int equiv_types (struct type *, struct type *);
167
168 static int is_name_suffix (const char *);
169
170 static int advance_wild_match (const char **, const char *, char);
171
172 static bool wild_match (const char *name, const char *patn);
173
174 static struct value *ada_coerce_ref (struct value *);
175
176 static LONGEST pos_atr (struct value *);
177
178 static struct value *val_atr (struct type *, LONGEST);
179
180 static struct value *ada_search_struct_field (const char *, struct value *, int,
181 struct type *);
182
183 static int find_struct_field (const char *, struct type *, int,
184 struct type **, int *, int *, int *, int *);
185
186 static int ada_resolve_function (std::vector<struct block_symbol> &,
187 struct value **, int, const char *,
188 struct type *, bool);
189
190 static int ada_is_direct_array_type (struct type *);
191
192 static struct value *ada_index_struct_field (int, struct value *, int,
193 struct type *);
194
195 static struct type *ada_find_any_type (const char *name);
196
197 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
198 (const lookup_name_info &lookup_name);
199
200 static int symbols_are_identical_enums
201 (const std::vector<struct block_symbol> &syms);
202
203 static int ada_identical_enum_types_p (struct type *type1, struct type *type2);
204
205
206 /* The character set used for source files. */
207 static const char *ada_source_charset;
208
209 /* The string "UTF-8". This is here so we can check for the UTF-8
210 charset using == rather than strcmp. */
211 static const char ada_utf8[] = "UTF-8";
212
213 /* Each entry in the UTF-32 case-folding table is of this form. */
214 struct utf8_entry
215 {
216 /* The start and end, inclusive, of this range of codepoints. */
217 uint32_t start, end;
218 /* The delta to apply to get the upper-case form. 0 if this is
219 already upper-case. */
220 int upper_delta;
221 /* The delta to apply to get the lower-case form. 0 if this is
222 already lower-case. */
223 int lower_delta;
224
225 bool operator< (uint32_t val) const
226 {
227 return end < val;
228 }
229 };
230
231 static const utf8_entry ada_case_fold[] =
232 {
233 #include "ada-casefold.h"
234 };
235
236
237
238 static const char ada_completer_word_break_characters[] =
239 #ifdef VMS
240 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
241 #else
242 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
243 #endif
244
245 /* The name of the symbol to use to get the name of the main subprogram. */
246 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
247 = "__gnat_ada_main_program_name";
248
249 /* Limit on the number of warnings to raise per expression evaluation. */
250 static int warning_limit = 2;
251
252 /* Number of warning messages issued; reset to 0 by cleanups after
253 expression evaluation. */
254 static int warnings_issued = 0;
255
256 static const char * const known_runtime_file_name_patterns[] = {
257 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
258 };
259
260 static const char * const known_auxiliary_function_name_patterns[] = {
261 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
262 };
263
264 /* Maintenance-related settings for this module. */
265
266 static struct cmd_list_element *maint_set_ada_cmdlist;
267 static struct cmd_list_element *maint_show_ada_cmdlist;
268
269 /* The "maintenance ada set/show ignore-descriptive-type" value. */
270
271 static bool ada_ignore_descriptive_types_p = false;
272
273 /* Inferior-specific data. */
274
275 /* Per-inferior data for this module. */
276
277 struct ada_inferior_data
278 {
279 /* The ada__tags__type_specific_data type, which is used when decoding
280 tagged types. With older versions of GNAT, this type was directly
281 accessible through a component ("tsd") in the object tag. But this
282 is no longer the case, so we cache it for each inferior. */
283 struct type *tsd_type = nullptr;
284
285 /* The exception_support_info data. This data is used to determine
286 how to implement support for Ada exception catchpoints in a given
287 inferior. */
288 const struct exception_support_info *exception_info = nullptr;
289 };
290
291 /* Our key to this module's inferior data. */
292 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
293
294 /* Return our inferior data for the given inferior (INF).
295
296 This function always returns a valid pointer to an allocated
297 ada_inferior_data structure. If INF's inferior data has not
298 been previously set, this functions creates a new one with all
299 fields set to zero, sets INF's inferior to it, and then returns
300 a pointer to that newly allocated ada_inferior_data. */
301
302 static struct ada_inferior_data *
get_ada_inferior_data(struct inferior * inf)303 get_ada_inferior_data (struct inferior *inf)
304 {
305 struct ada_inferior_data *data;
306
307 data = ada_inferior_data.get (inf);
308 if (data == NULL)
309 data = ada_inferior_data.emplace (inf);
310
311 return data;
312 }
313
314 /* Perform all necessary cleanups regarding our module's inferior data
315 that is required after the inferior INF just exited. */
316
317 static void
ada_inferior_exit(struct inferior * inf)318 ada_inferior_exit (struct inferior *inf)
319 {
320 ada_inferior_data.clear (inf);
321 }
322
323
324 /* program-space-specific data. */
325
326 /* The result of a symbol lookup to be stored in our symbol cache. */
327
328 struct cache_entry
329 {
330 /* The name used to perform the lookup. */
331 std::string name;
332 /* The namespace used during the lookup. */
333 domain_search_flags domain = 0;
334 /* The symbol returned by the lookup, or NULL if no matching symbol
335 was found. */
336 struct symbol *sym = nullptr;
337 /* The block where the symbol was found, or NULL if no matching
338 symbol was found. */
339 const struct block *block = nullptr;
340 };
341
342 /* The symbol cache uses this type when searching. */
343
344 struct cache_entry_search
345 {
346 const char *name;
347 domain_search_flags domain;
348
hashcache_entry_search349 hashval_t hash () const
350 {
351 /* This must agree with hash_cache_entry, below. */
352 return htab_hash_string (name);
353 }
354 };
355
356 /* Hash function for cache_entry. */
357
358 static hashval_t
hash_cache_entry(const void * v)359 hash_cache_entry (const void *v)
360 {
361 const cache_entry *entry = (const cache_entry *) v;
362 return htab_hash_string (entry->name.c_str ());
363 }
364
365 /* Equality function for cache_entry. */
366
367 static int
eq_cache_entry(const void * a,const void * b)368 eq_cache_entry (const void *a, const void *b)
369 {
370 const cache_entry *entrya = (const cache_entry *) a;
371 const cache_entry_search *entryb = (const cache_entry_search *) b;
372
373 return entrya->domain == entryb->domain && entrya->name == entryb->name;
374 }
375
376 /* Key to our per-program-space data. */
377 static const registry<program_space>::key<htab, htab_deleter>
378 ada_pspace_data_handle;
379
380 /* Return this module's data for the given program space (PSPACE).
381 If not is found, add a zero'ed one now.
382
383 This function always returns a valid object. */
384
385 static htab_t
get_ada_pspace_data(struct program_space * pspace)386 get_ada_pspace_data (struct program_space *pspace)
387 {
388 htab_t data = ada_pspace_data_handle.get (pspace);
389 if (data == nullptr)
390 {
391 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
392 htab_delete_entry<cache_entry>,
393 xcalloc, xfree);
394 ada_pspace_data_handle.set (pspace, data);
395 }
396
397 return data;
398 }
399
400 /* Utilities */
401
402 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
403 all typedef layers have been peeled. Otherwise, return TYPE.
404
405 Normally, we really expect a typedef type to only have 1 typedef layer.
406 In other words, we really expect the target type of a typedef type to be
407 a non-typedef type. This is particularly true for Ada units, because
408 the language does not have a typedef vs not-typedef distinction.
409 In that respect, the Ada compiler has been trying to eliminate as many
410 typedef definitions in the debugging information, since they generally
411 do not bring any extra information (we still use typedef under certain
412 circumstances related mostly to the GNAT encoding).
413
414 Unfortunately, we have seen situations where the debugging information
415 generated by the compiler leads to such multiple typedef layers. For
416 instance, consider the following example with stabs:
417
418 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
419 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
420
421 This is an error in the debugging information which causes type
422 pck__float_array___XUP to be defined twice, and the second time,
423 it is defined as a typedef of a typedef.
424
425 This is on the fringe of legality as far as debugging information is
426 concerned, and certainly unexpected. But it is easy to handle these
427 situations correctly, so we can afford to be lenient in this case. */
428
429 static struct type *
ada_typedef_target_type(struct type * type)430 ada_typedef_target_type (struct type *type)
431 {
432 while (type->code () == TYPE_CODE_TYPEDEF)
433 type = type->target_type ();
434 return type;
435 }
436
437 /* Given DECODED_NAME a string holding a symbol name in its
438 decoded form (ie using the Ada dotted notation), returns
439 its unqualified name. */
440
441 static const char *
ada_unqualified_name(const char * decoded_name)442 ada_unqualified_name (const char *decoded_name)
443 {
444 const char *result;
445
446 /* If the decoded name starts with '<', it means that the encoded
447 name does not follow standard naming conventions, and thus that
448 it is not your typical Ada symbol name. Trying to unqualify it
449 is therefore pointless and possibly erroneous. */
450 if (decoded_name[0] == '<')
451 return decoded_name;
452
453 result = strrchr (decoded_name, '.');
454 if (result != NULL)
455 result++; /* Skip the dot... */
456 else
457 result = decoded_name;
458
459 return result;
460 }
461
462 /* Return a string starting with '<', followed by STR, and '>'. */
463
464 static std::string
add_angle_brackets(const char * str)465 add_angle_brackets (const char *str)
466 {
467 return string_printf ("<%s>", str);
468 }
469
470 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
471 suffix of FIELD_NAME beginning "___". */
472
473 static int
field_name_match(const char * field_name,const char * target)474 field_name_match (const char *field_name, const char *target)
475 {
476 int len = strlen (target);
477
478 return
479 (strncmp (field_name, target, len) == 0
480 && (field_name[len] == '\0'
481 || (startswith (field_name + len, "___")
482 && strcmp (field_name + strlen (field_name) - 6,
483 "___XVN") != 0)));
484 }
485
486
487 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
488 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
489 and return its index. This function also handles fields whose name
490 have ___ suffixes because the compiler sometimes alters their name
491 by adding such a suffix to represent fields with certain constraints.
492 If the field could not be found, return a negative number if
493 MAYBE_MISSING is set. Otherwise raise an error. */
494
495 int
ada_get_field_index(const struct type * type,const char * field_name,int maybe_missing)496 ada_get_field_index (const struct type *type, const char *field_name,
497 int maybe_missing)
498 {
499 int fieldno;
500 struct type *struct_type = check_typedef ((struct type *) type);
501
502 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
503 if (field_name_match (struct_type->field (fieldno).name (), field_name))
504 return fieldno;
505
506 if (!maybe_missing)
507 error (_("Unable to find field %s in struct %s. Aborting"),
508 field_name, struct_type->name ());
509
510 return -1;
511 }
512
513 /* The length of the prefix of NAME prior to any "___" suffix. */
514
515 int
ada_name_prefix_len(const char * name)516 ada_name_prefix_len (const char *name)
517 {
518 if (name == NULL)
519 return 0;
520 else
521 {
522 const char *p = strstr (name, "___");
523
524 if (p == NULL)
525 return strlen (name);
526 else
527 return p - name;
528 }
529 }
530
531 /* Return non-zero if SUFFIX is a suffix of STR.
532 Return zero if STR is null. */
533
534 static int
is_suffix(const char * str,const char * suffix)535 is_suffix (const char *str, const char *suffix)
536 {
537 int len1, len2;
538
539 if (str == NULL)
540 return 0;
541 len1 = strlen (str);
542 len2 = strlen (suffix);
543 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
544 }
545
546 /* The contents of value VAL, treated as a value of type TYPE. The
547 result is an lval in memory if VAL is. */
548
549 static struct value *
coerce_unspec_val_to_type(struct value * val,struct type * type)550 coerce_unspec_val_to_type (struct value *val, struct type *type)
551 {
552 type = ada_check_typedef (type);
553 if (val->type () == type)
554 return val;
555 else
556 {
557 struct value *result;
558
559 if (val->optimized_out ())
560 result = value::allocate_optimized_out (type);
561 else if (val->lazy ()
562 /* Be careful not to make a lazy not_lval value. */
563 || (val->lval () != not_lval
564 && type->length () > val->type ()->length ()))
565 result = value::allocate_lazy (type);
566 else
567 {
568 result = value::allocate (type);
569 val->contents_copy (result, 0, 0, type->length ());
570 }
571 result->set_component_location (val);
572 result->set_bitsize (val->bitsize ());
573 result->set_bitpos (val->bitpos ());
574 if (result->lval () == lval_memory)
575 result->set_address (val->address ());
576 return result;
577 }
578 }
579
580 static const gdb_byte *
cond_offset_host(const gdb_byte * valaddr,long offset)581 cond_offset_host (const gdb_byte *valaddr, long offset)
582 {
583 if (valaddr == NULL)
584 return NULL;
585 else
586 return valaddr + offset;
587 }
588
589 static CORE_ADDR
cond_offset_target(CORE_ADDR address,long offset)590 cond_offset_target (CORE_ADDR address, long offset)
591 {
592 if (address == 0)
593 return 0;
594 else
595 return address + offset;
596 }
597
598 /* Issue a warning (as for the definition of warning in utils.c, but
599 with exactly one argument rather than ...), unless the limit on the
600 number of warnings has passed during the evaluation of the current
601 expression. */
602
603 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
604 provided by "complaint". */
605 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
606
607 static void
lim_warning(const char * format,...)608 lim_warning (const char *format, ...)
609 {
610 va_list args;
611
612 va_start (args, format);
613 warnings_issued += 1;
614 if (warnings_issued <= warning_limit)
615 vwarning (format, args);
616
617 va_end (args);
618 }
619
620 /* Maximum value of a SIZE-byte signed integer type. */
621 static LONGEST
max_of_size(int size)622 max_of_size (int size)
623 {
624 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
625
626 return top_bit | (top_bit - 1);
627 }
628
629 /* Minimum value of a SIZE-byte signed integer type. */
630 static LONGEST
min_of_size(int size)631 min_of_size (int size)
632 {
633 return -max_of_size (size) - 1;
634 }
635
636 /* Maximum value of a SIZE-byte unsigned integer type. */
637 static ULONGEST
umax_of_size(int size)638 umax_of_size (int size)
639 {
640 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
641
642 return top_bit | (top_bit - 1);
643 }
644
645 /* Maximum value of integral type T, as a signed quantity. */
646 static LONGEST
max_of_type(struct type * t)647 max_of_type (struct type *t)
648 {
649 if (t->is_unsigned ())
650 return (LONGEST) umax_of_size (t->length ());
651 else
652 return max_of_size (t->length ());
653 }
654
655 /* Minimum value of integral type T, as a signed quantity. */
656 static LONGEST
min_of_type(struct type * t)657 min_of_type (struct type *t)
658 {
659 if (t->is_unsigned ())
660 return 0;
661 else
662 return min_of_size (t->length ());
663 }
664
665 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
666 LONGEST
ada_discrete_type_high_bound(struct type * type)667 ada_discrete_type_high_bound (struct type *type)
668 {
669 type = resolve_dynamic_type (type, {}, 0);
670 switch (type->code ())
671 {
672 case TYPE_CODE_RANGE:
673 {
674 const dynamic_prop &high = type->bounds ()->high;
675
676 if (high.is_constant ())
677 return high.const_val ();
678 else
679 {
680 gdb_assert (!high.is_available ());
681
682 /* This happens when trying to evaluate a type's dynamic bound
683 without a live target. There is nothing relevant for us to
684 return here, so return 0. */
685 return 0;
686 }
687 }
688 case TYPE_CODE_ENUM:
689 return type->field (type->num_fields () - 1).loc_enumval ();
690 case TYPE_CODE_BOOL:
691 return 1;
692 case TYPE_CODE_CHAR:
693 case TYPE_CODE_INT:
694 return max_of_type (type);
695 default:
696 error (_("Unexpected type in ada_discrete_type_high_bound."));
697 }
698 }
699
700 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
701 LONGEST
ada_discrete_type_low_bound(struct type * type)702 ada_discrete_type_low_bound (struct type *type)
703 {
704 type = resolve_dynamic_type (type, {}, 0);
705 switch (type->code ())
706 {
707 case TYPE_CODE_RANGE:
708 {
709 const dynamic_prop &low = type->bounds ()->low;
710
711 if (low.is_constant ())
712 return low.const_val ();
713 else
714 {
715 gdb_assert (!low.is_available ());
716
717 /* This happens when trying to evaluate a type's dynamic bound
718 without a live target. There is nothing relevant for us to
719 return here, so return 0. */
720 return 0;
721 }
722 }
723 case TYPE_CODE_ENUM:
724 return type->field (0).loc_enumval ();
725 case TYPE_CODE_BOOL:
726 return 0;
727 case TYPE_CODE_CHAR:
728 case TYPE_CODE_INT:
729 return min_of_type (type);
730 default:
731 error (_("Unexpected type in ada_discrete_type_low_bound."));
732 }
733 }
734
735 /* The identity on non-range types. For range types, the underlying
736 non-range scalar type. */
737
738 static struct type *
get_base_type(struct type * type)739 get_base_type (struct type *type)
740 {
741 while (type != NULL && type->code () == TYPE_CODE_RANGE)
742 {
743 if (type == type->target_type () || type->target_type () == NULL)
744 return type;
745 type = type->target_type ();
746 }
747 return type;
748 }
749
750 /* Return a decoded version of the given VALUE. This means returning
751 a value whose type is obtained by applying all the GNAT-specific
752 encodings, making the resulting type a static but standard description
753 of the initial type. */
754
755 struct value *
ada_get_decoded_value(struct value * value)756 ada_get_decoded_value (struct value *value)
757 {
758 struct type *type = ada_check_typedef (value->type ());
759
760 if (ada_is_array_descriptor_type (type)
761 || (ada_is_constrained_packed_array_type (type)
762 && type->code () != TYPE_CODE_PTR))
763 {
764 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
765 value = ada_coerce_to_simple_array_ptr (value);
766 else
767 value = ada_coerce_to_simple_array (value);
768 }
769 else
770 value = ada_to_fixed_value (value);
771
772 return value;
773 }
774
775 /* Same as ada_get_decoded_value, but with the given TYPE.
776 Because there is no associated actual value for this type,
777 the resulting type might be a best-effort approximation in
778 the case of dynamic types. */
779
780 struct type *
ada_get_decoded_type(struct type * type)781 ada_get_decoded_type (struct type *type)
782 {
783 type = to_static_fixed_type (type);
784 if (ada_is_constrained_packed_array_type (type))
785 type = ada_coerce_to_simple_array_type (type);
786 return type;
787 }
788
789
790
791 /* Language Selection */
792
793 /* If the main procedure is written in Ada, then return its name.
794 The result is good until the next call. Return NULL if the main
795 procedure doesn't appear to be in Ada. */
796
797 const char *
ada_main_name()798 ada_main_name ()
799 {
800 struct bound_minimal_symbol msym;
801 static gdb::unique_xmalloc_ptr<char> main_program_name;
802
803 /* For Ada, the name of the main procedure is stored in a specific
804 string constant, generated by the binder. Look for that symbol,
805 extract its address, and then read that string. If we didn't find
806 that string, then most probably the main procedure is not written
807 in Ada. */
808 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
809
810 if (msym.minsym != NULL)
811 {
812 CORE_ADDR main_program_name_addr = msym.value_address ();
813 if (main_program_name_addr == 0)
814 error (_("Invalid address for Ada main program name."));
815
816 /* Force trust_readonly, because we always want to fetch this
817 string from the executable, not from inferior memory. If the
818 user changes the exec-file and invokes "start", we want to
819 pick the "main" from the new executable, not one that may
820 come from the still-live inferior. */
821 scoped_restore save_trust_readonly
822 = make_scoped_restore (&trust_readonly, true);
823 main_program_name = target_read_string (main_program_name_addr, 1024);
824 return main_program_name.get ();
825 }
826
827 /* The main procedure doesn't seem to be in Ada. */
828 return NULL;
829 }
830
831 /* Symbols */
832
833 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
834 of NULLs. */
835
836 const struct ada_opname_map ada_opname_table[] = {
837 {"Oadd", "\"+\"", BINOP_ADD},
838 {"Osubtract", "\"-\"", BINOP_SUB},
839 {"Omultiply", "\"*\"", BINOP_MUL},
840 {"Odivide", "\"/\"", BINOP_DIV},
841 {"Omod", "\"mod\"", BINOP_MOD},
842 {"Orem", "\"rem\"", BINOP_REM},
843 {"Oexpon", "\"**\"", BINOP_EXP},
844 {"Olt", "\"<\"", BINOP_LESS},
845 {"Ole", "\"<=\"", BINOP_LEQ},
846 {"Ogt", "\">\"", BINOP_GTR},
847 {"Oge", "\">=\"", BINOP_GEQ},
848 {"Oeq", "\"=\"", BINOP_EQUAL},
849 {"One", "\"/=\"", BINOP_NOTEQUAL},
850 {"Oand", "\"and\"", BINOP_BITWISE_AND},
851 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
852 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
853 {"Oconcat", "\"&\"", BINOP_CONCAT},
854 {"Oabs", "\"abs\"", UNOP_ABS},
855 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
856 {"Oadd", "\"+\"", UNOP_PLUS},
857 {"Osubtract", "\"-\"", UNOP_NEG},
858 {NULL, NULL}
859 };
860
861 /* If STR is a decoded version of a compiler-provided suffix (like the
862 "[cold]" in "symbol[cold]"), return true. Otherwise, return
863 false. */
864
865 static bool
is_compiler_suffix(const char * str)866 is_compiler_suffix (const char *str)
867 {
868 gdb_assert (*str == '[');
869 ++str;
870 while (*str != '\0' && isalpha (*str))
871 ++str;
872 /* We accept a missing "]" in order to support completion. */
873 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
874 }
875
876 /* Append a non-ASCII character to RESULT. */
877 static void
append_hex_encoded(std::string & result,uint32_t one_char)878 append_hex_encoded (std::string &result, uint32_t one_char)
879 {
880 if (one_char <= 0xff)
881 {
882 result.append ("U");
883 result.append (phex (one_char, 1));
884 }
885 else if (one_char <= 0xffff)
886 {
887 result.append ("W");
888 result.append (phex (one_char, 2));
889 }
890 else
891 {
892 result.append ("WW");
893 result.append (phex (one_char, 4));
894 }
895 }
896
897 /* Return a string that is a copy of the data in STORAGE, with
898 non-ASCII characters replaced by the appropriate hex encoding. A
899 template is used because, for UTF-8, we actually want to work with
900 UTF-32 codepoints. */
901 template<typename T>
902 std::string
copy_and_hex_encode(struct obstack * storage)903 copy_and_hex_encode (struct obstack *storage)
904 {
905 const T *chars = (T *) obstack_base (storage);
906 int num_chars = obstack_object_size (storage) / sizeof (T);
907 std::string result;
908 for (int i = 0; i < num_chars; ++i)
909 {
910 if (chars[i] <= 0x7f)
911 {
912 /* The host character set has to be a superset of ASCII, as
913 are all the other character sets we can use. */
914 result.push_back (chars[i]);
915 }
916 else
917 append_hex_encoded (result, chars[i]);
918 }
919 return result;
920 }
921
922 /* The "encoded" form of DECODED, according to GNAT conventions. If
923 THROW_ERRORS, throw an error if invalid operator name is found.
924 Otherwise, return the empty string in that case. */
925
926 static std::string
ada_encode_1(const char * decoded,bool throw_errors)927 ada_encode_1 (const char *decoded, bool throw_errors)
928 {
929 if (decoded == NULL)
930 return {};
931
932 std::string encoding_buffer;
933 bool saw_non_ascii = false;
934 for (const char *p = decoded; *p != '\0'; p += 1)
935 {
936 if ((*p & 0x80) != 0)
937 saw_non_ascii = true;
938
939 if (*p == '.')
940 encoding_buffer.append ("__");
941 else if (*p == '[' && is_compiler_suffix (p))
942 {
943 encoding_buffer = encoding_buffer + "." + (p + 1);
944 if (encoding_buffer.back () == ']')
945 encoding_buffer.pop_back ();
946 break;
947 }
948 else if (*p == '"')
949 {
950 const struct ada_opname_map *mapping;
951
952 for (mapping = ada_opname_table;
953 mapping->encoded != NULL
954 && !startswith (p, mapping->decoded); mapping += 1)
955 ;
956 if (mapping->encoded == NULL)
957 {
958 if (throw_errors)
959 error (_("invalid Ada operator name: %s"), p);
960 else
961 return {};
962 }
963 encoding_buffer.append (mapping->encoded);
964 break;
965 }
966 else
967 encoding_buffer.push_back (*p);
968 }
969
970 /* If a non-ASCII character is seen, we must convert it to the
971 appropriate hex form. As this is more expensive, we keep track
972 of whether it is even necessary. */
973 if (saw_non_ascii)
974 {
975 auto_obstack storage;
976 bool is_utf8 = ada_source_charset == ada_utf8;
977 try
978 {
979 convert_between_encodings
980 (host_charset (),
981 is_utf8 ? HOST_UTF32 : ada_source_charset,
982 (const gdb_byte *) encoding_buffer.c_str (),
983 encoding_buffer.length (), 1,
984 &storage, translit_none);
985 }
986 catch (const gdb_exception &)
987 {
988 static bool warned = false;
989
990 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
991 might like to know why. */
992 if (!warned)
993 {
994 warned = true;
995 warning (_("charset conversion failure for '%s'.\n"
996 "You may have the wrong value for 'set ada source-charset'."),
997 encoding_buffer.c_str ());
998 }
999
1000 /* We don't try to recover from errors. */
1001 return encoding_buffer;
1002 }
1003
1004 if (is_utf8)
1005 return copy_and_hex_encode<uint32_t> (&storage);
1006 return copy_and_hex_encode<gdb_byte> (&storage);
1007 }
1008
1009 return encoding_buffer;
1010 }
1011
1012 /* Find the entry for C in the case-folding table. Return nullptr if
1013 the entry does not cover C. */
1014 static const utf8_entry *
find_case_fold_entry(uint32_t c)1015 find_case_fold_entry (uint32_t c)
1016 {
1017 auto iter = std::lower_bound (std::begin (ada_case_fold),
1018 std::end (ada_case_fold),
1019 c);
1020 if (iter == std::end (ada_case_fold)
1021 || c < iter->start
1022 || c > iter->end)
1023 return nullptr;
1024 return &*iter;
1025 }
1026
1027 /* Return NAME folded to lower case, or, if surrounded by single
1028 quotes, unfolded, but with the quotes stripped away. If
1029 THROW_ON_ERROR is true, encoding failures will throw an exception
1030 rather than emitting a warning. Result good to next call. */
1031
1032 static const char *
1033 ada_fold_name (std::string_view name, bool throw_on_error = false)
1034 {
1035 static std::string fold_storage;
1036
1037 if (!name.empty () && name[0] == '\'')
1038 fold_storage = name.substr (1, name.size () - 2);
1039 else
1040 {
1041 /* Why convert to UTF-32 and implement our own case-folding,
1042 rather than convert to wchar_t and use the platform's
1043 functions? I'm glad you asked.
1044
1045 The main problem is that GNAT implements an unusual rule for
1046 case folding. For ASCII letters, letters in single-byte
1047 encodings (such as ISO-8859-*), and Unicode letters that fit
1048 in a single byte (i.e., code point is <= 0xff), the letter is
1049 folded to lower case. Other Unicode letters are folded to
1050 upper case.
1051
1052 This rule means that the code must be able to examine the
1053 value of the character. And, some hosts do not use Unicode
1054 for wchar_t, so examining the value of such characters is
1055 forbidden. */
1056 auto_obstack storage;
1057 try
1058 {
1059 convert_between_encodings
1060 (host_charset (), HOST_UTF32,
1061 (const gdb_byte *) name.data (),
1062 name.length (), 1,
1063 &storage, translit_none);
1064 }
catch(const gdb_exception &)1065 catch (const gdb_exception &)
1066 {
1067 if (throw_on_error)
1068 throw;
1069
1070 static bool warned = false;
1071
1072 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1073 might like to know why. */
1074 if (!warned)
1075 {
1076 warned = true;
1077 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1078 "This normally should not happen, please file a bug report."),
1079 std::string (name).c_str (), host_charset ());
1080 }
1081
1082 /* We don't try to recover from errors; just return the
1083 original string. */
1084 fold_storage = name;
1085 return fold_storage.c_str ();
1086 }
1087
1088 bool is_utf8 = ada_source_charset == ada_utf8;
1089 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1090 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1091 for (int i = 0; i < num_chars; ++i)
1092 {
1093 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1094 if (entry != nullptr)
1095 {
1096 uint32_t low = chars[i] + entry->lower_delta;
1097 if (!is_utf8 || low <= 0xff)
1098 chars[i] = low;
1099 else
1100 chars[i] = chars[i] + entry->upper_delta;
1101 }
1102 }
1103
1104 /* Now convert back to ordinary characters. */
1105 auto_obstack reconverted;
1106 try
1107 {
1108 convert_between_encodings (HOST_UTF32,
1109 host_charset (),
1110 (const gdb_byte *) chars,
1111 num_chars * sizeof (uint32_t),
1112 sizeof (uint32_t),
1113 &reconverted,
1114 translit_none);
1115 obstack_1grow (&reconverted, '\0');
1116 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1117 }
catch(const gdb_exception &)1118 catch (const gdb_exception &)
1119 {
1120 if (throw_on_error)
1121 throw;
1122
1123 static bool warned = false;
1124
1125 /* Converting back from UTF-32 shouldn't normally fail, but
1126 there are some host encodings without upper/lower
1127 equivalence. */
1128 if (!warned)
1129 {
1130 warned = true;
1131 warning (_("could not convert the lower-cased variant of '%s'\n"
1132 "from UTF-32 to the host encoding (%s)."),
1133 std::string (name).c_str (), host_charset ());
1134 }
1135
1136 /* We don't try to recover from errors; just return the
1137 original string. */
1138 fold_storage = name;
1139 }
1140 }
1141
1142 return fold_storage.c_str ();
1143 }
1144
1145 /* The "encoded" form of DECODED, according to GNAT conventions. If
1146 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1147 with <...> quoting are not folded in any case. */
1148
1149 std::string
ada_encode(const char * decoded,bool fold)1150 ada_encode (const char *decoded, bool fold)
1151 {
1152 if (fold && decoded[0] != '<')
1153 decoded = ada_fold_name (decoded);
1154 return ada_encode_1 (decoded, true);
1155 }
1156
1157 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1158
1159 static int
is_lower_alphanum(const char c)1160 is_lower_alphanum (const char c)
1161 {
1162 return (isdigit (c) || (isalpha (c) && islower (c)));
1163 }
1164
1165 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1166 This function saves in LEN the length of that same symbol name but
1167 without either of these suffixes:
1168 . .{DIGIT}+
1169 . ${DIGIT}+
1170 . ___{DIGIT}+
1171 . __{DIGIT}+.
1172
1173 These are suffixes introduced by the compiler for entities such as
1174 nested subprogram for instance, in order to avoid name clashes.
1175 They do not serve any purpose for the debugger. */
1176
1177 static void
ada_remove_trailing_digits(const char * encoded,int * len)1178 ada_remove_trailing_digits (const char *encoded, int *len)
1179 {
1180 if (*len > 1 && isdigit (encoded[*len - 1]))
1181 {
1182 int i = *len - 2;
1183
1184 while (i > 0 && isdigit (encoded[i]))
1185 i--;
1186 if (i >= 0 && encoded[i] == '.')
1187 *len = i;
1188 else if (i >= 0 && encoded[i] == '$')
1189 *len = i;
1190 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1191 *len = i - 2;
1192 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1193 *len = i - 1;
1194 }
1195 }
1196
1197 /* Remove the suffix introduced by the compiler for protected object
1198 subprograms. */
1199
1200 static void
ada_remove_po_subprogram_suffix(const char * encoded,int * len)1201 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1202 {
1203 /* Remove trailing N. */
1204
1205 /* Protected entry subprograms are broken into two
1206 separate subprograms: The first one is unprotected, and has
1207 a 'N' suffix; the second is the protected version, and has
1208 the 'P' suffix. The second calls the first one after handling
1209 the protection. Since the P subprograms are internally generated,
1210 we leave these names undecoded, giving the user a clue that this
1211 entity is internal. */
1212
1213 if (*len > 1
1214 && encoded[*len - 1] == 'N'
1215 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1216 *len = *len - 1;
1217 }
1218
1219 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1220 then update *LEN to remove the suffix and return the offset of the
1221 character just past the ".". Otherwise, return -1. */
1222
1223 static int
remove_compiler_suffix(const char * encoded,int * len)1224 remove_compiler_suffix (const char *encoded, int *len)
1225 {
1226 int offset = *len - 1;
1227 while (offset > 0 && isalpha (encoded[offset]))
1228 --offset;
1229 if (offset > 0 && encoded[offset] == '.')
1230 {
1231 *len = offset;
1232 return offset + 1;
1233 }
1234 return -1;
1235 }
1236
1237 /* Convert an ASCII hex string to a number. Reads exactly N
1238 characters from STR. Returns true on success, false if one of the
1239 digits was not a hex digit. */
1240 static bool
convert_hex(const char * str,int n,uint32_t * out)1241 convert_hex (const char *str, int n, uint32_t *out)
1242 {
1243 uint32_t result = 0;
1244
1245 for (int i = 0; i < n; ++i)
1246 {
1247 if (!isxdigit (str[i]))
1248 return false;
1249 result <<= 4;
1250 result |= fromhex (str[i]);
1251 }
1252
1253 *out = result;
1254 return true;
1255 }
1256
1257 /* Convert a wide character from its ASCII hex representation in STR
1258 (consisting of exactly N characters) to the host encoding,
1259 appending the resulting bytes to OUT. If N==2 and the Ada source
1260 charset is not UTF-8, then hex refers to an encoding in the
1261 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1262 Return false and do not modify OUT on conversion failure. */
1263 static bool
convert_from_hex_encoded(std::string & out,const char * str,int n)1264 convert_from_hex_encoded (std::string &out, const char *str, int n)
1265 {
1266 uint32_t value;
1267
1268 if (!convert_hex (str, n, &value))
1269 return false;
1270 try
1271 {
1272 auto_obstack bytes;
1273 /* In the 'U' case, the hex digits encode the character in the
1274 Ada source charset. However, if the source charset is UTF-8,
1275 this really means it is a single-byte UTF-32 character. */
1276 if (n == 2 && ada_source_charset != ada_utf8)
1277 {
1278 gdb_byte one_char = (gdb_byte) value;
1279
1280 convert_between_encodings (ada_source_charset, host_charset (),
1281 &one_char,
1282 sizeof (one_char), sizeof (one_char),
1283 &bytes, translit_none);
1284 }
1285 else
1286 convert_between_encodings (HOST_UTF32, host_charset (),
1287 (const gdb_byte *) &value,
1288 sizeof (value), sizeof (value),
1289 &bytes, translit_none);
1290 obstack_1grow (&bytes, '\0');
1291 out.append ((const char *) obstack_base (&bytes));
1292 }
1293 catch (const gdb_exception &)
1294 {
1295 /* On failure, the caller will just let the encoded form
1296 through, which seems basically reasonable. */
1297 return false;
1298 }
1299
1300 return true;
1301 }
1302
1303 /* See ada-lang.h. */
1304
1305 std::string
ada_decode(const char * encoded,bool wrap,bool operators,bool wide)1306 ada_decode (const char *encoded, bool wrap, bool operators, bool wide)
1307 {
1308 int i;
1309 int len0;
1310 const char *p;
1311 int at_start_name;
1312 std::string decoded;
1313 int suffix = -1;
1314
1315 /* With function descriptors on PPC64, the value of a symbol named
1316 ".FN", if it exists, is the entry point of the function "FN". */
1317 if (encoded[0] == '.')
1318 encoded += 1;
1319
1320 /* The name of the Ada main procedure starts with "_ada_".
1321 This prefix is not part of the decoded name, so skip this part
1322 if we see this prefix. */
1323 if (startswith (encoded, "_ada_"))
1324 encoded += 5;
1325 /* The "___ghost_" prefix is used for ghost entities. Normally
1326 these aren't preserved but when they are, it's useful to see
1327 them. */
1328 if (startswith (encoded, "___ghost_"))
1329 encoded += 9;
1330
1331 /* If the name starts with '_', then it is not a properly encoded
1332 name, so do not attempt to decode it. Similarly, if the name
1333 starts with '<', the name should not be decoded. */
1334 if (encoded[0] == '_' || encoded[0] == '<')
1335 goto Suppress;
1336
1337 len0 = strlen (encoded);
1338
1339 suffix = remove_compiler_suffix (encoded, &len0);
1340
1341 ada_remove_trailing_digits (encoded, &len0);
1342 ada_remove_po_subprogram_suffix (encoded, &len0);
1343
1344 /* Remove the ___X.* suffix if present. Do not forget to verify that
1345 the suffix is located before the current "end" of ENCODED. We want
1346 to avoid re-matching parts of ENCODED that have previously been
1347 marked as discarded (by decrementing LEN0). */
1348 p = strstr (encoded, "___");
1349 if (p != NULL && p - encoded < len0 - 3)
1350 {
1351 if (p[3] == 'X')
1352 len0 = p - encoded;
1353 else
1354 goto Suppress;
1355 }
1356
1357 /* Remove any trailing TKB suffix. It tells us that this symbol
1358 is for the body of a task, but that information does not actually
1359 appear in the decoded name. */
1360
1361 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1362 len0 -= 3;
1363
1364 /* Remove any trailing TB suffix. The TB suffix is slightly different
1365 from the TKB suffix because it is used for non-anonymous task
1366 bodies. */
1367
1368 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1369 len0 -= 2;
1370
1371 /* Remove trailing "B" suffixes. */
1372 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1373
1374 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1375 len0 -= 1;
1376
1377 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1378
1379 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1380 {
1381 i = len0 - 2;
1382 while ((i >= 0 && isdigit (encoded[i]))
1383 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1384 i -= 1;
1385 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1386 len0 = i - 1;
1387 else if (i >= 0 && encoded[i] == '$')
1388 len0 = i;
1389 }
1390
1391 /* The first few characters that are not alphabetic are not part
1392 of any encoding we use, so we can copy them over verbatim. */
1393
1394 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1395 decoded.push_back (encoded[i]);
1396
1397 at_start_name = 1;
1398 while (i < len0)
1399 {
1400 /* Is this a symbol function? */
1401 if (operators && at_start_name && encoded[i] == 'O')
1402 {
1403 int k;
1404
1405 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1406 {
1407 int op_len = strlen (ada_opname_table[k].encoded);
1408 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1409 op_len - 1) == 0)
1410 && !isalnum (encoded[i + op_len]))
1411 {
1412 decoded.append (ada_opname_table[k].decoded);
1413 at_start_name = 0;
1414 i += op_len;
1415 break;
1416 }
1417 }
1418 if (ada_opname_table[k].encoded != NULL)
1419 continue;
1420 }
1421 at_start_name = 0;
1422
1423 /* Replace "TK__" with "__", which will eventually be translated
1424 into "." (just below). */
1425
1426 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1427 i += 2;
1428
1429 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1430 be translated into "." (just below). These are internal names
1431 generated for anonymous blocks inside which our symbol is nested. */
1432
1433 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1434 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1435 && isdigit (encoded [i+4]))
1436 {
1437 int k = i + 5;
1438
1439 while (k < len0 && isdigit (encoded[k]))
1440 k++; /* Skip any extra digit. */
1441
1442 /* Double-check that the "__B_{DIGITS}+" sequence we found
1443 is indeed followed by "__". */
1444 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1445 i = k;
1446 }
1447
1448 /* Remove _E{DIGITS}+[sb] */
1449
1450 /* Just as for protected object subprograms, there are 2 categories
1451 of subprograms created by the compiler for each entry. The first
1452 one implements the actual entry code, and has a suffix following
1453 the convention above; the second one implements the barrier and
1454 uses the same convention as above, except that the 'E' is replaced
1455 by a 'B'.
1456
1457 Just as above, we do not decode the name of barrier functions
1458 to give the user a clue that the code he is debugging has been
1459 internally generated. */
1460
1461 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1462 && isdigit (encoded[i+2]))
1463 {
1464 int k = i + 3;
1465
1466 while (k < len0 && isdigit (encoded[k]))
1467 k++;
1468
1469 if (k < len0
1470 && (encoded[k] == 'b' || encoded[k] == 's'))
1471 {
1472 k++;
1473 /* Just as an extra precaution, make sure that if this
1474 suffix is followed by anything else, it is a '_'.
1475 Otherwise, we matched this sequence by accident. */
1476 if (k == len0
1477 || (k < len0 && encoded[k] == '_'))
1478 i = k;
1479 }
1480 }
1481
1482 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1483 the GNAT front-end in protected object subprograms. */
1484
1485 if (i < len0 + 3
1486 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1487 {
1488 /* Backtrack a bit up until we reach either the begining of
1489 the encoded name, or "__". Make sure that we only find
1490 digits or lowercase characters. */
1491 const char *ptr = encoded + i - 1;
1492
1493 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1494 ptr--;
1495 if (ptr < encoded
1496 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1497 i++;
1498 }
1499
1500 if (wide && i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1501 {
1502 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1503 {
1504 i += 3;
1505 continue;
1506 }
1507 }
1508 else if (wide && i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1509 {
1510 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1511 {
1512 i += 5;
1513 continue;
1514 }
1515 }
1516 else if (wide && i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1517 && isxdigit (encoded[i + 2]))
1518 {
1519 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1520 {
1521 i += 10;
1522 continue;
1523 }
1524 }
1525
1526 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1527 {
1528 /* This is a X[bn]* sequence not separated from the previous
1529 part of the name with a non-alpha-numeric character (in other
1530 words, immediately following an alpha-numeric character), then
1531 verify that it is placed at the end of the encoded name. If
1532 not, then the encoding is not valid and we should abort the
1533 decoding. Otherwise, just skip it, it is used in body-nested
1534 package names. */
1535 do
1536 i += 1;
1537 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1538 if (i < len0)
1539 goto Suppress;
1540 }
1541 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1542 {
1543 /* Replace '__' by '.'. */
1544 decoded.push_back ('.');
1545 at_start_name = 1;
1546 i += 2;
1547 }
1548 else
1549 {
1550 /* It's a character part of the decoded name, so just copy it
1551 over. */
1552 decoded.push_back (encoded[i]);
1553 i += 1;
1554 }
1555 }
1556
1557 /* Decoded names should never contain any uppercase character.
1558 Double-check this, and abort the decoding if we find one. */
1559
1560 if (operators)
1561 {
1562 for (i = 0; i < decoded.length(); ++i)
1563 if (isupper (decoded[i]) || decoded[i] == ' ')
1564 goto Suppress;
1565 }
1566
1567 /* If the compiler added a suffix, append it now. */
1568 if (suffix >= 0)
1569 decoded = decoded + "[" + &encoded[suffix] + "]";
1570
1571 return decoded;
1572
1573 Suppress:
1574 if (!wrap)
1575 return {};
1576
1577 if (encoded[0] == '<')
1578 decoded = encoded;
1579 else
1580 decoded = '<' + std::string(encoded) + '>';
1581 return decoded;
1582 }
1583
1584 #ifdef GDB_SELF_TEST
1585
1586 static void
ada_decode_tests()1587 ada_decode_tests ()
1588 {
1589 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1590 result does not really matter very much. */
1591 SELF_CHECK (ada_decode ("44") == "44");
1592 }
1593
1594 #endif
1595
1596 /* Table for keeping permanent unique copies of decoded names. Once
1597 allocated, names in this table are never released. While this is a
1598 storage leak, it should not be significant unless there are massive
1599 changes in the set of decoded names in successive versions of a
1600 symbol table loaded during a single session. */
1601 static struct htab *decoded_names_store;
1602
1603 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1604 in the language-specific part of GSYMBOL, if it has not been
1605 previously computed. Tries to save the decoded name in the same
1606 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1607 in any case, the decoded symbol has a lifetime at least that of
1608 GSYMBOL).
1609 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1610 const, but nevertheless modified to a semantically equivalent form
1611 when a decoded name is cached in it. */
1612
1613 const char *
ada_decode_symbol(const struct general_symbol_info * arg)1614 ada_decode_symbol (const struct general_symbol_info *arg)
1615 {
1616 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1617 const char **resultp =
1618 &gsymbol->language_specific.demangled_name;
1619
1620 if (!gsymbol->ada_mangled)
1621 {
1622 std::string decoded = ada_decode (gsymbol->linkage_name ());
1623 struct obstack *obstack = gsymbol->language_specific.obstack;
1624
1625 gsymbol->ada_mangled = 1;
1626
1627 if (obstack != NULL)
1628 *resultp = obstack_strdup (obstack, decoded.c_str ());
1629 else
1630 {
1631 /* Sometimes, we can't find a corresponding objfile, in
1632 which case, we put the result on the heap. Since we only
1633 decode when needed, we hope this usually does not cause a
1634 significant memory leak (FIXME). */
1635
1636 char **slot = (char **) htab_find_slot (decoded_names_store,
1637 decoded.c_str (), INSERT);
1638
1639 if (*slot == NULL)
1640 *slot = xstrdup (decoded.c_str ());
1641 *resultp = *slot;
1642 }
1643 }
1644
1645 return *resultp;
1646 }
1647
1648
1649
1650 /* Arrays */
1651
1652 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1653 generated by the GNAT compiler to describe the index type used
1654 for each dimension of an array, check whether it follows the latest
1655 known encoding. If not, fix it up to conform to the latest encoding.
1656 Otherwise, do nothing. This function also does nothing if
1657 INDEX_DESC_TYPE is NULL.
1658
1659 The GNAT encoding used to describe the array index type evolved a bit.
1660 Initially, the information would be provided through the name of each
1661 field of the structure type only, while the type of these fields was
1662 described as unspecified and irrelevant. The debugger was then expected
1663 to perform a global type lookup using the name of that field in order
1664 to get access to the full index type description. Because these global
1665 lookups can be very expensive, the encoding was later enhanced to make
1666 the global lookup unnecessary by defining the field type as being
1667 the full index type description.
1668
1669 The purpose of this routine is to allow us to support older versions
1670 of the compiler by detecting the use of the older encoding, and by
1671 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1672 we essentially replace each field's meaningless type by the associated
1673 index subtype). */
1674
1675 void
ada_fixup_array_indexes_type(struct type * index_desc_type)1676 ada_fixup_array_indexes_type (struct type *index_desc_type)
1677 {
1678 int i;
1679
1680 if (index_desc_type == NULL)
1681 return;
1682 gdb_assert (index_desc_type->num_fields () > 0);
1683
1684 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1685 to check one field only, no need to check them all). If not, return
1686 now.
1687
1688 If our INDEX_DESC_TYPE was generated using the older encoding,
1689 the field type should be a meaningless integer type whose name
1690 is not equal to the field name. */
1691 if (index_desc_type->field (0).type ()->name () != NULL
1692 && strcmp (index_desc_type->field (0).type ()->name (),
1693 index_desc_type->field (0).name ()) == 0)
1694 return;
1695
1696 /* Fixup each field of INDEX_DESC_TYPE. */
1697 for (i = 0; i < index_desc_type->num_fields (); i++)
1698 {
1699 const char *name = index_desc_type->field (i).name ();
1700 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1701
1702 if (raw_type)
1703 index_desc_type->field (i).set_type (raw_type);
1704 }
1705 }
1706
1707 /* The desc_* routines return primitive portions of array descriptors
1708 (fat pointers). */
1709
1710 /* The descriptor or array type, if any, indicated by TYPE; removes
1711 level of indirection, if needed. */
1712
1713 static struct type *
desc_base_type(struct type * type)1714 desc_base_type (struct type *type)
1715 {
1716 if (type == NULL)
1717 return NULL;
1718 type = ada_check_typedef (type);
1719 if (type->code () == TYPE_CODE_TYPEDEF)
1720 type = ada_typedef_target_type (type);
1721
1722 if (type != NULL
1723 && (type->code () == TYPE_CODE_PTR
1724 || type->code () == TYPE_CODE_REF))
1725 return ada_check_typedef (type->target_type ());
1726 else
1727 return type;
1728 }
1729
1730 /* True iff TYPE indicates a "thin" array pointer type. */
1731
1732 static int
is_thin_pntr(struct type * type)1733 is_thin_pntr (struct type *type)
1734 {
1735 return
1736 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1737 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1738 }
1739
1740 /* The descriptor type for thin pointer type TYPE. */
1741
1742 static struct type *
thin_descriptor_type(struct type * type)1743 thin_descriptor_type (struct type *type)
1744 {
1745 struct type *base_type = desc_base_type (type);
1746
1747 if (base_type == NULL)
1748 return NULL;
1749 if (is_suffix (ada_type_name (base_type), "___XVE"))
1750 return base_type;
1751 else
1752 {
1753 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1754
1755 if (alt_type == NULL)
1756 return base_type;
1757 else
1758 return alt_type;
1759 }
1760 }
1761
1762 /* A pointer to the array data for thin-pointer value VAL. */
1763
1764 static struct value *
thin_data_pntr(struct value * val)1765 thin_data_pntr (struct value *val)
1766 {
1767 struct type *type = ada_check_typedef (val->type ());
1768 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1769
1770 data_type = lookup_pointer_type (data_type);
1771
1772 if (type->code () == TYPE_CODE_PTR)
1773 return value_cast (data_type, val->copy ());
1774 else
1775 return value_from_longest (data_type, val->address ());
1776 }
1777
1778 /* True iff TYPE indicates a "thick" array pointer type. */
1779
1780 static int
is_thick_pntr(struct type * type)1781 is_thick_pntr (struct type *type)
1782 {
1783 type = desc_base_type (type);
1784 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1785 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1786 }
1787
1788 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1789 pointer to one, the type of its bounds data; otherwise, NULL. */
1790
1791 static struct type *
desc_bounds_type(struct type * type)1792 desc_bounds_type (struct type *type)
1793 {
1794 struct type *r;
1795
1796 type = desc_base_type (type);
1797
1798 if (type == NULL)
1799 return NULL;
1800 else if (is_thin_pntr (type))
1801 {
1802 type = thin_descriptor_type (type);
1803 if (type == NULL)
1804 return NULL;
1805 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1806 if (r != NULL)
1807 return ada_check_typedef (r);
1808 }
1809 else if (type->code () == TYPE_CODE_STRUCT)
1810 {
1811 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1812 if (r != NULL)
1813 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1814 }
1815 return NULL;
1816 }
1817
1818 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1819 one, a pointer to its bounds data. Otherwise NULL. */
1820
1821 static struct value *
desc_bounds(struct value * arr)1822 desc_bounds (struct value *arr)
1823 {
1824 struct type *type = ada_check_typedef (arr->type ());
1825
1826 if (is_thin_pntr (type))
1827 {
1828 struct type *bounds_type =
1829 desc_bounds_type (thin_descriptor_type (type));
1830 LONGEST addr;
1831
1832 if (bounds_type == NULL)
1833 error (_("Bad GNAT array descriptor"));
1834
1835 /* NOTE: The following calculation is not really kosher, but
1836 since desc_type is an XVE-encoded type (and shouldn't be),
1837 the correct calculation is a real pain. FIXME (and fix GCC). */
1838 if (type->code () == TYPE_CODE_PTR)
1839 addr = value_as_long (arr);
1840 else
1841 addr = arr->address ();
1842
1843 return
1844 value_from_longest (lookup_pointer_type (bounds_type),
1845 addr - bounds_type->length ());
1846 }
1847
1848 else if (is_thick_pntr (type))
1849 {
1850 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1851 _("Bad GNAT array descriptor"));
1852 struct type *p_bounds_type = p_bounds->type ();
1853
1854 if (p_bounds_type
1855 && p_bounds_type->code () == TYPE_CODE_PTR)
1856 {
1857 struct type *target_type = p_bounds_type->target_type ();
1858
1859 if (target_type->is_stub ())
1860 p_bounds = value_cast (lookup_pointer_type
1861 (ada_check_typedef (target_type)),
1862 p_bounds);
1863 }
1864 else
1865 error (_("Bad GNAT array descriptor"));
1866
1867 return p_bounds;
1868 }
1869 else
1870 return NULL;
1871 }
1872
1873 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1874 position of the field containing the address of the bounds data. */
1875
1876 static int
fat_pntr_bounds_bitpos(struct type * type)1877 fat_pntr_bounds_bitpos (struct type *type)
1878 {
1879 return desc_base_type (type)->field (1).loc_bitpos ();
1880 }
1881
1882 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1883 size of the field containing the address of the bounds data. */
1884
1885 static int
fat_pntr_bounds_bitsize(struct type * type)1886 fat_pntr_bounds_bitsize (struct type *type)
1887 {
1888 type = desc_base_type (type);
1889
1890 if (type->field (1).bitsize () > 0)
1891 return type->field (1).bitsize ();
1892 else
1893 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1894 }
1895
1896 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1897 pointer to one, the type of its array data (a array-with-no-bounds type);
1898 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1899 data. */
1900
1901 static struct type *
desc_data_target_type(struct type * type)1902 desc_data_target_type (struct type *type)
1903 {
1904 type = desc_base_type (type);
1905
1906 /* NOTE: The following is bogus; see comment in desc_bounds. */
1907 if (is_thin_pntr (type))
1908 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1909 else if (is_thick_pntr (type))
1910 {
1911 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1912
1913 if (data_type
1914 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1915 return ada_check_typedef (data_type->target_type ());
1916 }
1917
1918 return NULL;
1919 }
1920
1921 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1922 its array data. */
1923
1924 static struct value *
desc_data(struct value * arr)1925 desc_data (struct value *arr)
1926 {
1927 struct type *type = arr->type ();
1928
1929 if (is_thin_pntr (type))
1930 return thin_data_pntr (arr);
1931 else if (is_thick_pntr (type))
1932 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1933 _("Bad GNAT array descriptor"));
1934 else
1935 return NULL;
1936 }
1937
1938
1939 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1940 position of the field containing the address of the data. */
1941
1942 static int
fat_pntr_data_bitpos(struct type * type)1943 fat_pntr_data_bitpos (struct type *type)
1944 {
1945 return desc_base_type (type)->field (0).loc_bitpos ();
1946 }
1947
1948 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1949 size of the field containing the address of the data. */
1950
1951 static int
fat_pntr_data_bitsize(struct type * type)1952 fat_pntr_data_bitsize (struct type *type)
1953 {
1954 type = desc_base_type (type);
1955
1956 if (type->field (0).bitsize () > 0)
1957 return type->field (0).bitsize ();
1958 else
1959 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1960 }
1961
1962 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1963 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1964 bound, if WHICH is 1. The first bound is I=1. */
1965
1966 static struct value *
desc_one_bound(struct value * bounds,int i,int which)1967 desc_one_bound (struct value *bounds, int i, int which)
1968 {
1969 char bound_name[20];
1970 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1971 which ? 'U' : 'L', i - 1);
1972 return value_struct_elt (&bounds, {}, bound_name, NULL,
1973 _("Bad GNAT array descriptor bounds"));
1974 }
1975
1976 /* If BOUNDS is an array-bounds structure type, return the bit position
1977 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1978 bound, if WHICH is 1. The first bound is I=1. */
1979
1980 static int
desc_bound_bitpos(struct type * type,int i,int which)1981 desc_bound_bitpos (struct type *type, int i, int which)
1982 {
1983 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1984 }
1985
1986 /* If BOUNDS is an array-bounds structure type, return the bit field size
1987 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1988 bound, if WHICH is 1. The first bound is I=1. */
1989
1990 static int
desc_bound_bitsize(struct type * type,int i,int which)1991 desc_bound_bitsize (struct type *type, int i, int which)
1992 {
1993 type = desc_base_type (type);
1994
1995 if (type->field (2 * i + which - 2).bitsize () > 0)
1996 return type->field (2 * i + which - 2).bitsize ();
1997 else
1998 return 8 * type->field (2 * i + which - 2).type ()->length ();
1999 }
2000
2001 /* If TYPE is the type of an array-bounds structure, the type of its
2002 Ith bound (numbering from 1). Otherwise, NULL. */
2003
2004 static struct type *
desc_index_type(struct type * type,int i)2005 desc_index_type (struct type *type, int i)
2006 {
2007 type = desc_base_type (type);
2008
2009 if (type->code () == TYPE_CODE_STRUCT)
2010 {
2011 char bound_name[20];
2012 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2013 return lookup_struct_elt_type (type, bound_name, 1);
2014 }
2015 else
2016 return NULL;
2017 }
2018
2019 /* The number of index positions in the array-bounds type TYPE.
2020 Return 0 if TYPE is NULL. */
2021
2022 static int
desc_arity(struct type * type)2023 desc_arity (struct type *type)
2024 {
2025 type = desc_base_type (type);
2026
2027 if (type != NULL)
2028 return type->num_fields () / 2;
2029 return 0;
2030 }
2031
2032 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2033 an array descriptor type (representing an unconstrained array
2034 type). */
2035
2036 static int
ada_is_direct_array_type(struct type * type)2037 ada_is_direct_array_type (struct type *type)
2038 {
2039 if (type == NULL)
2040 return 0;
2041 type = ada_check_typedef (type);
2042 return (type->code () == TYPE_CODE_ARRAY
2043 || ada_is_array_descriptor_type (type));
2044 }
2045
2046 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2047 * to one. */
2048
2049 static int
ada_is_array_type(struct type * type)2050 ada_is_array_type (struct type *type)
2051 {
2052 while (type != NULL
2053 && (type->code () == TYPE_CODE_PTR
2054 || type->code () == TYPE_CODE_REF))
2055 type = type->target_type ();
2056 return ada_is_direct_array_type (type);
2057 }
2058
2059 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2060
2061 int
ada_is_simple_array_type(struct type * type)2062 ada_is_simple_array_type (struct type *type)
2063 {
2064 if (type == NULL)
2065 return 0;
2066 type = ada_check_typedef (type);
2067 return (type->code () == TYPE_CODE_ARRAY
2068 || (type->code () == TYPE_CODE_PTR
2069 && (ada_check_typedef (type->target_type ())->code ()
2070 == TYPE_CODE_ARRAY)));
2071 }
2072
2073 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2074
2075 int
ada_is_array_descriptor_type(struct type * type)2076 ada_is_array_descriptor_type (struct type *type)
2077 {
2078 struct type *data_type = desc_data_target_type (type);
2079
2080 if (type == NULL)
2081 return 0;
2082 type = ada_check_typedef (type);
2083 return (data_type != NULL
2084 && data_type->code () == TYPE_CODE_ARRAY
2085 && desc_arity (desc_bounds_type (type)) > 0);
2086 }
2087
2088 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2089 (fat pointer) returns the type of the array data described---specifically,
2090 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2091 in from the descriptor; otherwise, they are left unspecified. If
2092 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2093 returns NULL. The result is simply the type of ARR if ARR is not
2094 a descriptor. */
2095
2096 static struct type *
ada_type_of_array(struct value * arr,int bounds)2097 ada_type_of_array (struct value *arr, int bounds)
2098 {
2099 if (ada_is_constrained_packed_array_type (arr->type ()))
2100 return decode_constrained_packed_array_type (arr->type ());
2101
2102 if (!ada_is_array_descriptor_type (arr->type ()))
2103 return arr->type ();
2104
2105 if (!bounds)
2106 {
2107 struct type *array_type =
2108 ada_check_typedef (desc_data_target_type (arr->type ()));
2109
2110 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2111 array_type->field (0).set_bitsize
2112 (decode_packed_array_bitsize (arr->type ()));
2113
2114 return array_type;
2115 }
2116 else
2117 {
2118 struct type *elt_type;
2119 int arity;
2120 struct value *descriptor;
2121
2122 elt_type = ada_array_element_type (arr->type (), -1);
2123 arity = ada_array_arity (arr->type ());
2124
2125 if (elt_type == NULL || arity == 0)
2126 return ada_check_typedef (arr->type ());
2127
2128 descriptor = desc_bounds (arr);
2129 if (value_as_long (descriptor) == 0)
2130 return NULL;
2131 while (arity > 0)
2132 {
2133 type_allocator alloc (arr->type ());
2134 struct value *low = desc_one_bound (descriptor, arity, 0);
2135 struct value *high = desc_one_bound (descriptor, arity, 1);
2136
2137 arity -= 1;
2138 struct type *range_type
2139 = create_static_range_type (alloc, low->type (),
2140 longest_to_int (value_as_long (low)),
2141 longest_to_int (value_as_long (high)));
2142 elt_type = create_array_type (alloc, elt_type, range_type);
2143 INIT_GNAT_SPECIFIC (elt_type);
2144
2145 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2146 {
2147 /* We need to store the element packed bitsize, as well as
2148 recompute the array size, because it was previously
2149 computed based on the unpacked element size. */
2150 LONGEST lo = value_as_long (low);
2151 LONGEST hi = value_as_long (high);
2152
2153 elt_type->field (0).set_bitsize
2154 (decode_packed_array_bitsize (arr->type ()));
2155
2156 /* If the array has no element, then the size is already
2157 zero, and does not need to be recomputed. */
2158 if (lo < hi)
2159 {
2160 int array_bitsize =
2161 (hi - lo + 1) * elt_type->field (0).bitsize ();
2162
2163 elt_type->set_length ((array_bitsize + 7) / 8);
2164 }
2165 }
2166 }
2167
2168 return lookup_pointer_type (elt_type);
2169 }
2170 }
2171
2172 /* If ARR does not represent an array, returns ARR unchanged.
2173 Otherwise, returns either a standard GDB array with bounds set
2174 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2175 GDB array. Returns NULL if ARR is a null fat pointer. */
2176
2177 struct value *
ada_coerce_to_simple_array_ptr(struct value * arr)2178 ada_coerce_to_simple_array_ptr (struct value *arr)
2179 {
2180 if (ada_is_array_descriptor_type (arr->type ()))
2181 {
2182 struct type *arrType = ada_type_of_array (arr, 1);
2183
2184 if (arrType == NULL)
2185 return NULL;
2186 return value_cast (arrType, desc_data (arr)->copy ());
2187 }
2188 else if (ada_is_constrained_packed_array_type (arr->type ()))
2189 return decode_constrained_packed_array (arr);
2190 else
2191 return arr;
2192 }
2193
2194 /* If ARR does not represent an array, returns ARR unchanged.
2195 Otherwise, returns a standard GDB array describing ARR (which may
2196 be ARR itself if it already is in the proper form). */
2197
2198 struct value *
ada_coerce_to_simple_array(struct value * arr)2199 ada_coerce_to_simple_array (struct value *arr)
2200 {
2201 if (ada_is_array_descriptor_type (arr->type ()))
2202 {
2203 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2204
2205 if (arrVal == NULL)
2206 error (_("Bounds unavailable for null array pointer."));
2207 return value_ind (arrVal);
2208 }
2209 else if (ada_is_constrained_packed_array_type (arr->type ()))
2210 return decode_constrained_packed_array (arr);
2211 else
2212 return arr;
2213 }
2214
2215 /* If TYPE represents a GNAT array type, return it translated to an
2216 ordinary GDB array type (possibly with BITSIZE fields indicating
2217 packing). For other types, is the identity. */
2218
2219 struct type *
ada_coerce_to_simple_array_type(struct type * type)2220 ada_coerce_to_simple_array_type (struct type *type)
2221 {
2222 if (ada_is_constrained_packed_array_type (type))
2223 return decode_constrained_packed_array_type (type);
2224
2225 if (ada_is_array_descriptor_type (type))
2226 return ada_check_typedef (desc_data_target_type (type));
2227
2228 return type;
2229 }
2230
2231 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2232
2233 static int
ada_is_gnat_encoded_packed_array_type(struct type * type)2234 ada_is_gnat_encoded_packed_array_type (struct type *type)
2235 {
2236 if (type == NULL)
2237 return 0;
2238 type = desc_base_type (type);
2239 type = ada_check_typedef (type);
2240 return
2241 ada_type_name (type) != NULL
2242 && strstr (ada_type_name (type), "___XP") != NULL;
2243 }
2244
2245 /* Non-zero iff TYPE represents a standard GNAT constrained
2246 packed-array type. */
2247
2248 int
ada_is_constrained_packed_array_type(struct type * type)2249 ada_is_constrained_packed_array_type (struct type *type)
2250 {
2251 return ada_is_gnat_encoded_packed_array_type (type)
2252 && !ada_is_array_descriptor_type (type);
2253 }
2254
2255 /* Non-zero iff TYPE represents an array descriptor for a
2256 unconstrained packed-array type. */
2257
2258 static int
ada_is_unconstrained_packed_array_type(struct type * type)2259 ada_is_unconstrained_packed_array_type (struct type *type)
2260 {
2261 if (!ada_is_array_descriptor_type (type))
2262 return 0;
2263
2264 if (ada_is_gnat_encoded_packed_array_type (type))
2265 return 1;
2266
2267 /* If we saw GNAT encodings, then the above code is sufficient.
2268 However, with minimal encodings, we will just have a thick
2269 pointer instead. */
2270 if (is_thick_pntr (type))
2271 {
2272 type = desc_base_type (type);
2273 /* The structure's first field is a pointer to an array, so this
2274 fetches the array type. */
2275 type = type->field (0).type ()->target_type ();
2276 if (type->code () == TYPE_CODE_TYPEDEF)
2277 type = ada_typedef_target_type (type);
2278 /* Now we can see if the array elements are packed. */
2279 return type->field (0).bitsize () > 0;
2280 }
2281
2282 return 0;
2283 }
2284
2285 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2286 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2287
2288 static bool
ada_is_any_packed_array_type(struct type * type)2289 ada_is_any_packed_array_type (struct type *type)
2290 {
2291 return (ada_is_constrained_packed_array_type (type)
2292 || (type->code () == TYPE_CODE_ARRAY
2293 && type->field (0).bitsize () % 8 != 0));
2294 }
2295
2296 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2297 return the size of its elements in bits. */
2298
2299 static long
decode_packed_array_bitsize(struct type * type)2300 decode_packed_array_bitsize (struct type *type)
2301 {
2302 const char *raw_name;
2303 const char *tail;
2304 long bits;
2305
2306 /* Access to arrays implemented as fat pointers are encoded as a typedef
2307 of the fat pointer type. We need the name of the fat pointer type
2308 to do the decoding, so strip the typedef layer. */
2309 if (type->code () == TYPE_CODE_TYPEDEF)
2310 type = ada_typedef_target_type (type);
2311
2312 raw_name = ada_type_name (ada_check_typedef (type));
2313 if (!raw_name)
2314 raw_name = ada_type_name (desc_base_type (type));
2315
2316 if (!raw_name)
2317 return 0;
2318
2319 tail = strstr (raw_name, "___XP");
2320 if (tail == nullptr)
2321 {
2322 gdb_assert (is_thick_pntr (type));
2323 /* The structure's first field is a pointer to an array, so this
2324 fetches the array type. */
2325 type = type->field (0).type ()->target_type ();
2326 /* Now we can see if the array elements are packed. */
2327 return type->field (0).bitsize ();
2328 }
2329
2330 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2331 {
2332 lim_warning
2333 (_("could not understand bit size information on packed array"));
2334 return 0;
2335 }
2336
2337 return bits;
2338 }
2339
2340 /* Given that TYPE is a standard GDB array type with all bounds filled
2341 in, and that the element size of its ultimate scalar constituents
2342 (that is, either its elements, or, if it is an array of arrays, its
2343 elements' elements, etc.) is *ELT_BITS, return an identical type,
2344 but with the bit sizes of its elements (and those of any
2345 constituent arrays) recorded in the BITSIZE components of its
2346 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2347 in bits.
2348
2349 Note that, for arrays whose index type has an XA encoding where
2350 a bound references a record discriminant, getting that discriminant,
2351 and therefore the actual value of that bound, is not possible
2352 because none of the given parameters gives us access to the record.
2353 This function assumes that it is OK in the context where it is being
2354 used to return an array whose bounds are still dynamic and where
2355 the length is arbitrary. */
2356
2357 static struct type *
constrained_packed_array_type(struct type * type,long * elt_bits)2358 constrained_packed_array_type (struct type *type, long *elt_bits)
2359 {
2360 struct type *new_elt_type;
2361 struct type *new_type;
2362 struct type *index_type_desc;
2363 struct type *index_type;
2364 LONGEST low_bound, high_bound;
2365
2366 type = ada_check_typedef (type);
2367 if (type->code () != TYPE_CODE_ARRAY)
2368 return type;
2369
2370 index_type_desc = ada_find_parallel_type (type, "___XA");
2371 if (index_type_desc)
2372 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2373 NULL);
2374 else
2375 index_type = type->index_type ();
2376
2377 type_allocator alloc (type);
2378 new_elt_type =
2379 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2380 elt_bits);
2381 new_type = create_array_type (alloc, new_elt_type, index_type);
2382 new_type->field (0).set_bitsize (*elt_bits);
2383 new_type->set_name (ada_type_name (type));
2384
2385 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2386 && is_dynamic_type (check_typedef (index_type)))
2387 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2388 low_bound = high_bound = 0;
2389 if (high_bound < low_bound)
2390 {
2391 *elt_bits = 0;
2392 new_type->set_length (0);
2393 }
2394 else
2395 {
2396 *elt_bits *= (high_bound - low_bound + 1);
2397 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2398 }
2399
2400 new_type->set_is_fixed_instance (true);
2401 return new_type;
2402 }
2403
2404 /* The array type encoded by TYPE, where
2405 ada_is_constrained_packed_array_type (TYPE). */
2406
2407 static struct type *
decode_constrained_packed_array_type(struct type * type)2408 decode_constrained_packed_array_type (struct type *type)
2409 {
2410 const char *raw_name = ada_type_name (ada_check_typedef (type));
2411 char *name;
2412 const char *tail;
2413 struct type *shadow_type;
2414 long bits;
2415
2416 if (!raw_name)
2417 raw_name = ada_type_name (desc_base_type (type));
2418
2419 if (!raw_name)
2420 return NULL;
2421
2422 name = (char *) alloca (strlen (raw_name) + 1);
2423 tail = strstr (raw_name, "___XP");
2424 type = desc_base_type (type);
2425
2426 memcpy (name, raw_name, tail - raw_name);
2427 name[tail - raw_name] = '\000';
2428
2429 shadow_type = ada_find_parallel_type_with_name (type, name);
2430
2431 if (shadow_type == NULL)
2432 {
2433 lim_warning (_("could not find bounds information on packed array"));
2434 return NULL;
2435 }
2436 shadow_type = check_typedef (shadow_type);
2437
2438 if (shadow_type->code () != TYPE_CODE_ARRAY)
2439 {
2440 lim_warning (_("could not understand bounds "
2441 "information on packed array"));
2442 return NULL;
2443 }
2444
2445 bits = decode_packed_array_bitsize (type);
2446 return constrained_packed_array_type (shadow_type, &bits);
2447 }
2448
2449 /* Helper function for decode_constrained_packed_array. Set the field
2450 bitsize on a series of packed arrays. Returns the number of
2451 elements in TYPE. */
2452
2453 static LONGEST
recursively_update_array_bitsize(struct type * type)2454 recursively_update_array_bitsize (struct type *type)
2455 {
2456 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2457
2458 LONGEST low, high;
2459 if (!get_discrete_bounds (type->index_type (), &low, &high)
2460 || low > high)
2461 return 0;
2462 LONGEST our_len = high - low + 1;
2463
2464 struct type *elt_type = type->target_type ();
2465 if (elt_type->code () == TYPE_CODE_ARRAY)
2466 {
2467 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2468 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
2469 type->field (0).set_bitsize (elt_bitsize);
2470
2471 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2472 / HOST_CHAR_BIT));
2473 }
2474
2475 return our_len;
2476 }
2477
2478 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2479 array, returns a simple array that denotes that array. Its type is a
2480 standard GDB array type except that the BITSIZEs of the array
2481 target types are set to the number of bits in each element, and the
2482 type length is set appropriately. */
2483
2484 static struct value *
decode_constrained_packed_array(struct value * arr)2485 decode_constrained_packed_array (struct value *arr)
2486 {
2487 struct type *type;
2488
2489 /* If our value is a pointer, then dereference it. Likewise if
2490 the value is a reference. Make sure that this operation does not
2491 cause the target type to be fixed, as this would indirectly cause
2492 this array to be decoded. The rest of the routine assumes that
2493 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2494 and "value_ind" routines to perform the dereferencing, as opposed
2495 to using "ada_coerce_ref" or "ada_value_ind". */
2496 arr = coerce_ref (arr);
2497 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2498 arr = value_ind (arr);
2499
2500 type = decode_constrained_packed_array_type (arr->type ());
2501 if (type == NULL)
2502 {
2503 error (_("can't unpack array"));
2504 return NULL;
2505 }
2506
2507 /* Decoding the packed array type could not correctly set the field
2508 bitsizes for any dimension except the innermost, because the
2509 bounds may be variable and were not passed to that function. So,
2510 we further resolve the array bounds here and then update the
2511 sizes. */
2512 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2513 CORE_ADDR address = arr->address ();
2514 gdb::array_view<const gdb_byte> view
2515 = gdb::make_array_view (valaddr, type->length ());
2516 type = resolve_dynamic_type (type, view, address);
2517 recursively_update_array_bitsize (type);
2518
2519 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2520 && ada_is_modular_type (arr->type ()))
2521 {
2522 /* This is a (right-justified) modular type representing a packed
2523 array with no wrapper. In order to interpret the value through
2524 the (left-justified) packed array type we just built, we must
2525 first left-justify it. */
2526 int bit_size, bit_pos;
2527 ULONGEST mod;
2528
2529 mod = ada_modulus (arr->type ()) - 1;
2530 bit_size = 0;
2531 while (mod > 0)
2532 {
2533 bit_size += 1;
2534 mod >>= 1;
2535 }
2536 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2537 arr = ada_value_primitive_packed_val (arr, NULL,
2538 bit_pos / HOST_CHAR_BIT,
2539 bit_pos % HOST_CHAR_BIT,
2540 bit_size,
2541 type);
2542 }
2543
2544 return coerce_unspec_val_to_type (arr, type);
2545 }
2546
2547
2548 /* The value of the element of packed array ARR at the ARITY indices
2549 given in IND. ARR must be a simple array. */
2550
2551 static struct value *
value_subscript_packed(struct value * arr,int arity,struct value ** ind)2552 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2553 {
2554 int i;
2555 int bits, elt_off, bit_off;
2556 long elt_total_bit_offset;
2557 struct type *elt_type;
2558 struct value *v;
2559
2560 bits = 0;
2561 elt_total_bit_offset = 0;
2562 elt_type = ada_check_typedef (arr->type ());
2563 for (i = 0; i < arity; i += 1)
2564 {
2565 if (elt_type->code () != TYPE_CODE_ARRAY
2566 || elt_type->field (0).bitsize () == 0)
2567 error
2568 (_("attempt to do packed indexing of "
2569 "something other than a packed array"));
2570 else
2571 {
2572 struct type *range_type = elt_type->index_type ();
2573 LONGEST lowerbound, upperbound;
2574 LONGEST idx;
2575
2576 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2577 {
2578 lim_warning (_("don't know bounds of array"));
2579 lowerbound = upperbound = 0;
2580 }
2581
2582 idx = pos_atr (ind[i]);
2583 if (idx < lowerbound || idx > upperbound)
2584 lim_warning (_("packed array index %ld out of bounds"),
2585 (long) idx);
2586 bits = elt_type->field (0).bitsize ();
2587 elt_total_bit_offset += (idx - lowerbound) * bits;
2588 elt_type = ada_check_typedef (elt_type->target_type ());
2589 }
2590 }
2591 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2592 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2593
2594 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2595 bits, elt_type);
2596 return v;
2597 }
2598
2599 /* Non-zero iff TYPE includes negative integer values. */
2600
2601 static int
has_negatives(struct type * type)2602 has_negatives (struct type *type)
2603 {
2604 switch (type->code ())
2605 {
2606 default:
2607 return 0;
2608 case TYPE_CODE_INT:
2609 return !type->is_unsigned ();
2610 case TYPE_CODE_RANGE:
2611 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2612 }
2613 }
2614
2615 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2616 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2617 the unpacked buffer.
2618
2619 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2620 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2621
2622 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2623 zero otherwise.
2624
2625 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2626
2627 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2628
2629 static void
ada_unpack_from_contents(const gdb_byte * src,int bit_offset,int bit_size,gdb_byte * unpacked,int unpacked_len,int is_big_endian,int is_signed_type,int is_scalar)2630 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2631 gdb_byte *unpacked, int unpacked_len,
2632 int is_big_endian, int is_signed_type,
2633 int is_scalar)
2634 {
2635 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2636 int src_idx; /* Index into the source area */
2637 int src_bytes_left; /* Number of source bytes left to process. */
2638 int srcBitsLeft; /* Number of source bits left to move */
2639 int unusedLS; /* Number of bits in next significant
2640 byte of source that are unused */
2641
2642 int unpacked_idx; /* Index into the unpacked buffer */
2643 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2644
2645 unsigned long accum; /* Staging area for bits being transferred */
2646 int accumSize; /* Number of meaningful bits in accum */
2647 unsigned char sign;
2648
2649 /* Transmit bytes from least to most significant; delta is the direction
2650 the indices move. */
2651 int delta = is_big_endian ? -1 : 1;
2652
2653 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2654 bits from SRC. .*/
2655 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2656 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2657 bit_size, unpacked_len);
2658
2659 srcBitsLeft = bit_size;
2660 src_bytes_left = src_len;
2661 unpacked_bytes_left = unpacked_len;
2662 sign = 0;
2663
2664 if (is_big_endian)
2665 {
2666 src_idx = src_len - 1;
2667 if (is_signed_type
2668 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2669 sign = ~0;
2670
2671 unusedLS =
2672 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2673 % HOST_CHAR_BIT;
2674
2675 if (is_scalar)
2676 {
2677 accumSize = 0;
2678 unpacked_idx = unpacked_len - 1;
2679 }
2680 else
2681 {
2682 /* Non-scalar values must be aligned at a byte boundary... */
2683 accumSize =
2684 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2685 /* ... And are placed at the beginning (most-significant) bytes
2686 of the target. */
2687 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2688 unpacked_bytes_left = unpacked_idx + 1;
2689 }
2690 }
2691 else
2692 {
2693 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2694
2695 src_idx = unpacked_idx = 0;
2696 unusedLS = bit_offset;
2697 accumSize = 0;
2698
2699 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2700 sign = ~0;
2701 }
2702
2703 accum = 0;
2704 while (src_bytes_left > 0)
2705 {
2706 /* Mask for removing bits of the next source byte that are not
2707 part of the value. */
2708 unsigned int unusedMSMask =
2709 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2710 1;
2711 /* Sign-extend bits for this byte. */
2712 unsigned int signMask = sign & ~unusedMSMask;
2713
2714 accum |=
2715 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2716 accumSize += HOST_CHAR_BIT - unusedLS;
2717 if (accumSize >= HOST_CHAR_BIT)
2718 {
2719 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2720 accumSize -= HOST_CHAR_BIT;
2721 accum >>= HOST_CHAR_BIT;
2722 unpacked_bytes_left -= 1;
2723 unpacked_idx += delta;
2724 }
2725 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2726 unusedLS = 0;
2727 src_bytes_left -= 1;
2728 src_idx += delta;
2729 }
2730 while (unpacked_bytes_left > 0)
2731 {
2732 accum |= sign << accumSize;
2733 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2734 accumSize -= HOST_CHAR_BIT;
2735 if (accumSize < 0)
2736 accumSize = 0;
2737 accum >>= HOST_CHAR_BIT;
2738 unpacked_bytes_left -= 1;
2739 unpacked_idx += delta;
2740 }
2741 }
2742
2743 /* Create a new value of type TYPE from the contents of OBJ starting
2744 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2745 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2746 assigning through the result will set the field fetched from.
2747 VALADDR is ignored unless OBJ is NULL, in which case,
2748 VALADDR+OFFSET must address the start of storage containing the
2749 packed value. The value returned in this case is never an lval.
2750 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2751
2752 struct value *
ada_value_primitive_packed_val(struct value * obj,const gdb_byte * valaddr,long offset,int bit_offset,int bit_size,struct type * type)2753 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2754 long offset, int bit_offset, int bit_size,
2755 struct type *type)
2756 {
2757 struct value *v;
2758 const gdb_byte *src; /* First byte containing data to unpack */
2759 gdb_byte *unpacked;
2760 const int is_scalar = is_scalar_type (type);
2761 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2762 gdb::byte_vector staging;
2763
2764 type = ada_check_typedef (type);
2765
2766 if (obj == NULL)
2767 src = valaddr + offset;
2768 else
2769 src = obj->contents ().data () + offset;
2770
2771 if (is_dynamic_type (type))
2772 {
2773 /* The length of TYPE might by dynamic, so we need to resolve
2774 TYPE in order to know its actual size, which we then use
2775 to create the contents buffer of the value we return.
2776 The difficulty is that the data containing our object is
2777 packed, and therefore maybe not at a byte boundary. So, what
2778 we do, is unpack the data into a byte-aligned buffer, and then
2779 use that buffer as our object's value for resolving the type. */
2780 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2781 staging.resize (staging_len);
2782
2783 ada_unpack_from_contents (src, bit_offset, bit_size,
2784 staging.data (), staging.size (),
2785 is_big_endian, has_negatives (type),
2786 is_scalar);
2787 type = resolve_dynamic_type (type, staging, 0);
2788 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2789 {
2790 /* This happens when the length of the object is dynamic,
2791 and is actually smaller than the space reserved for it.
2792 For instance, in an array of variant records, the bit_size
2793 we're given is the array stride, which is constant and
2794 normally equal to the maximum size of its element.
2795 But, in reality, each element only actually spans a portion
2796 of that stride. */
2797 bit_size = type->length () * HOST_CHAR_BIT;
2798 }
2799 }
2800
2801 if (obj == NULL)
2802 {
2803 v = value::allocate (type);
2804 src = valaddr + offset;
2805 }
2806 else if (obj->lval () == lval_memory && obj->lazy ())
2807 {
2808 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2809 gdb_byte *buf;
2810
2811 v = value_at (type, obj->address () + offset);
2812 buf = (gdb_byte *) alloca (src_len);
2813 read_memory (v->address (), buf, src_len);
2814 src = buf;
2815 }
2816 else
2817 {
2818 v = value::allocate (type);
2819 src = obj->contents ().data () + offset;
2820 }
2821
2822 if (obj != NULL)
2823 {
2824 long new_offset = offset;
2825
2826 v->set_component_location (obj);
2827 v->set_bitpos (bit_offset + obj->bitpos ());
2828 v->set_bitsize (bit_size);
2829 if (v->bitpos () >= HOST_CHAR_BIT)
2830 {
2831 ++new_offset;
2832 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2833 }
2834 v->set_offset (new_offset);
2835
2836 /* Also set the parent value. This is needed when trying to
2837 assign a new value (in inferior memory). */
2838 v->set_parent (obj);
2839 }
2840 else
2841 v->set_bitsize (bit_size);
2842 unpacked = v->contents_writeable ().data ();
2843
2844 if (bit_size == 0)
2845 {
2846 memset (unpacked, 0, type->length ());
2847 return v;
2848 }
2849
2850 if (staging.size () == type->length ())
2851 {
2852 /* Small short-cut: If we've unpacked the data into a buffer
2853 of the same size as TYPE's length, then we can reuse that,
2854 instead of doing the unpacking again. */
2855 memcpy (unpacked, staging.data (), staging.size ());
2856 }
2857 else
2858 ada_unpack_from_contents (src, bit_offset, bit_size,
2859 unpacked, type->length (),
2860 is_big_endian, has_negatives (type), is_scalar);
2861
2862 return v;
2863 }
2864
2865 /* Store the contents of FROMVAL into the location of TOVAL.
2866 Return a new value with the location of TOVAL and contents of
2867 FROMVAL. Handles assignment into packed fields that have
2868 floating-point or non-scalar types. */
2869
2870 static struct value *
ada_value_assign(struct value * toval,struct value * fromval)2871 ada_value_assign (struct value *toval, struct value *fromval)
2872 {
2873 struct type *type = toval->type ();
2874 int bits = toval->bitsize ();
2875
2876 toval = ada_coerce_ref (toval);
2877 fromval = ada_coerce_ref (fromval);
2878
2879 if (ada_is_direct_array_type (toval->type ()))
2880 toval = ada_coerce_to_simple_array (toval);
2881 if (ada_is_direct_array_type (fromval->type ()))
2882 fromval = ada_coerce_to_simple_array (fromval);
2883
2884 if (!toval->deprecated_modifiable ())
2885 error (_("Left operand of assignment is not a modifiable lvalue."));
2886
2887 if (toval->lval () == lval_memory
2888 && bits > 0
2889 && (type->code () == TYPE_CODE_FLT
2890 || type->code () == TYPE_CODE_STRUCT))
2891 {
2892 int len = (toval->bitpos ()
2893 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2894 int from_size;
2895 gdb_byte *buffer = (gdb_byte *) alloca (len);
2896 struct value *val;
2897 CORE_ADDR to_addr = toval->address ();
2898
2899 if (type->code () == TYPE_CODE_FLT)
2900 fromval = value_cast (type, fromval);
2901
2902 read_memory (to_addr, buffer, len);
2903 from_size = fromval->bitsize ();
2904 if (from_size == 0)
2905 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2906
2907 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2908 ULONGEST from_offset = 0;
2909 if (is_big_endian && is_scalar_type (fromval->type ()))
2910 from_offset = from_size - bits;
2911 copy_bitwise (buffer, toval->bitpos (),
2912 fromval->contents ().data (), from_offset,
2913 bits, is_big_endian);
2914 write_memory_with_notification (to_addr, buffer, len);
2915
2916 val = toval->copy ();
2917 memcpy (val->contents_raw ().data (),
2918 fromval->contents ().data (),
2919 type->length ());
2920 val->deprecated_set_type (type);
2921
2922 return val;
2923 }
2924
2925 return value_assign (toval, fromval);
2926 }
2927
2928
2929 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2930 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2931 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2932 COMPONENT, and not the inferior's memory. The current contents
2933 of COMPONENT are ignored.
2934
2935 Although not part of the initial design, this function also works
2936 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2937 had a null address, and COMPONENT had an address which is equal to
2938 its offset inside CONTAINER. */
2939
2940 static void
value_assign_to_component(struct value * container,struct value * component,struct value * val)2941 value_assign_to_component (struct value *container, struct value *component,
2942 struct value *val)
2943 {
2944 LONGEST offset_in_container =
2945 (LONGEST) (component->address () - container->address ());
2946 int bit_offset_in_container =
2947 component->bitpos () - container->bitpos ();
2948 int bits;
2949
2950 val = value_cast (component->type (), val);
2951
2952 if (component->bitsize () == 0)
2953 bits = TARGET_CHAR_BIT * component->type ()->length ();
2954 else
2955 bits = component->bitsize ();
2956
2957 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2958 {
2959 int src_offset;
2960
2961 if (is_scalar_type (check_typedef (component->type ())))
2962 src_offset
2963 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2964 else
2965 src_offset = 0;
2966 copy_bitwise ((container->contents_writeable ().data ()
2967 + offset_in_container),
2968 container->bitpos () + bit_offset_in_container,
2969 val->contents ().data (), src_offset, bits, 1);
2970 }
2971 else
2972 copy_bitwise ((container->contents_writeable ().data ()
2973 + offset_in_container),
2974 container->bitpos () + bit_offset_in_container,
2975 val->contents ().data (), 0, bits, 0);
2976 }
2977
2978 /* Determine if TYPE is an access to an unconstrained array. */
2979
2980 bool
ada_is_access_to_unconstrained_array(struct type * type)2981 ada_is_access_to_unconstrained_array (struct type *type)
2982 {
2983 return (type->code () == TYPE_CODE_TYPEDEF
2984 && is_thick_pntr (ada_typedef_target_type (type)));
2985 }
2986
2987 /* The value of the element of array ARR at the ARITY indices given in IND.
2988 ARR may be either a simple array, GNAT array descriptor, or pointer
2989 thereto. */
2990
2991 struct value *
ada_value_subscript(struct value * arr,int arity,struct value ** ind)2992 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2993 {
2994 int k;
2995 struct value *elt;
2996 struct type *elt_type;
2997
2998 elt = ada_coerce_to_simple_array (arr);
2999
3000 elt_type = ada_check_typedef (elt->type ());
3001 if (elt_type->code () == TYPE_CODE_ARRAY
3002 && elt_type->field (0).bitsize () > 0)
3003 return value_subscript_packed (elt, arity, ind);
3004
3005 for (k = 0; k < arity; k += 1)
3006 {
3007 struct type *saved_elt_type = elt_type->target_type ();
3008
3009 if (elt_type->code () != TYPE_CODE_ARRAY)
3010 error (_("too many subscripts (%d expected)"), k);
3011
3012 elt = value_subscript (elt, pos_atr (ind[k]));
3013
3014 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3015 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3016 {
3017 /* The element is a typedef to an unconstrained array,
3018 except that the value_subscript call stripped the
3019 typedef layer. The typedef layer is GNAT's way to
3020 specify that the element is, at the source level, an
3021 access to the unconstrained array, rather than the
3022 unconstrained array. So, we need to restore that
3023 typedef layer, which we can do by forcing the element's
3024 type back to its original type. Otherwise, the returned
3025 value is going to be printed as the array, rather
3026 than as an access. Another symptom of the same issue
3027 would be that an expression trying to dereference the
3028 element would also be improperly rejected. */
3029 elt->deprecated_set_type (saved_elt_type);
3030 }
3031
3032 elt_type = ada_check_typedef (elt->type ());
3033 }
3034
3035 return elt;
3036 }
3037
3038 /* Assuming ARR is a pointer to a GDB array, the value of the element
3039 of *ARR at the ARITY indices given in IND.
3040 Does not read the entire array into memory.
3041
3042 Note: Unlike what one would expect, this function is used instead of
3043 ada_value_subscript for basically all non-packed array types. The reason
3044 for this is that a side effect of doing our own pointer arithmetics instead
3045 of relying on value_subscript is that there is no implicit typedef peeling.
3046 This is important for arrays of array accesses, where it allows us to
3047 preserve the fact that the array's element is an array access, where the
3048 access part os encoded in a typedef layer. */
3049
3050 static struct value *
ada_value_ptr_subscript(struct value * arr,int arity,struct value ** ind)3051 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3052 {
3053 int k;
3054 struct value *array_ind = ada_value_ind (arr);
3055 struct type *type
3056 = check_typedef (array_ind->enclosing_type ());
3057
3058 if (type->code () == TYPE_CODE_ARRAY
3059 && type->field (0).bitsize () > 0)
3060 return value_subscript_packed (array_ind, arity, ind);
3061
3062 for (k = 0; k < arity; k += 1)
3063 {
3064 LONGEST lwb, upb;
3065
3066 if (type->code () != TYPE_CODE_ARRAY)
3067 error (_("too many subscripts (%d expected)"), k);
3068 arr = value_cast (lookup_pointer_type (type->target_type ()),
3069 arr->copy ());
3070 get_discrete_bounds (type->index_type (), &lwb, &upb);
3071 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3072 type = type->target_type ();
3073 }
3074
3075 return value_ind (arr);
3076 }
3077
3078 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3079 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3080 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3081 this array is LOW, as per Ada rules. */
3082 static struct value *
ada_value_slice_from_ptr(struct value * array_ptr,struct type * type,int low,int high)3083 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3084 int low, int high)
3085 {
3086 struct type *type0 = ada_check_typedef (type);
3087 struct type *base_index_type = type0->index_type ()->target_type ();
3088 type_allocator alloc (base_index_type);
3089 struct type *index_type
3090 = create_static_range_type (alloc, base_index_type, low, high);
3091 struct type *slice_type = create_array_type_with_stride
3092 (alloc, type0->target_type (), index_type,
3093 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3094 type0->field (0).bitsize ());
3095 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3096 std::optional<LONGEST> base_low_pos, low_pos;
3097 CORE_ADDR base;
3098
3099 low_pos = discrete_position (base_index_type, low);
3100 base_low_pos = discrete_position (base_index_type, base_low);
3101
3102 if (!low_pos.has_value () || !base_low_pos.has_value ())
3103 {
3104 warning (_("unable to get positions in slice, use bounds instead"));
3105 low_pos = low;
3106 base_low_pos = base_low;
3107 }
3108
3109 ULONGEST stride = slice_type->field (0).bitsize () / 8;
3110 if (stride == 0)
3111 stride = type0->target_type ()->length ();
3112
3113 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3114 return value_at_lazy (slice_type, base);
3115 }
3116
3117
3118 static struct value *
ada_value_slice(struct value * array,int low,int high)3119 ada_value_slice (struct value *array, int low, int high)
3120 {
3121 struct type *type = ada_check_typedef (array->type ());
3122 struct type *base_index_type = type->index_type ()->target_type ();
3123 type_allocator alloc (type->index_type ());
3124 struct type *index_type
3125 = create_static_range_type (alloc, type->index_type (), low, high);
3126 struct type *slice_type = create_array_type_with_stride
3127 (alloc, type->target_type (), index_type,
3128 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3129 type->field (0).bitsize ());
3130 std::optional<LONGEST> low_pos, high_pos;
3131
3132
3133 low_pos = discrete_position (base_index_type, low);
3134 high_pos = discrete_position (base_index_type, high);
3135
3136 if (!low_pos.has_value () || !high_pos.has_value ())
3137 {
3138 warning (_("unable to get positions in slice, use bounds instead"));
3139 low_pos = low;
3140 high_pos = high;
3141 }
3142
3143 return value_cast (slice_type,
3144 value_slice (array, low, *high_pos - *low_pos + 1));
3145 }
3146
3147 /* If type is a record type in the form of a standard GNAT array
3148 descriptor, returns the number of dimensions for type. If arr is a
3149 simple array, returns the number of "array of"s that prefix its
3150 type designation. Otherwise, returns 0. */
3151
3152 int
ada_array_arity(struct type * type)3153 ada_array_arity (struct type *type)
3154 {
3155 int arity;
3156
3157 if (type == NULL)
3158 return 0;
3159
3160 type = desc_base_type (type);
3161
3162 arity = 0;
3163 if (type->code () == TYPE_CODE_STRUCT)
3164 return desc_arity (desc_bounds_type (type));
3165 else
3166 while (type->code () == TYPE_CODE_ARRAY)
3167 {
3168 arity += 1;
3169 type = ada_check_typedef (type->target_type ());
3170 }
3171
3172 return arity;
3173 }
3174
3175 /* If TYPE is a record type in the form of a standard GNAT array
3176 descriptor or a simple array type, returns the element type for
3177 TYPE after indexing by NINDICES indices, or by all indices if
3178 NINDICES is -1. Otherwise, returns NULL. */
3179
3180 struct type *
ada_array_element_type(struct type * type,int nindices)3181 ada_array_element_type (struct type *type, int nindices)
3182 {
3183 type = desc_base_type (type);
3184
3185 if (type->code () == TYPE_CODE_STRUCT)
3186 {
3187 int k;
3188 struct type *p_array_type;
3189
3190 p_array_type = desc_data_target_type (type);
3191
3192 k = ada_array_arity (type);
3193 if (k == 0)
3194 return NULL;
3195
3196 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3197 if (nindices >= 0 && k > nindices)
3198 k = nindices;
3199 while (k > 0 && p_array_type != NULL)
3200 {
3201 p_array_type = ada_check_typedef (p_array_type->target_type ());
3202 k -= 1;
3203 }
3204 return p_array_type;
3205 }
3206 else if (type->code () == TYPE_CODE_ARRAY)
3207 {
3208 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3209 {
3210 type = type->target_type ();
3211 /* A multi-dimensional array is represented using a sequence
3212 of array types. If one of these types has a name, then
3213 it is not another dimension of the outer array, but
3214 rather the element type of the outermost array. */
3215 if (type->name () != nullptr)
3216 break;
3217 nindices -= 1;
3218 }
3219 return type;
3220 }
3221
3222 return NULL;
3223 }
3224
3225 /* See ada-lang.h. */
3226
3227 struct type *
ada_index_type(struct type * type,int n,const char * name)3228 ada_index_type (struct type *type, int n, const char *name)
3229 {
3230 struct type *result_type;
3231
3232 type = desc_base_type (type);
3233
3234 if (n < 0 || n > ada_array_arity (type))
3235 error (_("invalid dimension number to '%s"), name);
3236
3237 if (ada_is_simple_array_type (type))
3238 {
3239 int i;
3240
3241 for (i = 1; i < n; i += 1)
3242 {
3243 type = ada_check_typedef (type);
3244 type = type->target_type ();
3245 }
3246 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3247 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3248 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3249 perhaps stabsread.c would make more sense. */
3250 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3251 result_type = NULL;
3252 }
3253 else
3254 {
3255 result_type = desc_index_type (desc_bounds_type (type), n);
3256 if (result_type == NULL)
3257 error (_("attempt to take bound of something that is not an array"));
3258 }
3259
3260 return result_type;
3261 }
3262
3263 /* Given that arr is an array type, returns the lower bound of the
3264 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3265 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3266 array-descriptor type. It works for other arrays with bounds supplied
3267 by run-time quantities other than discriminants. */
3268
3269 static LONGEST
ada_array_bound_from_type(struct type * arr_type,int n,int which)3270 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3271 {
3272 struct type *type, *index_type_desc, *index_type;
3273 int i;
3274
3275 gdb_assert (which == 0 || which == 1);
3276
3277 if (ada_is_constrained_packed_array_type (arr_type))
3278 arr_type = decode_constrained_packed_array_type (arr_type);
3279
3280 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3281 return - which;
3282
3283 if (arr_type->code () == TYPE_CODE_PTR)
3284 type = arr_type->target_type ();
3285 else
3286 type = arr_type;
3287
3288 if (type->is_fixed_instance ())
3289 {
3290 /* The array has already been fixed, so we do not need to
3291 check the parallel ___XA type again. That encoding has
3292 already been applied, so ignore it now. */
3293 index_type_desc = NULL;
3294 }
3295 else
3296 {
3297 index_type_desc = ada_find_parallel_type (type, "___XA");
3298 ada_fixup_array_indexes_type (index_type_desc);
3299 }
3300
3301 if (index_type_desc != NULL)
3302 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3303 NULL);
3304 else
3305 {
3306 struct type *elt_type = check_typedef (type);
3307
3308 for (i = 1; i < n; i++)
3309 elt_type = check_typedef (elt_type->target_type ());
3310
3311 index_type = elt_type->index_type ();
3312 }
3313
3314 return (which == 0
3315 ? ada_discrete_type_low_bound (index_type)
3316 : ada_discrete_type_high_bound (index_type));
3317 }
3318
3319 /* Given that arr is an array value, returns the lower bound of the
3320 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3321 WHICH is 1. This routine will also work for arrays with bounds
3322 supplied by run-time quantities other than discriminants. */
3323
3324 static LONGEST
ada_array_bound(struct value * arr,int n,int which)3325 ada_array_bound (struct value *arr, int n, int which)
3326 {
3327 struct type *arr_type;
3328
3329 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3330 arr = value_ind (arr);
3331 arr_type = arr->enclosing_type ();
3332
3333 if (ada_is_constrained_packed_array_type (arr_type))
3334 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3335 else if (ada_is_simple_array_type (arr_type))
3336 return ada_array_bound_from_type (arr_type, n, which);
3337 else
3338 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3339 }
3340
3341 /* Given that arr is an array value, returns the length of the
3342 nth index. This routine will also work for arrays with bounds
3343 supplied by run-time quantities other than discriminants.
3344 Does not work for arrays indexed by enumeration types with representation
3345 clauses at the moment. */
3346
3347 static LONGEST
ada_array_length(struct value * arr,int n)3348 ada_array_length (struct value *arr, int n)
3349 {
3350 struct type *arr_type, *index_type;
3351 int low, high;
3352
3353 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3354 arr = value_ind (arr);
3355 arr_type = arr->enclosing_type ();
3356
3357 if (ada_is_constrained_packed_array_type (arr_type))
3358 return ada_array_length (decode_constrained_packed_array (arr), n);
3359
3360 if (ada_is_simple_array_type (arr_type))
3361 {
3362 low = ada_array_bound_from_type (arr_type, n, 0);
3363 high = ada_array_bound_from_type (arr_type, n, 1);
3364 }
3365 else
3366 {
3367 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3368 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3369 }
3370
3371 arr_type = check_typedef (arr_type);
3372 index_type = ada_index_type (arr_type, n, "length");
3373 if (index_type != NULL)
3374 {
3375 struct type *base_type;
3376 if (index_type->code () == TYPE_CODE_RANGE)
3377 base_type = index_type->target_type ();
3378 else
3379 base_type = index_type;
3380
3381 low = pos_atr (value_from_longest (base_type, low));
3382 high = pos_atr (value_from_longest (base_type, high));
3383 }
3384 return high - low + 1;
3385 }
3386
3387 /* An array whose type is that of ARR_TYPE (an array type), with
3388 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3389 less than LOW, then LOW-1 is used. */
3390
3391 static struct value *
empty_array(struct type * arr_type,int low,int high)3392 empty_array (struct type *arr_type, int low, int high)
3393 {
3394 struct type *arr_type0 = ada_check_typedef (arr_type);
3395 type_allocator alloc (arr_type0->index_type ()->target_type ());
3396 struct type *index_type
3397 = create_static_range_type
3398 (alloc, arr_type0->index_type ()->target_type (), low,
3399 high < low ? low - 1 : high);
3400 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3401
3402 return value::allocate (create_array_type (alloc, elt_type, index_type));
3403 }
3404
3405
3406 /* Name resolution */
3407
3408 /* The "decoded" name for the user-definable Ada operator corresponding
3409 to OP. */
3410
3411 static const char *
ada_decoded_op_name(enum exp_opcode op)3412 ada_decoded_op_name (enum exp_opcode op)
3413 {
3414 int i;
3415
3416 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3417 {
3418 if (ada_opname_table[i].op == op)
3419 return ada_opname_table[i].decoded;
3420 }
3421 error (_("Could not find operator name for opcode"));
3422 }
3423
3424 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3425 in a listing of choices during disambiguation (see sort_choices, below).
3426 The idea is that overloadings of a subprogram name from the
3427 same package should sort in their source order. We settle for ordering
3428 such symbols by their trailing number (__N or $N). */
3429
3430 static int
encoded_ordered_before(const char * N0,const char * N1)3431 encoded_ordered_before (const char *N0, const char *N1)
3432 {
3433 if (N1 == NULL)
3434 return 0;
3435 else if (N0 == NULL)
3436 return 1;
3437 else
3438 {
3439 int k0, k1;
3440
3441 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3442 ;
3443 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3444 ;
3445 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3446 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3447 {
3448 int n0, n1;
3449
3450 n0 = k0;
3451 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3452 n0 -= 1;
3453 n1 = k1;
3454 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3455 n1 -= 1;
3456 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3457 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3458 }
3459 return (strcmp (N0, N1) < 0);
3460 }
3461 }
3462
3463 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3464 encoded names. */
3465
3466 static void
sort_choices(struct block_symbol syms[],int nsyms)3467 sort_choices (struct block_symbol syms[], int nsyms)
3468 {
3469 int i;
3470
3471 for (i = 1; i < nsyms; i += 1)
3472 {
3473 struct block_symbol sym = syms[i];
3474 int j;
3475
3476 for (j = i - 1; j >= 0; j -= 1)
3477 {
3478 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3479 sym.symbol->linkage_name ()))
3480 break;
3481 syms[j + 1] = syms[j];
3482 }
3483 syms[j + 1] = sym;
3484 }
3485 }
3486
3487 /* Whether GDB should display formals and return types for functions in the
3488 overloads selection menu. */
3489 static bool print_signatures = true;
3490
3491 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3492 all but functions, the signature is just the name of the symbol. For
3493 functions, this is the name of the function, the list of types for formals
3494 and the return type (if any). */
3495
3496 static void
ada_print_symbol_signature(struct ui_file * stream,struct symbol * sym,const struct type_print_options * flags)3497 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3498 const struct type_print_options *flags)
3499 {
3500 struct type *type = sym->type ();
3501
3502 gdb_printf (stream, "%s", sym->print_name ());
3503 if (!print_signatures
3504 || type == NULL
3505 || type->code () != TYPE_CODE_FUNC)
3506 return;
3507
3508 if (type->num_fields () > 0)
3509 {
3510 int i;
3511
3512 gdb_printf (stream, " (");
3513 for (i = 0; i < type->num_fields (); ++i)
3514 {
3515 if (i > 0)
3516 gdb_printf (stream, "; ");
3517 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3518 flags);
3519 }
3520 gdb_printf (stream, ")");
3521 }
3522 if (type->target_type () != NULL
3523 && type->target_type ()->code () != TYPE_CODE_VOID)
3524 {
3525 gdb_printf (stream, " return ");
3526 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3527 }
3528 }
3529
3530 /* Read and validate a set of numeric choices from the user in the
3531 range 0 .. N_CHOICES-1. Place the results in increasing
3532 order in CHOICES[0 .. N-1], and return N.
3533
3534 The user types choices as a sequence of numbers on one line
3535 separated by blanks, encoding them as follows:
3536
3537 + A choice of 0 means to cancel the selection, throwing an error.
3538 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3539 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3540
3541 The user is not allowed to choose more than MAX_RESULTS values.
3542
3543 ANNOTATION_SUFFIX, if present, is used to annotate the input
3544 prompts (for use with the -f switch). */
3545
3546 static int
get_selections(int * choices,int n_choices,int max_results,int is_all_choice,const char * annotation_suffix)3547 get_selections (int *choices, int n_choices, int max_results,
3548 int is_all_choice, const char *annotation_suffix)
3549 {
3550 const char *args;
3551 const char *prompt;
3552 int n_chosen;
3553 int first_choice = is_all_choice ? 2 : 1;
3554
3555 prompt = getenv ("PS2");
3556 if (prompt == NULL)
3557 prompt = "> ";
3558
3559 std::string buffer;
3560 args = command_line_input (buffer, prompt, annotation_suffix);
3561
3562 if (args == NULL)
3563 error_no_arg (_("one or more choice numbers"));
3564
3565 n_chosen = 0;
3566
3567 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3568 order, as given in args. Choices are validated. */
3569 while (1)
3570 {
3571 char *args2;
3572 int choice, j;
3573
3574 args = skip_spaces (args);
3575 if (*args == '\0' && n_chosen == 0)
3576 error_no_arg (_("one or more choice numbers"));
3577 else if (*args == '\0')
3578 break;
3579
3580 choice = strtol (args, &args2, 10);
3581 if (args == args2 || choice < 0
3582 || choice > n_choices + first_choice - 1)
3583 error (_("Argument must be choice number"));
3584 args = args2;
3585
3586 if (choice == 0)
3587 error (_("cancelled"));
3588
3589 if (choice < first_choice)
3590 {
3591 n_chosen = n_choices;
3592 for (j = 0; j < n_choices; j += 1)
3593 choices[j] = j;
3594 break;
3595 }
3596 choice -= first_choice;
3597
3598 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3599 {
3600 }
3601
3602 if (j < 0 || choice != choices[j])
3603 {
3604 int k;
3605
3606 for (k = n_chosen - 1; k > j; k -= 1)
3607 choices[k + 1] = choices[k];
3608 choices[j + 1] = choice;
3609 n_chosen += 1;
3610 }
3611 }
3612
3613 if (n_chosen > max_results)
3614 error (_("Select no more than %d of the above"), max_results);
3615
3616 return n_chosen;
3617 }
3618
3619 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3620 by asking the user (if necessary), returning the number selected,
3621 and setting the first elements of SYMS items. Error if no symbols
3622 selected. */
3623
3624 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3625 to be re-integrated one of these days. */
3626
3627 static int
user_select_syms(struct block_symbol * syms,int nsyms,int max_results)3628 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3629 {
3630 int i;
3631 int *chosen = XALLOCAVEC (int , nsyms);
3632 int n_chosen;
3633 int first_choice = (max_results == 1) ? 1 : 2;
3634 const char *select_mode = multiple_symbols_select_mode ();
3635
3636 if (max_results < 1)
3637 error (_("Request to select 0 symbols!"));
3638 if (nsyms <= 1)
3639 return nsyms;
3640
3641 if (select_mode == multiple_symbols_cancel)
3642 error (_("\
3643 canceled because the command is ambiguous\n\
3644 See set/show multiple-symbol."));
3645
3646 /* If select_mode is "all", then return all possible symbols.
3647 Only do that if more than one symbol can be selected, of course.
3648 Otherwise, display the menu as usual. */
3649 if (select_mode == multiple_symbols_all && max_results > 1)
3650 return nsyms;
3651
3652 gdb_printf (_("[0] cancel\n"));
3653 if (max_results > 1)
3654 gdb_printf (_("[1] all\n"));
3655
3656 sort_choices (syms, nsyms);
3657
3658 for (i = 0; i < nsyms; i += 1)
3659 {
3660 if (syms[i].symbol == NULL)
3661 continue;
3662
3663 if (syms[i].symbol->aclass () == LOC_BLOCK)
3664 {
3665 struct symtab_and_line sal =
3666 find_function_start_sal (syms[i].symbol, 1);
3667
3668 gdb_printf ("[%d] ", i + first_choice);
3669 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3670 &type_print_raw_options);
3671 if (sal.symtab == NULL)
3672 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3673 metadata_style.style ().ptr (), nullptr, sal.line);
3674 else
3675 gdb_printf
3676 (_(" at %ps:%d\n"),
3677 styled_string (file_name_style.style (),
3678 symtab_to_filename_for_display (sal.symtab)),
3679 sal.line);
3680 continue;
3681 }
3682 else
3683 {
3684 int is_enumeral =
3685 (syms[i].symbol->aclass () == LOC_CONST
3686 && syms[i].symbol->type () != NULL
3687 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3688 struct symtab *symtab = NULL;
3689
3690 if (syms[i].symbol->is_objfile_owned ())
3691 symtab = syms[i].symbol->symtab ();
3692
3693 if (syms[i].symbol->line () != 0 && symtab != NULL)
3694 {
3695 gdb_printf ("[%d] ", i + first_choice);
3696 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3697 &type_print_raw_options);
3698 gdb_printf (_(" at %s:%d\n"),
3699 symtab_to_filename_for_display (symtab),
3700 syms[i].symbol->line ());
3701 }
3702 else if (is_enumeral
3703 && syms[i].symbol->type ()->name () != NULL)
3704 {
3705 gdb_printf (("[%d] "), i + first_choice);
3706 ada_print_type (syms[i].symbol->type (), NULL,
3707 gdb_stdout, -1, 0, &type_print_raw_options);
3708 gdb_printf (_("'(%s) (enumeral)\n"),
3709 syms[i].symbol->print_name ());
3710 }
3711 else
3712 {
3713 gdb_printf ("[%d] ", i + first_choice);
3714 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3715 &type_print_raw_options);
3716
3717 if (symtab != NULL)
3718 gdb_printf (is_enumeral
3719 ? _(" in %s (enumeral)\n")
3720 : _(" at %s:?\n"),
3721 symtab_to_filename_for_display (symtab));
3722 else
3723 gdb_printf (is_enumeral
3724 ? _(" (enumeral)\n")
3725 : _(" at ?\n"));
3726 }
3727 }
3728 }
3729
3730 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3731 "overload-choice");
3732
3733 for (i = 0; i < n_chosen; i += 1)
3734 syms[i] = syms[chosen[i]];
3735
3736 return n_chosen;
3737 }
3738
3739 /* See ada-lang.h. */
3740
3741 block_symbol
ada_find_operator_symbol(enum exp_opcode op,bool parse_completion,int nargs,value * argvec[])3742 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3743 int nargs, value *argvec[])
3744 {
3745 if (possible_user_operator_p (op, argvec))
3746 {
3747 std::vector<struct block_symbol> candidates
3748 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3749 NULL, SEARCH_VFT);
3750
3751 int i = ada_resolve_function (candidates, argvec,
3752 nargs, ada_decoded_op_name (op), NULL,
3753 parse_completion);
3754 if (i >= 0)
3755 return candidates[i];
3756 }
3757 return {};
3758 }
3759
3760 /* See ada-lang.h. */
3761
3762 block_symbol
ada_resolve_funcall(struct symbol * sym,const struct block * block,struct type * context_type,bool parse_completion,int nargs,value * argvec[],innermost_block_tracker * tracker)3763 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3764 struct type *context_type,
3765 bool parse_completion,
3766 int nargs, value *argvec[],
3767 innermost_block_tracker *tracker)
3768 {
3769 std::vector<struct block_symbol> candidates
3770 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3771
3772 int i;
3773 if (candidates.size () == 1)
3774 i = 0;
3775 else
3776 {
3777 i = ada_resolve_function
3778 (candidates,
3779 argvec, nargs,
3780 sym->linkage_name (),
3781 context_type, parse_completion);
3782 if (i < 0)
3783 error (_("Could not find a match for %s"), sym->print_name ());
3784 }
3785
3786 tracker->update (candidates[i]);
3787 return candidates[i];
3788 }
3789
3790 /* Resolve a mention of a name where the context type is an
3791 enumeration type. */
3792
3793 static int
ada_resolve_enum(std::vector<struct block_symbol> & syms,const char * name,struct type * context_type,bool parse_completion)3794 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3795 const char *name, struct type *context_type,
3796 bool parse_completion)
3797 {
3798 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3799 context_type = ada_check_typedef (context_type);
3800
3801 /* We already know the name matches, so we're just looking for
3802 an element of the correct enum type. */
3803 struct type *type1 = context_type;
3804 for (int i = 0; i < syms.size (); ++i)
3805 {
3806 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3807 if (type1 == type2)
3808 return i;
3809 }
3810
3811 for (int i = 0; i < syms.size (); ++i)
3812 {
3813 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3814 if (type1->num_fields () != type2->num_fields ())
3815 continue;
3816 if (strcmp (type1->name (), type2->name ()) != 0)
3817 continue;
3818 if (ada_identical_enum_types_p (type1, type2))
3819 return i;
3820 }
3821
3822 error (_("No name '%s' in enumeration type '%s'"), name,
3823 ada_type_name (context_type));
3824 }
3825
3826 /* See ada-lang.h. */
3827
3828 block_symbol
ada_resolve_variable(struct symbol * sym,const struct block * block,struct type * context_type,bool parse_completion,int deprocedure_p,innermost_block_tracker * tracker)3829 ada_resolve_variable (struct symbol *sym, const struct block *block,
3830 struct type *context_type,
3831 bool parse_completion,
3832 int deprocedure_p,
3833 innermost_block_tracker *tracker)
3834 {
3835 std::vector<struct block_symbol> candidates
3836 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
3837
3838 if (std::any_of (candidates.begin (),
3839 candidates.end (),
3840 [] (block_symbol &bsym)
3841 {
3842 switch (bsym.symbol->aclass ())
3843 {
3844 case LOC_REGISTER:
3845 case LOC_ARG:
3846 case LOC_REF_ARG:
3847 case LOC_REGPARM_ADDR:
3848 case LOC_LOCAL:
3849 case LOC_COMPUTED:
3850 return true;
3851 default:
3852 return false;
3853 }
3854 }))
3855 {
3856 /* Types tend to get re-introduced locally, so if there
3857 are any local symbols that are not types, first filter
3858 out all types. */
3859 candidates.erase
3860 (std::remove_if
3861 (candidates.begin (),
3862 candidates.end (),
3863 [] (block_symbol &bsym)
3864 {
3865 return bsym.symbol->aclass () == LOC_TYPEDEF;
3866 }),
3867 candidates.end ());
3868 }
3869
3870 /* Filter out artificial symbols. */
3871 candidates.erase
3872 (std::remove_if
3873 (candidates.begin (),
3874 candidates.end (),
3875 [] (block_symbol &bsym)
3876 {
3877 return bsym.symbol->is_artificial ();
3878 }),
3879 candidates.end ());
3880
3881 int i;
3882 if (candidates.empty ())
3883 error (_("No definition found for %s"), sym->print_name ());
3884 else if (candidates.size () == 1)
3885 i = 0;
3886 else if (context_type != nullptr
3887 && context_type->code () == TYPE_CODE_ENUM)
3888 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3889 parse_completion);
3890 else if (context_type == nullptr
3891 && symbols_are_identical_enums (candidates))
3892 {
3893 /* If all the remaining symbols are identical enumerals, then
3894 just keep the first one and discard the rest.
3895
3896 Unlike what we did previously, we do not discard any entry
3897 unless they are ALL identical. This is because the symbol
3898 comparison is not a strict comparison, but rather a practical
3899 comparison. If all symbols are considered identical, then
3900 we can just go ahead and use the first one and discard the rest.
3901 But if we cannot reduce the list to a single element, we have
3902 to ask the user to disambiguate anyways. And if we have to
3903 present a multiple-choice menu, it's less confusing if the list
3904 isn't missing some choices that were identical and yet distinct. */
3905 candidates.resize (1);
3906 i = 0;
3907 }
3908 else if (deprocedure_p && !is_nonfunction (candidates))
3909 {
3910 i = ada_resolve_function
3911 (candidates, NULL, 0,
3912 sym->linkage_name (),
3913 context_type, parse_completion);
3914 if (i < 0)
3915 error (_("Could not find a match for %s"), sym->print_name ());
3916 }
3917 else
3918 {
3919 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3920 user_select_syms (candidates.data (), candidates.size (), 1);
3921 i = 0;
3922 }
3923
3924 tracker->update (candidates[i]);
3925 return candidates[i];
3926 }
3927
3928 static bool ada_type_match (struct type *ftype, struct type *atype);
3929
3930 /* Helper for ada_type_match that checks that two array types are
3931 compatible. As with that function, FTYPE is the formal type and
3932 ATYPE is the actual type. */
3933
3934 static bool
ada_type_match_arrays(struct type * ftype,struct type * atype)3935 ada_type_match_arrays (struct type *ftype, struct type *atype)
3936 {
3937 if (ftype->code () != TYPE_CODE_ARRAY
3938 && !ada_is_array_descriptor_type (ftype))
3939 return false;
3940 if (atype->code () != TYPE_CODE_ARRAY
3941 && !ada_is_array_descriptor_type (atype))
3942 return false;
3943
3944 if (ada_array_arity (ftype) != ada_array_arity (atype))
3945 return false;
3946
3947 struct type *f_elt_type = ada_array_element_type (ftype, -1);
3948 struct type *a_elt_type = ada_array_element_type (atype, -1);
3949 return ada_type_match (f_elt_type, a_elt_type);
3950 }
3951
3952 /* Return non-zero if formal type FTYPE matches actual type ATYPE.
3953 The term "match" here is rather loose. The match is heuristic and
3954 liberal -- while it tries to reject matches that are obviously
3955 incorrect, it may still let through some that do not strictly
3956 correspond to Ada rules. */
3957
3958 static bool
ada_type_match(struct type * ftype,struct type * atype)3959 ada_type_match (struct type *ftype, struct type *atype)
3960 {
3961 ftype = ada_check_typedef (ftype);
3962 atype = ada_check_typedef (atype);
3963
3964 if (ftype->code () == TYPE_CODE_REF)
3965 ftype = ftype->target_type ();
3966 if (atype->code () == TYPE_CODE_REF)
3967 atype = atype->target_type ();
3968
3969 switch (ftype->code ())
3970 {
3971 default:
3972 return ftype->code () == atype->code ();
3973 case TYPE_CODE_PTR:
3974 if (atype->code () != TYPE_CODE_PTR)
3975 return false;
3976 atype = atype->target_type ();
3977 /* This can only happen if the actual argument is 'null'. */
3978 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3979 return true;
3980 return ada_type_match (ftype->target_type (), atype);
3981 case TYPE_CODE_INT:
3982 case TYPE_CODE_ENUM:
3983 case TYPE_CODE_RANGE:
3984 switch (atype->code ())
3985 {
3986 case TYPE_CODE_INT:
3987 case TYPE_CODE_ENUM:
3988 case TYPE_CODE_RANGE:
3989 return true;
3990 default:
3991 return false;
3992 }
3993
3994 case TYPE_CODE_STRUCT:
3995 if (!ada_is_array_descriptor_type (ftype))
3996 return (atype->code () == TYPE_CODE_STRUCT
3997 && !ada_is_array_descriptor_type (atype));
3998
3999 [[fallthrough]];
4000 case TYPE_CODE_ARRAY:
4001 return ada_type_match_arrays (ftype, atype);
4002
4003 case TYPE_CODE_UNION:
4004 case TYPE_CODE_FLT:
4005 return (atype->code () == ftype->code ());
4006 }
4007 }
4008
4009 /* Return non-zero if the formals of FUNC "sufficiently match" the
4010 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
4011 may also be an enumeral, in which case it is treated as a 0-
4012 argument function. */
4013
4014 static int
ada_args_match(struct symbol * func,struct value ** actuals,int n_actuals)4015 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
4016 {
4017 int i;
4018 struct type *func_type = func->type ();
4019
4020 if (func->aclass () == LOC_CONST
4021 && func_type->code () == TYPE_CODE_ENUM)
4022 return (n_actuals == 0);
4023 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
4024 return 0;
4025
4026 if (func_type->num_fields () != n_actuals)
4027 return 0;
4028
4029 for (i = 0; i < n_actuals; i += 1)
4030 {
4031 if (actuals[i] == NULL)
4032 return 0;
4033 else
4034 {
4035 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
4036 struct type *atype = ada_check_typedef (actuals[i]->type ());
4037
4038 if (!ada_type_match (ftype, atype))
4039 return 0;
4040 }
4041 }
4042 return 1;
4043 }
4044
4045 /* False iff function type FUNC_TYPE definitely does not produce a value
4046 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4047 FUNC_TYPE is not a valid function type with a non-null return type
4048 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4049
4050 static int
return_match(struct type * func_type,struct type * context_type)4051 return_match (struct type *func_type, struct type *context_type)
4052 {
4053 struct type *return_type;
4054
4055 if (func_type == NULL)
4056 return 1;
4057
4058 if (func_type->code () == TYPE_CODE_FUNC)
4059 return_type = get_base_type (func_type->target_type ());
4060 else
4061 return_type = get_base_type (func_type);
4062 if (return_type == NULL)
4063 return 1;
4064
4065 context_type = get_base_type (context_type);
4066
4067 if (return_type->code () == TYPE_CODE_ENUM)
4068 return context_type == NULL || return_type == context_type;
4069 else if (context_type == NULL)
4070 return return_type->code () != TYPE_CODE_VOID;
4071 else
4072 return return_type->code () == context_type->code ();
4073 }
4074
4075
4076 /* Returns the index in SYMS that contains the symbol for the
4077 function (if any) that matches the types of the NARGS arguments in
4078 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4079 that returns that type, then eliminate matches that don't. If
4080 CONTEXT_TYPE is void and there is at least one match that does not
4081 return void, eliminate all matches that do.
4082
4083 Asks the user if there is more than one match remaining. Returns -1
4084 if there is no such symbol or none is selected. NAME is used
4085 solely for messages. May re-arrange and modify SYMS in
4086 the process; the index returned is for the modified vector. */
4087
4088 static int
ada_resolve_function(std::vector<struct block_symbol> & syms,struct value ** args,int nargs,const char * name,struct type * context_type,bool parse_completion)4089 ada_resolve_function (std::vector<struct block_symbol> &syms,
4090 struct value **args, int nargs,
4091 const char *name, struct type *context_type,
4092 bool parse_completion)
4093 {
4094 int fallback;
4095 int k;
4096 int m; /* Number of hits */
4097
4098 m = 0;
4099 /* In the first pass of the loop, we only accept functions matching
4100 context_type. If none are found, we add a second pass of the loop
4101 where every function is accepted. */
4102 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4103 {
4104 for (k = 0; k < syms.size (); k += 1)
4105 {
4106 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4107
4108 if (ada_args_match (syms[k].symbol, args, nargs)
4109 && (fallback || return_match (type, context_type)))
4110 {
4111 syms[m] = syms[k];
4112 m += 1;
4113 }
4114 }
4115 }
4116
4117 /* If we got multiple matches, ask the user which one to use. Don't do this
4118 interactive thing during completion, though, as the purpose of the
4119 completion is providing a list of all possible matches. Prompting the
4120 user to filter it down would be completely unexpected in this case. */
4121 if (m == 0)
4122 return -1;
4123 else if (m > 1 && !parse_completion)
4124 {
4125 gdb_printf (_("Multiple matches for %s\n"), name);
4126 user_select_syms (syms.data (), m, 1);
4127 return 0;
4128 }
4129 return 0;
4130 }
4131
4132 /* Type-class predicates */
4133
4134 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4135 or FLOAT). */
4136
4137 static int
numeric_type_p(struct type * type)4138 numeric_type_p (struct type *type)
4139 {
4140 if (type == NULL)
4141 return 0;
4142 else
4143 {
4144 switch (type->code ())
4145 {
4146 case TYPE_CODE_INT:
4147 case TYPE_CODE_FLT:
4148 case TYPE_CODE_FIXED_POINT:
4149 return 1;
4150 case TYPE_CODE_RANGE:
4151 return (type == type->target_type ()
4152 || numeric_type_p (type->target_type ()));
4153 default:
4154 return 0;
4155 }
4156 }
4157 }
4158
4159 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4160
4161 static int
integer_type_p(struct type * type)4162 integer_type_p (struct type *type)
4163 {
4164 if (type == NULL)
4165 return 0;
4166 else
4167 {
4168 switch (type->code ())
4169 {
4170 case TYPE_CODE_INT:
4171 return 1;
4172 case TYPE_CODE_RANGE:
4173 return (type == type->target_type ()
4174 || integer_type_p (type->target_type ()));
4175 default:
4176 return 0;
4177 }
4178 }
4179 }
4180
4181 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4182
4183 static int
scalar_type_p(struct type * type)4184 scalar_type_p (struct type *type)
4185 {
4186 if (type == NULL)
4187 return 0;
4188 else
4189 {
4190 switch (type->code ())
4191 {
4192 case TYPE_CODE_INT:
4193 case TYPE_CODE_RANGE:
4194 case TYPE_CODE_ENUM:
4195 case TYPE_CODE_FLT:
4196 case TYPE_CODE_FIXED_POINT:
4197 return 1;
4198 default:
4199 return 0;
4200 }
4201 }
4202 }
4203
4204 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4205 This essentially means one of (INT, RANGE, ENUM) -- but note that
4206 "enum" includes character and boolean as well. */
4207
4208 static int
discrete_type_p(struct type * type)4209 discrete_type_p (struct type *type)
4210 {
4211 if (type == NULL)
4212 return 0;
4213 else
4214 {
4215 switch (type->code ())
4216 {
4217 case TYPE_CODE_INT:
4218 case TYPE_CODE_RANGE:
4219 case TYPE_CODE_ENUM:
4220 case TYPE_CODE_BOOL:
4221 case TYPE_CODE_CHAR:
4222 return 1;
4223 default:
4224 return 0;
4225 }
4226 }
4227 }
4228
4229 /* Returns non-zero if OP with operands in the vector ARGS could be
4230 a user-defined function. Errs on the side of pre-defined operators
4231 (i.e., result 0). */
4232
4233 static int
possible_user_operator_p(enum exp_opcode op,struct value * args[])4234 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4235 {
4236 struct type *type0 =
4237 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4238 struct type *type1 =
4239 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4240
4241 if (type0 == NULL)
4242 return 0;
4243
4244 switch (op)
4245 {
4246 default:
4247 return 0;
4248
4249 case BINOP_ADD:
4250 case BINOP_SUB:
4251 case BINOP_MUL:
4252 case BINOP_DIV:
4253 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4254
4255 case BINOP_REM:
4256 case BINOP_MOD:
4257 case BINOP_BITWISE_AND:
4258 case BINOP_BITWISE_IOR:
4259 case BINOP_BITWISE_XOR:
4260 return (!(integer_type_p (type0) && integer_type_p (type1)));
4261
4262 case BINOP_EQUAL:
4263 case BINOP_NOTEQUAL:
4264 case BINOP_LESS:
4265 case BINOP_GTR:
4266 case BINOP_LEQ:
4267 case BINOP_GEQ:
4268 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4269
4270 case BINOP_CONCAT:
4271 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4272
4273 case BINOP_EXP:
4274 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4275
4276 case UNOP_NEG:
4277 case UNOP_PLUS:
4278 case UNOP_LOGICAL_NOT:
4279 case UNOP_ABS:
4280 return (!numeric_type_p (type0));
4281
4282 }
4283 }
4284
4285 /* Renaming */
4286
4287 /* NOTES:
4288
4289 1. In the following, we assume that a renaming type's name may
4290 have an ___XD suffix. It would be nice if this went away at some
4291 point.
4292 2. We handle both the (old) purely type-based representation of
4293 renamings and the (new) variable-based encoding. At some point,
4294 it is devoutly to be hoped that the former goes away
4295 (FIXME: hilfinger-2007-07-09).
4296 3. Subprogram renamings are not implemented, although the XRS
4297 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4298
4299 /* If SYM encodes a renaming,
4300
4301 <renaming> renames <renamed entity>,
4302
4303 sets *LEN to the length of the renamed entity's name,
4304 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4305 the string describing the subcomponent selected from the renamed
4306 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4307 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4308 are undefined). Otherwise, returns a value indicating the category
4309 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4310 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4311 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4312 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4313 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4314 may be NULL, in which case they are not assigned.
4315
4316 [Currently, however, GCC does not generate subprogram renamings.] */
4317
4318 enum ada_renaming_category
ada_parse_renaming(struct symbol * sym,const char ** renamed_entity,int * len,const char ** renaming_expr)4319 ada_parse_renaming (struct symbol *sym,
4320 const char **renamed_entity, int *len,
4321 const char **renaming_expr)
4322 {
4323 enum ada_renaming_category kind;
4324 const char *info;
4325 const char *suffix;
4326
4327 if (sym == NULL)
4328 return ADA_NOT_RENAMING;
4329 switch (sym->aclass ())
4330 {
4331 default:
4332 return ADA_NOT_RENAMING;
4333 case LOC_LOCAL:
4334 case LOC_STATIC:
4335 case LOC_COMPUTED:
4336 case LOC_OPTIMIZED_OUT:
4337 info = strstr (sym->linkage_name (), "___XR");
4338 if (info == NULL)
4339 return ADA_NOT_RENAMING;
4340 switch (info[5])
4341 {
4342 case '_':
4343 kind = ADA_OBJECT_RENAMING;
4344 info += 6;
4345 break;
4346 case 'E':
4347 kind = ADA_EXCEPTION_RENAMING;
4348 info += 7;
4349 break;
4350 case 'P':
4351 kind = ADA_PACKAGE_RENAMING;
4352 info += 7;
4353 break;
4354 case 'S':
4355 kind = ADA_SUBPROGRAM_RENAMING;
4356 info += 7;
4357 break;
4358 default:
4359 return ADA_NOT_RENAMING;
4360 }
4361 }
4362
4363 if (renamed_entity != NULL)
4364 *renamed_entity = info;
4365 suffix = strstr (info, "___XE");
4366 if (suffix == NULL || suffix == info)
4367 return ADA_NOT_RENAMING;
4368 if (len != NULL)
4369 *len = strlen (info) - strlen (suffix);
4370 suffix += 5;
4371 if (renaming_expr != NULL)
4372 *renaming_expr = suffix;
4373 return kind;
4374 }
4375
4376 /* Compute the value of the given RENAMING_SYM, which is expected to
4377 be a symbol encoding a renaming expression. BLOCK is the block
4378 used to evaluate the renaming. */
4379
4380 static struct value *
ada_read_renaming_var_value(struct symbol * renaming_sym,const struct block * block)4381 ada_read_renaming_var_value (struct symbol *renaming_sym,
4382 const struct block *block)
4383 {
4384 const char *sym_name;
4385
4386 sym_name = renaming_sym->linkage_name ();
4387 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4388 return expr->evaluate ();
4389 }
4390
4391
4392 /* Evaluation: Function Calls */
4393
4394 /* Return an lvalue containing the value VAL. This is the identity on
4395 lvalues, and otherwise has the side-effect of allocating memory
4396 in the inferior where a copy of the value contents is copied. */
4397
4398 static struct value *
ensure_lval(struct value * val)4399 ensure_lval (struct value *val)
4400 {
4401 if (val->lval () == not_lval
4402 || val->lval () == lval_internalvar)
4403 {
4404 int len = ada_check_typedef (val->type ())->length ();
4405 const CORE_ADDR addr =
4406 value_as_long (value_allocate_space_in_inferior (len));
4407
4408 val->set_lval (lval_memory);
4409 val->set_address (addr);
4410 write_memory (addr, val->contents ().data (), len);
4411 }
4412
4413 return val;
4414 }
4415
4416 /* Given ARG, a value of type (pointer or reference to a)*
4417 structure/union, extract the component named NAME from the ultimate
4418 target structure/union and return it as a value with its
4419 appropriate type.
4420
4421 The routine searches for NAME among all members of the structure itself
4422 and (recursively) among all members of any wrapper members
4423 (e.g., '_parent').
4424
4425 If NO_ERR, then simply return NULL in case of error, rather than
4426 calling error. */
4427
4428 static struct value *
ada_value_struct_elt(struct value * arg,const char * name,int no_err)4429 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4430 {
4431 struct type *t, *t1;
4432 struct value *v;
4433 int check_tag;
4434
4435 v = NULL;
4436 t1 = t = ada_check_typedef (arg->type ());
4437 if (t->code () == TYPE_CODE_REF)
4438 {
4439 t1 = t->target_type ();
4440 if (t1 == NULL)
4441 goto BadValue;
4442 t1 = ada_check_typedef (t1);
4443 if (t1->code () == TYPE_CODE_PTR)
4444 {
4445 arg = coerce_ref (arg);
4446 t = t1;
4447 }
4448 }
4449
4450 while (t->code () == TYPE_CODE_PTR)
4451 {
4452 t1 = t->target_type ();
4453 if (t1 == NULL)
4454 goto BadValue;
4455 t1 = ada_check_typedef (t1);
4456 if (t1->code () == TYPE_CODE_PTR)
4457 {
4458 arg = value_ind (arg);
4459 t = t1;
4460 }
4461 else
4462 break;
4463 }
4464
4465 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4466 goto BadValue;
4467
4468 if (t1 == t)
4469 v = ada_search_struct_field (name, arg, 0, t);
4470 else
4471 {
4472 int bit_offset, bit_size, byte_offset;
4473 struct type *field_type;
4474 CORE_ADDR address;
4475
4476 if (t->code () == TYPE_CODE_PTR)
4477 address = ada_value_ind (arg)->address ();
4478 else
4479 address = ada_coerce_ref (arg)->address ();
4480
4481 /* Check to see if this is a tagged type. We also need to handle
4482 the case where the type is a reference to a tagged type, but
4483 we have to be careful to exclude pointers to tagged types.
4484 The latter should be shown as usual (as a pointer), whereas
4485 a reference should mostly be transparent to the user. */
4486
4487 if (ada_is_tagged_type (t1, 0)
4488 || (t1->code () == TYPE_CODE_REF
4489 && ada_is_tagged_type (t1->target_type (), 0)))
4490 {
4491 /* We first try to find the searched field in the current type.
4492 If not found then let's look in the fixed type. */
4493
4494 if (!find_struct_field (name, t1, 0,
4495 nullptr, nullptr, nullptr,
4496 nullptr, nullptr))
4497 check_tag = 1;
4498 else
4499 check_tag = 0;
4500 }
4501 else
4502 check_tag = 0;
4503
4504 /* Convert to fixed type in all cases, so that we have proper
4505 offsets to each field in unconstrained record types. */
4506 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4507 address, NULL, check_tag);
4508
4509 /* Resolve the dynamic type as well. */
4510 arg = value_from_contents_and_address (t1, nullptr, address);
4511 t1 = arg->type ();
4512
4513 if (find_struct_field (name, t1, 0,
4514 &field_type, &byte_offset, &bit_offset,
4515 &bit_size, NULL))
4516 {
4517 if (bit_size != 0)
4518 {
4519 if (t->code () == TYPE_CODE_REF)
4520 arg = ada_coerce_ref (arg);
4521 else
4522 arg = ada_value_ind (arg);
4523 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4524 bit_offset, bit_size,
4525 field_type);
4526 }
4527 else
4528 v = value_at_lazy (field_type, address + byte_offset);
4529 }
4530 }
4531
4532 if (v != NULL || no_err)
4533 return v;
4534 else
4535 error (_("There is no member named %s."), name);
4536
4537 BadValue:
4538 if (no_err)
4539 return NULL;
4540 else
4541 error (_("Attempt to extract a component of "
4542 "a value that is not a record."));
4543 }
4544
4545 /* Return the value ACTUAL, converted to be an appropriate value for a
4546 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4547 allocating any necessary descriptors (fat pointers), or copies of
4548 values not residing in memory, updating it as needed. */
4549
4550 struct value *
ada_convert_actual(struct value * actual,struct type * formal_type0)4551 ada_convert_actual (struct value *actual, struct type *formal_type0)
4552 {
4553 struct type *actual_type = ada_check_typedef (actual->type ());
4554 struct type *formal_type = ada_check_typedef (formal_type0);
4555 struct type *formal_target =
4556 formal_type->code () == TYPE_CODE_PTR
4557 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4558 struct type *actual_target =
4559 actual_type->code () == TYPE_CODE_PTR
4560 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4561
4562 if (ada_is_array_descriptor_type (formal_target)
4563 && actual_target->code () == TYPE_CODE_ARRAY)
4564 return make_array_descriptor (formal_type, actual);
4565 else if (formal_type->code () == TYPE_CODE_PTR
4566 || formal_type->code () == TYPE_CODE_REF)
4567 {
4568 struct value *result;
4569
4570 if (formal_target->code () == TYPE_CODE_ARRAY
4571 && ada_is_array_descriptor_type (actual_target))
4572 result = desc_data (actual);
4573 else if (formal_type->code () != TYPE_CODE_PTR)
4574 {
4575 if (actual->lval () != lval_memory)
4576 {
4577 struct value *val;
4578
4579 actual_type = ada_check_typedef (actual->type ());
4580 val = value::allocate (actual_type);
4581 copy (actual->contents (), val->contents_raw ());
4582 actual = ensure_lval (val);
4583 }
4584 result = value_addr (actual);
4585 }
4586 else
4587 return actual;
4588 return value_cast_pointers (formal_type, result, 0);
4589 }
4590 else if (actual_type->code () == TYPE_CODE_PTR)
4591 return ada_value_ind (actual);
4592 else if (ada_is_aligner_type (formal_type))
4593 {
4594 /* We need to turn this parameter into an aligner type
4595 as well. */
4596 struct value *aligner = value::allocate (formal_type);
4597 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4598
4599 value_assign_to_component (aligner, component, actual);
4600 return aligner;
4601 }
4602
4603 return actual;
4604 }
4605
4606 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4607 type TYPE. This is usually an inefficient no-op except on some targets
4608 (such as AVR) where the representation of a pointer and an address
4609 differs. */
4610
4611 static CORE_ADDR
value_pointer(struct value * value,struct type * type)4612 value_pointer (struct value *value, struct type *type)
4613 {
4614 unsigned len = type->length ();
4615 gdb_byte *buf = (gdb_byte *) alloca (len);
4616 CORE_ADDR addr;
4617
4618 addr = value->address ();
4619 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4620 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4621 return addr;
4622 }
4623
4624
4625 /* Push a descriptor of type TYPE for array value ARR on the stack at
4626 *SP, updating *SP to reflect the new descriptor. Return either
4627 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4628 to-descriptor type rather than a descriptor type), a struct value *
4629 representing a pointer to this descriptor. */
4630
4631 static struct value *
make_array_descriptor(struct type * type,struct value * arr)4632 make_array_descriptor (struct type *type, struct value *arr)
4633 {
4634 struct type *bounds_type = desc_bounds_type (type);
4635 struct type *desc_type = desc_base_type (type);
4636 struct value *descriptor = value::allocate (desc_type);
4637 struct value *bounds = value::allocate (bounds_type);
4638 int i;
4639
4640 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4641 i > 0; i -= 1)
4642 {
4643 modify_field (bounds->type (),
4644 bounds->contents_writeable ().data (),
4645 ada_array_bound (arr, i, 0),
4646 desc_bound_bitpos (bounds_type, i, 0),
4647 desc_bound_bitsize (bounds_type, i, 0));
4648 modify_field (bounds->type (),
4649 bounds->contents_writeable ().data (),
4650 ada_array_bound (arr, i, 1),
4651 desc_bound_bitpos (bounds_type, i, 1),
4652 desc_bound_bitsize (bounds_type, i, 1));
4653 }
4654
4655 bounds = ensure_lval (bounds);
4656
4657 modify_field (descriptor->type (),
4658 descriptor->contents_writeable ().data (),
4659 value_pointer (ensure_lval (arr),
4660 desc_type->field (0).type ()),
4661 fat_pntr_data_bitpos (desc_type),
4662 fat_pntr_data_bitsize (desc_type));
4663
4664 modify_field (descriptor->type (),
4665 descriptor->contents_writeable ().data (),
4666 value_pointer (bounds,
4667 desc_type->field (1).type ()),
4668 fat_pntr_bounds_bitpos (desc_type),
4669 fat_pntr_bounds_bitsize (desc_type));
4670
4671 descriptor = ensure_lval (descriptor);
4672
4673 if (type->code () == TYPE_CODE_PTR)
4674 return value_addr (descriptor);
4675 else
4676 return descriptor;
4677 }
4678
4679 /* Symbol Cache Module */
4680
4681 /* Performance measurements made as of 2010-01-15 indicate that
4682 this cache does bring some noticeable improvements. Depending
4683 on the type of entity being printed, the cache can make it as much
4684 as an order of magnitude faster than without it.
4685
4686 The descriptive type DWARF extension has significantly reduced
4687 the need for this cache, at least when DWARF is being used. However,
4688 even in this case, some expensive name-based symbol searches are still
4689 sometimes necessary - to find an XVZ variable, mostly. */
4690
4691 /* Clear all entries from the symbol cache. */
4692
4693 static void
ada_clear_symbol_cache(program_space * pspace)4694 ada_clear_symbol_cache (program_space *pspace)
4695 {
4696 ada_pspace_data_handle.clear (pspace);
4697 }
4698
4699 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4700 Return 1 if found, 0 otherwise.
4701
4702 If an entry was found and SYM is not NULL, set *SYM to the entry's
4703 SYM. Same principle for BLOCK if not NULL. */
4704
4705 static int
lookup_cached_symbol(const char * name,domain_search_flags domain,struct symbol ** sym,const struct block ** block)4706 lookup_cached_symbol (const char *name, domain_search_flags domain,
4707 struct symbol **sym, const struct block **block)
4708 {
4709 htab_t tab = get_ada_pspace_data (current_program_space);
4710 cache_entry_search search;
4711 search.name = name;
4712 search.domain = domain;
4713
4714 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4715 search.hash ());
4716 if (e == nullptr)
4717 return 0;
4718 if (sym != nullptr)
4719 *sym = e->sym;
4720 if (block != nullptr)
4721 *block = e->block;
4722 return 1;
4723 }
4724
4725 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4726 in domain DOMAIN, save this result in our symbol cache. */
4727
4728 static void
cache_symbol(const char * name,domain_search_flags domain,struct symbol * sym,const struct block * block)4729 cache_symbol (const char *name, domain_search_flags domain,
4730 struct symbol *sym, const struct block *block)
4731 {
4732 /* Symbols for builtin types don't have a block.
4733 For now don't cache such symbols. */
4734 if (sym != NULL && !sym->is_objfile_owned ())
4735 return;
4736
4737 /* If the symbol is a local symbol, then do not cache it, as a search
4738 for that symbol depends on the context. To determine whether
4739 the symbol is local or not, we check the block where we found it
4740 against the global and static blocks of its associated symtab. */
4741 if (sym != nullptr)
4742 {
4743 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4744
4745 if (bv.global_block () != block && bv.static_block () != block)
4746 return;
4747 }
4748
4749 htab_t tab = get_ada_pspace_data (current_program_space);
4750 cache_entry_search search;
4751 search.name = name;
4752 search.domain = domain;
4753
4754 void **slot = htab_find_slot_with_hash (tab, &search,
4755 search.hash (), INSERT);
4756
4757 cache_entry *e = new cache_entry;
4758 e->name = name;
4759 e->domain = domain;
4760 e->sym = sym;
4761 e->block = block;
4762
4763 *slot = e;
4764 }
4765
4766 /* Symbol Lookup */
4767
4768 /* Return the symbol name match type that should be used used when
4769 searching for all symbols matching LOOKUP_NAME.
4770
4771 LOOKUP_NAME is expected to be a symbol name after transformation
4772 for Ada lookups. */
4773
4774 static symbol_name_match_type
name_match_type_from_name(const char * lookup_name)4775 name_match_type_from_name (const char *lookup_name)
4776 {
4777 return (strstr (lookup_name, "__") == NULL
4778 ? symbol_name_match_type::WILD
4779 : symbol_name_match_type::FULL);
4780 }
4781
4782 /* Return the result of a standard (literal, C-like) lookup of NAME in
4783 given DOMAIN, visible from lexical block BLOCK. */
4784
4785 static struct symbol *
standard_lookup(const char * name,const struct block * block,domain_search_flags domain)4786 standard_lookup (const char *name, const struct block *block,
4787 domain_search_flags domain)
4788 {
4789 /* Initialize it just to avoid a GCC false warning. */
4790 struct block_symbol sym = {};
4791
4792 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4793 return sym.symbol;
4794 ada_lookup_encoded_symbol (name, block, domain, &sym);
4795 cache_symbol (name, domain, sym.symbol, sym.block);
4796 return sym.symbol;
4797 }
4798
4799
4800 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4801 in the symbol fields of SYMS. We treat enumerals as functions,
4802 since they contend in overloading in the same way. */
4803 static int
is_nonfunction(const std::vector<struct block_symbol> & syms)4804 is_nonfunction (const std::vector<struct block_symbol> &syms)
4805 {
4806 for (const block_symbol &sym : syms)
4807 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4808 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4809 || sym.symbol->aclass () != LOC_CONST))
4810 return 1;
4811
4812 return 0;
4813 }
4814
4815 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4816 struct types. Otherwise, they may not. */
4817
4818 static int
equiv_types(struct type * type0,struct type * type1)4819 equiv_types (struct type *type0, struct type *type1)
4820 {
4821 if (type0 == type1)
4822 return 1;
4823 if (type0 == NULL || type1 == NULL
4824 || type0->code () != type1->code ())
4825 return 0;
4826 if ((type0->code () == TYPE_CODE_STRUCT
4827 || type0->code () == TYPE_CODE_ENUM)
4828 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4829 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4830 return 1;
4831
4832 return 0;
4833 }
4834
4835 /* True iff SYM0 represents the same entity as SYM1, or one that is
4836 no more defined than that of SYM1. */
4837
4838 static int
lesseq_defined_than(struct symbol * sym0,struct symbol * sym1)4839 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4840 {
4841 if (sym0 == sym1)
4842 return 1;
4843 if (sym0->domain () != sym1->domain ()
4844 || sym0->aclass () != sym1->aclass ())
4845 return 0;
4846
4847 switch (sym0->aclass ())
4848 {
4849 case LOC_UNDEF:
4850 return 1;
4851 case LOC_TYPEDEF:
4852 {
4853 struct type *type0 = sym0->type ();
4854 struct type *type1 = sym1->type ();
4855 const char *name0 = sym0->linkage_name ();
4856 const char *name1 = sym1->linkage_name ();
4857 int len0 = strlen (name0);
4858
4859 return
4860 type0->code () == type1->code ()
4861 && (equiv_types (type0, type1)
4862 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4863 && startswith (name1 + len0, "___XV")));
4864 }
4865 case LOC_CONST:
4866 return sym0->value_longest () == sym1->value_longest ()
4867 && equiv_types (sym0->type (), sym1->type ());
4868
4869 case LOC_STATIC:
4870 {
4871 const char *name0 = sym0->linkage_name ();
4872 const char *name1 = sym1->linkage_name ();
4873 return (strcmp (name0, name1) == 0
4874 && sym0->value_address () == sym1->value_address ());
4875 }
4876
4877 default:
4878 return 0;
4879 }
4880 }
4881
4882 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4883 records in RESULT. Do nothing if SYM is a duplicate. */
4884
4885 static void
add_defn_to_vec(std::vector<struct block_symbol> & result,struct symbol * sym,const struct block * block)4886 add_defn_to_vec (std::vector<struct block_symbol> &result,
4887 struct symbol *sym,
4888 const struct block *block)
4889 {
4890 /* Do not try to complete stub types, as the debugger is probably
4891 already scanning all symbols matching a certain name at the
4892 time when this function is called. Trying to replace the stub
4893 type by its associated full type will cause us to restart a scan
4894 which may lead to an infinite recursion. Instead, the client
4895 collecting the matching symbols will end up collecting several
4896 matches, with at least one of them complete. It can then filter
4897 out the stub ones if needed. */
4898
4899 for (int i = result.size () - 1; i >= 0; i -= 1)
4900 {
4901 if (lesseq_defined_than (sym, result[i].symbol))
4902 return;
4903 else if (lesseq_defined_than (result[i].symbol, sym))
4904 {
4905 result[i].symbol = sym;
4906 result[i].block = block;
4907 return;
4908 }
4909 }
4910
4911 struct block_symbol info;
4912 info.symbol = sym;
4913 info.block = block;
4914 result.push_back (info);
4915 }
4916
4917 /* Return a bound minimal symbol matching NAME according to Ada
4918 decoding rules. Returns an invalid symbol if there is no such
4919 minimal symbol. Names prefixed with "standard__" are handled
4920 specially: "standard__" is first stripped off, and only static and
4921 global symbols are searched. */
4922
4923 struct bound_minimal_symbol
ada_lookup_simple_minsym(const char * name,struct objfile * objfile)4924 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4925 {
4926 struct bound_minimal_symbol result;
4927
4928 symbol_name_match_type match_type = name_match_type_from_name (name);
4929 lookup_name_info lookup_name (name, match_type);
4930
4931 symbol_name_matcher_ftype *match_name
4932 = ada_get_symbol_name_matcher (lookup_name);
4933
4934 gdbarch_iterate_over_objfiles_in_search_order
4935 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
4936 [&result, lookup_name, match_name] (struct objfile *obj)
4937 {
4938 for (minimal_symbol *msymbol : obj->msymbols ())
4939 {
4940 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4941 && msymbol->type () != mst_solib_trampoline)
4942 {
4943 result.minsym = msymbol;
4944 result.objfile = obj;
4945 return 1;
4946 }
4947 }
4948
4949 return 0;
4950 }, objfile);
4951
4952 return result;
4953 }
4954
4955 /* True if TYPE is definitely an artificial type supplied to a symbol
4956 for which no debugging information was given in the symbol file. */
4957
4958 static int
is_nondebugging_type(struct type * type)4959 is_nondebugging_type (struct type *type)
4960 {
4961 const char *name = ada_type_name (type);
4962
4963 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4964 }
4965
4966 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4967 that are deemed "identical" for practical purposes.
4968
4969 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4970 types and that their number of enumerals is identical (in other
4971 words, type1->num_fields () == type2->num_fields ()). */
4972
4973 static int
ada_identical_enum_types_p(struct type * type1,struct type * type2)4974 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4975 {
4976 int i;
4977
4978 /* The heuristic we use here is fairly conservative. We consider
4979 that 2 enumerate types are identical if they have the same
4980 number of enumerals and that all enumerals have the same
4981 underlying value and name. */
4982
4983 /* All enums in the type should have an identical underlying value. */
4984 for (i = 0; i < type1->num_fields (); i++)
4985 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4986 return 0;
4987
4988 /* All enumerals should also have the same name (modulo any numerical
4989 suffix). */
4990 for (i = 0; i < type1->num_fields (); i++)
4991 {
4992 const char *name_1 = type1->field (i).name ();
4993 const char *name_2 = type2->field (i).name ();
4994 int len_1 = strlen (name_1);
4995 int len_2 = strlen (name_2);
4996
4997 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4998 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4999 if (len_1 != len_2
5000 || strncmp (type1->field (i).name (),
5001 type2->field (i).name (),
5002 len_1) != 0)
5003 return 0;
5004 }
5005
5006 return 1;
5007 }
5008
5009 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
5010 that are deemed "identical" for practical purposes. Sometimes,
5011 enumerals are not strictly identical, but their types are so similar
5012 that they can be considered identical.
5013
5014 For instance, consider the following code:
5015
5016 type Color is (Black, Red, Green, Blue, White);
5017 type RGB_Color is new Color range Red .. Blue;
5018
5019 Type RGB_Color is a subrange of an implicit type which is a copy
5020 of type Color. If we call that implicit type RGB_ColorB ("B" is
5021 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5022 As a result, when an expression references any of the enumeral
5023 by name (Eg. "print green"), the expression is technically
5024 ambiguous and the user should be asked to disambiguate. But
5025 doing so would only hinder the user, since it wouldn't matter
5026 what choice he makes, the outcome would always be the same.
5027 So, for practical purposes, we consider them as the same. */
5028
5029 static int
symbols_are_identical_enums(const std::vector<struct block_symbol> & syms)5030 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5031 {
5032 int i;
5033
5034 /* Before performing a thorough comparison check of each type,
5035 we perform a series of inexpensive checks. We expect that these
5036 checks will quickly fail in the vast majority of cases, and thus
5037 help prevent the unnecessary use of a more expensive comparison.
5038 Said comparison also expects us to make some of these checks
5039 (see ada_identical_enum_types_p). */
5040
5041 /* Quick check: All symbols should have an enum type. */
5042 for (i = 0; i < syms.size (); i++)
5043 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5044 return 0;
5045
5046 /* Quick check: They should all have the same value. */
5047 for (i = 1; i < syms.size (); i++)
5048 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5049 return 0;
5050
5051 /* Quick check: They should all have the same number of enumerals. */
5052 for (i = 1; i < syms.size (); i++)
5053 if (syms[i].symbol->type ()->num_fields ()
5054 != syms[0].symbol->type ()->num_fields ())
5055 return 0;
5056
5057 /* All the sanity checks passed, so we might have a set of
5058 identical enumeration types. Perform a more complete
5059 comparison of the type of each symbol. */
5060 for (i = 1; i < syms.size (); i++)
5061 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5062 syms[0].symbol->type ()))
5063 return 0;
5064
5065 return 1;
5066 }
5067
5068 /* Remove any non-debugging symbols in SYMS that definitely
5069 duplicate other symbols in the list (The only case I know of where
5070 this happens is when object files containing stabs-in-ecoff are
5071 linked with files containing ordinary ecoff debugging symbols (or no
5072 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5073
5074 static void
remove_extra_symbols(std::vector<struct block_symbol> & syms)5075 remove_extra_symbols (std::vector<struct block_symbol> &syms)
5076 {
5077 int i, j;
5078
5079 /* We should never be called with less than 2 symbols, as there
5080 cannot be any extra symbol in that case. But it's easy to
5081 handle, since we have nothing to do in that case. */
5082 if (syms.size () < 2)
5083 return;
5084
5085 i = 0;
5086 while (i < syms.size ())
5087 {
5088 bool remove_p = false;
5089
5090 /* If two symbols have the same name and one of them is a stub type,
5091 the get rid of the stub. */
5092
5093 if (syms[i].symbol->type ()->is_stub ()
5094 && syms[i].symbol->linkage_name () != NULL)
5095 {
5096 for (j = 0; !remove_p && j < syms.size (); j++)
5097 {
5098 if (j != i
5099 && !syms[j].symbol->type ()->is_stub ()
5100 && syms[j].symbol->linkage_name () != NULL
5101 && strcmp (syms[i].symbol->linkage_name (),
5102 syms[j].symbol->linkage_name ()) == 0)
5103 remove_p = true;
5104 }
5105 }
5106
5107 /* Two symbols with the same name, same class and same address
5108 should be identical. */
5109
5110 else if (syms[i].symbol->linkage_name () != NULL
5111 && syms[i].symbol->aclass () == LOC_STATIC
5112 && is_nondebugging_type (syms[i].symbol->type ()))
5113 {
5114 for (j = 0; !remove_p && j < syms.size (); j += 1)
5115 {
5116 if (i != j
5117 && syms[j].symbol->linkage_name () != NULL
5118 && strcmp (syms[i].symbol->linkage_name (),
5119 syms[j].symbol->linkage_name ()) == 0
5120 && (syms[i].symbol->aclass ()
5121 == syms[j].symbol->aclass ())
5122 && syms[i].symbol->value_address ()
5123 == syms[j].symbol->value_address ())
5124 remove_p = true;
5125 }
5126 }
5127
5128 /* Two functions with the same block are identical. */
5129
5130 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5131 {
5132 for (j = 0; !remove_p && j < syms.size (); j += 1)
5133 {
5134 if (i != j
5135 && syms[j].symbol->aclass () == LOC_BLOCK
5136 && (syms[i].symbol->value_block ()
5137 == syms[j].symbol->value_block ()))
5138 remove_p = true;
5139 }
5140 }
5141
5142 if (remove_p)
5143 syms.erase (syms.begin () + i);
5144 else
5145 i += 1;
5146 }
5147 }
5148
5149 /* Given a type that corresponds to a renaming entity, use the type name
5150 to extract the scope (package name or function name, fully qualified,
5151 and following the GNAT encoding convention) where this renaming has been
5152 defined. */
5153
5154 static std::string
xget_renaming_scope(struct type * renaming_type)5155 xget_renaming_scope (struct type *renaming_type)
5156 {
5157 /* The renaming types adhere to the following convention:
5158 <scope>__<rename>___<XR extension>.
5159 So, to extract the scope, we search for the "___XR" extension,
5160 and then backtrack until we find the first "__". */
5161
5162 const char *name = renaming_type->name ();
5163 const char *suffix = strstr (name, "___XR");
5164 const char *last;
5165
5166 /* Now, backtrack a bit until we find the first "__". Start looking
5167 at suffix - 3, as the <rename> part is at least one character long. */
5168
5169 for (last = suffix - 3; last > name; last--)
5170 if (last[0] == '_' && last[1] == '_')
5171 break;
5172
5173 /* Make a copy of scope and return it. */
5174 return std::string (name, last);
5175 }
5176
5177 /* Return nonzero if NAME corresponds to a package name. */
5178
5179 static int
is_package_name(const char * name)5180 is_package_name (const char *name)
5181 {
5182 /* Here, We take advantage of the fact that no symbols are generated
5183 for packages, while symbols are generated for each function.
5184 So the condition for NAME represent a package becomes equivalent
5185 to NAME not existing in our list of symbols. There is only one
5186 small complication with library-level functions (see below). */
5187
5188 /* If it is a function that has not been defined at library level,
5189 then we should be able to look it up in the symbols. */
5190 if (standard_lookup (name, NULL, SEARCH_VFT) != NULL)
5191 return 0;
5192
5193 /* Library-level function names start with "_ada_". See if function
5194 "_ada_" followed by NAME can be found. */
5195
5196 /* Do a quick check that NAME does not contain "__", since library-level
5197 functions names cannot contain "__" in them. */
5198 if (strstr (name, "__") != NULL)
5199 return 0;
5200
5201 std::string fun_name = string_printf ("_ada_%s", name);
5202
5203 return (standard_lookup (fun_name.c_str (), NULL, SEARCH_VFT) == NULL);
5204 }
5205
5206 /* Return nonzero if SYM corresponds to a renaming entity that is
5207 not visible from FUNCTION_NAME. */
5208
5209 static int
old_renaming_is_invisible(const struct symbol * sym,const char * function_name)5210 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5211 {
5212 if (sym->aclass () != LOC_TYPEDEF)
5213 return 0;
5214
5215 std::string scope = xget_renaming_scope (sym->type ());
5216
5217 /* If the rename has been defined in a package, then it is visible. */
5218 if (is_package_name (scope.c_str ()))
5219 return 0;
5220
5221 /* Check that the rename is in the current function scope by checking
5222 that its name starts with SCOPE. */
5223
5224 /* If the function name starts with "_ada_", it means that it is
5225 a library-level function. Strip this prefix before doing the
5226 comparison, as the encoding for the renaming does not contain
5227 this prefix. */
5228 if (startswith (function_name, "_ada_"))
5229 function_name += 5;
5230
5231 return !startswith (function_name, scope.c_str ());
5232 }
5233
5234 /* Remove entries from SYMS that corresponds to a renaming entity that
5235 is not visible from the function associated with CURRENT_BLOCK or
5236 that is superfluous due to the presence of more specific renaming
5237 information. Places surviving symbols in the initial entries of
5238 SYMS.
5239
5240 Rationale:
5241 First, in cases where an object renaming is implemented as a
5242 reference variable, GNAT may produce both the actual reference
5243 variable and the renaming encoding. In this case, we discard the
5244 latter.
5245
5246 Second, GNAT emits a type following a specified encoding for each renaming
5247 entity. Unfortunately, STABS currently does not support the definition
5248 of types that are local to a given lexical block, so all renamings types
5249 are emitted at library level. As a consequence, if an application
5250 contains two renaming entities using the same name, and a user tries to
5251 print the value of one of these entities, the result of the ada symbol
5252 lookup will also contain the wrong renaming type.
5253
5254 This function partially covers for this limitation by attempting to
5255 remove from the SYMS list renaming symbols that should be visible
5256 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5257 method with the current information available. The implementation
5258 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5259
5260 - When the user tries to print a rename in a function while there
5261 is another rename entity defined in a package: Normally, the
5262 rename in the function has precedence over the rename in the
5263 package, so the latter should be removed from the list. This is
5264 currently not the case.
5265
5266 - This function will incorrectly remove valid renames if
5267 the CURRENT_BLOCK corresponds to a function which symbol name
5268 has been changed by an "Export" pragma. As a consequence,
5269 the user will be unable to print such rename entities. */
5270
5271 static void
remove_irrelevant_renamings(std::vector<struct block_symbol> * syms,const struct block * current_block)5272 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5273 const struct block *current_block)
5274 {
5275 struct symbol *current_function;
5276 const char *current_function_name;
5277 int i;
5278 int is_new_style_renaming;
5279
5280 /* If there is both a renaming foo___XR... encoded as a variable and
5281 a simple variable foo in the same block, discard the latter.
5282 First, zero out such symbols, then compress. */
5283 is_new_style_renaming = 0;
5284 for (i = 0; i < syms->size (); i += 1)
5285 {
5286 struct symbol *sym = (*syms)[i].symbol;
5287 const struct block *block = (*syms)[i].block;
5288 const char *name;
5289 const char *suffix;
5290
5291 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5292 continue;
5293 name = sym->linkage_name ();
5294 suffix = strstr (name, "___XR");
5295
5296 if (suffix != NULL)
5297 {
5298 int name_len = suffix - name;
5299 int j;
5300
5301 is_new_style_renaming = 1;
5302 for (j = 0; j < syms->size (); j += 1)
5303 if (i != j && (*syms)[j].symbol != NULL
5304 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5305 name_len) == 0
5306 && block == (*syms)[j].block)
5307 (*syms)[j].symbol = NULL;
5308 }
5309 }
5310 if (is_new_style_renaming)
5311 {
5312 int j, k;
5313
5314 for (j = k = 0; j < syms->size (); j += 1)
5315 if ((*syms)[j].symbol != NULL)
5316 {
5317 (*syms)[k] = (*syms)[j];
5318 k += 1;
5319 }
5320 syms->resize (k);
5321 return;
5322 }
5323
5324 /* Extract the function name associated to CURRENT_BLOCK.
5325 Abort if unable to do so. */
5326
5327 if (current_block == NULL)
5328 return;
5329
5330 current_function = current_block->linkage_function ();
5331 if (current_function == NULL)
5332 return;
5333
5334 current_function_name = current_function->linkage_name ();
5335 if (current_function_name == NULL)
5336 return;
5337
5338 /* Check each of the symbols, and remove it from the list if it is
5339 a type corresponding to a renaming that is out of the scope of
5340 the current block. */
5341
5342 i = 0;
5343 while (i < syms->size ())
5344 {
5345 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5346 == ADA_OBJECT_RENAMING
5347 && old_renaming_is_invisible ((*syms)[i].symbol,
5348 current_function_name))
5349 syms->erase (syms->begin () + i);
5350 else
5351 i += 1;
5352 }
5353 }
5354
5355 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5356 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5357
5358 Note: This function assumes that RESULT is empty. */
5359
5360 static void
ada_add_local_symbols(std::vector<struct block_symbol> & result,const lookup_name_info & lookup_name,const struct block * block,domain_search_flags domain)5361 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5362 const lookup_name_info &lookup_name,
5363 const struct block *block, domain_search_flags domain)
5364 {
5365 while (block != NULL)
5366 {
5367 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5368
5369 /* If we found a non-function match, assume that's the one. We
5370 only check this when finding a function boundary, so that we
5371 can accumulate all results from intervening blocks first. */
5372 if (block->function () != nullptr && is_nonfunction (result))
5373 return;
5374
5375 block = block->superblock ();
5376 }
5377 }
5378
5379 /* An object of this type is used as the callback argument when
5380 calling the map_matching_symbols method. */
5381
5382 struct match_data
5383 {
match_datamatch_data5384 explicit match_data (std::vector<struct block_symbol> *rp)
5385 : resultp (rp)
5386 {
5387 }
5388 DISABLE_COPY_AND_ASSIGN (match_data);
5389
5390 bool operator() (struct block_symbol *bsym);
5391
5392 struct objfile *objfile = nullptr;
5393 std::vector<struct block_symbol> *resultp;
5394 struct symbol *arg_sym = nullptr;
5395 bool found_sym = false;
5396 };
5397
5398 /* A callback for add_nonlocal_symbols that adds symbol, found in
5399 BSYM, to a list of symbols. */
5400
5401 bool
operator()5402 match_data::operator() (struct block_symbol *bsym)
5403 {
5404 const struct block *block = bsym->block;
5405 struct symbol *sym = bsym->symbol;
5406
5407 if (sym == NULL)
5408 {
5409 if (!found_sym && arg_sym != NULL)
5410 add_defn_to_vec (*resultp, arg_sym, block);
5411 found_sym = false;
5412 arg_sym = NULL;
5413 }
5414 else
5415 {
5416 if (sym->aclass () == LOC_UNRESOLVED)
5417 return true;
5418 else if (sym->is_argument ())
5419 arg_sym = sym;
5420 else
5421 {
5422 found_sym = true;
5423 add_defn_to_vec (*resultp, sym, block);
5424 }
5425 }
5426 return true;
5427 }
5428
5429 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5430 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5431 symbols to RESULT. Return whether we found such symbols. */
5432
5433 static int
ada_add_block_renamings(std::vector<struct block_symbol> & result,const struct block * block,const lookup_name_info & lookup_name,domain_search_flags domain)5434 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5435 const struct block *block,
5436 const lookup_name_info &lookup_name,
5437 domain_search_flags domain)
5438 {
5439 struct using_direct *renaming;
5440 int defns_mark = result.size ();
5441
5442 symbol_name_matcher_ftype *name_match
5443 = ada_get_symbol_name_matcher (lookup_name);
5444
5445 for (renaming = block->get_using ();
5446 renaming != NULL;
5447 renaming = renaming->next)
5448 {
5449 const char *r_name;
5450
5451 /* Avoid infinite recursions: skip this renaming if we are actually
5452 already traversing it.
5453
5454 Currently, symbol lookup in Ada don't use the namespace machinery from
5455 C++/Fortran support: skip namespace imports that use them. */
5456 if (renaming->searched
5457 || (renaming->import_src != NULL
5458 && renaming->import_src[0] != '\0')
5459 || (renaming->import_dest != NULL
5460 && renaming->import_dest[0] != '\0'))
5461 continue;
5462 renaming->searched = 1;
5463
5464 /* TODO: here, we perform another name-based symbol lookup, which can
5465 pull its own multiple overloads. In theory, we should be able to do
5466 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5467 not a simple name. But in order to do this, we would need to enhance
5468 the DWARF reader to associate a symbol to this renaming, instead of a
5469 name. So, for now, we do something simpler: re-use the C++/Fortran
5470 namespace machinery. */
5471 r_name = (renaming->alias != NULL
5472 ? renaming->alias
5473 : renaming->declaration);
5474 if (name_match (r_name, lookup_name, NULL))
5475 {
5476 lookup_name_info decl_lookup_name (renaming->declaration,
5477 lookup_name.match_type ());
5478 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5479 1, NULL);
5480 }
5481 renaming->searched = 0;
5482 }
5483 return result.size () != defns_mark;
5484 }
5485
5486 /* Convenience function to get at the Ada encoded lookup name for
5487 LOOKUP_NAME, as a C string. */
5488
5489 static const char *
ada_lookup_name(const lookup_name_info & lookup_name)5490 ada_lookup_name (const lookup_name_info &lookup_name)
5491 {
5492 return lookup_name.ada ().lookup_name ().c_str ();
5493 }
5494
5495 /* A helper for add_nonlocal_symbols. Expand all necessary symtabs
5496 for OBJFILE, then walk the objfile's symtabs and update the
5497 results. */
5498
5499 static void
map_matching_symbols(struct objfile * objfile,const lookup_name_info & lookup_name,domain_search_flags domain,int global,match_data & data)5500 map_matching_symbols (struct objfile *objfile,
5501 const lookup_name_info &lookup_name,
5502 domain_search_flags domain,
5503 int global,
5504 match_data &data)
5505 {
5506 data.objfile = objfile;
5507 objfile->expand_symtabs_matching (nullptr, &lookup_name,
5508 nullptr, nullptr,
5509 global
5510 ? SEARCH_GLOBAL_BLOCK
5511 : SEARCH_STATIC_BLOCK,
5512 domain);
5513
5514 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5515 for (compunit_symtab *symtab : objfile->compunits ())
5516 {
5517 const struct block *block
5518 = symtab->blockvector ()->block (block_kind);
5519 if (!iterate_over_symbols_terminated (block, lookup_name,
5520 domain, data))
5521 break;
5522 }
5523 }
5524
5525 /* Add to RESULT all non-local symbols whose name and domain match
5526 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5527 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5528 symbols otherwise. */
5529
5530 static void
add_nonlocal_symbols(std::vector<struct block_symbol> & result,const lookup_name_info & lookup_name,domain_search_flags domain,int global)5531 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5532 const lookup_name_info &lookup_name,
5533 domain_search_flags domain, int global)
5534 {
5535 struct match_data data (&result);
5536
5537 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5538
5539 for (objfile *objfile : current_program_space->objfiles ())
5540 {
5541 map_matching_symbols (objfile, lookup_name, domain, global, data);
5542
5543 for (compunit_symtab *cu : objfile->compunits ())
5544 {
5545 const struct block *global_block
5546 = cu->blockvector ()->global_block ();
5547
5548 if (ada_add_block_renamings (result, global_block, lookup_name,
5549 domain))
5550 data.found_sym = true;
5551 }
5552 }
5553
5554 if (result.empty () && global && !is_wild_match)
5555 {
5556 const char *name = ada_lookup_name (lookup_name);
5557 std::string bracket_name = std::string ("<_ada_") + name + '>';
5558 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5559
5560 for (objfile *objfile : current_program_space->objfiles ())
5561 map_matching_symbols (objfile, name1, domain, global, data);
5562 }
5563 }
5564
5565 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5566 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5567 returning the number of matches. Add these to RESULT.
5568
5569 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5570 symbol match within the nest of blocks whose innermost member is BLOCK,
5571 is the one match returned (no other matches in that or
5572 enclosing blocks is returned). If there are any matches in or
5573 surrounding BLOCK, then these alone are returned.
5574
5575 Names prefixed with "standard__" are handled specially:
5576 "standard__" is first stripped off (by the lookup_name
5577 constructor), and only static and global symbols are searched.
5578
5579 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5580 to lookup global symbols. */
5581
5582 static void
ada_add_all_symbols(std::vector<struct block_symbol> & result,const struct block * block,const lookup_name_info & lookup_name,domain_search_flags domain,int full_search,int * made_global_lookup_p)5583 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5584 const struct block *block,
5585 const lookup_name_info &lookup_name,
5586 domain_search_flags domain,
5587 int full_search,
5588 int *made_global_lookup_p)
5589 {
5590 struct symbol *sym;
5591
5592 if (made_global_lookup_p)
5593 *made_global_lookup_p = 0;
5594
5595 /* Special case: If the user specifies a symbol name inside package
5596 Standard, do a non-wild matching of the symbol name without
5597 the "standard__" prefix. This was primarily introduced in order
5598 to allow the user to specifically access the standard exceptions
5599 using, for instance, Standard.Constraint_Error when Constraint_Error
5600 is ambiguous (due to the user defining its own Constraint_Error
5601 entity inside its program). */
5602 if (lookup_name.ada ().standard_p ())
5603 block = NULL;
5604
5605 /* Check the non-global symbols. If we have ANY match, then we're done. */
5606
5607 if (block != NULL)
5608 {
5609 if (full_search)
5610 ada_add_local_symbols (result, lookup_name, block, domain);
5611 else
5612 {
5613 /* In the !full_search case we're are being called by
5614 iterate_over_symbols, and we don't want to search
5615 superblocks. */
5616 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5617 }
5618 if (!result.empty () || !full_search)
5619 return;
5620 }
5621
5622 /* No non-global symbols found. Check our cache to see if we have
5623 already performed this search before. If we have, then return
5624 the same result. */
5625
5626 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5627 domain, &sym, &block))
5628 {
5629 if (sym != NULL)
5630 add_defn_to_vec (result, sym, block);
5631 return;
5632 }
5633
5634 if (made_global_lookup_p)
5635 *made_global_lookup_p = 1;
5636
5637 /* Search symbols from all global blocks. */
5638
5639 add_nonlocal_symbols (result, lookup_name, domain, 1);
5640
5641 /* Now add symbols from all per-file blocks if we've gotten no hits
5642 (not strictly correct, but perhaps better than an error). */
5643
5644 if (result.empty ())
5645 add_nonlocal_symbols (result, lookup_name, domain, 0);
5646 }
5647
5648 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5649 is non-zero, enclosing scope and in global scopes.
5650
5651 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5652 blocks and symbol tables (if any) in which they were found.
5653
5654 When full_search is non-zero, any non-function/non-enumeral
5655 symbol match within the nest of blocks whose innermost member is BLOCK,
5656 is the one match returned (no other matches in that or
5657 enclosing blocks is returned). If there are any matches in or
5658 surrounding BLOCK, then these alone are returned.
5659
5660 Names prefixed with "standard__" are handled specially: "standard__"
5661 is first stripped off, and only static and global symbols are searched. */
5662
5663 static std::vector<struct block_symbol>
ada_lookup_symbol_list_worker(const lookup_name_info & lookup_name,const struct block * block,domain_search_flags domain,int full_search)5664 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5665 const struct block *block,
5666 domain_search_flags domain,
5667 int full_search)
5668 {
5669 int syms_from_global_search;
5670 std::vector<struct block_symbol> results;
5671
5672 ada_add_all_symbols (results, block, lookup_name,
5673 domain, full_search, &syms_from_global_search);
5674
5675 remove_extra_symbols (results);
5676
5677 if (results.empty () && full_search && syms_from_global_search)
5678 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5679
5680 if (results.size () == 1 && full_search && syms_from_global_search)
5681 cache_symbol (ada_lookup_name (lookup_name), domain,
5682 results[0].symbol, results[0].block);
5683
5684 remove_irrelevant_renamings (&results, block);
5685 return results;
5686 }
5687
5688 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5689 in global scopes, returning (SYM,BLOCK) tuples.
5690
5691 See ada_lookup_symbol_list_worker for further details. */
5692
5693 std::vector<struct block_symbol>
ada_lookup_symbol_list(const char * name,const struct block * block,domain_search_flags domain)5694 ada_lookup_symbol_list (const char *name, const struct block *block,
5695 domain_search_flags domain)
5696 {
5697 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5698 lookup_name_info lookup_name (name, name_match_type);
5699
5700 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5701 }
5702
5703 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5704 to 1, but choosing the first symbol found if there are multiple
5705 choices.
5706
5707 The result is stored in *INFO, which must be non-NULL.
5708 If no match is found, INFO->SYM is set to NULL. */
5709
5710 void
ada_lookup_encoded_symbol(const char * name,const struct block * block,domain_search_flags domain,struct block_symbol * info)5711 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5712 domain_search_flags domain,
5713 struct block_symbol *info)
5714 {
5715 /* Since we already have an encoded name, wrap it in '<>' to force a
5716 verbatim match. Otherwise, if the name happens to not look like
5717 an encoded name (because it doesn't include a "__"),
5718 ada_lookup_name_info would re-encode/fold it again, and that
5719 would e.g., incorrectly lowercase object renaming names like
5720 "R28b" -> "r28b". */
5721 std::string verbatim = add_angle_brackets (name);
5722
5723 gdb_assert (info != NULL);
5724 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5725 }
5726
5727 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5728 scope and in global scopes, or NULL if none. NAME is folded and
5729 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5730 choosing the first symbol if there are multiple choices. */
5731
5732 struct block_symbol
ada_lookup_symbol(const char * name,const struct block * block0,domain_search_flags domain)5733 ada_lookup_symbol (const char *name, const struct block *block0,
5734 domain_search_flags domain)
5735 {
5736 std::vector<struct block_symbol> candidates
5737 = ada_lookup_symbol_list (name, block0, domain);
5738
5739 if (candidates.empty ())
5740 return {};
5741
5742 return candidates[0];
5743 }
5744
5745
5746 /* True iff STR is a possible encoded suffix of a normal Ada name
5747 that is to be ignored for matching purposes. Suffixes of parallel
5748 names (e.g., XVE) are not included here. Currently, the possible suffixes
5749 are given by any of the regular expressions:
5750
5751 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5752 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5753 TKB [subprogram suffix for task bodies]
5754 _E[0-9]+[bs]$ [protected object entry suffixes]
5755 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5756
5757 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5758 match is performed. This sequence is used to differentiate homonyms,
5759 is an optional part of a valid name suffix. */
5760
5761 static int
is_name_suffix(const char * str)5762 is_name_suffix (const char *str)
5763 {
5764 int k;
5765 const char *matching;
5766 const int len = strlen (str);
5767
5768 /* Skip optional leading __[0-9]+. */
5769
5770 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5771 {
5772 str += 3;
5773 while (isdigit (str[0]))
5774 str += 1;
5775 }
5776
5777 /* [.$][0-9]+ */
5778
5779 if (str[0] == '.' || str[0] == '$')
5780 {
5781 matching = str + 1;
5782 while (isdigit (matching[0]))
5783 matching += 1;
5784 if (matching[0] == '\0')
5785 return 1;
5786 }
5787
5788 /* ___[0-9]+ */
5789
5790 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5791 {
5792 matching = str + 3;
5793 while (isdigit (matching[0]))
5794 matching += 1;
5795 if (matching[0] == '\0')
5796 return 1;
5797 }
5798
5799 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5800
5801 if (strcmp (str, "TKB") == 0)
5802 return 1;
5803
5804 #if 0
5805 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5806 with a N at the end. Unfortunately, the compiler uses the same
5807 convention for other internal types it creates. So treating
5808 all entity names that end with an "N" as a name suffix causes
5809 some regressions. For instance, consider the case of an enumerated
5810 type. To support the 'Image attribute, it creates an array whose
5811 name ends with N.
5812 Having a single character like this as a suffix carrying some
5813 information is a bit risky. Perhaps we should change the encoding
5814 to be something like "_N" instead. In the meantime, do not do
5815 the following check. */
5816 /* Protected Object Subprograms */
5817 if (len == 1 && str [0] == 'N')
5818 return 1;
5819 #endif
5820
5821 /* _E[0-9]+[bs]$ */
5822 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5823 {
5824 matching = str + 3;
5825 while (isdigit (matching[0]))
5826 matching += 1;
5827 if ((matching[0] == 'b' || matching[0] == 's')
5828 && matching [1] == '\0')
5829 return 1;
5830 }
5831
5832 /* ??? We should not modify STR directly, as we are doing below. This
5833 is fine in this case, but may become problematic later if we find
5834 that this alternative did not work, and want to try matching
5835 another one from the begining of STR. Since we modified it, we
5836 won't be able to find the begining of the string anymore! */
5837 if (str[0] == 'X')
5838 {
5839 str += 1;
5840 while (str[0] != '_' && str[0] != '\0')
5841 {
5842 if (str[0] != 'n' && str[0] != 'b')
5843 return 0;
5844 str += 1;
5845 }
5846 }
5847
5848 if (str[0] == '\000')
5849 return 1;
5850
5851 if (str[0] == '_')
5852 {
5853 if (str[1] != '_' || str[2] == '\000')
5854 return 0;
5855 if (str[2] == '_')
5856 {
5857 if (strcmp (str + 3, "JM") == 0)
5858 return 1;
5859 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5860 the LJM suffix in favor of the JM one. But we will
5861 still accept LJM as a valid suffix for a reasonable
5862 amount of time, just to allow ourselves to debug programs
5863 compiled using an older version of GNAT. */
5864 if (strcmp (str + 3, "LJM") == 0)
5865 return 1;
5866 if (str[3] != 'X')
5867 return 0;
5868 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5869 || str[4] == 'U' || str[4] == 'P')
5870 return 1;
5871 if (str[4] == 'R' && str[5] != 'T')
5872 return 1;
5873 return 0;
5874 }
5875 if (!isdigit (str[2]))
5876 return 0;
5877 for (k = 3; str[k] != '\0'; k += 1)
5878 if (!isdigit (str[k]) && str[k] != '_')
5879 return 0;
5880 return 1;
5881 }
5882 if (str[0] == '$' && isdigit (str[1]))
5883 {
5884 for (k = 2; str[k] != '\0'; k += 1)
5885 if (!isdigit (str[k]) && str[k] != '_')
5886 return 0;
5887 return 1;
5888 }
5889 return 0;
5890 }
5891
5892 /* Return non-zero if the string starting at NAME and ending before
5893 NAME_END contains no capital letters. */
5894
5895 static int
is_valid_name_for_wild_match(const char * name0)5896 is_valid_name_for_wild_match (const char *name0)
5897 {
5898 std::string decoded_name = ada_decode (name0);
5899 int i;
5900
5901 /* If the decoded name starts with an angle bracket, it means that
5902 NAME0 does not follow the GNAT encoding format. It should then
5903 not be allowed as a possible wild match. */
5904 if (decoded_name[0] == '<')
5905 return 0;
5906
5907 for (i=0; decoded_name[i] != '\0'; i++)
5908 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5909 return 0;
5910
5911 return 1;
5912 }
5913
5914 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5915 character which could start a simple name. Assumes that *NAMEP points
5916 somewhere inside the string beginning at NAME0. */
5917
5918 static int
advance_wild_match(const char ** namep,const char * name0,char target0)5919 advance_wild_match (const char **namep, const char *name0, char target0)
5920 {
5921 const char *name = *namep;
5922
5923 while (1)
5924 {
5925 char t0, t1;
5926
5927 t0 = *name;
5928 if (t0 == '_')
5929 {
5930 t1 = name[1];
5931 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5932 {
5933 name += 1;
5934 if (name == name0 + 5 && startswith (name0, "_ada"))
5935 break;
5936 else
5937 name += 1;
5938 }
5939 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5940 || name[2] == target0))
5941 {
5942 name += 2;
5943 break;
5944 }
5945 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5946 {
5947 /* Names like "pkg__B_N__name", where N is a number, are
5948 block-local. We can handle these by simply skipping
5949 the "B_" here. */
5950 name += 4;
5951 }
5952 else
5953 return 0;
5954 }
5955 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5956 name += 1;
5957 else
5958 return 0;
5959 }
5960
5961 *namep = name;
5962 return 1;
5963 }
5964
5965 /* Return true iff NAME encodes a name of the form prefix.PATN.
5966 Ignores any informational suffixes of NAME (i.e., for which
5967 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5968 simple name. */
5969
5970 static bool
wild_match(const char * name,const char * patn)5971 wild_match (const char *name, const char *patn)
5972 {
5973 const char *p;
5974 const char *name0 = name;
5975
5976 if (startswith (name, "___ghost_"))
5977 name += 9;
5978
5979 while (1)
5980 {
5981 const char *match = name;
5982
5983 if (*name == *patn)
5984 {
5985 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5986 if (*p != *name)
5987 break;
5988 if (*p == '\0' && is_name_suffix (name))
5989 return match == name0 || is_valid_name_for_wild_match (name0);
5990
5991 if (name[-1] == '_')
5992 name -= 1;
5993 }
5994 if (!advance_wild_match (&name, name0, *patn))
5995 return false;
5996 }
5997 }
5998
5999 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6000 necessary). OBJFILE is the section containing BLOCK. */
6001
6002 static void
ada_add_block_symbols(std::vector<struct block_symbol> & result,const struct block * block,const lookup_name_info & lookup_name,domain_search_flags domain,struct objfile * objfile)6003 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6004 const struct block *block,
6005 const lookup_name_info &lookup_name,
6006 domain_search_flags domain, struct objfile *objfile)
6007 {
6008 /* A matching argument symbol, if any. */
6009 struct symbol *arg_sym;
6010 /* Set true when we find a matching non-argument symbol. */
6011 bool found_sym;
6012
6013 arg_sym = NULL;
6014 found_sym = false;
6015 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
6016 {
6017 if (sym->matches (domain))
6018 {
6019 if (sym->aclass () != LOC_UNRESOLVED)
6020 {
6021 if (sym->is_argument ())
6022 arg_sym = sym;
6023 else
6024 {
6025 found_sym = true;
6026 add_defn_to_vec (result, sym, block);
6027 }
6028 }
6029 }
6030 }
6031
6032 /* Handle renamings. */
6033
6034 if (ada_add_block_renamings (result, block, lookup_name, domain))
6035 found_sym = true;
6036
6037 if (!found_sym && arg_sym != NULL)
6038 {
6039 add_defn_to_vec (result, arg_sym, block);
6040 }
6041
6042 if (!lookup_name.ada ().wild_match_p ())
6043 {
6044 arg_sym = NULL;
6045 found_sym = false;
6046 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6047 const char *name = ada_lookup_name.c_str ();
6048 size_t name_len = ada_lookup_name.size ();
6049
6050 for (struct symbol *sym : block_iterator_range (block))
6051 {
6052 if (sym->matches (domain))
6053 {
6054 int cmp;
6055
6056 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6057 if (cmp == 0)
6058 {
6059 cmp = !startswith (sym->linkage_name (), "_ada_");
6060 if (cmp == 0)
6061 cmp = strncmp (name, sym->linkage_name () + 5,
6062 name_len);
6063 }
6064
6065 if (cmp == 0
6066 && is_name_suffix (sym->linkage_name () + name_len + 5))
6067 {
6068 if (sym->aclass () != LOC_UNRESOLVED)
6069 {
6070 if (sym->is_argument ())
6071 arg_sym = sym;
6072 else
6073 {
6074 found_sym = true;
6075 add_defn_to_vec (result, sym, block);
6076 }
6077 }
6078 }
6079 }
6080 }
6081
6082 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6083 They aren't parameters, right? */
6084 if (!found_sym && arg_sym != NULL)
6085 {
6086 add_defn_to_vec (result, arg_sym, block);
6087 }
6088 }
6089 }
6090
6091
6092 /* Symbol Completion */
6093
6094 /* See symtab.h. */
6095
6096 bool
matches(const char * sym_name,symbol_name_match_type match_type,completion_match_result * comp_match_res)6097 ada_lookup_name_info::matches
6098 (const char *sym_name,
6099 symbol_name_match_type match_type,
6100 completion_match_result *comp_match_res) const
6101 {
6102 bool match = false;
6103 const char *text = m_encoded_name.c_str ();
6104 size_t text_len = m_encoded_name.size ();
6105
6106 /* First, test against the fully qualified name of the symbol. */
6107
6108 if (strncmp (sym_name, text, text_len) == 0)
6109 match = true;
6110
6111 std::string decoded_name = ada_decode (sym_name);
6112 if (match && !m_encoded_p)
6113 {
6114 /* One needed check before declaring a positive match is to verify
6115 that iff we are doing a verbatim match, the decoded version
6116 of the symbol name starts with '<'. Otherwise, this symbol name
6117 is not a suitable completion. */
6118
6119 bool has_angle_bracket = (decoded_name[0] == '<');
6120 match = (has_angle_bracket == m_verbatim_p);
6121 }
6122
6123 if (match && !m_verbatim_p)
6124 {
6125 /* When doing non-verbatim match, another check that needs to
6126 be done is to verify that the potentially matching symbol name
6127 does not include capital letters, because the ada-mode would
6128 not be able to understand these symbol names without the
6129 angle bracket notation. */
6130 const char *tmp;
6131
6132 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6133 if (*tmp != '\0')
6134 match = false;
6135 }
6136
6137 /* Second: Try wild matching... */
6138
6139 if (!match && m_wild_match_p)
6140 {
6141 /* Since we are doing wild matching, this means that TEXT
6142 may represent an unqualified symbol name. We therefore must
6143 also compare TEXT against the unqualified name of the symbol. */
6144 sym_name = ada_unqualified_name (decoded_name.c_str ());
6145
6146 if (strncmp (sym_name, text, text_len) == 0)
6147 match = true;
6148 }
6149
6150 /* Finally: If we found a match, prepare the result to return. */
6151
6152 if (!match)
6153 return false;
6154
6155 if (comp_match_res != NULL)
6156 {
6157 std::string &match_str = comp_match_res->match.storage ();
6158
6159 if (!m_encoded_p)
6160 match_str = ada_decode (sym_name);
6161 else
6162 {
6163 if (m_verbatim_p)
6164 match_str = add_angle_brackets (sym_name);
6165 else
6166 match_str = sym_name;
6167
6168 }
6169
6170 comp_match_res->set_match (match_str.c_str ());
6171 }
6172
6173 return true;
6174 }
6175
6176 /* Field Access */
6177
6178 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6179 for tagged types. */
6180
6181 static int
ada_is_dispatch_table_ptr_type(struct type * type)6182 ada_is_dispatch_table_ptr_type (struct type *type)
6183 {
6184 const char *name;
6185
6186 if (type->code () != TYPE_CODE_PTR)
6187 return 0;
6188
6189 name = type->target_type ()->name ();
6190 if (name == NULL)
6191 return 0;
6192
6193 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6194 }
6195
6196 /* Return non-zero if TYPE is an interface tag. */
6197
6198 static int
ada_is_interface_tag(struct type * type)6199 ada_is_interface_tag (struct type *type)
6200 {
6201 const char *name = type->name ();
6202
6203 if (name == NULL)
6204 return 0;
6205
6206 return (strcmp (name, "ada__tags__interface_tag") == 0);
6207 }
6208
6209 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6210 to be invisible to users. */
6211
6212 int
ada_is_ignored_field(struct type * type,int field_num)6213 ada_is_ignored_field (struct type *type, int field_num)
6214 {
6215 if (field_num < 0 || field_num > type->num_fields ())
6216 return 1;
6217
6218 /* Check the name of that field. */
6219 {
6220 const char *name = type->field (field_num).name ();
6221
6222 /* Anonymous field names should not be printed.
6223 brobecker/2007-02-20: I don't think this can actually happen
6224 but we don't want to print the value of anonymous fields anyway. */
6225 if (name == NULL)
6226 return 1;
6227
6228 /* Normally, fields whose name start with an underscore ("_")
6229 are fields that have been internally generated by the compiler,
6230 and thus should not be printed. The "_parent" field is special,
6231 however: This is a field internally generated by the compiler
6232 for tagged types, and it contains the components inherited from
6233 the parent type. This field should not be printed as is, but
6234 should not be ignored either. */
6235 if (name[0] == '_' && !startswith (name, "_parent"))
6236 return 1;
6237
6238 /* The compiler doesn't document this, but sometimes it emits
6239 a field whose name starts with a capital letter, like 'V148s'.
6240 These aren't marked as artificial in any way, but we know they
6241 should be ignored. However, wrapper fields should not be
6242 ignored. */
6243 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6244 {
6245 /* Wrapper field. */
6246 }
6247 else if (isupper (name[0]))
6248 return 1;
6249 }
6250
6251 /* If this is the dispatch table of a tagged type or an interface tag,
6252 then ignore. */
6253 if (ada_is_tagged_type (type, 1)
6254 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6255 || ada_is_interface_tag (type->field (field_num).type ())))
6256 return 1;
6257
6258 /* Not a special field, so it should not be ignored. */
6259 return 0;
6260 }
6261
6262 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6263 pointer or reference type whose ultimate target has a tag field. */
6264
6265 int
ada_is_tagged_type(struct type * type,int refok)6266 ada_is_tagged_type (struct type *type, int refok)
6267 {
6268 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6269 }
6270
6271 /* True iff TYPE represents the type of X'Tag */
6272
6273 int
ada_is_tag_type(struct type * type)6274 ada_is_tag_type (struct type *type)
6275 {
6276 type = ada_check_typedef (type);
6277
6278 if (type == NULL || type->code () != TYPE_CODE_PTR)
6279 return 0;
6280 else
6281 {
6282 const char *name = ada_type_name (type->target_type ());
6283
6284 return (name != NULL
6285 && strcmp (name, "ada__tags__dispatch_table") == 0);
6286 }
6287 }
6288
6289 /* The type of the tag on VAL. */
6290
6291 static struct type *
ada_tag_type(struct value * val)6292 ada_tag_type (struct value *val)
6293 {
6294 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6295 }
6296
6297 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6298 retired at Ada 05). */
6299
6300 static int
is_ada95_tag(struct value * tag)6301 is_ada95_tag (struct value *tag)
6302 {
6303 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6304 }
6305
6306 /* The value of the tag on VAL. */
6307
6308 static struct value *
ada_value_tag(struct value * val)6309 ada_value_tag (struct value *val)
6310 {
6311 return ada_value_struct_elt (val, "_tag", 0);
6312 }
6313
6314 /* The value of the tag on the object of type TYPE whose contents are
6315 saved at VALADDR, if it is non-null, or is at memory address
6316 ADDRESS. */
6317
6318 static struct value *
value_tag_from_contents_and_address(struct type * type,const gdb_byte * valaddr,CORE_ADDR address)6319 value_tag_from_contents_and_address (struct type *type,
6320 const gdb_byte *valaddr,
6321 CORE_ADDR address)
6322 {
6323 int tag_byte_offset;
6324 struct type *tag_type;
6325
6326 gdb::array_view<const gdb_byte> contents;
6327 if (valaddr != nullptr)
6328 contents = gdb::make_array_view (valaddr, type->length ());
6329 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6330 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6331 NULL, NULL, NULL))
6332 {
6333 const gdb_byte *valaddr1 = ((valaddr == NULL)
6334 ? NULL
6335 : valaddr + tag_byte_offset);
6336 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6337
6338 return value_from_contents_and_address (tag_type, valaddr1, address1);
6339 }
6340 return NULL;
6341 }
6342
6343 static struct type *
type_from_tag(struct value * tag)6344 type_from_tag (struct value *tag)
6345 {
6346 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6347
6348 if (type_name != NULL)
6349 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6350 return NULL;
6351 }
6352
6353 /* Given a value OBJ of a tagged type, return a value of this
6354 type at the base address of the object. The base address, as
6355 defined in Ada.Tags, it is the address of the primary tag of
6356 the object, and therefore where the field values of its full
6357 view can be fetched. */
6358
6359 struct value *
ada_tag_value_at_base_address(struct value * obj)6360 ada_tag_value_at_base_address (struct value *obj)
6361 {
6362 struct value *val;
6363 LONGEST offset_to_top = 0;
6364 struct type *ptr_type, *obj_type;
6365 struct value *tag;
6366 CORE_ADDR base_address;
6367
6368 obj_type = obj->type ();
6369
6370 /* It is the responsibility of the caller to deref pointers. */
6371
6372 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6373 return obj;
6374
6375 tag = ada_value_tag (obj);
6376 if (!tag)
6377 return obj;
6378
6379 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6380
6381 if (is_ada95_tag (tag))
6382 return obj;
6383
6384 struct type *offset_type
6385 = language_lookup_primitive_type (language_def (language_ada),
6386 current_inferior ()->arch (),
6387 "storage_offset");
6388 ptr_type = lookup_pointer_type (offset_type);
6389 val = value_cast (ptr_type, tag);
6390 if (!val)
6391 return obj;
6392
6393 /* It is perfectly possible that an exception be raised while
6394 trying to determine the base address, just like for the tag;
6395 see ada_tag_name for more details. We do not print the error
6396 message for the same reason. */
6397
6398 try
6399 {
6400 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6401 }
6402
6403 catch (const gdb_exception_error &e)
6404 {
6405 return obj;
6406 }
6407
6408 /* If offset is null, nothing to do. */
6409
6410 if (offset_to_top == 0)
6411 return obj;
6412
6413 /* -1 is a special case in Ada.Tags; however, what should be done
6414 is not quite clear from the documentation. So do nothing for
6415 now. */
6416
6417 if (offset_to_top == -1)
6418 return obj;
6419
6420 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6421 top is used. In this situation the offset is stored just after
6422 the tag, in the object itself. */
6423 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6424 if (offset_to_top == last)
6425 {
6426 struct value *tem = value_addr (tag);
6427 tem = value_ptradd (tem, 1);
6428 tem = value_cast (ptr_type, tem);
6429 offset_to_top = value_as_long (value_ind (tem));
6430 }
6431
6432 if (offset_to_top > 0)
6433 {
6434 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6435 from the base address. This was however incompatible with
6436 C++ dispatch table: C++ uses a *negative* value to *add*
6437 to the base address. Ada's convention has therefore been
6438 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6439 use the same convention. Here, we support both cases by
6440 checking the sign of OFFSET_TO_TOP. */
6441 offset_to_top = -offset_to_top;
6442 }
6443
6444 base_address = obj->address () + offset_to_top;
6445 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6446
6447 /* Make sure that we have a proper tag at the new address.
6448 Otherwise, offset_to_top is bogus (which can happen when
6449 the object is not initialized yet). */
6450
6451 if (!tag)
6452 return obj;
6453
6454 obj_type = type_from_tag (tag);
6455
6456 if (!obj_type)
6457 return obj;
6458
6459 return value_from_contents_and_address (obj_type, NULL, base_address);
6460 }
6461
6462 /* Return the "ada__tags__type_specific_data" type. */
6463
6464 static struct type *
ada_get_tsd_type(struct inferior * inf)6465 ada_get_tsd_type (struct inferior *inf)
6466 {
6467 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6468
6469 if (data->tsd_type == 0)
6470 data->tsd_type
6471 = lookup_transparent_type ("<ada__tags__type_specific_data>",
6472 SEARCH_TYPE_DOMAIN);
6473 return data->tsd_type;
6474 }
6475
6476 /* Return the TSD (type-specific data) associated to the given TAG.
6477 TAG is assumed to be the tag of a tagged-type entity.
6478
6479 May return NULL if we are unable to get the TSD. */
6480
6481 static struct value *
ada_get_tsd_from_tag(struct value * tag)6482 ada_get_tsd_from_tag (struct value *tag)
6483 {
6484 struct value *val;
6485 struct type *type;
6486
6487 /* First option: The TSD is simply stored as a field of our TAG.
6488 Only older versions of GNAT would use this format, but we have
6489 to test it first, because there are no visible markers for
6490 the current approach except the absence of that field. */
6491
6492 val = ada_value_struct_elt (tag, "tsd", 1);
6493 if (val)
6494 return val;
6495
6496 /* Try the second representation for the dispatch table (in which
6497 there is no explicit 'tsd' field in the referent of the tag pointer,
6498 and instead the tsd pointer is stored just before the dispatch
6499 table. */
6500
6501 type = ada_get_tsd_type (current_inferior());
6502 if (type == NULL)
6503 return NULL;
6504 type = lookup_pointer_type (lookup_pointer_type (type));
6505 val = value_cast (type, tag);
6506 if (val == NULL)
6507 return NULL;
6508 return value_ind (value_ptradd (val, -1));
6509 }
6510
6511 /* Given the TSD of a tag (type-specific data), return a string
6512 containing the name of the associated type.
6513
6514 May return NULL if we are unable to determine the tag name. */
6515
6516 static gdb::unique_xmalloc_ptr<char>
ada_tag_name_from_tsd(struct value * tsd)6517 ada_tag_name_from_tsd (struct value *tsd)
6518 {
6519 struct value *val;
6520
6521 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6522 if (val == NULL)
6523 return NULL;
6524 gdb::unique_xmalloc_ptr<char> buffer
6525 = target_read_string (value_as_address (val), INT_MAX);
6526 if (buffer == nullptr)
6527 return nullptr;
6528
6529 try
6530 {
6531 /* Let this throw an exception on error. If the data is
6532 uninitialized, we'd rather not have the user see a
6533 warning. */
6534 const char *folded = ada_fold_name (buffer.get (), true);
6535 return make_unique_xstrdup (folded);
6536 }
6537 catch (const gdb_exception &)
6538 {
6539 return nullptr;
6540 }
6541 }
6542
6543 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6544 a C string.
6545
6546 Return NULL if the TAG is not an Ada tag, or if we were unable to
6547 determine the name of that tag. */
6548
6549 gdb::unique_xmalloc_ptr<char>
ada_tag_name(struct value * tag)6550 ada_tag_name (struct value *tag)
6551 {
6552 gdb::unique_xmalloc_ptr<char> name;
6553
6554 if (!ada_is_tag_type (tag->type ()))
6555 return NULL;
6556
6557 /* It is perfectly possible that an exception be raised while trying
6558 to determine the TAG's name, even under normal circumstances:
6559 The associated variable may be uninitialized or corrupted, for
6560 instance. We do not let any exception propagate past this point.
6561 instead we return NULL.
6562
6563 We also do not print the error message either (which often is very
6564 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6565 the caller print a more meaningful message if necessary. */
6566 try
6567 {
6568 struct value *tsd = ada_get_tsd_from_tag (tag);
6569
6570 if (tsd != NULL)
6571 name = ada_tag_name_from_tsd (tsd);
6572 }
6573 catch (const gdb_exception_error &e)
6574 {
6575 }
6576
6577 return name;
6578 }
6579
6580 /* The parent type of TYPE, or NULL if none. */
6581
6582 struct type *
ada_parent_type(struct type * type)6583 ada_parent_type (struct type *type)
6584 {
6585 int i;
6586
6587 type = ada_check_typedef (type);
6588
6589 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6590 return NULL;
6591
6592 for (i = 0; i < type->num_fields (); i += 1)
6593 if (ada_is_parent_field (type, i))
6594 {
6595 struct type *parent_type = type->field (i).type ();
6596
6597 /* If the _parent field is a pointer, then dereference it. */
6598 if (parent_type->code () == TYPE_CODE_PTR)
6599 parent_type = parent_type->target_type ();
6600 /* If there is a parallel XVS type, get the actual base type. */
6601 parent_type = ada_get_base_type (parent_type);
6602
6603 return ada_check_typedef (parent_type);
6604 }
6605
6606 return NULL;
6607 }
6608
6609 /* True iff field number FIELD_NUM of structure type TYPE contains the
6610 parent-type (inherited) fields of a derived type. Assumes TYPE is
6611 a structure type with at least FIELD_NUM+1 fields. */
6612
6613 int
ada_is_parent_field(struct type * type,int field_num)6614 ada_is_parent_field (struct type *type, int field_num)
6615 {
6616 const char *name = ada_check_typedef (type)->field (field_num).name ();
6617
6618 return (name != NULL
6619 && (startswith (name, "PARENT")
6620 || startswith (name, "_parent")));
6621 }
6622
6623 /* True iff field number FIELD_NUM of structure type TYPE is a
6624 transparent wrapper field (which should be silently traversed when doing
6625 field selection and flattened when printing). Assumes TYPE is a
6626 structure type with at least FIELD_NUM+1 fields. Such fields are always
6627 structures. */
6628
6629 int
ada_is_wrapper_field(struct type * type,int field_num)6630 ada_is_wrapper_field (struct type *type, int field_num)
6631 {
6632 const char *name = type->field (field_num).name ();
6633
6634 if (name != NULL && strcmp (name, "RETVAL") == 0)
6635 {
6636 /* This happens in functions with "out" or "in out" parameters
6637 which are passed by copy. For such functions, GNAT describes
6638 the function's return type as being a struct where the return
6639 value is in a field called RETVAL, and where the other "out"
6640 or "in out" parameters are fields of that struct. This is not
6641 a wrapper. */
6642 return 0;
6643 }
6644
6645 return (name != NULL
6646 && (startswith (name, "PARENT")
6647 || strcmp (name, "REP") == 0
6648 || startswith (name, "_parent")
6649 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6650 }
6651
6652 /* True iff field number FIELD_NUM of structure or union type TYPE
6653 is a variant wrapper. Assumes TYPE is a structure type with at least
6654 FIELD_NUM+1 fields. */
6655
6656 int
ada_is_variant_part(struct type * type,int field_num)6657 ada_is_variant_part (struct type *type, int field_num)
6658 {
6659 /* Only Ada types are eligible. */
6660 if (!ADA_TYPE_P (type))
6661 return 0;
6662
6663 struct type *field_type = type->field (field_num).type ();
6664
6665 return (field_type->code () == TYPE_CODE_UNION
6666 || (is_dynamic_field (type, field_num)
6667 && (field_type->target_type ()->code ()
6668 == TYPE_CODE_UNION)));
6669 }
6670
6671 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6672 whose discriminants are contained in the record type OUTER_TYPE,
6673 returns the type of the controlling discriminant for the variant.
6674 May return NULL if the type could not be found. */
6675
6676 struct type *
ada_variant_discrim_type(struct type * var_type,struct type * outer_type)6677 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6678 {
6679 const char *name = ada_variant_discrim_name (var_type);
6680
6681 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6682 }
6683
6684 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6685 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6686 represents a 'when others' clause; otherwise 0. */
6687
6688 static int
ada_is_others_clause(struct type * type,int field_num)6689 ada_is_others_clause (struct type *type, int field_num)
6690 {
6691 const char *name = type->field (field_num).name ();
6692
6693 return (name != NULL && name[0] == 'O');
6694 }
6695
6696 /* Assuming that TYPE0 is the type of the variant part of a record,
6697 returns the name of the discriminant controlling the variant.
6698 The value is valid until the next call to ada_variant_discrim_name. */
6699
6700 const char *
ada_variant_discrim_name(struct type * type0)6701 ada_variant_discrim_name (struct type *type0)
6702 {
6703 static std::string result;
6704 struct type *type;
6705 const char *name;
6706 const char *discrim_end;
6707 const char *discrim_start;
6708
6709 if (type0->code () == TYPE_CODE_PTR)
6710 type = type0->target_type ();
6711 else
6712 type = type0;
6713
6714 name = ada_type_name (type);
6715
6716 if (name == NULL || name[0] == '\000')
6717 return "";
6718
6719 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6720 discrim_end -= 1)
6721 {
6722 if (startswith (discrim_end, "___XVN"))
6723 break;
6724 }
6725 if (discrim_end == name)
6726 return "";
6727
6728 for (discrim_start = discrim_end; discrim_start != name + 3;
6729 discrim_start -= 1)
6730 {
6731 if (discrim_start == name + 1)
6732 return "";
6733 if ((discrim_start > name + 3
6734 && startswith (discrim_start - 3, "___"))
6735 || discrim_start[-1] == '.')
6736 break;
6737 }
6738
6739 result = std::string (discrim_start, discrim_end - discrim_start);
6740 return result.c_str ();
6741 }
6742
6743 /* Scan STR for a subtype-encoded number, beginning at position K.
6744 Put the position of the character just past the number scanned in
6745 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6746 Return 1 if there was a valid number at the given position, and 0
6747 otherwise. A "subtype-encoded" number consists of the absolute value
6748 in decimal, followed by the letter 'm' to indicate a negative number.
6749 Assumes 0m does not occur. */
6750
6751 int
ada_scan_number(const char str[],int k,LONGEST * R,int * new_k)6752 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6753 {
6754 ULONGEST RU;
6755
6756 if (!isdigit (str[k]))
6757 return 0;
6758
6759 /* Do it the hard way so as not to make any assumption about
6760 the relationship of unsigned long (%lu scan format code) and
6761 LONGEST. */
6762 RU = 0;
6763 while (isdigit (str[k]))
6764 {
6765 RU = RU * 10 + (str[k] - '0');
6766 k += 1;
6767 }
6768
6769 if (str[k] == 'm')
6770 {
6771 if (R != NULL)
6772 *R = (-(LONGEST) (RU - 1)) - 1;
6773 k += 1;
6774 }
6775 else if (R != NULL)
6776 *R = (LONGEST) RU;
6777
6778 /* NOTE on the above: Technically, C does not say what the results of
6779 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6780 number representable as a LONGEST (although either would probably work
6781 in most implementations). When RU>0, the locution in the then branch
6782 above is always equivalent to the negative of RU. */
6783
6784 if (new_k != NULL)
6785 *new_k = k;
6786 return 1;
6787 }
6788
6789 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6790 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6791 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6792
6793 static int
ada_in_variant(LONGEST val,struct type * type,int field_num)6794 ada_in_variant (LONGEST val, struct type *type, int field_num)
6795 {
6796 const char *name = type->field (field_num).name ();
6797 int p;
6798
6799 p = 0;
6800 while (1)
6801 {
6802 switch (name[p])
6803 {
6804 case '\0':
6805 return 0;
6806 case 'S':
6807 {
6808 LONGEST W;
6809
6810 if (!ada_scan_number (name, p + 1, &W, &p))
6811 return 0;
6812 if (val == W)
6813 return 1;
6814 break;
6815 }
6816 case 'R':
6817 {
6818 LONGEST L, U;
6819
6820 if (!ada_scan_number (name, p + 1, &L, &p)
6821 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6822 return 0;
6823 if (val >= L && val <= U)
6824 return 1;
6825 break;
6826 }
6827 case 'O':
6828 return 1;
6829 default:
6830 return 0;
6831 }
6832 }
6833 }
6834
6835 /* FIXME: Lots of redundancy below. Try to consolidate. */
6836
6837 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6838 ARG_TYPE, extract and return the value of one of its (non-static)
6839 fields. FIELDNO says which field. Differs from value_primitive_field
6840 only in that it can handle packed values of arbitrary type. */
6841
6842 struct value *
ada_value_primitive_field(struct value * arg1,int offset,int fieldno,struct type * arg_type)6843 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6844 struct type *arg_type)
6845 {
6846 struct type *type;
6847
6848 arg_type = ada_check_typedef (arg_type);
6849 type = arg_type->field (fieldno).type ();
6850
6851 /* Handle packed fields. It might be that the field is not packed
6852 relative to its containing structure, but the structure itself is
6853 packed; in this case we must take the bit-field path. */
6854 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
6855 {
6856 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6857 int bit_size = arg_type->field (fieldno).bitsize ();
6858
6859 return ada_value_primitive_packed_val (arg1,
6860 arg1->contents ().data (),
6861 offset + bit_pos / 8,
6862 bit_pos % 8, bit_size, type);
6863 }
6864 else
6865 return arg1->primitive_field (offset, fieldno, arg_type);
6866 }
6867
6868 /* Find field with name NAME in object of type TYPE. If found,
6869 set the following for each argument that is non-null:
6870 - *FIELD_TYPE_P to the field's type;
6871 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6872 an object of that type;
6873 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6874 - *BIT_SIZE_P to its size in bits if the field is packed, and
6875 0 otherwise;
6876 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6877 fields up to but not including the desired field, or by the total
6878 number of fields if not found. A NULL value of NAME never
6879 matches; the function just counts visible fields in this case.
6880
6881 Notice that we need to handle when a tagged record hierarchy
6882 has some components with the same name, like in this scenario:
6883
6884 type Top_T is tagged record
6885 N : Integer := 1;
6886 U : Integer := 974;
6887 A : Integer := 48;
6888 end record;
6889
6890 type Middle_T is new Top.Top_T with record
6891 N : Character := 'a';
6892 C : Integer := 3;
6893 end record;
6894
6895 type Bottom_T is new Middle.Middle_T with record
6896 N : Float := 4.0;
6897 C : Character := '5';
6898 X : Integer := 6;
6899 A : Character := 'J';
6900 end record;
6901
6902 Let's say we now have a variable declared and initialized as follow:
6903
6904 TC : Top_A := new Bottom_T;
6905
6906 And then we use this variable to call this function
6907
6908 procedure Assign (Obj: in out Top_T; TV : Integer);
6909
6910 as follow:
6911
6912 Assign (Top_T (B), 12);
6913
6914 Now, we're in the debugger, and we're inside that procedure
6915 then and we want to print the value of obj.c:
6916
6917 Usually, the tagged record or one of the parent type owns the
6918 component to print and there's no issue but in this particular
6919 case, what does it mean to ask for Obj.C? Since the actual
6920 type for object is type Bottom_T, it could mean two things: type
6921 component C from the Middle_T view, but also component C from
6922 Bottom_T. So in that "undefined" case, when the component is
6923 not found in the non-resolved type (which includes all the
6924 components of the parent type), then resolve it and see if we
6925 get better luck once expanded.
6926
6927 In the case of homonyms in the derived tagged type, we don't
6928 guaranty anything, and pick the one that's easiest for us
6929 to program.
6930
6931 Returns 1 if found, 0 otherwise. */
6932
6933 static int
find_struct_field(const char * name,struct type * type,int offset,struct type ** field_type_p,int * byte_offset_p,int * bit_offset_p,int * bit_size_p,int * index_p)6934 find_struct_field (const char *name, struct type *type, int offset,
6935 struct type **field_type_p,
6936 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6937 int *index_p)
6938 {
6939 int i;
6940 int parent_offset = -1;
6941
6942 type = ada_check_typedef (type);
6943
6944 if (field_type_p != NULL)
6945 *field_type_p = NULL;
6946 if (byte_offset_p != NULL)
6947 *byte_offset_p = 0;
6948 if (bit_offset_p != NULL)
6949 *bit_offset_p = 0;
6950 if (bit_size_p != NULL)
6951 *bit_size_p = 0;
6952
6953 for (i = 0; i < type->num_fields (); i += 1)
6954 {
6955 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6956 type. However, we only need the values to be correct when
6957 the caller asks for them. */
6958 int bit_pos = 0, fld_offset = 0;
6959 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6960 {
6961 bit_pos = type->field (i).loc_bitpos ();
6962 fld_offset = offset + bit_pos / 8;
6963 }
6964
6965 const char *t_field_name = type->field (i).name ();
6966
6967 if (t_field_name == NULL)
6968 continue;
6969
6970 else if (ada_is_parent_field (type, i))
6971 {
6972 /* This is a field pointing us to the parent type of a tagged
6973 type. As hinted in this function's documentation, we give
6974 preference to fields in the current record first, so what
6975 we do here is just record the index of this field before
6976 we skip it. If it turns out we couldn't find our field
6977 in the current record, then we'll get back to it and search
6978 inside it whether the field might exist in the parent. */
6979
6980 parent_offset = i;
6981 continue;
6982 }
6983
6984 else if (name != NULL && field_name_match (t_field_name, name))
6985 {
6986 int bit_size = type->field (i).bitsize ();
6987
6988 if (field_type_p != NULL)
6989 *field_type_p = type->field (i).type ();
6990 if (byte_offset_p != NULL)
6991 *byte_offset_p = fld_offset;
6992 if (bit_offset_p != NULL)
6993 *bit_offset_p = bit_pos % 8;
6994 if (bit_size_p != NULL)
6995 *bit_size_p = bit_size;
6996 return 1;
6997 }
6998 else if (ada_is_wrapper_field (type, i))
6999 {
7000 if (find_struct_field (name, type->field (i).type (), fld_offset,
7001 field_type_p, byte_offset_p, bit_offset_p,
7002 bit_size_p, index_p))
7003 return 1;
7004 }
7005 else if (ada_is_variant_part (type, i))
7006 {
7007 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7008 fixed type?? */
7009 int j;
7010 struct type *field_type
7011 = ada_check_typedef (type->field (i).type ());
7012
7013 for (j = 0; j < field_type->num_fields (); j += 1)
7014 {
7015 if (find_struct_field (name, field_type->field (j).type (),
7016 fld_offset
7017 + field_type->field (j).loc_bitpos () / 8,
7018 field_type_p, byte_offset_p,
7019 bit_offset_p, bit_size_p, index_p))
7020 return 1;
7021 }
7022 }
7023 else if (index_p != NULL)
7024 *index_p += 1;
7025 }
7026
7027 /* Field not found so far. If this is a tagged type which
7028 has a parent, try finding that field in the parent now. */
7029
7030 if (parent_offset != -1)
7031 {
7032 /* As above, only compute the offset when truly needed. */
7033 int fld_offset = offset;
7034 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7035 {
7036 int bit_pos = type->field (parent_offset).loc_bitpos ();
7037 fld_offset += bit_pos / 8;
7038 }
7039
7040 if (find_struct_field (name, type->field (parent_offset).type (),
7041 fld_offset, field_type_p, byte_offset_p,
7042 bit_offset_p, bit_size_p, index_p))
7043 return 1;
7044 }
7045
7046 return 0;
7047 }
7048
7049 /* Number of user-visible fields in record type TYPE. */
7050
7051 static int
num_visible_fields(struct type * type)7052 num_visible_fields (struct type *type)
7053 {
7054 int n;
7055
7056 n = 0;
7057 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7058 return n;
7059 }
7060
7061 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7062 and search in it assuming it has (class) type TYPE.
7063 If found, return value, else return NULL.
7064
7065 Searches recursively through wrapper fields (e.g., '_parent').
7066
7067 In the case of homonyms in the tagged types, please refer to the
7068 long explanation in find_struct_field's function documentation. */
7069
7070 static struct value *
ada_search_struct_field(const char * name,struct value * arg,int offset,struct type * type)7071 ada_search_struct_field (const char *name, struct value *arg, int offset,
7072 struct type *type)
7073 {
7074 int i;
7075 int parent_offset = -1;
7076
7077 type = ada_check_typedef (type);
7078 for (i = 0; i < type->num_fields (); i += 1)
7079 {
7080 const char *t_field_name = type->field (i).name ();
7081
7082 if (t_field_name == NULL)
7083 continue;
7084
7085 else if (ada_is_parent_field (type, i))
7086 {
7087 /* This is a field pointing us to the parent type of a tagged
7088 type. As hinted in this function's documentation, we give
7089 preference to fields in the current record first, so what
7090 we do here is just record the index of this field before
7091 we skip it. If it turns out we couldn't find our field
7092 in the current record, then we'll get back to it and search
7093 inside it whether the field might exist in the parent. */
7094
7095 parent_offset = i;
7096 continue;
7097 }
7098
7099 else if (field_name_match (t_field_name, name))
7100 return ada_value_primitive_field (arg, offset, i, type);
7101
7102 else if (ada_is_wrapper_field (type, i))
7103 {
7104 struct value *v = /* Do not let indent join lines here. */
7105 ada_search_struct_field (name, arg,
7106 offset + type->field (i).loc_bitpos () / 8,
7107 type->field (i).type ());
7108
7109 if (v != NULL)
7110 return v;
7111 }
7112
7113 else if (ada_is_variant_part (type, i))
7114 {
7115 /* PNH: Do we ever get here? See find_struct_field. */
7116 int j;
7117 struct type *field_type = ada_check_typedef (type->field (i).type ());
7118 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7119
7120 for (j = 0; j < field_type->num_fields (); j += 1)
7121 {
7122 struct value *v = ada_search_struct_field /* Force line
7123 break. */
7124 (name, arg,
7125 var_offset + field_type->field (j).loc_bitpos () / 8,
7126 field_type->field (j).type ());
7127
7128 if (v != NULL)
7129 return v;
7130 }
7131 }
7132 }
7133
7134 /* Field not found so far. If this is a tagged type which
7135 has a parent, try finding that field in the parent now. */
7136
7137 if (parent_offset != -1)
7138 {
7139 struct value *v = ada_search_struct_field (
7140 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7141 type->field (parent_offset).type ());
7142
7143 if (v != NULL)
7144 return v;
7145 }
7146
7147 return NULL;
7148 }
7149
7150 static struct value *ada_index_struct_field_1 (int *, struct value *,
7151 int, struct type *);
7152
7153
7154 /* Return field #INDEX in ARG, where the index is that returned by
7155 * find_struct_field through its INDEX_P argument. Adjust the address
7156 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7157 * If found, return value, else return NULL. */
7158
7159 static struct value *
ada_index_struct_field(int index,struct value * arg,int offset,struct type * type)7160 ada_index_struct_field (int index, struct value *arg, int offset,
7161 struct type *type)
7162 {
7163 return ada_index_struct_field_1 (&index, arg, offset, type);
7164 }
7165
7166
7167 /* Auxiliary function for ada_index_struct_field. Like
7168 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7169 * *INDEX_P. */
7170
7171 static struct value *
ada_index_struct_field_1(int * index_p,struct value * arg,int offset,struct type * type)7172 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7173 struct type *type)
7174 {
7175 int i;
7176 type = ada_check_typedef (type);
7177
7178 for (i = 0; i < type->num_fields (); i += 1)
7179 {
7180 if (type->field (i).name () == NULL)
7181 continue;
7182 else if (ada_is_wrapper_field (type, i))
7183 {
7184 struct value *v = /* Do not let indent join lines here. */
7185 ada_index_struct_field_1 (index_p, arg,
7186 offset + type->field (i).loc_bitpos () / 8,
7187 type->field (i).type ());
7188
7189 if (v != NULL)
7190 return v;
7191 }
7192
7193 else if (ada_is_variant_part (type, i))
7194 {
7195 /* PNH: Do we ever get here? See ada_search_struct_field,
7196 find_struct_field. */
7197 error (_("Cannot assign this kind of variant record"));
7198 }
7199 else if (*index_p == 0)
7200 return ada_value_primitive_field (arg, offset, i, type);
7201 else
7202 *index_p -= 1;
7203 }
7204 return NULL;
7205 }
7206
7207 /* Return a string representation of type TYPE. */
7208
7209 static std::string
type_as_string(struct type * type)7210 type_as_string (struct type *type)
7211 {
7212 string_file tmp_stream;
7213
7214 type_print (type, "", &tmp_stream, -1);
7215
7216 return tmp_stream.release ();
7217 }
7218
7219 /* Given a type TYPE, look up the type of the component of type named NAME.
7220
7221 Matches any field whose name has NAME as a prefix, possibly
7222 followed by "___".
7223
7224 TYPE can be either a struct or union. If REFOK, TYPE may also
7225 be a (pointer or reference)+ to a struct or union, and the
7226 ultimate target type will be searched.
7227
7228 Looks recursively into variant clauses and parent types.
7229
7230 In the case of homonyms in the tagged types, please refer to the
7231 long explanation in find_struct_field's function documentation.
7232
7233 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7234 TYPE is not a type of the right kind. */
7235
7236 static struct type *
ada_lookup_struct_elt_type(struct type * type,const char * name,int refok,int noerr)7237 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7238 int noerr)
7239 {
7240 if (name == NULL)
7241 goto BadName;
7242
7243 if (refok && type != NULL)
7244 while (1)
7245 {
7246 type = ada_check_typedef (type);
7247 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7248 break;
7249 type = type->target_type ();
7250 }
7251
7252 if (type == NULL
7253 || (type->code () != TYPE_CODE_STRUCT
7254 && type->code () != TYPE_CODE_UNION))
7255 {
7256 if (noerr)
7257 return NULL;
7258
7259 error (_("Type %s is not a structure or union type"),
7260 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7261 }
7262
7263 type = to_static_fixed_type (type);
7264
7265 struct type *result;
7266 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7267 nullptr);
7268 if (result != nullptr)
7269 return result;
7270
7271 BadName:
7272 if (!noerr)
7273 {
7274 const char *name_str = name != NULL ? name : _("<null>");
7275
7276 error (_("Type %s has no component named %s"),
7277 type_as_string (type).c_str (), name_str);
7278 }
7279
7280 return NULL;
7281 }
7282
7283 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7284 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7285 represents an unchecked union (that is, the variant part of a
7286 record that is named in an Unchecked_Union pragma). */
7287
7288 static int
is_unchecked_variant(struct type * var_type,struct type * outer_type)7289 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7290 {
7291 const char *discrim_name = ada_variant_discrim_name (var_type);
7292
7293 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7294 }
7295
7296
7297 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7298 within OUTER, determine which variant clause (field number in VAR_TYPE,
7299 numbering from 0) is applicable. Returns -1 if none are. */
7300
7301 int
ada_which_variant_applies(struct type * var_type,struct value * outer)7302 ada_which_variant_applies (struct type *var_type, struct value *outer)
7303 {
7304 int others_clause;
7305 int i;
7306 const char *discrim_name = ada_variant_discrim_name (var_type);
7307 struct value *discrim;
7308 LONGEST discrim_val;
7309
7310 /* Using plain value_from_contents_and_address here causes problems
7311 because we will end up trying to resolve a type that is currently
7312 being constructed. */
7313 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7314 if (discrim == NULL)
7315 return -1;
7316 discrim_val = value_as_long (discrim);
7317
7318 others_clause = -1;
7319 for (i = 0; i < var_type->num_fields (); i += 1)
7320 {
7321 if (ada_is_others_clause (var_type, i))
7322 others_clause = i;
7323 else if (ada_in_variant (discrim_val, var_type, i))
7324 return i;
7325 }
7326
7327 return others_clause;
7328 }
7329
7330
7331
7332 /* Dynamic-Sized Records */
7333
7334 /* Strategy: The type ostensibly attached to a value with dynamic size
7335 (i.e., a size that is not statically recorded in the debugging
7336 data) does not accurately reflect the size or layout of the value.
7337 Our strategy is to convert these values to values with accurate,
7338 conventional types that are constructed on the fly. */
7339
7340 /* There is a subtle and tricky problem here. In general, we cannot
7341 determine the size of dynamic records without its data. However,
7342 the 'struct value' data structure, which GDB uses to represent
7343 quantities in the inferior process (the target), requires the size
7344 of the type at the time of its allocation in order to reserve space
7345 for GDB's internal copy of the data. That's why the
7346 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7347 rather than struct value*s.
7348
7349 However, GDB's internal history variables ($1, $2, etc.) are
7350 struct value*s containing internal copies of the data that are not, in
7351 general, the same as the data at their corresponding addresses in
7352 the target. Fortunately, the types we give to these values are all
7353 conventional, fixed-size types (as per the strategy described
7354 above), so that we don't usually have to perform the
7355 'to_fixed_xxx_type' conversions to look at their values.
7356 Unfortunately, there is one exception: if one of the internal
7357 history variables is an array whose elements are unconstrained
7358 records, then we will need to create distinct fixed types for each
7359 element selected. */
7360
7361 /* The upshot of all of this is that many routines take a (type, host
7362 address, target address) triple as arguments to represent a value.
7363 The host address, if non-null, is supposed to contain an internal
7364 copy of the relevant data; otherwise, the program is to consult the
7365 target at the target address. */
7366
7367 /* Assuming that VAL0 represents a pointer value, the result of
7368 dereferencing it. Differs from value_ind in its treatment of
7369 dynamic-sized types. */
7370
7371 struct value *
ada_value_ind(struct value * val0)7372 ada_value_ind (struct value *val0)
7373 {
7374 struct value *val = value_ind (val0);
7375
7376 if (ada_is_tagged_type (val->type (), 0))
7377 val = ada_tag_value_at_base_address (val);
7378
7379 return ada_to_fixed_value (val);
7380 }
7381
7382 /* The value resulting from dereferencing any "reference to"
7383 qualifiers on VAL0. */
7384
7385 static struct value *
ada_coerce_ref(struct value * val0)7386 ada_coerce_ref (struct value *val0)
7387 {
7388 if (val0->type ()->code () == TYPE_CODE_REF)
7389 {
7390 struct value *val = val0;
7391
7392 val = coerce_ref (val);
7393
7394 if (ada_is_tagged_type (val->type (), 0))
7395 val = ada_tag_value_at_base_address (val);
7396
7397 return ada_to_fixed_value (val);
7398 }
7399 else
7400 return val0;
7401 }
7402
7403 /* Return the bit alignment required for field #F of template type TYPE. */
7404
7405 static unsigned int
field_alignment(struct type * type,int f)7406 field_alignment (struct type *type, int f)
7407 {
7408 const char *name = type->field (f).name ();
7409 int len;
7410 int align_offset;
7411
7412 /* The field name should never be null, unless the debugging information
7413 is somehow malformed. In this case, we assume the field does not
7414 require any alignment. */
7415 if (name == NULL)
7416 return 1;
7417
7418 len = strlen (name);
7419
7420 if (!isdigit (name[len - 1]))
7421 return 1;
7422
7423 if (isdigit (name[len - 2]))
7424 align_offset = len - 2;
7425 else
7426 align_offset = len - 1;
7427
7428 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7429 return TARGET_CHAR_BIT;
7430
7431 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7432 }
7433
7434 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7435
7436 static struct symbol *
ada_find_any_type_symbol(const char * name)7437 ada_find_any_type_symbol (const char *name)
7438 {
7439 return standard_lookup (name, get_selected_block (nullptr),
7440 SEARCH_TYPE_DOMAIN);
7441 }
7442
7443 /* Find a type named NAME. Ignores ambiguity. This routine will look
7444 solely for types defined by debug info, it will not search the GDB
7445 primitive types. */
7446
7447 static struct type *
ada_find_any_type(const char * name)7448 ada_find_any_type (const char *name)
7449 {
7450 struct symbol *sym = ada_find_any_type_symbol (name);
7451
7452 if (sym != NULL)
7453 return sym->type ();
7454
7455 return NULL;
7456 }
7457
7458 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7459 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7460 symbol, in which case it is returned. Otherwise, this looks for
7461 symbols whose name is that of NAME_SYM suffixed with "___XR".
7462 Return symbol if found, and NULL otherwise. */
7463
7464 static bool
ada_is_renaming_symbol(struct symbol * name_sym)7465 ada_is_renaming_symbol (struct symbol *name_sym)
7466 {
7467 const char *name = name_sym->linkage_name ();
7468 return strstr (name, "___XR") != NULL;
7469 }
7470
7471 /* Because of GNAT encoding conventions, several GDB symbols may match a
7472 given type name. If the type denoted by TYPE0 is to be preferred to
7473 that of TYPE1 for purposes of type printing, return non-zero;
7474 otherwise return 0. */
7475
7476 int
ada_prefer_type(struct type * type0,struct type * type1)7477 ada_prefer_type (struct type *type0, struct type *type1)
7478 {
7479 if (type1 == NULL)
7480 return 1;
7481 else if (type0 == NULL)
7482 return 0;
7483 else if (type1->code () == TYPE_CODE_VOID)
7484 return 1;
7485 else if (type0->code () == TYPE_CODE_VOID)
7486 return 0;
7487 else if (type1->name () == NULL && type0->name () != NULL)
7488 return 1;
7489 else if (ada_is_constrained_packed_array_type (type0))
7490 return 1;
7491 else if (ada_is_array_descriptor_type (type0)
7492 && !ada_is_array_descriptor_type (type1))
7493 return 1;
7494 else
7495 {
7496 const char *type0_name = type0->name ();
7497 const char *type1_name = type1->name ();
7498
7499 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7500 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7501 return 1;
7502 }
7503 return 0;
7504 }
7505
7506 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7507 null. */
7508
7509 const char *
ada_type_name(struct type * type)7510 ada_type_name (struct type *type)
7511 {
7512 if (type == NULL)
7513 return NULL;
7514 return type->name ();
7515 }
7516
7517 /* Search the list of "descriptive" types associated to TYPE for a type
7518 whose name is NAME. */
7519
7520 static struct type *
find_parallel_type_by_descriptive_type(struct type * type,const char * name)7521 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7522 {
7523 struct type *result, *tmp;
7524
7525 if (ada_ignore_descriptive_types_p)
7526 return NULL;
7527
7528 /* If there no descriptive-type info, then there is no parallel type
7529 to be found. */
7530 if (!HAVE_GNAT_AUX_INFO (type))
7531 return NULL;
7532
7533 result = TYPE_DESCRIPTIVE_TYPE (type);
7534 while (result != NULL)
7535 {
7536 const char *result_name = ada_type_name (result);
7537
7538 if (result_name == NULL)
7539 {
7540 warning (_("unexpected null name on descriptive type"));
7541 return NULL;
7542 }
7543
7544 /* If the names match, stop. */
7545 if (strcmp (result_name, name) == 0)
7546 break;
7547
7548 /* Otherwise, look at the next item on the list, if any. */
7549 if (HAVE_GNAT_AUX_INFO (result))
7550 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7551 else
7552 tmp = NULL;
7553
7554 /* If not found either, try after having resolved the typedef. */
7555 if (tmp != NULL)
7556 result = tmp;
7557 else
7558 {
7559 result = check_typedef (result);
7560 if (HAVE_GNAT_AUX_INFO (result))
7561 result = TYPE_DESCRIPTIVE_TYPE (result);
7562 else
7563 result = NULL;
7564 }
7565 }
7566
7567 /* If we didn't find a match, see whether this is a packed array. With
7568 older compilers, the descriptive type information is either absent or
7569 irrelevant when it comes to packed arrays so the above lookup fails.
7570 Fall back to using a parallel lookup by name in this case. */
7571 if (result == NULL && ada_is_constrained_packed_array_type (type))
7572 return ada_find_any_type (name);
7573
7574 return result;
7575 }
7576
7577 /* Find a parallel type to TYPE with the specified NAME, using the
7578 descriptive type taken from the debugging information, if available,
7579 and otherwise using the (slower) name-based method. */
7580
7581 static struct type *
ada_find_parallel_type_with_name(struct type * type,const char * name)7582 ada_find_parallel_type_with_name (struct type *type, const char *name)
7583 {
7584 struct type *result = NULL;
7585
7586 if (HAVE_GNAT_AUX_INFO (type))
7587 result = find_parallel_type_by_descriptive_type (type, name);
7588 else
7589 result = ada_find_any_type (name);
7590
7591 return result;
7592 }
7593
7594 /* Same as above, but specify the name of the parallel type by appending
7595 SUFFIX to the name of TYPE. */
7596
7597 struct type *
ada_find_parallel_type(struct type * type,const char * suffix)7598 ada_find_parallel_type (struct type *type, const char *suffix)
7599 {
7600 char *name;
7601 const char *type_name = ada_type_name (type);
7602 int len;
7603
7604 if (type_name == NULL)
7605 return NULL;
7606
7607 len = strlen (type_name);
7608
7609 name = (char *) alloca (len + strlen (suffix) + 1);
7610
7611 strcpy (name, type_name);
7612 strcpy (name + len, suffix);
7613
7614 return ada_find_parallel_type_with_name (type, name);
7615 }
7616
7617 /* If TYPE is a variable-size record type, return the corresponding template
7618 type describing its fields. Otherwise, return NULL. */
7619
7620 static struct type *
dynamic_template_type(struct type * type)7621 dynamic_template_type (struct type *type)
7622 {
7623 type = ada_check_typedef (type);
7624
7625 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7626 || ada_type_name (type) == NULL)
7627 return NULL;
7628 else
7629 {
7630 int len = strlen (ada_type_name (type));
7631
7632 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7633 return type;
7634 else
7635 return ada_find_parallel_type (type, "___XVE");
7636 }
7637 }
7638
7639 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7640 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7641
7642 static int
is_dynamic_field(struct type * templ_type,int field_num)7643 is_dynamic_field (struct type *templ_type, int field_num)
7644 {
7645 const char *name = templ_type->field (field_num).name ();
7646
7647 return name != NULL
7648 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7649 && strstr (name, "___XVL") != NULL;
7650 }
7651
7652 /* The index of the variant field of TYPE, or -1 if TYPE does not
7653 represent a variant record type. */
7654
7655 static int
variant_field_index(struct type * type)7656 variant_field_index (struct type *type)
7657 {
7658 int f;
7659
7660 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7661 return -1;
7662
7663 for (f = 0; f < type->num_fields (); f += 1)
7664 {
7665 if (ada_is_variant_part (type, f))
7666 return f;
7667 }
7668 return -1;
7669 }
7670
7671 /* A record type with no fields. */
7672
7673 static struct type *
empty_record(struct type * templ)7674 empty_record (struct type *templ)
7675 {
7676 struct type *type = type_allocator (templ).new_type ();
7677
7678 type->set_code (TYPE_CODE_STRUCT);
7679 INIT_NONE_SPECIFIC (type);
7680 type->set_name ("<empty>");
7681 type->set_length (0);
7682 return type;
7683 }
7684
7685 /* An ordinary record type (with fixed-length fields) that describes
7686 the value of type TYPE at VALADDR or ADDRESS (see comments at
7687 the beginning of this section) VAL according to GNAT conventions.
7688 DVAL0 should describe the (portion of a) record that contains any
7689 necessary discriminants. It should be NULL if VAL->type () is
7690 an outer-level type (i.e., as opposed to a branch of a variant.) A
7691 variant field (unless unchecked) is replaced by a particular branch
7692 of the variant.
7693
7694 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7695 length are not statically known are discarded. As a consequence,
7696 VALADDR, ADDRESS and DVAL0 are ignored.
7697
7698 NOTE: Limitations: For now, we assume that dynamic fields and
7699 variants occupy whole numbers of bytes. However, they need not be
7700 byte-aligned. */
7701
7702 struct type *
ada_template_to_fixed_record_type_1(struct type * type,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval0,int keep_dynamic_fields)7703 ada_template_to_fixed_record_type_1 (struct type *type,
7704 const gdb_byte *valaddr,
7705 CORE_ADDR address, struct value *dval0,
7706 int keep_dynamic_fields)
7707 {
7708 struct value *dval;
7709 struct type *rtype;
7710 int nfields, bit_len;
7711 int variant_field;
7712 long off;
7713 int fld_bit_len;
7714 int f;
7715
7716 scoped_value_mark mark;
7717
7718 /* Compute the number of fields in this record type that are going
7719 to be processed: unless keep_dynamic_fields, this includes only
7720 fields whose position and length are static will be processed. */
7721 if (keep_dynamic_fields)
7722 nfields = type->num_fields ();
7723 else
7724 {
7725 nfields = 0;
7726 while (nfields < type->num_fields ()
7727 && !ada_is_variant_part (type, nfields)
7728 && !is_dynamic_field (type, nfields))
7729 nfields++;
7730 }
7731
7732 rtype = type_allocator (type).new_type ();
7733 rtype->set_code (TYPE_CODE_STRUCT);
7734 INIT_NONE_SPECIFIC (rtype);
7735 rtype->alloc_fields (nfields);
7736 rtype->set_name (ada_type_name (type));
7737 rtype->set_is_fixed_instance (true);
7738
7739 off = 0;
7740 bit_len = 0;
7741 variant_field = -1;
7742
7743 for (f = 0; f < nfields; f += 1)
7744 {
7745 off = align_up (off, field_alignment (type, f))
7746 + type->field (f).loc_bitpos ();
7747 rtype->field (f).set_loc_bitpos (off);
7748 rtype->field (f).set_bitsize (0);
7749
7750 if (ada_is_variant_part (type, f))
7751 {
7752 variant_field = f;
7753 fld_bit_len = 0;
7754 }
7755 else if (is_dynamic_field (type, f))
7756 {
7757 const gdb_byte *field_valaddr = valaddr;
7758 CORE_ADDR field_address = address;
7759 struct type *field_type = type->field (f).type ()->target_type ();
7760
7761 if (dval0 == NULL)
7762 {
7763 /* Using plain value_from_contents_and_address here
7764 causes problems because we will end up trying to
7765 resolve a type that is currently being
7766 constructed. */
7767 dval = value_from_contents_and_address_unresolved (rtype,
7768 valaddr,
7769 address);
7770 rtype = dval->type ();
7771 }
7772 else
7773 dval = dval0;
7774
7775 /* If the type referenced by this field is an aligner type, we need
7776 to unwrap that aligner type, because its size might not be set.
7777 Keeping the aligner type would cause us to compute the wrong
7778 size for this field, impacting the offset of the all the fields
7779 that follow this one. */
7780 if (ada_is_aligner_type (field_type))
7781 {
7782 long field_offset = type->field (f).loc_bitpos ();
7783
7784 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7785 field_address = cond_offset_target (field_address, field_offset);
7786 field_type = ada_aligned_type (field_type);
7787 }
7788
7789 field_valaddr = cond_offset_host (field_valaddr,
7790 off / TARGET_CHAR_BIT);
7791 field_address = cond_offset_target (field_address,
7792 off / TARGET_CHAR_BIT);
7793
7794 /* Get the fixed type of the field. Note that, in this case,
7795 we do not want to get the real type out of the tag: if
7796 the current field is the parent part of a tagged record,
7797 we will get the tag of the object. Clearly wrong: the real
7798 type of the parent is not the real type of the child. We
7799 would end up in an infinite loop. */
7800 field_type = ada_get_base_type (field_type);
7801 field_type = ada_to_fixed_type (field_type, field_valaddr,
7802 field_address, dval, 0);
7803
7804 rtype->field (f).set_type (field_type);
7805 rtype->field (f).set_name (type->field (f).name ());
7806 /* The multiplication can potentially overflow. But because
7807 the field length has been size-checked just above, and
7808 assuming that the maximum size is a reasonable value,
7809 an overflow should not happen in practice. So rather than
7810 adding overflow recovery code to this already complex code,
7811 we just assume that it's not going to happen. */
7812 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7813 }
7814 else
7815 {
7816 /* Note: If this field's type is a typedef, it is important
7817 to preserve the typedef layer.
7818
7819 Otherwise, we might be transforming a typedef to a fat
7820 pointer (encoding a pointer to an unconstrained array),
7821 into a basic fat pointer (encoding an unconstrained
7822 array). As both types are implemented using the same
7823 structure, the typedef is the only clue which allows us
7824 to distinguish between the two options. Stripping it
7825 would prevent us from printing this field appropriately. */
7826 rtype->field (f).set_type (type->field (f).type ());
7827 rtype->field (f).set_name (type->field (f).name ());
7828 if (type->field (f).bitsize () > 0)
7829 {
7830 fld_bit_len = type->field (f).bitsize ();
7831 rtype->field (f).set_bitsize (fld_bit_len);
7832 }
7833 else
7834 {
7835 struct type *field_type = type->field (f).type ();
7836
7837 /* We need to be careful of typedefs when computing
7838 the length of our field. If this is a typedef,
7839 get the length of the target type, not the length
7840 of the typedef. */
7841 if (field_type->code () == TYPE_CODE_TYPEDEF)
7842 field_type = ada_typedef_target_type (field_type);
7843
7844 fld_bit_len =
7845 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7846 }
7847 }
7848 if (off + fld_bit_len > bit_len)
7849 bit_len = off + fld_bit_len;
7850 off += fld_bit_len;
7851 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7852 }
7853
7854 /* We handle the variant part, if any, at the end because of certain
7855 odd cases in which it is re-ordered so as NOT to be the last field of
7856 the record. This can happen in the presence of representation
7857 clauses. */
7858 if (variant_field >= 0)
7859 {
7860 struct type *branch_type;
7861
7862 off = rtype->field (variant_field).loc_bitpos ();
7863
7864 if (dval0 == NULL)
7865 {
7866 /* Using plain value_from_contents_and_address here causes
7867 problems because we will end up trying to resolve a type
7868 that is currently being constructed. */
7869 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7870 address);
7871 rtype = dval->type ();
7872 }
7873 else
7874 dval = dval0;
7875
7876 branch_type =
7877 to_fixed_variant_branch_type
7878 (type->field (variant_field).type (),
7879 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7880 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7881 if (branch_type == NULL)
7882 {
7883 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7884 rtype->field (f - 1) = rtype->field (f);
7885 rtype->set_num_fields (rtype->num_fields () - 1);
7886 }
7887 else
7888 {
7889 rtype->field (variant_field).set_type (branch_type);
7890 rtype->field (variant_field).set_name ("S");
7891 fld_bit_len =
7892 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
7893 if (off + fld_bit_len > bit_len)
7894 bit_len = off + fld_bit_len;
7895
7896 rtype->set_length
7897 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7898 }
7899 }
7900
7901 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7902 should contain the alignment of that record, which should be a strictly
7903 positive value. If null or negative, then something is wrong, most
7904 probably in the debug info. In that case, we don't round up the size
7905 of the resulting type. If this record is not part of another structure,
7906 the current RTYPE length might be good enough for our purposes. */
7907 if (type->length () <= 0)
7908 {
7909 if (rtype->name ())
7910 warning (_("Invalid type size for `%s' detected: %s."),
7911 rtype->name (), pulongest (type->length ()));
7912 else
7913 warning (_("Invalid type size for <unnamed> detected: %s."),
7914 pulongest (type->length ()));
7915 }
7916 else
7917 rtype->set_length (align_up (rtype->length (), type->length ()));
7918
7919 return rtype;
7920 }
7921
7922 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7923 of 1. */
7924
7925 static struct type *
template_to_fixed_record_type(struct type * type,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval0)7926 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7927 CORE_ADDR address, struct value *dval0)
7928 {
7929 return ada_template_to_fixed_record_type_1 (type, valaddr,
7930 address, dval0, 1);
7931 }
7932
7933 /* An ordinary record type in which ___XVL-convention fields and
7934 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7935 static approximations, containing all possible fields. Uses
7936 no runtime values. Useless for use in values, but that's OK,
7937 since the results are used only for type determinations. Works on both
7938 structs and unions. Representation note: to save space, we memorize
7939 the result of this function in the type::target_type of the
7940 template type. */
7941
7942 static struct type *
template_to_static_fixed_type(struct type * type0)7943 template_to_static_fixed_type (struct type *type0)
7944 {
7945 struct type *type;
7946 int nfields;
7947 int f;
7948
7949 /* No need no do anything if the input type is already fixed. */
7950 if (type0->is_fixed_instance ())
7951 return type0;
7952
7953 /* Likewise if we already have computed the static approximation. */
7954 if (type0->target_type () != NULL)
7955 return type0->target_type ();
7956
7957 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
7958 type = type0;
7959 nfields = type0->num_fields ();
7960
7961 /* Whether or not we cloned TYPE0, cache the result so that we don't do
7962 recompute all over next time. */
7963 type0->set_target_type (type);
7964
7965 for (f = 0; f < nfields; f += 1)
7966 {
7967 struct type *field_type = type0->field (f).type ();
7968 struct type *new_type;
7969
7970 if (is_dynamic_field (type0, f))
7971 {
7972 field_type = ada_check_typedef (field_type);
7973 new_type = to_static_fixed_type (field_type->target_type ());
7974 }
7975 else
7976 new_type = static_unwrap_type (field_type);
7977
7978 if (new_type != field_type)
7979 {
7980 /* Clone TYPE0 only the first time we get a new field type. */
7981 if (type == type0)
7982 {
7983 type = type_allocator (type0).new_type ();
7984 type0->set_target_type (type);
7985 type->set_code (type0->code ());
7986 INIT_NONE_SPECIFIC (type);
7987
7988 type->copy_fields (type0);
7989
7990 type->set_name (ada_type_name (type0));
7991 type->set_is_fixed_instance (true);
7992 type->set_length (0);
7993 }
7994 type->field (f).set_type (new_type);
7995 type->field (f).set_name (type0->field (f).name ());
7996 }
7997 }
7998
7999 return type;
8000 }
8001
8002 /* Given an object of type TYPE whose contents are at VALADDR and
8003 whose address in memory is ADDRESS, returns a revision of TYPE,
8004 which should be a non-dynamic-sized record, in which the variant
8005 part, if any, is replaced with the appropriate branch. Looks
8006 for discriminant values in DVAL0, which can be NULL if the record
8007 contains the necessary discriminant values. */
8008
8009 static struct type *
to_record_with_fixed_variant_part(struct type * type,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval0)8010 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8011 CORE_ADDR address, struct value *dval0)
8012 {
8013 struct value *dval;
8014 struct type *rtype;
8015 struct type *branch_type;
8016 int nfields = type->num_fields ();
8017 int variant_field = variant_field_index (type);
8018
8019 if (variant_field == -1)
8020 return type;
8021
8022 scoped_value_mark mark;
8023 if (dval0 == NULL)
8024 {
8025 dval = value_from_contents_and_address (type, valaddr, address);
8026 type = dval->type ();
8027 }
8028 else
8029 dval = dval0;
8030
8031 rtype = type_allocator (type).new_type ();
8032 rtype->set_code (TYPE_CODE_STRUCT);
8033 INIT_NONE_SPECIFIC (rtype);
8034 rtype->copy_fields (type);
8035
8036 rtype->set_name (ada_type_name (type));
8037 rtype->set_is_fixed_instance (true);
8038 rtype->set_length (type->length ());
8039
8040 branch_type = to_fixed_variant_branch_type
8041 (type->field (variant_field).type (),
8042 cond_offset_host (valaddr,
8043 type->field (variant_field).loc_bitpos ()
8044 / TARGET_CHAR_BIT),
8045 cond_offset_target (address,
8046 type->field (variant_field).loc_bitpos ()
8047 / TARGET_CHAR_BIT), dval);
8048 if (branch_type == NULL)
8049 {
8050 int f;
8051
8052 for (f = variant_field + 1; f < nfields; f += 1)
8053 rtype->field (f - 1) = rtype->field (f);
8054 rtype->set_num_fields (rtype->num_fields () - 1);
8055 }
8056 else
8057 {
8058 rtype->field (variant_field).set_type (branch_type);
8059 rtype->field (variant_field).set_name ("S");
8060 rtype->field (variant_field).set_bitsize (0);
8061 rtype->set_length (rtype->length () + branch_type->length ());
8062 }
8063
8064 rtype->set_length (rtype->length ()
8065 - type->field (variant_field).type ()->length ());
8066
8067 return rtype;
8068 }
8069
8070 /* An ordinary record type (with fixed-length fields) that describes
8071 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8072 beginning of this section]. Any necessary discriminants' values
8073 should be in DVAL, a record value; it may be NULL if the object
8074 at ADDR itself contains any necessary discriminant values.
8075 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8076 values from the record are needed. Except in the case that DVAL,
8077 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8078 unchecked) is replaced by a particular branch of the variant.
8079
8080 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8081 is questionable and may be removed. It can arise during the
8082 processing of an unconstrained-array-of-record type where all the
8083 variant branches have exactly the same size. This is because in
8084 such cases, the compiler does not bother to use the XVS convention
8085 when encoding the record. I am currently dubious of this
8086 shortcut and suspect the compiler should be altered. FIXME. */
8087
8088 static struct type *
to_fixed_record_type(struct type * type0,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval)8089 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8090 CORE_ADDR address, struct value *dval)
8091 {
8092 struct type *templ_type;
8093
8094 if (type0->is_fixed_instance ())
8095 return type0;
8096
8097 templ_type = dynamic_template_type (type0);
8098
8099 if (templ_type != NULL)
8100 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8101 else if (variant_field_index (type0) >= 0)
8102 {
8103 if (dval == NULL && valaddr == NULL && address == 0)
8104 return type0;
8105 return to_record_with_fixed_variant_part (type0, valaddr, address,
8106 dval);
8107 }
8108 else
8109 {
8110 type0->set_is_fixed_instance (true);
8111 return type0;
8112 }
8113
8114 }
8115
8116 /* An ordinary record type (with fixed-length fields) that describes
8117 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8118 union type. Any necessary discriminants' values should be in DVAL,
8119 a record value. That is, this routine selects the appropriate
8120 branch of the union at ADDR according to the discriminant value
8121 indicated in the union's type name. Returns VAR_TYPE0 itself if
8122 it represents a variant subject to a pragma Unchecked_Union. */
8123
8124 static struct type *
to_fixed_variant_branch_type(struct type * var_type0,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval)8125 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8126 CORE_ADDR address, struct value *dval)
8127 {
8128 int which;
8129 struct type *templ_type;
8130 struct type *var_type;
8131
8132 if (var_type0->code () == TYPE_CODE_PTR)
8133 var_type = var_type0->target_type ();
8134 else
8135 var_type = var_type0;
8136
8137 templ_type = ada_find_parallel_type (var_type, "___XVU");
8138
8139 if (templ_type != NULL)
8140 var_type = templ_type;
8141
8142 if (is_unchecked_variant (var_type, dval->type ()))
8143 return var_type0;
8144 which = ada_which_variant_applies (var_type, dval);
8145
8146 if (which < 0)
8147 return empty_record (var_type);
8148 else if (is_dynamic_field (var_type, which))
8149 return to_fixed_record_type
8150 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8151 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8152 return
8153 to_fixed_record_type
8154 (var_type->field (which).type (), valaddr, address, dval);
8155 else
8156 return var_type->field (which).type ();
8157 }
8158
8159 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8160 ENCODING_TYPE, a type following the GNAT conventions for discrete
8161 type encodings, only carries redundant information. */
8162
8163 static int
ada_is_redundant_range_encoding(struct type * range_type,struct type * encoding_type)8164 ada_is_redundant_range_encoding (struct type *range_type,
8165 struct type *encoding_type)
8166 {
8167 const char *bounds_str;
8168 int n;
8169 LONGEST lo, hi;
8170
8171 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8172
8173 if (get_base_type (range_type)->code ()
8174 != get_base_type (encoding_type)->code ())
8175 {
8176 /* The compiler probably used a simple base type to describe
8177 the range type instead of the range's actual base type,
8178 expecting us to get the real base type from the encoding
8179 anyway. In this situation, the encoding cannot be ignored
8180 as redundant. */
8181 return 0;
8182 }
8183
8184 if (is_dynamic_type (range_type))
8185 return 0;
8186
8187 if (encoding_type->name () == NULL)
8188 return 0;
8189
8190 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8191 if (bounds_str == NULL)
8192 return 0;
8193
8194 n = 8; /* Skip "___XDLU_". */
8195 if (!ada_scan_number (bounds_str, n, &lo, &n))
8196 return 0;
8197 if (range_type->bounds ()->low.const_val () != lo)
8198 return 0;
8199
8200 n += 2; /* Skip the "__" separator between the two bounds. */
8201 if (!ada_scan_number (bounds_str, n, &hi, &n))
8202 return 0;
8203 if (range_type->bounds ()->high.const_val () != hi)
8204 return 0;
8205
8206 return 1;
8207 }
8208
8209 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8210 a type following the GNAT encoding for describing array type
8211 indices, only carries redundant information. */
8212
8213 static int
ada_is_redundant_index_type_desc(struct type * array_type,struct type * desc_type)8214 ada_is_redundant_index_type_desc (struct type *array_type,
8215 struct type *desc_type)
8216 {
8217 struct type *this_layer = check_typedef (array_type);
8218 int i;
8219
8220 for (i = 0; i < desc_type->num_fields (); i++)
8221 {
8222 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8223 desc_type->field (i).type ()))
8224 return 0;
8225 this_layer = check_typedef (this_layer->target_type ());
8226 }
8227
8228 return 1;
8229 }
8230
8231 /* Assuming that TYPE0 is an array type describing the type of a value
8232 at ADDR, and that DVAL describes a record containing any
8233 discriminants used in TYPE0, returns a type for the value that
8234 contains no dynamic components (that is, no components whose sizes
8235 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8236 true, gives an error message if the resulting type's size is over
8237 varsize_limit. */
8238
8239 static struct type *
to_fixed_array_type(struct type * type0,struct value * dval,int ignore_too_big)8240 to_fixed_array_type (struct type *type0, struct value *dval,
8241 int ignore_too_big)
8242 {
8243 struct type *index_type_desc;
8244 struct type *result;
8245 int constrained_packed_array_p;
8246 static const char *xa_suffix = "___XA";
8247
8248 type0 = ada_check_typedef (type0);
8249 if (type0->is_fixed_instance ())
8250 return type0;
8251
8252 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8253 if (constrained_packed_array_p)
8254 {
8255 type0 = decode_constrained_packed_array_type (type0);
8256 if (type0 == nullptr)
8257 error (_("could not decode constrained packed array type"));
8258 }
8259
8260 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8261
8262 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8263 encoding suffixed with 'P' may still be generated. If so,
8264 it should be used to find the XA type. */
8265
8266 if (index_type_desc == NULL)
8267 {
8268 const char *type_name = ada_type_name (type0);
8269
8270 if (type_name != NULL)
8271 {
8272 const int len = strlen (type_name);
8273 char *name = (char *) alloca (len + strlen (xa_suffix));
8274
8275 if (type_name[len - 1] == 'P')
8276 {
8277 strcpy (name, type_name);
8278 strcpy (name + len - 1, xa_suffix);
8279 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8280 }
8281 }
8282 }
8283
8284 ada_fixup_array_indexes_type (index_type_desc);
8285 if (index_type_desc != NULL
8286 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8287 {
8288 /* Ignore this ___XA parallel type, as it does not bring any
8289 useful information. This allows us to avoid creating fixed
8290 versions of the array's index types, which would be identical
8291 to the original ones. This, in turn, can also help avoid
8292 the creation of fixed versions of the array itself. */
8293 index_type_desc = NULL;
8294 }
8295
8296 if (index_type_desc == NULL)
8297 {
8298 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8299
8300 /* NOTE: elt_type---the fixed version of elt_type0---should never
8301 depend on the contents of the array in properly constructed
8302 debugging data. */
8303 /* Create a fixed version of the array element type.
8304 We're not providing the address of an element here,
8305 and thus the actual object value cannot be inspected to do
8306 the conversion. This should not be a problem, since arrays of
8307 unconstrained objects are not allowed. In particular, all
8308 the elements of an array of a tagged type should all be of
8309 the same type specified in the debugging info. No need to
8310 consult the object tag. */
8311 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8312
8313 /* Make sure we always create a new array type when dealing with
8314 packed array types, since we're going to fix-up the array
8315 type length and element bitsize a little further down. */
8316 if (elt_type0 == elt_type && !constrained_packed_array_p)
8317 result = type0;
8318 else
8319 {
8320 type_allocator alloc (type0);
8321 result = create_array_type (alloc, elt_type, type0->index_type ());
8322 }
8323 }
8324 else
8325 {
8326 int i;
8327 struct type *elt_type0;
8328
8329 elt_type0 = type0;
8330 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8331 elt_type0 = elt_type0->target_type ();
8332
8333 /* NOTE: result---the fixed version of elt_type0---should never
8334 depend on the contents of the array in properly constructed
8335 debugging data. */
8336 /* Create a fixed version of the array element type.
8337 We're not providing the address of an element here,
8338 and thus the actual object value cannot be inspected to do
8339 the conversion. This should not be a problem, since arrays of
8340 unconstrained objects are not allowed. In particular, all
8341 the elements of an array of a tagged type should all be of
8342 the same type specified in the debugging info. No need to
8343 consult the object tag. */
8344 result =
8345 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8346
8347 elt_type0 = type0;
8348 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8349 {
8350 struct type *range_type =
8351 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8352
8353 type_allocator alloc (elt_type0);
8354 result = create_array_type (alloc, result, range_type);
8355 elt_type0 = elt_type0->target_type ();
8356 }
8357 }
8358
8359 /* We want to preserve the type name. This can be useful when
8360 trying to get the type name of a value that has already been
8361 printed (for instance, if the user did "print VAR; whatis $". */
8362 result->set_name (type0->name ());
8363
8364 if (constrained_packed_array_p)
8365 {
8366 /* So far, the resulting type has been created as if the original
8367 type was a regular (non-packed) array type. As a result, the
8368 bitsize of the array elements needs to be set again, and the array
8369 length needs to be recomputed based on that bitsize. */
8370 int len = result->length () / result->target_type ()->length ();
8371 int elt_bitsize = type0->field (0).bitsize ();
8372
8373 result->field (0).set_bitsize (elt_bitsize);
8374 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8375 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8376 result->set_length (result->length () + 1);
8377 }
8378
8379 result->set_is_fixed_instance (true);
8380 return result;
8381 }
8382
8383
8384 /* A standard type (containing no dynamically sized components)
8385 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8386 DVAL describes a record containing any discriminants used in TYPE0,
8387 and may be NULL if there are none, or if the object of type TYPE at
8388 ADDRESS or in VALADDR contains these discriminants.
8389
8390 If CHECK_TAG is not null, in the case of tagged types, this function
8391 attempts to locate the object's tag and use it to compute the actual
8392 type. However, when ADDRESS is null, we cannot use it to determine the
8393 location of the tag, and therefore compute the tagged type's actual type.
8394 So we return the tagged type without consulting the tag. */
8395
8396 static struct type *
ada_to_fixed_type_1(struct type * type,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval,int check_tag)8397 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8398 CORE_ADDR address, struct value *dval, int check_tag)
8399 {
8400 type = ada_check_typedef (type);
8401
8402 /* Only un-fixed types need to be handled here. */
8403 if (!HAVE_GNAT_AUX_INFO (type))
8404 return type;
8405
8406 switch (type->code ())
8407 {
8408 default:
8409 return type;
8410 case TYPE_CODE_STRUCT:
8411 {
8412 struct type *static_type = to_static_fixed_type (type);
8413 struct type *fixed_record_type =
8414 to_fixed_record_type (type, valaddr, address, NULL);
8415
8416 /* If STATIC_TYPE is a tagged type and we know the object's address,
8417 then we can determine its tag, and compute the object's actual
8418 type from there. Note that we have to use the fixed record
8419 type (the parent part of the record may have dynamic fields
8420 and the way the location of _tag is expressed may depend on
8421 them). */
8422
8423 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8424 {
8425 struct value *tag =
8426 value_tag_from_contents_and_address
8427 (fixed_record_type,
8428 valaddr,
8429 address);
8430 struct type *real_type = type_from_tag (tag);
8431 struct value *obj =
8432 value_from_contents_and_address (fixed_record_type,
8433 valaddr,
8434 address);
8435 fixed_record_type = obj->type ();
8436 if (real_type != NULL)
8437 return to_fixed_record_type
8438 (real_type, NULL,
8439 ada_tag_value_at_base_address (obj)->address (), NULL);
8440 }
8441
8442 /* Check to see if there is a parallel ___XVZ variable.
8443 If there is, then it provides the actual size of our type. */
8444 else if (ada_type_name (fixed_record_type) != NULL)
8445 {
8446 const char *name = ada_type_name (fixed_record_type);
8447 char *xvz_name
8448 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8449 bool xvz_found = false;
8450 LONGEST size;
8451
8452 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8453 try
8454 {
8455 xvz_found = get_int_var_value (xvz_name, size);
8456 }
8457 catch (const gdb_exception_error &except)
8458 {
8459 /* We found the variable, but somehow failed to read
8460 its value. Rethrow the same error, but with a little
8461 bit more information, to help the user understand
8462 what went wrong (Eg: the variable might have been
8463 optimized out). */
8464 throw_error (except.error,
8465 _("unable to read value of %s (%s)"),
8466 xvz_name, except.what ());
8467 }
8468
8469 if (xvz_found && fixed_record_type->length () != size)
8470 {
8471 fixed_record_type = copy_type (fixed_record_type);
8472 fixed_record_type->set_length (size);
8473
8474 /* The FIXED_RECORD_TYPE may have be a stub. We have
8475 observed this when the debugging info is STABS, and
8476 apparently it is something that is hard to fix.
8477
8478 In practice, we don't need the actual type definition
8479 at all, because the presence of the XVZ variable allows us
8480 to assume that there must be a XVS type as well, which we
8481 should be able to use later, when we need the actual type
8482 definition.
8483
8484 In the meantime, pretend that the "fixed" type we are
8485 returning is NOT a stub, because this can cause trouble
8486 when using this type to create new types targeting it.
8487 Indeed, the associated creation routines often check
8488 whether the target type is a stub and will try to replace
8489 it, thus using a type with the wrong size. This, in turn,
8490 might cause the new type to have the wrong size too.
8491 Consider the case of an array, for instance, where the size
8492 of the array is computed from the number of elements in
8493 our array multiplied by the size of its element. */
8494 fixed_record_type->set_is_stub (false);
8495 }
8496 }
8497 return fixed_record_type;
8498 }
8499 case TYPE_CODE_ARRAY:
8500 return to_fixed_array_type (type, dval, 1);
8501 case TYPE_CODE_UNION:
8502 if (dval == NULL)
8503 return type;
8504 else
8505 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8506 }
8507 }
8508
8509 /* The same as ada_to_fixed_type_1, except that it preserves the type
8510 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8511
8512 The typedef layer needs be preserved in order to differentiate between
8513 arrays and array pointers when both types are implemented using the same
8514 fat pointer. In the array pointer case, the pointer is encoded as
8515 a typedef of the pointer type. For instance, considering:
8516
8517 type String_Access is access String;
8518 S1 : String_Access := null;
8519
8520 To the debugger, S1 is defined as a typedef of type String. But
8521 to the user, it is a pointer. So if the user tries to print S1,
8522 we should not dereference the array, but print the array address
8523 instead.
8524
8525 If we didn't preserve the typedef layer, we would lose the fact that
8526 the type is to be presented as a pointer (needs de-reference before
8527 being printed). And we would also use the source-level type name. */
8528
8529 struct type *
ada_to_fixed_type(struct type * type,const gdb_byte * valaddr,CORE_ADDR address,struct value * dval,int check_tag)8530 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8531 CORE_ADDR address, struct value *dval, int check_tag)
8532
8533 {
8534 struct type *fixed_type =
8535 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8536
8537 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8538 then preserve the typedef layer.
8539
8540 Implementation note: We can only check the main-type portion of
8541 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8542 from TYPE now returns a type that has the same instance flags
8543 as TYPE. For instance, if TYPE is a "typedef const", and its
8544 target type is a "struct", then the typedef elimination will return
8545 a "const" version of the target type. See check_typedef for more
8546 details about how the typedef layer elimination is done.
8547
8548 brobecker/2010-11-19: It seems to me that the only case where it is
8549 useful to preserve the typedef layer is when dealing with fat pointers.
8550 Perhaps, we could add a check for that and preserve the typedef layer
8551 only in that situation. But this seems unnecessary so far, probably
8552 because we call check_typedef/ada_check_typedef pretty much everywhere.
8553 */
8554 if (type->code () == TYPE_CODE_TYPEDEF
8555 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8556 == TYPE_MAIN_TYPE (fixed_type)))
8557 return type;
8558
8559 return fixed_type;
8560 }
8561
8562 /* A standard (static-sized) type corresponding as well as possible to
8563 TYPE0, but based on no runtime data. */
8564
8565 static struct type *
to_static_fixed_type(struct type * type0)8566 to_static_fixed_type (struct type *type0)
8567 {
8568 struct type *type;
8569
8570 if (type0 == NULL)
8571 return NULL;
8572
8573 if (type0->is_fixed_instance ())
8574 return type0;
8575
8576 type0 = ada_check_typedef (type0);
8577
8578 switch (type0->code ())
8579 {
8580 default:
8581 return type0;
8582 case TYPE_CODE_STRUCT:
8583 type = dynamic_template_type (type0);
8584 if (type != NULL)
8585 return template_to_static_fixed_type (type);
8586 else
8587 return template_to_static_fixed_type (type0);
8588 case TYPE_CODE_UNION:
8589 type = ada_find_parallel_type (type0, "___XVU");
8590 if (type != NULL)
8591 return template_to_static_fixed_type (type);
8592 else
8593 return template_to_static_fixed_type (type0);
8594 }
8595 }
8596
8597 /* A static approximation of TYPE with all type wrappers removed. */
8598
8599 static struct type *
static_unwrap_type(struct type * type)8600 static_unwrap_type (struct type *type)
8601 {
8602 if (ada_is_aligner_type (type))
8603 {
8604 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8605 if (ada_type_name (type1) == NULL)
8606 type1->set_name (ada_type_name (type));
8607
8608 return static_unwrap_type (type1);
8609 }
8610 else
8611 {
8612 struct type *raw_real_type = ada_get_base_type (type);
8613
8614 if (raw_real_type == type)
8615 return type;
8616 else
8617 return to_static_fixed_type (raw_real_type);
8618 }
8619 }
8620
8621 /* In some cases, incomplete and private types require
8622 cross-references that are not resolved as records (for example,
8623 type Foo;
8624 type FooP is access Foo;
8625 V: FooP;
8626 type Foo is array ...;
8627 ). In these cases, since there is no mechanism for producing
8628 cross-references to such types, we instead substitute for FooP a
8629 stub enumeration type that is nowhere resolved, and whose tag is
8630 the name of the actual type. Call these types "non-record stubs". */
8631
8632 /* A type equivalent to TYPE that is not a non-record stub, if one
8633 exists, otherwise TYPE. */
8634
8635 struct type *
ada_check_typedef(struct type * type)8636 ada_check_typedef (struct type *type)
8637 {
8638 if (type == NULL)
8639 return NULL;
8640
8641 /* If our type is an access to an unconstrained array, which is encoded
8642 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8643 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8644 what allows us to distinguish between fat pointers that represent
8645 array types, and fat pointers that represent array access types
8646 (in both cases, the compiler implements them as fat pointers). */
8647 if (ada_is_access_to_unconstrained_array (type))
8648 return type;
8649
8650 type = check_typedef (type);
8651 if (type == NULL || type->code () != TYPE_CODE_ENUM
8652 || !type->is_stub ()
8653 || type->name () == NULL)
8654 return type;
8655 else
8656 {
8657 const char *name = type->name ();
8658 struct type *type1 = ada_find_any_type (name);
8659
8660 if (type1 == NULL)
8661 return type;
8662
8663 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8664 stubs pointing to arrays, as we don't create symbols for array
8665 types, only for the typedef-to-array types). If that's the case,
8666 strip the typedef layer. */
8667 if (type1->code () == TYPE_CODE_TYPEDEF)
8668 type1 = ada_check_typedef (type1);
8669
8670 return type1;
8671 }
8672 }
8673
8674 /* A value representing the data at VALADDR/ADDRESS as described by
8675 type TYPE0, but with a standard (static-sized) type that correctly
8676 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8677 type, then return VAL0 [this feature is simply to avoid redundant
8678 creation of struct values]. */
8679
8680 static struct value *
ada_to_fixed_value_create(struct type * type0,CORE_ADDR address,struct value * val0)8681 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8682 struct value *val0)
8683 {
8684 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8685
8686 if (type == type0 && val0 != NULL)
8687 return val0;
8688
8689 if (val0->lval () != lval_memory)
8690 {
8691 /* Our value does not live in memory; it could be a convenience
8692 variable, for instance. Create a not_lval value using val0's
8693 contents. */
8694 return value_from_contents (type, val0->contents ().data ());
8695 }
8696
8697 return value_from_contents_and_address (type, 0, address);
8698 }
8699
8700 /* A value representing VAL, but with a standard (static-sized) type
8701 that correctly describes it. Does not necessarily create a new
8702 value. */
8703
8704 struct value *
ada_to_fixed_value(struct value * val)8705 ada_to_fixed_value (struct value *val)
8706 {
8707 val = unwrap_value (val);
8708 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8709 return val;
8710 }
8711
8712
8713 /* Attributes */
8714
8715 /* Evaluate the 'POS attribute applied to ARG. */
8716
8717 static LONGEST
pos_atr(struct value * arg)8718 pos_atr (struct value *arg)
8719 {
8720 struct value *val = coerce_ref (arg);
8721 struct type *type = val->type ();
8722
8723 if (!discrete_type_p (type))
8724 error (_("'POS only defined on discrete types"));
8725
8726 std::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8727 if (!result.has_value ())
8728 error (_("enumeration value is invalid: can't find 'POS"));
8729
8730 return *result;
8731 }
8732
8733 struct value *
ada_pos_atr(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg)8734 ada_pos_atr (struct type *expect_type,
8735 struct expression *exp,
8736 enum noside noside, enum exp_opcode op,
8737 struct value *arg)
8738 {
8739 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8740 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8741 return value::zero (type, not_lval);
8742 return value_from_longest (type, pos_atr (arg));
8743 }
8744
8745 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8746
8747 static struct value *
val_atr(struct type * type,LONGEST val)8748 val_atr (struct type *type, LONGEST val)
8749 {
8750 gdb_assert (discrete_type_p (type));
8751 if (type->code () == TYPE_CODE_RANGE)
8752 type = type->target_type ();
8753 if (type->code () == TYPE_CODE_ENUM)
8754 {
8755 if (val < 0 || val >= type->num_fields ())
8756 error (_("argument to 'VAL out of range"));
8757 val = type->field (val).loc_enumval ();
8758 }
8759 return value_from_longest (type, val);
8760 }
8761
8762 struct value *
ada_val_atr(struct expression * exp,enum noside noside,struct type * type,struct value * arg)8763 ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8764 struct value *arg)
8765 {
8766 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8767 return value::zero (type, not_lval);
8768
8769 if (!discrete_type_p (type))
8770 error (_("'VAL only defined on discrete types"));
8771 if (!integer_type_p (arg->type ()))
8772 error (_("'VAL requires integral argument"));
8773
8774 return val_atr (type, value_as_long (arg));
8775 }
8776
8777 /* Implementation of the enum_rep attribute. */
8778 struct value *
ada_atr_enum_rep(struct expression * exp,enum noside noside,struct type * type,struct value * arg)8779 ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8780 struct value *arg)
8781 {
8782 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8783 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8784 return value::zero (inttype, not_lval);
8785
8786 if (type->code () == TYPE_CODE_RANGE)
8787 type = type->target_type ();
8788 if (type->code () != TYPE_CODE_ENUM)
8789 error (_("'Enum_Rep only defined on enum types"));
8790 if (!types_equal (type, arg->type ()))
8791 error (_("'Enum_Rep requires argument to have same type as enum"));
8792
8793 return value_cast (inttype, arg);
8794 }
8795
8796 /* Implementation of the enum_val attribute. */
8797 struct value *
ada_atr_enum_val(struct expression * exp,enum noside noside,struct type * type,struct value * arg)8798 ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8799 struct value *arg)
8800 {
8801 struct type *original_type = type;
8802 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8803 return value::zero (original_type, not_lval);
8804
8805 if (type->code () == TYPE_CODE_RANGE)
8806 type = type->target_type ();
8807 if (type->code () != TYPE_CODE_ENUM)
8808 error (_("'Enum_Val only defined on enum types"));
8809 if (!integer_type_p (arg->type ()))
8810 error (_("'Enum_Val requires integral argument"));
8811
8812 LONGEST value = value_as_long (arg);
8813 for (int i = 0; i < type->num_fields (); ++i)
8814 {
8815 if (type->field (i).loc_enumval () == value)
8816 return value_from_longest (original_type, value);
8817 }
8818
8819 error (_("value %s not found in enum"), plongest (value));
8820 }
8821
8822
8823
8824 /* Evaluation */
8825
8826 /* True if TYPE appears to be an Ada character type.
8827 [At the moment, this is true only for Character and Wide_Character;
8828 It is a heuristic test that could stand improvement]. */
8829
8830 bool
ada_is_character_type(struct type * type)8831 ada_is_character_type (struct type *type)
8832 {
8833 const char *name;
8834
8835 /* If the type code says it's a character, then assume it really is,
8836 and don't check any further. */
8837 if (type->code () == TYPE_CODE_CHAR)
8838 return true;
8839
8840 /* Otherwise, assume it's a character type iff it is a discrete type
8841 with a known character type name. */
8842 name = ada_type_name (type);
8843 return (name != NULL
8844 && (type->code () == TYPE_CODE_INT
8845 || type->code () == TYPE_CODE_RANGE)
8846 && (strcmp (name, "character") == 0
8847 || strcmp (name, "wide_character") == 0
8848 || strcmp (name, "wide_wide_character") == 0
8849 || strcmp (name, "unsigned char") == 0));
8850 }
8851
8852 /* True if TYPE appears to be an Ada string type. */
8853
8854 bool
ada_is_string_type(struct type * type)8855 ada_is_string_type (struct type *type)
8856 {
8857 type = ada_check_typedef (type);
8858 if (type != NULL
8859 && type->code () != TYPE_CODE_PTR
8860 && (ada_is_simple_array_type (type)
8861 || ada_is_array_descriptor_type (type))
8862 && ada_array_arity (type) == 1)
8863 {
8864 struct type *elttype = ada_array_element_type (type, 1);
8865
8866 return ada_is_character_type (elttype);
8867 }
8868 else
8869 return false;
8870 }
8871
8872 /* The compiler sometimes provides a parallel XVS type for a given
8873 PAD type. Normally, it is safe to follow the PAD type directly,
8874 but older versions of the compiler have a bug that causes the offset
8875 of its "F" field to be wrong. Following that field in that case
8876 would lead to incorrect results, but this can be worked around
8877 by ignoring the PAD type and using the associated XVS type instead.
8878
8879 Set to True if the debugger should trust the contents of PAD types.
8880 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8881 static bool trust_pad_over_xvs = true;
8882
8883 /* True if TYPE is a struct type introduced by the compiler to force the
8884 alignment of a value. Such types have a single field with a
8885 distinctive name. */
8886
8887 int
ada_is_aligner_type(struct type * type)8888 ada_is_aligner_type (struct type *type)
8889 {
8890 type = ada_check_typedef (type);
8891
8892 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8893 return 0;
8894
8895 return (type->code () == TYPE_CODE_STRUCT
8896 && type->num_fields () == 1
8897 && strcmp (type->field (0).name (), "F") == 0);
8898 }
8899
8900 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8901 the parallel type. */
8902
8903 struct type *
ada_get_base_type(struct type * raw_type)8904 ada_get_base_type (struct type *raw_type)
8905 {
8906 struct type *real_type_namer;
8907 struct type *raw_real_type;
8908
8909 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8910 return raw_type;
8911
8912 if (ada_is_aligner_type (raw_type))
8913 /* The encoding specifies that we should always use the aligner type.
8914 So, even if this aligner type has an associated XVS type, we should
8915 simply ignore it.
8916
8917 According to the compiler gurus, an XVS type parallel to an aligner
8918 type may exist because of a stabs limitation. In stabs, aligner
8919 types are empty because the field has a variable-sized type, and
8920 thus cannot actually be used as an aligner type. As a result,
8921 we need the associated parallel XVS type to decode the type.
8922 Since the policy in the compiler is to not change the internal
8923 representation based on the debugging info format, we sometimes
8924 end up having a redundant XVS type parallel to the aligner type. */
8925 return raw_type;
8926
8927 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8928 if (real_type_namer == NULL
8929 || real_type_namer->code () != TYPE_CODE_STRUCT
8930 || real_type_namer->num_fields () != 1)
8931 return raw_type;
8932
8933 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8934 {
8935 /* This is an older encoding form where the base type needs to be
8936 looked up by name. We prefer the newer encoding because it is
8937 more efficient. */
8938 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
8939 if (raw_real_type == NULL)
8940 return raw_type;
8941 else
8942 return raw_real_type;
8943 }
8944
8945 /* The field in our XVS type is a reference to the base type. */
8946 return real_type_namer->field (0).type ()->target_type ();
8947 }
8948
8949 /* The type of value designated by TYPE, with all aligners removed. */
8950
8951 struct type *
ada_aligned_type(struct type * type)8952 ada_aligned_type (struct type *type)
8953 {
8954 if (ada_is_aligner_type (type))
8955 return ada_aligned_type (type->field (0).type ());
8956 else
8957 return ada_get_base_type (type);
8958 }
8959
8960
8961 /* The address of the aligned value in an object at address VALADDR
8962 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
8963
8964 const gdb_byte *
ada_aligned_value_addr(struct type * type,const gdb_byte * valaddr)8965 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8966 {
8967 if (ada_is_aligner_type (type))
8968 return ada_aligned_value_addr
8969 (type->field (0).type (),
8970 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
8971 else
8972 return valaddr;
8973 }
8974
8975
8976
8977 /* The printed representation of an enumeration literal with encoded
8978 name NAME. The value is good to the next call of ada_enum_name. */
8979 const char *
ada_enum_name(const char * name)8980 ada_enum_name (const char *name)
8981 {
8982 static std::string storage;
8983 const char *tmp;
8984
8985 /* First, unqualify the enumeration name:
8986 1. Search for the last '.' character. If we find one, then skip
8987 all the preceding characters, the unqualified name starts
8988 right after that dot.
8989 2. Otherwise, we may be debugging on a target where the compiler
8990 translates dots into "__". Search forward for double underscores,
8991 but stop searching when we hit an overloading suffix, which is
8992 of the form "__" followed by digits. */
8993
8994 tmp = strrchr (name, '.');
8995 if (tmp != NULL)
8996 name = tmp + 1;
8997 else
8998 {
8999 while ((tmp = strstr (name, "__")) != NULL)
9000 {
9001 if (isdigit (tmp[2]))
9002 break;
9003 else
9004 name = tmp + 2;
9005 }
9006 }
9007
9008 if (name[0] == 'Q')
9009 {
9010 int v;
9011
9012 if (name[1] == 'U' || name[1] == 'W')
9013 {
9014 int offset = 2;
9015 if (name[1] == 'W' && name[2] == 'W')
9016 {
9017 /* Also handle the QWW case. */
9018 ++offset;
9019 }
9020 if (sscanf (name + offset, "%x", &v) != 1)
9021 return name;
9022 }
9023 else if (((name[1] >= '0' && name[1] <= '9')
9024 || (name[1] >= 'a' && name[1] <= 'z'))
9025 && name[2] == '\0')
9026 {
9027 storage = string_printf ("'%c'", name[1]);
9028 return storage.c_str ();
9029 }
9030 else
9031 return name;
9032
9033 if (isascii (v) && isprint (v))
9034 storage = string_printf ("'%c'", v);
9035 else if (name[1] == 'U')
9036 storage = string_printf ("'[\"%02x\"]'", v);
9037 else if (name[2] != 'W')
9038 storage = string_printf ("'[\"%04x\"]'", v);
9039 else
9040 storage = string_printf ("'[\"%06x\"]'", v);
9041
9042 return storage.c_str ();
9043 }
9044 else
9045 {
9046 tmp = strstr (name, "__");
9047 if (tmp == NULL)
9048 tmp = strstr (name, "$");
9049 if (tmp != NULL)
9050 {
9051 storage = std::string (name, tmp - name);
9052 return storage.c_str ();
9053 }
9054
9055 return name;
9056 }
9057 }
9058
9059 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9060 there is no parallel type, return nullptr. */
9061
9062 static struct type *
find_base_type(struct type * type)9063 find_base_type (struct type *type)
9064 {
9065 struct type *raw_real_type
9066 = ada_check_typedef (ada_get_base_type (type));
9067
9068 /* No parallel XVS or XVE type. */
9069 if (type == raw_real_type
9070 && ada_find_parallel_type (type, "___XVE") == nullptr)
9071 return nullptr;
9072
9073 return raw_real_type;
9074 }
9075
9076 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9077 value it wraps. */
9078
9079 static struct value *
unwrap_value(struct value * val)9080 unwrap_value (struct value *val)
9081 {
9082 struct type *type = ada_check_typedef (val->type ());
9083
9084 if (ada_is_aligner_type (type))
9085 {
9086 struct value *v = ada_value_struct_elt (val, "F", 0);
9087 struct type *val_type = ada_check_typedef (v->type ());
9088
9089 if (ada_type_name (val_type) == NULL)
9090 val_type->set_name (ada_type_name (type));
9091
9092 return unwrap_value (v);
9093 }
9094 else
9095 {
9096 struct type *raw_real_type = find_base_type (type);
9097 if (raw_real_type == nullptr)
9098 return val;
9099
9100 return
9101 coerce_unspec_val_to_type
9102 (val, ada_to_fixed_type (raw_real_type, 0,
9103 val->address (),
9104 NULL, 1));
9105 }
9106 }
9107
9108 /* Given two array types T1 and T2, return nonzero iff both arrays
9109 contain the same number of elements. */
9110
9111 static int
ada_same_array_size_p(struct type * t1,struct type * t2)9112 ada_same_array_size_p (struct type *t1, struct type *t2)
9113 {
9114 LONGEST lo1, hi1, lo2, hi2;
9115
9116 /* Get the array bounds in order to verify that the size of
9117 the two arrays match. */
9118 if (!get_array_bounds (t1, &lo1, &hi1)
9119 || !get_array_bounds (t2, &lo2, &hi2))
9120 error (_("unable to determine array bounds"));
9121
9122 /* To make things easier for size comparison, normalize a bit
9123 the case of empty arrays by making sure that the difference
9124 between upper bound and lower bound is always -1. */
9125 if (lo1 > hi1)
9126 hi1 = lo1 - 1;
9127 if (lo2 > hi2)
9128 hi2 = lo2 - 1;
9129
9130 return (hi1 - lo1 == hi2 - lo2);
9131 }
9132
9133 /* Assuming that VAL is an array of integrals, and TYPE represents
9134 an array with the same number of elements, but with wider integral
9135 elements, return an array "casted" to TYPE. In practice, this
9136 means that the returned array is built by casting each element
9137 of the original array into TYPE's (wider) element type. */
9138
9139 static struct value *
ada_promote_array_of_integrals(struct type * type,struct value * val)9140 ada_promote_array_of_integrals (struct type *type, struct value *val)
9141 {
9142 struct type *elt_type = type->target_type ();
9143 LONGEST lo, hi;
9144 LONGEST i;
9145
9146 /* Verify that both val and type are arrays of scalars, and
9147 that the size of val's elements is smaller than the size
9148 of type's element. */
9149 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9150 gdb_assert (is_integral_type (type->target_type ()));
9151 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9152 gdb_assert (is_integral_type (val->type ()->target_type ()));
9153 gdb_assert (type->target_type ()->length ()
9154 > val->type ()->target_type ()->length ());
9155
9156 if (!get_array_bounds (type, &lo, &hi))
9157 error (_("unable to determine array bounds"));
9158
9159 value *res = value::allocate (type);
9160 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9161
9162 /* Promote each array element. */
9163 for (i = 0; i < hi - lo + 1; i++)
9164 {
9165 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9166 int elt_len = elt_type->length ();
9167
9168 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9169 }
9170
9171 return res;
9172 }
9173
9174 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9175 return the converted value. */
9176
9177 static struct value *
coerce_for_assign(struct type * type,struct value * val)9178 coerce_for_assign (struct type *type, struct value *val)
9179 {
9180 struct type *type2 = val->type ();
9181
9182 if (type == type2)
9183 return val;
9184
9185 type2 = ada_check_typedef (type2);
9186 type = ada_check_typedef (type);
9187
9188 if (type2->code () == TYPE_CODE_PTR
9189 && type->code () == TYPE_CODE_ARRAY)
9190 {
9191 val = ada_value_ind (val);
9192 type2 = val->type ();
9193 }
9194
9195 if (type2->code () == TYPE_CODE_ARRAY
9196 && type->code () == TYPE_CODE_ARRAY)
9197 {
9198 if (!ada_same_array_size_p (type, type2))
9199 error (_("cannot assign arrays of different length"));
9200
9201 if (is_integral_type (type->target_type ())
9202 && is_integral_type (type2->target_type ())
9203 && type2->target_type ()->length () < type->target_type ()->length ())
9204 {
9205 /* Allow implicit promotion of the array elements to
9206 a wider type. */
9207 return ada_promote_array_of_integrals (type, val);
9208 }
9209
9210 if (type2->target_type ()->length () != type->target_type ()->length ())
9211 error (_("Incompatible types in assignment"));
9212 val->deprecated_set_type (type);
9213 }
9214 return val;
9215 }
9216
9217 static struct value *
ada_value_binop(struct value * arg1,struct value * arg2,enum exp_opcode op)9218 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9219 {
9220 struct type *type1, *type2;
9221
9222 arg1 = coerce_ref (arg1);
9223 arg2 = coerce_ref (arg2);
9224 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9225 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9226
9227 if (type1->code () != TYPE_CODE_INT
9228 || type2->code () != TYPE_CODE_INT)
9229 return value_binop (arg1, arg2, op);
9230
9231 switch (op)
9232 {
9233 case BINOP_MOD:
9234 case BINOP_DIV:
9235 case BINOP_REM:
9236 break;
9237 default:
9238 return value_binop (arg1, arg2, op);
9239 }
9240
9241 gdb_mpz v2 = value_as_mpz (arg2);
9242 if (v2.sgn () == 0)
9243 {
9244 const char *name;
9245 if (op == BINOP_MOD)
9246 name = "mod";
9247 else if (op == BINOP_DIV)
9248 name = "/";
9249 else
9250 {
9251 gdb_assert (op == BINOP_REM);
9252 name = "rem";
9253 }
9254
9255 error (_("second operand of %s must not be zero."), name);
9256 }
9257
9258 if (type1->is_unsigned () || op == BINOP_MOD)
9259 return value_binop (arg1, arg2, op);
9260
9261 gdb_mpz v1 = value_as_mpz (arg1);
9262 gdb_mpz v;
9263 switch (op)
9264 {
9265 case BINOP_DIV:
9266 v = v1 / v2;
9267 break;
9268 case BINOP_REM:
9269 v = v1 % v2;
9270 if (v * v1 < 0)
9271 v -= v2;
9272 break;
9273 default:
9274 /* Should not reach this point. */
9275 gdb_assert_not_reached ("invalid operator");
9276 }
9277
9278 return value_from_mpz (type1, v);
9279 }
9280
9281 static int
ada_value_equal(struct value * arg1,struct value * arg2)9282 ada_value_equal (struct value *arg1, struct value *arg2)
9283 {
9284 if (ada_is_direct_array_type (arg1->type ())
9285 || ada_is_direct_array_type (arg2->type ()))
9286 {
9287 struct type *arg1_type, *arg2_type;
9288
9289 /* Automatically dereference any array reference before
9290 we attempt to perform the comparison. */
9291 arg1 = ada_coerce_ref (arg1);
9292 arg2 = ada_coerce_ref (arg2);
9293
9294 arg1 = ada_coerce_to_simple_array (arg1);
9295 arg2 = ada_coerce_to_simple_array (arg2);
9296
9297 arg1_type = ada_check_typedef (arg1->type ());
9298 arg2_type = ada_check_typedef (arg2->type ());
9299
9300 if (arg1_type->code () != TYPE_CODE_ARRAY
9301 || arg2_type->code () != TYPE_CODE_ARRAY)
9302 error (_("Attempt to compare array with non-array"));
9303 /* FIXME: The following works only for types whose
9304 representations use all bits (no padding or undefined bits)
9305 and do not have user-defined equality. */
9306 return (arg1_type->length () == arg2_type->length ()
9307 && memcmp (arg1->contents ().data (),
9308 arg2->contents ().data (),
9309 arg1_type->length ()) == 0);
9310 }
9311 return value_equal (arg1, arg2);
9312 }
9313
9314 namespace expr
9315 {
9316
9317 bool
check_objfile(const std::unique_ptr<ada_component> & comp,struct objfile * objfile)9318 check_objfile (const std::unique_ptr<ada_component> &comp,
9319 struct objfile *objfile)
9320 {
9321 return comp->uses_objfile (objfile);
9322 }
9323
9324 /* See ada-exp.h. */
9325
9326 void
assign(LONGEST index,operation_up & arg)9327 aggregate_assigner::assign (LONGEST index, operation_up &arg)
9328 {
9329 scoped_value_mark mark;
9330
9331 struct value *elt;
9332 struct type *lhs_type = check_typedef (lhs->type ());
9333
9334 if (lhs_type->code () == TYPE_CODE_ARRAY)
9335 {
9336 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9337 struct value *index_val = value_from_longest (index_type, index);
9338
9339 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9340 }
9341 else
9342 {
9343 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9344 elt = ada_to_fixed_value (elt);
9345 }
9346
9347 scoped_restore save_index = make_scoped_restore (&m_current_index, index);
9348
9349 ada_aggregate_operation *ag_op
9350 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9351 if (ag_op != nullptr)
9352 ag_op->assign_aggregate (container, elt, exp);
9353 else
9354 value_assign_to_component (container, elt,
9355 arg->evaluate (nullptr, exp,
9356 EVAL_NORMAL));
9357 }
9358
9359 /* See ada-exp.h. */
9360
9361 value *
current_value()9362 aggregate_assigner::current_value () const
9363 {
9364 /* Note that using an integer type here is incorrect -- the type
9365 should be the array's index type. Unfortunately, though, this
9366 isn't currently available during parsing and type resolution. */
9367 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9368 return value_from_longest (index_type, m_current_index);
9369 }
9370
9371 bool
uses_objfile(struct objfile * objfile)9372 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9373 {
9374 if (m_base != nullptr && m_base->uses_objfile (objfile))
9375 return true;
9376 for (const auto &item : m_components)
9377 if (item->uses_objfile (objfile))
9378 return true;
9379 return false;
9380 }
9381
9382 void
dump(ui_file * stream,int depth)9383 ada_aggregate_component::dump (ui_file *stream, int depth)
9384 {
9385 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9386 if (m_base != nullptr)
9387 {
9388 gdb_printf (stream, _("%*swith delta\n"), depth + 1, "");
9389 m_base->dump (stream, depth + 2);
9390 }
9391 for (const auto &item : m_components)
9392 item->dump (stream, depth + 1);
9393 }
9394
9395 void
assign(aggregate_assigner & assigner)9396 ada_aggregate_component::assign (aggregate_assigner &assigner)
9397 {
9398 if (m_base != nullptr)
9399 {
9400 value *base = m_base->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9401 if (ada_is_direct_array_type (base->type ()))
9402 base = ada_coerce_to_simple_array (base);
9403 if (!types_deeply_equal (assigner.container->type (), base->type ()))
9404 error (_("Type mismatch in delta aggregate"));
9405 value_assign_to_component (assigner.container, assigner.container,
9406 base);
9407 }
9408
9409 for (auto &item : m_components)
9410 item->assign (assigner);
9411 }
9412
9413 /* See ada-exp.h. */
9414
ada_aggregate_component(operation_up && base,std::vector<ada_component_up> && components)9415 ada_aggregate_component::ada_aggregate_component
9416 (operation_up &&base, std::vector<ada_component_up> &&components)
9417 : m_base (std::move (base)),
9418 m_components (std::move (components))
9419 {
9420 for (const auto &component : m_components)
9421 if (dynamic_cast<const ada_others_component *> (component.get ())
9422 != nullptr)
9423 {
9424 /* It's invalid and nonsensical to have 'others => ...' with a
9425 delta aggregate. It was simpler to enforce this
9426 restriction here as opposed to in the parser. */
9427 error (_("'others' invalid in delta aggregate"));
9428 }
9429 }
9430
9431 /* See ada-exp.h. */
9432
9433 value *
assign_aggregate(struct value * container,struct value * lhs,struct expression * exp)9434 ada_aggregate_operation::assign_aggregate (struct value *container,
9435 struct value *lhs,
9436 struct expression *exp)
9437 {
9438 struct type *lhs_type;
9439 aggregate_assigner assigner;
9440
9441 container = ada_coerce_ref (container);
9442 if (ada_is_direct_array_type (container->type ()))
9443 container = ada_coerce_to_simple_array (container);
9444 lhs = ada_coerce_ref (lhs);
9445 if (!lhs->deprecated_modifiable ())
9446 error (_("Left operand of assignment is not a modifiable lvalue."));
9447
9448 lhs_type = check_typedef (lhs->type ());
9449 if (ada_is_direct_array_type (lhs_type))
9450 {
9451 lhs = ada_coerce_to_simple_array (lhs);
9452 lhs_type = check_typedef (lhs->type ());
9453 assigner.low = lhs_type->bounds ()->low.const_val ();
9454 assigner.high = lhs_type->bounds ()->high.const_val ();
9455 }
9456 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9457 {
9458 assigner.low = 0;
9459 assigner.high = num_visible_fields (lhs_type) - 1;
9460 }
9461 else
9462 error (_("Left-hand side must be array or record."));
9463
9464 assigner.indices.push_back (assigner.low - 1);
9465 assigner.indices.push_back (assigner.low - 1);
9466 assigner.indices.push_back (assigner.high + 1);
9467 assigner.indices.push_back (assigner.high + 1);
9468
9469 assigner.container = container;
9470 assigner.lhs = lhs;
9471 assigner.exp = exp;
9472
9473 std::get<0> (m_storage)->assign (assigner);
9474
9475 return container;
9476 }
9477
9478 bool
uses_objfile(struct objfile * objfile)9479 ada_positional_component::uses_objfile (struct objfile *objfile)
9480 {
9481 return m_op->uses_objfile (objfile);
9482 }
9483
9484 void
dump(ui_file * stream,int depth)9485 ada_positional_component::dump (ui_file *stream, int depth)
9486 {
9487 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9488 depth, "", m_index);
9489 m_op->dump (stream, depth + 1);
9490 }
9491
9492 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9493 construct, given that the positions are relative to lower bound
9494 LOW, where HIGH is the upper bound. Record the position in
9495 INDICES. CONTAINER is as for assign_aggregate. */
9496 void
assign(aggregate_assigner & assigner)9497 ada_positional_component::assign (aggregate_assigner &assigner)
9498 {
9499 LONGEST ind = m_index + assigner.low;
9500
9501 if (ind - 1 == assigner.high)
9502 warning (_("Extra components in aggregate ignored."));
9503 if (ind <= assigner.high)
9504 {
9505 assigner.add_interval (ind, ind);
9506 assigner.assign (ind, m_op);
9507 }
9508 }
9509
9510 bool
uses_objfile(struct objfile * objfile)9511 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9512 {
9513 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9514 }
9515
9516 void
dump(ui_file * stream,int depth)9517 ada_discrete_range_association::dump (ui_file *stream, int depth)
9518 {
9519 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9520 m_low->dump (stream, depth + 1);
9521 m_high->dump (stream, depth + 1);
9522 }
9523
9524 void
assign(aggregate_assigner & assigner,operation_up & op)9525 ada_discrete_range_association::assign (aggregate_assigner &assigner,
9526 operation_up &op)
9527 {
9528 LONGEST lower = value_as_long (m_low->evaluate (nullptr, assigner.exp,
9529 EVAL_NORMAL));
9530 LONGEST upper = value_as_long (m_high->evaluate (nullptr, assigner.exp,
9531 EVAL_NORMAL));
9532
9533 if (lower <= upper && (lower < assigner.low || upper > assigner.high))
9534 error (_("Index in component association out of bounds."));
9535
9536 assigner.add_interval (lower, upper);
9537 while (lower <= upper)
9538 {
9539 assigner.assign (lower, op);
9540 lower += 1;
9541 }
9542 }
9543
9544 bool
uses_objfile(struct objfile * objfile)9545 ada_name_association::uses_objfile (struct objfile *objfile)
9546 {
9547 return m_val->uses_objfile (objfile);
9548 }
9549
9550 void
dump(ui_file * stream,int depth)9551 ada_name_association::dump (ui_file *stream, int depth)
9552 {
9553 gdb_printf (stream, _("%*sName:\n"), depth, "");
9554 m_val->dump (stream, depth + 1);
9555 }
9556
9557 void
assign(aggregate_assigner & assigner,operation_up & op)9558 ada_name_association::assign (aggregate_assigner &assigner,
9559 operation_up &op)
9560 {
9561 int index;
9562
9563 if (ada_is_direct_array_type (assigner.lhs->type ()))
9564 {
9565 value *tem = m_val->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9566 index = longest_to_int (value_as_long (tem));
9567 }
9568 else
9569 {
9570 ada_string_operation *strop
9571 = dynamic_cast<ada_string_operation *> (m_val.get ());
9572
9573 const char *name;
9574 if (strop != nullptr)
9575 name = strop->get_name ();
9576 else
9577 {
9578 ada_var_value_operation *vvo
9579 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9580 if (vvo == nullptr)
9581 error (_("Invalid record component association."));
9582 name = vvo->get_symbol ()->natural_name ();
9583 /* In this scenario, the user wrote (name => expr), but
9584 write_name_assoc found some fully-qualified name and
9585 substituted it. This happens because, at parse time, the
9586 meaning of the expression isn't known; but here we know
9587 that just the base name was supplied and it refers to the
9588 name of a field. */
9589 name = ada_unqualified_name (name);
9590 }
9591
9592 index = 0;
9593 if (! find_struct_field (name, assigner.lhs->type (), 0,
9594 NULL, NULL, NULL, NULL, &index))
9595 error (_("Unknown component name: %s."), name);
9596 }
9597
9598 assigner.add_interval (index, index);
9599 assigner.assign (index, op);
9600 }
9601
9602 bool
uses_objfile(struct objfile * objfile)9603 ada_choices_component::uses_objfile (struct objfile *objfile)
9604 {
9605 if (m_op->uses_objfile (objfile))
9606 return true;
9607 for (const auto &item : m_assocs)
9608 if (item->uses_objfile (objfile))
9609 return true;
9610 return false;
9611 }
9612
9613 void
dump(ui_file * stream,int depth)9614 ada_choices_component::dump (ui_file *stream, int depth)
9615 {
9616 if (m_name.empty ())
9617 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9618 else
9619 {
9620 gdb_printf (stream, _("%*sIterated choices:\n"), depth, "");
9621 gdb_printf (stream, _("%*sName: %s\n"), depth + 1, "", m_name.c_str ());
9622 }
9623 m_op->dump (stream, depth + 1);
9624
9625 for (const auto &item : m_assocs)
9626 item->dump (stream, depth + 1);
9627 }
9628
9629 /* Assign into the components of LHS indexed by the OP_CHOICES
9630 construct at *POS, updating *POS past the construct, given that
9631 the allowable indices are LOW..HIGH. Record the indices assigned
9632 to in INDICES. CONTAINER is as for assign_aggregate. */
9633 void
assign(aggregate_assigner & assigner)9634 ada_choices_component::assign (aggregate_assigner &assigner)
9635 {
9636 scoped_restore save_index = make_scoped_restore (&m_assigner, &assigner);
9637 for (auto &item : m_assocs)
9638 item->assign (assigner, m_op);
9639 }
9640
9641 void
dump(struct ui_file * stream,int depth)9642 ada_index_var_operation::dump (struct ui_file *stream, int depth) const
9643 {
9644 gdb_printf (stream, _("%*sIndex variable: %s\n"), depth, "",
9645 m_var->name ().c_str ());
9646 }
9647
9648 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)9649 ada_index_var_operation::evaluate (struct type *expect_type,
9650 struct expression *exp,
9651 enum noside noside)
9652 {
9653 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9654 {
9655 /* Note that using an integer type here is incorrect -- the type
9656 should be the array's index type. Unfortunately, though,
9657 this isn't currently available during parsing and type
9658 resolution. */
9659 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9660 return value::zero (index_type, not_lval);
9661 }
9662
9663 return m_var->current_value ();
9664 }
9665
9666 bool
uses_objfile(struct objfile * objfile)9667 ada_others_component::uses_objfile (struct objfile *objfile)
9668 {
9669 return m_op->uses_objfile (objfile);
9670 }
9671
9672 void
dump(ui_file * stream,int depth)9673 ada_others_component::dump (ui_file *stream, int depth)
9674 {
9675 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9676 m_op->dump (stream, depth + 1);
9677 }
9678
9679 /* Assign the value of the expression in the OP_OTHERS construct in
9680 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9681 have not been previously assigned. The index intervals already assigned
9682 are in INDICES. CONTAINER is as for assign_aggregate. */
9683 void
assign(aggregate_assigner & assigner)9684 ada_others_component::assign (aggregate_assigner &assigner)
9685 {
9686 int num_indices = assigner.indices.size ();
9687 for (int i = 0; i < num_indices - 2; i += 2)
9688 {
9689 for (LONGEST ind = assigner.indices[i + 1] + 1;
9690 ind < assigner.indices[i + 2];
9691 ind += 1)
9692 assigner.assign (ind, m_op);
9693 }
9694 }
9695
9696 struct value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)9697 ada_assign_operation::evaluate (struct type *expect_type,
9698 struct expression *exp,
9699 enum noside noside)
9700 {
9701 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9702 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
9703
9704 ada_aggregate_operation *ag_op
9705 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9706 if (ag_op != nullptr)
9707 {
9708 if (noside != EVAL_NORMAL)
9709 return arg1;
9710
9711 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9712 return ada_value_assign (arg1, arg1);
9713 }
9714 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9715 except if the lhs of our assignment is a convenience variable.
9716 In the case of assigning to a convenience variable, the lhs
9717 should be exactly the result of the evaluation of the rhs. */
9718 struct type *type = arg1->type ();
9719 if (arg1->lval () == lval_internalvar)
9720 type = NULL;
9721 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9722 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9723 return arg1;
9724 if (arg1->lval () == lval_internalvar)
9725 {
9726 /* Nothing. */
9727 }
9728 else
9729 arg2 = coerce_for_assign (arg1->type (), arg2);
9730 return ada_value_assign (arg1, arg2);
9731 }
9732
9733 /* See ada-exp.h. */
9734
9735 void
add_interval(LONGEST from,LONGEST to)9736 aggregate_assigner::add_interval (LONGEST from, LONGEST to)
9737 {
9738 int i, j;
9739
9740 int size = indices.size ();
9741 for (i = 0; i < size; i += 2) {
9742 if (to >= indices[i] && from <= indices[i + 1])
9743 {
9744 int kh;
9745
9746 for (kh = i + 2; kh < size; kh += 2)
9747 if (to < indices[kh])
9748 break;
9749 if (from < indices[i])
9750 indices[i] = from;
9751 indices[i + 1] = indices[kh - 1];
9752 if (to > indices[i + 1])
9753 indices[i + 1] = to;
9754 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9755 indices.resize (kh - i - 2);
9756 return;
9757 }
9758 else if (to < indices[i])
9759 break;
9760 }
9761
9762 indices.resize (indices.size () + 2);
9763 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9764 indices[j] = indices[j - 2];
9765 indices[i] = from;
9766 indices[i + 1] = to;
9767 }
9768
9769 } /* namespace expr */
9770
9771 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9772 is different. */
9773
9774 static struct value *
ada_value_cast(struct type * type,struct value * arg2)9775 ada_value_cast (struct type *type, struct value *arg2)
9776 {
9777 if (type == ada_check_typedef (arg2->type ()))
9778 return arg2;
9779
9780 return value_cast (type, arg2);
9781 }
9782
9783 /* Evaluating Ada expressions, and printing their result.
9784 ------------------------------------------------------
9785
9786 1. Introduction:
9787 ----------------
9788
9789 We usually evaluate an Ada expression in order to print its value.
9790 We also evaluate an expression in order to print its type, which
9791 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9792 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9793 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9794 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9795 similar.
9796
9797 Evaluating expressions is a little more complicated for Ada entities
9798 than it is for entities in languages such as C. The main reason for
9799 this is that Ada provides types whose definition might be dynamic.
9800 One example of such types is variant records. Or another example
9801 would be an array whose bounds can only be known at run time.
9802
9803 The following description is a general guide as to what should be
9804 done (and what should NOT be done) in order to evaluate an expression
9805 involving such types, and when. This does not cover how the semantic
9806 information is encoded by GNAT as this is covered separatly. For the
9807 document used as the reference for the GNAT encoding, see exp_dbug.ads
9808 in the GNAT sources.
9809
9810 Ideally, we should embed each part of this description next to its
9811 associated code. Unfortunately, the amount of code is so vast right
9812 now that it's hard to see whether the code handling a particular
9813 situation might be duplicated or not. One day, when the code is
9814 cleaned up, this guide might become redundant with the comments
9815 inserted in the code, and we might want to remove it.
9816
9817 2. ``Fixing'' an Entity, the Simple Case:
9818 -----------------------------------------
9819
9820 When evaluating Ada expressions, the tricky issue is that they may
9821 reference entities whose type contents and size are not statically
9822 known. Consider for instance a variant record:
9823
9824 type Rec (Empty : Boolean := True) is record
9825 case Empty is
9826 when True => null;
9827 when False => Value : Integer;
9828 end case;
9829 end record;
9830 Yes : Rec := (Empty => False, Value => 1);
9831 No : Rec := (empty => True);
9832
9833 The size and contents of that record depends on the value of the
9834 discriminant (Rec.Empty). At this point, neither the debugging
9835 information nor the associated type structure in GDB are able to
9836 express such dynamic types. So what the debugger does is to create
9837 "fixed" versions of the type that applies to the specific object.
9838 We also informally refer to this operation as "fixing" an object,
9839 which means creating its associated fixed type.
9840
9841 Example: when printing the value of variable "Yes" above, its fixed
9842 type would look like this:
9843
9844 type Rec is record
9845 Empty : Boolean;
9846 Value : Integer;
9847 end record;
9848
9849 On the other hand, if we printed the value of "No", its fixed type
9850 would become:
9851
9852 type Rec is record
9853 Empty : Boolean;
9854 end record;
9855
9856 Things become a little more complicated when trying to fix an entity
9857 with a dynamic type that directly contains another dynamic type,
9858 such as an array of variant records, for instance. There are
9859 two possible cases: Arrays, and records.
9860
9861 3. ``Fixing'' Arrays:
9862 ---------------------
9863
9864 The type structure in GDB describes an array in terms of its bounds,
9865 and the type of its elements. By design, all elements in the array
9866 have the same type and we cannot represent an array of variant elements
9867 using the current type structure in GDB. When fixing an array,
9868 we cannot fix the array element, as we would potentially need one
9869 fixed type per element of the array. As a result, the best we can do
9870 when fixing an array is to produce an array whose bounds and size
9871 are correct (allowing us to read it from memory), but without having
9872 touched its element type. Fixing each element will be done later,
9873 when (if) necessary.
9874
9875 Arrays are a little simpler to handle than records, because the same
9876 amount of memory is allocated for each element of the array, even if
9877 the amount of space actually used by each element differs from element
9878 to element. Consider for instance the following array of type Rec:
9879
9880 type Rec_Array is array (1 .. 2) of Rec;
9881
9882 The actual amount of memory occupied by each element might be different
9883 from element to element, depending on the value of their discriminant.
9884 But the amount of space reserved for each element in the array remains
9885 fixed regardless. So we simply need to compute that size using
9886 the debugging information available, from which we can then determine
9887 the array size (we multiply the number of elements of the array by
9888 the size of each element).
9889
9890 The simplest case is when we have an array of a constrained element
9891 type. For instance, consider the following type declarations:
9892
9893 type Bounded_String (Max_Size : Integer) is
9894 Length : Integer;
9895 Buffer : String (1 .. Max_Size);
9896 end record;
9897 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9898
9899 In this case, the compiler describes the array as an array of
9900 variable-size elements (identified by its XVS suffix) for which
9901 the size can be read in the parallel XVZ variable.
9902
9903 In the case of an array of an unconstrained element type, the compiler
9904 wraps the array element inside a private PAD type. This type should not
9905 be shown to the user, and must be "unwrap"'ed before printing. Note
9906 that we also use the adjective "aligner" in our code to designate
9907 these wrapper types.
9908
9909 In some cases, the size allocated for each element is statically
9910 known. In that case, the PAD type already has the correct size,
9911 and the array element should remain unfixed.
9912
9913 But there are cases when this size is not statically known.
9914 For instance, assuming that "Five" is an integer variable:
9915
9916 type Dynamic is array (1 .. Five) of Integer;
9917 type Wrapper (Has_Length : Boolean := False) is record
9918 Data : Dynamic;
9919 case Has_Length is
9920 when True => Length : Integer;
9921 when False => null;
9922 end case;
9923 end record;
9924 type Wrapper_Array is array (1 .. 2) of Wrapper;
9925
9926 Hello : Wrapper_Array := (others => (Has_Length => True,
9927 Data => (others => 17),
9928 Length => 1));
9929
9930
9931 The debugging info would describe variable Hello as being an
9932 array of a PAD type. The size of that PAD type is not statically
9933 known, but can be determined using a parallel XVZ variable.
9934 In that case, a copy of the PAD type with the correct size should
9935 be used for the fixed array.
9936
9937 3. ``Fixing'' record type objects:
9938 ----------------------------------
9939
9940 Things are slightly different from arrays in the case of dynamic
9941 record types. In this case, in order to compute the associated
9942 fixed type, we need to determine the size and offset of each of
9943 its components. This, in turn, requires us to compute the fixed
9944 type of each of these components.
9945
9946 Consider for instance the example:
9947
9948 type Bounded_String (Max_Size : Natural) is record
9949 Str : String (1 .. Max_Size);
9950 Length : Natural;
9951 end record;
9952 My_String : Bounded_String (Max_Size => 10);
9953
9954 In that case, the position of field "Length" depends on the size
9955 of field Str, which itself depends on the value of the Max_Size
9956 discriminant. In order to fix the type of variable My_String,
9957 we need to fix the type of field Str. Therefore, fixing a variant
9958 record requires us to fix each of its components.
9959
9960 However, if a component does not have a dynamic size, the component
9961 should not be fixed. In particular, fields that use a PAD type
9962 should not fixed. Here is an example where this might happen
9963 (assuming type Rec above):
9964
9965 type Container (Big : Boolean) is record
9966 First : Rec;
9967 After : Integer;
9968 case Big is
9969 when True => Another : Integer;
9970 when False => null;
9971 end case;
9972 end record;
9973 My_Container : Container := (Big => False,
9974 First => (Empty => True),
9975 After => 42);
9976
9977 In that example, the compiler creates a PAD type for component First,
9978 whose size is constant, and then positions the component After just
9979 right after it. The offset of component After is therefore constant
9980 in this case.
9981
9982 The debugger computes the position of each field based on an algorithm
9983 that uses, among other things, the actual position and size of the field
9984 preceding it. Let's now imagine that the user is trying to print
9985 the value of My_Container. If the type fixing was recursive, we would
9986 end up computing the offset of field After based on the size of the
9987 fixed version of field First. And since in our example First has
9988 only one actual field, the size of the fixed type is actually smaller
9989 than the amount of space allocated to that field, and thus we would
9990 compute the wrong offset of field After.
9991
9992 To make things more complicated, we need to watch out for dynamic
9993 components of variant records (identified by the ___XVL suffix in
9994 the component name). Even if the target type is a PAD type, the size
9995 of that type might not be statically known. So the PAD type needs
9996 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9997 we might end up with the wrong size for our component. This can be
9998 observed with the following type declarations:
9999
10000 type Octal is new Integer range 0 .. 7;
10001 type Octal_Array is array (Positive range <>) of Octal;
10002 pragma Pack (Octal_Array);
10003
10004 type Octal_Buffer (Size : Positive) is record
10005 Buffer : Octal_Array (1 .. Size);
10006 Length : Integer;
10007 end record;
10008
10009 In that case, Buffer is a PAD type whose size is unset and needs
10010 to be computed by fixing the unwrapped type.
10011
10012 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10013 ----------------------------------------------------------
10014
10015 Lastly, when should the sub-elements of an entity that remained unfixed
10016 thus far, be actually fixed?
10017
10018 The answer is: Only when referencing that element. For instance
10019 when selecting one component of a record, this specific component
10020 should be fixed at that point in time. Or when printing the value
10021 of a record, each component should be fixed before its value gets
10022 printed. Similarly for arrays, the element of the array should be
10023 fixed when printing each element of the array, or when extracting
10024 one element out of that array. On the other hand, fixing should
10025 not be performed on the elements when taking a slice of an array!
10026
10027 Note that one of the side effects of miscomputing the offset and
10028 size of each field is that we end up also miscomputing the size
10029 of the containing type. This can have adverse results when computing
10030 the value of an entity. GDB fetches the value of an entity based
10031 on the size of its type, and thus a wrong size causes GDB to fetch
10032 the wrong amount of memory. In the case where the computed size is
10033 too small, GDB fetches too little data to print the value of our
10034 entity. Results in this case are unpredictable, as we usually read
10035 past the buffer containing the data =:-o. */
10036
10037 /* A helper function for TERNOP_IN_RANGE. */
10038
10039 static value *
eval_ternop_in_range(struct type * expect_type,struct expression * exp,enum noside noside,value * arg1,value * arg2,value * arg3)10040 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10041 enum noside noside,
10042 value *arg1, value *arg2, value *arg3)
10043 {
10044 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10045 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10046 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10047 return
10048 value_from_longest (type,
10049 (value_less (arg1, arg3)
10050 || value_equal (arg1, arg3))
10051 && (value_less (arg2, arg1)
10052 || value_equal (arg2, arg1)));
10053 }
10054
10055 /* A helper function for UNOP_NEG. */
10056
10057 value *
ada_unop_neg(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1)10058 ada_unop_neg (struct type *expect_type,
10059 struct expression *exp,
10060 enum noside noside, enum exp_opcode op,
10061 struct value *arg1)
10062 {
10063 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10064 return value_neg (arg1);
10065 }
10066
10067 /* A helper function for UNOP_IN_RANGE. */
10068
10069 value *
ada_unop_in_range(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1,struct type * type)10070 ada_unop_in_range (struct type *expect_type,
10071 struct expression *exp,
10072 enum noside noside, enum exp_opcode op,
10073 struct value *arg1, struct type *type)
10074 {
10075 struct value *arg2, *arg3;
10076 switch (type->code ())
10077 {
10078 default:
10079 lim_warning (_("Membership test incompletely implemented; "
10080 "always returns true"));
10081 type = language_bool_type (exp->language_defn, exp->gdbarch);
10082 return value_from_longest (type, 1);
10083
10084 case TYPE_CODE_RANGE:
10085 arg2 = value_from_longest (type,
10086 type->bounds ()->low.const_val ());
10087 arg3 = value_from_longest (type,
10088 type->bounds ()->high.const_val ());
10089 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10090 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10091 type = language_bool_type (exp->language_defn, exp->gdbarch);
10092 return
10093 value_from_longest (type,
10094 (value_less (arg1, arg3)
10095 || value_equal (arg1, arg3))
10096 && (value_less (arg2, arg1)
10097 || value_equal (arg2, arg1)));
10098 }
10099 }
10100
10101 /* A helper function for OP_ATR_TAG. */
10102
10103 value *
ada_atr_tag(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1)10104 ada_atr_tag (struct type *expect_type,
10105 struct expression *exp,
10106 enum noside noside, enum exp_opcode op,
10107 struct value *arg1)
10108 {
10109 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10110 return value::zero (ada_tag_type (arg1), not_lval);
10111
10112 return ada_value_tag (arg1);
10113 }
10114
10115 /* A helper function for OP_ATR_SIZE. */
10116
10117 value *
ada_atr_size(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1)10118 ada_atr_size (struct type *expect_type,
10119 struct expression *exp,
10120 enum noside noside, enum exp_opcode op,
10121 struct value *arg1)
10122 {
10123 struct type *type = arg1->type ();
10124
10125 /* If the argument is a reference, then dereference its type, since
10126 the user is really asking for the size of the actual object,
10127 not the size of the pointer. */
10128 if (type->code () == TYPE_CODE_REF)
10129 type = type->target_type ();
10130
10131 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10132 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10133 else
10134 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10135 TARGET_CHAR_BIT * type->length ());
10136 }
10137
10138 /* A helper function for UNOP_ABS. */
10139
10140 value *
ada_abs(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1)10141 ada_abs (struct type *expect_type,
10142 struct expression *exp,
10143 enum noside noside, enum exp_opcode op,
10144 struct value *arg1)
10145 {
10146 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10147 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10148 return value_neg (arg1);
10149 else
10150 return arg1;
10151 }
10152
10153 /* A helper function for BINOP_MUL. */
10154
10155 value *
ada_mult_binop(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1,struct value * arg2)10156 ada_mult_binop (struct type *expect_type,
10157 struct expression *exp,
10158 enum noside noside, enum exp_opcode op,
10159 struct value *arg1, struct value *arg2)
10160 {
10161 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10162 {
10163 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10164 return value::zero (arg1->type (), not_lval);
10165 }
10166 else
10167 {
10168 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10169 return ada_value_binop (arg1, arg2, op);
10170 }
10171 }
10172
10173 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10174
10175 value *
ada_equal_binop(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1,struct value * arg2)10176 ada_equal_binop (struct type *expect_type,
10177 struct expression *exp,
10178 enum noside noside, enum exp_opcode op,
10179 struct value *arg1, struct value *arg2)
10180 {
10181 int tem;
10182 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10183 tem = 0;
10184 else
10185 {
10186 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10187 tem = ada_value_equal (arg1, arg2);
10188 }
10189 if (op == BINOP_NOTEQUAL)
10190 tem = !tem;
10191 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10192 return value_from_longest (type, tem);
10193 }
10194
10195 /* A helper function for TERNOP_SLICE. */
10196
10197 value *
ada_ternop_slice(struct expression * exp,enum noside noside,struct value * array,struct value * low_bound_val,struct value * high_bound_val)10198 ada_ternop_slice (struct expression *exp,
10199 enum noside noside,
10200 struct value *array, struct value *low_bound_val,
10201 struct value *high_bound_val)
10202 {
10203 LONGEST low_bound;
10204 LONGEST high_bound;
10205
10206 low_bound_val = coerce_ref (low_bound_val);
10207 high_bound_val = coerce_ref (high_bound_val);
10208 low_bound = value_as_long (low_bound_val);
10209 high_bound = value_as_long (high_bound_val);
10210
10211 /* If this is a reference to an aligner type, then remove all
10212 the aligners. */
10213 if (array->type ()->code () == TYPE_CODE_REF
10214 && ada_is_aligner_type (array->type ()->target_type ()))
10215 array->type ()->set_target_type
10216 (ada_aligned_type (array->type ()->target_type ()));
10217
10218 if (ada_is_any_packed_array_type (array->type ()))
10219 error (_("cannot slice a packed array"));
10220
10221 /* If this is a reference to an array or an array lvalue,
10222 convert to a pointer. */
10223 if (array->type ()->code () == TYPE_CODE_REF
10224 || (array->type ()->code () == TYPE_CODE_ARRAY
10225 && array->lval () == lval_memory))
10226 array = value_addr (array);
10227
10228 if (noside == EVAL_AVOID_SIDE_EFFECTS
10229 && ada_is_array_descriptor_type (ada_check_typedef
10230 (array->type ())))
10231 return empty_array (ada_type_of_array (array, 0), low_bound,
10232 high_bound);
10233
10234 array = ada_coerce_to_simple_array_ptr (array);
10235
10236 /* If we have more than one level of pointer indirection,
10237 dereference the value until we get only one level. */
10238 while (array->type ()->code () == TYPE_CODE_PTR
10239 && (array->type ()->target_type ()->code ()
10240 == TYPE_CODE_PTR))
10241 array = value_ind (array);
10242
10243 /* Make sure we really do have an array type before going further,
10244 to avoid a SEGV when trying to get the index type or the target
10245 type later down the road if the debug info generated by
10246 the compiler is incorrect or incomplete. */
10247 if (!ada_is_simple_array_type (array->type ()))
10248 error (_("cannot take slice of non-array"));
10249
10250 if (ada_check_typedef (array->type ())->code ()
10251 == TYPE_CODE_PTR)
10252 {
10253 struct type *type0 = ada_check_typedef (array->type ());
10254
10255 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10256 return empty_array (type0->target_type (), low_bound, high_bound);
10257 else
10258 {
10259 struct type *arr_type0 =
10260 to_fixed_array_type (type0->target_type (), NULL, 1);
10261
10262 return ada_value_slice_from_ptr (array, arr_type0,
10263 longest_to_int (low_bound),
10264 longest_to_int (high_bound));
10265 }
10266 }
10267 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10268 return array;
10269 else if (high_bound < low_bound)
10270 return empty_array (array->type (), low_bound, high_bound);
10271 else
10272 return ada_value_slice (array, longest_to_int (low_bound),
10273 longest_to_int (high_bound));
10274 }
10275
10276 /* A helper function for BINOP_IN_BOUNDS. */
10277
10278 value *
ada_binop_in_bounds(struct expression * exp,enum noside noside,struct value * arg1,struct value * arg2,int n)10279 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10280 struct value *arg1, struct value *arg2, int n)
10281 {
10282 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10283 {
10284 struct type *type = language_bool_type (exp->language_defn,
10285 exp->gdbarch);
10286 return value::zero (type, not_lval);
10287 }
10288
10289 struct type *type = ada_index_type (arg2->type (), n, "range");
10290 if (!type)
10291 type = arg1->type ();
10292
10293 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10294 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10295
10296 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10297 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10298 type = language_bool_type (exp->language_defn, exp->gdbarch);
10299 return value_from_longest (type,
10300 (value_less (arg1, arg3)
10301 || value_equal (arg1, arg3))
10302 && (value_less (arg2, arg1)
10303 || value_equal (arg2, arg1)));
10304 }
10305
10306 /* A helper function for some attribute operations. */
10307
10308 static value *
ada_unop_atr(struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1,struct type * type_arg,int tem)10309 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10310 struct value *arg1, struct type *type_arg, int tem)
10311 {
10312 const char *attr_name = nullptr;
10313 if (op == OP_ATR_FIRST)
10314 attr_name = "first";
10315 else if (op == OP_ATR_LAST)
10316 attr_name = "last";
10317
10318 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10319 {
10320 if (type_arg == NULL)
10321 type_arg = arg1->type ();
10322
10323 if (ada_is_constrained_packed_array_type (type_arg))
10324 type_arg = decode_constrained_packed_array_type (type_arg);
10325
10326 if (!discrete_type_p (type_arg))
10327 {
10328 switch (op)
10329 {
10330 default: /* Should never happen. */
10331 error (_("unexpected attribute encountered"));
10332 case OP_ATR_FIRST:
10333 case OP_ATR_LAST:
10334 type_arg = ada_index_type (type_arg, tem,
10335 attr_name);
10336 break;
10337 case OP_ATR_LENGTH:
10338 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10339 break;
10340 }
10341 }
10342
10343 return value::zero (type_arg, not_lval);
10344 }
10345 else if (type_arg == NULL)
10346 {
10347 arg1 = ada_coerce_ref (arg1);
10348
10349 if (ada_is_constrained_packed_array_type (arg1->type ()))
10350 arg1 = ada_coerce_to_simple_array (arg1);
10351
10352 struct type *type;
10353 if (op == OP_ATR_LENGTH)
10354 type = builtin_type (exp->gdbarch)->builtin_int;
10355 else
10356 {
10357 type = ada_index_type (arg1->type (), tem,
10358 attr_name);
10359 if (type == NULL)
10360 type = builtin_type (exp->gdbarch)->builtin_int;
10361 }
10362
10363 switch (op)
10364 {
10365 default: /* Should never happen. */
10366 error (_("unexpected attribute encountered"));
10367 case OP_ATR_FIRST:
10368 return value_from_longest
10369 (type, ada_array_bound (arg1, tem, 0));
10370 case OP_ATR_LAST:
10371 return value_from_longest
10372 (type, ada_array_bound (arg1, tem, 1));
10373 case OP_ATR_LENGTH:
10374 return value_from_longest
10375 (type, ada_array_length (arg1, tem));
10376 }
10377 }
10378 else if (discrete_type_p (type_arg))
10379 {
10380 struct type *range_type;
10381 const char *name = ada_type_name (type_arg);
10382
10383 range_type = NULL;
10384 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10385 range_type = to_fixed_range_type (type_arg, NULL);
10386 if (range_type == NULL)
10387 range_type = type_arg;
10388 switch (op)
10389 {
10390 default:
10391 error (_("unexpected attribute encountered"));
10392 case OP_ATR_FIRST:
10393 return value_from_longest
10394 (range_type, ada_discrete_type_low_bound (range_type));
10395 case OP_ATR_LAST:
10396 return value_from_longest
10397 (range_type, ada_discrete_type_high_bound (range_type));
10398 case OP_ATR_LENGTH:
10399 error (_("the 'length attribute applies only to array types"));
10400 }
10401 }
10402 else if (type_arg->code () == TYPE_CODE_FLT)
10403 error (_("unimplemented type attribute"));
10404 else
10405 {
10406 LONGEST low, high;
10407
10408 if (ada_is_constrained_packed_array_type (type_arg))
10409 type_arg = decode_constrained_packed_array_type (type_arg);
10410
10411 struct type *type;
10412 if (op == OP_ATR_LENGTH)
10413 type = builtin_type (exp->gdbarch)->builtin_int;
10414 else
10415 {
10416 type = ada_index_type (type_arg, tem, attr_name);
10417 if (type == NULL)
10418 type = builtin_type (exp->gdbarch)->builtin_int;
10419 }
10420
10421 switch (op)
10422 {
10423 default:
10424 error (_("unexpected attribute encountered"));
10425 case OP_ATR_FIRST:
10426 low = ada_array_bound_from_type (type_arg, tem, 0);
10427 return value_from_longest (type, low);
10428 case OP_ATR_LAST:
10429 high = ada_array_bound_from_type (type_arg, tem, 1);
10430 return value_from_longest (type, high);
10431 case OP_ATR_LENGTH:
10432 low = ada_array_bound_from_type (type_arg, tem, 0);
10433 high = ada_array_bound_from_type (type_arg, tem, 1);
10434 return value_from_longest (type, high - low + 1);
10435 }
10436 }
10437 }
10438
10439 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10440
10441 struct value *
ada_binop_minmax(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1,struct value * arg2)10442 ada_binop_minmax (struct type *expect_type,
10443 struct expression *exp,
10444 enum noside noside, enum exp_opcode op,
10445 struct value *arg1, struct value *arg2)
10446 {
10447 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10448 return value::zero (arg1->type (), not_lval);
10449 else
10450 {
10451 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10452 return value_binop (arg1, arg2, op);
10453 }
10454 }
10455
10456 /* A helper function for BINOP_EXP. */
10457
10458 struct value *
ada_binop_exp(struct type * expect_type,struct expression * exp,enum noside noside,enum exp_opcode op,struct value * arg1,struct value * arg2)10459 ada_binop_exp (struct type *expect_type,
10460 struct expression *exp,
10461 enum noside noside, enum exp_opcode op,
10462 struct value *arg1, struct value *arg2)
10463 {
10464 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10465 return value::zero (arg1->type (), not_lval);
10466 else
10467 {
10468 /* For integer exponentiation operations,
10469 only promote the first argument. */
10470 if (is_integral_type (arg2->type ()))
10471 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10472 else
10473 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10474
10475 return value_binop (arg1, arg2, op);
10476 }
10477 }
10478
10479 namespace expr
10480 {
10481
10482 /* See ada-exp.h. */
10483
10484 operation_up
replace(operation_up && owner,struct expression * exp,bool deprocedure_p,bool parse_completion,innermost_block_tracker * tracker,struct type * context_type)10485 ada_resolvable::replace (operation_up &&owner,
10486 struct expression *exp,
10487 bool deprocedure_p,
10488 bool parse_completion,
10489 innermost_block_tracker *tracker,
10490 struct type *context_type)
10491 {
10492 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10493 return (make_operation<ada_funcall_operation>
10494 (std::move (owner),
10495 std::vector<operation_up> ()));
10496 return std::move (owner);
10497 }
10498
10499 /* Convert the character literal whose value would be VAL to the
10500 appropriate value of type TYPE, if there is a translation.
10501 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10502 the literal 'A' (VAL == 65), returns 0. */
10503
10504 static LONGEST
convert_char_literal(struct type * type,LONGEST val)10505 convert_char_literal (struct type *type, LONGEST val)
10506 {
10507 char name[12];
10508 int f;
10509
10510 if (type == NULL)
10511 return val;
10512 type = check_typedef (type);
10513 if (type->code () != TYPE_CODE_ENUM)
10514 return val;
10515
10516 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10517 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10518 else if (val >= 0 && val < 256)
10519 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10520 else if (val >= 0 && val < 0x10000)
10521 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10522 else
10523 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10524 size_t len = strlen (name);
10525 for (f = 0; f < type->num_fields (); f += 1)
10526 {
10527 /* Check the suffix because an enum constant in a package will
10528 have a name like "pkg__QUxx". This is safe enough because we
10529 already have the correct type, and because mangling means
10530 there can't be clashes. */
10531 const char *ename = type->field (f).name ();
10532 size_t elen = strlen (ename);
10533
10534 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10535 return type->field (f).loc_enumval ();
10536 }
10537 return val;
10538 }
10539
10540 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10541 ada_char_operation::evaluate (struct type *expect_type,
10542 struct expression *exp,
10543 enum noside noside)
10544 {
10545 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10546 if (expect_type != nullptr)
10547 result = ada_value_cast (expect_type, result);
10548 return result;
10549 }
10550
10551 /* See ada-exp.h. */
10552
10553 operation_up
replace(operation_up && owner,struct expression * exp,bool deprocedure_p,bool parse_completion,innermost_block_tracker * tracker,struct type * context_type)10554 ada_char_operation::replace (operation_up &&owner,
10555 struct expression *exp,
10556 bool deprocedure_p,
10557 bool parse_completion,
10558 innermost_block_tracker *tracker,
10559 struct type *context_type)
10560 {
10561 operation_up result = std::move (owner);
10562
10563 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10564 {
10565 LONGEST val = as_longest ();
10566 gdb_assert (result.get () == this);
10567 std::get<0> (m_storage) = context_type;
10568 std::get<1> (m_storage) = convert_char_literal (context_type, val);
10569 }
10570
10571 return result;
10572 }
10573
10574 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10575 ada_wrapped_operation::evaluate (struct type *expect_type,
10576 struct expression *exp,
10577 enum noside noside)
10578 {
10579 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10580 if (noside == EVAL_NORMAL)
10581 result = unwrap_value (result);
10582
10583 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10584 then we need to perform the conversion manually, because
10585 evaluate_subexp_standard doesn't do it. This conversion is
10586 necessary in Ada because the different kinds of float/fixed
10587 types in Ada have different representations.
10588
10589 Similarly, we need to perform the conversion from OP_LONG
10590 ourselves. */
10591 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10592 result = ada_value_cast (expect_type, result);
10593
10594 return result;
10595 }
10596
10597 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)10598 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10599 struct agent_expr *ax,
10600 struct axs_value *value,
10601 struct type *cast_type)
10602 {
10603 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10604
10605 struct type *type = value->type;
10606 if (ada_is_aligner_type (type))
10607 error (_("Aligner types cannot be handled in agent expressions"));
10608 else if (find_base_type (type) != nullptr)
10609 error (_("Dynamic types cannot be handled in agent expressions"));
10610 }
10611
10612 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10613 ada_string_operation::evaluate (struct type *expect_type,
10614 struct expression *exp,
10615 enum noside noside)
10616 {
10617 struct type *char_type;
10618 if (expect_type != nullptr && ada_is_string_type (expect_type))
10619 char_type = ada_array_element_type (expect_type, 1);
10620 else
10621 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10622
10623 const std::string &str = std::get<0> (m_storage);
10624 const char *encoding;
10625 switch (char_type->length ())
10626 {
10627 case 1:
10628 {
10629 /* Simply copy over the data -- this isn't perhaps strictly
10630 correct according to the encodings, but it is gdb's
10631 historical behavior. */
10632 struct type *stringtype
10633 = lookup_array_range_type (char_type, 1, str.length ());
10634 struct value *val = value::allocate (stringtype);
10635 memcpy (val->contents_raw ().data (), str.c_str (),
10636 str.length ());
10637 return val;
10638 }
10639
10640 case 2:
10641 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10642 encoding = "UTF-16BE";
10643 else
10644 encoding = "UTF-16LE";
10645 break;
10646
10647 case 4:
10648 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10649 encoding = "UTF-32BE";
10650 else
10651 encoding = "UTF-32LE";
10652 break;
10653
10654 default:
10655 error (_("unexpected character type size %s"),
10656 pulongest (char_type->length ()));
10657 }
10658
10659 auto_obstack converted;
10660 convert_between_encodings (host_charset (), encoding,
10661 (const gdb_byte *) str.c_str (),
10662 str.length (), 1,
10663 &converted, translit_none);
10664
10665 struct type *stringtype
10666 = lookup_array_range_type (char_type, 1,
10667 obstack_object_size (&converted)
10668 / char_type->length ());
10669 struct value *val = value::allocate (stringtype);
10670 memcpy (val->contents_raw ().data (),
10671 obstack_base (&converted),
10672 obstack_object_size (&converted));
10673 return val;
10674 }
10675
10676 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10677 ada_concat_operation::evaluate (struct type *expect_type,
10678 struct expression *exp,
10679 enum noside noside)
10680 {
10681 /* If one side is a literal, evaluate the other side first so that
10682 the expected type can be set properly. */
10683 const operation_up &lhs_expr = std::get<0> (m_storage);
10684 const operation_up &rhs_expr = std::get<1> (m_storage);
10685
10686 value *lhs, *rhs;
10687 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10688 {
10689 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10690 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10691 }
10692 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10693 {
10694 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10695 struct type *rhs_type = check_typedef (rhs->type ());
10696 struct type *elt_type = nullptr;
10697 if (rhs_type->code () == TYPE_CODE_ARRAY)
10698 elt_type = rhs_type->target_type ();
10699 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10700 }
10701 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10702 {
10703 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10704 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10705 }
10706 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10707 {
10708 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10709 struct type *lhs_type = check_typedef (lhs->type ());
10710 struct type *elt_type = nullptr;
10711 if (lhs_type->code () == TYPE_CODE_ARRAY)
10712 elt_type = lhs_type->target_type ();
10713 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10714 }
10715 else
10716 return concat_operation::evaluate (expect_type, exp, noside);
10717
10718 return value_concat (lhs, rhs);
10719 }
10720
10721 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10722 ada_qual_operation::evaluate (struct type *expect_type,
10723 struct expression *exp,
10724 enum noside noside)
10725 {
10726 struct type *type = std::get<1> (m_storage);
10727 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10728 }
10729
10730 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10731 ada_ternop_range_operation::evaluate (struct type *expect_type,
10732 struct expression *exp,
10733 enum noside noside)
10734 {
10735 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10736 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10737 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10738 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10739 }
10740
10741 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10742 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10743 struct expression *exp,
10744 enum noside noside)
10745 {
10746 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10747 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10748
10749 auto do_op = [this] (LONGEST x, LONGEST y)
10750 {
10751 if (std::get<0> (m_storage) == BINOP_ADD)
10752 return x + y;
10753 return x - y;
10754 };
10755
10756 if (arg1->type ()->code () == TYPE_CODE_PTR)
10757 return (value_from_longest
10758 (arg1->type (),
10759 do_op (value_as_long (arg1), value_as_long (arg2))));
10760 if (arg2->type ()->code () == TYPE_CODE_PTR)
10761 return (value_from_longest
10762 (arg2->type (),
10763 do_op (value_as_long (arg1), value_as_long (arg2))));
10764 /* Preserve the original type for use by the range case below.
10765 We cannot cast the result to a reference type, so if ARG1 is
10766 a reference type, find its underlying type. */
10767 struct type *type = arg1->type ();
10768 while (type->code () == TYPE_CODE_REF)
10769 type = type->target_type ();
10770 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10771 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10772 /* We need to special-case the result with a range.
10773 This is done for the benefit of "ptype". gdb's Ada support
10774 historically used the LHS to set the result type here, so
10775 preserve this behavior. */
10776 if (type->code () == TYPE_CODE_RANGE)
10777 arg1 = value_cast (type, arg1);
10778 return arg1;
10779 }
10780
10781 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10782 ada_unop_atr_operation::evaluate (struct type *expect_type,
10783 struct expression *exp,
10784 enum noside noside)
10785 {
10786 struct type *type_arg = nullptr;
10787 value *val = nullptr;
10788
10789 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10790 {
10791 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10792 EVAL_AVOID_SIDE_EFFECTS);
10793 type_arg = tem->type ();
10794 }
10795 else
10796 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10797
10798 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10799 val, type_arg, std::get<2> (m_storage));
10800 }
10801
10802 value *
evaluate_for_cast(struct type * expect_type,struct expression * exp,enum noside noside)10803 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10804 struct expression *exp,
10805 enum noside noside)
10806 {
10807 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10808 return value::zero (expect_type, not_lval);
10809
10810 const bound_minimal_symbol &b = std::get<0> (m_storage);
10811 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10812
10813 val = ada_value_cast (expect_type, val);
10814
10815 /* Follow the Ada language semantics that do not allow taking
10816 an address of the result of a cast (view conversion in Ada). */
10817 if (val->lval () == lval_memory)
10818 {
10819 if (val->lazy ())
10820 val->fetch_lazy ();
10821 val->set_lval (not_lval);
10822 }
10823 return val;
10824 }
10825
10826 value *
evaluate_for_cast(struct type * expect_type,struct expression * exp,enum noside noside)10827 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10828 struct expression *exp,
10829 enum noside noside)
10830 {
10831 value *val = evaluate_var_value (noside,
10832 std::get<0> (m_storage).block,
10833 std::get<0> (m_storage).symbol);
10834
10835 val = ada_value_cast (expect_type, val);
10836
10837 /* Follow the Ada language semantics that do not allow taking
10838 an address of the result of a cast (view conversion in Ada). */
10839 if (val->lval () == lval_memory)
10840 {
10841 if (val->lazy ())
10842 val->fetch_lazy ();
10843 val->set_lval (not_lval);
10844 }
10845 return val;
10846 }
10847
10848 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10849 ada_var_value_operation::evaluate (struct type *expect_type,
10850 struct expression *exp,
10851 enum noside noside)
10852 {
10853 symbol *sym = std::get<0> (m_storage).symbol;
10854
10855 if (sym->domain () == UNDEF_DOMAIN)
10856 /* Only encountered when an unresolved symbol occurs in a
10857 context other than a function call, in which case, it is
10858 invalid. */
10859 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10860 sym->print_name ());
10861
10862 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10863 {
10864 struct type *type = static_unwrap_type (sym->type ());
10865 /* Check to see if this is a tagged type. We also need to handle
10866 the case where the type is a reference to a tagged type, but
10867 we have to be careful to exclude pointers to tagged types.
10868 The latter should be shown as usual (as a pointer), whereas
10869 a reference should mostly be transparent to the user. */
10870 if (ada_is_tagged_type (type, 0)
10871 || (type->code () == TYPE_CODE_REF
10872 && ada_is_tagged_type (type->target_type (), 0)))
10873 {
10874 /* Tagged types are a little special in the fact that the real
10875 type is dynamic and can only be determined by inspecting the
10876 object's tag. This means that we need to get the object's
10877 value first (EVAL_NORMAL) and then extract the actual object
10878 type from its tag.
10879
10880 Note that we cannot skip the final step where we extract
10881 the object type from its tag, because the EVAL_NORMAL phase
10882 results in dynamic components being resolved into fixed ones.
10883 This can cause problems when trying to print the type
10884 description of tagged types whose parent has a dynamic size:
10885 We use the type name of the "_parent" component in order
10886 to print the name of the ancestor type in the type description.
10887 If that component had a dynamic size, the resolution into
10888 a fixed type would result in the loss of that type name,
10889 thus preventing us from printing the name of the ancestor
10890 type in the type description. */
10891 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10892
10893 if (type->code () != TYPE_CODE_REF)
10894 {
10895 struct type *actual_type;
10896
10897 actual_type = type_from_tag (ada_value_tag (arg1));
10898 if (actual_type == NULL)
10899 /* If, for some reason, we were unable to determine
10900 the actual type from the tag, then use the static
10901 approximation that we just computed as a fallback.
10902 This can happen if the debugging information is
10903 incomplete, for instance. */
10904 actual_type = type;
10905 return value::zero (actual_type, not_lval);
10906 }
10907 else
10908 {
10909 /* In the case of a ref, ada_coerce_ref takes care
10910 of determining the actual type. But the evaluation
10911 should return a ref as it should be valid to ask
10912 for its address; so rebuild a ref after coerce. */
10913 arg1 = ada_coerce_ref (arg1);
10914 return value_ref (arg1, TYPE_CODE_REF);
10915 }
10916 }
10917
10918 /* Records and unions for which GNAT encodings have been
10919 generated need to be statically fixed as well.
10920 Otherwise, non-static fixing produces a type where
10921 all dynamic properties are removed, which prevents "ptype"
10922 from being able to completely describe the type.
10923 For instance, a case statement in a variant record would be
10924 replaced by the relevant components based on the actual
10925 value of the discriminants. */
10926 if ((type->code () == TYPE_CODE_STRUCT
10927 && dynamic_template_type (type) != NULL)
10928 || (type->code () == TYPE_CODE_UNION
10929 && ada_find_parallel_type (type, "___XVU") != NULL))
10930 return value::zero (to_static_fixed_type (type), not_lval);
10931 }
10932
10933 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10934 return ada_to_fixed_value (arg1);
10935 }
10936
10937 bool
resolve(struct expression * exp,bool deprocedure_p,bool parse_completion,innermost_block_tracker * tracker,struct type * context_type)10938 ada_var_value_operation::resolve (struct expression *exp,
10939 bool deprocedure_p,
10940 bool parse_completion,
10941 innermost_block_tracker *tracker,
10942 struct type *context_type)
10943 {
10944 symbol *sym = std::get<0> (m_storage).symbol;
10945 if (sym->domain () == UNDEF_DOMAIN)
10946 {
10947 block_symbol resolved
10948 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10949 context_type, parse_completion,
10950 deprocedure_p, tracker);
10951 std::get<0> (m_storage) = resolved;
10952 }
10953
10954 if (deprocedure_p
10955 && (std::get<0> (m_storage).symbol->type ()->code ()
10956 == TYPE_CODE_FUNC))
10957 return true;
10958
10959 return false;
10960 }
10961
10962 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)10963 ada_var_value_operation::do_generate_ax (struct expression *exp,
10964 struct agent_expr *ax,
10965 struct axs_value *value,
10966 struct type *cast_type)
10967 {
10968 symbol *sym = std::get<0> (m_storage).symbol;
10969
10970 if (sym->domain () == UNDEF_DOMAIN)
10971 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10972 sym->print_name ());
10973
10974 struct type *type = static_unwrap_type (sym->type ());
10975 if (ada_is_tagged_type (type, 0)
10976 || (type->code () == TYPE_CODE_REF
10977 && ada_is_tagged_type (type->target_type (), 0)))
10978 error (_("Tagged types cannot be handled in agent expressions"));
10979
10980 if ((type->code () == TYPE_CODE_STRUCT
10981 && dynamic_template_type (type) != NULL)
10982 || (type->code () == TYPE_CODE_UNION
10983 && ada_find_parallel_type (type, "___XVU") != NULL))
10984 error (_("Dynamic types cannot be handled in agent expressions"));
10985
10986 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10987 }
10988
10989 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)10990 ada_unop_ind_operation::evaluate (struct type *expect_type,
10991 struct expression *exp,
10992 enum noside noside)
10993 {
10994 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10995
10996 struct type *type = ada_check_typedef (arg1->type ());
10997 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10998 {
10999 if (ada_is_array_descriptor_type (type))
11000 {
11001 /* GDB allows dereferencing GNAT array descriptors.
11002 However, for 'ptype' we don't want to try to
11003 "dereference" a thick pointer here -- that will end up
11004 giving us an array with (1 .. 0) for bounds, which is
11005 less clear than (<>). */
11006 struct type *arrType = ada_type_of_array (arg1, 0);
11007
11008 if (arrType == NULL)
11009 error (_("Attempt to dereference null array pointer."));
11010 if (is_thick_pntr (type))
11011 return arg1;
11012 return value_at_lazy (arrType, 0);
11013 }
11014 else if (type->code () == TYPE_CODE_PTR
11015 || type->code () == TYPE_CODE_REF
11016 /* In C you can dereference an array to get the 1st elt. */
11017 || type->code () == TYPE_CODE_ARRAY)
11018 {
11019 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11020 only be determined by inspecting the object's tag.
11021 This means that we need to evaluate completely the
11022 expression in order to get its type. */
11023
11024 if ((type->code () == TYPE_CODE_REF
11025 || type->code () == TYPE_CODE_PTR)
11026 && ada_is_tagged_type (type->target_type (), 0))
11027 {
11028 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11029 EVAL_NORMAL);
11030 type = ada_value_ind (arg1)->type ();
11031 }
11032 else
11033 {
11034 type = to_static_fixed_type
11035 (ada_aligned_type
11036 (ada_check_typedef (type->target_type ())));
11037 }
11038 return value::zero (type, lval_memory);
11039 }
11040 else if (type->code () == TYPE_CODE_INT)
11041 {
11042 /* GDB allows dereferencing an int. */
11043 if (expect_type == NULL)
11044 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11045 lval_memory);
11046 else
11047 {
11048 expect_type =
11049 to_static_fixed_type (ada_aligned_type (expect_type));
11050 return value::zero (expect_type, lval_memory);
11051 }
11052 }
11053 else
11054 error (_("Attempt to take contents of a non-pointer value."));
11055 }
11056 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11057 type = ada_check_typedef (arg1->type ());
11058
11059 if (type->code () == TYPE_CODE_INT)
11060 /* GDB allows dereferencing an int. If we were given
11061 the expect_type, then use that as the target type.
11062 Otherwise, assume that the target type is an int. */
11063 {
11064 if (expect_type != NULL)
11065 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11066 arg1));
11067 else
11068 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11069 value_as_address (arg1));
11070 }
11071
11072 if (ada_is_array_descriptor_type (type))
11073 /* GDB allows dereferencing GNAT array descriptors. */
11074 return ada_coerce_to_simple_array (arg1);
11075 else
11076 return ada_value_ind (arg1);
11077 }
11078
11079 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)11080 ada_structop_operation::evaluate (struct type *expect_type,
11081 struct expression *exp,
11082 enum noside noside)
11083 {
11084 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11085 const char *str = std::get<1> (m_storage).c_str ();
11086 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11087 {
11088 struct type *type;
11089 struct type *type1 = arg1->type ();
11090
11091 if (ada_is_tagged_type (type1, 1))
11092 {
11093 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11094
11095 /* If the field is not found, check if it exists in the
11096 extension of this object's type. This means that we
11097 need to evaluate completely the expression. */
11098
11099 if (type == NULL)
11100 {
11101 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11102 EVAL_NORMAL);
11103 arg1 = ada_value_struct_elt (arg1, str, 0);
11104 arg1 = unwrap_value (arg1);
11105 type = ada_to_fixed_value (arg1)->type ();
11106 }
11107 }
11108 else
11109 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11110
11111 return value::zero (ada_aligned_type (type), lval_memory);
11112 }
11113 else
11114 {
11115 arg1 = ada_value_struct_elt (arg1, str, 0);
11116 arg1 = unwrap_value (arg1);
11117 return ada_to_fixed_value (arg1);
11118 }
11119 }
11120
11121 value *
evaluate(struct type * expect_type,struct expression * exp,enum noside noside)11122 ada_funcall_operation::evaluate (struct type *expect_type,
11123 struct expression *exp,
11124 enum noside noside)
11125 {
11126 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11127 int nargs = args_up.size ();
11128 std::vector<value *> argvec (nargs);
11129 operation_up &callee_op = std::get<0> (m_storage);
11130
11131 ada_var_value_operation *avv
11132 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11133 if (avv != nullptr
11134 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11135 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11136 avv->get_symbol ()->print_name ());
11137
11138 value *callee = callee_op->evaluate (nullptr, exp, noside);
11139 for (int i = 0; i < args_up.size (); ++i)
11140 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11141
11142 if (ada_is_constrained_packed_array_type
11143 (desc_base_type (callee->type ())))
11144 callee = ada_coerce_to_simple_array (callee);
11145 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11146 && callee->type ()->field (0).bitsize () != 0)
11147 /* This is a packed array that has already been fixed, and
11148 therefore already coerced to a simple array. Nothing further
11149 to do. */
11150 ;
11151 else if (callee->type ()->code () == TYPE_CODE_REF)
11152 {
11153 /* Make sure we dereference references so that all the code below
11154 feels like it's really handling the referenced value. Wrapping
11155 types (for alignment) may be there, so make sure we strip them as
11156 well. */
11157 callee = ada_to_fixed_value (coerce_ref (callee));
11158 }
11159 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11160 && callee->lval () == lval_memory)
11161 callee = value_addr (callee);
11162
11163 struct type *type = ada_check_typedef (callee->type ());
11164
11165 /* Ada allows us to implicitly dereference arrays when subscripting
11166 them. So, if this is an array typedef (encoding use for array
11167 access types encoded as fat pointers), strip it now. */
11168 if (type->code () == TYPE_CODE_TYPEDEF)
11169 type = ada_typedef_target_type (type);
11170
11171 if (type->code () == TYPE_CODE_PTR)
11172 {
11173 switch (ada_check_typedef (type->target_type ())->code ())
11174 {
11175 case TYPE_CODE_FUNC:
11176 type = ada_check_typedef (type->target_type ());
11177 break;
11178 case TYPE_CODE_ARRAY:
11179 break;
11180 case TYPE_CODE_STRUCT:
11181 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11182 callee = ada_value_ind (callee);
11183 type = ada_check_typedef (type->target_type ());
11184 break;
11185 default:
11186 error (_("cannot subscript or call something of type `%s'"),
11187 ada_type_name (callee->type ()));
11188 break;
11189 }
11190 }
11191
11192 switch (type->code ())
11193 {
11194 case TYPE_CODE_FUNC:
11195 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11196 {
11197 if (type->target_type () == NULL)
11198 error_call_unknown_return_type (NULL);
11199 return value::allocate (type->target_type ());
11200 }
11201 return call_function_by_hand (callee, expect_type, argvec);
11202 case TYPE_CODE_INTERNAL_FUNCTION:
11203 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11204 /* We don't know anything about what the internal
11205 function might return, but we have to return
11206 something. */
11207 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11208 not_lval);
11209 else
11210 return call_internal_function (exp->gdbarch, exp->language_defn,
11211 callee, nargs,
11212 argvec.data ());
11213
11214 case TYPE_CODE_STRUCT:
11215 {
11216 int arity;
11217
11218 arity = ada_array_arity (type);
11219 type = ada_array_element_type (type, nargs);
11220 if (type == NULL)
11221 error (_("cannot subscript or call a record"));
11222 if (arity != nargs)
11223 error (_("wrong number of subscripts; expecting %d"), arity);
11224 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11225 return value::zero (ada_aligned_type (type), lval_memory);
11226 return
11227 unwrap_value (ada_value_subscript
11228 (callee, nargs, argvec.data ()));
11229 }
11230 case TYPE_CODE_ARRAY:
11231 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11232 {
11233 type = ada_array_element_type (type, nargs);
11234 if (type == NULL)
11235 error (_("element type of array unknown"));
11236 else
11237 return value::zero (ada_aligned_type (type), lval_memory);
11238 }
11239 return
11240 unwrap_value (ada_value_subscript
11241 (ada_coerce_to_simple_array (callee),
11242 nargs, argvec.data ()));
11243 case TYPE_CODE_PTR: /* Pointer to array */
11244 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11245 {
11246 type = to_fixed_array_type (type->target_type (), NULL, 1);
11247 type = ada_array_element_type (type, nargs);
11248 if (type == NULL)
11249 error (_("element type of array unknown"));
11250 else
11251 return value::zero (ada_aligned_type (type), lval_memory);
11252 }
11253 return
11254 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11255 argvec.data ()));
11256
11257 default:
11258 error (_("Attempt to index or call something other than an "
11259 "array or function"));
11260 }
11261 }
11262
11263 bool
resolve(struct expression * exp,bool deprocedure_p,bool parse_completion,innermost_block_tracker * tracker,struct type * context_type)11264 ada_funcall_operation::resolve (struct expression *exp,
11265 bool deprocedure_p,
11266 bool parse_completion,
11267 innermost_block_tracker *tracker,
11268 struct type *context_type)
11269 {
11270 operation_up &callee_op = std::get<0> (m_storage);
11271
11272 ada_var_value_operation *avv
11273 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11274 if (avv == nullptr)
11275 return false;
11276
11277 symbol *sym = avv->get_symbol ();
11278 if (sym->domain () != UNDEF_DOMAIN)
11279 return false;
11280
11281 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11282 int nargs = args_up.size ();
11283 std::vector<value *> argvec (nargs);
11284
11285 for (int i = 0; i < args_up.size (); ++i)
11286 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11287
11288 const block *block = avv->get_block ();
11289 block_symbol resolved
11290 = ada_resolve_funcall (sym, block,
11291 context_type, parse_completion,
11292 nargs, argvec.data (),
11293 tracker);
11294
11295 std::get<0> (m_storage)
11296 = make_operation<ada_var_value_operation> (resolved);
11297 return false;
11298 }
11299
11300 bool
resolve(struct expression * exp,bool deprocedure_p,bool parse_completion,innermost_block_tracker * tracker,struct type * context_type)11301 ada_ternop_slice_operation::resolve (struct expression *exp,
11302 bool deprocedure_p,
11303 bool parse_completion,
11304 innermost_block_tracker *tracker,
11305 struct type *context_type)
11306 {
11307 /* Historically this check was done during resolution, so we
11308 continue that here. */
11309 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11310 EVAL_AVOID_SIDE_EFFECTS);
11311 if (ada_is_any_packed_array_type (v->type ()))
11312 error (_("cannot slice a packed array"));
11313 return false;
11314 }
11315
11316 }
11317
11318
11319
11320 /* Return non-zero iff TYPE represents a System.Address type. */
11321
11322 int
ada_is_system_address_type(struct type * type)11323 ada_is_system_address_type (struct type *type)
11324 {
11325 return (type->name () && strcmp (type->name (), "system__address") == 0);
11326 }
11327
11328
11329
11330 /* Range types */
11331
11332 /* Scan STR beginning at position K for a discriminant name, and
11333 return the value of that discriminant field of DVAL in *PX. If
11334 PNEW_K is not null, put the position of the character beyond the
11335 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11336 not alter *PX and *PNEW_K if unsuccessful. */
11337
11338 static int
scan_discrim_bound(const char * str,int k,struct value * dval,LONGEST * px,int * pnew_k)11339 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11340 int *pnew_k)
11341 {
11342 static std::string storage;
11343 const char *pstart, *pend, *bound;
11344 struct value *bound_val;
11345
11346 if (dval == NULL || str == NULL || str[k] == '\0')
11347 return 0;
11348
11349 pstart = str + k;
11350 pend = strstr (pstart, "__");
11351 if (pend == NULL)
11352 {
11353 bound = pstart;
11354 k += strlen (bound);
11355 }
11356 else
11357 {
11358 int len = pend - pstart;
11359
11360 /* Strip __ and beyond. */
11361 storage = std::string (pstart, len);
11362 bound = storage.c_str ();
11363 k = pend - str;
11364 }
11365
11366 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11367 if (bound_val == NULL)
11368 return 0;
11369
11370 *px = value_as_long (bound_val);
11371 if (pnew_k != NULL)
11372 *pnew_k = k;
11373 return 1;
11374 }
11375
11376 /* Value of variable named NAME. Only exact matches are considered.
11377 If no such variable found, then if ERR_MSG is null, returns 0, and
11378 otherwise causes an error with message ERR_MSG. */
11379
11380 static struct value *
get_var_value(const char * name,const char * err_msg)11381 get_var_value (const char *name, const char *err_msg)
11382 {
11383 std::string quoted_name = add_angle_brackets (name);
11384
11385 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11386
11387 std::vector<struct block_symbol> syms
11388 = ada_lookup_symbol_list_worker (lookup_name,
11389 get_selected_block (0),
11390 SEARCH_VFT, 1);
11391
11392 if (syms.size () != 1)
11393 {
11394 if (err_msg == NULL)
11395 return 0;
11396 else
11397 error (("%s"), err_msg);
11398 }
11399
11400 return value_of_variable (syms[0].symbol, syms[0].block);
11401 }
11402
11403 /* Value of integer variable named NAME in the current environment.
11404 If no such variable is found, returns false. Otherwise, sets VALUE
11405 to the variable's value and returns true. */
11406
11407 bool
get_int_var_value(const char * name,LONGEST & value)11408 get_int_var_value (const char *name, LONGEST &value)
11409 {
11410 struct value *var_val = get_var_value (name, 0);
11411
11412 if (var_val == 0)
11413 return false;
11414
11415 value = value_as_long (var_val);
11416 return true;
11417 }
11418
11419
11420 /* Return a range type whose base type is that of the range type named
11421 NAME in the current environment, and whose bounds are calculated
11422 from NAME according to the GNAT range encoding conventions.
11423 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11424 corresponding range type from debug information; fall back to using it
11425 if symbol lookup fails. If a new type must be created, allocate it
11426 like ORIG_TYPE was. The bounds information, in general, is encoded
11427 in NAME, the base type given in the named range type. */
11428
11429 static struct type *
to_fixed_range_type(struct type * raw_type,struct value * dval)11430 to_fixed_range_type (struct type *raw_type, struct value *dval)
11431 {
11432 const char *name;
11433 struct type *base_type;
11434 const char *subtype_info;
11435
11436 gdb_assert (raw_type != NULL);
11437 gdb_assert (raw_type->name () != NULL);
11438
11439 if (raw_type->code () == TYPE_CODE_RANGE)
11440 base_type = raw_type->target_type ();
11441 else
11442 base_type = raw_type;
11443
11444 name = raw_type->name ();
11445 subtype_info = strstr (name, "___XD");
11446 if (subtype_info == NULL)
11447 {
11448 LONGEST L = ada_discrete_type_low_bound (raw_type);
11449 LONGEST U = ada_discrete_type_high_bound (raw_type);
11450
11451 if (L < INT_MIN || U > INT_MAX)
11452 return raw_type;
11453 else
11454 {
11455 type_allocator alloc (raw_type);
11456 return create_static_range_type (alloc, raw_type, L, U);
11457 }
11458 }
11459 else
11460 {
11461 int prefix_len = subtype_info - name;
11462 LONGEST L, U;
11463 struct type *type;
11464 const char *bounds_str;
11465 int n;
11466
11467 subtype_info += 5;
11468 bounds_str = strchr (subtype_info, '_');
11469 n = 1;
11470
11471 if (*subtype_info == 'L')
11472 {
11473 if (!ada_scan_number (bounds_str, n, &L, &n)
11474 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11475 return raw_type;
11476 if (bounds_str[n] == '_')
11477 n += 2;
11478 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11479 n += 1;
11480 subtype_info += 1;
11481 }
11482 else
11483 {
11484 std::string name_buf = std::string (name, prefix_len) + "___L";
11485 if (!get_int_var_value (name_buf.c_str (), L))
11486 {
11487 lim_warning (_("Unknown lower bound, using 1."));
11488 L = 1;
11489 }
11490 }
11491
11492 if (*subtype_info == 'U')
11493 {
11494 if (!ada_scan_number (bounds_str, n, &U, &n)
11495 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11496 return raw_type;
11497 }
11498 else
11499 {
11500 std::string name_buf = std::string (name, prefix_len) + "___U";
11501 if (!get_int_var_value (name_buf.c_str (), U))
11502 {
11503 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11504 U = L;
11505 }
11506 }
11507
11508 type_allocator alloc (raw_type);
11509 type = create_static_range_type (alloc, base_type, L, U);
11510 /* create_static_range_type alters the resulting type's length
11511 to match the size of the base_type, which is not what we want.
11512 Set it back to the original range type's length. */
11513 type->set_length (raw_type->length ());
11514 type->set_name (name);
11515 return type;
11516 }
11517 }
11518
11519 /* True iff NAME is the name of a range type. */
11520
11521 int
ada_is_range_type_name(const char * name)11522 ada_is_range_type_name (const char *name)
11523 {
11524 return (name != NULL && strstr (name, "___XD"));
11525 }
11526
11527
11528 /* Modular types */
11529
11530 /* True iff TYPE is an Ada modular type. */
11531
11532 int
ada_is_modular_type(struct type * type)11533 ada_is_modular_type (struct type *type)
11534 {
11535 struct type *subranged_type = get_base_type (type);
11536
11537 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11538 && subranged_type->code () == TYPE_CODE_INT
11539 && subranged_type->is_unsigned ());
11540 }
11541
11542 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11543
11544 ULONGEST
ada_modulus(struct type * type)11545 ada_modulus (struct type *type)
11546 {
11547 const dynamic_prop &high = type->bounds ()->high;
11548
11549 if (high.is_constant ())
11550 return (ULONGEST) high.const_val () + 1;
11551
11552 /* If TYPE is unresolved, the high bound might be a location list. Return
11553 0, for lack of a better value to return. */
11554 return 0;
11555 }
11556
11557
11558 /* Ada exception catchpoint support:
11559 ---------------------------------
11560
11561 We support 3 kinds of exception catchpoints:
11562 . catchpoints on Ada exceptions
11563 . catchpoints on unhandled Ada exceptions
11564 . catchpoints on failed assertions
11565
11566 Exceptions raised during failed assertions, or unhandled exceptions
11567 could perfectly be caught with the general catchpoint on Ada exceptions.
11568 However, we can easily differentiate these two special cases, and having
11569 the option to distinguish these two cases from the rest can be useful
11570 to zero-in on certain situations.
11571
11572 Exception catchpoints are a specialized form of breakpoint,
11573 since they rely on inserting breakpoints inside known routines
11574 of the GNAT runtime. The implementation therefore uses a standard
11575 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11576 of breakpoint_ops.
11577
11578 Support in the runtime for exception catchpoints have been changed
11579 a few times already, and these changes affect the implementation
11580 of these catchpoints. In order to be able to support several
11581 variants of the runtime, we use a sniffer that will determine
11582 the runtime variant used by the program being debugged. */
11583
11584 /* Ada's standard exceptions.
11585
11586 The Ada 83 standard also defined Numeric_Error. But there so many
11587 situations where it was unclear from the Ada 83 Reference Manual
11588 (RM) whether Constraint_Error or Numeric_Error should be raised,
11589 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11590 Interpretation saying that anytime the RM says that Numeric_Error
11591 should be raised, the implementation may raise Constraint_Error.
11592 Ada 95 went one step further and pretty much removed Numeric_Error
11593 from the list of standard exceptions (it made it a renaming of
11594 Constraint_Error, to help preserve compatibility when compiling
11595 an Ada83 compiler). As such, we do not include Numeric_Error from
11596 this list of standard exceptions. */
11597
11598 static const char * const standard_exc[] = {
11599 "constraint_error",
11600 "program_error",
11601 "storage_error",
11602 "tasking_error"
11603 };
11604
11605 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11606
11607 /* A structure that describes how to support exception catchpoints
11608 for a given executable. */
11609
11610 struct exception_support_info
11611 {
11612 /* The name of the symbol to break on in order to insert
11613 a catchpoint on exceptions. */
11614 const char *catch_exception_sym;
11615
11616 /* The name of the symbol to break on in order to insert
11617 a catchpoint on unhandled exceptions. */
11618 const char *catch_exception_unhandled_sym;
11619
11620 /* The name of the symbol to break on in order to insert
11621 a catchpoint on failed assertions. */
11622 const char *catch_assert_sym;
11623
11624 /* The name of the symbol to break on in order to insert
11625 a catchpoint on exception handling. */
11626 const char *catch_handlers_sym;
11627
11628 /* Assuming that the inferior just triggered an unhandled exception
11629 catchpoint, this function is responsible for returning the address
11630 in inferior memory where the name of that exception is stored.
11631 Return zero if the address could not be computed. */
11632 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11633 };
11634
11635 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11636 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11637
11638 /* The following exception support info structure describes how to
11639 implement exception catchpoints with the latest version of the
11640 Ada runtime (as of 2019-08-??). */
11641
11642 static const struct exception_support_info default_exception_support_info =
11643 {
11644 "__gnat_debug_raise_exception", /* catch_exception_sym */
11645 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11646 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11647 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11648 ada_unhandled_exception_name_addr
11649 };
11650
11651 /* The following exception support info structure describes how to
11652 implement exception catchpoints with an earlier version of the
11653 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11654
11655 static const struct exception_support_info exception_support_info_v0 =
11656 {
11657 "__gnat_debug_raise_exception", /* catch_exception_sym */
11658 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11659 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11660 "__gnat_begin_handler", /* catch_handlers_sym */
11661 ada_unhandled_exception_name_addr
11662 };
11663
11664 /* The following exception support info structure describes how to
11665 implement exception catchpoints with a slightly older version
11666 of the Ada runtime. */
11667
11668 static const struct exception_support_info exception_support_info_fallback =
11669 {
11670 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11671 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11672 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11673 "__gnat_begin_handler", /* catch_handlers_sym */
11674 ada_unhandled_exception_name_addr_from_raise
11675 };
11676
11677 /* Return nonzero if we can detect the exception support routines
11678 described in EINFO.
11679
11680 This function errors out if an abnormal situation is detected
11681 (for instance, if we find the exception support routines, but
11682 that support is found to be incomplete). */
11683
11684 static int
ada_has_this_exception_support(const struct exception_support_info * einfo)11685 ada_has_this_exception_support (const struct exception_support_info *einfo)
11686 {
11687 struct symbol *sym;
11688
11689 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11690 that should be compiled with debugging information. As a result, we
11691 expect to find that symbol in the symtabs. */
11692
11693 sym = standard_lookup (einfo->catch_exception_sym, NULL, SEARCH_VFT);
11694 if (sym == NULL)
11695 {
11696 /* Perhaps we did not find our symbol because the Ada runtime was
11697 compiled without debugging info, or simply stripped of it.
11698 It happens on some GNU/Linux distributions for instance, where
11699 users have to install a separate debug package in order to get
11700 the runtime's debugging info. In that situation, let the user
11701 know why we cannot insert an Ada exception catchpoint.
11702
11703 Note: Just for the purpose of inserting our Ada exception
11704 catchpoint, we could rely purely on the associated minimal symbol.
11705 But we would be operating in degraded mode anyway, since we are
11706 still lacking the debugging info needed later on to extract
11707 the name of the exception being raised (this name is printed in
11708 the catchpoint message, and is also used when trying to catch
11709 a specific exception). We do not handle this case for now. */
11710 struct bound_minimal_symbol msym
11711 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11712
11713 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11714 error (_("Your Ada runtime appears to be missing some debugging "
11715 "information.\nCannot insert Ada exception catchpoint "
11716 "in this configuration."));
11717
11718 return 0;
11719 }
11720
11721 /* Make sure that the symbol we found corresponds to a function. */
11722
11723 if (sym->aclass () != LOC_BLOCK)
11724 error (_("Symbol \"%s\" is not a function (class = %d)"),
11725 sym->linkage_name (), sym->aclass ());
11726
11727 sym = standard_lookup (einfo->catch_handlers_sym, NULL, SEARCH_VFT);
11728 if (sym == NULL)
11729 {
11730 struct bound_minimal_symbol msym
11731 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11732
11733 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11734 error (_("Your Ada runtime appears to be missing some debugging "
11735 "information.\nCannot insert Ada exception catchpoint "
11736 "in this configuration."));
11737
11738 return 0;
11739 }
11740
11741 /* Make sure that the symbol we found corresponds to a function. */
11742
11743 if (sym->aclass () != LOC_BLOCK)
11744 error (_("Symbol \"%s\" is not a function (class = %d)"),
11745 sym->linkage_name (), sym->aclass ());
11746
11747 return 1;
11748 }
11749
11750 /* Inspect the Ada runtime and determine which exception info structure
11751 should be used to provide support for exception catchpoints.
11752
11753 This function will always set the per-inferior exception_info,
11754 or raise an error. */
11755
11756 static void
ada_exception_support_info_sniffer(void)11757 ada_exception_support_info_sniffer (void)
11758 {
11759 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11760
11761 /* If the exception info is already known, then no need to recompute it. */
11762 if (data->exception_info != NULL)
11763 return;
11764
11765 /* Check the latest (default) exception support info. */
11766 if (ada_has_this_exception_support (&default_exception_support_info))
11767 {
11768 data->exception_info = &default_exception_support_info;
11769 return;
11770 }
11771
11772 /* Try the v0 exception suport info. */
11773 if (ada_has_this_exception_support (&exception_support_info_v0))
11774 {
11775 data->exception_info = &exception_support_info_v0;
11776 return;
11777 }
11778
11779 /* Try our fallback exception suport info. */
11780 if (ada_has_this_exception_support (&exception_support_info_fallback))
11781 {
11782 data->exception_info = &exception_support_info_fallback;
11783 return;
11784 }
11785
11786 throw_error (NOT_FOUND_ERROR,
11787 _("Could not find Ada runtime exception support"));
11788 }
11789
11790 /* True iff FRAME is very likely to be that of a function that is
11791 part of the runtime system. This is all very heuristic, but is
11792 intended to be used as advice as to what frames are uninteresting
11793 to most users. */
11794
11795 static int
is_known_support_routine(const frame_info_ptr & frame)11796 is_known_support_routine (const frame_info_ptr &frame)
11797 {
11798 enum language func_lang;
11799 int i;
11800 const char *fullname;
11801
11802 /* If this code does not have any debugging information (no symtab),
11803 This cannot be any user code. */
11804
11805 symtab_and_line sal = find_frame_sal (frame);
11806 if (sal.symtab == NULL)
11807 return 1;
11808
11809 /* If there is a symtab, but the associated source file cannot be
11810 located, then assume this is not user code: Selecting a frame
11811 for which we cannot display the code would not be very helpful
11812 for the user. This should also take care of case such as VxWorks
11813 where the kernel has some debugging info provided for a few units. */
11814
11815 fullname = symtab_to_fullname (sal.symtab);
11816 if (access (fullname, R_OK) != 0)
11817 return 1;
11818
11819 /* Check the unit filename against the Ada runtime file naming.
11820 We also check the name of the objfile against the name of some
11821 known system libraries that sometimes come with debugging info
11822 too. */
11823
11824 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11825 {
11826 re_comp (known_runtime_file_name_patterns[i]);
11827 if (re_exec (lbasename (sal.symtab->filename)))
11828 return 1;
11829 if (sal.symtab->compunit ()->objfile () != NULL
11830 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11831 return 1;
11832 }
11833
11834 /* Check whether the function is a GNAT-generated entity. */
11835
11836 gdb::unique_xmalloc_ptr<char> func_name
11837 = find_frame_funname (frame, &func_lang, NULL);
11838 if (func_name == NULL)
11839 return 1;
11840
11841 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11842 {
11843 re_comp (known_auxiliary_function_name_patterns[i]);
11844 if (re_exec (func_name.get ()))
11845 return 1;
11846 }
11847
11848 return 0;
11849 }
11850
11851 /* Find the first frame that contains debugging information and that is not
11852 part of the Ada run-time, starting from FI and moving upward. */
11853
11854 void
ada_find_printable_frame(const frame_info_ptr & initial_fi)11855 ada_find_printable_frame (const frame_info_ptr &initial_fi)
11856 {
11857 for (frame_info_ptr fi = initial_fi; fi != nullptr; fi = get_prev_frame (fi))
11858 {
11859 if (!is_known_support_routine (fi))
11860 {
11861 select_frame (fi);
11862 break;
11863 }
11864 }
11865
11866 }
11867
11868 /* Assuming that the inferior just triggered an unhandled exception
11869 catchpoint, return the address in inferior memory where the name
11870 of the exception is stored.
11871
11872 Return zero if the address could not be computed. */
11873
11874 static CORE_ADDR
ada_unhandled_exception_name_addr(void)11875 ada_unhandled_exception_name_addr (void)
11876 {
11877 return parse_and_eval_address ("e.full_name");
11878 }
11879
11880 /* Same as ada_unhandled_exception_name_addr, except that this function
11881 should be used when the inferior uses an older version of the runtime,
11882 where the exception name needs to be extracted from a specific frame
11883 several frames up in the callstack. */
11884
11885 static CORE_ADDR
ada_unhandled_exception_name_addr_from_raise(void)11886 ada_unhandled_exception_name_addr_from_raise (void)
11887 {
11888 int frame_level;
11889 frame_info_ptr fi;
11890 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11891
11892 /* To determine the name of this exception, we need to select
11893 the frame corresponding to RAISE_SYM_NAME. This frame is
11894 at least 3 levels up, so we simply skip the first 3 frames
11895 without checking the name of their associated function. */
11896 fi = get_current_frame ();
11897 for (frame_level = 0; frame_level < 3; frame_level += 1)
11898 if (fi != NULL)
11899 fi = get_prev_frame (fi);
11900
11901 while (fi != NULL)
11902 {
11903 enum language func_lang;
11904
11905 gdb::unique_xmalloc_ptr<char> func_name
11906 = find_frame_funname (fi, &func_lang, NULL);
11907 if (func_name != NULL)
11908 {
11909 if (strcmp (func_name.get (),
11910 data->exception_info->catch_exception_sym) == 0)
11911 break; /* We found the frame we were looking for... */
11912 }
11913 fi = get_prev_frame (fi);
11914 }
11915
11916 if (fi == NULL)
11917 return 0;
11918
11919 select_frame (fi);
11920 return parse_and_eval_address ("id.full_name");
11921 }
11922
11923 /* Assuming the inferior just triggered an Ada exception catchpoint
11924 (of any type), return the address in inferior memory where the name
11925 of the exception is stored, if applicable.
11926
11927 Assumes the selected frame is the current frame.
11928
11929 Return zero if the address could not be computed, or if not relevant. */
11930
11931 static CORE_ADDR
ada_exception_name_addr_1(enum ada_exception_catchpoint_kind ex)11932 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
11933 {
11934 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11935
11936 switch (ex)
11937 {
11938 case ada_catch_exception:
11939 return (parse_and_eval_address ("e.full_name"));
11940 break;
11941
11942 case ada_catch_exception_unhandled:
11943 return data->exception_info->unhandled_exception_name_addr ();
11944 break;
11945
11946 case ada_catch_handlers:
11947 return 0; /* The runtimes does not provide access to the exception
11948 name. */
11949 break;
11950
11951 case ada_catch_assert:
11952 return 0; /* Exception name is not relevant in this case. */
11953 break;
11954
11955 default:
11956 internal_error (_("unexpected catchpoint type"));
11957 break;
11958 }
11959
11960 return 0; /* Should never be reached. */
11961 }
11962
11963 /* Assuming the inferior is stopped at an exception catchpoint,
11964 return the message which was associated to the exception, if
11965 available. Return NULL if the message could not be retrieved.
11966
11967 Note: The exception message can be associated to an exception
11968 either through the use of the Raise_Exception function, or
11969 more simply (Ada 2005 and later), via:
11970
11971 raise Exception_Name with "exception message";
11972
11973 */
11974
11975 static gdb::unique_xmalloc_ptr<char>
ada_exception_message_1(void)11976 ada_exception_message_1 (void)
11977 {
11978 struct value *e_msg_val;
11979 int e_msg_len;
11980
11981 /* For runtimes that support this feature, the exception message
11982 is passed as an unbounded string argument called "message". */
11983 e_msg_val = parse_and_eval ("message");
11984 if (e_msg_val == NULL)
11985 return NULL; /* Exception message not supported. */
11986
11987 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11988 gdb_assert (e_msg_val != NULL);
11989 e_msg_len = e_msg_val->type ()->length ();
11990
11991 /* If the message string is empty, then treat it as if there was
11992 no exception message. */
11993 if (e_msg_len <= 0)
11994 return NULL;
11995
11996 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11997 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
11998 e_msg_len);
11999 e_msg.get ()[e_msg_len] = '\0';
12000
12001 return e_msg;
12002 }
12003
12004 /* Same as ada_exception_message_1, except that all exceptions are
12005 contained here (returning NULL instead). */
12006
12007 static gdb::unique_xmalloc_ptr<char>
ada_exception_message(void)12008 ada_exception_message (void)
12009 {
12010 gdb::unique_xmalloc_ptr<char> e_msg;
12011
12012 try
12013 {
12014 e_msg = ada_exception_message_1 ();
12015 }
12016 catch (const gdb_exception_error &e)
12017 {
12018 e_msg.reset (nullptr);
12019 }
12020
12021 return e_msg;
12022 }
12023
12024 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12025 any error that ada_exception_name_addr_1 might cause to be thrown.
12026 When an error is intercepted, a warning with the error message is printed,
12027 and zero is returned. */
12028
12029 static CORE_ADDR
ada_exception_name_addr(enum ada_exception_catchpoint_kind ex)12030 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12031 {
12032 CORE_ADDR result = 0;
12033
12034 try
12035 {
12036 result = ada_exception_name_addr_1 (ex);
12037 }
12038
12039 catch (const gdb_exception_error &e)
12040 {
12041 warning (_("failed to get exception name: %s"), e.what ());
12042 return 0;
12043 }
12044
12045 return result;
12046 }
12047
12048 static std::string ada_exception_catchpoint_cond_string
12049 (const char *excep_string,
12050 enum ada_exception_catchpoint_kind ex);
12051
12052 /* Ada catchpoints.
12053
12054 In the case of catchpoints on Ada exceptions, the catchpoint will
12055 stop the target on every exception the program throws. When a user
12056 specifies the name of a specific exception, we translate this
12057 request into a condition expression (in text form), and then parse
12058 it into an expression stored in each of the catchpoint's locations.
12059 We then use this condition to check whether the exception that was
12060 raised is the one the user is interested in. If not, then the
12061 target is resumed again. We store the name of the requested
12062 exception, in order to be able to re-set the condition expression
12063 when symbols change. */
12064
12065 /* An instance of this type is used to represent an Ada catchpoint. */
12066
12067 struct ada_catchpoint : public code_breakpoint
12068 {
ada_catchpointada_catchpoint12069 ada_catchpoint (struct gdbarch *gdbarch_,
12070 enum ada_exception_catchpoint_kind kind,
12071 const char *cond_string,
12072 bool tempflag,
12073 bool enabled,
12074 bool from_tty,
12075 std::string &&excep_string_)
12076 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
12077 m_excep_string (std::move (excep_string_)),
12078 m_kind (kind)
12079 {
12080 /* Unlike most code_breakpoint types, Ada catchpoints are
12081 pspace-specific. */
12082 pspace = current_program_space;
12083 enable_state = enabled ? bp_enabled : bp_disabled;
12084 language = language_ada;
12085
12086 re_set ();
12087 }
12088
12089 struct bp_location *allocate_location () override;
12090 void re_set () override;
12091 void check_status (struct bpstat *bs) override;
12092 enum print_stop_action print_it (const bpstat *bs) const override;
12093 bool print_one (const bp_location **) const override;
12094 void print_mention () const override;
12095 void print_recreate (struct ui_file *fp) const override;
12096
12097 private:
12098
12099 /* A helper function for check_status. Returns true if we should
12100 stop for this breakpoint hit. If the user specified a specific
12101 exception, we only want to cause a stop if the program thrown
12102 that exception. */
12103 bool should_stop_exception (const struct bp_location *bl) const;
12104
12105 /* The name of the specific exception the user specified. */
12106 std::string m_excep_string;
12107
12108 /* What kind of catchpoint this is. */
12109 enum ada_exception_catchpoint_kind m_kind;
12110 };
12111
12112 /* An instance of this type is used to represent an Ada catchpoint
12113 breakpoint location. */
12114
12115 class ada_catchpoint_location : public bp_location
12116 {
12117 public:
ada_catchpoint_location(ada_catchpoint * owner)12118 explicit ada_catchpoint_location (ada_catchpoint *owner)
12119 : bp_location (owner, bp_loc_software_breakpoint)
12120 {}
12121
12122 /* The condition that checks whether the exception that was raised
12123 is the specific exception the user specified on catchpoint
12124 creation. */
12125 expression_up excep_cond_expr;
12126 };
12127
12128 static struct symtab_and_line ada_exception_sal
12129 (enum ada_exception_catchpoint_kind ex);
12130
12131 /* Implement the RE_SET method in the structure for all exception
12132 catchpoint kinds. */
12133
12134 void
re_set()12135 ada_catchpoint::re_set ()
12136 {
12137 std::vector<symtab_and_line> sals;
12138 try
12139 {
12140 struct symtab_and_line sal = ada_exception_sal (m_kind);
12141 sals.push_back (sal);
12142 }
12143 catch (const gdb_exception_error &ex)
12144 {
12145 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12146 if (ex.error != NOT_FOUND_ERROR)
12147 throw;
12148 }
12149
12150 update_breakpoint_locations (this, pspace, sals, {});
12151
12152 /* Reparse the exception conditional expressions. One for each
12153 location. */
12154
12155 /* Nothing to do if there's no specific exception to catch. */
12156 if (m_excep_string.empty ())
12157 return;
12158
12159 /* Same if there are no locations... */
12160 if (!has_locations ())
12161 return;
12162
12163 /* Compute the condition expression in text form, from the specific
12164 exception we want to catch. */
12165 std::string cond_string
12166 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
12167
12168 /* Iterate over all the catchpoint's locations, and parse an
12169 expression for each. */
12170 for (bp_location &bl : locations ())
12171 {
12172 ada_catchpoint_location &ada_loc
12173 = static_cast<ada_catchpoint_location &> (bl);
12174 expression_up exp;
12175
12176 if (!bl.shlib_disabled)
12177 {
12178 const char *s;
12179
12180 s = cond_string.c_str ();
12181 try
12182 {
12183 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
12184 }
12185 catch (const gdb_exception_error &e)
12186 {
12187 warning (_("failed to reevaluate internal exception condition "
12188 "for catchpoint %d: %s"),
12189 number, e.what ());
12190 }
12191 }
12192
12193 ada_loc.excep_cond_expr = std::move (exp);
12194 }
12195 }
12196
12197 /* Implement the ALLOCATE_LOCATION method in the structure for all
12198 exception catchpoint kinds. */
12199
12200 struct bp_location *
allocate_location()12201 ada_catchpoint::allocate_location ()
12202 {
12203 return new ada_catchpoint_location (this);
12204 }
12205
12206 /* See declaration. */
12207
12208 bool
should_stop_exception(const struct bp_location * bl)12209 ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
12210 {
12211 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
12212 const struct ada_catchpoint_location *ada_loc
12213 = (const struct ada_catchpoint_location *) bl;
12214 bool stop;
12215
12216 struct internalvar *var = lookup_internalvar ("_ada_exception");
12217 if (c->m_kind == ada_catch_assert)
12218 clear_internalvar (var);
12219 else
12220 {
12221 try
12222 {
12223 const char *expr;
12224
12225 if (c->m_kind == ada_catch_handlers)
12226 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12227 ".all.occurrence.id");
12228 else
12229 expr = "e";
12230
12231 struct value *exc = parse_and_eval (expr);
12232 set_internalvar (var, exc);
12233 }
12234 catch (const gdb_exception_error &ex)
12235 {
12236 clear_internalvar (var);
12237 }
12238 }
12239
12240 /* With no specific exception, should always stop. */
12241 if (c->m_excep_string.empty ())
12242 return true;
12243
12244 if (ada_loc->excep_cond_expr == NULL)
12245 {
12246 /* We will have a NULL expression if back when we were creating
12247 the expressions, this location's had failed to parse. */
12248 return true;
12249 }
12250
12251 stop = true;
12252 try
12253 {
12254 scoped_value_mark mark;
12255 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
12256 }
12257 catch (const gdb_exception_error &ex)
12258 {
12259 exception_fprintf (gdb_stderr, ex,
12260 _("Error in testing exception condition:\n"));
12261 }
12262
12263 return stop;
12264 }
12265
12266 /* Implement the CHECK_STATUS method in the structure for all
12267 exception catchpoint kinds. */
12268
12269 void
check_status(bpstat * bs)12270 ada_catchpoint::check_status (bpstat *bs)
12271 {
12272 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12273 }
12274
12275 /* Implement the PRINT_IT method in the structure for all exception
12276 catchpoint kinds. */
12277
12278 enum print_stop_action
print_it(const bpstat * bs)12279 ada_catchpoint::print_it (const bpstat *bs) const
12280 {
12281 struct ui_out *uiout = current_uiout;
12282
12283 annotate_catchpoint (number);
12284
12285 if (uiout->is_mi_like_p ())
12286 {
12287 uiout->field_string ("reason",
12288 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12289 uiout->field_string ("disp", bpdisp_text (disposition));
12290 }
12291
12292 uiout->text (disposition == disp_del
12293 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12294 print_num_locno (bs, uiout);
12295 uiout->text (", ");
12296
12297 /* ada_exception_name_addr relies on the selected frame being the
12298 current frame. Need to do this here because this function may be
12299 called more than once when printing a stop, and below, we'll
12300 select the first frame past the Ada run-time (see
12301 ada_find_printable_frame). */
12302 select_frame (get_current_frame ());
12303
12304 switch (m_kind)
12305 {
12306 case ada_catch_exception:
12307 case ada_catch_exception_unhandled:
12308 case ada_catch_handlers:
12309 {
12310 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12311 char exception_name[256];
12312
12313 if (addr != 0)
12314 {
12315 read_memory (addr, (gdb_byte *) exception_name,
12316 sizeof (exception_name) - 1);
12317 exception_name [sizeof (exception_name) - 1] = '\0';
12318 }
12319 else
12320 {
12321 /* For some reason, we were unable to read the exception
12322 name. This could happen if the Runtime was compiled
12323 without debugging info, for instance. In that case,
12324 just replace the exception name by the generic string
12325 "exception" - it will read as "an exception" in the
12326 notification we are about to print. */
12327 memcpy (exception_name, "exception", sizeof ("exception"));
12328 }
12329 /* In the case of unhandled exception breakpoints, we print
12330 the exception name as "unhandled EXCEPTION_NAME", to make
12331 it clearer to the user which kind of catchpoint just got
12332 hit. We used ui_out_text to make sure that this extra
12333 info does not pollute the exception name in the MI case. */
12334 if (m_kind == ada_catch_exception_unhandled)
12335 uiout->text ("unhandled ");
12336 uiout->field_string ("exception-name", exception_name);
12337 }
12338 break;
12339 case ada_catch_assert:
12340 /* In this case, the name of the exception is not really
12341 important. Just print "failed assertion" to make it clearer
12342 that his program just hit an assertion-failure catchpoint.
12343 We used ui_out_text because this info does not belong in
12344 the MI output. */
12345 uiout->text ("failed assertion");
12346 break;
12347 }
12348
12349 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12350 if (exception_message != NULL)
12351 {
12352 uiout->text (" (");
12353 uiout->field_string ("exception-message", exception_message.get ());
12354 uiout->text (")");
12355 }
12356
12357 uiout->text (" at ");
12358 ada_find_printable_frame (get_current_frame ());
12359
12360 return PRINT_SRC_AND_LOC;
12361 }
12362
12363 /* Implement the PRINT_ONE method in the structure for all exception
12364 catchpoint kinds. */
12365
12366 bool
print_one(const bp_location ** last_loc)12367 ada_catchpoint::print_one (const bp_location **last_loc) const
12368 {
12369 struct ui_out *uiout = current_uiout;
12370 struct value_print_options opts;
12371
12372 get_user_print_options (&opts);
12373
12374 if (opts.addressprint)
12375 uiout->field_skip ("addr");
12376
12377 annotate_field (5);
12378 switch (m_kind)
12379 {
12380 case ada_catch_exception:
12381 if (!m_excep_string.empty ())
12382 {
12383 std::string msg = string_printf (_("`%s' Ada exception"),
12384 m_excep_string.c_str ());
12385
12386 uiout->field_string ("what", msg);
12387 }
12388 else
12389 uiout->field_string ("what", "all Ada exceptions");
12390
12391 break;
12392
12393 case ada_catch_exception_unhandled:
12394 uiout->field_string ("what", "unhandled Ada exceptions");
12395 break;
12396
12397 case ada_catch_handlers:
12398 if (!m_excep_string.empty ())
12399 {
12400 uiout->field_fmt ("what",
12401 _("`%s' Ada exception handlers"),
12402 m_excep_string.c_str ());
12403 }
12404 else
12405 uiout->field_string ("what", "all Ada exceptions handlers");
12406 break;
12407
12408 case ada_catch_assert:
12409 uiout->field_string ("what", "failed Ada assertions");
12410 break;
12411
12412 default:
12413 internal_error (_("unexpected catchpoint type"));
12414 break;
12415 }
12416
12417 return true;
12418 }
12419
12420 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12421 for all exception catchpoint kinds. */
12422
12423 void
print_mention()12424 ada_catchpoint::print_mention () const
12425 {
12426 struct ui_out *uiout = current_uiout;
12427
12428 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12429 : _("Catchpoint "));
12430 uiout->field_signed ("bkptno", number);
12431 uiout->text (": ");
12432
12433 switch (m_kind)
12434 {
12435 case ada_catch_exception:
12436 if (!m_excep_string.empty ())
12437 {
12438 std::string info = string_printf (_("`%s' Ada exception"),
12439 m_excep_string.c_str ());
12440 uiout->text (info);
12441 }
12442 else
12443 uiout->text (_("all Ada exceptions"));
12444 break;
12445
12446 case ada_catch_exception_unhandled:
12447 uiout->text (_("unhandled Ada exceptions"));
12448 break;
12449
12450 case ada_catch_handlers:
12451 if (!m_excep_string.empty ())
12452 {
12453 std::string info
12454 = string_printf (_("`%s' Ada exception handlers"),
12455 m_excep_string.c_str ());
12456 uiout->text (info);
12457 }
12458 else
12459 uiout->text (_("all Ada exceptions handlers"));
12460 break;
12461
12462 case ada_catch_assert:
12463 uiout->text (_("failed Ada assertions"));
12464 break;
12465
12466 default:
12467 internal_error (_("unexpected catchpoint type"));
12468 break;
12469 }
12470 }
12471
12472 /* Implement the PRINT_RECREATE method in the structure for all
12473 exception catchpoint kinds. */
12474
12475 void
print_recreate(struct ui_file * fp)12476 ada_catchpoint::print_recreate (struct ui_file *fp) const
12477 {
12478 switch (m_kind)
12479 {
12480 case ada_catch_exception:
12481 gdb_printf (fp, "catch exception");
12482 if (!m_excep_string.empty ())
12483 gdb_printf (fp, " %s", m_excep_string.c_str ());
12484 break;
12485
12486 case ada_catch_exception_unhandled:
12487 gdb_printf (fp, "catch exception unhandled");
12488 break;
12489
12490 case ada_catch_handlers:
12491 gdb_printf (fp, "catch handlers");
12492 break;
12493
12494 case ada_catch_assert:
12495 gdb_printf (fp, "catch assert");
12496 break;
12497
12498 default:
12499 internal_error (_("unexpected catchpoint type"));
12500 }
12501 print_recreate_thread (fp);
12502 }
12503
12504 /* See ada-lang.h. */
12505
12506 bool
is_ada_exception_catchpoint(breakpoint * bp)12507 is_ada_exception_catchpoint (breakpoint *bp)
12508 {
12509 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12510 }
12511
12512 /* Split the arguments specified in a "catch exception" command.
12513 Set EX to the appropriate catchpoint type.
12514 Set EXCEP_STRING to the name of the specific exception if
12515 specified by the user.
12516 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12517 "catch handlers" command. False otherwise.
12518 If a condition is found at the end of the arguments, the condition
12519 expression is stored in COND_STRING (memory must be deallocated
12520 after use). Otherwise COND_STRING is set to NULL. */
12521
12522 static void
catch_ada_exception_command_split(const char * args,bool is_catch_handlers_cmd,enum ada_exception_catchpoint_kind * ex,std::string * excep_string,std::string * cond_string)12523 catch_ada_exception_command_split (const char *args,
12524 bool is_catch_handlers_cmd,
12525 enum ada_exception_catchpoint_kind *ex,
12526 std::string *excep_string,
12527 std::string *cond_string)
12528 {
12529 std::string exception_name;
12530
12531 exception_name = extract_arg (&args);
12532 if (exception_name == "if")
12533 {
12534 /* This is not an exception name; this is the start of a condition
12535 expression for a catchpoint on all exceptions. So, "un-get"
12536 this token, and set exception_name to NULL. */
12537 exception_name.clear ();
12538 args -= 2;
12539 }
12540
12541 /* Check to see if we have a condition. */
12542
12543 args = skip_spaces (args);
12544 if (startswith (args, "if")
12545 && (isspace (args[2]) || args[2] == '\0'))
12546 {
12547 args += 2;
12548 args = skip_spaces (args);
12549
12550 if (args[0] == '\0')
12551 error (_("Condition missing after `if' keyword"));
12552 *cond_string = args;
12553
12554 args += strlen (args);
12555 }
12556
12557 /* Check that we do not have any more arguments. Anything else
12558 is unexpected. */
12559
12560 if (args[0] != '\0')
12561 error (_("Junk at end of expression"));
12562
12563 if (is_catch_handlers_cmd)
12564 {
12565 /* Catch handling of exceptions. */
12566 *ex = ada_catch_handlers;
12567 *excep_string = exception_name;
12568 }
12569 else if (exception_name.empty ())
12570 {
12571 /* Catch all exceptions. */
12572 *ex = ada_catch_exception;
12573 excep_string->clear ();
12574 }
12575 else if (exception_name == "unhandled")
12576 {
12577 /* Catch unhandled exceptions. */
12578 *ex = ada_catch_exception_unhandled;
12579 excep_string->clear ();
12580 }
12581 else
12582 {
12583 /* Catch a specific exception. */
12584 *ex = ada_catch_exception;
12585 *excep_string = exception_name;
12586 }
12587 }
12588
12589 /* Return the name of the symbol on which we should break in order to
12590 implement a catchpoint of the EX kind. */
12591
12592 static const char *
ada_exception_sym_name(enum ada_exception_catchpoint_kind ex)12593 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12594 {
12595 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12596
12597 gdb_assert (data->exception_info != NULL);
12598
12599 switch (ex)
12600 {
12601 case ada_catch_exception:
12602 return (data->exception_info->catch_exception_sym);
12603 break;
12604 case ada_catch_exception_unhandled:
12605 return (data->exception_info->catch_exception_unhandled_sym);
12606 break;
12607 case ada_catch_assert:
12608 return (data->exception_info->catch_assert_sym);
12609 break;
12610 case ada_catch_handlers:
12611 return (data->exception_info->catch_handlers_sym);
12612 break;
12613 default:
12614 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12615 }
12616 }
12617
12618 /* Return the condition that will be used to match the current exception
12619 being raised with the exception that the user wants to catch. This
12620 assumes that this condition is used when the inferior just triggered
12621 an exception catchpoint.
12622 EX: the type of catchpoints used for catching Ada exceptions. */
12623
12624 static std::string
ada_exception_catchpoint_cond_string(const char * excep_string,enum ada_exception_catchpoint_kind ex)12625 ada_exception_catchpoint_cond_string (const char *excep_string,
12626 enum ada_exception_catchpoint_kind ex)
12627 {
12628 bool is_standard_exc = false;
12629 std::string result;
12630
12631 if (ex == ada_catch_handlers)
12632 {
12633 /* For exception handlers catchpoints, the condition string does
12634 not use the same parameter as for the other exceptions. */
12635 result = ("long_integer (GNAT_GCC_exception_Access"
12636 "(gcc_exception).all.occurrence.id)");
12637 }
12638 else
12639 result = "long_integer (e)";
12640
12641 /* The standard exceptions are a special case. They are defined in
12642 runtime units that have been compiled without debugging info; if
12643 EXCEP_STRING is the not-fully-qualified name of a standard
12644 exception (e.g. "constraint_error") then, during the evaluation
12645 of the condition expression, the symbol lookup on this name would
12646 *not* return this standard exception. The catchpoint condition
12647 may then be set only on user-defined exceptions which have the
12648 same not-fully-qualified name (e.g. my_package.constraint_error).
12649
12650 To avoid this unexcepted behavior, these standard exceptions are
12651 systematically prefixed by "standard". This means that "catch
12652 exception constraint_error" is rewritten into "catch exception
12653 standard.constraint_error".
12654
12655 If an exception named constraint_error is defined in another package of
12656 the inferior program, then the only way to specify this exception as a
12657 breakpoint condition is to use its fully-qualified named:
12658 e.g. my_package.constraint_error. */
12659
12660 for (const char *name : standard_exc)
12661 {
12662 if (strcmp (name, excep_string) == 0)
12663 {
12664 is_standard_exc = true;
12665 break;
12666 }
12667 }
12668
12669 result += " = ";
12670
12671 if (is_standard_exc)
12672 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12673 else
12674 string_appendf (result, "long_integer (&%s)", excep_string);
12675
12676 return result;
12677 }
12678
12679 /* Return the symtab_and_line that should be used to insert an
12680 exception catchpoint of the TYPE kind. */
12681
12682 static struct symtab_and_line
ada_exception_sal(enum ada_exception_catchpoint_kind ex)12683 ada_exception_sal (enum ada_exception_catchpoint_kind ex)
12684 {
12685 const char *sym_name;
12686 struct symbol *sym;
12687
12688 /* First, find out which exception support info to use. */
12689 ada_exception_support_info_sniffer ();
12690
12691 /* Then lookup the function on which we will break in order to catch
12692 the Ada exceptions requested by the user. */
12693 sym_name = ada_exception_sym_name (ex);
12694 sym = standard_lookup (sym_name, NULL, SEARCH_VFT);
12695
12696 if (sym == NULL)
12697 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12698 sym_name);
12699
12700 if (sym->aclass () != LOC_BLOCK)
12701 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12702
12703 return find_function_start_sal (sym, 1);
12704 }
12705
12706 /* Create an Ada exception catchpoint.
12707
12708 EX_KIND is the kind of exception catchpoint to be created.
12709
12710 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12711 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12712 of the exception to which this catchpoint applies.
12713
12714 COND_STRING, if not empty, is the catchpoint condition.
12715
12716 TEMPFLAG, if nonzero, means that the underlying breakpoint
12717 should be temporary.
12718
12719 FROM_TTY is the usual argument passed to all commands implementations. */
12720
12721 void
create_ada_exception_catchpoint(struct gdbarch * gdbarch,enum ada_exception_catchpoint_kind ex_kind,std::string && excep_string,const std::string & cond_string,int tempflag,int enabled,int from_tty)12722 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12723 enum ada_exception_catchpoint_kind ex_kind,
12724 std::string &&excep_string,
12725 const std::string &cond_string,
12726 int tempflag,
12727 int enabled,
12728 int from_tty)
12729 {
12730 std::unique_ptr<ada_catchpoint> c
12731 (new ada_catchpoint (gdbarch, ex_kind,
12732 cond_string.empty () ? nullptr : cond_string.c_str (),
12733 tempflag, enabled, from_tty,
12734 std::move (excep_string)));
12735 install_breakpoint (0, std::move (c), 1);
12736 }
12737
12738 /* Implement the "catch exception" command. */
12739
12740 static void
catch_ada_exception_command(const char * arg_entry,int from_tty,struct cmd_list_element * command)12741 catch_ada_exception_command (const char *arg_entry, int from_tty,
12742 struct cmd_list_element *command)
12743 {
12744 const char *arg = arg_entry;
12745 struct gdbarch *gdbarch = get_current_arch ();
12746 int tempflag;
12747 enum ada_exception_catchpoint_kind ex_kind;
12748 std::string excep_string;
12749 std::string cond_string;
12750
12751 tempflag = command->context () == CATCH_TEMPORARY;
12752
12753 if (!arg)
12754 arg = "";
12755 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12756 &cond_string);
12757 create_ada_exception_catchpoint (gdbarch, ex_kind,
12758 std::move (excep_string), cond_string,
12759 tempflag, 1 /* enabled */,
12760 from_tty);
12761 }
12762
12763 /* Implement the "catch handlers" command. */
12764
12765 static void
catch_ada_handlers_command(const char * arg_entry,int from_tty,struct cmd_list_element * command)12766 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12767 struct cmd_list_element *command)
12768 {
12769 const char *arg = arg_entry;
12770 struct gdbarch *gdbarch = get_current_arch ();
12771 int tempflag;
12772 enum ada_exception_catchpoint_kind ex_kind;
12773 std::string excep_string;
12774 std::string cond_string;
12775
12776 tempflag = command->context () == CATCH_TEMPORARY;
12777
12778 if (!arg)
12779 arg = "";
12780 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12781 &cond_string);
12782 create_ada_exception_catchpoint (gdbarch, ex_kind,
12783 std::move (excep_string), cond_string,
12784 tempflag, 1 /* enabled */,
12785 from_tty);
12786 }
12787
12788 /* Completion function for the Ada "catch" commands. */
12789
12790 static void
catch_ada_completer(struct cmd_list_element * cmd,completion_tracker & tracker,const char * text,const char * word)12791 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12792 const char *text, const char *word)
12793 {
12794 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12795
12796 for (const ada_exc_info &info : exceptions)
12797 {
12798 if (startswith (info.name, word))
12799 tracker.add_completion (make_unique_xstrdup (info.name));
12800 }
12801 }
12802
12803 /* Split the arguments specified in a "catch assert" command.
12804
12805 ARGS contains the command's arguments (or the empty string if
12806 no arguments were passed).
12807
12808 If ARGS contains a condition, set COND_STRING to that condition
12809 (the memory needs to be deallocated after use). */
12810
12811 static void
catch_ada_assert_command_split(const char * args,std::string & cond_string)12812 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12813 {
12814 args = skip_spaces (args);
12815
12816 /* Check whether a condition was provided. */
12817 if (startswith (args, "if")
12818 && (isspace (args[2]) || args[2] == '\0'))
12819 {
12820 args += 2;
12821 args = skip_spaces (args);
12822 if (args[0] == '\0')
12823 error (_("condition missing after `if' keyword"));
12824 cond_string.assign (args);
12825 }
12826
12827 /* Otherwise, there should be no other argument at the end of
12828 the command. */
12829 else if (args[0] != '\0')
12830 error (_("Junk at end of arguments."));
12831 }
12832
12833 /* Implement the "catch assert" command. */
12834
12835 static void
catch_assert_command(const char * arg_entry,int from_tty,struct cmd_list_element * command)12836 catch_assert_command (const char *arg_entry, int from_tty,
12837 struct cmd_list_element *command)
12838 {
12839 const char *arg = arg_entry;
12840 struct gdbarch *gdbarch = get_current_arch ();
12841 int tempflag;
12842 std::string cond_string;
12843
12844 tempflag = command->context () == CATCH_TEMPORARY;
12845
12846 if (!arg)
12847 arg = "";
12848 catch_ada_assert_command_split (arg, cond_string);
12849 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12850 {}, cond_string,
12851 tempflag, 1 /* enabled */,
12852 from_tty);
12853 }
12854
12855 /* Return non-zero if the symbol SYM is an Ada exception object. */
12856
12857 static int
ada_is_exception_sym(struct symbol * sym)12858 ada_is_exception_sym (struct symbol *sym)
12859 {
12860 const char *type_name = sym->type ()->name ();
12861
12862 return (sym->aclass () != LOC_TYPEDEF
12863 && sym->aclass () != LOC_BLOCK
12864 && sym->aclass () != LOC_CONST
12865 && sym->aclass () != LOC_UNRESOLVED
12866 && type_name != NULL && strcmp (type_name, "exception") == 0);
12867 }
12868
12869 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12870 Ada exception object. This matches all exceptions except the ones
12871 defined by the Ada language. */
12872
12873 static int
ada_is_non_standard_exception_sym(struct symbol * sym)12874 ada_is_non_standard_exception_sym (struct symbol *sym)
12875 {
12876 if (!ada_is_exception_sym (sym))
12877 return 0;
12878
12879 for (const char *name : standard_exc)
12880 if (strcmp (sym->linkage_name (), name) == 0)
12881 return 0; /* A standard exception. */
12882
12883 /* Numeric_Error is also a standard exception, so exclude it.
12884 See the STANDARD_EXC description for more details as to why
12885 this exception is not listed in that array. */
12886 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12887 return 0;
12888
12889 return 1;
12890 }
12891
12892 /* A helper function for std::sort, comparing two struct ada_exc_info
12893 objects.
12894
12895 The comparison is determined first by exception name, and then
12896 by exception address. */
12897
12898 bool
12899 ada_exc_info::operator< (const ada_exc_info &other) const
12900 {
12901 int result;
12902
12903 result = strcmp (name, other.name);
12904 if (result < 0)
12905 return true;
12906 if (result == 0 && addr < other.addr)
12907 return true;
12908 return false;
12909 }
12910
12911 bool
12912 ada_exc_info::operator== (const ada_exc_info &other) const
12913 {
12914 return addr == other.addr && strcmp (name, other.name) == 0;
12915 }
12916
12917 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12918 routine, but keeping the first SKIP elements untouched.
12919
12920 All duplicates are also removed. */
12921
12922 static void
sort_remove_dups_ada_exceptions_list(std::vector<ada_exc_info> * exceptions,int skip)12923 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12924 int skip)
12925 {
12926 std::sort (exceptions->begin () + skip, exceptions->end ());
12927 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12928 exceptions->end ());
12929 }
12930
12931 /* Add all exceptions defined by the Ada standard whose name match
12932 a regular expression.
12933
12934 If PREG is not NULL, then this regexp_t object is used to
12935 perform the symbol name matching. Otherwise, no name-based
12936 filtering is performed.
12937
12938 EXCEPTIONS is a vector of exceptions to which matching exceptions
12939 gets pushed. */
12940
12941 static void
ada_add_standard_exceptions(compiled_regex * preg,std::vector<ada_exc_info> * exceptions)12942 ada_add_standard_exceptions (compiled_regex *preg,
12943 std::vector<ada_exc_info> *exceptions)
12944 {
12945 for (const char *name : standard_exc)
12946 {
12947 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12948 {
12949 symbol_name_match_type match_type = name_match_type_from_name (name);
12950 lookup_name_info lookup_name (name, match_type);
12951
12952 symbol_name_matcher_ftype *match_name
12953 = ada_get_symbol_name_matcher (lookup_name);
12954
12955 /* Iterate over all objfiles irrespective of scope or linker
12956 namespaces so we get all exceptions anywhere in the
12957 progspace. */
12958 for (objfile *objfile : current_program_space->objfiles ())
12959 {
12960 for (minimal_symbol *msymbol : objfile->msymbols ())
12961 {
12962 if (match_name (msymbol->linkage_name (), lookup_name,
12963 nullptr)
12964 && msymbol->type () != mst_solib_trampoline)
12965 {
12966 ada_exc_info info
12967 = {name, msymbol->value_address (objfile)};
12968
12969 exceptions->push_back (info);
12970 }
12971 }
12972 }
12973 }
12974 }
12975 }
12976
12977 /* Add all Ada exceptions defined locally and accessible from the given
12978 FRAME.
12979
12980 If PREG is not NULL, then this regexp_t object is used to
12981 perform the symbol name matching. Otherwise, no name-based
12982 filtering is performed.
12983
12984 EXCEPTIONS is a vector of exceptions to which matching exceptions
12985 gets pushed. */
12986
12987 static void
ada_add_exceptions_from_frame(compiled_regex * preg,const frame_info_ptr & frame,std::vector<ada_exc_info> * exceptions)12988 ada_add_exceptions_from_frame (compiled_regex *preg,
12989 const frame_info_ptr &frame,
12990 std::vector<ada_exc_info> *exceptions)
12991 {
12992 const struct block *block = get_frame_block (frame, 0);
12993
12994 while (block != 0)
12995 {
12996 for (struct symbol *sym : block_iterator_range (block))
12997 {
12998 switch (sym->aclass ())
12999 {
13000 case LOC_TYPEDEF:
13001 case LOC_BLOCK:
13002 case LOC_CONST:
13003 break;
13004 default:
13005 if (ada_is_exception_sym (sym))
13006 {
13007 struct ada_exc_info info = {sym->print_name (),
13008 sym->value_address ()};
13009
13010 exceptions->push_back (info);
13011 }
13012 }
13013 }
13014 if (block->function () != NULL)
13015 break;
13016 block = block->superblock ();
13017 }
13018 }
13019
13020 /* Return true if NAME matches PREG or if PREG is NULL. */
13021
13022 static bool
name_matches_regex(const char * name,compiled_regex * preg)13023 name_matches_regex (const char *name, compiled_regex *preg)
13024 {
13025 return (preg == NULL
13026 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13027 }
13028
13029 /* Add all exceptions defined globally whose name name match
13030 a regular expression, excluding standard exceptions.
13031
13032 The reason we exclude standard exceptions is that they need
13033 to be handled separately: Standard exceptions are defined inside
13034 a runtime unit which is normally not compiled with debugging info,
13035 and thus usually do not show up in our symbol search. However,
13036 if the unit was in fact built with debugging info, we need to
13037 exclude them because they would duplicate the entry we found
13038 during the special loop that specifically searches for those
13039 standard exceptions.
13040
13041 If PREG is not NULL, then this regexp_t object is used to
13042 perform the symbol name matching. Otherwise, no name-based
13043 filtering is performed.
13044
13045 EXCEPTIONS is a vector of exceptions to which matching exceptions
13046 gets pushed. */
13047
13048 static void
ada_add_global_exceptions(compiled_regex * preg,std::vector<ada_exc_info> * exceptions)13049 ada_add_global_exceptions (compiled_regex *preg,
13050 std::vector<ada_exc_info> *exceptions)
13051 {
13052 /* In Ada, the symbol "search name" is a linkage name, whereas the
13053 regular expression used to do the matching refers to the natural
13054 name. So match against the decoded name. */
13055 expand_symtabs_matching (NULL,
13056 lookup_name_info::match_any (),
13057 [&] (const char *search_name)
13058 {
13059 std::string decoded = ada_decode (search_name);
13060 return name_matches_regex (decoded.c_str (), preg);
13061 },
13062 NULL,
13063 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13064 SEARCH_VAR_DOMAIN);
13065
13066 /* Iterate over all objfiles irrespective of scope or linker namespaces
13067 so we get all exceptions anywhere in the progspace. */
13068 for (objfile *objfile : current_program_space->objfiles ())
13069 {
13070 for (compunit_symtab *s : objfile->compunits ())
13071 {
13072 const struct blockvector *bv = s->blockvector ();
13073 int i;
13074
13075 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13076 {
13077 const struct block *b = bv->block (i);
13078
13079 for (struct symbol *sym : block_iterator_range (b))
13080 if (ada_is_non_standard_exception_sym (sym)
13081 && name_matches_regex (sym->natural_name (), preg))
13082 {
13083 struct ada_exc_info info
13084 = {sym->print_name (), sym->value_address ()};
13085
13086 exceptions->push_back (info);
13087 }
13088 }
13089 }
13090 }
13091 }
13092
13093 /* Implements ada_exceptions_list with the regular expression passed
13094 as a regex_t, rather than a string.
13095
13096 If not NULL, PREG is used to filter out exceptions whose names
13097 do not match. Otherwise, all exceptions are listed. */
13098
13099 static std::vector<ada_exc_info>
ada_exceptions_list_1(compiled_regex * preg)13100 ada_exceptions_list_1 (compiled_regex *preg)
13101 {
13102 std::vector<ada_exc_info> result;
13103 int prev_len;
13104
13105 /* First, list the known standard exceptions. These exceptions
13106 need to be handled separately, as they are usually defined in
13107 runtime units that have been compiled without debugging info. */
13108
13109 ada_add_standard_exceptions (preg, &result);
13110
13111 /* Next, find all exceptions whose scope is local and accessible
13112 from the currently selected frame. */
13113
13114 if (has_stack_frames ())
13115 {
13116 prev_len = result.size ();
13117 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13118 &result);
13119 if (result.size () > prev_len)
13120 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13121 }
13122
13123 /* Add all exceptions whose scope is global. */
13124
13125 prev_len = result.size ();
13126 ada_add_global_exceptions (preg, &result);
13127 if (result.size () > prev_len)
13128 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13129
13130 return result;
13131 }
13132
13133 /* Return a vector of ada_exc_info.
13134
13135 If REGEXP is NULL, all exceptions are included in the result.
13136 Otherwise, it should contain a valid regular expression,
13137 and only the exceptions whose names match that regular expression
13138 are included in the result.
13139
13140 The exceptions are sorted in the following order:
13141 - Standard exceptions (defined by the Ada language), in
13142 alphabetical order;
13143 - Exceptions only visible from the current frame, in
13144 alphabetical order;
13145 - Exceptions whose scope is global, in alphabetical order. */
13146
13147 std::vector<ada_exc_info>
ada_exceptions_list(const char * regexp)13148 ada_exceptions_list (const char *regexp)
13149 {
13150 if (regexp == NULL)
13151 return ada_exceptions_list_1 (NULL);
13152
13153 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13154 return ada_exceptions_list_1 (®);
13155 }
13156
13157 /* Implement the "info exceptions" command. */
13158
13159 static void
info_exceptions_command(const char * regexp,int from_tty)13160 info_exceptions_command (const char *regexp, int from_tty)
13161 {
13162 struct gdbarch *gdbarch = get_current_arch ();
13163
13164 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13165
13166 if (regexp != NULL)
13167 gdb_printf
13168 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13169 else
13170 gdb_printf (_("All defined Ada exceptions:\n"));
13171
13172 for (const ada_exc_info &info : exceptions)
13173 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13174 }
13175
13176
13177 /* Language vector */
13178
13179 /* symbol_name_matcher_ftype adapter for wild_match. */
13180
13181 static bool
do_wild_match(const char * symbol_search_name,const lookup_name_info & lookup_name,completion_match_result * comp_match_res)13182 do_wild_match (const char *symbol_search_name,
13183 const lookup_name_info &lookup_name,
13184 completion_match_result *comp_match_res)
13185 {
13186 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13187 }
13188
13189 /* symbol_name_matcher_ftype adapter for full_match. */
13190
13191 static bool
do_full_match(const char * symbol_search_name,const lookup_name_info & lookup_name,completion_match_result * comp_match_res)13192 do_full_match (const char *symbol_search_name,
13193 const lookup_name_info &lookup_name,
13194 completion_match_result *comp_match_res)
13195 {
13196 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13197
13198 /* If both symbols start with "_ada_", just let the loop below
13199 handle the comparison. However, if only the symbol name starts
13200 with "_ada_", skip the prefix and let the match proceed as
13201 usual. */
13202 if (startswith (symbol_search_name, "_ada_")
13203 && !startswith (lname, "_ada"))
13204 symbol_search_name += 5;
13205 /* Likewise for ghost entities. */
13206 if (startswith (symbol_search_name, "___ghost_")
13207 && !startswith (lname, "___ghost_"))
13208 symbol_search_name += 9;
13209
13210 int uscore_count = 0;
13211 while (*lname != '\0')
13212 {
13213 if (*symbol_search_name != *lname)
13214 {
13215 if (*symbol_search_name == 'B' && uscore_count == 2
13216 && symbol_search_name[1] == '_')
13217 {
13218 symbol_search_name += 2;
13219 while (isdigit (*symbol_search_name))
13220 ++symbol_search_name;
13221 if (symbol_search_name[0] == '_'
13222 && symbol_search_name[1] == '_')
13223 {
13224 symbol_search_name += 2;
13225 continue;
13226 }
13227 }
13228 return false;
13229 }
13230
13231 if (*symbol_search_name == '_')
13232 ++uscore_count;
13233 else
13234 uscore_count = 0;
13235
13236 ++symbol_search_name;
13237 ++lname;
13238 }
13239
13240 return is_name_suffix (symbol_search_name);
13241 }
13242
13243 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13244
13245 static bool
do_exact_match(const char * symbol_search_name,const lookup_name_info & lookup_name,completion_match_result * comp_match_res)13246 do_exact_match (const char *symbol_search_name,
13247 const lookup_name_info &lookup_name,
13248 completion_match_result *comp_match_res)
13249 {
13250 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13251 }
13252
13253 /* Build the Ada lookup name for LOOKUP_NAME. */
13254
ada_lookup_name_info(const lookup_name_info & lookup_name)13255 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13256 {
13257 std::string_view user_name = lookup_name.name ();
13258
13259 if (!user_name.empty () && user_name[0] == '<')
13260 {
13261 if (user_name.back () == '>')
13262 m_encoded_name = user_name.substr (1, user_name.size () - 2);
13263 else
13264 m_encoded_name = user_name.substr (1, user_name.size () - 1);
13265 m_encoded_p = true;
13266 m_verbatim_p = true;
13267 m_wild_match_p = false;
13268 m_standard_p = false;
13269 }
13270 else
13271 {
13272 m_verbatim_p = false;
13273
13274 m_encoded_p = user_name.find ("__") != std::string_view::npos;
13275
13276 if (!m_encoded_p)
13277 {
13278 const char *folded = ada_fold_name (user_name);
13279 m_encoded_name = ada_encode_1 (folded, false);
13280 if (m_encoded_name.empty ())
13281 m_encoded_name = user_name;
13282 }
13283 else
13284 m_encoded_name = user_name;
13285
13286 /* Handle the 'package Standard' special case. See description
13287 of m_standard_p. */
13288 if (startswith (m_encoded_name.c_str (), "standard__"))
13289 {
13290 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13291 m_standard_p = true;
13292 }
13293 else
13294 m_standard_p = false;
13295
13296 m_decoded_name = ada_decode (m_encoded_name.c_str (), true, false, false);
13297
13298 /* If the name contains a ".", then the user is entering a fully
13299 qualified entity name, and the match must not be done in wild
13300 mode. Similarly, if the user wants to complete what looks
13301 like an encoded name, the match must not be done in wild
13302 mode. Also, in the standard__ special case always do
13303 non-wild matching. */
13304 m_wild_match_p
13305 = (lookup_name.match_type () != symbol_name_match_type::FULL
13306 && !m_encoded_p
13307 && !m_standard_p
13308 && user_name.find ('.') == std::string::npos);
13309 }
13310 }
13311
13312 /* symbol_name_matcher_ftype method for Ada. This only handles
13313 completion mode. */
13314
13315 static bool
ada_symbol_name_matches(const char * symbol_search_name,const lookup_name_info & lookup_name,completion_match_result * comp_match_res)13316 ada_symbol_name_matches (const char *symbol_search_name,
13317 const lookup_name_info &lookup_name,
13318 completion_match_result *comp_match_res)
13319 {
13320 return lookup_name.ada ().matches (symbol_search_name,
13321 lookup_name.match_type (),
13322 comp_match_res);
13323 }
13324
13325 /* A name matcher that matches the symbol name exactly, with
13326 strcmp. */
13327
13328 static bool
literal_symbol_name_matcher(const char * symbol_search_name,const lookup_name_info & lookup_name,completion_match_result * comp_match_res)13329 literal_symbol_name_matcher (const char *symbol_search_name,
13330 const lookup_name_info &lookup_name,
13331 completion_match_result *comp_match_res)
13332 {
13333 std::string_view name_view = lookup_name.name ();
13334
13335 if (lookup_name.completion_mode ()
13336 ? (strncmp (symbol_search_name, name_view.data (),
13337 name_view.size ()) == 0)
13338 : symbol_search_name == name_view)
13339 {
13340 if (comp_match_res != NULL)
13341 comp_match_res->set_match (symbol_search_name);
13342 return true;
13343 }
13344 else
13345 return false;
13346 }
13347
13348 /* Implement the "get_symbol_name_matcher" language_defn method for
13349 Ada. */
13350
13351 static symbol_name_matcher_ftype *
ada_get_symbol_name_matcher(const lookup_name_info & lookup_name)13352 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13353 {
13354 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13355 return literal_symbol_name_matcher;
13356
13357 if (lookup_name.completion_mode ())
13358 return ada_symbol_name_matches;
13359 else
13360 {
13361 if (lookup_name.ada ().wild_match_p ())
13362 return do_wild_match;
13363 else if (lookup_name.ada ().verbatim_p ())
13364 return do_exact_match;
13365 else
13366 return do_full_match;
13367 }
13368 }
13369
13370 /* Class representing the Ada language. */
13371
13372 class ada_language : public language_defn
13373 {
13374 public:
ada_language()13375 ada_language ()
13376 : language_defn (language_ada)
13377 { /* Nothing. */ }
13378
13379 /* See language.h. */
13380
name()13381 const char *name () const override
13382 { return "ada"; }
13383
13384 /* See language.h. */
13385
natural_name()13386 const char *natural_name () const override
13387 { return "Ada"; }
13388
13389 /* See language.h. */
13390
filename_extensions()13391 const std::vector<const char *> &filename_extensions () const override
13392 {
13393 static const std::vector<const char *> extensions
13394 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13395 return extensions;
13396 }
13397
13398 /* Print an array element index using the Ada syntax. */
13399
print_array_index(struct type * index_type,LONGEST index,struct ui_file * stream,const value_print_options * options)13400 void print_array_index (struct type *index_type,
13401 LONGEST index,
13402 struct ui_file *stream,
13403 const value_print_options *options) const override
13404 {
13405 struct value *index_value = val_atr (index_type, index);
13406
13407 value_print (index_value, stream, options);
13408 gdb_printf (stream, " => ");
13409 }
13410
13411 /* Implement the "read_var_value" language_defn method for Ada. */
13412
read_var_value(struct symbol * var,const struct block * var_block,const frame_info_ptr & frame)13413 struct value *read_var_value (struct symbol *var,
13414 const struct block *var_block,
13415 const frame_info_ptr &frame) const override
13416 {
13417 /* The only case where default_read_var_value is not sufficient
13418 is when VAR is a renaming... */
13419 if (frame != nullptr)
13420 {
13421 const struct block *frame_block = get_frame_block (frame, NULL);
13422 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13423 return ada_read_renaming_var_value (var, frame_block);
13424 }
13425
13426 /* This is a typical case where we expect the default_read_var_value
13427 function to work. */
13428 return language_defn::read_var_value (var, var_block, frame);
13429 }
13430
13431 /* See language.h. */
symbol_printing_suppressed(struct symbol * symbol)13432 bool symbol_printing_suppressed (struct symbol *symbol) const override
13433 {
13434 return symbol->is_artificial ();
13435 }
13436
13437 /* See language.h. */
value_string(struct gdbarch * gdbarch,const char * ptr,ssize_t len)13438 struct value *value_string (struct gdbarch *gdbarch,
13439 const char *ptr, ssize_t len) const override
13440 {
13441 struct type *type = language_string_char_type (this, gdbarch);
13442 value *val = ::value_string (ptr, len, type);
13443 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13444 strings that are arrays of characters, so fix the type now. */
13445 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13446 val->type ()->set_code (TYPE_CODE_ARRAY);
13447 return val;
13448 }
13449
13450 /* See language.h. */
language_arch_info(struct gdbarch * gdbarch,struct language_arch_info * lai)13451 void language_arch_info (struct gdbarch *gdbarch,
13452 struct language_arch_info *lai) const override
13453 {
13454 const struct builtin_type *builtin = builtin_type (gdbarch);
13455
13456 /* Helper function to allow shorter lines below. */
13457 auto add = [&] (struct type *t)
13458 {
13459 lai->add_primitive_type (t);
13460 };
13461
13462 type_allocator alloc (gdbarch);
13463 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13464 0, "integer"));
13465 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13466 0, "long_integer"));
13467 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13468 0, "short_integer"));
13469 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13470 1, "character");
13471 lai->set_string_char_type (char_type);
13472 add (char_type);
13473 add (init_character_type (alloc, 16, 1, "wide_character"));
13474 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13475 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13476 "float", gdbarch_float_format (gdbarch)));
13477 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13478 "long_float", gdbarch_double_format (gdbarch)));
13479 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13480 0, "long_long_integer"));
13481 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13482 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
13483 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13484 "long_long_float",
13485 gdbarch_long_double_format (gdbarch)));
13486 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13487 0, "natural"));
13488 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13489 0, "positive"));
13490 add (builtin->builtin_void);
13491
13492 struct type *system_addr_ptr
13493 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13494 "void"));
13495 system_addr_ptr->set_name ("system__address");
13496 add (system_addr_ptr);
13497
13498 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13499 type. This is a signed integral type whose size is the same as
13500 the size of addresses. */
13501 unsigned int addr_length = system_addr_ptr->length ();
13502 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13503 "storage_offset"));
13504
13505 lai->set_bool_type (builtin->builtin_bool);
13506 }
13507
13508 /* See language.h. */
13509
iterate_over_symbols(const struct block * block,const lookup_name_info & name,domain_search_flags domain,gdb::function_view<symbol_found_callback_ftype> callback)13510 bool iterate_over_symbols
13511 (const struct block *block, const lookup_name_info &name,
13512 domain_search_flags domain,
13513 gdb::function_view<symbol_found_callback_ftype> callback) const override
13514 {
13515 std::vector<struct block_symbol> results
13516 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13517 for (block_symbol &sym : results)
13518 {
13519 if (!callback (&sym))
13520 return false;
13521 }
13522
13523 return true;
13524 }
13525
13526 /* See language.h. */
sniff_from_mangled_name(const char * mangled,gdb::unique_xmalloc_ptr<char> * out)13527 bool sniff_from_mangled_name
13528 (const char *mangled,
13529 gdb::unique_xmalloc_ptr<char> *out) const override
13530 {
13531 std::string demangled = ada_decode (mangled);
13532
13533 *out = NULL;
13534
13535 if (demangled != mangled && demangled[0] != '<')
13536 {
13537 /* Set the gsymbol language to Ada, but still return 0.
13538 Two reasons for that:
13539
13540 1. For Ada, we prefer computing the symbol's decoded name
13541 on the fly rather than pre-compute it, in order to save
13542 memory (Ada projects are typically very large).
13543
13544 2. There are some areas in the definition of the GNAT
13545 encoding where, with a bit of bad luck, we might be able
13546 to decode a non-Ada symbol, generating an incorrect
13547 demangled name (Eg: names ending with "TB" for instance
13548 are identified as task bodies and so stripped from
13549 the decoded name returned).
13550
13551 Returning true, here, but not setting *DEMANGLED, helps us get
13552 a little bit of the best of both worlds. Because we're last,
13553 we should not affect any of the other languages that were
13554 able to demangle the symbol before us; we get to correctly
13555 tag Ada symbols as such; and even if we incorrectly tagged a
13556 non-Ada symbol, which should be rare, any routing through the
13557 Ada language should be transparent (Ada tries to behave much
13558 like C/C++ with non-Ada symbols). */
13559 return true;
13560 }
13561
13562 return false;
13563 }
13564
13565 /* See language.h. */
13566
demangle_symbol(const char * mangled,int options)13567 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13568 int options) const override
13569 {
13570 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13571 }
13572
13573 /* See language.h. */
13574
print_type(struct type * type,const char * varstring,struct ui_file * stream,int show,int level,const struct type_print_options * flags)13575 void print_type (struct type *type, const char *varstring,
13576 struct ui_file *stream, int show, int level,
13577 const struct type_print_options *flags) const override
13578 {
13579 ada_print_type (type, varstring, stream, show, level, flags);
13580 }
13581
13582 /* See language.h. */
13583
word_break_characters(void)13584 const char *word_break_characters (void) const override
13585 {
13586 return ada_completer_word_break_characters;
13587 }
13588
13589 /* See language.h. */
13590
collect_symbol_completion_matches(completion_tracker & tracker,complete_symbol_mode mode,symbol_name_match_type name_match_type,const char * text,const char * word,enum type_code code)13591 void collect_symbol_completion_matches (completion_tracker &tracker,
13592 complete_symbol_mode mode,
13593 symbol_name_match_type name_match_type,
13594 const char *text, const char *word,
13595 enum type_code code) const override
13596 {
13597 const struct block *b, *surrounding_static_block = 0;
13598
13599 gdb_assert (code == TYPE_CODE_UNDEF);
13600
13601 lookup_name_info lookup_name (text, name_match_type, true);
13602
13603 /* First, look at the partial symtab symbols. */
13604 expand_symtabs_matching (NULL,
13605 lookup_name,
13606 NULL,
13607 NULL,
13608 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13609 SEARCH_ALL_DOMAINS);
13610
13611 /* At this point scan through the misc symbol vectors and add each
13612 symbol you find to the list. Eventually we want to ignore
13613 anything that isn't a text symbol (everything else will be
13614 handled by the psymtab code above). */
13615
13616 for (objfile *objfile : current_program_space->objfiles ())
13617 {
13618 for (minimal_symbol *msymbol : objfile->msymbols ())
13619 {
13620 QUIT;
13621
13622 if (completion_skip_symbol (mode, msymbol))
13623 continue;
13624
13625 language symbol_language = msymbol->language ();
13626
13627 /* Ada minimal symbols won't have their language set to Ada. If
13628 we let completion_list_add_name compare using the
13629 default/C-like matcher, then when completing e.g., symbols in a
13630 package named "pck", we'd match internal Ada symbols like
13631 "pckS", which are invalid in an Ada expression, unless you wrap
13632 them in '<' '>' to request a verbatim match.
13633
13634 Unfortunately, some Ada encoded names successfully demangle as
13635 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13636 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13637 with the wrong language set. Paper over that issue here. */
13638 if (symbol_language == language_unknown
13639 || symbol_language == language_cplus)
13640 symbol_language = language_ada;
13641
13642 completion_list_add_name (tracker,
13643 symbol_language,
13644 msymbol->linkage_name (),
13645 lookup_name, text, word);
13646 }
13647 }
13648
13649 /* Search upwards from currently selected frame (so that we can
13650 complete on local vars. */
13651
13652 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13653 {
13654 if (!b->superblock ())
13655 surrounding_static_block = b; /* For elmin of dups */
13656
13657 for (struct symbol *sym : block_iterator_range (b))
13658 {
13659 if (completion_skip_symbol (mode, sym))
13660 continue;
13661
13662 completion_list_add_name (tracker,
13663 sym->language (),
13664 sym->linkage_name (),
13665 lookup_name, text, word);
13666 }
13667 }
13668
13669 /* Go through the symtabs and check the externs and statics for
13670 symbols which match. */
13671
13672 for (objfile *objfile : current_program_space->objfiles ())
13673 {
13674 for (compunit_symtab *s : objfile->compunits ())
13675 {
13676 QUIT;
13677 b = s->blockvector ()->global_block ();
13678 for (struct symbol *sym : block_iterator_range (b))
13679 {
13680 if (completion_skip_symbol (mode, sym))
13681 continue;
13682
13683 completion_list_add_name (tracker,
13684 sym->language (),
13685 sym->linkage_name (),
13686 lookup_name, text, word);
13687 }
13688 }
13689 }
13690
13691 for (objfile *objfile : current_program_space->objfiles ())
13692 {
13693 for (compunit_symtab *s : objfile->compunits ())
13694 {
13695 QUIT;
13696 b = s->blockvector ()->static_block ();
13697 /* Don't do this block twice. */
13698 if (b == surrounding_static_block)
13699 continue;
13700 for (struct symbol *sym : block_iterator_range (b))
13701 {
13702 if (completion_skip_symbol (mode, sym))
13703 continue;
13704
13705 completion_list_add_name (tracker,
13706 sym->language (),
13707 sym->linkage_name (),
13708 lookup_name, text, word);
13709 }
13710 }
13711 }
13712 }
13713
13714 /* See language.h. */
13715
watch_location_expression(struct type * type,CORE_ADDR addr)13716 gdb::unique_xmalloc_ptr<char> watch_location_expression
13717 (struct type *type, CORE_ADDR addr) const override
13718 {
13719 type = check_typedef (check_typedef (type)->target_type ());
13720 std::string name = type_to_string (type);
13721 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13722 }
13723
13724 /* See language.h. */
13725
value_print(struct value * val,struct ui_file * stream,const struct value_print_options * options)13726 void value_print (struct value *val, struct ui_file *stream,
13727 const struct value_print_options *options) const override
13728 {
13729 return ada_value_print (val, stream, options);
13730 }
13731
13732 /* See language.h. */
13733
value_print_inner(struct value * val,struct ui_file * stream,int recurse,const struct value_print_options * options)13734 void value_print_inner
13735 (struct value *val, struct ui_file *stream, int recurse,
13736 const struct value_print_options *options) const override
13737 {
13738 return ada_value_print_inner (val, stream, recurse, options);
13739 }
13740
13741 /* See language.h. */
13742
lookup_symbol_nonlocal(const char * name,const struct block * block,const domain_search_flags domain)13743 struct block_symbol lookup_symbol_nonlocal
13744 (const char *name, const struct block *block,
13745 const domain_search_flags domain) const override
13746 {
13747 struct block_symbol sym;
13748
13749 sym = ada_lookup_symbol (name,
13750 (block == nullptr
13751 ? nullptr
13752 : block->static_block ()),
13753 domain);
13754 if (sym.symbol != NULL)
13755 return sym;
13756
13757 /* If we haven't found a match at this point, try the primitive
13758 types. In other languages, this search is performed before
13759 searching for global symbols in order to short-circuit that
13760 global-symbol search if it happens that the name corresponds
13761 to a primitive type. But we cannot do the same in Ada, because
13762 it is perfectly legitimate for a program to declare a type which
13763 has the same name as a standard type. If looking up a type in
13764 that situation, we have traditionally ignored the primitive type
13765 in favor of user-defined types. This is why, unlike most other
13766 languages, we search the primitive types this late and only after
13767 having searched the global symbols without success. */
13768
13769 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
13770 {
13771 struct gdbarch *gdbarch;
13772
13773 if (block == NULL)
13774 gdbarch = current_inferior ()->arch ();
13775 else
13776 gdbarch = block->gdbarch ();
13777 sym.symbol
13778 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13779 if (sym.symbol != NULL)
13780 return sym;
13781 }
13782
13783 return {};
13784 }
13785
13786 /* See language.h. */
13787
parser(struct parser_state * ps)13788 int parser (struct parser_state *ps) const override
13789 {
13790 warnings_issued = 0;
13791 return ada_parse (ps);
13792 }
13793
13794 /* See language.h. */
13795
emitchar(int ch,struct type * chtype,struct ui_file * stream,int quoter)13796 void emitchar (int ch, struct type *chtype,
13797 struct ui_file *stream, int quoter) const override
13798 {
13799 ada_emit_char (ch, chtype, stream, quoter, 1);
13800 }
13801
13802 /* See language.h. */
13803
printchar(int ch,struct type * chtype,struct ui_file * stream)13804 void printchar (int ch, struct type *chtype,
13805 struct ui_file *stream) const override
13806 {
13807 ada_printchar (ch, chtype, stream);
13808 }
13809
13810 /* See language.h. */
13811
printstr(struct ui_file * stream,struct type * elttype,const gdb_byte * string,unsigned int length,const char * encoding,int force_ellipses,const struct value_print_options * options)13812 void printstr (struct ui_file *stream, struct type *elttype,
13813 const gdb_byte *string, unsigned int length,
13814 const char *encoding, int force_ellipses,
13815 const struct value_print_options *options) const override
13816 {
13817 ada_printstr (stream, elttype, string, length, encoding,
13818 force_ellipses, options);
13819 }
13820
13821 /* See language.h. */
13822
print_typedef(struct type * type,struct symbol * new_symbol,struct ui_file * stream)13823 void print_typedef (struct type *type, struct symbol *new_symbol,
13824 struct ui_file *stream) const override
13825 {
13826 ada_print_typedef (type, new_symbol, stream);
13827 }
13828
13829 /* See language.h. */
13830
is_string_type_p(struct type * type)13831 bool is_string_type_p (struct type *type) const override
13832 {
13833 return ada_is_string_type (type);
13834 }
13835
13836 /* See language.h. */
13837
is_array_like(struct type * type)13838 bool is_array_like (struct type *type) const override
13839 {
13840 return (ada_is_constrained_packed_array_type (type)
13841 || ada_is_array_descriptor_type (type));
13842 }
13843
13844 /* See language.h. */
13845
to_array(struct value * val)13846 struct value *to_array (struct value *val) const override
13847 { return ada_coerce_to_simple_array (val); }
13848
13849 /* See language.h. */
13850
struct_too_deep_ellipsis()13851 const char *struct_too_deep_ellipsis () const override
13852 { return "(...)"; }
13853
13854 /* See language.h. */
13855
c_style_arrays_p()13856 bool c_style_arrays_p () const override
13857 { return false; }
13858
13859 /* See language.h. */
13860
store_sym_names_in_linkage_form_p()13861 bool store_sym_names_in_linkage_form_p () const override
13862 { return true; }
13863
13864 /* See language.h. */
13865
varobj_ops()13866 const struct lang_varobj_ops *varobj_ops () const override
13867 { return &ada_varobj_ops; }
13868
13869 protected:
13870 /* See language.h. */
13871
get_symbol_name_matcher_inner(const lookup_name_info & lookup_name)13872 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13873 (const lookup_name_info &lookup_name) const override
13874 {
13875 return ada_get_symbol_name_matcher (lookup_name);
13876 }
13877 };
13878
13879 /* Single instance of the Ada language class. */
13880
13881 static ada_language ada_language_defn;
13882
13883 /* Command-list for the "set/show ada" prefix command. */
13884 static struct cmd_list_element *set_ada_list;
13885 static struct cmd_list_element *show_ada_list;
13886
13887 /* This module's 'new_objfile' observer. */
13888
13889 static void
ada_new_objfile_observer(struct objfile * objfile)13890 ada_new_objfile_observer (struct objfile *objfile)
13891 {
13892 ada_clear_symbol_cache (objfile->pspace);
13893 }
13894
13895 /* This module's 'free_objfile' observer. */
13896
13897 static void
ada_free_objfile_observer(struct objfile * objfile)13898 ada_free_objfile_observer (struct objfile *objfile)
13899 {
13900 ada_clear_symbol_cache (objfile->pspace);
13901 }
13902
13903 /* Charsets known to GNAT. */
13904 static const char * const gnat_source_charsets[] =
13905 {
13906 /* Note that code below assumes that the default comes first.
13907 Latin-1 is the default here, because that is also GNAT's
13908 default. */
13909 "ISO-8859-1",
13910 "ISO-8859-2",
13911 "ISO-8859-3",
13912 "ISO-8859-4",
13913 "ISO-8859-5",
13914 "ISO-8859-15",
13915 "CP437",
13916 "CP850",
13917 /* Note that this value is special-cased in the encoder and
13918 decoder. */
13919 ada_utf8,
13920 nullptr
13921 };
13922
13923 void _initialize_ada_language ();
13924 void
_initialize_ada_language()13925 _initialize_ada_language ()
13926 {
13927 add_setshow_prefix_cmd
13928 ("ada", no_class,
13929 _("Prefix command for changing Ada-specific settings."),
13930 _("Generic command for showing Ada-specific settings."),
13931 &set_ada_list, &show_ada_list,
13932 &setlist, &showlist);
13933
13934 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13935 &trust_pad_over_xvs, _("\
13936 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13937 Show whether an optimization trusting PAD types over XVS types is activated."),
13938 _("\
13939 This is related to the encoding used by the GNAT compiler. The debugger\n\
13940 should normally trust the contents of PAD types, but certain older versions\n\
13941 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13942 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13943 work around this bug. It is always safe to turn this option \"off\", but\n\
13944 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13945 this option to \"off\" unless necessary."),
13946 NULL, NULL, &set_ada_list, &show_ada_list);
13947
13948 add_setshow_boolean_cmd ("print-signatures", class_vars,
13949 &print_signatures, _("\
13950 Enable or disable the output of formal and return types for functions in the \
13951 overloads selection menu."), _("\
13952 Show whether the output of formal and return types for functions in the \
13953 overloads selection menu is activated."),
13954 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13955
13956 ada_source_charset = gnat_source_charsets[0];
13957 add_setshow_enum_cmd ("source-charset", class_files,
13958 gnat_source_charsets,
13959 &ada_source_charset, _("\
13960 Set the Ada source character set."), _("\
13961 Show the Ada source character set."), _("\
13962 The character set used for Ada source files.\n\
13963 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13964 nullptr, nullptr,
13965 &set_ada_list, &show_ada_list);
13966
13967 add_catch_command ("exception", _("\
13968 Catch Ada exceptions, when raised.\n\
13969 Usage: catch exception [ARG] [if CONDITION]\n\
13970 Without any argument, stop when any Ada exception is raised.\n\
13971 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13972 being raised does not have a handler (and will therefore lead to the task's\n\
13973 termination).\n\
13974 Otherwise, the catchpoint only stops when the name of the exception being\n\
13975 raised is the same as ARG.\n\
13976 CONDITION is a boolean expression that is evaluated to see whether the\n\
13977 exception should cause a stop."),
13978 catch_ada_exception_command,
13979 catch_ada_completer,
13980 CATCH_PERMANENT,
13981 CATCH_TEMPORARY);
13982
13983 add_catch_command ("handlers", _("\
13984 Catch Ada exceptions, when handled.\n\
13985 Usage: catch handlers [ARG] [if CONDITION]\n\
13986 Without any argument, stop when any Ada exception is handled.\n\
13987 With an argument, catch only exceptions with the given name.\n\
13988 CONDITION is a boolean expression that is evaluated to see whether the\n\
13989 exception should cause a stop."),
13990 catch_ada_handlers_command,
13991 catch_ada_completer,
13992 CATCH_PERMANENT,
13993 CATCH_TEMPORARY);
13994 add_catch_command ("assert", _("\
13995 Catch failed Ada assertions, when raised.\n\
13996 Usage: catch assert [if CONDITION]\n\
13997 CONDITION is a boolean expression that is evaluated to see whether the\n\
13998 exception should cause a stop."),
13999 catch_assert_command,
14000 NULL,
14001 CATCH_PERMANENT,
14002 CATCH_TEMPORARY);
14003
14004 add_info ("exceptions", info_exceptions_command,
14005 _("\
14006 List all Ada exception names.\n\
14007 Usage: info exceptions [REGEXP]\n\
14008 If a regular expression is passed as an argument, only those matching\n\
14009 the regular expression are listed."));
14010
14011 add_setshow_prefix_cmd ("ada", class_maintenance,
14012 _("Set Ada maintenance-related variables."),
14013 _("Show Ada maintenance-related variables."),
14014 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14015 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14016
14017 add_setshow_boolean_cmd
14018 ("ignore-descriptive-types", class_maintenance,
14019 &ada_ignore_descriptive_types_p,
14020 _("Set whether descriptive types generated by GNAT should be ignored."),
14021 _("Show whether descriptive types generated by GNAT should be ignored."),
14022 _("\
14023 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14024 DWARF attribute."),
14025 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14026
14027 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14028 htab_eq_string,
14029 NULL, xcalloc, xfree);
14030
14031 /* The ada-lang observers. */
14032 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14033 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14034 "ada-lang");
14035 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14036 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14037
14038 #ifdef GDB_SELF_TEST
14039 selftests::register_test ("ada-decode", ada_decode_tests);
14040 #endif
14041 }
14042