]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/ada-lang.c
Use type allocator for array types
[thirdparty/binutils-gdb.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2023 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 "defs.h"
22 #include <ctype.h>
23 #include "gdbsupport/gdb_regex.h"
24 #include "frame.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "gdbcmd.h"
28 #include "expression.h"
29 #include "parser-defs.h"
30 #include "language.h"
31 #include "varobj.h"
32 #include "inferior.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "breakpoint.h"
36 #include "gdbcore.h"
37 #include "hashtab.h"
38 #include "gdbsupport/gdb_obstack.h"
39 #include "ada-lang.h"
40 #include "completer.h"
41 #include "ui-out.h"
42 #include "block.h"
43 #include "infcall.h"
44 #include "annotate.h"
45 #include "valprint.h"
46 #include "source.h"
47 #include "observable.h"
48 #include "stack.h"
49 #include "typeprint.h"
50 #include "namespace.h"
51 #include "cli/cli-style.h"
52 #include "cli/cli-decode.h"
53
54 #include "value.h"
55 #include "mi/mi-common.h"
56 #include "arch-utils.h"
57 #include "cli/cli-utils.h"
58 #include "gdbsupport/function-view.h"
59 #include "gdbsupport/byte-vector.h"
60 #include <algorithm>
61 #include "ada-exp.h"
62 #include "charset.h"
63 #include "ax-gdb.h"
64
65 /* Define whether or not the C operator '/' truncates towards zero for
66 differently signed operands (truncation direction is undefined in C).
67 Copied from valarith.c. */
68
69 #ifndef TRUNCATION_TOWARDS_ZERO
70 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
71 #endif
72
73 static struct type *desc_base_type (struct type *);
74
75 static struct type *desc_bounds_type (struct type *);
76
77 static struct value *desc_bounds (struct value *);
78
79 static int fat_pntr_bounds_bitpos (struct type *);
80
81 static int fat_pntr_bounds_bitsize (struct type *);
82
83 static struct type *desc_data_target_type (struct type *);
84
85 static struct value *desc_data (struct value *);
86
87 static int fat_pntr_data_bitpos (struct type *);
88
89 static int fat_pntr_data_bitsize (struct type *);
90
91 static struct value *desc_one_bound (struct value *, int, int);
92
93 static int desc_bound_bitpos (struct type *, int, int);
94
95 static int desc_bound_bitsize (struct type *, int, int);
96
97 static struct type *desc_index_type (struct type *, int);
98
99 static int desc_arity (struct type *);
100
101 static int ada_args_match (struct symbol *, struct value **, int);
102
103 static struct value *make_array_descriptor (struct type *, struct value *);
104
105 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
106 const struct block *,
107 const lookup_name_info &lookup_name,
108 domain_enum, struct objfile *);
109
110 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
111 const struct block *,
112 const lookup_name_info &lookup_name,
113 domain_enum, int, int *);
114
115 static int is_nonfunction (const std::vector<struct block_symbol> &);
116
117 static void add_defn_to_vec (std::vector<struct block_symbol> &,
118 struct symbol *,
119 const struct block *);
120
121 static int possible_user_operator_p (enum exp_opcode, struct value **);
122
123 static const char *ada_decoded_op_name (enum exp_opcode);
124
125 static int numeric_type_p (struct type *);
126
127 static int integer_type_p (struct type *);
128
129 static int scalar_type_p (struct type *);
130
131 static int discrete_type_p (struct type *);
132
133 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
134 int, int);
135
136 static struct type *ada_find_parallel_type_with_name (struct type *,
137 const char *);
138
139 static int is_dynamic_field (struct type *, int);
140
141 static struct type *to_fixed_variant_branch_type (struct type *,
142 const gdb_byte *,
143 CORE_ADDR, struct value *);
144
145 static struct type *to_fixed_array_type (struct type *, struct value *, int);
146
147 static struct type *to_fixed_range_type (struct type *, struct value *);
148
149 static struct type *to_static_fixed_type (struct type *);
150 static struct type *static_unwrap_type (struct type *type);
151
152 static struct value *unwrap_value (struct value *);
153
154 static struct type *constrained_packed_array_type (struct type *, long *);
155
156 static struct type *decode_constrained_packed_array_type (struct type *);
157
158 static long decode_packed_array_bitsize (struct type *);
159
160 static struct value *decode_constrained_packed_array (struct value *);
161
162 static int ada_is_unconstrained_packed_array_type (struct type *);
163
164 static struct value *value_subscript_packed (struct value *, int,
165 struct value **);
166
167 static struct value *coerce_unspec_val_to_type (struct value *,
168 struct type *);
169
170 static int lesseq_defined_than (struct symbol *, struct symbol *);
171
172 static int equiv_types (struct type *, struct type *);
173
174 static int is_name_suffix (const char *);
175
176 static int advance_wild_match (const char **, const char *, char);
177
178 static bool wild_match (const char *name, const char *patn);
179
180 static struct value *ada_coerce_ref (struct value *);
181
182 static LONGEST pos_atr (struct value *);
183
184 static struct value *val_atr (struct type *, LONGEST);
185
186 static struct symbol *standard_lookup (const char *, const struct block *,
187 domain_enum);
188
189 static struct value *ada_search_struct_field (const char *, struct value *, int,
190 struct type *);
191
192 static int find_struct_field (const char *, struct type *, int,
193 struct type **, int *, int *, int *, int *);
194
195 static int ada_resolve_function (std::vector<struct block_symbol> &,
196 struct value **, int, const char *,
197 struct type *, bool);
198
199 static int ada_is_direct_array_type (struct type *);
200
201 static struct value *ada_index_struct_field (int, struct value *, int,
202 struct type *);
203
204 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
205
206
207 static struct type *ada_find_any_type (const char *name);
208
209 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
210 (const lookup_name_info &lookup_name);
211
212 \f
213
214 /* The character set used for source files. */
215 static const char *ada_source_charset;
216
217 /* The string "UTF-8". This is here so we can check for the UTF-8
218 charset using == rather than strcmp. */
219 static const char ada_utf8[] = "UTF-8";
220
221 /* Each entry in the UTF-32 case-folding table is of this form. */
222 struct utf8_entry
223 {
224 /* The start and end, inclusive, of this range of codepoints. */
225 uint32_t start, end;
226 /* The delta to apply to get the upper-case form. 0 if this is
227 already upper-case. */
228 int upper_delta;
229 /* The delta to apply to get the lower-case form. 0 if this is
230 already lower-case. */
231 int lower_delta;
232
233 bool operator< (uint32_t val) const
234 {
235 return end < val;
236 }
237 };
238
239 static const utf8_entry ada_case_fold[] =
240 {
241 #include "ada-casefold.h"
242 };
243
244 \f
245
246 /* The result of a symbol lookup to be stored in our symbol cache. */
247
248 struct cache_entry
249 {
250 /* The name used to perform the lookup. */
251 const char *name;
252 /* The namespace used during the lookup. */
253 domain_enum domain;
254 /* The symbol returned by the lookup, or NULL if no matching symbol
255 was found. */
256 struct symbol *sym;
257 /* The block where the symbol was found, or NULL if no matching
258 symbol was found. */
259 const struct block *block;
260 /* A pointer to the next entry with the same hash. */
261 struct cache_entry *next;
262 };
263
264 /* The Ada symbol cache, used to store the result of Ada-mode symbol
265 lookups in the course of executing the user's commands.
266
267 The cache is implemented using a simple, fixed-sized hash.
268 The size is fixed on the grounds that there are not likely to be
269 all that many symbols looked up during any given session, regardless
270 of the size of the symbol table. If we decide to go to a resizable
271 table, let's just use the stuff from libiberty instead. */
272
273 #define HASH_SIZE 1009
274
275 struct ada_symbol_cache
276 {
277 /* An obstack used to store the entries in our cache. */
278 struct auto_obstack cache_space;
279
280 /* The root of the hash table used to implement our symbol cache. */
281 struct cache_entry *root[HASH_SIZE] {};
282 };
283
284 static const char ada_completer_word_break_characters[] =
285 #ifdef VMS
286 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
287 #else
288 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
289 #endif
290
291 /* The name of the symbol to use to get the name of the main subprogram. */
292 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
293 = "__gnat_ada_main_program_name";
294
295 /* Limit on the number of warnings to raise per expression evaluation. */
296 static int warning_limit = 2;
297
298 /* Number of warning messages issued; reset to 0 by cleanups after
299 expression evaluation. */
300 static int warnings_issued = 0;
301
302 static const char * const known_runtime_file_name_patterns[] = {
303 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
304 };
305
306 static const char * const known_auxiliary_function_name_patterns[] = {
307 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
308 };
309
310 /* Maintenance-related settings for this module. */
311
312 static struct cmd_list_element *maint_set_ada_cmdlist;
313 static struct cmd_list_element *maint_show_ada_cmdlist;
314
315 /* The "maintenance ada set/show ignore-descriptive-type" value. */
316
317 static bool ada_ignore_descriptive_types_p = false;
318
319 /* Inferior-specific data. */
320
321 /* Per-inferior data for this module. */
322
323 struct ada_inferior_data
324 {
325 /* The ada__tags__type_specific_data type, which is used when decoding
326 tagged types. With older versions of GNAT, this type was directly
327 accessible through a component ("tsd") in the object tag. But this
328 is no longer the case, so we cache it for each inferior. */
329 struct type *tsd_type = nullptr;
330
331 /* The exception_support_info data. This data is used to determine
332 how to implement support for Ada exception catchpoints in a given
333 inferior. */
334 const struct exception_support_info *exception_info = nullptr;
335 };
336
337 /* Our key to this module's inferior data. */
338 static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
339
340 /* Return our inferior data for the given inferior (INF).
341
342 This function always returns a valid pointer to an allocated
343 ada_inferior_data structure. If INF's inferior data has not
344 been previously set, this functions creates a new one with all
345 fields set to zero, sets INF's inferior to it, and then returns
346 a pointer to that newly allocated ada_inferior_data. */
347
348 static struct ada_inferior_data *
349 get_ada_inferior_data (struct inferior *inf)
350 {
351 struct ada_inferior_data *data;
352
353 data = ada_inferior_data.get (inf);
354 if (data == NULL)
355 data = ada_inferior_data.emplace (inf);
356
357 return data;
358 }
359
360 /* Perform all necessary cleanups regarding our module's inferior data
361 that is required after the inferior INF just exited. */
362
363 static void
364 ada_inferior_exit (struct inferior *inf)
365 {
366 ada_inferior_data.clear (inf);
367 }
368
369
370 /* program-space-specific data. */
371
372 /* This module's per-program-space data. */
373 struct ada_pspace_data
374 {
375 /* The Ada symbol cache. */
376 std::unique_ptr<ada_symbol_cache> sym_cache;
377 };
378
379 /* Key to our per-program-space data. */
380 static const registry<program_space>::key<ada_pspace_data>
381 ada_pspace_data_handle;
382
383 /* Return this module's data for the given program space (PSPACE).
384 If not is found, add a zero'ed one now.
385
386 This function always returns a valid object. */
387
388 static struct ada_pspace_data *
389 get_ada_pspace_data (struct program_space *pspace)
390 {
391 struct ada_pspace_data *data;
392
393 data = ada_pspace_data_handle.get (pspace);
394 if (data == NULL)
395 data = ada_pspace_data_handle.emplace (pspace);
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 *
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 *
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
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
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
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
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
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 *
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 *
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
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
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
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
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
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
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
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
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.kind () == PROP_CONST)
677 return high.const_val ();
678 else
679 {
680 gdb_assert (high.kind () == PROP_UNDEFINED);
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
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.kind () == PROP_CONST)
712 return low.const_val ();
713 else
714 {
715 gdb_assert (low.kind () == PROP_UNDEFINED);
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 *
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 *
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 *
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 \f
790
791 /* Language Selection */
792
793 /* If the main program is in Ada, return language_ada, otherwise return LANG
794 (the main program is in Ada iif the adainit symbol is found). */
795
796 static enum language
797 ada_update_initial_language (enum language lang)
798 {
799 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
800 return language_ada;
801
802 return lang;
803 }
804
805 /* If the main procedure is written in Ada, then return its name.
806 The result is good until the next call. Return NULL if the main
807 procedure doesn't appear to be in Ada. */
808
809 const char *
810 ada_main_name ()
811 {
812 struct bound_minimal_symbol msym;
813 static gdb::unique_xmalloc_ptr<char> main_program_name;
814
815 /* For Ada, the name of the main procedure is stored in a specific
816 string constant, generated by the binder. Look for that symbol,
817 extract its address, and then read that string. If we didn't find
818 that string, then most probably the main procedure is not written
819 in Ada. */
820 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
821
822 if (msym.minsym != NULL)
823 {
824 CORE_ADDR main_program_name_addr = msym.value_address ();
825 if (main_program_name_addr == 0)
826 error (_("Invalid address for Ada main program name."));
827
828 main_program_name = target_read_string (main_program_name_addr, 1024);
829 return main_program_name.get ();
830 }
831
832 /* The main procedure doesn't seem to be in Ada. */
833 return NULL;
834 }
835 \f
836 /* Symbols */
837
838 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
839 of NULLs. */
840
841 const struct ada_opname_map ada_opname_table[] = {
842 {"Oadd", "\"+\"", BINOP_ADD},
843 {"Osubtract", "\"-\"", BINOP_SUB},
844 {"Omultiply", "\"*\"", BINOP_MUL},
845 {"Odivide", "\"/\"", BINOP_DIV},
846 {"Omod", "\"mod\"", BINOP_MOD},
847 {"Orem", "\"rem\"", BINOP_REM},
848 {"Oexpon", "\"**\"", BINOP_EXP},
849 {"Olt", "\"<\"", BINOP_LESS},
850 {"Ole", "\"<=\"", BINOP_LEQ},
851 {"Ogt", "\">\"", BINOP_GTR},
852 {"Oge", "\">=\"", BINOP_GEQ},
853 {"Oeq", "\"=\"", BINOP_EQUAL},
854 {"One", "\"/=\"", BINOP_NOTEQUAL},
855 {"Oand", "\"and\"", BINOP_BITWISE_AND},
856 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
857 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
858 {"Oconcat", "\"&\"", BINOP_CONCAT},
859 {"Oabs", "\"abs\"", UNOP_ABS},
860 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
861 {"Oadd", "\"+\"", UNOP_PLUS},
862 {"Osubtract", "\"-\"", UNOP_NEG},
863 {NULL, NULL}
864 };
865
866 /* If STR is a decoded version of a compiler-provided suffix (like the
867 "[cold]" in "symbol[cold]"), return true. Otherwise, return
868 false. */
869
870 static bool
871 is_compiler_suffix (const char *str)
872 {
873 gdb_assert (*str == '[');
874 ++str;
875 while (*str != '\0' && isalpha (*str))
876 ++str;
877 /* We accept a missing "]" in order to support completion. */
878 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
879 }
880
881 /* Append a non-ASCII character to RESULT. */
882 static void
883 append_hex_encoded (std::string &result, uint32_t one_char)
884 {
885 if (one_char <= 0xff)
886 {
887 result.append ("U");
888 result.append (phex (one_char, 1));
889 }
890 else if (one_char <= 0xffff)
891 {
892 result.append ("W");
893 result.append (phex (one_char, 2));
894 }
895 else
896 {
897 result.append ("WW");
898 result.append (phex (one_char, 4));
899 }
900 }
901
902 /* Return a string that is a copy of the data in STORAGE, with
903 non-ASCII characters replaced by the appropriate hex encoding. A
904 template is used because, for UTF-8, we actually want to work with
905 UTF-32 codepoints. */
906 template<typename T>
907 std::string
908 copy_and_hex_encode (struct obstack *storage)
909 {
910 const T *chars = (T *) obstack_base (storage);
911 int num_chars = obstack_object_size (storage) / sizeof (T);
912 std::string result;
913 for (int i = 0; i < num_chars; ++i)
914 {
915 if (chars[i] <= 0x7f)
916 {
917 /* The host character set has to be a superset of ASCII, as
918 are all the other character sets we can use. */
919 result.push_back (chars[i]);
920 }
921 else
922 append_hex_encoded (result, chars[i]);
923 }
924 return result;
925 }
926
927 /* The "encoded" form of DECODED, according to GNAT conventions. If
928 THROW_ERRORS, throw an error if invalid operator name is found.
929 Otherwise, return the empty string in that case. */
930
931 static std::string
932 ada_encode_1 (const char *decoded, bool throw_errors)
933 {
934 if (decoded == NULL)
935 return {};
936
937 std::string encoding_buffer;
938 bool saw_non_ascii = false;
939 for (const char *p = decoded; *p != '\0'; p += 1)
940 {
941 if ((*p & 0x80) != 0)
942 saw_non_ascii = true;
943
944 if (*p == '.')
945 encoding_buffer.append ("__");
946 else if (*p == '[' && is_compiler_suffix (p))
947 {
948 encoding_buffer = encoding_buffer + "." + (p + 1);
949 if (encoding_buffer.back () == ']')
950 encoding_buffer.pop_back ();
951 break;
952 }
953 else if (*p == '"')
954 {
955 const struct ada_opname_map *mapping;
956
957 for (mapping = ada_opname_table;
958 mapping->encoded != NULL
959 && !startswith (p, mapping->decoded); mapping += 1)
960 ;
961 if (mapping->encoded == NULL)
962 {
963 if (throw_errors)
964 error (_("invalid Ada operator name: %s"), p);
965 else
966 return {};
967 }
968 encoding_buffer.append (mapping->encoded);
969 break;
970 }
971 else
972 encoding_buffer.push_back (*p);
973 }
974
975 /* If a non-ASCII character is seen, we must convert it to the
976 appropriate hex form. As this is more expensive, we keep track
977 of whether it is even necessary. */
978 if (saw_non_ascii)
979 {
980 auto_obstack storage;
981 bool is_utf8 = ada_source_charset == ada_utf8;
982 try
983 {
984 convert_between_encodings
985 (host_charset (),
986 is_utf8 ? HOST_UTF32 : ada_source_charset,
987 (const gdb_byte *) encoding_buffer.c_str (),
988 encoding_buffer.length (), 1,
989 &storage, translit_none);
990 }
991 catch (const gdb_exception &)
992 {
993 static bool warned = false;
994
995 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
996 might like to know why. */
997 if (!warned)
998 {
999 warned = true;
1000 warning (_("charset conversion failure for '%s'.\n"
1001 "You may have the wrong value for 'set ada source-charset'."),
1002 encoding_buffer.c_str ());
1003 }
1004
1005 /* We don't try to recover from errors. */
1006 return encoding_buffer;
1007 }
1008
1009 if (is_utf8)
1010 return copy_and_hex_encode<uint32_t> (&storage);
1011 return copy_and_hex_encode<gdb_byte> (&storage);
1012 }
1013
1014 return encoding_buffer;
1015 }
1016
1017 /* Find the entry for C in the case-folding table. Return nullptr if
1018 the entry does not cover C. */
1019 static const utf8_entry *
1020 find_case_fold_entry (uint32_t c)
1021 {
1022 auto iter = std::lower_bound (std::begin (ada_case_fold),
1023 std::end (ada_case_fold),
1024 c);
1025 if (iter == std::end (ada_case_fold)
1026 || c < iter->start
1027 || c > iter->end)
1028 return nullptr;
1029 return &*iter;
1030 }
1031
1032 /* Return NAME folded to lower case, or, if surrounded by single
1033 quotes, unfolded, but with the quotes stripped away. If
1034 THROW_ON_ERROR is true, encoding failures will throw an exception
1035 rather than emitting a warning. Result good to next call. */
1036
1037 static const char *
1038 ada_fold_name (gdb::string_view name, bool throw_on_error = false)
1039 {
1040 static std::string fold_storage;
1041
1042 if (!name.empty () && name[0] == '\'')
1043 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
1044 else
1045 {
1046 /* Why convert to UTF-32 and implement our own case-folding,
1047 rather than convert to wchar_t and use the platform's
1048 functions? I'm glad you asked.
1049
1050 The main problem is that GNAT implements an unusual rule for
1051 case folding. For ASCII letters, letters in single-byte
1052 encodings (such as ISO-8859-*), and Unicode letters that fit
1053 in a single byte (i.e., code point is <= 0xff), the letter is
1054 folded to lower case. Other Unicode letters are folded to
1055 upper case.
1056
1057 This rule means that the code must be able to examine the
1058 value of the character. And, some hosts do not use Unicode
1059 for wchar_t, so examining the value of such characters is
1060 forbidden. */
1061 auto_obstack storage;
1062 try
1063 {
1064 convert_between_encodings
1065 (host_charset (), HOST_UTF32,
1066 (const gdb_byte *) name.data (),
1067 name.length (), 1,
1068 &storage, translit_none);
1069 }
1070 catch (const gdb_exception &)
1071 {
1072 if (throw_on_error)
1073 throw;
1074
1075 static bool warned = false;
1076
1077 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1078 might like to know why. */
1079 if (!warned)
1080 {
1081 warned = true;
1082 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1083 "This normally should not happen, please file a bug report."),
1084 gdb::to_string (name).c_str (), host_charset ());
1085 }
1086
1087 /* We don't try to recover from errors; just return the
1088 original string. */
1089 fold_storage = gdb::to_string (name);
1090 return fold_storage.c_str ();
1091 }
1092
1093 bool is_utf8 = ada_source_charset == ada_utf8;
1094 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1095 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1096 for (int i = 0; i < num_chars; ++i)
1097 {
1098 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1099 if (entry != nullptr)
1100 {
1101 uint32_t low = chars[i] + entry->lower_delta;
1102 if (!is_utf8 || low <= 0xff)
1103 chars[i] = low;
1104 else
1105 chars[i] = chars[i] + entry->upper_delta;
1106 }
1107 }
1108
1109 /* Now convert back to ordinary characters. */
1110 auto_obstack reconverted;
1111 try
1112 {
1113 convert_between_encodings (HOST_UTF32,
1114 host_charset (),
1115 (const gdb_byte *) chars,
1116 num_chars * sizeof (uint32_t),
1117 sizeof (uint32_t),
1118 &reconverted,
1119 translit_none);
1120 obstack_1grow (&reconverted, '\0');
1121 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1122 }
1123 catch (const gdb_exception &)
1124 {
1125 if (throw_on_error)
1126 throw;
1127
1128 static bool warned = false;
1129
1130 /* Converting back from UTF-32 shouldn't normally fail, but
1131 there are some host encodings without upper/lower
1132 equivalence. */
1133 if (!warned)
1134 {
1135 warned = true;
1136 warning (_("could not convert the lower-cased variant of '%s'\n"
1137 "from UTF-32 to the host encoding (%s)."),
1138 gdb::to_string (name).c_str (), host_charset ());
1139 }
1140
1141 /* We don't try to recover from errors; just return the
1142 original string. */
1143 fold_storage = gdb::to_string (name);
1144 }
1145 }
1146
1147 return fold_storage.c_str ();
1148 }
1149
1150 /* The "encoded" form of DECODED, according to GNAT conventions. If
1151 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1152 with <...> quoting are not folded in any case. */
1153
1154 std::string
1155 ada_encode (const char *decoded, bool fold)
1156 {
1157 if (fold && decoded[0] != '<')
1158 decoded = ada_fold_name (decoded);
1159 return ada_encode_1 (decoded, true);
1160 }
1161
1162 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1163
1164 static int
1165 is_lower_alphanum (const char c)
1166 {
1167 return (isdigit (c) || (isalpha (c) && islower (c)));
1168 }
1169
1170 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1171 This function saves in LEN the length of that same symbol name but
1172 without either of these suffixes:
1173 . .{DIGIT}+
1174 . ${DIGIT}+
1175 . ___{DIGIT}+
1176 . __{DIGIT}+.
1177
1178 These are suffixes introduced by the compiler for entities such as
1179 nested subprogram for instance, in order to avoid name clashes.
1180 They do not serve any purpose for the debugger. */
1181
1182 static void
1183 ada_remove_trailing_digits (const char *encoded, int *len)
1184 {
1185 if (*len > 1 && isdigit (encoded[*len - 1]))
1186 {
1187 int i = *len - 2;
1188
1189 while (i > 0 && isdigit (encoded[i]))
1190 i--;
1191 if (i >= 0 && encoded[i] == '.')
1192 *len = i;
1193 else if (i >= 0 && encoded[i] == '$')
1194 *len = i;
1195 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1196 *len = i - 2;
1197 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1198 *len = i - 1;
1199 }
1200 }
1201
1202 /* Remove the suffix introduced by the compiler for protected object
1203 subprograms. */
1204
1205 static void
1206 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1207 {
1208 /* Remove trailing N. */
1209
1210 /* Protected entry subprograms are broken into two
1211 separate subprograms: The first one is unprotected, and has
1212 a 'N' suffix; the second is the protected version, and has
1213 the 'P' suffix. The second calls the first one after handling
1214 the protection. Since the P subprograms are internally generated,
1215 we leave these names undecoded, giving the user a clue that this
1216 entity is internal. */
1217
1218 if (*len > 1
1219 && encoded[*len - 1] == 'N'
1220 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1221 *len = *len - 1;
1222 }
1223
1224 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1225 then update *LEN to remove the suffix and return the offset of the
1226 character just past the ".". Otherwise, return -1. */
1227
1228 static int
1229 remove_compiler_suffix (const char *encoded, int *len)
1230 {
1231 int offset = *len - 1;
1232 while (offset > 0 && isalpha (encoded[offset]))
1233 --offset;
1234 if (offset > 0 && encoded[offset] == '.')
1235 {
1236 *len = offset;
1237 return offset + 1;
1238 }
1239 return -1;
1240 }
1241
1242 /* Convert an ASCII hex string to a number. Reads exactly N
1243 characters from STR. Returns true on success, false if one of the
1244 digits was not a hex digit. */
1245 static bool
1246 convert_hex (const char *str, int n, uint32_t *out)
1247 {
1248 uint32_t result = 0;
1249
1250 for (int i = 0; i < n; ++i)
1251 {
1252 if (!isxdigit (str[i]))
1253 return false;
1254 result <<= 4;
1255 result |= fromhex (str[i]);
1256 }
1257
1258 *out = result;
1259 return true;
1260 }
1261
1262 /* Convert a wide character from its ASCII hex representation in STR
1263 (consisting of exactly N characters) to the host encoding,
1264 appending the resulting bytes to OUT. If N==2 and the Ada source
1265 charset is not UTF-8, then hex refers to an encoding in the
1266 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1267 Return false and do not modify OUT on conversion failure. */
1268 static bool
1269 convert_from_hex_encoded (std::string &out, const char *str, int n)
1270 {
1271 uint32_t value;
1272
1273 if (!convert_hex (str, n, &value))
1274 return false;
1275 try
1276 {
1277 auto_obstack bytes;
1278 /* In the 'U' case, the hex digits encode the character in the
1279 Ada source charset. However, if the source charset is UTF-8,
1280 this really means it is a single-byte UTF-32 character. */
1281 if (n == 2 && ada_source_charset != ada_utf8)
1282 {
1283 gdb_byte one_char = (gdb_byte) value;
1284
1285 convert_between_encodings (ada_source_charset, host_charset (),
1286 &one_char,
1287 sizeof (one_char), sizeof (one_char),
1288 &bytes, translit_none);
1289 }
1290 else
1291 convert_between_encodings (HOST_UTF32, host_charset (),
1292 (const gdb_byte *) &value,
1293 sizeof (value), sizeof (value),
1294 &bytes, translit_none);
1295 obstack_1grow (&bytes, '\0');
1296 out.append ((const char *) obstack_base (&bytes));
1297 }
1298 catch (const gdb_exception &)
1299 {
1300 /* On failure, the caller will just let the encoded form
1301 through, which seems basically reasonable. */
1302 return false;
1303 }
1304
1305 return true;
1306 }
1307
1308 /* See ada-lang.h. */
1309
1310 std::string
1311 ada_decode (const char *encoded, bool wrap, bool operators)
1312 {
1313 int i;
1314 int len0;
1315 const char *p;
1316 int at_start_name;
1317 std::string decoded;
1318 int suffix = -1;
1319
1320 /* With function descriptors on PPC64, the value of a symbol named
1321 ".FN", if it exists, is the entry point of the function "FN". */
1322 if (encoded[0] == '.')
1323 encoded += 1;
1324
1325 /* The name of the Ada main procedure starts with "_ada_".
1326 This prefix is not part of the decoded name, so skip this part
1327 if we see this prefix. */
1328 if (startswith (encoded, "_ada_"))
1329 encoded += 5;
1330 /* The "___ghost_" prefix is used for ghost entities. Normally
1331 these aren't preserved but when they are, it's useful to see
1332 them. */
1333 if (startswith (encoded, "___ghost_"))
1334 encoded += 9;
1335
1336 /* If the name starts with '_', then it is not a properly encoded
1337 name, so do not attempt to decode it. Similarly, if the name
1338 starts with '<', the name should not be decoded. */
1339 if (encoded[0] == '_' || encoded[0] == '<')
1340 goto Suppress;
1341
1342 len0 = strlen (encoded);
1343
1344 suffix = remove_compiler_suffix (encoded, &len0);
1345
1346 ada_remove_trailing_digits (encoded, &len0);
1347 ada_remove_po_subprogram_suffix (encoded, &len0);
1348
1349 /* Remove the ___X.* suffix if present. Do not forget to verify that
1350 the suffix is located before the current "end" of ENCODED. We want
1351 to avoid re-matching parts of ENCODED that have previously been
1352 marked as discarded (by decrementing LEN0). */
1353 p = strstr (encoded, "___");
1354 if (p != NULL && p - encoded < len0 - 3)
1355 {
1356 if (p[3] == 'X')
1357 len0 = p - encoded;
1358 else
1359 goto Suppress;
1360 }
1361
1362 /* Remove any trailing TKB suffix. It tells us that this symbol
1363 is for the body of a task, but that information does not actually
1364 appear in the decoded name. */
1365
1366 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1367 len0 -= 3;
1368
1369 /* Remove any trailing TB suffix. The TB suffix is slightly different
1370 from the TKB suffix because it is used for non-anonymous task
1371 bodies. */
1372
1373 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1374 len0 -= 2;
1375
1376 /* Remove trailing "B" suffixes. */
1377 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1378
1379 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1380 len0 -= 1;
1381
1382 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1383
1384 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1385 {
1386 i = len0 - 2;
1387 while ((i >= 0 && isdigit (encoded[i]))
1388 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1389 i -= 1;
1390 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1391 len0 = i - 1;
1392 else if (encoded[i] == '$')
1393 len0 = i;
1394 }
1395
1396 /* The first few characters that are not alphabetic are not part
1397 of any encoding we use, so we can copy them over verbatim. */
1398
1399 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1400 decoded.push_back (encoded[i]);
1401
1402 at_start_name = 1;
1403 while (i < len0)
1404 {
1405 /* Is this a symbol function? */
1406 if (operators && at_start_name && encoded[i] == 'O')
1407 {
1408 int k;
1409
1410 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1411 {
1412 int op_len = strlen (ada_opname_table[k].encoded);
1413 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1414 op_len - 1) == 0)
1415 && !isalnum (encoded[i + op_len]))
1416 {
1417 decoded.append (ada_opname_table[k].decoded);
1418 at_start_name = 0;
1419 i += op_len;
1420 break;
1421 }
1422 }
1423 if (ada_opname_table[k].encoded != NULL)
1424 continue;
1425 }
1426 at_start_name = 0;
1427
1428 /* Replace "TK__" with "__", which will eventually be translated
1429 into "." (just below). */
1430
1431 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1432 i += 2;
1433
1434 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1435 be translated into "." (just below). These are internal names
1436 generated for anonymous blocks inside which our symbol is nested. */
1437
1438 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1439 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1440 && isdigit (encoded [i+4]))
1441 {
1442 int k = i + 5;
1443
1444 while (k < len0 && isdigit (encoded[k]))
1445 k++; /* Skip any extra digit. */
1446
1447 /* Double-check that the "__B_{DIGITS}+" sequence we found
1448 is indeed followed by "__". */
1449 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1450 i = k;
1451 }
1452
1453 /* Remove _E{DIGITS}+[sb] */
1454
1455 /* Just as for protected object subprograms, there are 2 categories
1456 of subprograms created by the compiler for each entry. The first
1457 one implements the actual entry code, and has a suffix following
1458 the convention above; the second one implements the barrier and
1459 uses the same convention as above, except that the 'E' is replaced
1460 by a 'B'.
1461
1462 Just as above, we do not decode the name of barrier functions
1463 to give the user a clue that the code he is debugging has been
1464 internally generated. */
1465
1466 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1467 && isdigit (encoded[i+2]))
1468 {
1469 int k = i + 3;
1470
1471 while (k < len0 && isdigit (encoded[k]))
1472 k++;
1473
1474 if (k < len0
1475 && (encoded[k] == 'b' || encoded[k] == 's'))
1476 {
1477 k++;
1478 /* Just as an extra precaution, make sure that if this
1479 suffix is followed by anything else, it is a '_'.
1480 Otherwise, we matched this sequence by accident. */
1481 if (k == len0
1482 || (k < len0 && encoded[k] == '_'))
1483 i = k;
1484 }
1485 }
1486
1487 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1488 the GNAT front-end in protected object subprograms. */
1489
1490 if (i < len0 + 3
1491 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1492 {
1493 /* Backtrack a bit up until we reach either the begining of
1494 the encoded name, or "__". Make sure that we only find
1495 digits or lowercase characters. */
1496 const char *ptr = encoded + i - 1;
1497
1498 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1499 ptr--;
1500 if (ptr < encoded
1501 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1502 i++;
1503 }
1504
1505 if (i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1506 {
1507 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1508 {
1509 i += 3;
1510 continue;
1511 }
1512 }
1513 else if (i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1514 {
1515 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1516 {
1517 i += 5;
1518 continue;
1519 }
1520 }
1521 else if (i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1522 && isxdigit (encoded[i + 2]))
1523 {
1524 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1525 {
1526 i += 10;
1527 continue;
1528 }
1529 }
1530
1531 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1532 {
1533 /* This is a X[bn]* sequence not separated from the previous
1534 part of the name with a non-alpha-numeric character (in other
1535 words, immediately following an alpha-numeric character), then
1536 verify that it is placed at the end of the encoded name. If
1537 not, then the encoding is not valid and we should abort the
1538 decoding. Otherwise, just skip it, it is used in body-nested
1539 package names. */
1540 do
1541 i += 1;
1542 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1543 if (i < len0)
1544 goto Suppress;
1545 }
1546 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1547 {
1548 /* Replace '__' by '.'. */
1549 decoded.push_back ('.');
1550 at_start_name = 1;
1551 i += 2;
1552 }
1553 else
1554 {
1555 /* It's a character part of the decoded name, so just copy it
1556 over. */
1557 decoded.push_back (encoded[i]);
1558 i += 1;
1559 }
1560 }
1561
1562 /* Decoded names should never contain any uppercase character.
1563 Double-check this, and abort the decoding if we find one. */
1564
1565 if (operators)
1566 {
1567 for (i = 0; i < decoded.length(); ++i)
1568 if (isupper (decoded[i]) || decoded[i] == ' ')
1569 goto Suppress;
1570 }
1571
1572 /* If the compiler added a suffix, append it now. */
1573 if (suffix >= 0)
1574 decoded = decoded + "[" + &encoded[suffix] + "]";
1575
1576 return decoded;
1577
1578 Suppress:
1579 if (!wrap)
1580 return {};
1581
1582 if (encoded[0] == '<')
1583 decoded = encoded;
1584 else
1585 decoded = '<' + std::string(encoded) + '>';
1586 return decoded;
1587 }
1588
1589 /* Table for keeping permanent unique copies of decoded names. Once
1590 allocated, names in this table are never released. While this is a
1591 storage leak, it should not be significant unless there are massive
1592 changes in the set of decoded names in successive versions of a
1593 symbol table loaded during a single session. */
1594 static struct htab *decoded_names_store;
1595
1596 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1597 in the language-specific part of GSYMBOL, if it has not been
1598 previously computed. Tries to save the decoded name in the same
1599 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1600 in any case, the decoded symbol has a lifetime at least that of
1601 GSYMBOL).
1602 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1603 const, but nevertheless modified to a semantically equivalent form
1604 when a decoded name is cached in it. */
1605
1606 const char *
1607 ada_decode_symbol (const struct general_symbol_info *arg)
1608 {
1609 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1610 const char **resultp =
1611 &gsymbol->language_specific.demangled_name;
1612
1613 if (!gsymbol->ada_mangled)
1614 {
1615 std::string decoded = ada_decode (gsymbol->linkage_name ());
1616 struct obstack *obstack = gsymbol->language_specific.obstack;
1617
1618 gsymbol->ada_mangled = 1;
1619
1620 if (obstack != NULL)
1621 *resultp = obstack_strdup (obstack, decoded.c_str ());
1622 else
1623 {
1624 /* Sometimes, we can't find a corresponding objfile, in
1625 which case, we put the result on the heap. Since we only
1626 decode when needed, we hope this usually does not cause a
1627 significant memory leak (FIXME). */
1628
1629 char **slot = (char **) htab_find_slot (decoded_names_store,
1630 decoded.c_str (), INSERT);
1631
1632 if (*slot == NULL)
1633 *slot = xstrdup (decoded.c_str ());
1634 *resultp = *slot;
1635 }
1636 }
1637
1638 return *resultp;
1639 }
1640
1641 \f
1642
1643 /* Arrays */
1644
1645 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1646 generated by the GNAT compiler to describe the index type used
1647 for each dimension of an array, check whether it follows the latest
1648 known encoding. If not, fix it up to conform to the latest encoding.
1649 Otherwise, do nothing. This function also does nothing if
1650 INDEX_DESC_TYPE is NULL.
1651
1652 The GNAT encoding used to describe the array index type evolved a bit.
1653 Initially, the information would be provided through the name of each
1654 field of the structure type only, while the type of these fields was
1655 described as unspecified and irrelevant. The debugger was then expected
1656 to perform a global type lookup using the name of that field in order
1657 to get access to the full index type description. Because these global
1658 lookups can be very expensive, the encoding was later enhanced to make
1659 the global lookup unnecessary by defining the field type as being
1660 the full index type description.
1661
1662 The purpose of this routine is to allow us to support older versions
1663 of the compiler by detecting the use of the older encoding, and by
1664 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1665 we essentially replace each field's meaningless type by the associated
1666 index subtype). */
1667
1668 void
1669 ada_fixup_array_indexes_type (struct type *index_desc_type)
1670 {
1671 int i;
1672
1673 if (index_desc_type == NULL)
1674 return;
1675 gdb_assert (index_desc_type->num_fields () > 0);
1676
1677 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1678 to check one field only, no need to check them all). If not, return
1679 now.
1680
1681 If our INDEX_DESC_TYPE was generated using the older encoding,
1682 the field type should be a meaningless integer type whose name
1683 is not equal to the field name. */
1684 if (index_desc_type->field (0).type ()->name () != NULL
1685 && strcmp (index_desc_type->field (0).type ()->name (),
1686 index_desc_type->field (0).name ()) == 0)
1687 return;
1688
1689 /* Fixup each field of INDEX_DESC_TYPE. */
1690 for (i = 0; i < index_desc_type->num_fields (); i++)
1691 {
1692 const char *name = index_desc_type->field (i).name ();
1693 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1694
1695 if (raw_type)
1696 index_desc_type->field (i).set_type (raw_type);
1697 }
1698 }
1699
1700 /* The desc_* routines return primitive portions of array descriptors
1701 (fat pointers). */
1702
1703 /* The descriptor or array type, if any, indicated by TYPE; removes
1704 level of indirection, if needed. */
1705
1706 static struct type *
1707 desc_base_type (struct type *type)
1708 {
1709 if (type == NULL)
1710 return NULL;
1711 type = ada_check_typedef (type);
1712 if (type->code () == TYPE_CODE_TYPEDEF)
1713 type = ada_typedef_target_type (type);
1714
1715 if (type != NULL
1716 && (type->code () == TYPE_CODE_PTR
1717 || type->code () == TYPE_CODE_REF))
1718 return ada_check_typedef (type->target_type ());
1719 else
1720 return type;
1721 }
1722
1723 /* True iff TYPE indicates a "thin" array pointer type. */
1724
1725 static int
1726 is_thin_pntr (struct type *type)
1727 {
1728 return
1729 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1730 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1731 }
1732
1733 /* The descriptor type for thin pointer type TYPE. */
1734
1735 static struct type *
1736 thin_descriptor_type (struct type *type)
1737 {
1738 struct type *base_type = desc_base_type (type);
1739
1740 if (base_type == NULL)
1741 return NULL;
1742 if (is_suffix (ada_type_name (base_type), "___XVE"))
1743 return base_type;
1744 else
1745 {
1746 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1747
1748 if (alt_type == NULL)
1749 return base_type;
1750 else
1751 return alt_type;
1752 }
1753 }
1754
1755 /* A pointer to the array data for thin-pointer value VAL. */
1756
1757 static struct value *
1758 thin_data_pntr (struct value *val)
1759 {
1760 struct type *type = ada_check_typedef (val->type ());
1761 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1762
1763 data_type = lookup_pointer_type (data_type);
1764
1765 if (type->code () == TYPE_CODE_PTR)
1766 return value_cast (data_type, val->copy ());
1767 else
1768 return value_from_longest (data_type, val->address ());
1769 }
1770
1771 /* True iff TYPE indicates a "thick" array pointer type. */
1772
1773 static int
1774 is_thick_pntr (struct type *type)
1775 {
1776 type = desc_base_type (type);
1777 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1778 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1779 }
1780
1781 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1782 pointer to one, the type of its bounds data; otherwise, NULL. */
1783
1784 static struct type *
1785 desc_bounds_type (struct type *type)
1786 {
1787 struct type *r;
1788
1789 type = desc_base_type (type);
1790
1791 if (type == NULL)
1792 return NULL;
1793 else if (is_thin_pntr (type))
1794 {
1795 type = thin_descriptor_type (type);
1796 if (type == NULL)
1797 return NULL;
1798 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1799 if (r != NULL)
1800 return ada_check_typedef (r);
1801 }
1802 else if (type->code () == TYPE_CODE_STRUCT)
1803 {
1804 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1805 if (r != NULL)
1806 return ada_check_typedef (ada_check_typedef (r)->target_type ());
1807 }
1808 return NULL;
1809 }
1810
1811 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1812 one, a pointer to its bounds data. Otherwise NULL. */
1813
1814 static struct value *
1815 desc_bounds (struct value *arr)
1816 {
1817 struct type *type = ada_check_typedef (arr->type ());
1818
1819 if (is_thin_pntr (type))
1820 {
1821 struct type *bounds_type =
1822 desc_bounds_type (thin_descriptor_type (type));
1823 LONGEST addr;
1824
1825 if (bounds_type == NULL)
1826 error (_("Bad GNAT array descriptor"));
1827
1828 /* NOTE: The following calculation is not really kosher, but
1829 since desc_type is an XVE-encoded type (and shouldn't be),
1830 the correct calculation is a real pain. FIXME (and fix GCC). */
1831 if (type->code () == TYPE_CODE_PTR)
1832 addr = value_as_long (arr);
1833 else
1834 addr = arr->address ();
1835
1836 return
1837 value_from_longest (lookup_pointer_type (bounds_type),
1838 addr - bounds_type->length ());
1839 }
1840
1841 else if (is_thick_pntr (type))
1842 {
1843 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1844 _("Bad GNAT array descriptor"));
1845 struct type *p_bounds_type = p_bounds->type ();
1846
1847 if (p_bounds_type
1848 && p_bounds_type->code () == TYPE_CODE_PTR)
1849 {
1850 struct type *target_type = p_bounds_type->target_type ();
1851
1852 if (target_type->is_stub ())
1853 p_bounds = value_cast (lookup_pointer_type
1854 (ada_check_typedef (target_type)),
1855 p_bounds);
1856 }
1857 else
1858 error (_("Bad GNAT array descriptor"));
1859
1860 return p_bounds;
1861 }
1862 else
1863 return NULL;
1864 }
1865
1866 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1867 position of the field containing the address of the bounds data. */
1868
1869 static int
1870 fat_pntr_bounds_bitpos (struct type *type)
1871 {
1872 return desc_base_type (type)->field (1).loc_bitpos ();
1873 }
1874
1875 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1876 size of the field containing the address of the bounds data. */
1877
1878 static int
1879 fat_pntr_bounds_bitsize (struct type *type)
1880 {
1881 type = desc_base_type (type);
1882
1883 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1884 return TYPE_FIELD_BITSIZE (type, 1);
1885 else
1886 return 8 * ada_check_typedef (type->field (1).type ())->length ();
1887 }
1888
1889 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1890 pointer to one, the type of its array data (a array-with-no-bounds type);
1891 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1892 data. */
1893
1894 static struct type *
1895 desc_data_target_type (struct type *type)
1896 {
1897 type = desc_base_type (type);
1898
1899 /* NOTE: The following is bogus; see comment in desc_bounds. */
1900 if (is_thin_pntr (type))
1901 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1902 else if (is_thick_pntr (type))
1903 {
1904 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1905
1906 if (data_type
1907 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1908 return ada_check_typedef (data_type->target_type ());
1909 }
1910
1911 return NULL;
1912 }
1913
1914 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1915 its array data. */
1916
1917 static struct value *
1918 desc_data (struct value *arr)
1919 {
1920 struct type *type = arr->type ();
1921
1922 if (is_thin_pntr (type))
1923 return thin_data_pntr (arr);
1924 else if (is_thick_pntr (type))
1925 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1926 _("Bad GNAT array descriptor"));
1927 else
1928 return NULL;
1929 }
1930
1931
1932 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1933 position of the field containing the address of the data. */
1934
1935 static int
1936 fat_pntr_data_bitpos (struct type *type)
1937 {
1938 return desc_base_type (type)->field (0).loc_bitpos ();
1939 }
1940
1941 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1942 size of the field containing the address of the data. */
1943
1944 static int
1945 fat_pntr_data_bitsize (struct type *type)
1946 {
1947 type = desc_base_type (type);
1948
1949 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1950 return TYPE_FIELD_BITSIZE (type, 0);
1951 else
1952 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
1953 }
1954
1955 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1956 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1957 bound, if WHICH is 1. The first bound is I=1. */
1958
1959 static struct value *
1960 desc_one_bound (struct value *bounds, int i, int which)
1961 {
1962 char bound_name[20];
1963 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1964 which ? 'U' : 'L', i - 1);
1965 return value_struct_elt (&bounds, {}, bound_name, NULL,
1966 _("Bad GNAT array descriptor bounds"));
1967 }
1968
1969 /* If BOUNDS is an array-bounds structure type, return the bit position
1970 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1971 bound, if WHICH is 1. The first bound is I=1. */
1972
1973 static int
1974 desc_bound_bitpos (struct type *type, int i, int which)
1975 {
1976 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1977 }
1978
1979 /* If BOUNDS is an array-bounds structure type, return the bit field size
1980 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1981 bound, if WHICH is 1. The first bound is I=1. */
1982
1983 static int
1984 desc_bound_bitsize (struct type *type, int i, int which)
1985 {
1986 type = desc_base_type (type);
1987
1988 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1989 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1990 else
1991 return 8 * type->field (2 * i + which - 2).type ()->length ();
1992 }
1993
1994 /* If TYPE is the type of an array-bounds structure, the type of its
1995 Ith bound (numbering from 1). Otherwise, NULL. */
1996
1997 static struct type *
1998 desc_index_type (struct type *type, int i)
1999 {
2000 type = desc_base_type (type);
2001
2002 if (type->code () == TYPE_CODE_STRUCT)
2003 {
2004 char bound_name[20];
2005 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2006 return lookup_struct_elt_type (type, bound_name, 1);
2007 }
2008 else
2009 return NULL;
2010 }
2011
2012 /* The number of index positions in the array-bounds type TYPE.
2013 Return 0 if TYPE is NULL. */
2014
2015 static int
2016 desc_arity (struct type *type)
2017 {
2018 type = desc_base_type (type);
2019
2020 if (type != NULL)
2021 return type->num_fields () / 2;
2022 return 0;
2023 }
2024
2025 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2026 an array descriptor type (representing an unconstrained array
2027 type). */
2028
2029 static int
2030 ada_is_direct_array_type (struct type *type)
2031 {
2032 if (type == NULL)
2033 return 0;
2034 type = ada_check_typedef (type);
2035 return (type->code () == TYPE_CODE_ARRAY
2036 || ada_is_array_descriptor_type (type));
2037 }
2038
2039 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
2040 * to one. */
2041
2042 static int
2043 ada_is_array_type (struct type *type)
2044 {
2045 while (type != NULL
2046 && (type->code () == TYPE_CODE_PTR
2047 || type->code () == TYPE_CODE_REF))
2048 type = type->target_type ();
2049 return ada_is_direct_array_type (type);
2050 }
2051
2052 /* Non-zero iff TYPE is a simple array type or pointer to one. */
2053
2054 int
2055 ada_is_simple_array_type (struct type *type)
2056 {
2057 if (type == NULL)
2058 return 0;
2059 type = ada_check_typedef (type);
2060 return (type->code () == TYPE_CODE_ARRAY
2061 || (type->code () == TYPE_CODE_PTR
2062 && (ada_check_typedef (type->target_type ())->code ()
2063 == TYPE_CODE_ARRAY)));
2064 }
2065
2066 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2067
2068 int
2069 ada_is_array_descriptor_type (struct type *type)
2070 {
2071 struct type *data_type = desc_data_target_type (type);
2072
2073 if (type == NULL)
2074 return 0;
2075 type = ada_check_typedef (type);
2076 return (data_type != NULL
2077 && data_type->code () == TYPE_CODE_ARRAY
2078 && desc_arity (desc_bounds_type (type)) > 0);
2079 }
2080
2081 /* Non-zero iff type is a partially mal-formed GNAT array
2082 descriptor. FIXME: This is to compensate for some problems with
2083 debugging output from GNAT. Re-examine periodically to see if it
2084 is still needed. */
2085
2086 int
2087 ada_is_bogus_array_descriptor (struct type *type)
2088 {
2089 return
2090 type != NULL
2091 && type->code () == TYPE_CODE_STRUCT
2092 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
2093 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
2094 && !ada_is_array_descriptor_type (type);
2095 }
2096
2097
2098 /* If ARR has a record type in the form of a standard GNAT array descriptor,
2099 (fat pointer) returns the type of the array data described---specifically,
2100 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
2101 in from the descriptor; otherwise, they are left unspecified. If
2102 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2103 returns NULL. The result is simply the type of ARR if ARR is not
2104 a descriptor. */
2105
2106 static struct type *
2107 ada_type_of_array (struct value *arr, int bounds)
2108 {
2109 if (ada_is_constrained_packed_array_type (arr->type ()))
2110 return decode_constrained_packed_array_type (arr->type ());
2111
2112 if (!ada_is_array_descriptor_type (arr->type ()))
2113 return arr->type ();
2114
2115 if (!bounds)
2116 {
2117 struct type *array_type =
2118 ada_check_typedef (desc_data_target_type (arr->type ()));
2119
2120 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2121 TYPE_FIELD_BITSIZE (array_type, 0) =
2122 decode_packed_array_bitsize (arr->type ());
2123
2124 return array_type;
2125 }
2126 else
2127 {
2128 struct type *elt_type;
2129 int arity;
2130 struct value *descriptor;
2131
2132 elt_type = ada_array_element_type (arr->type (), -1);
2133 arity = ada_array_arity (arr->type ());
2134
2135 if (elt_type == NULL || arity == 0)
2136 return ada_check_typedef (arr->type ());
2137
2138 descriptor = desc_bounds (arr);
2139 if (value_as_long (descriptor) == 0)
2140 return NULL;
2141 while (arity > 0)
2142 {
2143 type_allocator alloc (arr->type ());
2144 struct value *low = desc_one_bound (descriptor, arity, 0);
2145 struct value *high = desc_one_bound (descriptor, arity, 1);
2146
2147 arity -= 1;
2148 struct type *range_type
2149 = create_static_range_type (alloc, low->type (),
2150 longest_to_int (value_as_long (low)),
2151 longest_to_int (value_as_long (high)));
2152 elt_type = create_array_type (alloc, elt_type, range_type);
2153
2154 if (ada_is_unconstrained_packed_array_type (arr->type ()))
2155 {
2156 /* We need to store the element packed bitsize, as well as
2157 recompute the array size, because it was previously
2158 computed based on the unpacked element size. */
2159 LONGEST lo = value_as_long (low);
2160 LONGEST hi = value_as_long (high);
2161
2162 TYPE_FIELD_BITSIZE (elt_type, 0) =
2163 decode_packed_array_bitsize (arr->type ());
2164 /* If the array has no element, then the size is already
2165 zero, and does not need to be recomputed. */
2166 if (lo < hi)
2167 {
2168 int array_bitsize =
2169 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
2170
2171 elt_type->set_length ((array_bitsize + 7) / 8);
2172 }
2173 }
2174 }
2175
2176 return lookup_pointer_type (elt_type);
2177 }
2178 }
2179
2180 /* If ARR does not represent an array, returns ARR unchanged.
2181 Otherwise, returns either a standard GDB array with bounds set
2182 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2183 GDB array. Returns NULL if ARR is a null fat pointer. */
2184
2185 struct value *
2186 ada_coerce_to_simple_array_ptr (struct value *arr)
2187 {
2188 if (ada_is_array_descriptor_type (arr->type ()))
2189 {
2190 struct type *arrType = ada_type_of_array (arr, 1);
2191
2192 if (arrType == NULL)
2193 return NULL;
2194 return value_cast (arrType, desc_data (arr)->copy ());
2195 }
2196 else if (ada_is_constrained_packed_array_type (arr->type ()))
2197 return decode_constrained_packed_array (arr);
2198 else
2199 return arr;
2200 }
2201
2202 /* If ARR does not represent an array, returns ARR unchanged.
2203 Otherwise, returns a standard GDB array describing ARR (which may
2204 be ARR itself if it already is in the proper form). */
2205
2206 struct value *
2207 ada_coerce_to_simple_array (struct value *arr)
2208 {
2209 if (ada_is_array_descriptor_type (arr->type ()))
2210 {
2211 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2212
2213 if (arrVal == NULL)
2214 error (_("Bounds unavailable for null array pointer."));
2215 return value_ind (arrVal);
2216 }
2217 else if (ada_is_constrained_packed_array_type (arr->type ()))
2218 return decode_constrained_packed_array (arr);
2219 else
2220 return arr;
2221 }
2222
2223 /* If TYPE represents a GNAT array type, return it translated to an
2224 ordinary GDB array type (possibly with BITSIZE fields indicating
2225 packing). For other types, is the identity. */
2226
2227 struct type *
2228 ada_coerce_to_simple_array_type (struct type *type)
2229 {
2230 if (ada_is_constrained_packed_array_type (type))
2231 return decode_constrained_packed_array_type (type);
2232
2233 if (ada_is_array_descriptor_type (type))
2234 return ada_check_typedef (desc_data_target_type (type));
2235
2236 return type;
2237 }
2238
2239 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2240
2241 static int
2242 ada_is_gnat_encoded_packed_array_type (struct type *type)
2243 {
2244 if (type == NULL)
2245 return 0;
2246 type = desc_base_type (type);
2247 type = ada_check_typedef (type);
2248 return
2249 ada_type_name (type) != NULL
2250 && strstr (ada_type_name (type), "___XP") != NULL;
2251 }
2252
2253 /* Non-zero iff TYPE represents a standard GNAT constrained
2254 packed-array type. */
2255
2256 int
2257 ada_is_constrained_packed_array_type (struct type *type)
2258 {
2259 return ada_is_gnat_encoded_packed_array_type (type)
2260 && !ada_is_array_descriptor_type (type);
2261 }
2262
2263 /* Non-zero iff TYPE represents an array descriptor for a
2264 unconstrained packed-array type. */
2265
2266 static int
2267 ada_is_unconstrained_packed_array_type (struct type *type)
2268 {
2269 if (!ada_is_array_descriptor_type (type))
2270 return 0;
2271
2272 if (ada_is_gnat_encoded_packed_array_type (type))
2273 return 1;
2274
2275 /* If we saw GNAT encodings, then the above code is sufficient.
2276 However, with minimal encodings, we will just have a thick
2277 pointer instead. */
2278 if (is_thick_pntr (type))
2279 {
2280 type = desc_base_type (type);
2281 /* The structure's first field is a pointer to an array, so this
2282 fetches the array type. */
2283 type = type->field (0).type ()->target_type ();
2284 if (type->code () == TYPE_CODE_TYPEDEF)
2285 type = ada_typedef_target_type (type);
2286 /* Now we can see if the array elements are packed. */
2287 return TYPE_FIELD_BITSIZE (type, 0) > 0;
2288 }
2289
2290 return 0;
2291 }
2292
2293 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
2294 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2295
2296 static bool
2297 ada_is_any_packed_array_type (struct type *type)
2298 {
2299 return (ada_is_constrained_packed_array_type (type)
2300 || (type->code () == TYPE_CODE_ARRAY
2301 && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
2302 }
2303
2304 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2305 return the size of its elements in bits. */
2306
2307 static long
2308 decode_packed_array_bitsize (struct type *type)
2309 {
2310 const char *raw_name;
2311 const char *tail;
2312 long bits;
2313
2314 /* Access to arrays implemented as fat pointers are encoded as a typedef
2315 of the fat pointer type. We need the name of the fat pointer type
2316 to do the decoding, so strip the typedef layer. */
2317 if (type->code () == TYPE_CODE_TYPEDEF)
2318 type = ada_typedef_target_type (type);
2319
2320 raw_name = ada_type_name (ada_check_typedef (type));
2321 if (!raw_name)
2322 raw_name = ada_type_name (desc_base_type (type));
2323
2324 if (!raw_name)
2325 return 0;
2326
2327 tail = strstr (raw_name, "___XP");
2328 if (tail == nullptr)
2329 {
2330 gdb_assert (is_thick_pntr (type));
2331 /* The structure's first field is a pointer to an array, so this
2332 fetches the array type. */
2333 type = type->field (0).type ()->target_type ();
2334 /* Now we can see if the array elements are packed. */
2335 return TYPE_FIELD_BITSIZE (type, 0);
2336 }
2337
2338 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2339 {
2340 lim_warning
2341 (_("could not understand bit size information on packed array"));
2342 return 0;
2343 }
2344
2345 return bits;
2346 }
2347
2348 /* Given that TYPE is a standard GDB array type with all bounds filled
2349 in, and that the element size of its ultimate scalar constituents
2350 (that is, either its elements, or, if it is an array of arrays, its
2351 elements' elements, etc.) is *ELT_BITS, return an identical type,
2352 but with the bit sizes of its elements (and those of any
2353 constituent arrays) recorded in the BITSIZE components of its
2354 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2355 in bits.
2356
2357 Note that, for arrays whose index type has an XA encoding where
2358 a bound references a record discriminant, getting that discriminant,
2359 and therefore the actual value of that bound, is not possible
2360 because none of the given parameters gives us access to the record.
2361 This function assumes that it is OK in the context where it is being
2362 used to return an array whose bounds are still dynamic and where
2363 the length is arbitrary. */
2364
2365 static struct type *
2366 constrained_packed_array_type (struct type *type, long *elt_bits)
2367 {
2368 struct type *new_elt_type;
2369 struct type *new_type;
2370 struct type *index_type_desc;
2371 struct type *index_type;
2372 LONGEST low_bound, high_bound;
2373
2374 type = ada_check_typedef (type);
2375 if (type->code () != TYPE_CODE_ARRAY)
2376 return type;
2377
2378 index_type_desc = ada_find_parallel_type (type, "___XA");
2379 if (index_type_desc)
2380 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2381 NULL);
2382 else
2383 index_type = type->index_type ();
2384
2385 type_allocator alloc (type);
2386 new_elt_type =
2387 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
2388 elt_bits);
2389 new_type = create_array_type (alloc, new_elt_type, index_type);
2390 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2391 new_type->set_name (ada_type_name (type));
2392
2393 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2394 && is_dynamic_type (check_typedef (index_type)))
2395 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2396 low_bound = high_bound = 0;
2397 if (high_bound < low_bound)
2398 {
2399 *elt_bits = 0;
2400 new_type->set_length (0);
2401 }
2402 else
2403 {
2404 *elt_bits *= (high_bound - low_bound + 1);
2405 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
2406 }
2407
2408 new_type->set_is_fixed_instance (true);
2409 return new_type;
2410 }
2411
2412 /* The array type encoded by TYPE, where
2413 ada_is_constrained_packed_array_type (TYPE). */
2414
2415 static struct type *
2416 decode_constrained_packed_array_type (struct type *type)
2417 {
2418 const char *raw_name = ada_type_name (ada_check_typedef (type));
2419 char *name;
2420 const char *tail;
2421 struct type *shadow_type;
2422 long bits;
2423
2424 if (!raw_name)
2425 raw_name = ada_type_name (desc_base_type (type));
2426
2427 if (!raw_name)
2428 return NULL;
2429
2430 name = (char *) alloca (strlen (raw_name) + 1);
2431 tail = strstr (raw_name, "___XP");
2432 type = desc_base_type (type);
2433
2434 memcpy (name, raw_name, tail - raw_name);
2435 name[tail - raw_name] = '\000';
2436
2437 shadow_type = ada_find_parallel_type_with_name (type, name);
2438
2439 if (shadow_type == NULL)
2440 {
2441 lim_warning (_("could not find bounds information on packed array"));
2442 return NULL;
2443 }
2444 shadow_type = check_typedef (shadow_type);
2445
2446 if (shadow_type->code () != TYPE_CODE_ARRAY)
2447 {
2448 lim_warning (_("could not understand bounds "
2449 "information on packed array"));
2450 return NULL;
2451 }
2452
2453 bits = decode_packed_array_bitsize (type);
2454 return constrained_packed_array_type (shadow_type, &bits);
2455 }
2456
2457 /* Helper function for decode_constrained_packed_array. Set the field
2458 bitsize on a series of packed arrays. Returns the number of
2459 elements in TYPE. */
2460
2461 static LONGEST
2462 recursively_update_array_bitsize (struct type *type)
2463 {
2464 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2465
2466 LONGEST low, high;
2467 if (!get_discrete_bounds (type->index_type (), &low, &high)
2468 || low > high)
2469 return 0;
2470 LONGEST our_len = high - low + 1;
2471
2472 struct type *elt_type = type->target_type ();
2473 if (elt_type->code () == TYPE_CODE_ARRAY)
2474 {
2475 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2476 LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2477 TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2478
2479 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2480 / HOST_CHAR_BIT));
2481 }
2482
2483 return our_len;
2484 }
2485
2486 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2487 array, returns a simple array that denotes that array. Its type is a
2488 standard GDB array type except that the BITSIZEs of the array
2489 target types are set to the number of bits in each element, and the
2490 type length is set appropriately. */
2491
2492 static struct value *
2493 decode_constrained_packed_array (struct value *arr)
2494 {
2495 struct type *type;
2496
2497 /* If our value is a pointer, then dereference it. Likewise if
2498 the value is a reference. Make sure that this operation does not
2499 cause the target type to be fixed, as this would indirectly cause
2500 this array to be decoded. The rest of the routine assumes that
2501 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2502 and "value_ind" routines to perform the dereferencing, as opposed
2503 to using "ada_coerce_ref" or "ada_value_ind". */
2504 arr = coerce_ref (arr);
2505 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
2506 arr = value_ind (arr);
2507
2508 type = decode_constrained_packed_array_type (arr->type ());
2509 if (type == NULL)
2510 {
2511 error (_("can't unpack array"));
2512 return NULL;
2513 }
2514
2515 /* Decoding the packed array type could not correctly set the field
2516 bitsizes for any dimension except the innermost, because the
2517 bounds may be variable and were not passed to that function. So,
2518 we further resolve the array bounds here and then update the
2519 sizes. */
2520 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
2521 CORE_ADDR address = arr->address ();
2522 gdb::array_view<const gdb_byte> view
2523 = gdb::make_array_view (valaddr, type->length ());
2524 type = resolve_dynamic_type (type, view, address);
2525 recursively_update_array_bitsize (type);
2526
2527 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2528 && ada_is_modular_type (arr->type ()))
2529 {
2530 /* This is a (right-justified) modular type representing a packed
2531 array with no wrapper. In order to interpret the value through
2532 the (left-justified) packed array type we just built, we must
2533 first left-justify it. */
2534 int bit_size, bit_pos;
2535 ULONGEST mod;
2536
2537 mod = ada_modulus (arr->type ()) - 1;
2538 bit_size = 0;
2539 while (mod > 0)
2540 {
2541 bit_size += 1;
2542 mod >>= 1;
2543 }
2544 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
2545 arr = ada_value_primitive_packed_val (arr, NULL,
2546 bit_pos / HOST_CHAR_BIT,
2547 bit_pos % HOST_CHAR_BIT,
2548 bit_size,
2549 type);
2550 }
2551
2552 return coerce_unspec_val_to_type (arr, type);
2553 }
2554
2555
2556 /* The value of the element of packed array ARR at the ARITY indices
2557 given in IND. ARR must be a simple array. */
2558
2559 static struct value *
2560 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2561 {
2562 int i;
2563 int bits, elt_off, bit_off;
2564 long elt_total_bit_offset;
2565 struct type *elt_type;
2566 struct value *v;
2567
2568 bits = 0;
2569 elt_total_bit_offset = 0;
2570 elt_type = ada_check_typedef (arr->type ());
2571 for (i = 0; i < arity; i += 1)
2572 {
2573 if (elt_type->code () != TYPE_CODE_ARRAY
2574 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2575 error
2576 (_("attempt to do packed indexing of "
2577 "something other than a packed array"));
2578 else
2579 {
2580 struct type *range_type = elt_type->index_type ();
2581 LONGEST lowerbound, upperbound;
2582 LONGEST idx;
2583
2584 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2585 {
2586 lim_warning (_("don't know bounds of array"));
2587 lowerbound = upperbound = 0;
2588 }
2589
2590 idx = pos_atr (ind[i]);
2591 if (idx < lowerbound || idx > upperbound)
2592 lim_warning (_("packed array index %ld out of bounds"),
2593 (long) idx);
2594 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2595 elt_total_bit_offset += (idx - lowerbound) * bits;
2596 elt_type = ada_check_typedef (elt_type->target_type ());
2597 }
2598 }
2599 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2600 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2601
2602 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2603 bits, elt_type);
2604 return v;
2605 }
2606
2607 /* Non-zero iff TYPE includes negative integer values. */
2608
2609 static int
2610 has_negatives (struct type *type)
2611 {
2612 switch (type->code ())
2613 {
2614 default:
2615 return 0;
2616 case TYPE_CODE_INT:
2617 return !type->is_unsigned ();
2618 case TYPE_CODE_RANGE:
2619 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2620 }
2621 }
2622
2623 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2624 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2625 the unpacked buffer.
2626
2627 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2628 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2629
2630 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2631 zero otherwise.
2632
2633 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2634
2635 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2636
2637 static void
2638 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2639 gdb_byte *unpacked, int unpacked_len,
2640 int is_big_endian, int is_signed_type,
2641 int is_scalar)
2642 {
2643 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2644 int src_idx; /* Index into the source area */
2645 int src_bytes_left; /* Number of source bytes left to process. */
2646 int srcBitsLeft; /* Number of source bits left to move */
2647 int unusedLS; /* Number of bits in next significant
2648 byte of source that are unused */
2649
2650 int unpacked_idx; /* Index into the unpacked buffer */
2651 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2652
2653 unsigned long accum; /* Staging area for bits being transferred */
2654 int accumSize; /* Number of meaningful bits in accum */
2655 unsigned char sign;
2656
2657 /* Transmit bytes from least to most significant; delta is the direction
2658 the indices move. */
2659 int delta = is_big_endian ? -1 : 1;
2660
2661 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2662 bits from SRC. .*/
2663 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2664 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2665 bit_size, unpacked_len);
2666
2667 srcBitsLeft = bit_size;
2668 src_bytes_left = src_len;
2669 unpacked_bytes_left = unpacked_len;
2670 sign = 0;
2671
2672 if (is_big_endian)
2673 {
2674 src_idx = src_len - 1;
2675 if (is_signed_type
2676 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2677 sign = ~0;
2678
2679 unusedLS =
2680 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2681 % HOST_CHAR_BIT;
2682
2683 if (is_scalar)
2684 {
2685 accumSize = 0;
2686 unpacked_idx = unpacked_len - 1;
2687 }
2688 else
2689 {
2690 /* Non-scalar values must be aligned at a byte boundary... */
2691 accumSize =
2692 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2693 /* ... And are placed at the beginning (most-significant) bytes
2694 of the target. */
2695 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2696 unpacked_bytes_left = unpacked_idx + 1;
2697 }
2698 }
2699 else
2700 {
2701 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2702
2703 src_idx = unpacked_idx = 0;
2704 unusedLS = bit_offset;
2705 accumSize = 0;
2706
2707 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2708 sign = ~0;
2709 }
2710
2711 accum = 0;
2712 while (src_bytes_left > 0)
2713 {
2714 /* Mask for removing bits of the next source byte that are not
2715 part of the value. */
2716 unsigned int unusedMSMask =
2717 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2718 1;
2719 /* Sign-extend bits for this byte. */
2720 unsigned int signMask = sign & ~unusedMSMask;
2721
2722 accum |=
2723 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2724 accumSize += HOST_CHAR_BIT - unusedLS;
2725 if (accumSize >= HOST_CHAR_BIT)
2726 {
2727 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2728 accumSize -= HOST_CHAR_BIT;
2729 accum >>= HOST_CHAR_BIT;
2730 unpacked_bytes_left -= 1;
2731 unpacked_idx += delta;
2732 }
2733 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2734 unusedLS = 0;
2735 src_bytes_left -= 1;
2736 src_idx += delta;
2737 }
2738 while (unpacked_bytes_left > 0)
2739 {
2740 accum |= sign << accumSize;
2741 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2742 accumSize -= HOST_CHAR_BIT;
2743 if (accumSize < 0)
2744 accumSize = 0;
2745 accum >>= HOST_CHAR_BIT;
2746 unpacked_bytes_left -= 1;
2747 unpacked_idx += delta;
2748 }
2749 }
2750
2751 /* Create a new value of type TYPE from the contents of OBJ starting
2752 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2753 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2754 assigning through the result will set the field fetched from.
2755 VALADDR is ignored unless OBJ is NULL, in which case,
2756 VALADDR+OFFSET must address the start of storage containing the
2757 packed value. The value returned in this case is never an lval.
2758 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2759
2760 struct value *
2761 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2762 long offset, int bit_offset, int bit_size,
2763 struct type *type)
2764 {
2765 struct value *v;
2766 const gdb_byte *src; /* First byte containing data to unpack */
2767 gdb_byte *unpacked;
2768 const int is_scalar = is_scalar_type (type);
2769 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2770 gdb::byte_vector staging;
2771
2772 type = ada_check_typedef (type);
2773
2774 if (obj == NULL)
2775 src = valaddr + offset;
2776 else
2777 src = obj->contents ().data () + offset;
2778
2779 if (is_dynamic_type (type))
2780 {
2781 /* The length of TYPE might by dynamic, so we need to resolve
2782 TYPE in order to know its actual size, which we then use
2783 to create the contents buffer of the value we return.
2784 The difficulty is that the data containing our object is
2785 packed, and therefore maybe not at a byte boundary. So, what
2786 we do, is unpack the data into a byte-aligned buffer, and then
2787 use that buffer as our object's value for resolving the type. */
2788 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2789 staging.resize (staging_len);
2790
2791 ada_unpack_from_contents (src, bit_offset, bit_size,
2792 staging.data (), staging.size (),
2793 is_big_endian, has_negatives (type),
2794 is_scalar);
2795 type = resolve_dynamic_type (type, staging, 0);
2796 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2797 {
2798 /* This happens when the length of the object is dynamic,
2799 and is actually smaller than the space reserved for it.
2800 For instance, in an array of variant records, the bit_size
2801 we're given is the array stride, which is constant and
2802 normally equal to the maximum size of its element.
2803 But, in reality, each element only actually spans a portion
2804 of that stride. */
2805 bit_size = type->length () * HOST_CHAR_BIT;
2806 }
2807 }
2808
2809 if (obj == NULL)
2810 {
2811 v = value::allocate (type);
2812 src = valaddr + offset;
2813 }
2814 else if (obj->lval () == lval_memory && obj->lazy ())
2815 {
2816 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2817 gdb_byte *buf;
2818
2819 v = value_at (type, obj->address () + offset);
2820 buf = (gdb_byte *) alloca (src_len);
2821 read_memory (v->address (), buf, src_len);
2822 src = buf;
2823 }
2824 else
2825 {
2826 v = value::allocate (type);
2827 src = obj->contents ().data () + offset;
2828 }
2829
2830 if (obj != NULL)
2831 {
2832 long new_offset = offset;
2833
2834 v->set_component_location (obj);
2835 v->set_bitpos (bit_offset + obj->bitpos ());
2836 v->set_bitsize (bit_size);
2837 if (v->bitpos () >= HOST_CHAR_BIT)
2838 {
2839 ++new_offset;
2840 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
2841 }
2842 v->set_offset (new_offset);
2843
2844 /* Also set the parent value. This is needed when trying to
2845 assign a new value (in inferior memory). */
2846 v->set_parent (obj);
2847 }
2848 else
2849 v->set_bitsize (bit_size);
2850 unpacked = v->contents_writeable ().data ();
2851
2852 if (bit_size == 0)
2853 {
2854 memset (unpacked, 0, type->length ());
2855 return v;
2856 }
2857
2858 if (staging.size () == type->length ())
2859 {
2860 /* Small short-cut: If we've unpacked the data into a buffer
2861 of the same size as TYPE's length, then we can reuse that,
2862 instead of doing the unpacking again. */
2863 memcpy (unpacked, staging.data (), staging.size ());
2864 }
2865 else
2866 ada_unpack_from_contents (src, bit_offset, bit_size,
2867 unpacked, type->length (),
2868 is_big_endian, has_negatives (type), is_scalar);
2869
2870 return v;
2871 }
2872
2873 /* Store the contents of FROMVAL into the location of TOVAL.
2874 Return a new value with the location of TOVAL and contents of
2875 FROMVAL. Handles assignment into packed fields that have
2876 floating-point or non-scalar types. */
2877
2878 static struct value *
2879 ada_value_assign (struct value *toval, struct value *fromval)
2880 {
2881 struct type *type = toval->type ();
2882 int bits = toval->bitsize ();
2883
2884 toval = ada_coerce_ref (toval);
2885 fromval = ada_coerce_ref (fromval);
2886
2887 if (ada_is_direct_array_type (toval->type ()))
2888 toval = ada_coerce_to_simple_array (toval);
2889 if (ada_is_direct_array_type (fromval->type ()))
2890 fromval = ada_coerce_to_simple_array (fromval);
2891
2892 if (!toval->deprecated_modifiable ())
2893 error (_("Left operand of assignment is not a modifiable lvalue."));
2894
2895 if (toval->lval () == lval_memory
2896 && bits > 0
2897 && (type->code () == TYPE_CODE_FLT
2898 || type->code () == TYPE_CODE_STRUCT))
2899 {
2900 int len = (toval->bitpos ()
2901 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2902 int from_size;
2903 gdb_byte *buffer = (gdb_byte *) alloca (len);
2904 struct value *val;
2905 CORE_ADDR to_addr = toval->address ();
2906
2907 if (type->code () == TYPE_CODE_FLT)
2908 fromval = value_cast (type, fromval);
2909
2910 read_memory (to_addr, buffer, len);
2911 from_size = fromval->bitsize ();
2912 if (from_size == 0)
2913 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
2914
2915 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2916 ULONGEST from_offset = 0;
2917 if (is_big_endian && is_scalar_type (fromval->type ()))
2918 from_offset = from_size - bits;
2919 copy_bitwise (buffer, toval->bitpos (),
2920 fromval->contents ().data (), from_offset,
2921 bits, is_big_endian);
2922 write_memory_with_notification (to_addr, buffer, len);
2923
2924 val = toval->copy ();
2925 memcpy (val->contents_raw ().data (),
2926 fromval->contents ().data (),
2927 type->length ());
2928 val->deprecated_set_type (type);
2929
2930 return val;
2931 }
2932
2933 return value_assign (toval, fromval);
2934 }
2935
2936
2937 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2938 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2939 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2940 COMPONENT, and not the inferior's memory. The current contents
2941 of COMPONENT are ignored.
2942
2943 Although not part of the initial design, this function also works
2944 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2945 had a null address, and COMPONENT had an address which is equal to
2946 its offset inside CONTAINER. */
2947
2948 static void
2949 value_assign_to_component (struct value *container, struct value *component,
2950 struct value *val)
2951 {
2952 LONGEST offset_in_container =
2953 (LONGEST) (component->address () - container->address ());
2954 int bit_offset_in_container =
2955 component->bitpos () - container->bitpos ();
2956 int bits;
2957
2958 val = value_cast (component->type (), val);
2959
2960 if (component->bitsize () == 0)
2961 bits = TARGET_CHAR_BIT * component->type ()->length ();
2962 else
2963 bits = component->bitsize ();
2964
2965 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2966 {
2967 int src_offset;
2968
2969 if (is_scalar_type (check_typedef (component->type ())))
2970 src_offset
2971 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2972 else
2973 src_offset = 0;
2974 copy_bitwise ((container->contents_writeable ().data ()
2975 + offset_in_container),
2976 container->bitpos () + bit_offset_in_container,
2977 val->contents ().data (), src_offset, bits, 1);
2978 }
2979 else
2980 copy_bitwise ((container->contents_writeable ().data ()
2981 + offset_in_container),
2982 container->bitpos () + bit_offset_in_container,
2983 val->contents ().data (), 0, bits, 0);
2984 }
2985
2986 /* Determine if TYPE is an access to an unconstrained array. */
2987
2988 bool
2989 ada_is_access_to_unconstrained_array (struct type *type)
2990 {
2991 return (type->code () == TYPE_CODE_TYPEDEF
2992 && is_thick_pntr (ada_typedef_target_type (type)));
2993 }
2994
2995 /* The value of the element of array ARR at the ARITY indices given in IND.
2996 ARR may be either a simple array, GNAT array descriptor, or pointer
2997 thereto. */
2998
2999 struct value *
3000 ada_value_subscript (struct value *arr, int arity, struct value **ind)
3001 {
3002 int k;
3003 struct value *elt;
3004 struct type *elt_type;
3005
3006 elt = ada_coerce_to_simple_array (arr);
3007
3008 elt_type = ada_check_typedef (elt->type ());
3009 if (elt_type->code () == TYPE_CODE_ARRAY
3010 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
3011 return value_subscript_packed (elt, arity, ind);
3012
3013 for (k = 0; k < arity; k += 1)
3014 {
3015 struct type *saved_elt_type = elt_type->target_type ();
3016
3017 if (elt_type->code () != TYPE_CODE_ARRAY)
3018 error (_("too many subscripts (%d expected)"), k);
3019
3020 elt = value_subscript (elt, pos_atr (ind[k]));
3021
3022 if (ada_is_access_to_unconstrained_array (saved_elt_type)
3023 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
3024 {
3025 /* The element is a typedef to an unconstrained array,
3026 except that the value_subscript call stripped the
3027 typedef layer. The typedef layer is GNAT's way to
3028 specify that the element is, at the source level, an
3029 access to the unconstrained array, rather than the
3030 unconstrained array. So, we need to restore that
3031 typedef layer, which we can do by forcing the element's
3032 type back to its original type. Otherwise, the returned
3033 value is going to be printed as the array, rather
3034 than as an access. Another symptom of the same issue
3035 would be that an expression trying to dereference the
3036 element would also be improperly rejected. */
3037 elt->deprecated_set_type (saved_elt_type);
3038 }
3039
3040 elt_type = ada_check_typedef (elt->type ());
3041 }
3042
3043 return elt;
3044 }
3045
3046 /* Assuming ARR is a pointer to a GDB array, the value of the element
3047 of *ARR at the ARITY indices given in IND.
3048 Does not read the entire array into memory.
3049
3050 Note: Unlike what one would expect, this function is used instead of
3051 ada_value_subscript for basically all non-packed array types. The reason
3052 for this is that a side effect of doing our own pointer arithmetics instead
3053 of relying on value_subscript is that there is no implicit typedef peeling.
3054 This is important for arrays of array accesses, where it allows us to
3055 preserve the fact that the array's element is an array access, where the
3056 access part os encoded in a typedef layer. */
3057
3058 static struct value *
3059 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
3060 {
3061 int k;
3062 struct value *array_ind = ada_value_ind (arr);
3063 struct type *type
3064 = check_typedef (array_ind->enclosing_type ());
3065
3066 if (type->code () == TYPE_CODE_ARRAY
3067 && TYPE_FIELD_BITSIZE (type, 0) > 0)
3068 return value_subscript_packed (array_ind, arity, ind);
3069
3070 for (k = 0; k < arity; k += 1)
3071 {
3072 LONGEST lwb, upb;
3073
3074 if (type->code () != TYPE_CODE_ARRAY)
3075 error (_("too many subscripts (%d expected)"), k);
3076 arr = value_cast (lookup_pointer_type (type->target_type ()),
3077 arr->copy ());
3078 get_discrete_bounds (type->index_type (), &lwb, &upb);
3079 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
3080 type = type->target_type ();
3081 }
3082
3083 return value_ind (arr);
3084 }
3085
3086 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
3087 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3088 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3089 this array is LOW, as per Ada rules. */
3090 static struct value *
3091 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
3092 int low, int high)
3093 {
3094 struct type *type0 = ada_check_typedef (type);
3095 struct type *base_index_type = type0->index_type ()->target_type ();
3096 type_allocator alloc (base_index_type);
3097 struct type *index_type
3098 = create_static_range_type (alloc, base_index_type, low, high);
3099 struct type *slice_type = create_array_type_with_stride
3100 (alloc, type0->target_type (), index_type,
3101 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3102 TYPE_FIELD_BITSIZE (type0, 0));
3103 int base_low = ada_discrete_type_low_bound (type0->index_type ());
3104 gdb::optional<LONGEST> base_low_pos, low_pos;
3105 CORE_ADDR base;
3106
3107 low_pos = discrete_position (base_index_type, low);
3108 base_low_pos = discrete_position (base_index_type, base_low);
3109
3110 if (!low_pos.has_value () || !base_low_pos.has_value ())
3111 {
3112 warning (_("unable to get positions in slice, use bounds instead"));
3113 low_pos = low;
3114 base_low_pos = base_low;
3115 }
3116
3117 ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
3118 if (stride == 0)
3119 stride = type0->target_type ()->length ();
3120
3121 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
3122 return value_at_lazy (slice_type, base);
3123 }
3124
3125
3126 static struct value *
3127 ada_value_slice (struct value *array, int low, int high)
3128 {
3129 struct type *type = ada_check_typedef (array->type ());
3130 struct type *base_index_type = type->index_type ()->target_type ();
3131 type_allocator alloc (type->index_type ());
3132 struct type *index_type
3133 = create_static_range_type (alloc, type->index_type (), low, high);
3134 struct type *slice_type = create_array_type_with_stride
3135 (alloc, type->target_type (), index_type,
3136 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3137 TYPE_FIELD_BITSIZE (type, 0));
3138 gdb::optional<LONGEST> low_pos, high_pos;
3139
3140
3141 low_pos = discrete_position (base_index_type, low);
3142 high_pos = discrete_position (base_index_type, high);
3143
3144 if (!low_pos.has_value () || !high_pos.has_value ())
3145 {
3146 warning (_("unable to get positions in slice, use bounds instead"));
3147 low_pos = low;
3148 high_pos = high;
3149 }
3150
3151 return value_cast (slice_type,
3152 value_slice (array, low, *high_pos - *low_pos + 1));
3153 }
3154
3155 /* If type is a record type in the form of a standard GNAT array
3156 descriptor, returns the number of dimensions for type. If arr is a
3157 simple array, returns the number of "array of"s that prefix its
3158 type designation. Otherwise, returns 0. */
3159
3160 int
3161 ada_array_arity (struct type *type)
3162 {
3163 int arity;
3164
3165 if (type == NULL)
3166 return 0;
3167
3168 type = desc_base_type (type);
3169
3170 arity = 0;
3171 if (type->code () == TYPE_CODE_STRUCT)
3172 return desc_arity (desc_bounds_type (type));
3173 else
3174 while (type->code () == TYPE_CODE_ARRAY)
3175 {
3176 arity += 1;
3177 type = ada_check_typedef (type->target_type ());
3178 }
3179
3180 return arity;
3181 }
3182
3183 /* If TYPE is a record type in the form of a standard GNAT array
3184 descriptor or a simple array type, returns the element type for
3185 TYPE after indexing by NINDICES indices, or by all indices if
3186 NINDICES is -1. Otherwise, returns NULL. */
3187
3188 struct type *
3189 ada_array_element_type (struct type *type, int nindices)
3190 {
3191 type = desc_base_type (type);
3192
3193 if (type->code () == TYPE_CODE_STRUCT)
3194 {
3195 int k;
3196 struct type *p_array_type;
3197
3198 p_array_type = desc_data_target_type (type);
3199
3200 k = ada_array_arity (type);
3201 if (k == 0)
3202 return NULL;
3203
3204 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
3205 if (nindices >= 0 && k > nindices)
3206 k = nindices;
3207 while (k > 0 && p_array_type != NULL)
3208 {
3209 p_array_type = ada_check_typedef (p_array_type->target_type ());
3210 k -= 1;
3211 }
3212 return p_array_type;
3213 }
3214 else if (type->code () == TYPE_CODE_ARRAY)
3215 {
3216 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
3217 {
3218 type = type->target_type ();
3219 /* A multi-dimensional array is represented using a sequence
3220 of array types. If one of these types has a name, then
3221 it is not another dimension of the outer array, but
3222 rather the element type of the outermost array. */
3223 if (type->name () != nullptr)
3224 break;
3225 nindices -= 1;
3226 }
3227 return type;
3228 }
3229
3230 return NULL;
3231 }
3232
3233 /* See ada-lang.h. */
3234
3235 struct type *
3236 ada_index_type (struct type *type, int n, const char *name)
3237 {
3238 struct type *result_type;
3239
3240 type = desc_base_type (type);
3241
3242 if (n < 0 || n > ada_array_arity (type))
3243 error (_("invalid dimension number to '%s"), name);
3244
3245 if (ada_is_simple_array_type (type))
3246 {
3247 int i;
3248
3249 for (i = 1; i < n; i += 1)
3250 {
3251 type = ada_check_typedef (type);
3252 type = type->target_type ();
3253 }
3254 result_type = ada_check_typedef (type)->index_type ()->target_type ();
3255 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3256 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3257 perhaps stabsread.c would make more sense. */
3258 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
3259 result_type = NULL;
3260 }
3261 else
3262 {
3263 result_type = desc_index_type (desc_bounds_type (type), n);
3264 if (result_type == NULL)
3265 error (_("attempt to take bound of something that is not an array"));
3266 }
3267
3268 return result_type;
3269 }
3270
3271 /* Given that arr is an array type, returns the lower bound of the
3272 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3273 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3274 array-descriptor type. It works for other arrays with bounds supplied
3275 by run-time quantities other than discriminants. */
3276
3277 static LONGEST
3278 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3279 {
3280 struct type *type, *index_type_desc, *index_type;
3281 int i;
3282
3283 gdb_assert (which == 0 || which == 1);
3284
3285 if (ada_is_constrained_packed_array_type (arr_type))
3286 arr_type = decode_constrained_packed_array_type (arr_type);
3287
3288 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3289 return (LONGEST) - which;
3290
3291 if (arr_type->code () == TYPE_CODE_PTR)
3292 type = arr_type->target_type ();
3293 else
3294 type = arr_type;
3295
3296 if (type->is_fixed_instance ())
3297 {
3298 /* The array has already been fixed, so we do not need to
3299 check the parallel ___XA type again. That encoding has
3300 already been applied, so ignore it now. */
3301 index_type_desc = NULL;
3302 }
3303 else
3304 {
3305 index_type_desc = ada_find_parallel_type (type, "___XA");
3306 ada_fixup_array_indexes_type (index_type_desc);
3307 }
3308
3309 if (index_type_desc != NULL)
3310 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
3311 NULL);
3312 else
3313 {
3314 struct type *elt_type = check_typedef (type);
3315
3316 for (i = 1; i < n; i++)
3317 elt_type = check_typedef (elt_type->target_type ());
3318
3319 index_type = elt_type->index_type ();
3320 }
3321
3322 return
3323 (LONGEST) (which == 0
3324 ? ada_discrete_type_low_bound (index_type)
3325 : ada_discrete_type_high_bound (index_type));
3326 }
3327
3328 /* Given that arr is an array value, returns the lower bound of the
3329 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3330 WHICH is 1. This routine will also work for arrays with bounds
3331 supplied by run-time quantities other than discriminants. */
3332
3333 static LONGEST
3334 ada_array_bound (struct value *arr, int n, int which)
3335 {
3336 struct type *arr_type;
3337
3338 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3339 arr = value_ind (arr);
3340 arr_type = arr->enclosing_type ();
3341
3342 if (ada_is_constrained_packed_array_type (arr_type))
3343 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3344 else if (ada_is_simple_array_type (arr_type))
3345 return ada_array_bound_from_type (arr_type, n, which);
3346 else
3347 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3348 }
3349
3350 /* Given that arr is an array value, returns the length of the
3351 nth index. This routine will also work for arrays with bounds
3352 supplied by run-time quantities other than discriminants.
3353 Does not work for arrays indexed by enumeration types with representation
3354 clauses at the moment. */
3355
3356 static LONGEST
3357 ada_array_length (struct value *arr, int n)
3358 {
3359 struct type *arr_type, *index_type;
3360 int low, high;
3361
3362 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
3363 arr = value_ind (arr);
3364 arr_type = arr->enclosing_type ();
3365
3366 if (ada_is_constrained_packed_array_type (arr_type))
3367 return ada_array_length (decode_constrained_packed_array (arr), n);
3368
3369 if (ada_is_simple_array_type (arr_type))
3370 {
3371 low = ada_array_bound_from_type (arr_type, n, 0);
3372 high = ada_array_bound_from_type (arr_type, n, 1);
3373 }
3374 else
3375 {
3376 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3377 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3378 }
3379
3380 arr_type = check_typedef (arr_type);
3381 index_type = ada_index_type (arr_type, n, "length");
3382 if (index_type != NULL)
3383 {
3384 struct type *base_type;
3385 if (index_type->code () == TYPE_CODE_RANGE)
3386 base_type = index_type->target_type ();
3387 else
3388 base_type = index_type;
3389
3390 low = pos_atr (value_from_longest (base_type, low));
3391 high = pos_atr (value_from_longest (base_type, high));
3392 }
3393 return high - low + 1;
3394 }
3395
3396 /* An array whose type is that of ARR_TYPE (an array type), with
3397 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3398 less than LOW, then LOW-1 is used. */
3399
3400 static struct value *
3401 empty_array (struct type *arr_type, int low, int high)
3402 {
3403 struct type *arr_type0 = ada_check_typedef (arr_type);
3404 type_allocator alloc (arr_type0->index_type ()->target_type ());
3405 struct type *index_type
3406 = create_static_range_type
3407 (alloc, arr_type0->index_type ()->target_type (), low,
3408 high < low ? low - 1 : high);
3409 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3410
3411 return value::allocate (create_array_type (alloc, elt_type, index_type));
3412 }
3413 \f
3414
3415 /* Name resolution */
3416
3417 /* The "decoded" name for the user-definable Ada operator corresponding
3418 to OP. */
3419
3420 static const char *
3421 ada_decoded_op_name (enum exp_opcode op)
3422 {
3423 int i;
3424
3425 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3426 {
3427 if (ada_opname_table[i].op == op)
3428 return ada_opname_table[i].decoded;
3429 }
3430 error (_("Could not find operator name for opcode"));
3431 }
3432
3433 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3434 in a listing of choices during disambiguation (see sort_choices, below).
3435 The idea is that overloadings of a subprogram name from the
3436 same package should sort in their source order. We settle for ordering
3437 such symbols by their trailing number (__N or $N). */
3438
3439 static int
3440 encoded_ordered_before (const char *N0, const char *N1)
3441 {
3442 if (N1 == NULL)
3443 return 0;
3444 else if (N0 == NULL)
3445 return 1;
3446 else
3447 {
3448 int k0, k1;
3449
3450 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3451 ;
3452 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3453 ;
3454 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3455 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3456 {
3457 int n0, n1;
3458
3459 n0 = k0;
3460 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3461 n0 -= 1;
3462 n1 = k1;
3463 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3464 n1 -= 1;
3465 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3466 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3467 }
3468 return (strcmp (N0, N1) < 0);
3469 }
3470 }
3471
3472 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3473 encoded names. */
3474
3475 static void
3476 sort_choices (struct block_symbol syms[], int nsyms)
3477 {
3478 int i;
3479
3480 for (i = 1; i < nsyms; i += 1)
3481 {
3482 struct block_symbol sym = syms[i];
3483 int j;
3484
3485 for (j = i - 1; j >= 0; j -= 1)
3486 {
3487 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3488 sym.symbol->linkage_name ()))
3489 break;
3490 syms[j + 1] = syms[j];
3491 }
3492 syms[j + 1] = sym;
3493 }
3494 }
3495
3496 /* Whether GDB should display formals and return types for functions in the
3497 overloads selection menu. */
3498 static bool print_signatures = true;
3499
3500 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3501 all but functions, the signature is just the name of the symbol. For
3502 functions, this is the name of the function, the list of types for formals
3503 and the return type (if any). */
3504
3505 static void
3506 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3507 const struct type_print_options *flags)
3508 {
3509 struct type *type = sym->type ();
3510
3511 gdb_printf (stream, "%s", sym->print_name ());
3512 if (!print_signatures
3513 || type == NULL
3514 || type->code () != TYPE_CODE_FUNC)
3515 return;
3516
3517 if (type->num_fields () > 0)
3518 {
3519 int i;
3520
3521 gdb_printf (stream, " (");
3522 for (i = 0; i < type->num_fields (); ++i)
3523 {
3524 if (i > 0)
3525 gdb_printf (stream, "; ");
3526 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3527 flags);
3528 }
3529 gdb_printf (stream, ")");
3530 }
3531 if (type->target_type () != NULL
3532 && type->target_type ()->code () != TYPE_CODE_VOID)
3533 {
3534 gdb_printf (stream, " return ");
3535 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
3536 }
3537 }
3538
3539 /* Read and validate a set of numeric choices from the user in the
3540 range 0 .. N_CHOICES-1. Place the results in increasing
3541 order in CHOICES[0 .. N-1], and return N.
3542
3543 The user types choices as a sequence of numbers on one line
3544 separated by blanks, encoding them as follows:
3545
3546 + A choice of 0 means to cancel the selection, throwing an error.
3547 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3548 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3549
3550 The user is not allowed to choose more than MAX_RESULTS values.
3551
3552 ANNOTATION_SUFFIX, if present, is used to annotate the input
3553 prompts (for use with the -f switch). */
3554
3555 static int
3556 get_selections (int *choices, int n_choices, int max_results,
3557 int is_all_choice, const char *annotation_suffix)
3558 {
3559 const char *args;
3560 const char *prompt;
3561 int n_chosen;
3562 int first_choice = is_all_choice ? 2 : 1;
3563
3564 prompt = getenv ("PS2");
3565 if (prompt == NULL)
3566 prompt = "> ";
3567
3568 std::string buffer;
3569 args = command_line_input (buffer, prompt, annotation_suffix);
3570
3571 if (args == NULL)
3572 error_no_arg (_("one or more choice numbers"));
3573
3574 n_chosen = 0;
3575
3576 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3577 order, as given in args. Choices are validated. */
3578 while (1)
3579 {
3580 char *args2;
3581 int choice, j;
3582
3583 args = skip_spaces (args);
3584 if (*args == '\0' && n_chosen == 0)
3585 error_no_arg (_("one or more choice numbers"));
3586 else if (*args == '\0')
3587 break;
3588
3589 choice = strtol (args, &args2, 10);
3590 if (args == args2 || choice < 0
3591 || choice > n_choices + first_choice - 1)
3592 error (_("Argument must be choice number"));
3593 args = args2;
3594
3595 if (choice == 0)
3596 error (_("cancelled"));
3597
3598 if (choice < first_choice)
3599 {
3600 n_chosen = n_choices;
3601 for (j = 0; j < n_choices; j += 1)
3602 choices[j] = j;
3603 break;
3604 }
3605 choice -= first_choice;
3606
3607 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3608 {
3609 }
3610
3611 if (j < 0 || choice != choices[j])
3612 {
3613 int k;
3614
3615 for (k = n_chosen - 1; k > j; k -= 1)
3616 choices[k + 1] = choices[k];
3617 choices[j + 1] = choice;
3618 n_chosen += 1;
3619 }
3620 }
3621
3622 if (n_chosen > max_results)
3623 error (_("Select no more than %d of the above"), max_results);
3624
3625 return n_chosen;
3626 }
3627
3628 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3629 by asking the user (if necessary), returning the number selected,
3630 and setting the first elements of SYMS items. Error if no symbols
3631 selected. */
3632
3633 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3634 to be re-integrated one of these days. */
3635
3636 static int
3637 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3638 {
3639 int i;
3640 int *chosen = XALLOCAVEC (int , nsyms);
3641 int n_chosen;
3642 int first_choice = (max_results == 1) ? 1 : 2;
3643 const char *select_mode = multiple_symbols_select_mode ();
3644
3645 if (max_results < 1)
3646 error (_("Request to select 0 symbols!"));
3647 if (nsyms <= 1)
3648 return nsyms;
3649
3650 if (select_mode == multiple_symbols_cancel)
3651 error (_("\
3652 canceled because the command is ambiguous\n\
3653 See set/show multiple-symbol."));
3654
3655 /* If select_mode is "all", then return all possible symbols.
3656 Only do that if more than one symbol can be selected, of course.
3657 Otherwise, display the menu as usual. */
3658 if (select_mode == multiple_symbols_all && max_results > 1)
3659 return nsyms;
3660
3661 gdb_printf (_("[0] cancel\n"));
3662 if (max_results > 1)
3663 gdb_printf (_("[1] all\n"));
3664
3665 sort_choices (syms, nsyms);
3666
3667 for (i = 0; i < nsyms; i += 1)
3668 {
3669 if (syms[i].symbol == NULL)
3670 continue;
3671
3672 if (syms[i].symbol->aclass () == LOC_BLOCK)
3673 {
3674 struct symtab_and_line sal =
3675 find_function_start_sal (syms[i].symbol, 1);
3676
3677 gdb_printf ("[%d] ", i + first_choice);
3678 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3679 &type_print_raw_options);
3680 if (sal.symtab == NULL)
3681 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3682 metadata_style.style ().ptr (), nullptr, sal.line);
3683 else
3684 gdb_printf
3685 (_(" at %ps:%d\n"),
3686 styled_string (file_name_style.style (),
3687 symtab_to_filename_for_display (sal.symtab)),
3688 sal.line);
3689 continue;
3690 }
3691 else
3692 {
3693 int is_enumeral =
3694 (syms[i].symbol->aclass () == LOC_CONST
3695 && syms[i].symbol->type () != NULL
3696 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3697 struct symtab *symtab = NULL;
3698
3699 if (syms[i].symbol->is_objfile_owned ())
3700 symtab = syms[i].symbol->symtab ();
3701
3702 if (syms[i].symbol->line () != 0 && symtab != NULL)
3703 {
3704 gdb_printf ("[%d] ", i + first_choice);
3705 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3706 &type_print_raw_options);
3707 gdb_printf (_(" at %s:%d\n"),
3708 symtab_to_filename_for_display (symtab),
3709 syms[i].symbol->line ());
3710 }
3711 else if (is_enumeral
3712 && syms[i].symbol->type ()->name () != NULL)
3713 {
3714 gdb_printf (("[%d] "), i + first_choice);
3715 ada_print_type (syms[i].symbol->type (), NULL,
3716 gdb_stdout, -1, 0, &type_print_raw_options);
3717 gdb_printf (_("'(%s) (enumeral)\n"),
3718 syms[i].symbol->print_name ());
3719 }
3720 else
3721 {
3722 gdb_printf ("[%d] ", i + first_choice);
3723 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3724 &type_print_raw_options);
3725
3726 if (symtab != NULL)
3727 gdb_printf (is_enumeral
3728 ? _(" in %s (enumeral)\n")
3729 : _(" at %s:?\n"),
3730 symtab_to_filename_for_display (symtab));
3731 else
3732 gdb_printf (is_enumeral
3733 ? _(" (enumeral)\n")
3734 : _(" at ?\n"));
3735 }
3736 }
3737 }
3738
3739 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3740 "overload-choice");
3741
3742 for (i = 0; i < n_chosen; i += 1)
3743 syms[i] = syms[chosen[i]];
3744
3745 return n_chosen;
3746 }
3747
3748 /* See ada-lang.h. */
3749
3750 block_symbol
3751 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3752 int nargs, value *argvec[])
3753 {
3754 if (possible_user_operator_p (op, argvec))
3755 {
3756 std::vector<struct block_symbol> candidates
3757 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3758 NULL, VAR_DOMAIN);
3759
3760 int i = ada_resolve_function (candidates, argvec,
3761 nargs, ada_decoded_op_name (op), NULL,
3762 parse_completion);
3763 if (i >= 0)
3764 return candidates[i];
3765 }
3766 return {};
3767 }
3768
3769 /* See ada-lang.h. */
3770
3771 block_symbol
3772 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3773 struct type *context_type,
3774 bool parse_completion,
3775 int nargs, value *argvec[],
3776 innermost_block_tracker *tracker)
3777 {
3778 std::vector<struct block_symbol> candidates
3779 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3780
3781 int i;
3782 if (candidates.size () == 1)
3783 i = 0;
3784 else
3785 {
3786 i = ada_resolve_function
3787 (candidates,
3788 argvec, nargs,
3789 sym->linkage_name (),
3790 context_type, parse_completion);
3791 if (i < 0)
3792 error (_("Could not find a match for %s"), sym->print_name ());
3793 }
3794
3795 tracker->update (candidates[i]);
3796 return candidates[i];
3797 }
3798
3799 /* Resolve a mention of a name where the context type is an
3800 enumeration type. */
3801
3802 static int
3803 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3804 const char *name, struct type *context_type,
3805 bool parse_completion)
3806 {
3807 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3808 context_type = ada_check_typedef (context_type);
3809
3810 for (int i = 0; i < syms.size (); ++i)
3811 {
3812 /* We already know the name matches, so we're just looking for
3813 an element of the correct enum type. */
3814 if (ada_check_typedef (syms[i].symbol->type ()) == context_type)
3815 return i;
3816 }
3817
3818 error (_("No name '%s' in enumeration type '%s'"), name,
3819 ada_type_name (context_type));
3820 }
3821
3822 /* See ada-lang.h. */
3823
3824 block_symbol
3825 ada_resolve_variable (struct symbol *sym, const struct block *block,
3826 struct type *context_type,
3827 bool parse_completion,
3828 int deprocedure_p,
3829 innermost_block_tracker *tracker)
3830 {
3831 std::vector<struct block_symbol> candidates
3832 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3833
3834 if (std::any_of (candidates.begin (),
3835 candidates.end (),
3836 [] (block_symbol &bsym)
3837 {
3838 switch (bsym.symbol->aclass ())
3839 {
3840 case LOC_REGISTER:
3841 case LOC_ARG:
3842 case LOC_REF_ARG:
3843 case LOC_REGPARM_ADDR:
3844 case LOC_LOCAL:
3845 case LOC_COMPUTED:
3846 return true;
3847 default:
3848 return false;
3849 }
3850 }))
3851 {
3852 /* Types tend to get re-introduced locally, so if there
3853 are any local symbols that are not types, first filter
3854 out all types. */
3855 candidates.erase
3856 (std::remove_if
3857 (candidates.begin (),
3858 candidates.end (),
3859 [] (block_symbol &bsym)
3860 {
3861 return bsym.symbol->aclass () == LOC_TYPEDEF;
3862 }),
3863 candidates.end ());
3864 }
3865
3866 /* Filter out artificial symbols. */
3867 candidates.erase
3868 (std::remove_if
3869 (candidates.begin (),
3870 candidates.end (),
3871 [] (block_symbol &bsym)
3872 {
3873 return bsym.symbol->is_artificial ();
3874 }),
3875 candidates.end ());
3876
3877 int i;
3878 if (candidates.empty ())
3879 error (_("No definition found for %s"), sym->print_name ());
3880 else if (candidates.size () == 1)
3881 i = 0;
3882 else if (context_type != nullptr
3883 && context_type->code () == TYPE_CODE_ENUM)
3884 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3885 parse_completion);
3886 else if (deprocedure_p && !is_nonfunction (candidates))
3887 {
3888 i = ada_resolve_function
3889 (candidates, NULL, 0,
3890 sym->linkage_name (),
3891 context_type, parse_completion);
3892 if (i < 0)
3893 error (_("Could not find a match for %s"), sym->print_name ());
3894 }
3895 else
3896 {
3897 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
3898 user_select_syms (candidates.data (), candidates.size (), 1);
3899 i = 0;
3900 }
3901
3902 tracker->update (candidates[i]);
3903 return candidates[i];
3904 }
3905
3906 /* Return non-zero if formal type FTYPE matches actual type ATYPE. */
3907 /* The term "match" here is rather loose. The match is heuristic and
3908 liberal. */
3909
3910 static int
3911 ada_type_match (struct type *ftype, struct type *atype)
3912 {
3913 ftype = ada_check_typedef (ftype);
3914 atype = ada_check_typedef (atype);
3915
3916 if (ftype->code () == TYPE_CODE_REF)
3917 ftype = ftype->target_type ();
3918 if (atype->code () == TYPE_CODE_REF)
3919 atype = atype->target_type ();
3920
3921 switch (ftype->code ())
3922 {
3923 default:
3924 return ftype->code () == atype->code ();
3925 case TYPE_CODE_PTR:
3926 if (atype->code () != TYPE_CODE_PTR)
3927 return 0;
3928 atype = atype->target_type ();
3929 /* This can only happen if the actual argument is 'null'. */
3930 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
3931 return 1;
3932 return ada_type_match (ftype->target_type (), atype);
3933 case TYPE_CODE_INT:
3934 case TYPE_CODE_ENUM:
3935 case TYPE_CODE_RANGE:
3936 switch (atype->code ())
3937 {
3938 case TYPE_CODE_INT:
3939 case TYPE_CODE_ENUM:
3940 case TYPE_CODE_RANGE:
3941 return 1;
3942 default:
3943 return 0;
3944 }
3945
3946 case TYPE_CODE_ARRAY:
3947 return (atype->code () == TYPE_CODE_ARRAY
3948 || ada_is_array_descriptor_type (atype));
3949
3950 case TYPE_CODE_STRUCT:
3951 if (ada_is_array_descriptor_type (ftype))
3952 return (atype->code () == TYPE_CODE_ARRAY
3953 || ada_is_array_descriptor_type (atype));
3954 else
3955 return (atype->code () == TYPE_CODE_STRUCT
3956 && !ada_is_array_descriptor_type (atype));
3957
3958 case TYPE_CODE_UNION:
3959 case TYPE_CODE_FLT:
3960 return (atype->code () == ftype->code ());
3961 }
3962 }
3963
3964 /* Return non-zero if the formals of FUNC "sufficiently match" the
3965 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3966 may also be an enumeral, in which case it is treated as a 0-
3967 argument function. */
3968
3969 static int
3970 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3971 {
3972 int i;
3973 struct type *func_type = func->type ();
3974
3975 if (func->aclass () == LOC_CONST
3976 && func_type->code () == TYPE_CODE_ENUM)
3977 return (n_actuals == 0);
3978 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3979 return 0;
3980
3981 if (func_type->num_fields () != n_actuals)
3982 return 0;
3983
3984 for (i = 0; i < n_actuals; i += 1)
3985 {
3986 if (actuals[i] == NULL)
3987 return 0;
3988 else
3989 {
3990 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3991 struct type *atype = ada_check_typedef (actuals[i]->type ());
3992
3993 if (!ada_type_match (ftype, atype))
3994 return 0;
3995 }
3996 }
3997 return 1;
3998 }
3999
4000 /* False iff function type FUNC_TYPE definitely does not produce a value
4001 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4002 FUNC_TYPE is not a valid function type with a non-null return type
4003 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
4004
4005 static int
4006 return_match (struct type *func_type, struct type *context_type)
4007 {
4008 struct type *return_type;
4009
4010 if (func_type == NULL)
4011 return 1;
4012
4013 if (func_type->code () == TYPE_CODE_FUNC)
4014 return_type = get_base_type (func_type->target_type ());
4015 else
4016 return_type = get_base_type (func_type);
4017 if (return_type == NULL)
4018 return 1;
4019
4020 context_type = get_base_type (context_type);
4021
4022 if (return_type->code () == TYPE_CODE_ENUM)
4023 return context_type == NULL || return_type == context_type;
4024 else if (context_type == NULL)
4025 return return_type->code () != TYPE_CODE_VOID;
4026 else
4027 return return_type->code () == context_type->code ();
4028 }
4029
4030
4031 /* Returns the index in SYMS that contains the symbol for the
4032 function (if any) that matches the types of the NARGS arguments in
4033 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4034 that returns that type, then eliminate matches that don't. If
4035 CONTEXT_TYPE is void and there is at least one match that does not
4036 return void, eliminate all matches that do.
4037
4038 Asks the user if there is more than one match remaining. Returns -1
4039 if there is no such symbol or none is selected. NAME is used
4040 solely for messages. May re-arrange and modify SYMS in
4041 the process; the index returned is for the modified vector. */
4042
4043 static int
4044 ada_resolve_function (std::vector<struct block_symbol> &syms,
4045 struct value **args, int nargs,
4046 const char *name, struct type *context_type,
4047 bool parse_completion)
4048 {
4049 int fallback;
4050 int k;
4051 int m; /* Number of hits */
4052
4053 m = 0;
4054 /* In the first pass of the loop, we only accept functions matching
4055 context_type. If none are found, we add a second pass of the loop
4056 where every function is accepted. */
4057 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4058 {
4059 for (k = 0; k < syms.size (); k += 1)
4060 {
4061 struct type *type = ada_check_typedef (syms[k].symbol->type ());
4062
4063 if (ada_args_match (syms[k].symbol, args, nargs)
4064 && (fallback || return_match (type, context_type)))
4065 {
4066 syms[m] = syms[k];
4067 m += 1;
4068 }
4069 }
4070 }
4071
4072 /* If we got multiple matches, ask the user which one to use. Don't do this
4073 interactive thing during completion, though, as the purpose of the
4074 completion is providing a list of all possible matches. Prompting the
4075 user to filter it down would be completely unexpected in this case. */
4076 if (m == 0)
4077 return -1;
4078 else if (m > 1 && !parse_completion)
4079 {
4080 gdb_printf (_("Multiple matches for %s\n"), name);
4081 user_select_syms (syms.data (), m, 1);
4082 return 0;
4083 }
4084 return 0;
4085 }
4086
4087 /* Type-class predicates */
4088
4089 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4090 or FLOAT). */
4091
4092 static int
4093 numeric_type_p (struct type *type)
4094 {
4095 if (type == NULL)
4096 return 0;
4097 else
4098 {
4099 switch (type->code ())
4100 {
4101 case TYPE_CODE_INT:
4102 case TYPE_CODE_FLT:
4103 case TYPE_CODE_FIXED_POINT:
4104 return 1;
4105 case TYPE_CODE_RANGE:
4106 return (type == type->target_type ()
4107 || numeric_type_p (type->target_type ()));
4108 default:
4109 return 0;
4110 }
4111 }
4112 }
4113
4114 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4115
4116 static int
4117 integer_type_p (struct type *type)
4118 {
4119 if (type == NULL)
4120 return 0;
4121 else
4122 {
4123 switch (type->code ())
4124 {
4125 case TYPE_CODE_INT:
4126 return 1;
4127 case TYPE_CODE_RANGE:
4128 return (type == type->target_type ()
4129 || integer_type_p (type->target_type ()));
4130 default:
4131 return 0;
4132 }
4133 }
4134 }
4135
4136 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4137
4138 static int
4139 scalar_type_p (struct type *type)
4140 {
4141 if (type == NULL)
4142 return 0;
4143 else
4144 {
4145 switch (type->code ())
4146 {
4147 case TYPE_CODE_INT:
4148 case TYPE_CODE_RANGE:
4149 case TYPE_CODE_ENUM:
4150 case TYPE_CODE_FLT:
4151 case TYPE_CODE_FIXED_POINT:
4152 return 1;
4153 default:
4154 return 0;
4155 }
4156 }
4157 }
4158
4159 /* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4160 This essentially means one of (INT, RANGE, ENUM) -- but note that
4161 "enum" includes character and boolean as well. */
4162
4163 static int
4164 discrete_type_p (struct type *type)
4165 {
4166 if (type == NULL)
4167 return 0;
4168 else
4169 {
4170 switch (type->code ())
4171 {
4172 case TYPE_CODE_INT:
4173 case TYPE_CODE_RANGE:
4174 case TYPE_CODE_ENUM:
4175 case TYPE_CODE_BOOL:
4176 case TYPE_CODE_CHAR:
4177 return 1;
4178 default:
4179 return 0;
4180 }
4181 }
4182 }
4183
4184 /* Returns non-zero if OP with operands in the vector ARGS could be
4185 a user-defined function. Errs on the side of pre-defined operators
4186 (i.e., result 0). */
4187
4188 static int
4189 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4190 {
4191 struct type *type0 =
4192 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
4193 struct type *type1 =
4194 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
4195
4196 if (type0 == NULL)
4197 return 0;
4198
4199 switch (op)
4200 {
4201 default:
4202 return 0;
4203
4204 case BINOP_ADD:
4205 case BINOP_SUB:
4206 case BINOP_MUL:
4207 case BINOP_DIV:
4208 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4209
4210 case BINOP_REM:
4211 case BINOP_MOD:
4212 case BINOP_BITWISE_AND:
4213 case BINOP_BITWISE_IOR:
4214 case BINOP_BITWISE_XOR:
4215 return (!(integer_type_p (type0) && integer_type_p (type1)));
4216
4217 case BINOP_EQUAL:
4218 case BINOP_NOTEQUAL:
4219 case BINOP_LESS:
4220 case BINOP_GTR:
4221 case BINOP_LEQ:
4222 case BINOP_GEQ:
4223 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4224
4225 case BINOP_CONCAT:
4226 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4227
4228 case BINOP_EXP:
4229 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4230
4231 case UNOP_NEG:
4232 case UNOP_PLUS:
4233 case UNOP_LOGICAL_NOT:
4234 case UNOP_ABS:
4235 return (!numeric_type_p (type0));
4236
4237 }
4238 }
4239 \f
4240 /* Renaming */
4241
4242 /* NOTES:
4243
4244 1. In the following, we assume that a renaming type's name may
4245 have an ___XD suffix. It would be nice if this went away at some
4246 point.
4247 2. We handle both the (old) purely type-based representation of
4248 renamings and the (new) variable-based encoding. At some point,
4249 it is devoutly to be hoped that the former goes away
4250 (FIXME: hilfinger-2007-07-09).
4251 3. Subprogram renamings are not implemented, although the XRS
4252 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4253
4254 /* If SYM encodes a renaming,
4255
4256 <renaming> renames <renamed entity>,
4257
4258 sets *LEN to the length of the renamed entity's name,
4259 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4260 the string describing the subcomponent selected from the renamed
4261 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4262 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4263 are undefined). Otherwise, returns a value indicating the category
4264 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4265 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4266 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4267 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4268 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4269 may be NULL, in which case they are not assigned.
4270
4271 [Currently, however, GCC does not generate subprogram renamings.] */
4272
4273 enum ada_renaming_category
4274 ada_parse_renaming (struct symbol *sym,
4275 const char **renamed_entity, int *len,
4276 const char **renaming_expr)
4277 {
4278 enum ada_renaming_category kind;
4279 const char *info;
4280 const char *suffix;
4281
4282 if (sym == NULL)
4283 return ADA_NOT_RENAMING;
4284 switch (sym->aclass ())
4285 {
4286 default:
4287 return ADA_NOT_RENAMING;
4288 case LOC_LOCAL:
4289 case LOC_STATIC:
4290 case LOC_COMPUTED:
4291 case LOC_OPTIMIZED_OUT:
4292 info = strstr (sym->linkage_name (), "___XR");
4293 if (info == NULL)
4294 return ADA_NOT_RENAMING;
4295 switch (info[5])
4296 {
4297 case '_':
4298 kind = ADA_OBJECT_RENAMING;
4299 info += 6;
4300 break;
4301 case 'E':
4302 kind = ADA_EXCEPTION_RENAMING;
4303 info += 7;
4304 break;
4305 case 'P':
4306 kind = ADA_PACKAGE_RENAMING;
4307 info += 7;
4308 break;
4309 case 'S':
4310 kind = ADA_SUBPROGRAM_RENAMING;
4311 info += 7;
4312 break;
4313 default:
4314 return ADA_NOT_RENAMING;
4315 }
4316 }
4317
4318 if (renamed_entity != NULL)
4319 *renamed_entity = info;
4320 suffix = strstr (info, "___XE");
4321 if (suffix == NULL || suffix == info)
4322 return ADA_NOT_RENAMING;
4323 if (len != NULL)
4324 *len = strlen (info) - strlen (suffix);
4325 suffix += 5;
4326 if (renaming_expr != NULL)
4327 *renaming_expr = suffix;
4328 return kind;
4329 }
4330
4331 /* Compute the value of the given RENAMING_SYM, which is expected to
4332 be a symbol encoding a renaming expression. BLOCK is the block
4333 used to evaluate the renaming. */
4334
4335 static struct value *
4336 ada_read_renaming_var_value (struct symbol *renaming_sym,
4337 const struct block *block)
4338 {
4339 const char *sym_name;
4340
4341 sym_name = renaming_sym->linkage_name ();
4342 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4343 return evaluate_expression (expr.get ());
4344 }
4345 \f
4346
4347 /* Evaluation: Function Calls */
4348
4349 /* Return an lvalue containing the value VAL. This is the identity on
4350 lvalues, and otherwise has the side-effect of allocating memory
4351 in the inferior where a copy of the value contents is copied. */
4352
4353 static struct value *
4354 ensure_lval (struct value *val)
4355 {
4356 if (val->lval () == not_lval
4357 || val->lval () == lval_internalvar)
4358 {
4359 int len = ada_check_typedef (val->type ())->length ();
4360 const CORE_ADDR addr =
4361 value_as_long (value_allocate_space_in_inferior (len));
4362
4363 val->set_lval (lval_memory);
4364 val->set_address (addr);
4365 write_memory (addr, val->contents ().data (), len);
4366 }
4367
4368 return val;
4369 }
4370
4371 /* Given ARG, a value of type (pointer or reference to a)*
4372 structure/union, extract the component named NAME from the ultimate
4373 target structure/union and return it as a value with its
4374 appropriate type.
4375
4376 The routine searches for NAME among all members of the structure itself
4377 and (recursively) among all members of any wrapper members
4378 (e.g., '_parent').
4379
4380 If NO_ERR, then simply return NULL in case of error, rather than
4381 calling error. */
4382
4383 static struct value *
4384 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4385 {
4386 struct type *t, *t1;
4387 struct value *v;
4388 int check_tag;
4389
4390 v = NULL;
4391 t1 = t = ada_check_typedef (arg->type ());
4392 if (t->code () == TYPE_CODE_REF)
4393 {
4394 t1 = t->target_type ();
4395 if (t1 == NULL)
4396 goto BadValue;
4397 t1 = ada_check_typedef (t1);
4398 if (t1->code () == TYPE_CODE_PTR)
4399 {
4400 arg = coerce_ref (arg);
4401 t = t1;
4402 }
4403 }
4404
4405 while (t->code () == TYPE_CODE_PTR)
4406 {
4407 t1 = t->target_type ();
4408 if (t1 == NULL)
4409 goto BadValue;
4410 t1 = ada_check_typedef (t1);
4411 if (t1->code () == TYPE_CODE_PTR)
4412 {
4413 arg = value_ind (arg);
4414 t = t1;
4415 }
4416 else
4417 break;
4418 }
4419
4420 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4421 goto BadValue;
4422
4423 if (t1 == t)
4424 v = ada_search_struct_field (name, arg, 0, t);
4425 else
4426 {
4427 int bit_offset, bit_size, byte_offset;
4428 struct type *field_type;
4429 CORE_ADDR address;
4430
4431 if (t->code () == TYPE_CODE_PTR)
4432 address = ada_value_ind (arg)->address ();
4433 else
4434 address = ada_coerce_ref (arg)->address ();
4435
4436 /* Check to see if this is a tagged type. We also need to handle
4437 the case where the type is a reference to a tagged type, but
4438 we have to be careful to exclude pointers to tagged types.
4439 The latter should be shown as usual (as a pointer), whereas
4440 a reference should mostly be transparent to the user. */
4441
4442 if (ada_is_tagged_type (t1, 0)
4443 || (t1->code () == TYPE_CODE_REF
4444 && ada_is_tagged_type (t1->target_type (), 0)))
4445 {
4446 /* We first try to find the searched field in the current type.
4447 If not found then let's look in the fixed type. */
4448
4449 if (!find_struct_field (name, t1, 0,
4450 nullptr, nullptr, nullptr,
4451 nullptr, nullptr))
4452 check_tag = 1;
4453 else
4454 check_tag = 0;
4455 }
4456 else
4457 check_tag = 0;
4458
4459 /* Convert to fixed type in all cases, so that we have proper
4460 offsets to each field in unconstrained record types. */
4461 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4462 address, NULL, check_tag);
4463
4464 /* Resolve the dynamic type as well. */
4465 arg = value_from_contents_and_address (t1, nullptr, address);
4466 t1 = arg->type ();
4467
4468 if (find_struct_field (name, t1, 0,
4469 &field_type, &byte_offset, &bit_offset,
4470 &bit_size, NULL))
4471 {
4472 if (bit_size != 0)
4473 {
4474 if (t->code () == TYPE_CODE_REF)
4475 arg = ada_coerce_ref (arg);
4476 else
4477 arg = ada_value_ind (arg);
4478 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4479 bit_offset, bit_size,
4480 field_type);
4481 }
4482 else
4483 v = value_at_lazy (field_type, address + byte_offset);
4484 }
4485 }
4486
4487 if (v != NULL || no_err)
4488 return v;
4489 else
4490 error (_("There is no member named %s."), name);
4491
4492 BadValue:
4493 if (no_err)
4494 return NULL;
4495 else
4496 error (_("Attempt to extract a component of "
4497 "a value that is not a record."));
4498 }
4499
4500 /* Return the value ACTUAL, converted to be an appropriate value for a
4501 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4502 allocating any necessary descriptors (fat pointers), or copies of
4503 values not residing in memory, updating it as needed. */
4504
4505 struct value *
4506 ada_convert_actual (struct value *actual, struct type *formal_type0)
4507 {
4508 struct type *actual_type = ada_check_typedef (actual->type ());
4509 struct type *formal_type = ada_check_typedef (formal_type0);
4510 struct type *formal_target =
4511 formal_type->code () == TYPE_CODE_PTR
4512 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
4513 struct type *actual_target =
4514 actual_type->code () == TYPE_CODE_PTR
4515 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
4516
4517 if (ada_is_array_descriptor_type (formal_target)
4518 && actual_target->code () == TYPE_CODE_ARRAY)
4519 return make_array_descriptor (formal_type, actual);
4520 else if (formal_type->code () == TYPE_CODE_PTR
4521 || formal_type->code () == TYPE_CODE_REF)
4522 {
4523 struct value *result;
4524
4525 if (formal_target->code () == TYPE_CODE_ARRAY
4526 && ada_is_array_descriptor_type (actual_target))
4527 result = desc_data (actual);
4528 else if (formal_type->code () != TYPE_CODE_PTR)
4529 {
4530 if (actual->lval () != lval_memory)
4531 {
4532 struct value *val;
4533
4534 actual_type = ada_check_typedef (actual->type ());
4535 val = value::allocate (actual_type);
4536 copy (actual->contents (), val->contents_raw ());
4537 actual = ensure_lval (val);
4538 }
4539 result = value_addr (actual);
4540 }
4541 else
4542 return actual;
4543 return value_cast_pointers (formal_type, result, 0);
4544 }
4545 else if (actual_type->code () == TYPE_CODE_PTR)
4546 return ada_value_ind (actual);
4547 else if (ada_is_aligner_type (formal_type))
4548 {
4549 /* We need to turn this parameter into an aligner type
4550 as well. */
4551 struct value *aligner = value::allocate (formal_type);
4552 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4553
4554 value_assign_to_component (aligner, component, actual);
4555 return aligner;
4556 }
4557
4558 return actual;
4559 }
4560
4561 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4562 type TYPE. This is usually an inefficient no-op except on some targets
4563 (such as AVR) where the representation of a pointer and an address
4564 differs. */
4565
4566 static CORE_ADDR
4567 value_pointer (struct value *value, struct type *type)
4568 {
4569 unsigned len = type->length ();
4570 gdb_byte *buf = (gdb_byte *) alloca (len);
4571 CORE_ADDR addr;
4572
4573 addr = value->address ();
4574 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4575 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4576 return addr;
4577 }
4578
4579
4580 /* Push a descriptor of type TYPE for array value ARR on the stack at
4581 *SP, updating *SP to reflect the new descriptor. Return either
4582 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4583 to-descriptor type rather than a descriptor type), a struct value *
4584 representing a pointer to this descriptor. */
4585
4586 static struct value *
4587 make_array_descriptor (struct type *type, struct value *arr)
4588 {
4589 struct type *bounds_type = desc_bounds_type (type);
4590 struct type *desc_type = desc_base_type (type);
4591 struct value *descriptor = value::allocate (desc_type);
4592 struct value *bounds = value::allocate (bounds_type);
4593 int i;
4594
4595 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
4596 i > 0; i -= 1)
4597 {
4598 modify_field (bounds->type (),
4599 bounds->contents_writeable ().data (),
4600 ada_array_bound (arr, i, 0),
4601 desc_bound_bitpos (bounds_type, i, 0),
4602 desc_bound_bitsize (bounds_type, i, 0));
4603 modify_field (bounds->type (),
4604 bounds->contents_writeable ().data (),
4605 ada_array_bound (arr, i, 1),
4606 desc_bound_bitpos (bounds_type, i, 1),
4607 desc_bound_bitsize (bounds_type, i, 1));
4608 }
4609
4610 bounds = ensure_lval (bounds);
4611
4612 modify_field (descriptor->type (),
4613 descriptor->contents_writeable ().data (),
4614 value_pointer (ensure_lval (arr),
4615 desc_type->field (0).type ()),
4616 fat_pntr_data_bitpos (desc_type),
4617 fat_pntr_data_bitsize (desc_type));
4618
4619 modify_field (descriptor->type (),
4620 descriptor->contents_writeable ().data (),
4621 value_pointer (bounds,
4622 desc_type->field (1).type ()),
4623 fat_pntr_bounds_bitpos (desc_type),
4624 fat_pntr_bounds_bitsize (desc_type));
4625
4626 descriptor = ensure_lval (descriptor);
4627
4628 if (type->code () == TYPE_CODE_PTR)
4629 return value_addr (descriptor);
4630 else
4631 return descriptor;
4632 }
4633 \f
4634 /* Symbol Cache Module */
4635
4636 /* Performance measurements made as of 2010-01-15 indicate that
4637 this cache does bring some noticeable improvements. Depending
4638 on the type of entity being printed, the cache can make it as much
4639 as an order of magnitude faster than without it.
4640
4641 The descriptive type DWARF extension has significantly reduced
4642 the need for this cache, at least when DWARF is being used. However,
4643 even in this case, some expensive name-based symbol searches are still
4644 sometimes necessary - to find an XVZ variable, mostly. */
4645
4646 /* Return the symbol cache associated to the given program space PSPACE.
4647 If not allocated for this PSPACE yet, allocate and initialize one. */
4648
4649 static struct ada_symbol_cache *
4650 ada_get_symbol_cache (struct program_space *pspace)
4651 {
4652 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4653
4654 if (pspace_data->sym_cache == nullptr)
4655 pspace_data->sym_cache.reset (new ada_symbol_cache);
4656
4657 return pspace_data->sym_cache.get ();
4658 }
4659
4660 /* Clear all entries from the symbol cache. */
4661
4662 static void
4663 ada_clear_symbol_cache ()
4664 {
4665 struct ada_pspace_data *pspace_data
4666 = get_ada_pspace_data (current_program_space);
4667
4668 if (pspace_data->sym_cache != nullptr)
4669 pspace_data->sym_cache.reset ();
4670 }
4671
4672 /* Search our cache for an entry matching NAME and DOMAIN.
4673 Return it if found, or NULL otherwise. */
4674
4675 static struct cache_entry **
4676 find_entry (const char *name, domain_enum domain)
4677 {
4678 struct ada_symbol_cache *sym_cache
4679 = ada_get_symbol_cache (current_program_space);
4680 int h = msymbol_hash (name) % HASH_SIZE;
4681 struct cache_entry **e;
4682
4683 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4684 {
4685 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4686 return e;
4687 }
4688 return NULL;
4689 }
4690
4691 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4692 Return 1 if found, 0 otherwise.
4693
4694 If an entry was found and SYM is not NULL, set *SYM to the entry's
4695 SYM. Same principle for BLOCK if not NULL. */
4696
4697 static int
4698 lookup_cached_symbol (const char *name, domain_enum domain,
4699 struct symbol **sym, const struct block **block)
4700 {
4701 struct cache_entry **e = find_entry (name, domain);
4702
4703 if (e == NULL)
4704 return 0;
4705 if (sym != NULL)
4706 *sym = (*e)->sym;
4707 if (block != NULL)
4708 *block = (*e)->block;
4709 return 1;
4710 }
4711
4712 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4713 in domain DOMAIN, save this result in our symbol cache. */
4714
4715 static void
4716 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4717 const struct block *block)
4718 {
4719 struct ada_symbol_cache *sym_cache
4720 = ada_get_symbol_cache (current_program_space);
4721 int h;
4722 struct cache_entry *e;
4723
4724 /* Symbols for builtin types don't have a block.
4725 For now don't cache such symbols. */
4726 if (sym != NULL && !sym->is_objfile_owned ())
4727 return;
4728
4729 /* If the symbol is a local symbol, then do not cache it, as a search
4730 for that symbol depends on the context. To determine whether
4731 the symbol is local or not, we check the block where we found it
4732 against the global and static blocks of its associated symtab. */
4733 if (sym != nullptr)
4734 {
4735 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4736
4737 if (bv.global_block () != block && bv.static_block () != block)
4738 return;
4739 }
4740
4741 h = msymbol_hash (name) % HASH_SIZE;
4742 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4743 e->next = sym_cache->root[h];
4744 sym_cache->root[h] = e;
4745 e->name = obstack_strdup (&sym_cache->cache_space, name);
4746 e->sym = sym;
4747 e->domain = domain;
4748 e->block = block;
4749 }
4750 \f
4751 /* Symbol Lookup */
4752
4753 /* Return the symbol name match type that should be used used when
4754 searching for all symbols matching LOOKUP_NAME.
4755
4756 LOOKUP_NAME is expected to be a symbol name after transformation
4757 for Ada lookups. */
4758
4759 static symbol_name_match_type
4760 name_match_type_from_name (const char *lookup_name)
4761 {
4762 return (strstr (lookup_name, "__") == NULL
4763 ? symbol_name_match_type::WILD
4764 : symbol_name_match_type::FULL);
4765 }
4766
4767 /* Return the result of a standard (literal, C-like) lookup of NAME in
4768 given DOMAIN, visible from lexical block BLOCK. */
4769
4770 static struct symbol *
4771 standard_lookup (const char *name, const struct block *block,
4772 domain_enum domain)
4773 {
4774 /* Initialize it just to avoid a GCC false warning. */
4775 struct block_symbol sym = {};
4776
4777 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4778 return sym.symbol;
4779 ada_lookup_encoded_symbol (name, block, domain, &sym);
4780 cache_symbol (name, domain, sym.symbol, sym.block);
4781 return sym.symbol;
4782 }
4783
4784
4785 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4786 in the symbol fields of SYMS. We treat enumerals as functions,
4787 since they contend in overloading in the same way. */
4788 static int
4789 is_nonfunction (const std::vector<struct block_symbol> &syms)
4790 {
4791 for (const block_symbol &sym : syms)
4792 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4793 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4794 || sym.symbol->aclass () != LOC_CONST))
4795 return 1;
4796
4797 return 0;
4798 }
4799
4800 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4801 struct types. Otherwise, they may not. */
4802
4803 static int
4804 equiv_types (struct type *type0, struct type *type1)
4805 {
4806 if (type0 == type1)
4807 return 1;
4808 if (type0 == NULL || type1 == NULL
4809 || type0->code () != type1->code ())
4810 return 0;
4811 if ((type0->code () == TYPE_CODE_STRUCT
4812 || type0->code () == TYPE_CODE_ENUM)
4813 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4814 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4815 return 1;
4816
4817 return 0;
4818 }
4819
4820 /* True iff SYM0 represents the same entity as SYM1, or one that is
4821 no more defined than that of SYM1. */
4822
4823 static int
4824 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4825 {
4826 if (sym0 == sym1)
4827 return 1;
4828 if (sym0->domain () != sym1->domain ()
4829 || sym0->aclass () != sym1->aclass ())
4830 return 0;
4831
4832 switch (sym0->aclass ())
4833 {
4834 case LOC_UNDEF:
4835 return 1;
4836 case LOC_TYPEDEF:
4837 {
4838 struct type *type0 = sym0->type ();
4839 struct type *type1 = sym1->type ();
4840 const char *name0 = sym0->linkage_name ();
4841 const char *name1 = sym1->linkage_name ();
4842 int len0 = strlen (name0);
4843
4844 return
4845 type0->code () == type1->code ()
4846 && (equiv_types (type0, type1)
4847 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4848 && startswith (name1 + len0, "___XV")));
4849 }
4850 case LOC_CONST:
4851 return sym0->value_longest () == sym1->value_longest ()
4852 && equiv_types (sym0->type (), sym1->type ());
4853
4854 case LOC_STATIC:
4855 {
4856 const char *name0 = sym0->linkage_name ();
4857 const char *name1 = sym1->linkage_name ();
4858 return (strcmp (name0, name1) == 0
4859 && sym0->value_address () == sym1->value_address ());
4860 }
4861
4862 default:
4863 return 0;
4864 }
4865 }
4866
4867 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4868 records in RESULT. Do nothing if SYM is a duplicate. */
4869
4870 static void
4871 add_defn_to_vec (std::vector<struct block_symbol> &result,
4872 struct symbol *sym,
4873 const struct block *block)
4874 {
4875 /* Do not try to complete stub types, as the debugger is probably
4876 already scanning all symbols matching a certain name at the
4877 time when this function is called. Trying to replace the stub
4878 type by its associated full type will cause us to restart a scan
4879 which may lead to an infinite recursion. Instead, the client
4880 collecting the matching symbols will end up collecting several
4881 matches, with at least one of them complete. It can then filter
4882 out the stub ones if needed. */
4883
4884 for (int i = result.size () - 1; i >= 0; i -= 1)
4885 {
4886 if (lesseq_defined_than (sym, result[i].symbol))
4887 return;
4888 else if (lesseq_defined_than (result[i].symbol, sym))
4889 {
4890 result[i].symbol = sym;
4891 result[i].block = block;
4892 return;
4893 }
4894 }
4895
4896 struct block_symbol info;
4897 info.symbol = sym;
4898 info.block = block;
4899 result.push_back (info);
4900 }
4901
4902 /* Return a bound minimal symbol matching NAME according to Ada
4903 decoding rules. Returns an invalid symbol if there is no such
4904 minimal symbol. Names prefixed with "standard__" are handled
4905 specially: "standard__" is first stripped off, and only static and
4906 global symbols are searched. */
4907
4908 struct bound_minimal_symbol
4909 ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4910 {
4911 struct bound_minimal_symbol result;
4912
4913 symbol_name_match_type match_type = name_match_type_from_name (name);
4914 lookup_name_info lookup_name (name, match_type);
4915
4916 symbol_name_matcher_ftype *match_name
4917 = ada_get_symbol_name_matcher (lookup_name);
4918
4919 gdbarch_iterate_over_objfiles_in_search_order
4920 (objfile != NULL ? objfile->arch () : target_gdbarch (),
4921 [&result, lookup_name, match_name] (struct objfile *obj)
4922 {
4923 for (minimal_symbol *msymbol : obj->msymbols ())
4924 {
4925 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4926 && msymbol->type () != mst_solib_trampoline)
4927 {
4928 result.minsym = msymbol;
4929 result.objfile = obj;
4930 return 1;
4931 }
4932 }
4933
4934 return 0;
4935 }, objfile);
4936
4937 return result;
4938 }
4939
4940 /* True if TYPE is definitely an artificial type supplied to a symbol
4941 for which no debugging information was given in the symbol file. */
4942
4943 static int
4944 is_nondebugging_type (struct type *type)
4945 {
4946 const char *name = ada_type_name (type);
4947
4948 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4949 }
4950
4951 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4952 that are deemed "identical" for practical purposes.
4953
4954 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4955 types and that their number of enumerals is identical (in other
4956 words, type1->num_fields () == type2->num_fields ()). */
4957
4958 static int
4959 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4960 {
4961 int i;
4962
4963 /* The heuristic we use here is fairly conservative. We consider
4964 that 2 enumerate types are identical if they have the same
4965 number of enumerals and that all enumerals have the same
4966 underlying value and name. */
4967
4968 /* All enums in the type should have an identical underlying value. */
4969 for (i = 0; i < type1->num_fields (); i++)
4970 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4971 return 0;
4972
4973 /* All enumerals should also have the same name (modulo any numerical
4974 suffix). */
4975 for (i = 0; i < type1->num_fields (); i++)
4976 {
4977 const char *name_1 = type1->field (i).name ();
4978 const char *name_2 = type2->field (i).name ();
4979 int len_1 = strlen (name_1);
4980 int len_2 = strlen (name_2);
4981
4982 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4983 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4984 if (len_1 != len_2
4985 || strncmp (type1->field (i).name (),
4986 type2->field (i).name (),
4987 len_1) != 0)
4988 return 0;
4989 }
4990
4991 return 1;
4992 }
4993
4994 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4995 that are deemed "identical" for practical purposes. Sometimes,
4996 enumerals are not strictly identical, but their types are so similar
4997 that they can be considered identical.
4998
4999 For instance, consider the following code:
5000
5001 type Color is (Black, Red, Green, Blue, White);
5002 type RGB_Color is new Color range Red .. Blue;
5003
5004 Type RGB_Color is a subrange of an implicit type which is a copy
5005 of type Color. If we call that implicit type RGB_ColorB ("B" is
5006 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5007 As a result, when an expression references any of the enumeral
5008 by name (Eg. "print green"), the expression is technically
5009 ambiguous and the user should be asked to disambiguate. But
5010 doing so would only hinder the user, since it wouldn't matter
5011 what choice he makes, the outcome would always be the same.
5012 So, for practical purposes, we consider them as the same. */
5013
5014 static int
5015 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5016 {
5017 int i;
5018
5019 /* Before performing a thorough comparison check of each type,
5020 we perform a series of inexpensive checks. We expect that these
5021 checks will quickly fail in the vast majority of cases, and thus
5022 help prevent the unnecessary use of a more expensive comparison.
5023 Said comparison also expects us to make some of these checks
5024 (see ada_identical_enum_types_p). */
5025
5026 /* Quick check: All symbols should have an enum type. */
5027 for (i = 0; i < syms.size (); i++)
5028 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
5029 return 0;
5030
5031 /* Quick check: They should all have the same value. */
5032 for (i = 1; i < syms.size (); i++)
5033 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
5034 return 0;
5035
5036 /* Quick check: They should all have the same number of enumerals. */
5037 for (i = 1; i < syms.size (); i++)
5038 if (syms[i].symbol->type ()->num_fields ()
5039 != syms[0].symbol->type ()->num_fields ())
5040 return 0;
5041
5042 /* All the sanity checks passed, so we might have a set of
5043 identical enumeration types. Perform a more complete
5044 comparison of the type of each symbol. */
5045 for (i = 1; i < syms.size (); i++)
5046 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5047 syms[0].symbol->type ()))
5048 return 0;
5049
5050 return 1;
5051 }
5052
5053 /* Remove any non-debugging symbols in SYMS that definitely
5054 duplicate other symbols in the list (The only case I know of where
5055 this happens is when object files containing stabs-in-ecoff are
5056 linked with files containing ordinary ecoff debugging symbols (or no
5057 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5058
5059 static void
5060 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5061 {
5062 int i, j;
5063
5064 /* We should never be called with less than 2 symbols, as there
5065 cannot be any extra symbol in that case. But it's easy to
5066 handle, since we have nothing to do in that case. */
5067 if (syms->size () < 2)
5068 return;
5069
5070 i = 0;
5071 while (i < syms->size ())
5072 {
5073 int remove_p = 0;
5074
5075 /* If two symbols have the same name and one of them is a stub type,
5076 the get rid of the stub. */
5077
5078 if ((*syms)[i].symbol->type ()->is_stub ()
5079 && (*syms)[i].symbol->linkage_name () != NULL)
5080 {
5081 for (j = 0; j < syms->size (); j++)
5082 {
5083 if (j != i
5084 && !(*syms)[j].symbol->type ()->is_stub ()
5085 && (*syms)[j].symbol->linkage_name () != NULL
5086 && strcmp ((*syms)[i].symbol->linkage_name (),
5087 (*syms)[j].symbol->linkage_name ()) == 0)
5088 remove_p = 1;
5089 }
5090 }
5091
5092 /* Two symbols with the same name, same class and same address
5093 should be identical. */
5094
5095 else if ((*syms)[i].symbol->linkage_name () != NULL
5096 && (*syms)[i].symbol->aclass () == LOC_STATIC
5097 && is_nondebugging_type ((*syms)[i].symbol->type ()))
5098 {
5099 for (j = 0; j < syms->size (); j += 1)
5100 {
5101 if (i != j
5102 && (*syms)[j].symbol->linkage_name () != NULL
5103 && strcmp ((*syms)[i].symbol->linkage_name (),
5104 (*syms)[j].symbol->linkage_name ()) == 0
5105 && ((*syms)[i].symbol->aclass ()
5106 == (*syms)[j].symbol->aclass ())
5107 && (*syms)[i].symbol->value_address ()
5108 == (*syms)[j].symbol->value_address ())
5109 remove_p = 1;
5110 }
5111 }
5112
5113 if (remove_p)
5114 syms->erase (syms->begin () + i);
5115 else
5116 i += 1;
5117 }
5118
5119 /* If all the remaining symbols are identical enumerals, then
5120 just keep the first one and discard the rest.
5121
5122 Unlike what we did previously, we do not discard any entry
5123 unless they are ALL identical. This is because the symbol
5124 comparison is not a strict comparison, but rather a practical
5125 comparison. If all symbols are considered identical, then
5126 we can just go ahead and use the first one and discard the rest.
5127 But if we cannot reduce the list to a single element, we have
5128 to ask the user to disambiguate anyways. And if we have to
5129 present a multiple-choice menu, it's less confusing if the list
5130 isn't missing some choices that were identical and yet distinct. */
5131 if (symbols_are_identical_enums (*syms))
5132 syms->resize (1);
5133 }
5134
5135 /* Given a type that corresponds to a renaming entity, use the type name
5136 to extract the scope (package name or function name, fully qualified,
5137 and following the GNAT encoding convention) where this renaming has been
5138 defined. */
5139
5140 static std::string
5141 xget_renaming_scope (struct type *renaming_type)
5142 {
5143 /* The renaming types adhere to the following convention:
5144 <scope>__<rename>___<XR extension>.
5145 So, to extract the scope, we search for the "___XR" extension,
5146 and then backtrack until we find the first "__". */
5147
5148 const char *name = renaming_type->name ();
5149 const char *suffix = strstr (name, "___XR");
5150 const char *last;
5151
5152 /* Now, backtrack a bit until we find the first "__". Start looking
5153 at suffix - 3, as the <rename> part is at least one character long. */
5154
5155 for (last = suffix - 3; last > name; last--)
5156 if (last[0] == '_' && last[1] == '_')
5157 break;
5158
5159 /* Make a copy of scope and return it. */
5160 return std::string (name, last);
5161 }
5162
5163 /* Return nonzero if NAME corresponds to a package name. */
5164
5165 static int
5166 is_package_name (const char *name)
5167 {
5168 /* Here, We take advantage of the fact that no symbols are generated
5169 for packages, while symbols are generated for each function.
5170 So the condition for NAME represent a package becomes equivalent
5171 to NAME not existing in our list of symbols. There is only one
5172 small complication with library-level functions (see below). */
5173
5174 /* If it is a function that has not been defined at library level,
5175 then we should be able to look it up in the symbols. */
5176 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5177 return 0;
5178
5179 /* Library-level function names start with "_ada_". See if function
5180 "_ada_" followed by NAME can be found. */
5181
5182 /* Do a quick check that NAME does not contain "__", since library-level
5183 functions names cannot contain "__" in them. */
5184 if (strstr (name, "__") != NULL)
5185 return 0;
5186
5187 std::string fun_name = string_printf ("_ada_%s", name);
5188
5189 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5190 }
5191
5192 /* Return nonzero if SYM corresponds to a renaming entity that is
5193 not visible from FUNCTION_NAME. */
5194
5195 static int
5196 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5197 {
5198 if (sym->aclass () != LOC_TYPEDEF)
5199 return 0;
5200
5201 std::string scope = xget_renaming_scope (sym->type ());
5202
5203 /* If the rename has been defined in a package, then it is visible. */
5204 if (is_package_name (scope.c_str ()))
5205 return 0;
5206
5207 /* Check that the rename is in the current function scope by checking
5208 that its name starts with SCOPE. */
5209
5210 /* If the function name starts with "_ada_", it means that it is
5211 a library-level function. Strip this prefix before doing the
5212 comparison, as the encoding for the renaming does not contain
5213 this prefix. */
5214 if (startswith (function_name, "_ada_"))
5215 function_name += 5;
5216
5217 return !startswith (function_name, scope.c_str ());
5218 }
5219
5220 /* Remove entries from SYMS that corresponds to a renaming entity that
5221 is not visible from the function associated with CURRENT_BLOCK or
5222 that is superfluous due to the presence of more specific renaming
5223 information. Places surviving symbols in the initial entries of
5224 SYMS.
5225
5226 Rationale:
5227 First, in cases where an object renaming is implemented as a
5228 reference variable, GNAT may produce both the actual reference
5229 variable and the renaming encoding. In this case, we discard the
5230 latter.
5231
5232 Second, GNAT emits a type following a specified encoding for each renaming
5233 entity. Unfortunately, STABS currently does not support the definition
5234 of types that are local to a given lexical block, so all renamings types
5235 are emitted at library level. As a consequence, if an application
5236 contains two renaming entities using the same name, and a user tries to
5237 print the value of one of these entities, the result of the ada symbol
5238 lookup will also contain the wrong renaming type.
5239
5240 This function partially covers for this limitation by attempting to
5241 remove from the SYMS list renaming symbols that should be visible
5242 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5243 method with the current information available. The implementation
5244 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5245
5246 - When the user tries to print a rename in a function while there
5247 is another rename entity defined in a package: Normally, the
5248 rename in the function has precedence over the rename in the
5249 package, so the latter should be removed from the list. This is
5250 currently not the case.
5251
5252 - This function will incorrectly remove valid renames if
5253 the CURRENT_BLOCK corresponds to a function which symbol name
5254 has been changed by an "Export" pragma. As a consequence,
5255 the user will be unable to print such rename entities. */
5256
5257 static void
5258 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5259 const struct block *current_block)
5260 {
5261 struct symbol *current_function;
5262 const char *current_function_name;
5263 int i;
5264 int is_new_style_renaming;
5265
5266 /* If there is both a renaming foo___XR... encoded as a variable and
5267 a simple variable foo in the same block, discard the latter.
5268 First, zero out such symbols, then compress. */
5269 is_new_style_renaming = 0;
5270 for (i = 0; i < syms->size (); i += 1)
5271 {
5272 struct symbol *sym = (*syms)[i].symbol;
5273 const struct block *block = (*syms)[i].block;
5274 const char *name;
5275 const char *suffix;
5276
5277 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
5278 continue;
5279 name = sym->linkage_name ();
5280 suffix = strstr (name, "___XR");
5281
5282 if (suffix != NULL)
5283 {
5284 int name_len = suffix - name;
5285 int j;
5286
5287 is_new_style_renaming = 1;
5288 for (j = 0; j < syms->size (); j += 1)
5289 if (i != j && (*syms)[j].symbol != NULL
5290 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5291 name_len) == 0
5292 && block == (*syms)[j].block)
5293 (*syms)[j].symbol = NULL;
5294 }
5295 }
5296 if (is_new_style_renaming)
5297 {
5298 int j, k;
5299
5300 for (j = k = 0; j < syms->size (); j += 1)
5301 if ((*syms)[j].symbol != NULL)
5302 {
5303 (*syms)[k] = (*syms)[j];
5304 k += 1;
5305 }
5306 syms->resize (k);
5307 return;
5308 }
5309
5310 /* Extract the function name associated to CURRENT_BLOCK.
5311 Abort if unable to do so. */
5312
5313 if (current_block == NULL)
5314 return;
5315
5316 current_function = current_block->linkage_function ();
5317 if (current_function == NULL)
5318 return;
5319
5320 current_function_name = current_function->linkage_name ();
5321 if (current_function_name == NULL)
5322 return;
5323
5324 /* Check each of the symbols, and remove it from the list if it is
5325 a type corresponding to a renaming that is out of the scope of
5326 the current block. */
5327
5328 i = 0;
5329 while (i < syms->size ())
5330 {
5331 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5332 == ADA_OBJECT_RENAMING
5333 && old_renaming_is_invisible ((*syms)[i].symbol,
5334 current_function_name))
5335 syms->erase (syms->begin () + i);
5336 else
5337 i += 1;
5338 }
5339 }
5340
5341 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5342 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
5343
5344 Note: This function assumes that RESULT is empty. */
5345
5346 static void
5347 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5348 const lookup_name_info &lookup_name,
5349 const struct block *block, domain_enum domain)
5350 {
5351 while (block != NULL)
5352 {
5353 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5354
5355 /* If we found a non-function match, assume that's the one. We
5356 only check this when finding a function boundary, so that we
5357 can accumulate all results from intervening blocks first. */
5358 if (block->function () != nullptr && is_nonfunction (result))
5359 return;
5360
5361 block = block->superblock ();
5362 }
5363 }
5364
5365 /* An object of this type is used as the callback argument when
5366 calling the map_matching_symbols method. */
5367
5368 struct match_data
5369 {
5370 explicit match_data (std::vector<struct block_symbol> *rp)
5371 : resultp (rp)
5372 {
5373 }
5374 DISABLE_COPY_AND_ASSIGN (match_data);
5375
5376 bool operator() (struct block_symbol *bsym);
5377
5378 struct objfile *objfile = nullptr;
5379 std::vector<struct block_symbol> *resultp;
5380 struct symbol *arg_sym = nullptr;
5381 bool found_sym = false;
5382 };
5383
5384 /* A callback for add_nonlocal_symbols that adds symbol, found in
5385 BSYM, to a list of symbols. */
5386
5387 bool
5388 match_data::operator() (struct block_symbol *bsym)
5389 {
5390 const struct block *block = bsym->block;
5391 struct symbol *sym = bsym->symbol;
5392
5393 if (sym == NULL)
5394 {
5395 if (!found_sym && arg_sym != NULL)
5396 add_defn_to_vec (*resultp, arg_sym, block);
5397 found_sym = false;
5398 arg_sym = NULL;
5399 }
5400 else
5401 {
5402 if (sym->aclass () == LOC_UNRESOLVED)
5403 return true;
5404 else if (sym->is_argument ())
5405 arg_sym = sym;
5406 else
5407 {
5408 found_sym = true;
5409 add_defn_to_vec (*resultp, sym, block);
5410 }
5411 }
5412 return true;
5413 }
5414
5415 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5416 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5417 symbols to RESULT. Return whether we found such symbols. */
5418
5419 static int
5420 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5421 const struct block *block,
5422 const lookup_name_info &lookup_name,
5423 domain_enum domain)
5424 {
5425 struct using_direct *renaming;
5426 int defns_mark = result.size ();
5427
5428 symbol_name_matcher_ftype *name_match
5429 = ada_get_symbol_name_matcher (lookup_name);
5430
5431 for (renaming = block->get_using ();
5432 renaming != NULL;
5433 renaming = renaming->next)
5434 {
5435 const char *r_name;
5436
5437 /* Avoid infinite recursions: skip this renaming if we are actually
5438 already traversing it.
5439
5440 Currently, symbol lookup in Ada don't use the namespace machinery from
5441 C++/Fortran support: skip namespace imports that use them. */
5442 if (renaming->searched
5443 || (renaming->import_src != NULL
5444 && renaming->import_src[0] != '\0')
5445 || (renaming->import_dest != NULL
5446 && renaming->import_dest[0] != '\0'))
5447 continue;
5448 renaming->searched = 1;
5449
5450 /* TODO: here, we perform another name-based symbol lookup, which can
5451 pull its own multiple overloads. In theory, we should be able to do
5452 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5453 not a simple name. But in order to do this, we would need to enhance
5454 the DWARF reader to associate a symbol to this renaming, instead of a
5455 name. So, for now, we do something simpler: re-use the C++/Fortran
5456 namespace machinery. */
5457 r_name = (renaming->alias != NULL
5458 ? renaming->alias
5459 : renaming->declaration);
5460 if (name_match (r_name, lookup_name, NULL))
5461 {
5462 lookup_name_info decl_lookup_name (renaming->declaration,
5463 lookup_name.match_type ());
5464 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5465 1, NULL);
5466 }
5467 renaming->searched = 0;
5468 }
5469 return result.size () != defns_mark;
5470 }
5471
5472 /* Implements compare_names, but only applying the comparision using
5473 the given CASING. */
5474
5475 static int
5476 compare_names_with_case (const char *string1, const char *string2,
5477 enum case_sensitivity casing)
5478 {
5479 while (*string1 != '\0' && *string2 != '\0')
5480 {
5481 char c1, c2;
5482
5483 if (isspace (*string1) || isspace (*string2))
5484 return strcmp_iw_ordered (string1, string2);
5485
5486 if (casing == case_sensitive_off)
5487 {
5488 c1 = tolower (*string1);
5489 c2 = tolower (*string2);
5490 }
5491 else
5492 {
5493 c1 = *string1;
5494 c2 = *string2;
5495 }
5496 if (c1 != c2)
5497 break;
5498
5499 string1 += 1;
5500 string2 += 1;
5501 }
5502
5503 switch (*string1)
5504 {
5505 case '(':
5506 return strcmp_iw_ordered (string1, string2);
5507 case '_':
5508 if (*string2 == '\0')
5509 {
5510 if (is_name_suffix (string1))
5511 return 0;
5512 else
5513 return 1;
5514 }
5515 /* FALLTHROUGH */
5516 default:
5517 if (*string2 == '(')
5518 return strcmp_iw_ordered (string1, string2);
5519 else
5520 {
5521 if (casing == case_sensitive_off)
5522 return tolower (*string1) - tolower (*string2);
5523 else
5524 return *string1 - *string2;
5525 }
5526 }
5527 }
5528
5529 /* Compare STRING1 to STRING2, with results as for strcmp.
5530 Compatible with strcmp_iw_ordered in that...
5531
5532 strcmp_iw_ordered (STRING1, STRING2) <= 0
5533
5534 ... implies...
5535
5536 compare_names (STRING1, STRING2) <= 0
5537
5538 (they may differ as to what symbols compare equal). */
5539
5540 static int
5541 compare_names (const char *string1, const char *string2)
5542 {
5543 int result;
5544
5545 /* Similar to what strcmp_iw_ordered does, we need to perform
5546 a case-insensitive comparison first, and only resort to
5547 a second, case-sensitive, comparison if the first one was
5548 not sufficient to differentiate the two strings. */
5549
5550 result = compare_names_with_case (string1, string2, case_sensitive_off);
5551 if (result == 0)
5552 result = compare_names_with_case (string1, string2, case_sensitive_on);
5553
5554 return result;
5555 }
5556
5557 /* Convenience function to get at the Ada encoded lookup name for
5558 LOOKUP_NAME, as a C string. */
5559
5560 static const char *
5561 ada_lookup_name (const lookup_name_info &lookup_name)
5562 {
5563 return lookup_name.ada ().lookup_name ().c_str ();
5564 }
5565
5566 /* A helper for add_nonlocal_symbols. Call expand_matching_symbols
5567 for OBJFILE, then walk the objfile's symtabs and update the
5568 results. */
5569
5570 static void
5571 map_matching_symbols (struct objfile *objfile,
5572 const lookup_name_info &lookup_name,
5573 bool is_wild_match,
5574 domain_enum domain,
5575 int global,
5576 match_data &data)
5577 {
5578 data.objfile = objfile;
5579 objfile->expand_matching_symbols (lookup_name, domain, global,
5580 is_wild_match ? nullptr : compare_names);
5581
5582 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5583 for (compunit_symtab *symtab : objfile->compunits ())
5584 {
5585 const struct block *block
5586 = symtab->blockvector ()->block (block_kind);
5587 if (!iterate_over_symbols_terminated (block, lookup_name,
5588 domain, data))
5589 break;
5590 }
5591 }
5592
5593 /* Add to RESULT all non-local symbols whose name and domain match
5594 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5595 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5596 symbols otherwise. */
5597
5598 static void
5599 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5600 const lookup_name_info &lookup_name,
5601 domain_enum domain, int global)
5602 {
5603 struct match_data data (&result);
5604
5605 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5606
5607 for (objfile *objfile : current_program_space->objfiles ())
5608 {
5609 map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5610 global, data);
5611
5612 for (compunit_symtab *cu : objfile->compunits ())
5613 {
5614 const struct block *global_block
5615 = cu->blockvector ()->global_block ();
5616
5617 if (ada_add_block_renamings (result, global_block, lookup_name,
5618 domain))
5619 data.found_sym = true;
5620 }
5621 }
5622
5623 if (result.empty () && global && !is_wild_match)
5624 {
5625 const char *name = ada_lookup_name (lookup_name);
5626 std::string bracket_name = std::string ("<_ada_") + name + '>';
5627 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5628
5629 for (objfile *objfile : current_program_space->objfiles ())
5630 map_matching_symbols (objfile, name1, false, domain, global, data);
5631 }
5632 }
5633
5634 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5635 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5636 returning the number of matches. Add these to RESULT.
5637
5638 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5639 symbol match within the nest of blocks whose innermost member is BLOCK,
5640 is the one match returned (no other matches in that or
5641 enclosing blocks is returned). If there are any matches in or
5642 surrounding BLOCK, then these alone are returned.
5643
5644 Names prefixed with "standard__" are handled specially:
5645 "standard__" is first stripped off (by the lookup_name
5646 constructor), and only static and global symbols are searched.
5647
5648 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5649 to lookup global symbols. */
5650
5651 static void
5652 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5653 const struct block *block,
5654 const lookup_name_info &lookup_name,
5655 domain_enum domain,
5656 int full_search,
5657 int *made_global_lookup_p)
5658 {
5659 struct symbol *sym;
5660
5661 if (made_global_lookup_p)
5662 *made_global_lookup_p = 0;
5663
5664 /* Special case: If the user specifies a symbol name inside package
5665 Standard, do a non-wild matching of the symbol name without
5666 the "standard__" prefix. This was primarily introduced in order
5667 to allow the user to specifically access the standard exceptions
5668 using, for instance, Standard.Constraint_Error when Constraint_Error
5669 is ambiguous (due to the user defining its own Constraint_Error
5670 entity inside its program). */
5671 if (lookup_name.ada ().standard_p ())
5672 block = NULL;
5673
5674 /* Check the non-global symbols. If we have ANY match, then we're done. */
5675
5676 if (block != NULL)
5677 {
5678 if (full_search)
5679 ada_add_local_symbols (result, lookup_name, block, domain);
5680 else
5681 {
5682 /* In the !full_search case we're are being called by
5683 iterate_over_symbols, and we don't want to search
5684 superblocks. */
5685 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5686 }
5687 if (!result.empty () || !full_search)
5688 return;
5689 }
5690
5691 /* No non-global symbols found. Check our cache to see if we have
5692 already performed this search before. If we have, then return
5693 the same result. */
5694
5695 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5696 domain, &sym, &block))
5697 {
5698 if (sym != NULL)
5699 add_defn_to_vec (result, sym, block);
5700 return;
5701 }
5702
5703 if (made_global_lookup_p)
5704 *made_global_lookup_p = 1;
5705
5706 /* Search symbols from all global blocks. */
5707
5708 add_nonlocal_symbols (result, lookup_name, domain, 1);
5709
5710 /* Now add symbols from all per-file blocks if we've gotten no hits
5711 (not strictly correct, but perhaps better than an error). */
5712
5713 if (result.empty ())
5714 add_nonlocal_symbols (result, lookup_name, domain, 0);
5715 }
5716
5717 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5718 is non-zero, enclosing scope and in global scopes.
5719
5720 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5721 blocks and symbol tables (if any) in which they were found.
5722
5723 When full_search is non-zero, any non-function/non-enumeral
5724 symbol match within the nest of blocks whose innermost member is BLOCK,
5725 is the one match returned (no other matches in that or
5726 enclosing blocks is returned). If there are any matches in or
5727 surrounding BLOCK, then these alone are returned.
5728
5729 Names prefixed with "standard__" are handled specially: "standard__"
5730 is first stripped off, and only static and global symbols are searched. */
5731
5732 static std::vector<struct block_symbol>
5733 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5734 const struct block *block,
5735 domain_enum domain,
5736 int full_search)
5737 {
5738 int syms_from_global_search;
5739 std::vector<struct block_symbol> results;
5740
5741 ada_add_all_symbols (results, block, lookup_name,
5742 domain, full_search, &syms_from_global_search);
5743
5744 remove_extra_symbols (&results);
5745
5746 if (results.empty () && full_search && syms_from_global_search)
5747 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5748
5749 if (results.size () == 1 && full_search && syms_from_global_search)
5750 cache_symbol (ada_lookup_name (lookup_name), domain,
5751 results[0].symbol, results[0].block);
5752
5753 remove_irrelevant_renamings (&results, block);
5754 return results;
5755 }
5756
5757 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5758 in global scopes, returning (SYM,BLOCK) tuples.
5759
5760 See ada_lookup_symbol_list_worker for further details. */
5761
5762 std::vector<struct block_symbol>
5763 ada_lookup_symbol_list (const char *name, const struct block *block,
5764 domain_enum domain)
5765 {
5766 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5767 lookup_name_info lookup_name (name, name_match_type);
5768
5769 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5770 }
5771
5772 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5773 to 1, but choosing the first symbol found if there are multiple
5774 choices.
5775
5776 The result is stored in *INFO, which must be non-NULL.
5777 If no match is found, INFO->SYM is set to NULL. */
5778
5779 void
5780 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5781 domain_enum domain,
5782 struct block_symbol *info)
5783 {
5784 /* Since we already have an encoded name, wrap it in '<>' to force a
5785 verbatim match. Otherwise, if the name happens to not look like
5786 an encoded name (because it doesn't include a "__"),
5787 ada_lookup_name_info would re-encode/fold it again, and that
5788 would e.g., incorrectly lowercase object renaming names like
5789 "R28b" -> "r28b". */
5790 std::string verbatim = add_angle_brackets (name);
5791
5792 gdb_assert (info != NULL);
5793 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5794 }
5795
5796 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5797 scope and in global scopes, or NULL if none. NAME is folded and
5798 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5799 choosing the first symbol if there are multiple choices. */
5800
5801 struct block_symbol
5802 ada_lookup_symbol (const char *name, const struct block *block0,
5803 domain_enum domain)
5804 {
5805 std::vector<struct block_symbol> candidates
5806 = ada_lookup_symbol_list (name, block0, domain);
5807
5808 if (candidates.empty ())
5809 return {};
5810
5811 return candidates[0];
5812 }
5813
5814
5815 /* True iff STR is a possible encoded suffix of a normal Ada name
5816 that is to be ignored for matching purposes. Suffixes of parallel
5817 names (e.g., XVE) are not included here. Currently, the possible suffixes
5818 are given by any of the regular expressions:
5819
5820 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5821 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5822 TKB [subprogram suffix for task bodies]
5823 _E[0-9]+[bs]$ [protected object entry suffixes]
5824 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5825
5826 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5827 match is performed. This sequence is used to differentiate homonyms,
5828 is an optional part of a valid name suffix. */
5829
5830 static int
5831 is_name_suffix (const char *str)
5832 {
5833 int k;
5834 const char *matching;
5835 const int len = strlen (str);
5836
5837 /* Skip optional leading __[0-9]+. */
5838
5839 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5840 {
5841 str += 3;
5842 while (isdigit (str[0]))
5843 str += 1;
5844 }
5845
5846 /* [.$][0-9]+ */
5847
5848 if (str[0] == '.' || str[0] == '$')
5849 {
5850 matching = str + 1;
5851 while (isdigit (matching[0]))
5852 matching += 1;
5853 if (matching[0] == '\0')
5854 return 1;
5855 }
5856
5857 /* ___[0-9]+ */
5858
5859 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5860 {
5861 matching = str + 3;
5862 while (isdigit (matching[0]))
5863 matching += 1;
5864 if (matching[0] == '\0')
5865 return 1;
5866 }
5867
5868 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5869
5870 if (strcmp (str, "TKB") == 0)
5871 return 1;
5872
5873 #if 0
5874 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5875 with a N at the end. Unfortunately, the compiler uses the same
5876 convention for other internal types it creates. So treating
5877 all entity names that end with an "N" as a name suffix causes
5878 some regressions. For instance, consider the case of an enumerated
5879 type. To support the 'Image attribute, it creates an array whose
5880 name ends with N.
5881 Having a single character like this as a suffix carrying some
5882 information is a bit risky. Perhaps we should change the encoding
5883 to be something like "_N" instead. In the meantime, do not do
5884 the following check. */
5885 /* Protected Object Subprograms */
5886 if (len == 1 && str [0] == 'N')
5887 return 1;
5888 #endif
5889
5890 /* _E[0-9]+[bs]$ */
5891 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5892 {
5893 matching = str + 3;
5894 while (isdigit (matching[0]))
5895 matching += 1;
5896 if ((matching[0] == 'b' || matching[0] == 's')
5897 && matching [1] == '\0')
5898 return 1;
5899 }
5900
5901 /* ??? We should not modify STR directly, as we are doing below. This
5902 is fine in this case, but may become problematic later if we find
5903 that this alternative did not work, and want to try matching
5904 another one from the begining of STR. Since we modified it, we
5905 won't be able to find the begining of the string anymore! */
5906 if (str[0] == 'X')
5907 {
5908 str += 1;
5909 while (str[0] != '_' && str[0] != '\0')
5910 {
5911 if (str[0] != 'n' && str[0] != 'b')
5912 return 0;
5913 str += 1;
5914 }
5915 }
5916
5917 if (str[0] == '\000')
5918 return 1;
5919
5920 if (str[0] == '_')
5921 {
5922 if (str[1] != '_' || str[2] == '\000')
5923 return 0;
5924 if (str[2] == '_')
5925 {
5926 if (strcmp (str + 3, "JM") == 0)
5927 return 1;
5928 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5929 the LJM suffix in favor of the JM one. But we will
5930 still accept LJM as a valid suffix for a reasonable
5931 amount of time, just to allow ourselves to debug programs
5932 compiled using an older version of GNAT. */
5933 if (strcmp (str + 3, "LJM") == 0)
5934 return 1;
5935 if (str[3] != 'X')
5936 return 0;
5937 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5938 || str[4] == 'U' || str[4] == 'P')
5939 return 1;
5940 if (str[4] == 'R' && str[5] != 'T')
5941 return 1;
5942 return 0;
5943 }
5944 if (!isdigit (str[2]))
5945 return 0;
5946 for (k = 3; str[k] != '\0'; k += 1)
5947 if (!isdigit (str[k]) && str[k] != '_')
5948 return 0;
5949 return 1;
5950 }
5951 if (str[0] == '$' && isdigit (str[1]))
5952 {
5953 for (k = 2; str[k] != '\0'; k += 1)
5954 if (!isdigit (str[k]) && str[k] != '_')
5955 return 0;
5956 return 1;
5957 }
5958 return 0;
5959 }
5960
5961 /* Return non-zero if the string starting at NAME and ending before
5962 NAME_END contains no capital letters. */
5963
5964 static int
5965 is_valid_name_for_wild_match (const char *name0)
5966 {
5967 std::string decoded_name = ada_decode (name0);
5968 int i;
5969
5970 /* If the decoded name starts with an angle bracket, it means that
5971 NAME0 does not follow the GNAT encoding format. It should then
5972 not be allowed as a possible wild match. */
5973 if (decoded_name[0] == '<')
5974 return 0;
5975
5976 for (i=0; decoded_name[i] != '\0'; i++)
5977 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5978 return 0;
5979
5980 return 1;
5981 }
5982
5983 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5984 character which could start a simple name. Assumes that *NAMEP points
5985 somewhere inside the string beginning at NAME0. */
5986
5987 static int
5988 advance_wild_match (const char **namep, const char *name0, char target0)
5989 {
5990 const char *name = *namep;
5991
5992 while (1)
5993 {
5994 char t0, t1;
5995
5996 t0 = *name;
5997 if (t0 == '_')
5998 {
5999 t1 = name[1];
6000 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
6001 {
6002 name += 1;
6003 if (name == name0 + 5 && startswith (name0, "_ada"))
6004 break;
6005 else
6006 name += 1;
6007 }
6008 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6009 || name[2] == target0))
6010 {
6011 name += 2;
6012 break;
6013 }
6014 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
6015 {
6016 /* Names like "pkg__B_N__name", where N is a number, are
6017 block-local. We can handle these by simply skipping
6018 the "B_" here. */
6019 name += 4;
6020 }
6021 else
6022 return 0;
6023 }
6024 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6025 name += 1;
6026 else
6027 return 0;
6028 }
6029
6030 *namep = name;
6031 return 1;
6032 }
6033
6034 /* Return true iff NAME encodes a name of the form prefix.PATN.
6035 Ignores any informational suffixes of NAME (i.e., for which
6036 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6037 simple name. */
6038
6039 static bool
6040 wild_match (const char *name, const char *patn)
6041 {
6042 const char *p;
6043 const char *name0 = name;
6044
6045 if (startswith (name, "___ghost_"))
6046 name += 9;
6047
6048 while (1)
6049 {
6050 const char *match = name;
6051
6052 if (*name == *patn)
6053 {
6054 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6055 if (*p != *name)
6056 break;
6057 if (*p == '\0' && is_name_suffix (name))
6058 return match == name0 || is_valid_name_for_wild_match (name0);
6059
6060 if (name[-1] == '_')
6061 name -= 1;
6062 }
6063 if (!advance_wild_match (&name, name0, *patn))
6064 return false;
6065 }
6066 }
6067
6068 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6069 necessary). OBJFILE is the section containing BLOCK. */
6070
6071 static void
6072 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6073 const struct block *block,
6074 const lookup_name_info &lookup_name,
6075 domain_enum domain, struct objfile *objfile)
6076 {
6077 /* A matching argument symbol, if any. */
6078 struct symbol *arg_sym;
6079 /* Set true when we find a matching non-argument symbol. */
6080 bool found_sym;
6081
6082 arg_sym = NULL;
6083 found_sym = false;
6084 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
6085 {
6086 if (symbol_matches_domain (sym->language (), sym->domain (), domain))
6087 {
6088 if (sym->aclass () != LOC_UNRESOLVED)
6089 {
6090 if (sym->is_argument ())
6091 arg_sym = sym;
6092 else
6093 {
6094 found_sym = true;
6095 add_defn_to_vec (result, sym, block);
6096 }
6097 }
6098 }
6099 }
6100
6101 /* Handle renamings. */
6102
6103 if (ada_add_block_renamings (result, block, lookup_name, domain))
6104 found_sym = true;
6105
6106 if (!found_sym && arg_sym != NULL)
6107 {
6108 add_defn_to_vec (result, arg_sym, block);
6109 }
6110
6111 if (!lookup_name.ada ().wild_match_p ())
6112 {
6113 arg_sym = NULL;
6114 found_sym = false;
6115 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6116 const char *name = ada_lookup_name.c_str ();
6117 size_t name_len = ada_lookup_name.size ();
6118
6119 for (struct symbol *sym : block_iterator_range (block))
6120 {
6121 if (symbol_matches_domain (sym->language (),
6122 sym->domain (), domain))
6123 {
6124 int cmp;
6125
6126 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6127 if (cmp == 0)
6128 {
6129 cmp = !startswith (sym->linkage_name (), "_ada_");
6130 if (cmp == 0)
6131 cmp = strncmp (name, sym->linkage_name () + 5,
6132 name_len);
6133 }
6134
6135 if (cmp == 0
6136 && is_name_suffix (sym->linkage_name () + name_len + 5))
6137 {
6138 if (sym->aclass () != LOC_UNRESOLVED)
6139 {
6140 if (sym->is_argument ())
6141 arg_sym = sym;
6142 else
6143 {
6144 found_sym = true;
6145 add_defn_to_vec (result, sym, block);
6146 }
6147 }
6148 }
6149 }
6150 }
6151
6152 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6153 They aren't parameters, right? */
6154 if (!found_sym && arg_sym != NULL)
6155 {
6156 add_defn_to_vec (result, arg_sym, block);
6157 }
6158 }
6159 }
6160 \f
6161
6162 /* Symbol Completion */
6163
6164 /* See symtab.h. */
6165
6166 bool
6167 ada_lookup_name_info::matches
6168 (const char *sym_name,
6169 symbol_name_match_type match_type,
6170 completion_match_result *comp_match_res) const
6171 {
6172 bool match = false;
6173 const char *text = m_encoded_name.c_str ();
6174 size_t text_len = m_encoded_name.size ();
6175
6176 /* First, test against the fully qualified name of the symbol. */
6177
6178 if (strncmp (sym_name, text, text_len) == 0)
6179 match = true;
6180
6181 std::string decoded_name = ada_decode (sym_name);
6182 if (match && !m_encoded_p)
6183 {
6184 /* One needed check before declaring a positive match is to verify
6185 that iff we are doing a verbatim match, the decoded version
6186 of the symbol name starts with '<'. Otherwise, this symbol name
6187 is not a suitable completion. */
6188
6189 bool has_angle_bracket = (decoded_name[0] == '<');
6190 match = (has_angle_bracket == m_verbatim_p);
6191 }
6192
6193 if (match && !m_verbatim_p)
6194 {
6195 /* When doing non-verbatim match, another check that needs to
6196 be done is to verify that the potentially matching symbol name
6197 does not include capital letters, because the ada-mode would
6198 not be able to understand these symbol names without the
6199 angle bracket notation. */
6200 const char *tmp;
6201
6202 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6203 if (*tmp != '\0')
6204 match = false;
6205 }
6206
6207 /* Second: Try wild matching... */
6208
6209 if (!match && m_wild_match_p)
6210 {
6211 /* Since we are doing wild matching, this means that TEXT
6212 may represent an unqualified symbol name. We therefore must
6213 also compare TEXT against the unqualified name of the symbol. */
6214 sym_name = ada_unqualified_name (decoded_name.c_str ());
6215
6216 if (strncmp (sym_name, text, text_len) == 0)
6217 match = true;
6218 }
6219
6220 /* Finally: If we found a match, prepare the result to return. */
6221
6222 if (!match)
6223 return false;
6224
6225 if (comp_match_res != NULL)
6226 {
6227 std::string &match_str = comp_match_res->match.storage ();
6228
6229 if (!m_encoded_p)
6230 match_str = ada_decode (sym_name);
6231 else
6232 {
6233 if (m_verbatim_p)
6234 match_str = add_angle_brackets (sym_name);
6235 else
6236 match_str = sym_name;
6237
6238 }
6239
6240 comp_match_res->set_match (match_str.c_str ());
6241 }
6242
6243 return true;
6244 }
6245
6246 /* Field Access */
6247
6248 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6249 for tagged types. */
6250
6251 static int
6252 ada_is_dispatch_table_ptr_type (struct type *type)
6253 {
6254 const char *name;
6255
6256 if (type->code () != TYPE_CODE_PTR)
6257 return 0;
6258
6259 name = type->target_type ()->name ();
6260 if (name == NULL)
6261 return 0;
6262
6263 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6264 }
6265
6266 /* Return non-zero if TYPE is an interface tag. */
6267
6268 static int
6269 ada_is_interface_tag (struct type *type)
6270 {
6271 const char *name = type->name ();
6272
6273 if (name == NULL)
6274 return 0;
6275
6276 return (strcmp (name, "ada__tags__interface_tag") == 0);
6277 }
6278
6279 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6280 to be invisible to users. */
6281
6282 int
6283 ada_is_ignored_field (struct type *type, int field_num)
6284 {
6285 if (field_num < 0 || field_num > type->num_fields ())
6286 return 1;
6287
6288 /* Check the name of that field. */
6289 {
6290 const char *name = type->field (field_num).name ();
6291
6292 /* Anonymous field names should not be printed.
6293 brobecker/2007-02-20: I don't think this can actually happen
6294 but we don't want to print the value of anonymous fields anyway. */
6295 if (name == NULL)
6296 return 1;
6297
6298 /* Normally, fields whose name start with an underscore ("_")
6299 are fields that have been internally generated by the compiler,
6300 and thus should not be printed. The "_parent" field is special,
6301 however: This is a field internally generated by the compiler
6302 for tagged types, and it contains the components inherited from
6303 the parent type. This field should not be printed as is, but
6304 should not be ignored either. */
6305 if (name[0] == '_' && !startswith (name, "_parent"))
6306 return 1;
6307
6308 /* The compiler doesn't document this, but sometimes it emits
6309 a field whose name starts with a capital letter, like 'V148s'.
6310 These aren't marked as artificial in any way, but we know they
6311 should be ignored. However, wrapper fields should not be
6312 ignored. */
6313 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6314 {
6315 /* Wrapper field. */
6316 }
6317 else if (isupper (name[0]))
6318 return 1;
6319 }
6320
6321 /* If this is the dispatch table of a tagged type or an interface tag,
6322 then ignore. */
6323 if (ada_is_tagged_type (type, 1)
6324 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6325 || ada_is_interface_tag (type->field (field_num).type ())))
6326 return 1;
6327
6328 /* Not a special field, so it should not be ignored. */
6329 return 0;
6330 }
6331
6332 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6333 pointer or reference type whose ultimate target has a tag field. */
6334
6335 int
6336 ada_is_tagged_type (struct type *type, int refok)
6337 {
6338 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6339 }
6340
6341 /* True iff TYPE represents the type of X'Tag */
6342
6343 int
6344 ada_is_tag_type (struct type *type)
6345 {
6346 type = ada_check_typedef (type);
6347
6348 if (type == NULL || type->code () != TYPE_CODE_PTR)
6349 return 0;
6350 else
6351 {
6352 const char *name = ada_type_name (type->target_type ());
6353
6354 return (name != NULL
6355 && strcmp (name, "ada__tags__dispatch_table") == 0);
6356 }
6357 }
6358
6359 /* The type of the tag on VAL. */
6360
6361 static struct type *
6362 ada_tag_type (struct value *val)
6363 {
6364 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
6365 }
6366
6367 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6368 retired at Ada 05). */
6369
6370 static int
6371 is_ada95_tag (struct value *tag)
6372 {
6373 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6374 }
6375
6376 /* The value of the tag on VAL. */
6377
6378 static struct value *
6379 ada_value_tag (struct value *val)
6380 {
6381 return ada_value_struct_elt (val, "_tag", 0);
6382 }
6383
6384 /* The value of the tag on the object of type TYPE whose contents are
6385 saved at VALADDR, if it is non-null, or is at memory address
6386 ADDRESS. */
6387
6388 static struct value *
6389 value_tag_from_contents_and_address (struct type *type,
6390 const gdb_byte *valaddr,
6391 CORE_ADDR address)
6392 {
6393 int tag_byte_offset;
6394 struct type *tag_type;
6395
6396 gdb::array_view<const gdb_byte> contents;
6397 if (valaddr != nullptr)
6398 contents = gdb::make_array_view (valaddr, type->length ());
6399 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6400 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6401 NULL, NULL, NULL))
6402 {
6403 const gdb_byte *valaddr1 = ((valaddr == NULL)
6404 ? NULL
6405 : valaddr + tag_byte_offset);
6406 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6407
6408 return value_from_contents_and_address (tag_type, valaddr1, address1);
6409 }
6410 return NULL;
6411 }
6412
6413 static struct type *
6414 type_from_tag (struct value *tag)
6415 {
6416 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6417
6418 if (type_name != NULL)
6419 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6420 return NULL;
6421 }
6422
6423 /* Given a value OBJ of a tagged type, return a value of this
6424 type at the base address of the object. The base address, as
6425 defined in Ada.Tags, it is the address of the primary tag of
6426 the object, and therefore where the field values of its full
6427 view can be fetched. */
6428
6429 struct value *
6430 ada_tag_value_at_base_address (struct value *obj)
6431 {
6432 struct value *val;
6433 LONGEST offset_to_top = 0;
6434 struct type *ptr_type, *obj_type;
6435 struct value *tag;
6436 CORE_ADDR base_address;
6437
6438 obj_type = obj->type ();
6439
6440 /* It is the responsability of the caller to deref pointers. */
6441
6442 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6443 return obj;
6444
6445 tag = ada_value_tag (obj);
6446 if (!tag)
6447 return obj;
6448
6449 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6450
6451 if (is_ada95_tag (tag))
6452 return obj;
6453
6454 struct type *offset_type
6455 = language_lookup_primitive_type (language_def (language_ada),
6456 target_gdbarch(), "storage_offset");
6457 ptr_type = lookup_pointer_type (offset_type);
6458 val = value_cast (ptr_type, tag);
6459 if (!val)
6460 return obj;
6461
6462 /* It is perfectly possible that an exception be raised while
6463 trying to determine the base address, just like for the tag;
6464 see ada_tag_name for more details. We do not print the error
6465 message for the same reason. */
6466
6467 try
6468 {
6469 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6470 }
6471
6472 catch (const gdb_exception_error &e)
6473 {
6474 return obj;
6475 }
6476
6477 /* If offset is null, nothing to do. */
6478
6479 if (offset_to_top == 0)
6480 return obj;
6481
6482 /* -1 is a special case in Ada.Tags; however, what should be done
6483 is not quite clear from the documentation. So do nothing for
6484 now. */
6485
6486 if (offset_to_top == -1)
6487 return obj;
6488
6489 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6490 top is used. In this situation the offset is stored just after
6491 the tag, in the object itself. */
6492 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
6493 if (offset_to_top == last)
6494 {
6495 struct value *tem = value_addr (tag);
6496 tem = value_ptradd (tem, 1);
6497 tem = value_cast (ptr_type, tem);
6498 offset_to_top = value_as_long (value_ind (tem));
6499 }
6500
6501 if (offset_to_top > 0)
6502 {
6503 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6504 from the base address. This was however incompatible with
6505 C++ dispatch table: C++ uses a *negative* value to *add*
6506 to the base address. Ada's convention has therefore been
6507 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6508 use the same convention. Here, we support both cases by
6509 checking the sign of OFFSET_TO_TOP. */
6510 offset_to_top = -offset_to_top;
6511 }
6512
6513 base_address = obj->address () + offset_to_top;
6514 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6515
6516 /* Make sure that we have a proper tag at the new address.
6517 Otherwise, offset_to_top is bogus (which can happen when
6518 the object is not initialized yet). */
6519
6520 if (!tag)
6521 return obj;
6522
6523 obj_type = type_from_tag (tag);
6524
6525 if (!obj_type)
6526 return obj;
6527
6528 return value_from_contents_and_address (obj_type, NULL, base_address);
6529 }
6530
6531 /* Return the "ada__tags__type_specific_data" type. */
6532
6533 static struct type *
6534 ada_get_tsd_type (struct inferior *inf)
6535 {
6536 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6537
6538 if (data->tsd_type == 0)
6539 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6540 return data->tsd_type;
6541 }
6542
6543 /* Return the TSD (type-specific data) associated to the given TAG.
6544 TAG is assumed to be the tag of a tagged-type entity.
6545
6546 May return NULL if we are unable to get the TSD. */
6547
6548 static struct value *
6549 ada_get_tsd_from_tag (struct value *tag)
6550 {
6551 struct value *val;
6552 struct type *type;
6553
6554 /* First option: The TSD is simply stored as a field of our TAG.
6555 Only older versions of GNAT would use this format, but we have
6556 to test it first, because there are no visible markers for
6557 the current approach except the absence of that field. */
6558
6559 val = ada_value_struct_elt (tag, "tsd", 1);
6560 if (val)
6561 return val;
6562
6563 /* Try the second representation for the dispatch table (in which
6564 there is no explicit 'tsd' field in the referent of the tag pointer,
6565 and instead the tsd pointer is stored just before the dispatch
6566 table. */
6567
6568 type = ada_get_tsd_type (current_inferior());
6569 if (type == NULL)
6570 return NULL;
6571 type = lookup_pointer_type (lookup_pointer_type (type));
6572 val = value_cast (type, tag);
6573 if (val == NULL)
6574 return NULL;
6575 return value_ind (value_ptradd (val, -1));
6576 }
6577
6578 /* Given the TSD of a tag (type-specific data), return a string
6579 containing the name of the associated type.
6580
6581 May return NULL if we are unable to determine the tag name. */
6582
6583 static gdb::unique_xmalloc_ptr<char>
6584 ada_tag_name_from_tsd (struct value *tsd)
6585 {
6586 struct value *val;
6587
6588 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6589 if (val == NULL)
6590 return NULL;
6591 gdb::unique_xmalloc_ptr<char> buffer
6592 = target_read_string (value_as_address (val), INT_MAX);
6593 if (buffer == nullptr)
6594 return nullptr;
6595
6596 try
6597 {
6598 /* Let this throw an exception on error. If the data is
6599 uninitialized, we'd rather not have the user see a
6600 warning. */
6601 const char *folded = ada_fold_name (buffer.get (), true);
6602 return make_unique_xstrdup (folded);
6603 }
6604 catch (const gdb_exception &)
6605 {
6606 return nullptr;
6607 }
6608 }
6609
6610 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6611 a C string.
6612
6613 Return NULL if the TAG is not an Ada tag, or if we were unable to
6614 determine the name of that tag. */
6615
6616 gdb::unique_xmalloc_ptr<char>
6617 ada_tag_name (struct value *tag)
6618 {
6619 gdb::unique_xmalloc_ptr<char> name;
6620
6621 if (!ada_is_tag_type (tag->type ()))
6622 return NULL;
6623
6624 /* It is perfectly possible that an exception be raised while trying
6625 to determine the TAG's name, even under normal circumstances:
6626 The associated variable may be uninitialized or corrupted, for
6627 instance. We do not let any exception propagate past this point.
6628 instead we return NULL.
6629
6630 We also do not print the error message either (which often is very
6631 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6632 the caller print a more meaningful message if necessary. */
6633 try
6634 {
6635 struct value *tsd = ada_get_tsd_from_tag (tag);
6636
6637 if (tsd != NULL)
6638 name = ada_tag_name_from_tsd (tsd);
6639 }
6640 catch (const gdb_exception_error &e)
6641 {
6642 }
6643
6644 return name;
6645 }
6646
6647 /* The parent type of TYPE, or NULL if none. */
6648
6649 struct type *
6650 ada_parent_type (struct type *type)
6651 {
6652 int i;
6653
6654 type = ada_check_typedef (type);
6655
6656 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6657 return NULL;
6658
6659 for (i = 0; i < type->num_fields (); i += 1)
6660 if (ada_is_parent_field (type, i))
6661 {
6662 struct type *parent_type = type->field (i).type ();
6663
6664 /* If the _parent field is a pointer, then dereference it. */
6665 if (parent_type->code () == TYPE_CODE_PTR)
6666 parent_type = parent_type->target_type ();
6667 /* If there is a parallel XVS type, get the actual base type. */
6668 parent_type = ada_get_base_type (parent_type);
6669
6670 return ada_check_typedef (parent_type);
6671 }
6672
6673 return NULL;
6674 }
6675
6676 /* True iff field number FIELD_NUM of structure type TYPE contains the
6677 parent-type (inherited) fields of a derived type. Assumes TYPE is
6678 a structure type with at least FIELD_NUM+1 fields. */
6679
6680 int
6681 ada_is_parent_field (struct type *type, int field_num)
6682 {
6683 const char *name = ada_check_typedef (type)->field (field_num).name ();
6684
6685 return (name != NULL
6686 && (startswith (name, "PARENT")
6687 || startswith (name, "_parent")));
6688 }
6689
6690 /* True iff field number FIELD_NUM of structure type TYPE is a
6691 transparent wrapper field (which should be silently traversed when doing
6692 field selection and flattened when printing). Assumes TYPE is a
6693 structure type with at least FIELD_NUM+1 fields. Such fields are always
6694 structures. */
6695
6696 int
6697 ada_is_wrapper_field (struct type *type, int field_num)
6698 {
6699 const char *name = type->field (field_num).name ();
6700
6701 if (name != NULL && strcmp (name, "RETVAL") == 0)
6702 {
6703 /* This happens in functions with "out" or "in out" parameters
6704 which are passed by copy. For such functions, GNAT describes
6705 the function's return type as being a struct where the return
6706 value is in a field called RETVAL, and where the other "out"
6707 or "in out" parameters are fields of that struct. This is not
6708 a wrapper. */
6709 return 0;
6710 }
6711
6712 return (name != NULL
6713 && (startswith (name, "PARENT")
6714 || strcmp (name, "REP") == 0
6715 || startswith (name, "_parent")
6716 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6717 }
6718
6719 /* True iff field number FIELD_NUM of structure or union type TYPE
6720 is a variant wrapper. Assumes TYPE is a structure type with at least
6721 FIELD_NUM+1 fields. */
6722
6723 int
6724 ada_is_variant_part (struct type *type, int field_num)
6725 {
6726 /* Only Ada types are eligible. */
6727 if (!ADA_TYPE_P (type))
6728 return 0;
6729
6730 struct type *field_type = type->field (field_num).type ();
6731
6732 return (field_type->code () == TYPE_CODE_UNION
6733 || (is_dynamic_field (type, field_num)
6734 && (field_type->target_type ()->code ()
6735 == TYPE_CODE_UNION)));
6736 }
6737
6738 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6739 whose discriminants are contained in the record type OUTER_TYPE,
6740 returns the type of the controlling discriminant for the variant.
6741 May return NULL if the type could not be found. */
6742
6743 struct type *
6744 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6745 {
6746 const char *name = ada_variant_discrim_name (var_type);
6747
6748 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6749 }
6750
6751 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6752 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6753 represents a 'when others' clause; otherwise 0. */
6754
6755 static int
6756 ada_is_others_clause (struct type *type, int field_num)
6757 {
6758 const char *name = type->field (field_num).name ();
6759
6760 return (name != NULL && name[0] == 'O');
6761 }
6762
6763 /* Assuming that TYPE0 is the type of the variant part of a record,
6764 returns the name of the discriminant controlling the variant.
6765 The value is valid until the next call to ada_variant_discrim_name. */
6766
6767 const char *
6768 ada_variant_discrim_name (struct type *type0)
6769 {
6770 static std::string result;
6771 struct type *type;
6772 const char *name;
6773 const char *discrim_end;
6774 const char *discrim_start;
6775
6776 if (type0->code () == TYPE_CODE_PTR)
6777 type = type0->target_type ();
6778 else
6779 type = type0;
6780
6781 name = ada_type_name (type);
6782
6783 if (name == NULL || name[0] == '\000')
6784 return "";
6785
6786 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6787 discrim_end -= 1)
6788 {
6789 if (startswith (discrim_end, "___XVN"))
6790 break;
6791 }
6792 if (discrim_end == name)
6793 return "";
6794
6795 for (discrim_start = discrim_end; discrim_start != name + 3;
6796 discrim_start -= 1)
6797 {
6798 if (discrim_start == name + 1)
6799 return "";
6800 if ((discrim_start > name + 3
6801 && startswith (discrim_start - 3, "___"))
6802 || discrim_start[-1] == '.')
6803 break;
6804 }
6805
6806 result = std::string (discrim_start, discrim_end - discrim_start);
6807 return result.c_str ();
6808 }
6809
6810 /* Scan STR for a subtype-encoded number, beginning at position K.
6811 Put the position of the character just past the number scanned in
6812 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6813 Return 1 if there was a valid number at the given position, and 0
6814 otherwise. A "subtype-encoded" number consists of the absolute value
6815 in decimal, followed by the letter 'm' to indicate a negative number.
6816 Assumes 0m does not occur. */
6817
6818 int
6819 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6820 {
6821 ULONGEST RU;
6822
6823 if (!isdigit (str[k]))
6824 return 0;
6825
6826 /* Do it the hard way so as not to make any assumption about
6827 the relationship of unsigned long (%lu scan format code) and
6828 LONGEST. */
6829 RU = 0;
6830 while (isdigit (str[k]))
6831 {
6832 RU = RU * 10 + (str[k] - '0');
6833 k += 1;
6834 }
6835
6836 if (str[k] == 'm')
6837 {
6838 if (R != NULL)
6839 *R = (-(LONGEST) (RU - 1)) - 1;
6840 k += 1;
6841 }
6842 else if (R != NULL)
6843 *R = (LONGEST) RU;
6844
6845 /* NOTE on the above: Technically, C does not say what the results of
6846 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6847 number representable as a LONGEST (although either would probably work
6848 in most implementations). When RU>0, the locution in the then branch
6849 above is always equivalent to the negative of RU. */
6850
6851 if (new_k != NULL)
6852 *new_k = k;
6853 return 1;
6854 }
6855
6856 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6857 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6858 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6859
6860 static int
6861 ada_in_variant (LONGEST val, struct type *type, int field_num)
6862 {
6863 const char *name = type->field (field_num).name ();
6864 int p;
6865
6866 p = 0;
6867 while (1)
6868 {
6869 switch (name[p])
6870 {
6871 case '\0':
6872 return 0;
6873 case 'S':
6874 {
6875 LONGEST W;
6876
6877 if (!ada_scan_number (name, p + 1, &W, &p))
6878 return 0;
6879 if (val == W)
6880 return 1;
6881 break;
6882 }
6883 case 'R':
6884 {
6885 LONGEST L, U;
6886
6887 if (!ada_scan_number (name, p + 1, &L, &p)
6888 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6889 return 0;
6890 if (val >= L && val <= U)
6891 return 1;
6892 break;
6893 }
6894 case 'O':
6895 return 1;
6896 default:
6897 return 0;
6898 }
6899 }
6900 }
6901
6902 /* FIXME: Lots of redundancy below. Try to consolidate. */
6903
6904 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6905 ARG_TYPE, extract and return the value of one of its (non-static)
6906 fields. FIELDNO says which field. Differs from value_primitive_field
6907 only in that it can handle packed values of arbitrary type. */
6908
6909 struct value *
6910 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6911 struct type *arg_type)
6912 {
6913 struct type *type;
6914
6915 arg_type = ada_check_typedef (arg_type);
6916 type = arg_type->field (fieldno).type ();
6917
6918 /* Handle packed fields. It might be that the field is not packed
6919 relative to its containing structure, but the structure itself is
6920 packed; in this case we must take the bit-field path. */
6921 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || arg1->bitpos () != 0)
6922 {
6923 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6924 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6925
6926 return ada_value_primitive_packed_val (arg1,
6927 arg1->contents ().data (),
6928 offset + bit_pos / 8,
6929 bit_pos % 8, bit_size, type);
6930 }
6931 else
6932 return arg1->primitive_field (offset, fieldno, arg_type);
6933 }
6934
6935 /* Find field with name NAME in object of type TYPE. If found,
6936 set the following for each argument that is non-null:
6937 - *FIELD_TYPE_P to the field's type;
6938 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6939 an object of that type;
6940 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6941 - *BIT_SIZE_P to its size in bits if the field is packed, and
6942 0 otherwise;
6943 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6944 fields up to but not including the desired field, or by the total
6945 number of fields if not found. A NULL value of NAME never
6946 matches; the function just counts visible fields in this case.
6947
6948 Notice that we need to handle when a tagged record hierarchy
6949 has some components with the same name, like in this scenario:
6950
6951 type Top_T is tagged record
6952 N : Integer := 1;
6953 U : Integer := 974;
6954 A : Integer := 48;
6955 end record;
6956
6957 type Middle_T is new Top.Top_T with record
6958 N : Character := 'a';
6959 C : Integer := 3;
6960 end record;
6961
6962 type Bottom_T is new Middle.Middle_T with record
6963 N : Float := 4.0;
6964 C : Character := '5';
6965 X : Integer := 6;
6966 A : Character := 'J';
6967 end record;
6968
6969 Let's say we now have a variable declared and initialized as follow:
6970
6971 TC : Top_A := new Bottom_T;
6972
6973 And then we use this variable to call this function
6974
6975 procedure Assign (Obj: in out Top_T; TV : Integer);
6976
6977 as follow:
6978
6979 Assign (Top_T (B), 12);
6980
6981 Now, we're in the debugger, and we're inside that procedure
6982 then and we want to print the value of obj.c:
6983
6984 Usually, the tagged record or one of the parent type owns the
6985 component to print and there's no issue but in this particular
6986 case, what does it mean to ask for Obj.C? Since the actual
6987 type for object is type Bottom_T, it could mean two things: type
6988 component C from the Middle_T view, but also component C from
6989 Bottom_T. So in that "undefined" case, when the component is
6990 not found in the non-resolved type (which includes all the
6991 components of the parent type), then resolve it and see if we
6992 get better luck once expanded.
6993
6994 In the case of homonyms in the derived tagged type, we don't
6995 guaranty anything, and pick the one that's easiest for us
6996 to program.
6997
6998 Returns 1 if found, 0 otherwise. */
6999
7000 static int
7001 find_struct_field (const char *name, struct type *type, int offset,
7002 struct type **field_type_p,
7003 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
7004 int *index_p)
7005 {
7006 int i;
7007 int parent_offset = -1;
7008
7009 type = ada_check_typedef (type);
7010
7011 if (field_type_p != NULL)
7012 *field_type_p = NULL;
7013 if (byte_offset_p != NULL)
7014 *byte_offset_p = 0;
7015 if (bit_offset_p != NULL)
7016 *bit_offset_p = 0;
7017 if (bit_size_p != NULL)
7018 *bit_size_p = 0;
7019
7020 for (i = 0; i < type->num_fields (); i += 1)
7021 {
7022 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7023 type. However, we only need the values to be correct when
7024 the caller asks for them. */
7025 int bit_pos = 0, fld_offset = 0;
7026 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7027 {
7028 bit_pos = type->field (i).loc_bitpos ();
7029 fld_offset = offset + bit_pos / 8;
7030 }
7031
7032 const char *t_field_name = type->field (i).name ();
7033
7034 if (t_field_name == NULL)
7035 continue;
7036
7037 else if (ada_is_parent_field (type, i))
7038 {
7039 /* This is a field pointing us to the parent type of a tagged
7040 type. As hinted in this function's documentation, we give
7041 preference to fields in the current record first, so what
7042 we do here is just record the index of this field before
7043 we skip it. If it turns out we couldn't find our field
7044 in the current record, then we'll get back to it and search
7045 inside it whether the field might exist in the parent. */
7046
7047 parent_offset = i;
7048 continue;
7049 }
7050
7051 else if (name != NULL && field_name_match (t_field_name, name))
7052 {
7053 int bit_size = TYPE_FIELD_BITSIZE (type, i);
7054
7055 if (field_type_p != NULL)
7056 *field_type_p = type->field (i).type ();
7057 if (byte_offset_p != NULL)
7058 *byte_offset_p = fld_offset;
7059 if (bit_offset_p != NULL)
7060 *bit_offset_p = bit_pos % 8;
7061 if (bit_size_p != NULL)
7062 *bit_size_p = bit_size;
7063 return 1;
7064 }
7065 else if (ada_is_wrapper_field (type, i))
7066 {
7067 if (find_struct_field (name, type->field (i).type (), fld_offset,
7068 field_type_p, byte_offset_p, bit_offset_p,
7069 bit_size_p, index_p))
7070 return 1;
7071 }
7072 else if (ada_is_variant_part (type, i))
7073 {
7074 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7075 fixed type?? */
7076 int j;
7077 struct type *field_type
7078 = ada_check_typedef (type->field (i).type ());
7079
7080 for (j = 0; j < field_type->num_fields (); j += 1)
7081 {
7082 if (find_struct_field (name, field_type->field (j).type (),
7083 fld_offset
7084 + field_type->field (j).loc_bitpos () / 8,
7085 field_type_p, byte_offset_p,
7086 bit_offset_p, bit_size_p, index_p))
7087 return 1;
7088 }
7089 }
7090 else if (index_p != NULL)
7091 *index_p += 1;
7092 }
7093
7094 /* Field not found so far. If this is a tagged type which
7095 has a parent, try finding that field in the parent now. */
7096
7097 if (parent_offset != -1)
7098 {
7099 /* As above, only compute the offset when truly needed. */
7100 int fld_offset = offset;
7101 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7102 {
7103 int bit_pos = type->field (parent_offset).loc_bitpos ();
7104 fld_offset += bit_pos / 8;
7105 }
7106
7107 if (find_struct_field (name, type->field (parent_offset).type (),
7108 fld_offset, field_type_p, byte_offset_p,
7109 bit_offset_p, bit_size_p, index_p))
7110 return 1;
7111 }
7112
7113 return 0;
7114 }
7115
7116 /* Number of user-visible fields in record type TYPE. */
7117
7118 static int
7119 num_visible_fields (struct type *type)
7120 {
7121 int n;
7122
7123 n = 0;
7124 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7125 return n;
7126 }
7127
7128 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7129 and search in it assuming it has (class) type TYPE.
7130 If found, return value, else return NULL.
7131
7132 Searches recursively through wrapper fields (e.g., '_parent').
7133
7134 In the case of homonyms in the tagged types, please refer to the
7135 long explanation in find_struct_field's function documentation. */
7136
7137 static struct value *
7138 ada_search_struct_field (const char *name, struct value *arg, int offset,
7139 struct type *type)
7140 {
7141 int i;
7142 int parent_offset = -1;
7143
7144 type = ada_check_typedef (type);
7145 for (i = 0; i < type->num_fields (); i += 1)
7146 {
7147 const char *t_field_name = type->field (i).name ();
7148
7149 if (t_field_name == NULL)
7150 continue;
7151
7152 else if (ada_is_parent_field (type, i))
7153 {
7154 /* This is a field pointing us to the parent type of a tagged
7155 type. As hinted in this function's documentation, we give
7156 preference to fields in the current record first, so what
7157 we do here is just record the index of this field before
7158 we skip it. If it turns out we couldn't find our field
7159 in the current record, then we'll get back to it and search
7160 inside it whether the field might exist in the parent. */
7161
7162 parent_offset = i;
7163 continue;
7164 }
7165
7166 else if (field_name_match (t_field_name, name))
7167 return ada_value_primitive_field (arg, offset, i, type);
7168
7169 else if (ada_is_wrapper_field (type, i))
7170 {
7171 struct value *v = /* Do not let indent join lines here. */
7172 ada_search_struct_field (name, arg,
7173 offset + type->field (i).loc_bitpos () / 8,
7174 type->field (i).type ());
7175
7176 if (v != NULL)
7177 return v;
7178 }
7179
7180 else if (ada_is_variant_part (type, i))
7181 {
7182 /* PNH: Do we ever get here? See find_struct_field. */
7183 int j;
7184 struct type *field_type = ada_check_typedef (type->field (i).type ());
7185 int var_offset = offset + type->field (i).loc_bitpos () / 8;
7186
7187 for (j = 0; j < field_type->num_fields (); j += 1)
7188 {
7189 struct value *v = ada_search_struct_field /* Force line
7190 break. */
7191 (name, arg,
7192 var_offset + field_type->field (j).loc_bitpos () / 8,
7193 field_type->field (j).type ());
7194
7195 if (v != NULL)
7196 return v;
7197 }
7198 }
7199 }
7200
7201 /* Field not found so far. If this is a tagged type which
7202 has a parent, try finding that field in the parent now. */
7203
7204 if (parent_offset != -1)
7205 {
7206 struct value *v = ada_search_struct_field (
7207 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
7208 type->field (parent_offset).type ());
7209
7210 if (v != NULL)
7211 return v;
7212 }
7213
7214 return NULL;
7215 }
7216
7217 static struct value *ada_index_struct_field_1 (int *, struct value *,
7218 int, struct type *);
7219
7220
7221 /* Return field #INDEX in ARG, where the index is that returned by
7222 * find_struct_field through its INDEX_P argument. Adjust the address
7223 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7224 * If found, return value, else return NULL. */
7225
7226 static struct value *
7227 ada_index_struct_field (int index, struct value *arg, int offset,
7228 struct type *type)
7229 {
7230 return ada_index_struct_field_1 (&index, arg, offset, type);
7231 }
7232
7233
7234 /* Auxiliary function for ada_index_struct_field. Like
7235 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7236 * *INDEX_P. */
7237
7238 static struct value *
7239 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7240 struct type *type)
7241 {
7242 int i;
7243 type = ada_check_typedef (type);
7244
7245 for (i = 0; i < type->num_fields (); i += 1)
7246 {
7247 if (type->field (i).name () == NULL)
7248 continue;
7249 else if (ada_is_wrapper_field (type, i))
7250 {
7251 struct value *v = /* Do not let indent join lines here. */
7252 ada_index_struct_field_1 (index_p, arg,
7253 offset + type->field (i).loc_bitpos () / 8,
7254 type->field (i).type ());
7255
7256 if (v != NULL)
7257 return v;
7258 }
7259
7260 else if (ada_is_variant_part (type, i))
7261 {
7262 /* PNH: Do we ever get here? See ada_search_struct_field,
7263 find_struct_field. */
7264 error (_("Cannot assign this kind of variant record"));
7265 }
7266 else if (*index_p == 0)
7267 return ada_value_primitive_field (arg, offset, i, type);
7268 else
7269 *index_p -= 1;
7270 }
7271 return NULL;
7272 }
7273
7274 /* Return a string representation of type TYPE. */
7275
7276 static std::string
7277 type_as_string (struct type *type)
7278 {
7279 string_file tmp_stream;
7280
7281 type_print (type, "", &tmp_stream, -1);
7282
7283 return tmp_stream.release ();
7284 }
7285
7286 /* Given a type TYPE, look up the type of the component of type named NAME.
7287 If DISPP is non-null, add its byte displacement from the beginning of a
7288 structure (pointed to by a value) of type TYPE to *DISPP (does not
7289 work for packed fields).
7290
7291 Matches any field whose name has NAME as a prefix, possibly
7292 followed by "___".
7293
7294 TYPE can be either a struct or union. If REFOK, TYPE may also
7295 be a (pointer or reference)+ to a struct or union, and the
7296 ultimate target type will be searched.
7297
7298 Looks recursively into variant clauses and parent types.
7299
7300 In the case of homonyms in the tagged types, please refer to the
7301 long explanation in find_struct_field's function documentation.
7302
7303 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7304 TYPE is not a type of the right kind. */
7305
7306 static struct type *
7307 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7308 int noerr)
7309 {
7310 int i;
7311 int parent_offset = -1;
7312
7313 if (name == NULL)
7314 goto BadName;
7315
7316 if (refok && type != NULL)
7317 while (1)
7318 {
7319 type = ada_check_typedef (type);
7320 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7321 break;
7322 type = type->target_type ();
7323 }
7324
7325 if (type == NULL
7326 || (type->code () != TYPE_CODE_STRUCT
7327 && type->code () != TYPE_CODE_UNION))
7328 {
7329 if (noerr)
7330 return NULL;
7331
7332 error (_("Type %s is not a structure or union type"),
7333 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7334 }
7335
7336 type = to_static_fixed_type (type);
7337
7338 for (i = 0; i < type->num_fields (); i += 1)
7339 {
7340 const char *t_field_name = type->field (i).name ();
7341 struct type *t;
7342
7343 if (t_field_name == NULL)
7344 continue;
7345
7346 else if (ada_is_parent_field (type, i))
7347 {
7348 /* This is a field pointing us to the parent type of a tagged
7349 type. As hinted in this function's documentation, we give
7350 preference to fields in the current record first, so what
7351 we do here is just record the index of this field before
7352 we skip it. If it turns out we couldn't find our field
7353 in the current record, then we'll get back to it and search
7354 inside it whether the field might exist in the parent. */
7355
7356 parent_offset = i;
7357 continue;
7358 }
7359
7360 else if (field_name_match (t_field_name, name))
7361 return type->field (i).type ();
7362
7363 else if (ada_is_wrapper_field (type, i))
7364 {
7365 t = ada_lookup_struct_elt_type (type->field (i).type (), name,
7366 0, 1);
7367 if (t != NULL)
7368 return t;
7369 }
7370
7371 else if (ada_is_variant_part (type, i))
7372 {
7373 int j;
7374 struct type *field_type = ada_check_typedef (type->field (i).type ());
7375
7376 for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7377 {
7378 /* FIXME pnh 2008/01/26: We check for a field that is
7379 NOT wrapped in a struct, since the compiler sometimes
7380 generates these for unchecked variant types. Revisit
7381 if the compiler changes this practice. */
7382 const char *v_field_name = field_type->field (j).name ();
7383
7384 if (v_field_name != NULL
7385 && field_name_match (v_field_name, name))
7386 t = field_type->field (j).type ();
7387 else
7388 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
7389 name, 0, 1);
7390
7391 if (t != NULL)
7392 return t;
7393 }
7394 }
7395
7396 }
7397
7398 /* Field not found so far. If this is a tagged type which
7399 has a parent, try finding that field in the parent now. */
7400
7401 if (parent_offset != -1)
7402 {
7403 struct type *t;
7404
7405 t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7406 name, 0, 1);
7407 if (t != NULL)
7408 return t;
7409 }
7410
7411 BadName:
7412 if (!noerr)
7413 {
7414 const char *name_str = name != NULL ? name : _("<null>");
7415
7416 error (_("Type %s has no component named %s"),
7417 type_as_string (type).c_str (), name_str);
7418 }
7419
7420 return NULL;
7421 }
7422
7423 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7424 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7425 represents an unchecked union (that is, the variant part of a
7426 record that is named in an Unchecked_Union pragma). */
7427
7428 static int
7429 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7430 {
7431 const char *discrim_name = ada_variant_discrim_name (var_type);
7432
7433 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7434 }
7435
7436
7437 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7438 within OUTER, determine which variant clause (field number in VAR_TYPE,
7439 numbering from 0) is applicable. Returns -1 if none are. */
7440
7441 int
7442 ada_which_variant_applies (struct type *var_type, struct value *outer)
7443 {
7444 int others_clause;
7445 int i;
7446 const char *discrim_name = ada_variant_discrim_name (var_type);
7447 struct value *discrim;
7448 LONGEST discrim_val;
7449
7450 /* Using plain value_from_contents_and_address here causes problems
7451 because we will end up trying to resolve a type that is currently
7452 being constructed. */
7453 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7454 if (discrim == NULL)
7455 return -1;
7456 discrim_val = value_as_long (discrim);
7457
7458 others_clause = -1;
7459 for (i = 0; i < var_type->num_fields (); i += 1)
7460 {
7461 if (ada_is_others_clause (var_type, i))
7462 others_clause = i;
7463 else if (ada_in_variant (discrim_val, var_type, i))
7464 return i;
7465 }
7466
7467 return others_clause;
7468 }
7469 \f
7470
7471
7472 /* Dynamic-Sized Records */
7473
7474 /* Strategy: The type ostensibly attached to a value with dynamic size
7475 (i.e., a size that is not statically recorded in the debugging
7476 data) does not accurately reflect the size or layout of the value.
7477 Our strategy is to convert these values to values with accurate,
7478 conventional types that are constructed on the fly. */
7479
7480 /* There is a subtle and tricky problem here. In general, we cannot
7481 determine the size of dynamic records without its data. However,
7482 the 'struct value' data structure, which GDB uses to represent
7483 quantities in the inferior process (the target), requires the size
7484 of the type at the time of its allocation in order to reserve space
7485 for GDB's internal copy of the data. That's why the
7486 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7487 rather than struct value*s.
7488
7489 However, GDB's internal history variables ($1, $2, etc.) are
7490 struct value*s containing internal copies of the data that are not, in
7491 general, the same as the data at their corresponding addresses in
7492 the target. Fortunately, the types we give to these values are all
7493 conventional, fixed-size types (as per the strategy described
7494 above), so that we don't usually have to perform the
7495 'to_fixed_xxx_type' conversions to look at their values.
7496 Unfortunately, there is one exception: if one of the internal
7497 history variables is an array whose elements are unconstrained
7498 records, then we will need to create distinct fixed types for each
7499 element selected. */
7500
7501 /* The upshot of all of this is that many routines take a (type, host
7502 address, target address) triple as arguments to represent a value.
7503 The host address, if non-null, is supposed to contain an internal
7504 copy of the relevant data; otherwise, the program is to consult the
7505 target at the target address. */
7506
7507 /* Assuming that VAL0 represents a pointer value, the result of
7508 dereferencing it. Differs from value_ind in its treatment of
7509 dynamic-sized types. */
7510
7511 struct value *
7512 ada_value_ind (struct value *val0)
7513 {
7514 struct value *val = value_ind (val0);
7515
7516 if (ada_is_tagged_type (val->type (), 0))
7517 val = ada_tag_value_at_base_address (val);
7518
7519 return ada_to_fixed_value (val);
7520 }
7521
7522 /* The value resulting from dereferencing any "reference to"
7523 qualifiers on VAL0. */
7524
7525 static struct value *
7526 ada_coerce_ref (struct value *val0)
7527 {
7528 if (val0->type ()->code () == TYPE_CODE_REF)
7529 {
7530 struct value *val = val0;
7531
7532 val = coerce_ref (val);
7533
7534 if (ada_is_tagged_type (val->type (), 0))
7535 val = ada_tag_value_at_base_address (val);
7536
7537 return ada_to_fixed_value (val);
7538 }
7539 else
7540 return val0;
7541 }
7542
7543 /* Return the bit alignment required for field #F of template type TYPE. */
7544
7545 static unsigned int
7546 field_alignment (struct type *type, int f)
7547 {
7548 const char *name = type->field (f).name ();
7549 int len;
7550 int align_offset;
7551
7552 /* The field name should never be null, unless the debugging information
7553 is somehow malformed. In this case, we assume the field does not
7554 require any alignment. */
7555 if (name == NULL)
7556 return 1;
7557
7558 len = strlen (name);
7559
7560 if (!isdigit (name[len - 1]))
7561 return 1;
7562
7563 if (isdigit (name[len - 2]))
7564 align_offset = len - 2;
7565 else
7566 align_offset = len - 1;
7567
7568 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7569 return TARGET_CHAR_BIT;
7570
7571 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7572 }
7573
7574 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7575
7576 static struct symbol *
7577 ada_find_any_type_symbol (const char *name)
7578 {
7579 struct symbol *sym;
7580
7581 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7582 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
7583 return sym;
7584
7585 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7586 return sym;
7587 }
7588
7589 /* Find a type named NAME. Ignores ambiguity. This routine will look
7590 solely for types defined by debug info, it will not search the GDB
7591 primitive types. */
7592
7593 static struct type *
7594 ada_find_any_type (const char *name)
7595 {
7596 struct symbol *sym = ada_find_any_type_symbol (name);
7597
7598 if (sym != NULL)
7599 return sym->type ();
7600
7601 return NULL;
7602 }
7603
7604 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7605 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7606 symbol, in which case it is returned. Otherwise, this looks for
7607 symbols whose name is that of NAME_SYM suffixed with "___XR".
7608 Return symbol if found, and NULL otherwise. */
7609
7610 static bool
7611 ada_is_renaming_symbol (struct symbol *name_sym)
7612 {
7613 const char *name = name_sym->linkage_name ();
7614 return strstr (name, "___XR") != NULL;
7615 }
7616
7617 /* Because of GNAT encoding conventions, several GDB symbols may match a
7618 given type name. If the type denoted by TYPE0 is to be preferred to
7619 that of TYPE1 for purposes of type printing, return non-zero;
7620 otherwise return 0. */
7621
7622 int
7623 ada_prefer_type (struct type *type0, struct type *type1)
7624 {
7625 if (type1 == NULL)
7626 return 1;
7627 else if (type0 == NULL)
7628 return 0;
7629 else if (type1->code () == TYPE_CODE_VOID)
7630 return 1;
7631 else if (type0->code () == TYPE_CODE_VOID)
7632 return 0;
7633 else if (type1->name () == NULL && type0->name () != NULL)
7634 return 1;
7635 else if (ada_is_constrained_packed_array_type (type0))
7636 return 1;
7637 else if (ada_is_array_descriptor_type (type0)
7638 && !ada_is_array_descriptor_type (type1))
7639 return 1;
7640 else
7641 {
7642 const char *type0_name = type0->name ();
7643 const char *type1_name = type1->name ();
7644
7645 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7646 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7647 return 1;
7648 }
7649 return 0;
7650 }
7651
7652 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7653 null. */
7654
7655 const char *
7656 ada_type_name (struct type *type)
7657 {
7658 if (type == NULL)
7659 return NULL;
7660 return type->name ();
7661 }
7662
7663 /* Search the list of "descriptive" types associated to TYPE for a type
7664 whose name is NAME. */
7665
7666 static struct type *
7667 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7668 {
7669 struct type *result, *tmp;
7670
7671 if (ada_ignore_descriptive_types_p)
7672 return NULL;
7673
7674 /* If there no descriptive-type info, then there is no parallel type
7675 to be found. */
7676 if (!HAVE_GNAT_AUX_INFO (type))
7677 return NULL;
7678
7679 result = TYPE_DESCRIPTIVE_TYPE (type);
7680 while (result != NULL)
7681 {
7682 const char *result_name = ada_type_name (result);
7683
7684 if (result_name == NULL)
7685 {
7686 warning (_("unexpected null name on descriptive type"));
7687 return NULL;
7688 }
7689
7690 /* If the names match, stop. */
7691 if (strcmp (result_name, name) == 0)
7692 break;
7693
7694 /* Otherwise, look at the next item on the list, if any. */
7695 if (HAVE_GNAT_AUX_INFO (result))
7696 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7697 else
7698 tmp = NULL;
7699
7700 /* If not found either, try after having resolved the typedef. */
7701 if (tmp != NULL)
7702 result = tmp;
7703 else
7704 {
7705 result = check_typedef (result);
7706 if (HAVE_GNAT_AUX_INFO (result))
7707 result = TYPE_DESCRIPTIVE_TYPE (result);
7708 else
7709 result = NULL;
7710 }
7711 }
7712
7713 /* If we didn't find a match, see whether this is a packed array. With
7714 older compilers, the descriptive type information is either absent or
7715 irrelevant when it comes to packed arrays so the above lookup fails.
7716 Fall back to using a parallel lookup by name in this case. */
7717 if (result == NULL && ada_is_constrained_packed_array_type (type))
7718 return ada_find_any_type (name);
7719
7720 return result;
7721 }
7722
7723 /* Find a parallel type to TYPE with the specified NAME, using the
7724 descriptive type taken from the debugging information, if available,
7725 and otherwise using the (slower) name-based method. */
7726
7727 static struct type *
7728 ada_find_parallel_type_with_name (struct type *type, const char *name)
7729 {
7730 struct type *result = NULL;
7731
7732 if (HAVE_GNAT_AUX_INFO (type))
7733 result = find_parallel_type_by_descriptive_type (type, name);
7734 else
7735 result = ada_find_any_type (name);
7736
7737 return result;
7738 }
7739
7740 /* Same as above, but specify the name of the parallel type by appending
7741 SUFFIX to the name of TYPE. */
7742
7743 struct type *
7744 ada_find_parallel_type (struct type *type, const char *suffix)
7745 {
7746 char *name;
7747 const char *type_name = ada_type_name (type);
7748 int len;
7749
7750 if (type_name == NULL)
7751 return NULL;
7752
7753 len = strlen (type_name);
7754
7755 name = (char *) alloca (len + strlen (suffix) + 1);
7756
7757 strcpy (name, type_name);
7758 strcpy (name + len, suffix);
7759
7760 return ada_find_parallel_type_with_name (type, name);
7761 }
7762
7763 /* If TYPE is a variable-size record type, return the corresponding template
7764 type describing its fields. Otherwise, return NULL. */
7765
7766 static struct type *
7767 dynamic_template_type (struct type *type)
7768 {
7769 type = ada_check_typedef (type);
7770
7771 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7772 || ada_type_name (type) == NULL)
7773 return NULL;
7774 else
7775 {
7776 int len = strlen (ada_type_name (type));
7777
7778 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7779 return type;
7780 else
7781 return ada_find_parallel_type (type, "___XVE");
7782 }
7783 }
7784
7785 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7786 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7787
7788 static int
7789 is_dynamic_field (struct type *templ_type, int field_num)
7790 {
7791 const char *name = templ_type->field (field_num).name ();
7792
7793 return name != NULL
7794 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7795 && strstr (name, "___XVL") != NULL;
7796 }
7797
7798 /* The index of the variant field of TYPE, or -1 if TYPE does not
7799 represent a variant record type. */
7800
7801 static int
7802 variant_field_index (struct type *type)
7803 {
7804 int f;
7805
7806 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7807 return -1;
7808
7809 for (f = 0; f < type->num_fields (); f += 1)
7810 {
7811 if (ada_is_variant_part (type, f))
7812 return f;
7813 }
7814 return -1;
7815 }
7816
7817 /* A record type with no fields. */
7818
7819 static struct type *
7820 empty_record (struct type *templ)
7821 {
7822 struct type *type = type_allocator (templ).new_type ();
7823
7824 type->set_code (TYPE_CODE_STRUCT);
7825 INIT_NONE_SPECIFIC (type);
7826 type->set_name ("<empty>");
7827 type->set_length (0);
7828 return type;
7829 }
7830
7831 /* An ordinary record type (with fixed-length fields) that describes
7832 the value of type TYPE at VALADDR or ADDRESS (see comments at
7833 the beginning of this section) VAL according to GNAT conventions.
7834 DVAL0 should describe the (portion of a) record that contains any
7835 necessary discriminants. It should be NULL if VAL->type () is
7836 an outer-level type (i.e., as opposed to a branch of a variant.) A
7837 variant field (unless unchecked) is replaced by a particular branch
7838 of the variant.
7839
7840 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7841 length are not statically known are discarded. As a consequence,
7842 VALADDR, ADDRESS and DVAL0 are ignored.
7843
7844 NOTE: Limitations: For now, we assume that dynamic fields and
7845 variants occupy whole numbers of bytes. However, they need not be
7846 byte-aligned. */
7847
7848 struct type *
7849 ada_template_to_fixed_record_type_1 (struct type *type,
7850 const gdb_byte *valaddr,
7851 CORE_ADDR address, struct value *dval0,
7852 int keep_dynamic_fields)
7853 {
7854 struct value *dval;
7855 struct type *rtype;
7856 int nfields, bit_len;
7857 int variant_field;
7858 long off;
7859 int fld_bit_len;
7860 int f;
7861
7862 scoped_value_mark mark;
7863
7864 /* Compute the number of fields in this record type that are going
7865 to be processed: unless keep_dynamic_fields, this includes only
7866 fields whose position and length are static will be processed. */
7867 if (keep_dynamic_fields)
7868 nfields = type->num_fields ();
7869 else
7870 {
7871 nfields = 0;
7872 while (nfields < type->num_fields ()
7873 && !ada_is_variant_part (type, nfields)
7874 && !is_dynamic_field (type, nfields))
7875 nfields++;
7876 }
7877
7878 rtype = type_allocator (type).new_type ();
7879 rtype->set_code (TYPE_CODE_STRUCT);
7880 INIT_NONE_SPECIFIC (rtype);
7881 rtype->set_num_fields (nfields);
7882 rtype->set_fields
7883 ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7884 rtype->set_name (ada_type_name (type));
7885 rtype->set_is_fixed_instance (true);
7886
7887 off = 0;
7888 bit_len = 0;
7889 variant_field = -1;
7890
7891 for (f = 0; f < nfields; f += 1)
7892 {
7893 off = align_up (off, field_alignment (type, f))
7894 + type->field (f).loc_bitpos ();
7895 rtype->field (f).set_loc_bitpos (off);
7896 TYPE_FIELD_BITSIZE (rtype, f) = 0;
7897
7898 if (ada_is_variant_part (type, f))
7899 {
7900 variant_field = f;
7901 fld_bit_len = 0;
7902 }
7903 else if (is_dynamic_field (type, f))
7904 {
7905 const gdb_byte *field_valaddr = valaddr;
7906 CORE_ADDR field_address = address;
7907 struct type *field_type = type->field (f).type ()->target_type ();
7908
7909 if (dval0 == NULL)
7910 {
7911 /* Using plain value_from_contents_and_address here
7912 causes problems because we will end up trying to
7913 resolve a type that is currently being
7914 constructed. */
7915 dval = value_from_contents_and_address_unresolved (rtype,
7916 valaddr,
7917 address);
7918 rtype = dval->type ();
7919 }
7920 else
7921 dval = dval0;
7922
7923 /* If the type referenced by this field is an aligner type, we need
7924 to unwrap that aligner type, because its size might not be set.
7925 Keeping the aligner type would cause us to compute the wrong
7926 size for this field, impacting the offset of the all the fields
7927 that follow this one. */
7928 if (ada_is_aligner_type (field_type))
7929 {
7930 long field_offset = type->field (f).loc_bitpos ();
7931
7932 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7933 field_address = cond_offset_target (field_address, field_offset);
7934 field_type = ada_aligned_type (field_type);
7935 }
7936
7937 field_valaddr = cond_offset_host (field_valaddr,
7938 off / TARGET_CHAR_BIT);
7939 field_address = cond_offset_target (field_address,
7940 off / TARGET_CHAR_BIT);
7941
7942 /* Get the fixed type of the field. Note that, in this case,
7943 we do not want to get the real type out of the tag: if
7944 the current field is the parent part of a tagged record,
7945 we will get the tag of the object. Clearly wrong: the real
7946 type of the parent is not the real type of the child. We
7947 would end up in an infinite loop. */
7948 field_type = ada_get_base_type (field_type);
7949 field_type = ada_to_fixed_type (field_type, field_valaddr,
7950 field_address, dval, 0);
7951
7952 rtype->field (f).set_type (field_type);
7953 rtype->field (f).set_name (type->field (f).name ());
7954 /* The multiplication can potentially overflow. But because
7955 the field length has been size-checked just above, and
7956 assuming that the maximum size is a reasonable value,
7957 an overflow should not happen in practice. So rather than
7958 adding overflow recovery code to this already complex code,
7959 we just assume that it's not going to happen. */
7960 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
7961 }
7962 else
7963 {
7964 /* Note: If this field's type is a typedef, it is important
7965 to preserve the typedef layer.
7966
7967 Otherwise, we might be transforming a typedef to a fat
7968 pointer (encoding a pointer to an unconstrained array),
7969 into a basic fat pointer (encoding an unconstrained
7970 array). As both types are implemented using the same
7971 structure, the typedef is the only clue which allows us
7972 to distinguish between the two options. Stripping it
7973 would prevent us from printing this field appropriately. */
7974 rtype->field (f).set_type (type->field (f).type ());
7975 rtype->field (f).set_name (type->field (f).name ());
7976 if (TYPE_FIELD_BITSIZE (type, f) > 0)
7977 fld_bit_len =
7978 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7979 else
7980 {
7981 struct type *field_type = type->field (f).type ();
7982
7983 /* We need to be careful of typedefs when computing
7984 the length of our field. If this is a typedef,
7985 get the length of the target type, not the length
7986 of the typedef. */
7987 if (field_type->code () == TYPE_CODE_TYPEDEF)
7988 field_type = ada_typedef_target_type (field_type);
7989
7990 fld_bit_len =
7991 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
7992 }
7993 }
7994 if (off + fld_bit_len > bit_len)
7995 bit_len = off + fld_bit_len;
7996 off += fld_bit_len;
7997 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
7998 }
7999
8000 /* We handle the variant part, if any, at the end because of certain
8001 odd cases in which it is re-ordered so as NOT to be the last field of
8002 the record. This can happen in the presence of representation
8003 clauses. */
8004 if (variant_field >= 0)
8005 {
8006 struct type *branch_type;
8007
8008 off = rtype->field (variant_field).loc_bitpos ();
8009
8010 if (dval0 == NULL)
8011 {
8012 /* Using plain value_from_contents_and_address here causes
8013 problems because we will end up trying to resolve a type
8014 that is currently being constructed. */
8015 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
8016 address);
8017 rtype = dval->type ();
8018 }
8019 else
8020 dval = dval0;
8021
8022 branch_type =
8023 to_fixed_variant_branch_type
8024 (type->field (variant_field).type (),
8025 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
8026 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
8027 if (branch_type == NULL)
8028 {
8029 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
8030 rtype->field (f - 1) = rtype->field (f);
8031 rtype->set_num_fields (rtype->num_fields () - 1);
8032 }
8033 else
8034 {
8035 rtype->field (variant_field).set_type (branch_type);
8036 rtype->field (variant_field).set_name ("S");
8037 fld_bit_len =
8038 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
8039 if (off + fld_bit_len > bit_len)
8040 bit_len = off + fld_bit_len;
8041
8042 rtype->set_length
8043 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
8044 }
8045 }
8046
8047 /* According to exp_dbug.ads, the size of TYPE for variable-size records
8048 should contain the alignment of that record, which should be a strictly
8049 positive value. If null or negative, then something is wrong, most
8050 probably in the debug info. In that case, we don't round up the size
8051 of the resulting type. If this record is not part of another structure,
8052 the current RTYPE length might be good enough for our purposes. */
8053 if (type->length () <= 0)
8054 {
8055 if (rtype->name ())
8056 warning (_("Invalid type size for `%s' detected: %s."),
8057 rtype->name (), pulongest (type->length ()));
8058 else
8059 warning (_("Invalid type size for <unnamed> detected: %s."),
8060 pulongest (type->length ()));
8061 }
8062 else
8063 rtype->set_length (align_up (rtype->length (), type->length ()));
8064
8065 return rtype;
8066 }
8067
8068 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8069 of 1. */
8070
8071 static struct type *
8072 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8073 CORE_ADDR address, struct value *dval0)
8074 {
8075 return ada_template_to_fixed_record_type_1 (type, valaddr,
8076 address, dval0, 1);
8077 }
8078
8079 /* An ordinary record type in which ___XVL-convention fields and
8080 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8081 static approximations, containing all possible fields. Uses
8082 no runtime values. Useless for use in values, but that's OK,
8083 since the results are used only for type determinations. Works on both
8084 structs and unions. Representation note: to save space, we memorize
8085 the result of this function in the type::target_type of the
8086 template type. */
8087
8088 static struct type *
8089 template_to_static_fixed_type (struct type *type0)
8090 {
8091 struct type *type;
8092 int nfields;
8093 int f;
8094
8095 /* No need no do anything if the input type is already fixed. */
8096 if (type0->is_fixed_instance ())
8097 return type0;
8098
8099 /* Likewise if we already have computed the static approximation. */
8100 if (type0->target_type () != NULL)
8101 return type0->target_type ();
8102
8103 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8104 type = type0;
8105 nfields = type0->num_fields ();
8106
8107 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8108 recompute all over next time. */
8109 type0->set_target_type (type);
8110
8111 for (f = 0; f < nfields; f += 1)
8112 {
8113 struct type *field_type = type0->field (f).type ();
8114 struct type *new_type;
8115
8116 if (is_dynamic_field (type0, f))
8117 {
8118 field_type = ada_check_typedef (field_type);
8119 new_type = to_static_fixed_type (field_type->target_type ());
8120 }
8121 else
8122 new_type = static_unwrap_type (field_type);
8123
8124 if (new_type != field_type)
8125 {
8126 /* Clone TYPE0 only the first time we get a new field type. */
8127 if (type == type0)
8128 {
8129 type = type_allocator (type0).new_type ();
8130 type0->set_target_type (type);
8131 type->set_code (type0->code ());
8132 INIT_NONE_SPECIFIC (type);
8133 type->set_num_fields (nfields);
8134
8135 field *fields =
8136 ((struct field *)
8137 TYPE_ALLOC (type, nfields * sizeof (struct field)));
8138 memcpy (fields, type0->fields (),
8139 sizeof (struct field) * nfields);
8140 type->set_fields (fields);
8141
8142 type->set_name (ada_type_name (type0));
8143 type->set_is_fixed_instance (true);
8144 type->set_length (0);
8145 }
8146 type->field (f).set_type (new_type);
8147 type->field (f).set_name (type0->field (f).name ());
8148 }
8149 }
8150
8151 return type;
8152 }
8153
8154 /* Given an object of type TYPE whose contents are at VALADDR and
8155 whose address in memory is ADDRESS, returns a revision of TYPE,
8156 which should be a non-dynamic-sized record, in which the variant
8157 part, if any, is replaced with the appropriate branch. Looks
8158 for discriminant values in DVAL0, which can be NULL if the record
8159 contains the necessary discriminant values. */
8160
8161 static struct type *
8162 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8163 CORE_ADDR address, struct value *dval0)
8164 {
8165 struct value *dval;
8166 struct type *rtype;
8167 struct type *branch_type;
8168 int nfields = type->num_fields ();
8169 int variant_field = variant_field_index (type);
8170
8171 if (variant_field == -1)
8172 return type;
8173
8174 scoped_value_mark mark;
8175 if (dval0 == NULL)
8176 {
8177 dval = value_from_contents_and_address (type, valaddr, address);
8178 type = dval->type ();
8179 }
8180 else
8181 dval = dval0;
8182
8183 rtype = type_allocator (type).new_type ();
8184 rtype->set_code (TYPE_CODE_STRUCT);
8185 INIT_NONE_SPECIFIC (rtype);
8186 rtype->set_num_fields (nfields);
8187
8188 field *fields =
8189 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8190 memcpy (fields, type->fields (), sizeof (struct field) * nfields);
8191 rtype->set_fields (fields);
8192
8193 rtype->set_name (ada_type_name (type));
8194 rtype->set_is_fixed_instance (true);
8195 rtype->set_length (type->length ());
8196
8197 branch_type = to_fixed_variant_branch_type
8198 (type->field (variant_field).type (),
8199 cond_offset_host (valaddr,
8200 type->field (variant_field).loc_bitpos ()
8201 / TARGET_CHAR_BIT),
8202 cond_offset_target (address,
8203 type->field (variant_field).loc_bitpos ()
8204 / TARGET_CHAR_BIT), dval);
8205 if (branch_type == NULL)
8206 {
8207 int f;
8208
8209 for (f = variant_field + 1; f < nfields; f += 1)
8210 rtype->field (f - 1) = rtype->field (f);
8211 rtype->set_num_fields (rtype->num_fields () - 1);
8212 }
8213 else
8214 {
8215 rtype->field (variant_field).set_type (branch_type);
8216 rtype->field (variant_field).set_name ("S");
8217 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8218 rtype->set_length (rtype->length () + branch_type->length ());
8219 }
8220
8221 rtype->set_length (rtype->length ()
8222 - type->field (variant_field).type ()->length ());
8223
8224 return rtype;
8225 }
8226
8227 /* An ordinary record type (with fixed-length fields) that describes
8228 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8229 beginning of this section]. Any necessary discriminants' values
8230 should be in DVAL, a record value; it may be NULL if the object
8231 at ADDR itself contains any necessary discriminant values.
8232 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8233 values from the record are needed. Except in the case that DVAL,
8234 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8235 unchecked) is replaced by a particular branch of the variant.
8236
8237 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8238 is questionable and may be removed. It can arise during the
8239 processing of an unconstrained-array-of-record type where all the
8240 variant branches have exactly the same size. This is because in
8241 such cases, the compiler does not bother to use the XVS convention
8242 when encoding the record. I am currently dubious of this
8243 shortcut and suspect the compiler should be altered. FIXME. */
8244
8245 static struct type *
8246 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8247 CORE_ADDR address, struct value *dval)
8248 {
8249 struct type *templ_type;
8250
8251 if (type0->is_fixed_instance ())
8252 return type0;
8253
8254 templ_type = dynamic_template_type (type0);
8255
8256 if (templ_type != NULL)
8257 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8258 else if (variant_field_index (type0) >= 0)
8259 {
8260 if (dval == NULL && valaddr == NULL && address == 0)
8261 return type0;
8262 return to_record_with_fixed_variant_part (type0, valaddr, address,
8263 dval);
8264 }
8265 else
8266 {
8267 type0->set_is_fixed_instance (true);
8268 return type0;
8269 }
8270
8271 }
8272
8273 /* An ordinary record type (with fixed-length fields) that describes
8274 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8275 union type. Any necessary discriminants' values should be in DVAL,
8276 a record value. That is, this routine selects the appropriate
8277 branch of the union at ADDR according to the discriminant value
8278 indicated in the union's type name. Returns VAR_TYPE0 itself if
8279 it represents a variant subject to a pragma Unchecked_Union. */
8280
8281 static struct type *
8282 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8283 CORE_ADDR address, struct value *dval)
8284 {
8285 int which;
8286 struct type *templ_type;
8287 struct type *var_type;
8288
8289 if (var_type0->code () == TYPE_CODE_PTR)
8290 var_type = var_type0->target_type ();
8291 else
8292 var_type = var_type0;
8293
8294 templ_type = ada_find_parallel_type (var_type, "___XVU");
8295
8296 if (templ_type != NULL)
8297 var_type = templ_type;
8298
8299 if (is_unchecked_variant (var_type, dval->type ()))
8300 return var_type0;
8301 which = ada_which_variant_applies (var_type, dval);
8302
8303 if (which < 0)
8304 return empty_record (var_type);
8305 else if (is_dynamic_field (var_type, which))
8306 return to_fixed_record_type
8307 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
8308 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8309 return
8310 to_fixed_record_type
8311 (var_type->field (which).type (), valaddr, address, dval);
8312 else
8313 return var_type->field (which).type ();
8314 }
8315
8316 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8317 ENCODING_TYPE, a type following the GNAT conventions for discrete
8318 type encodings, only carries redundant information. */
8319
8320 static int
8321 ada_is_redundant_range_encoding (struct type *range_type,
8322 struct type *encoding_type)
8323 {
8324 const char *bounds_str;
8325 int n;
8326 LONGEST lo, hi;
8327
8328 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8329
8330 if (get_base_type (range_type)->code ()
8331 != get_base_type (encoding_type)->code ())
8332 {
8333 /* The compiler probably used a simple base type to describe
8334 the range type instead of the range's actual base type,
8335 expecting us to get the real base type from the encoding
8336 anyway. In this situation, the encoding cannot be ignored
8337 as redundant. */
8338 return 0;
8339 }
8340
8341 if (is_dynamic_type (range_type))
8342 return 0;
8343
8344 if (encoding_type->name () == NULL)
8345 return 0;
8346
8347 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8348 if (bounds_str == NULL)
8349 return 0;
8350
8351 n = 8; /* Skip "___XDLU_". */
8352 if (!ada_scan_number (bounds_str, n, &lo, &n))
8353 return 0;
8354 if (range_type->bounds ()->low.const_val () != lo)
8355 return 0;
8356
8357 n += 2; /* Skip the "__" separator between the two bounds. */
8358 if (!ada_scan_number (bounds_str, n, &hi, &n))
8359 return 0;
8360 if (range_type->bounds ()->high.const_val () != hi)
8361 return 0;
8362
8363 return 1;
8364 }
8365
8366 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8367 a type following the GNAT encoding for describing array type
8368 indices, only carries redundant information. */
8369
8370 static int
8371 ada_is_redundant_index_type_desc (struct type *array_type,
8372 struct type *desc_type)
8373 {
8374 struct type *this_layer = check_typedef (array_type);
8375 int i;
8376
8377 for (i = 0; i < desc_type->num_fields (); i++)
8378 {
8379 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8380 desc_type->field (i).type ()))
8381 return 0;
8382 this_layer = check_typedef (this_layer->target_type ());
8383 }
8384
8385 return 1;
8386 }
8387
8388 /* Assuming that TYPE0 is an array type describing the type of a value
8389 at ADDR, and that DVAL describes a record containing any
8390 discriminants used in TYPE0, returns a type for the value that
8391 contains no dynamic components (that is, no components whose sizes
8392 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8393 true, gives an error message if the resulting type's size is over
8394 varsize_limit. */
8395
8396 static struct type *
8397 to_fixed_array_type (struct type *type0, struct value *dval,
8398 int ignore_too_big)
8399 {
8400 struct type *index_type_desc;
8401 struct type *result;
8402 int constrained_packed_array_p;
8403 static const char *xa_suffix = "___XA";
8404
8405 type0 = ada_check_typedef (type0);
8406 if (type0->is_fixed_instance ())
8407 return type0;
8408
8409 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8410 if (constrained_packed_array_p)
8411 {
8412 type0 = decode_constrained_packed_array_type (type0);
8413 if (type0 == nullptr)
8414 error (_("could not decode constrained packed array type"));
8415 }
8416
8417 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8418
8419 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8420 encoding suffixed with 'P' may still be generated. If so,
8421 it should be used to find the XA type. */
8422
8423 if (index_type_desc == NULL)
8424 {
8425 const char *type_name = ada_type_name (type0);
8426
8427 if (type_name != NULL)
8428 {
8429 const int len = strlen (type_name);
8430 char *name = (char *) alloca (len + strlen (xa_suffix));
8431
8432 if (type_name[len - 1] == 'P')
8433 {
8434 strcpy (name, type_name);
8435 strcpy (name + len - 1, xa_suffix);
8436 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8437 }
8438 }
8439 }
8440
8441 ada_fixup_array_indexes_type (index_type_desc);
8442 if (index_type_desc != NULL
8443 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8444 {
8445 /* Ignore this ___XA parallel type, as it does not bring any
8446 useful information. This allows us to avoid creating fixed
8447 versions of the array's index types, which would be identical
8448 to the original ones. This, in turn, can also help avoid
8449 the creation of fixed versions of the array itself. */
8450 index_type_desc = NULL;
8451 }
8452
8453 if (index_type_desc == NULL)
8454 {
8455 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
8456
8457 /* NOTE: elt_type---the fixed version of elt_type0---should never
8458 depend on the contents of the array in properly constructed
8459 debugging data. */
8460 /* Create a fixed version of the array element type.
8461 We're not providing the address of an element here,
8462 and thus the actual object value cannot be inspected to do
8463 the conversion. This should not be a problem, since arrays of
8464 unconstrained objects are not allowed. In particular, all
8465 the elements of an array of a tagged type should all be of
8466 the same type specified in the debugging info. No need to
8467 consult the object tag. */
8468 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8469
8470 /* Make sure we always create a new array type when dealing with
8471 packed array types, since we're going to fix-up the array
8472 type length and element bitsize a little further down. */
8473 if (elt_type0 == elt_type && !constrained_packed_array_p)
8474 result = type0;
8475 else
8476 {
8477 type_allocator alloc (type0);
8478 result = create_array_type (alloc, elt_type, type0->index_type ());
8479 }
8480 }
8481 else
8482 {
8483 int i;
8484 struct type *elt_type0;
8485
8486 elt_type0 = type0;
8487 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8488 elt_type0 = elt_type0->target_type ();
8489
8490 /* NOTE: result---the fixed version of elt_type0---should never
8491 depend on the contents of the array in properly constructed
8492 debugging data. */
8493 /* Create a fixed version of the array element type.
8494 We're not providing the address of an element here,
8495 and thus the actual object value cannot be inspected to do
8496 the conversion. This should not be a problem, since arrays of
8497 unconstrained objects are not allowed. In particular, all
8498 the elements of an array of a tagged type should all be of
8499 the same type specified in the debugging info. No need to
8500 consult the object tag. */
8501 result =
8502 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8503
8504 elt_type0 = type0;
8505 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8506 {
8507 struct type *range_type =
8508 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8509
8510 type_allocator alloc (elt_type0);
8511 result = create_array_type (alloc, result, range_type);
8512 elt_type0 = elt_type0->target_type ();
8513 }
8514 }
8515
8516 /* We want to preserve the type name. This can be useful when
8517 trying to get the type name of a value that has already been
8518 printed (for instance, if the user did "print VAR; whatis $". */
8519 result->set_name (type0->name ());
8520
8521 if (constrained_packed_array_p)
8522 {
8523 /* So far, the resulting type has been created as if the original
8524 type was a regular (non-packed) array type. As a result, the
8525 bitsize of the array elements needs to be set again, and the array
8526 length needs to be recomputed based on that bitsize. */
8527 int len = result->length () / result->target_type ()->length ();
8528 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8529
8530 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8531 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
8532 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8533 result->set_length (result->length () + 1);
8534 }
8535
8536 result->set_is_fixed_instance (true);
8537 return result;
8538 }
8539
8540
8541 /* A standard type (containing no dynamically sized components)
8542 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8543 DVAL describes a record containing any discriminants used in TYPE0,
8544 and may be NULL if there are none, or if the object of type TYPE at
8545 ADDRESS or in VALADDR contains these discriminants.
8546
8547 If CHECK_TAG is not null, in the case of tagged types, this function
8548 attempts to locate the object's tag and use it to compute the actual
8549 type. However, when ADDRESS is null, we cannot use it to determine the
8550 location of the tag, and therefore compute the tagged type's actual type.
8551 So we return the tagged type without consulting the tag. */
8552
8553 static struct type *
8554 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8555 CORE_ADDR address, struct value *dval, int check_tag)
8556 {
8557 type = ada_check_typedef (type);
8558
8559 /* Only un-fixed types need to be handled here. */
8560 if (!HAVE_GNAT_AUX_INFO (type))
8561 return type;
8562
8563 switch (type->code ())
8564 {
8565 default:
8566 return type;
8567 case TYPE_CODE_STRUCT:
8568 {
8569 struct type *static_type = to_static_fixed_type (type);
8570 struct type *fixed_record_type =
8571 to_fixed_record_type (type, valaddr, address, NULL);
8572
8573 /* If STATIC_TYPE is a tagged type and we know the object's address,
8574 then we can determine its tag, and compute the object's actual
8575 type from there. Note that we have to use the fixed record
8576 type (the parent part of the record may have dynamic fields
8577 and the way the location of _tag is expressed may depend on
8578 them). */
8579
8580 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8581 {
8582 struct value *tag =
8583 value_tag_from_contents_and_address
8584 (fixed_record_type,
8585 valaddr,
8586 address);
8587 struct type *real_type = type_from_tag (tag);
8588 struct value *obj =
8589 value_from_contents_and_address (fixed_record_type,
8590 valaddr,
8591 address);
8592 fixed_record_type = obj->type ();
8593 if (real_type != NULL)
8594 return to_fixed_record_type
8595 (real_type, NULL,
8596 ada_tag_value_at_base_address (obj)->address (), NULL);
8597 }
8598
8599 /* Check to see if there is a parallel ___XVZ variable.
8600 If there is, then it provides the actual size of our type. */
8601 else if (ada_type_name (fixed_record_type) != NULL)
8602 {
8603 const char *name = ada_type_name (fixed_record_type);
8604 char *xvz_name
8605 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8606 bool xvz_found = false;
8607 LONGEST size;
8608
8609 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8610 try
8611 {
8612 xvz_found = get_int_var_value (xvz_name, size);
8613 }
8614 catch (const gdb_exception_error &except)
8615 {
8616 /* We found the variable, but somehow failed to read
8617 its value. Rethrow the same error, but with a little
8618 bit more information, to help the user understand
8619 what went wrong (Eg: the variable might have been
8620 optimized out). */
8621 throw_error (except.error,
8622 _("unable to read value of %s (%s)"),
8623 xvz_name, except.what ());
8624 }
8625
8626 if (xvz_found && fixed_record_type->length () != size)
8627 {
8628 fixed_record_type = copy_type (fixed_record_type);
8629 fixed_record_type->set_length (size);
8630
8631 /* The FIXED_RECORD_TYPE may have be a stub. We have
8632 observed this when the debugging info is STABS, and
8633 apparently it is something that is hard to fix.
8634
8635 In practice, we don't need the actual type definition
8636 at all, because the presence of the XVZ variable allows us
8637 to assume that there must be a XVS type as well, which we
8638 should be able to use later, when we need the actual type
8639 definition.
8640
8641 In the meantime, pretend that the "fixed" type we are
8642 returning is NOT a stub, because this can cause trouble
8643 when using this type to create new types targeting it.
8644 Indeed, the associated creation routines often check
8645 whether the target type is a stub and will try to replace
8646 it, thus using a type with the wrong size. This, in turn,
8647 might cause the new type to have the wrong size too.
8648 Consider the case of an array, for instance, where the size
8649 of the array is computed from the number of elements in
8650 our array multiplied by the size of its element. */
8651 fixed_record_type->set_is_stub (false);
8652 }
8653 }
8654 return fixed_record_type;
8655 }
8656 case TYPE_CODE_ARRAY:
8657 return to_fixed_array_type (type, dval, 1);
8658 case TYPE_CODE_UNION:
8659 if (dval == NULL)
8660 return type;
8661 else
8662 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8663 }
8664 }
8665
8666 /* The same as ada_to_fixed_type_1, except that it preserves the type
8667 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8668
8669 The typedef layer needs be preserved in order to differentiate between
8670 arrays and array pointers when both types are implemented using the same
8671 fat pointer. In the array pointer case, the pointer is encoded as
8672 a typedef of the pointer type. For instance, considering:
8673
8674 type String_Access is access String;
8675 S1 : String_Access := null;
8676
8677 To the debugger, S1 is defined as a typedef of type String. But
8678 to the user, it is a pointer. So if the user tries to print S1,
8679 we should not dereference the array, but print the array address
8680 instead.
8681
8682 If we didn't preserve the typedef layer, we would lose the fact that
8683 the type is to be presented as a pointer (needs de-reference before
8684 being printed). And we would also use the source-level type name. */
8685
8686 struct type *
8687 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8688 CORE_ADDR address, struct value *dval, int check_tag)
8689
8690 {
8691 struct type *fixed_type =
8692 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8693
8694 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8695 then preserve the typedef layer.
8696
8697 Implementation note: We can only check the main-type portion of
8698 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8699 from TYPE now returns a type that has the same instance flags
8700 as TYPE. For instance, if TYPE is a "typedef const", and its
8701 target type is a "struct", then the typedef elimination will return
8702 a "const" version of the target type. See check_typedef for more
8703 details about how the typedef layer elimination is done.
8704
8705 brobecker/2010-11-19: It seems to me that the only case where it is
8706 useful to preserve the typedef layer is when dealing with fat pointers.
8707 Perhaps, we could add a check for that and preserve the typedef layer
8708 only in that situation. But this seems unnecessary so far, probably
8709 because we call check_typedef/ada_check_typedef pretty much everywhere.
8710 */
8711 if (type->code () == TYPE_CODE_TYPEDEF
8712 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8713 == TYPE_MAIN_TYPE (fixed_type)))
8714 return type;
8715
8716 return fixed_type;
8717 }
8718
8719 /* A standard (static-sized) type corresponding as well as possible to
8720 TYPE0, but based on no runtime data. */
8721
8722 static struct type *
8723 to_static_fixed_type (struct type *type0)
8724 {
8725 struct type *type;
8726
8727 if (type0 == NULL)
8728 return NULL;
8729
8730 if (type0->is_fixed_instance ())
8731 return type0;
8732
8733 type0 = ada_check_typedef (type0);
8734
8735 switch (type0->code ())
8736 {
8737 default:
8738 return type0;
8739 case TYPE_CODE_STRUCT:
8740 type = dynamic_template_type (type0);
8741 if (type != NULL)
8742 return template_to_static_fixed_type (type);
8743 else
8744 return template_to_static_fixed_type (type0);
8745 case TYPE_CODE_UNION:
8746 type = ada_find_parallel_type (type0, "___XVU");
8747 if (type != NULL)
8748 return template_to_static_fixed_type (type);
8749 else
8750 return template_to_static_fixed_type (type0);
8751 }
8752 }
8753
8754 /* A static approximation of TYPE with all type wrappers removed. */
8755
8756 static struct type *
8757 static_unwrap_type (struct type *type)
8758 {
8759 if (ada_is_aligner_type (type))
8760 {
8761 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8762 if (ada_type_name (type1) == NULL)
8763 type1->set_name (ada_type_name (type));
8764
8765 return static_unwrap_type (type1);
8766 }
8767 else
8768 {
8769 struct type *raw_real_type = ada_get_base_type (type);
8770
8771 if (raw_real_type == type)
8772 return type;
8773 else
8774 return to_static_fixed_type (raw_real_type);
8775 }
8776 }
8777
8778 /* In some cases, incomplete and private types require
8779 cross-references that are not resolved as records (for example,
8780 type Foo;
8781 type FooP is access Foo;
8782 V: FooP;
8783 type Foo is array ...;
8784 ). In these cases, since there is no mechanism for producing
8785 cross-references to such types, we instead substitute for FooP a
8786 stub enumeration type that is nowhere resolved, and whose tag is
8787 the name of the actual type. Call these types "non-record stubs". */
8788
8789 /* A type equivalent to TYPE that is not a non-record stub, if one
8790 exists, otherwise TYPE. */
8791
8792 struct type *
8793 ada_check_typedef (struct type *type)
8794 {
8795 if (type == NULL)
8796 return NULL;
8797
8798 /* If our type is an access to an unconstrained array, which is encoded
8799 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8800 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8801 what allows us to distinguish between fat pointers that represent
8802 array types, and fat pointers that represent array access types
8803 (in both cases, the compiler implements them as fat pointers). */
8804 if (ada_is_access_to_unconstrained_array (type))
8805 return type;
8806
8807 type = check_typedef (type);
8808 if (type == NULL || type->code () != TYPE_CODE_ENUM
8809 || !type->is_stub ()
8810 || type->name () == NULL)
8811 return type;
8812 else
8813 {
8814 const char *name = type->name ();
8815 struct type *type1 = ada_find_any_type (name);
8816
8817 if (type1 == NULL)
8818 return type;
8819
8820 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8821 stubs pointing to arrays, as we don't create symbols for array
8822 types, only for the typedef-to-array types). If that's the case,
8823 strip the typedef layer. */
8824 if (type1->code () == TYPE_CODE_TYPEDEF)
8825 type1 = ada_check_typedef (type1);
8826
8827 return type1;
8828 }
8829 }
8830
8831 /* A value representing the data at VALADDR/ADDRESS as described by
8832 type TYPE0, but with a standard (static-sized) type that correctly
8833 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8834 type, then return VAL0 [this feature is simply to avoid redundant
8835 creation of struct values]. */
8836
8837 static struct value *
8838 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8839 struct value *val0)
8840 {
8841 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8842
8843 if (type == type0 && val0 != NULL)
8844 return val0;
8845
8846 if (val0->lval () != lval_memory)
8847 {
8848 /* Our value does not live in memory; it could be a convenience
8849 variable, for instance. Create a not_lval value using val0's
8850 contents. */
8851 return value_from_contents (type, val0->contents ().data ());
8852 }
8853
8854 return value_from_contents_and_address (type, 0, address);
8855 }
8856
8857 /* A value representing VAL, but with a standard (static-sized) type
8858 that correctly describes it. Does not necessarily create a new
8859 value. */
8860
8861 struct value *
8862 ada_to_fixed_value (struct value *val)
8863 {
8864 val = unwrap_value (val);
8865 val = ada_to_fixed_value_create (val->type (), val->address (), val);
8866 return val;
8867 }
8868 \f
8869
8870 /* Attributes */
8871
8872 /* Table mapping attribute numbers to names.
8873 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
8874
8875 static const char * const attribute_names[] = {
8876 "<?>",
8877
8878 "first",
8879 "last",
8880 "length",
8881 "image",
8882 "max",
8883 "min",
8884 "modulus",
8885 "pos",
8886 "size",
8887 "tag",
8888 "val",
8889 0
8890 };
8891
8892 static const char *
8893 ada_attribute_name (enum exp_opcode n)
8894 {
8895 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8896 return attribute_names[n - OP_ATR_FIRST + 1];
8897 else
8898 return attribute_names[0];
8899 }
8900
8901 /* Evaluate the 'POS attribute applied to ARG. */
8902
8903 static LONGEST
8904 pos_atr (struct value *arg)
8905 {
8906 struct value *val = coerce_ref (arg);
8907 struct type *type = val->type ();
8908
8909 if (!discrete_type_p (type))
8910 error (_("'POS only defined on discrete types"));
8911
8912 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8913 if (!result.has_value ())
8914 error (_("enumeration value is invalid: can't find 'POS"));
8915
8916 return *result;
8917 }
8918
8919 struct value *
8920 ada_pos_atr (struct type *expect_type,
8921 struct expression *exp,
8922 enum noside noside, enum exp_opcode op,
8923 struct value *arg)
8924 {
8925 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8926 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8927 return value::zero (type, not_lval);
8928 return value_from_longest (type, pos_atr (arg));
8929 }
8930
8931 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8932
8933 static struct value *
8934 val_atr (struct type *type, LONGEST val)
8935 {
8936 gdb_assert (discrete_type_p (type));
8937 if (type->code () == TYPE_CODE_RANGE)
8938 type = type->target_type ();
8939 if (type->code () == TYPE_CODE_ENUM)
8940 {
8941 if (val < 0 || val >= type->num_fields ())
8942 error (_("argument to 'VAL out of range"));
8943 val = type->field (val).loc_enumval ();
8944 }
8945 return value_from_longest (type, val);
8946 }
8947
8948 struct value *
8949 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8950 {
8951 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8952 return value::zero (type, not_lval);
8953
8954 if (!discrete_type_p (type))
8955 error (_("'VAL only defined on discrete types"));
8956 if (!integer_type_p (arg->type ()))
8957 error (_("'VAL requires integral argument"));
8958
8959 return val_atr (type, value_as_long (arg));
8960 }
8961 \f
8962
8963 /* Evaluation */
8964
8965 /* True if TYPE appears to be an Ada character type.
8966 [At the moment, this is true only for Character and Wide_Character;
8967 It is a heuristic test that could stand improvement]. */
8968
8969 bool
8970 ada_is_character_type (struct type *type)
8971 {
8972 const char *name;
8973
8974 /* If the type code says it's a character, then assume it really is,
8975 and don't check any further. */
8976 if (type->code () == TYPE_CODE_CHAR)
8977 return true;
8978
8979 /* Otherwise, assume it's a character type iff it is a discrete type
8980 with a known character type name. */
8981 name = ada_type_name (type);
8982 return (name != NULL
8983 && (type->code () == TYPE_CODE_INT
8984 || type->code () == TYPE_CODE_RANGE)
8985 && (strcmp (name, "character") == 0
8986 || strcmp (name, "wide_character") == 0
8987 || strcmp (name, "wide_wide_character") == 0
8988 || strcmp (name, "unsigned char") == 0));
8989 }
8990
8991 /* True if TYPE appears to be an Ada string type. */
8992
8993 bool
8994 ada_is_string_type (struct type *type)
8995 {
8996 type = ada_check_typedef (type);
8997 if (type != NULL
8998 && type->code () != TYPE_CODE_PTR
8999 && (ada_is_simple_array_type (type)
9000 || ada_is_array_descriptor_type (type))
9001 && ada_array_arity (type) == 1)
9002 {
9003 struct type *elttype = ada_array_element_type (type, 1);
9004
9005 return ada_is_character_type (elttype);
9006 }
9007 else
9008 return false;
9009 }
9010
9011 /* The compiler sometimes provides a parallel XVS type for a given
9012 PAD type. Normally, it is safe to follow the PAD type directly,
9013 but older versions of the compiler have a bug that causes the offset
9014 of its "F" field to be wrong. Following that field in that case
9015 would lead to incorrect results, but this can be worked around
9016 by ignoring the PAD type and using the associated XVS type instead.
9017
9018 Set to True if the debugger should trust the contents of PAD types.
9019 Otherwise, ignore the PAD type if there is a parallel XVS type. */
9020 static bool trust_pad_over_xvs = true;
9021
9022 /* True if TYPE is a struct type introduced by the compiler to force the
9023 alignment of a value. Such types have a single field with a
9024 distinctive name. */
9025
9026 int
9027 ada_is_aligner_type (struct type *type)
9028 {
9029 type = ada_check_typedef (type);
9030
9031 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
9032 return 0;
9033
9034 return (type->code () == TYPE_CODE_STRUCT
9035 && type->num_fields () == 1
9036 && strcmp (type->field (0).name (), "F") == 0);
9037 }
9038
9039 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
9040 the parallel type. */
9041
9042 struct type *
9043 ada_get_base_type (struct type *raw_type)
9044 {
9045 struct type *real_type_namer;
9046 struct type *raw_real_type;
9047
9048 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
9049 return raw_type;
9050
9051 if (ada_is_aligner_type (raw_type))
9052 /* The encoding specifies that we should always use the aligner type.
9053 So, even if this aligner type has an associated XVS type, we should
9054 simply ignore it.
9055
9056 According to the compiler gurus, an XVS type parallel to an aligner
9057 type may exist because of a stabs limitation. In stabs, aligner
9058 types are empty because the field has a variable-sized type, and
9059 thus cannot actually be used as an aligner type. As a result,
9060 we need the associated parallel XVS type to decode the type.
9061 Since the policy in the compiler is to not change the internal
9062 representation based on the debugging info format, we sometimes
9063 end up having a redundant XVS type parallel to the aligner type. */
9064 return raw_type;
9065
9066 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9067 if (real_type_namer == NULL
9068 || real_type_namer->code () != TYPE_CODE_STRUCT
9069 || real_type_namer->num_fields () != 1)
9070 return raw_type;
9071
9072 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
9073 {
9074 /* This is an older encoding form where the base type needs to be
9075 looked up by name. We prefer the newer encoding because it is
9076 more efficient. */
9077 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
9078 if (raw_real_type == NULL)
9079 return raw_type;
9080 else
9081 return raw_real_type;
9082 }
9083
9084 /* The field in our XVS type is a reference to the base type. */
9085 return real_type_namer->field (0).type ()->target_type ();
9086 }
9087
9088 /* The type of value designated by TYPE, with all aligners removed. */
9089
9090 struct type *
9091 ada_aligned_type (struct type *type)
9092 {
9093 if (ada_is_aligner_type (type))
9094 return ada_aligned_type (type->field (0).type ());
9095 else
9096 return ada_get_base_type (type);
9097 }
9098
9099
9100 /* The address of the aligned value in an object at address VALADDR
9101 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9102
9103 const gdb_byte *
9104 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9105 {
9106 if (ada_is_aligner_type (type))
9107 return ada_aligned_value_addr
9108 (type->field (0).type (),
9109 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
9110 else
9111 return valaddr;
9112 }
9113
9114
9115
9116 /* The printed representation of an enumeration literal with encoded
9117 name NAME. The value is good to the next call of ada_enum_name. */
9118 const char *
9119 ada_enum_name (const char *name)
9120 {
9121 static std::string storage;
9122 const char *tmp;
9123
9124 /* First, unqualify the enumeration name:
9125 1. Search for the last '.' character. If we find one, then skip
9126 all the preceding characters, the unqualified name starts
9127 right after that dot.
9128 2. Otherwise, we may be debugging on a target where the compiler
9129 translates dots into "__". Search forward for double underscores,
9130 but stop searching when we hit an overloading suffix, which is
9131 of the form "__" followed by digits. */
9132
9133 tmp = strrchr (name, '.');
9134 if (tmp != NULL)
9135 name = tmp + 1;
9136 else
9137 {
9138 while ((tmp = strstr (name, "__")) != NULL)
9139 {
9140 if (isdigit (tmp[2]))
9141 break;
9142 else
9143 name = tmp + 2;
9144 }
9145 }
9146
9147 if (name[0] == 'Q')
9148 {
9149 int v;
9150
9151 if (name[1] == 'U' || name[1] == 'W')
9152 {
9153 int offset = 2;
9154 if (name[1] == 'W' && name[2] == 'W')
9155 {
9156 /* Also handle the QWW case. */
9157 ++offset;
9158 }
9159 if (sscanf (name + offset, "%x", &v) != 1)
9160 return name;
9161 }
9162 else if (((name[1] >= '0' && name[1] <= '9')
9163 || (name[1] >= 'a' && name[1] <= 'z'))
9164 && name[2] == '\0')
9165 {
9166 storage = string_printf ("'%c'", name[1]);
9167 return storage.c_str ();
9168 }
9169 else
9170 return name;
9171
9172 if (isascii (v) && isprint (v))
9173 storage = string_printf ("'%c'", v);
9174 else if (name[1] == 'U')
9175 storage = string_printf ("'[\"%02x\"]'", v);
9176 else if (name[2] != 'W')
9177 storage = string_printf ("'[\"%04x\"]'", v);
9178 else
9179 storage = string_printf ("'[\"%06x\"]'", v);
9180
9181 return storage.c_str ();
9182 }
9183 else
9184 {
9185 tmp = strstr (name, "__");
9186 if (tmp == NULL)
9187 tmp = strstr (name, "$");
9188 if (tmp != NULL)
9189 {
9190 storage = std::string (name, tmp - name);
9191 return storage.c_str ();
9192 }
9193
9194 return name;
9195 }
9196 }
9197
9198 /* If TYPE is a dynamic type, return the base type. Otherwise, if
9199 there is no parallel type, return nullptr. */
9200
9201 static struct type *
9202 find_base_type (struct type *type)
9203 {
9204 struct type *raw_real_type
9205 = ada_check_typedef (ada_get_base_type (type));
9206
9207 /* No parallel XVS or XVE type. */
9208 if (type == raw_real_type
9209 && ada_find_parallel_type (type, "___XVE") == nullptr)
9210 return nullptr;
9211
9212 return raw_real_type;
9213 }
9214
9215 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9216 value it wraps. */
9217
9218 static struct value *
9219 unwrap_value (struct value *val)
9220 {
9221 struct type *type = ada_check_typedef (val->type ());
9222
9223 if (ada_is_aligner_type (type))
9224 {
9225 struct value *v = ada_value_struct_elt (val, "F", 0);
9226 struct type *val_type = ada_check_typedef (v->type ());
9227
9228 if (ada_type_name (val_type) == NULL)
9229 val_type->set_name (ada_type_name (type));
9230
9231 return unwrap_value (v);
9232 }
9233 else
9234 {
9235 struct type *raw_real_type = find_base_type (type);
9236 if (raw_real_type == nullptr)
9237 return val;
9238
9239 return
9240 coerce_unspec_val_to_type
9241 (val, ada_to_fixed_type (raw_real_type, 0,
9242 val->address (),
9243 NULL, 1));
9244 }
9245 }
9246
9247 /* Given two array types T1 and T2, return nonzero iff both arrays
9248 contain the same number of elements. */
9249
9250 static int
9251 ada_same_array_size_p (struct type *t1, struct type *t2)
9252 {
9253 LONGEST lo1, hi1, lo2, hi2;
9254
9255 /* Get the array bounds in order to verify that the size of
9256 the two arrays match. */
9257 if (!get_array_bounds (t1, &lo1, &hi1)
9258 || !get_array_bounds (t2, &lo2, &hi2))
9259 error (_("unable to determine array bounds"));
9260
9261 /* To make things easier for size comparison, normalize a bit
9262 the case of empty arrays by making sure that the difference
9263 between upper bound and lower bound is always -1. */
9264 if (lo1 > hi1)
9265 hi1 = lo1 - 1;
9266 if (lo2 > hi2)
9267 hi2 = lo2 - 1;
9268
9269 return (hi1 - lo1 == hi2 - lo2);
9270 }
9271
9272 /* Assuming that VAL is an array of integrals, and TYPE represents
9273 an array with the same number of elements, but with wider integral
9274 elements, return an array "casted" to TYPE. In practice, this
9275 means that the returned array is built by casting each element
9276 of the original array into TYPE's (wider) element type. */
9277
9278 static struct value *
9279 ada_promote_array_of_integrals (struct type *type, struct value *val)
9280 {
9281 struct type *elt_type = type->target_type ();
9282 LONGEST lo, hi;
9283 LONGEST i;
9284
9285 /* Verify that both val and type are arrays of scalars, and
9286 that the size of val's elements is smaller than the size
9287 of type's element. */
9288 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9289 gdb_assert (is_integral_type (type->target_type ()));
9290 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9291 gdb_assert (is_integral_type (val->type ()->target_type ()));
9292 gdb_assert (type->target_type ()->length ()
9293 > val->type ()->target_type ()->length ());
9294
9295 if (!get_array_bounds (type, &lo, &hi))
9296 error (_("unable to determine array bounds"));
9297
9298 value *res = value::allocate (type);
9299 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
9300
9301 /* Promote each array element. */
9302 for (i = 0; i < hi - lo + 1; i++)
9303 {
9304 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9305 int elt_len = elt_type->length ();
9306
9307 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
9308 }
9309
9310 return res;
9311 }
9312
9313 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9314 return the converted value. */
9315
9316 static struct value *
9317 coerce_for_assign (struct type *type, struct value *val)
9318 {
9319 struct type *type2 = val->type ();
9320
9321 if (type == type2)
9322 return val;
9323
9324 type2 = ada_check_typedef (type2);
9325 type = ada_check_typedef (type);
9326
9327 if (type2->code () == TYPE_CODE_PTR
9328 && type->code () == TYPE_CODE_ARRAY)
9329 {
9330 val = ada_value_ind (val);
9331 type2 = val->type ();
9332 }
9333
9334 if (type2->code () == TYPE_CODE_ARRAY
9335 && type->code () == TYPE_CODE_ARRAY)
9336 {
9337 if (!ada_same_array_size_p (type, type2))
9338 error (_("cannot assign arrays of different length"));
9339
9340 if (is_integral_type (type->target_type ())
9341 && is_integral_type (type2->target_type ())
9342 && type2->target_type ()->length () < type->target_type ()->length ())
9343 {
9344 /* Allow implicit promotion of the array elements to
9345 a wider type. */
9346 return ada_promote_array_of_integrals (type, val);
9347 }
9348
9349 if (type2->target_type ()->length () != type->target_type ()->length ())
9350 error (_("Incompatible types in assignment"));
9351 val->deprecated_set_type (type);
9352 }
9353 return val;
9354 }
9355
9356 static struct value *
9357 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9358 {
9359 struct value *val;
9360 struct type *type1, *type2;
9361 LONGEST v, v1, v2;
9362
9363 arg1 = coerce_ref (arg1);
9364 arg2 = coerce_ref (arg2);
9365 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9366 type2 = get_base_type (ada_check_typedef (arg2->type ()));
9367
9368 if (type1->code () != TYPE_CODE_INT
9369 || type2->code () != TYPE_CODE_INT)
9370 return value_binop (arg1, arg2, op);
9371
9372 switch (op)
9373 {
9374 case BINOP_MOD:
9375 case BINOP_DIV:
9376 case BINOP_REM:
9377 break;
9378 default:
9379 return value_binop (arg1, arg2, op);
9380 }
9381
9382 v2 = value_as_long (arg2);
9383 if (v2 == 0)
9384 {
9385 const char *name;
9386 if (op == BINOP_MOD)
9387 name = "mod";
9388 else if (op == BINOP_DIV)
9389 name = "/";
9390 else
9391 {
9392 gdb_assert (op == BINOP_REM);
9393 name = "rem";
9394 }
9395
9396 error (_("second operand of %s must not be zero."), name);
9397 }
9398
9399 if (type1->is_unsigned () || op == BINOP_MOD)
9400 return value_binop (arg1, arg2, op);
9401
9402 v1 = value_as_long (arg1);
9403 switch (op)
9404 {
9405 case BINOP_DIV:
9406 v = v1 / v2;
9407 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9408 v += v > 0 ? -1 : 1;
9409 break;
9410 case BINOP_REM:
9411 v = v1 % v2;
9412 if (v * v1 < 0)
9413 v -= v2;
9414 break;
9415 default:
9416 /* Should not reach this point. */
9417 v = 0;
9418 }
9419
9420 val = value::allocate (type1);
9421 store_unsigned_integer (val->contents_raw ().data (),
9422 val->type ()->length (),
9423 type_byte_order (type1), v);
9424 return val;
9425 }
9426
9427 static int
9428 ada_value_equal (struct value *arg1, struct value *arg2)
9429 {
9430 if (ada_is_direct_array_type (arg1->type ())
9431 || ada_is_direct_array_type (arg2->type ()))
9432 {
9433 struct type *arg1_type, *arg2_type;
9434
9435 /* Automatically dereference any array reference before
9436 we attempt to perform the comparison. */
9437 arg1 = ada_coerce_ref (arg1);
9438 arg2 = ada_coerce_ref (arg2);
9439
9440 arg1 = ada_coerce_to_simple_array (arg1);
9441 arg2 = ada_coerce_to_simple_array (arg2);
9442
9443 arg1_type = ada_check_typedef (arg1->type ());
9444 arg2_type = ada_check_typedef (arg2->type ());
9445
9446 if (arg1_type->code () != TYPE_CODE_ARRAY
9447 || arg2_type->code () != TYPE_CODE_ARRAY)
9448 error (_("Attempt to compare array with non-array"));
9449 /* FIXME: The following works only for types whose
9450 representations use all bits (no padding or undefined bits)
9451 and do not have user-defined equality. */
9452 return (arg1_type->length () == arg2_type->length ()
9453 && memcmp (arg1->contents ().data (),
9454 arg2->contents ().data (),
9455 arg1_type->length ()) == 0);
9456 }
9457 return value_equal (arg1, arg2);
9458 }
9459
9460 namespace expr
9461 {
9462
9463 bool
9464 check_objfile (const std::unique_ptr<ada_component> &comp,
9465 struct objfile *objfile)
9466 {
9467 return comp->uses_objfile (objfile);
9468 }
9469
9470 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9471 component of LHS (a simple array or a record). Does not modify the
9472 inferior's memory, nor does it modify LHS (unless LHS ==
9473 CONTAINER). */
9474
9475 static void
9476 assign_component (struct value *container, struct value *lhs, LONGEST index,
9477 struct expression *exp, operation_up &arg)
9478 {
9479 scoped_value_mark mark;
9480
9481 struct value *elt;
9482 struct type *lhs_type = check_typedef (lhs->type ());
9483
9484 if (lhs_type->code () == TYPE_CODE_ARRAY)
9485 {
9486 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9487 struct value *index_val = value_from_longest (index_type, index);
9488
9489 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9490 }
9491 else
9492 {
9493 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
9494 elt = ada_to_fixed_value (elt);
9495 }
9496
9497 ada_aggregate_operation *ag_op
9498 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9499 if (ag_op != nullptr)
9500 ag_op->assign_aggregate (container, elt, exp);
9501 else
9502 value_assign_to_component (container, elt,
9503 arg->evaluate (nullptr, exp,
9504 EVAL_NORMAL));
9505 }
9506
9507 bool
9508 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9509 {
9510 for (const auto &item : m_components)
9511 if (item->uses_objfile (objfile))
9512 return true;
9513 return false;
9514 }
9515
9516 void
9517 ada_aggregate_component::dump (ui_file *stream, int depth)
9518 {
9519 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
9520 for (const auto &item : m_components)
9521 item->dump (stream, depth + 1);
9522 }
9523
9524 void
9525 ada_aggregate_component::assign (struct value *container,
9526 struct value *lhs, struct expression *exp,
9527 std::vector<LONGEST> &indices,
9528 LONGEST low, LONGEST high)
9529 {
9530 for (auto &item : m_components)
9531 item->assign (container, lhs, exp, indices, low, high);
9532 }
9533
9534 /* See ada-exp.h. */
9535
9536 value *
9537 ada_aggregate_operation::assign_aggregate (struct value *container,
9538 struct value *lhs,
9539 struct expression *exp)
9540 {
9541 struct type *lhs_type;
9542 LONGEST low_index, high_index;
9543
9544 container = ada_coerce_ref (container);
9545 if (ada_is_direct_array_type (container->type ()))
9546 container = ada_coerce_to_simple_array (container);
9547 lhs = ada_coerce_ref (lhs);
9548 if (!lhs->deprecated_modifiable ())
9549 error (_("Left operand of assignment is not a modifiable lvalue."));
9550
9551 lhs_type = check_typedef (lhs->type ());
9552 if (ada_is_direct_array_type (lhs_type))
9553 {
9554 lhs = ada_coerce_to_simple_array (lhs);
9555 lhs_type = check_typedef (lhs->type ());
9556 low_index = lhs_type->bounds ()->low.const_val ();
9557 high_index = lhs_type->bounds ()->high.const_val ();
9558 }
9559 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9560 {
9561 low_index = 0;
9562 high_index = num_visible_fields (lhs_type) - 1;
9563 }
9564 else
9565 error (_("Left-hand side must be array or record."));
9566
9567 std::vector<LONGEST> indices (4);
9568 indices[0] = indices[1] = low_index - 1;
9569 indices[2] = indices[3] = high_index + 1;
9570
9571 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9572 low_index, high_index);
9573
9574 return container;
9575 }
9576
9577 bool
9578 ada_positional_component::uses_objfile (struct objfile *objfile)
9579 {
9580 return m_op->uses_objfile (objfile);
9581 }
9582
9583 void
9584 ada_positional_component::dump (ui_file *stream, int depth)
9585 {
9586 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9587 depth, "", m_index);
9588 m_op->dump (stream, depth + 1);
9589 }
9590
9591 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9592 construct, given that the positions are relative to lower bound
9593 LOW, where HIGH is the upper bound. Record the position in
9594 INDICES. CONTAINER is as for assign_aggregate. */
9595 void
9596 ada_positional_component::assign (struct value *container,
9597 struct value *lhs, struct expression *exp,
9598 std::vector<LONGEST> &indices,
9599 LONGEST low, LONGEST high)
9600 {
9601 LONGEST ind = m_index + low;
9602
9603 if (ind - 1 == high)
9604 warning (_("Extra components in aggregate ignored."));
9605 if (ind <= high)
9606 {
9607 add_component_interval (ind, ind, indices);
9608 assign_component (container, lhs, ind, exp, m_op);
9609 }
9610 }
9611
9612 bool
9613 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9614 {
9615 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9616 }
9617
9618 void
9619 ada_discrete_range_association::dump (ui_file *stream, int depth)
9620 {
9621 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
9622 m_low->dump (stream, depth + 1);
9623 m_high->dump (stream, depth + 1);
9624 }
9625
9626 void
9627 ada_discrete_range_association::assign (struct value *container,
9628 struct value *lhs,
9629 struct expression *exp,
9630 std::vector<LONGEST> &indices,
9631 LONGEST low, LONGEST high,
9632 operation_up &op)
9633 {
9634 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9635 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9636
9637 if (lower <= upper && (lower < low || upper > high))
9638 error (_("Index in component association out of bounds."));
9639
9640 add_component_interval (lower, upper, indices);
9641 while (lower <= upper)
9642 {
9643 assign_component (container, lhs, lower, exp, op);
9644 lower += 1;
9645 }
9646 }
9647
9648 bool
9649 ada_name_association::uses_objfile (struct objfile *objfile)
9650 {
9651 return m_val->uses_objfile (objfile);
9652 }
9653
9654 void
9655 ada_name_association::dump (ui_file *stream, int depth)
9656 {
9657 gdb_printf (stream, _("%*sName:\n"), depth, "");
9658 m_val->dump (stream, depth + 1);
9659 }
9660
9661 void
9662 ada_name_association::assign (struct value *container,
9663 struct value *lhs,
9664 struct expression *exp,
9665 std::vector<LONGEST> &indices,
9666 LONGEST low, LONGEST high,
9667 operation_up &op)
9668 {
9669 int index;
9670
9671 if (ada_is_direct_array_type (lhs->type ()))
9672 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9673 EVAL_NORMAL)));
9674 else
9675 {
9676 ada_string_operation *strop
9677 = dynamic_cast<ada_string_operation *> (m_val.get ());
9678
9679 const char *name;
9680 if (strop != nullptr)
9681 name = strop->get_name ();
9682 else
9683 {
9684 ada_var_value_operation *vvo
9685 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9686 if (vvo != nullptr)
9687 error (_("Invalid record component association."));
9688 name = vvo->get_symbol ()->natural_name ();
9689 }
9690
9691 index = 0;
9692 if (! find_struct_field (name, lhs->type (), 0,
9693 NULL, NULL, NULL, NULL, &index))
9694 error (_("Unknown component name: %s."), name);
9695 }
9696
9697 add_component_interval (index, index, indices);
9698 assign_component (container, lhs, index, exp, op);
9699 }
9700
9701 bool
9702 ada_choices_component::uses_objfile (struct objfile *objfile)
9703 {
9704 if (m_op->uses_objfile (objfile))
9705 return true;
9706 for (const auto &item : m_assocs)
9707 if (item->uses_objfile (objfile))
9708 return true;
9709 return false;
9710 }
9711
9712 void
9713 ada_choices_component::dump (ui_file *stream, int depth)
9714 {
9715 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9716 m_op->dump (stream, depth + 1);
9717 for (const auto &item : m_assocs)
9718 item->dump (stream, depth + 1);
9719 }
9720
9721 /* Assign into the components of LHS indexed by the OP_CHOICES
9722 construct at *POS, updating *POS past the construct, given that
9723 the allowable indices are LOW..HIGH. Record the indices assigned
9724 to in INDICES. CONTAINER is as for assign_aggregate. */
9725 void
9726 ada_choices_component::assign (struct value *container,
9727 struct value *lhs, struct expression *exp,
9728 std::vector<LONGEST> &indices,
9729 LONGEST low, LONGEST high)
9730 {
9731 for (auto &item : m_assocs)
9732 item->assign (container, lhs, exp, indices, low, high, m_op);
9733 }
9734
9735 bool
9736 ada_others_component::uses_objfile (struct objfile *objfile)
9737 {
9738 return m_op->uses_objfile (objfile);
9739 }
9740
9741 void
9742 ada_others_component::dump (ui_file *stream, int depth)
9743 {
9744 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
9745 m_op->dump (stream, depth + 1);
9746 }
9747
9748 /* Assign the value of the expression in the OP_OTHERS construct in
9749 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9750 have not been previously assigned. The index intervals already assigned
9751 are in INDICES. CONTAINER is as for assign_aggregate. */
9752 void
9753 ada_others_component::assign (struct value *container,
9754 struct value *lhs, struct expression *exp,
9755 std::vector<LONGEST> &indices,
9756 LONGEST low, LONGEST high)
9757 {
9758 int num_indices = indices.size ();
9759 for (int i = 0; i < num_indices - 2; i += 2)
9760 {
9761 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9762 assign_component (container, lhs, ind, exp, m_op);
9763 }
9764 }
9765
9766 struct value *
9767 ada_assign_operation::evaluate (struct type *expect_type,
9768 struct expression *exp,
9769 enum noside noside)
9770 {
9771 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9772
9773 ada_aggregate_operation *ag_op
9774 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9775 if (ag_op != nullptr)
9776 {
9777 if (noside != EVAL_NORMAL)
9778 return arg1;
9779
9780 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9781 return ada_value_assign (arg1, arg1);
9782 }
9783 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9784 except if the lhs of our assignment is a convenience variable.
9785 In the case of assigning to a convenience variable, the lhs
9786 should be exactly the result of the evaluation of the rhs. */
9787 struct type *type = arg1->type ();
9788 if (arg1->lval () == lval_internalvar)
9789 type = NULL;
9790 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9791 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9792 return arg1;
9793 if (arg1->lval () == lval_internalvar)
9794 {
9795 /* Nothing. */
9796 }
9797 else
9798 arg2 = coerce_for_assign (arg1->type (), arg2);
9799 return ada_value_assign (arg1, arg2);
9800 }
9801
9802 } /* namespace expr */
9803
9804 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9805 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9806 overlap. */
9807 static void
9808 add_component_interval (LONGEST low, LONGEST high,
9809 std::vector<LONGEST> &indices)
9810 {
9811 int i, j;
9812
9813 int size = indices.size ();
9814 for (i = 0; i < size; i += 2) {
9815 if (high >= indices[i] && low <= indices[i + 1])
9816 {
9817 int kh;
9818
9819 for (kh = i + 2; kh < size; kh += 2)
9820 if (high < indices[kh])
9821 break;
9822 if (low < indices[i])
9823 indices[i] = low;
9824 indices[i + 1] = indices[kh - 1];
9825 if (high > indices[i + 1])
9826 indices[i + 1] = high;
9827 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9828 indices.resize (kh - i - 2);
9829 return;
9830 }
9831 else if (high < indices[i])
9832 break;
9833 }
9834
9835 indices.resize (indices.size () + 2);
9836 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9837 indices[j] = indices[j - 2];
9838 indices[i] = low;
9839 indices[i + 1] = high;
9840 }
9841
9842 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9843 is different. */
9844
9845 static struct value *
9846 ada_value_cast (struct type *type, struct value *arg2)
9847 {
9848 if (type == ada_check_typedef (arg2->type ()))
9849 return arg2;
9850
9851 return value_cast (type, arg2);
9852 }
9853
9854 /* Evaluating Ada expressions, and printing their result.
9855 ------------------------------------------------------
9856
9857 1. Introduction:
9858 ----------------
9859
9860 We usually evaluate an Ada expression in order to print its value.
9861 We also evaluate an expression in order to print its type, which
9862 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9863 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9864 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9865 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9866 similar.
9867
9868 Evaluating expressions is a little more complicated for Ada entities
9869 than it is for entities in languages such as C. The main reason for
9870 this is that Ada provides types whose definition might be dynamic.
9871 One example of such types is variant records. Or another example
9872 would be an array whose bounds can only be known at run time.
9873
9874 The following description is a general guide as to what should be
9875 done (and what should NOT be done) in order to evaluate an expression
9876 involving such types, and when. This does not cover how the semantic
9877 information is encoded by GNAT as this is covered separatly. For the
9878 document used as the reference for the GNAT encoding, see exp_dbug.ads
9879 in the GNAT sources.
9880
9881 Ideally, we should embed each part of this description next to its
9882 associated code. Unfortunately, the amount of code is so vast right
9883 now that it's hard to see whether the code handling a particular
9884 situation might be duplicated or not. One day, when the code is
9885 cleaned up, this guide might become redundant with the comments
9886 inserted in the code, and we might want to remove it.
9887
9888 2. ``Fixing'' an Entity, the Simple Case:
9889 -----------------------------------------
9890
9891 When evaluating Ada expressions, the tricky issue is that they may
9892 reference entities whose type contents and size are not statically
9893 known. Consider for instance a variant record:
9894
9895 type Rec (Empty : Boolean := True) is record
9896 case Empty is
9897 when True => null;
9898 when False => Value : Integer;
9899 end case;
9900 end record;
9901 Yes : Rec := (Empty => False, Value => 1);
9902 No : Rec := (empty => True);
9903
9904 The size and contents of that record depends on the value of the
9905 descriminant (Rec.Empty). At this point, neither the debugging
9906 information nor the associated type structure in GDB are able to
9907 express such dynamic types. So what the debugger does is to create
9908 "fixed" versions of the type that applies to the specific object.
9909 We also informally refer to this operation as "fixing" an object,
9910 which means creating its associated fixed type.
9911
9912 Example: when printing the value of variable "Yes" above, its fixed
9913 type would look like this:
9914
9915 type Rec is record
9916 Empty : Boolean;
9917 Value : Integer;
9918 end record;
9919
9920 On the other hand, if we printed the value of "No", its fixed type
9921 would become:
9922
9923 type Rec is record
9924 Empty : Boolean;
9925 end record;
9926
9927 Things become a little more complicated when trying to fix an entity
9928 with a dynamic type that directly contains another dynamic type,
9929 such as an array of variant records, for instance. There are
9930 two possible cases: Arrays, and records.
9931
9932 3. ``Fixing'' Arrays:
9933 ---------------------
9934
9935 The type structure in GDB describes an array in terms of its bounds,
9936 and the type of its elements. By design, all elements in the array
9937 have the same type and we cannot represent an array of variant elements
9938 using the current type structure in GDB. When fixing an array,
9939 we cannot fix the array element, as we would potentially need one
9940 fixed type per element of the array. As a result, the best we can do
9941 when fixing an array is to produce an array whose bounds and size
9942 are correct (allowing us to read it from memory), but without having
9943 touched its element type. Fixing each element will be done later,
9944 when (if) necessary.
9945
9946 Arrays are a little simpler to handle than records, because the same
9947 amount of memory is allocated for each element of the array, even if
9948 the amount of space actually used by each element differs from element
9949 to element. Consider for instance the following array of type Rec:
9950
9951 type Rec_Array is array (1 .. 2) of Rec;
9952
9953 The actual amount of memory occupied by each element might be different
9954 from element to element, depending on the value of their discriminant.
9955 But the amount of space reserved for each element in the array remains
9956 fixed regardless. So we simply need to compute that size using
9957 the debugging information available, from which we can then determine
9958 the array size (we multiply the number of elements of the array by
9959 the size of each element).
9960
9961 The simplest case is when we have an array of a constrained element
9962 type. For instance, consider the following type declarations:
9963
9964 type Bounded_String (Max_Size : Integer) is
9965 Length : Integer;
9966 Buffer : String (1 .. Max_Size);
9967 end record;
9968 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9969
9970 In this case, the compiler describes the array as an array of
9971 variable-size elements (identified by its XVS suffix) for which
9972 the size can be read in the parallel XVZ variable.
9973
9974 In the case of an array of an unconstrained element type, the compiler
9975 wraps the array element inside a private PAD type. This type should not
9976 be shown to the user, and must be "unwrap"'ed before printing. Note
9977 that we also use the adjective "aligner" in our code to designate
9978 these wrapper types.
9979
9980 In some cases, the size allocated for each element is statically
9981 known. In that case, the PAD type already has the correct size,
9982 and the array element should remain unfixed.
9983
9984 But there are cases when this size is not statically known.
9985 For instance, assuming that "Five" is an integer variable:
9986
9987 type Dynamic is array (1 .. Five) of Integer;
9988 type Wrapper (Has_Length : Boolean := False) is record
9989 Data : Dynamic;
9990 case Has_Length is
9991 when True => Length : Integer;
9992 when False => null;
9993 end case;
9994 end record;
9995 type Wrapper_Array is array (1 .. 2) of Wrapper;
9996
9997 Hello : Wrapper_Array := (others => (Has_Length => True,
9998 Data => (others => 17),
9999 Length => 1));
10000
10001
10002 The debugging info would describe variable Hello as being an
10003 array of a PAD type. The size of that PAD type is not statically
10004 known, but can be determined using a parallel XVZ variable.
10005 In that case, a copy of the PAD type with the correct size should
10006 be used for the fixed array.
10007
10008 3. ``Fixing'' record type objects:
10009 ----------------------------------
10010
10011 Things are slightly different from arrays in the case of dynamic
10012 record types. In this case, in order to compute the associated
10013 fixed type, we need to determine the size and offset of each of
10014 its components. This, in turn, requires us to compute the fixed
10015 type of each of these components.
10016
10017 Consider for instance the example:
10018
10019 type Bounded_String (Max_Size : Natural) is record
10020 Str : String (1 .. Max_Size);
10021 Length : Natural;
10022 end record;
10023 My_String : Bounded_String (Max_Size => 10);
10024
10025 In that case, the position of field "Length" depends on the size
10026 of field Str, which itself depends on the value of the Max_Size
10027 discriminant. In order to fix the type of variable My_String,
10028 we need to fix the type of field Str. Therefore, fixing a variant
10029 record requires us to fix each of its components.
10030
10031 However, if a component does not have a dynamic size, the component
10032 should not be fixed. In particular, fields that use a PAD type
10033 should not fixed. Here is an example where this might happen
10034 (assuming type Rec above):
10035
10036 type Container (Big : Boolean) is record
10037 First : Rec;
10038 After : Integer;
10039 case Big is
10040 when True => Another : Integer;
10041 when False => null;
10042 end case;
10043 end record;
10044 My_Container : Container := (Big => False,
10045 First => (Empty => True),
10046 After => 42);
10047
10048 In that example, the compiler creates a PAD type for component First,
10049 whose size is constant, and then positions the component After just
10050 right after it. The offset of component After is therefore constant
10051 in this case.
10052
10053 The debugger computes the position of each field based on an algorithm
10054 that uses, among other things, the actual position and size of the field
10055 preceding it. Let's now imagine that the user is trying to print
10056 the value of My_Container. If the type fixing was recursive, we would
10057 end up computing the offset of field After based on the size of the
10058 fixed version of field First. And since in our example First has
10059 only one actual field, the size of the fixed type is actually smaller
10060 than the amount of space allocated to that field, and thus we would
10061 compute the wrong offset of field After.
10062
10063 To make things more complicated, we need to watch out for dynamic
10064 components of variant records (identified by the ___XVL suffix in
10065 the component name). Even if the target type is a PAD type, the size
10066 of that type might not be statically known. So the PAD type needs
10067 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10068 we might end up with the wrong size for our component. This can be
10069 observed with the following type declarations:
10070
10071 type Octal is new Integer range 0 .. 7;
10072 type Octal_Array is array (Positive range <>) of Octal;
10073 pragma Pack (Octal_Array);
10074
10075 type Octal_Buffer (Size : Positive) is record
10076 Buffer : Octal_Array (1 .. Size);
10077 Length : Integer;
10078 end record;
10079
10080 In that case, Buffer is a PAD type whose size is unset and needs
10081 to be computed by fixing the unwrapped type.
10082
10083 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10084 ----------------------------------------------------------
10085
10086 Lastly, when should the sub-elements of an entity that remained unfixed
10087 thus far, be actually fixed?
10088
10089 The answer is: Only when referencing that element. For instance
10090 when selecting one component of a record, this specific component
10091 should be fixed at that point in time. Or when printing the value
10092 of a record, each component should be fixed before its value gets
10093 printed. Similarly for arrays, the element of the array should be
10094 fixed when printing each element of the array, or when extracting
10095 one element out of that array. On the other hand, fixing should
10096 not be performed on the elements when taking a slice of an array!
10097
10098 Note that one of the side effects of miscomputing the offset and
10099 size of each field is that we end up also miscomputing the size
10100 of the containing type. This can have adverse results when computing
10101 the value of an entity. GDB fetches the value of an entity based
10102 on the size of its type, and thus a wrong size causes GDB to fetch
10103 the wrong amount of memory. In the case where the computed size is
10104 too small, GDB fetches too little data to print the value of our
10105 entity. Results in this case are unpredictable, as we usually read
10106 past the buffer containing the data =:-o. */
10107
10108 /* A helper function for TERNOP_IN_RANGE. */
10109
10110 static value *
10111 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10112 enum noside noside,
10113 value *arg1, value *arg2, value *arg3)
10114 {
10115 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10116 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10117 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10118 return
10119 value_from_longest (type,
10120 (value_less (arg1, arg3)
10121 || value_equal (arg1, arg3))
10122 && (value_less (arg2, arg1)
10123 || value_equal (arg2, arg1)));
10124 }
10125
10126 /* A helper function for UNOP_NEG. */
10127
10128 value *
10129 ada_unop_neg (struct type *expect_type,
10130 struct expression *exp,
10131 enum noside noside, enum exp_opcode op,
10132 struct value *arg1)
10133 {
10134 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10135 return value_neg (arg1);
10136 }
10137
10138 /* A helper function for UNOP_IN_RANGE. */
10139
10140 value *
10141 ada_unop_in_range (struct type *expect_type,
10142 struct expression *exp,
10143 enum noside noside, enum exp_opcode op,
10144 struct value *arg1, struct type *type)
10145 {
10146 struct value *arg2, *arg3;
10147 switch (type->code ())
10148 {
10149 default:
10150 lim_warning (_("Membership test incompletely implemented; "
10151 "always returns true"));
10152 type = language_bool_type (exp->language_defn, exp->gdbarch);
10153 return value_from_longest (type, (LONGEST) 1);
10154
10155 case TYPE_CODE_RANGE:
10156 arg2 = value_from_longest (type,
10157 type->bounds ()->low.const_val ());
10158 arg3 = value_from_longest (type,
10159 type->bounds ()->high.const_val ());
10160 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10161 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10162 type = language_bool_type (exp->language_defn, exp->gdbarch);
10163 return
10164 value_from_longest (type,
10165 (value_less (arg1, arg3)
10166 || value_equal (arg1, arg3))
10167 && (value_less (arg2, arg1)
10168 || value_equal (arg2, arg1)));
10169 }
10170 }
10171
10172 /* A helper function for OP_ATR_TAG. */
10173
10174 value *
10175 ada_atr_tag (struct type *expect_type,
10176 struct expression *exp,
10177 enum noside noside, enum exp_opcode op,
10178 struct value *arg1)
10179 {
10180 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10181 return value::zero (ada_tag_type (arg1), not_lval);
10182
10183 return ada_value_tag (arg1);
10184 }
10185
10186 /* A helper function for OP_ATR_SIZE. */
10187
10188 value *
10189 ada_atr_size (struct type *expect_type,
10190 struct expression *exp,
10191 enum noside noside, enum exp_opcode op,
10192 struct value *arg1)
10193 {
10194 struct type *type = arg1->type ();
10195
10196 /* If the argument is a reference, then dereference its type, since
10197 the user is really asking for the size of the actual object,
10198 not the size of the pointer. */
10199 if (type->code () == TYPE_CODE_REF)
10200 type = type->target_type ();
10201
10202 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10203 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10204 else
10205 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10206 TARGET_CHAR_BIT * type->length ());
10207 }
10208
10209 /* A helper function for UNOP_ABS. */
10210
10211 value *
10212 ada_abs (struct type *expect_type,
10213 struct expression *exp,
10214 enum noside noside, enum exp_opcode op,
10215 struct value *arg1)
10216 {
10217 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10218 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
10219 return value_neg (arg1);
10220 else
10221 return arg1;
10222 }
10223
10224 /* A helper function for BINOP_MUL. */
10225
10226 value *
10227 ada_mult_binop (struct type *expect_type,
10228 struct expression *exp,
10229 enum noside noside, enum exp_opcode op,
10230 struct value *arg1, struct value *arg2)
10231 {
10232 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10233 {
10234 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10235 return value::zero (arg1->type (), not_lval);
10236 }
10237 else
10238 {
10239 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10240 return ada_value_binop (arg1, arg2, op);
10241 }
10242 }
10243
10244 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10245
10246 value *
10247 ada_equal_binop (struct type *expect_type,
10248 struct expression *exp,
10249 enum noside noside, enum exp_opcode op,
10250 struct value *arg1, struct value *arg2)
10251 {
10252 int tem;
10253 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10254 tem = 0;
10255 else
10256 {
10257 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10258 tem = ada_value_equal (arg1, arg2);
10259 }
10260 if (op == BINOP_NOTEQUAL)
10261 tem = !tem;
10262 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10263 return value_from_longest (type, (LONGEST) tem);
10264 }
10265
10266 /* A helper function for TERNOP_SLICE. */
10267
10268 value *
10269 ada_ternop_slice (struct expression *exp,
10270 enum noside noside,
10271 struct value *array, struct value *low_bound_val,
10272 struct value *high_bound_val)
10273 {
10274 LONGEST low_bound;
10275 LONGEST high_bound;
10276
10277 low_bound_val = coerce_ref (low_bound_val);
10278 high_bound_val = coerce_ref (high_bound_val);
10279 low_bound = value_as_long (low_bound_val);
10280 high_bound = value_as_long (high_bound_val);
10281
10282 /* If this is a reference to an aligner type, then remove all
10283 the aligners. */
10284 if (array->type ()->code () == TYPE_CODE_REF
10285 && ada_is_aligner_type (array->type ()->target_type ()))
10286 array->type ()->set_target_type
10287 (ada_aligned_type (array->type ()->target_type ()));
10288
10289 if (ada_is_any_packed_array_type (array->type ()))
10290 error (_("cannot slice a packed array"));
10291
10292 /* If this is a reference to an array or an array lvalue,
10293 convert to a pointer. */
10294 if (array->type ()->code () == TYPE_CODE_REF
10295 || (array->type ()->code () == TYPE_CODE_ARRAY
10296 && array->lval () == lval_memory))
10297 array = value_addr (array);
10298
10299 if (noside == EVAL_AVOID_SIDE_EFFECTS
10300 && ada_is_array_descriptor_type (ada_check_typedef
10301 (array->type ())))
10302 return empty_array (ada_type_of_array (array, 0), low_bound,
10303 high_bound);
10304
10305 array = ada_coerce_to_simple_array_ptr (array);
10306
10307 /* If we have more than one level of pointer indirection,
10308 dereference the value until we get only one level. */
10309 while (array->type ()->code () == TYPE_CODE_PTR
10310 && (array->type ()->target_type ()->code ()
10311 == TYPE_CODE_PTR))
10312 array = value_ind (array);
10313
10314 /* Make sure we really do have an array type before going further,
10315 to avoid a SEGV when trying to get the index type or the target
10316 type later down the road if the debug info generated by
10317 the compiler is incorrect or incomplete. */
10318 if (!ada_is_simple_array_type (array->type ()))
10319 error (_("cannot take slice of non-array"));
10320
10321 if (ada_check_typedef (array->type ())->code ()
10322 == TYPE_CODE_PTR)
10323 {
10324 struct type *type0 = ada_check_typedef (array->type ());
10325
10326 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10327 return empty_array (type0->target_type (), low_bound, high_bound);
10328 else
10329 {
10330 struct type *arr_type0 =
10331 to_fixed_array_type (type0->target_type (), NULL, 1);
10332
10333 return ada_value_slice_from_ptr (array, arr_type0,
10334 longest_to_int (low_bound),
10335 longest_to_int (high_bound));
10336 }
10337 }
10338 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10339 return array;
10340 else if (high_bound < low_bound)
10341 return empty_array (array->type (), low_bound, high_bound);
10342 else
10343 return ada_value_slice (array, longest_to_int (low_bound),
10344 longest_to_int (high_bound));
10345 }
10346
10347 /* A helper function for BINOP_IN_BOUNDS. */
10348
10349 value *
10350 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10351 struct value *arg1, struct value *arg2, int n)
10352 {
10353 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10354 {
10355 struct type *type = language_bool_type (exp->language_defn,
10356 exp->gdbarch);
10357 return value::zero (type, not_lval);
10358 }
10359
10360 struct type *type = ada_index_type (arg2->type (), n, "range");
10361 if (!type)
10362 type = arg1->type ();
10363
10364 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10365 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10366
10367 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10368 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10369 type = language_bool_type (exp->language_defn, exp->gdbarch);
10370 return value_from_longest (type,
10371 (value_less (arg1, arg3)
10372 || value_equal (arg1, arg3))
10373 && (value_less (arg2, arg1)
10374 || value_equal (arg2, arg1)));
10375 }
10376
10377 /* A helper function for some attribute operations. */
10378
10379 static value *
10380 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10381 struct value *arg1, struct type *type_arg, int tem)
10382 {
10383 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10384 {
10385 if (type_arg == NULL)
10386 type_arg = arg1->type ();
10387
10388 if (ada_is_constrained_packed_array_type (type_arg))
10389 type_arg = decode_constrained_packed_array_type (type_arg);
10390
10391 if (!discrete_type_p (type_arg))
10392 {
10393 switch (op)
10394 {
10395 default: /* Should never happen. */
10396 error (_("unexpected attribute encountered"));
10397 case OP_ATR_FIRST:
10398 case OP_ATR_LAST:
10399 type_arg = ada_index_type (type_arg, tem,
10400 ada_attribute_name (op));
10401 break;
10402 case OP_ATR_LENGTH:
10403 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10404 break;
10405 }
10406 }
10407
10408 return value::zero (type_arg, not_lval);
10409 }
10410 else if (type_arg == NULL)
10411 {
10412 arg1 = ada_coerce_ref (arg1);
10413
10414 if (ada_is_constrained_packed_array_type (arg1->type ()))
10415 arg1 = ada_coerce_to_simple_array (arg1);
10416
10417 struct type *type;
10418 if (op == OP_ATR_LENGTH)
10419 type = builtin_type (exp->gdbarch)->builtin_int;
10420 else
10421 {
10422 type = ada_index_type (arg1->type (), tem,
10423 ada_attribute_name (op));
10424 if (type == NULL)
10425 type = builtin_type (exp->gdbarch)->builtin_int;
10426 }
10427
10428 switch (op)
10429 {
10430 default: /* Should never happen. */
10431 error (_("unexpected attribute encountered"));
10432 case OP_ATR_FIRST:
10433 return value_from_longest
10434 (type, ada_array_bound (arg1, tem, 0));
10435 case OP_ATR_LAST:
10436 return value_from_longest
10437 (type, ada_array_bound (arg1, tem, 1));
10438 case OP_ATR_LENGTH:
10439 return value_from_longest
10440 (type, ada_array_length (arg1, tem));
10441 }
10442 }
10443 else if (discrete_type_p (type_arg))
10444 {
10445 struct type *range_type;
10446 const char *name = ada_type_name (type_arg);
10447
10448 range_type = NULL;
10449 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10450 range_type = to_fixed_range_type (type_arg, NULL);
10451 if (range_type == NULL)
10452 range_type = type_arg;
10453 switch (op)
10454 {
10455 default:
10456 error (_("unexpected attribute encountered"));
10457 case OP_ATR_FIRST:
10458 return value_from_longest
10459 (range_type, ada_discrete_type_low_bound (range_type));
10460 case OP_ATR_LAST:
10461 return value_from_longest
10462 (range_type, ada_discrete_type_high_bound (range_type));
10463 case OP_ATR_LENGTH:
10464 error (_("the 'length attribute applies only to array types"));
10465 }
10466 }
10467 else if (type_arg->code () == TYPE_CODE_FLT)
10468 error (_("unimplemented type attribute"));
10469 else
10470 {
10471 LONGEST low, high;
10472
10473 if (ada_is_constrained_packed_array_type (type_arg))
10474 type_arg = decode_constrained_packed_array_type (type_arg);
10475
10476 struct type *type;
10477 if (op == OP_ATR_LENGTH)
10478 type = builtin_type (exp->gdbarch)->builtin_int;
10479 else
10480 {
10481 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10482 if (type == NULL)
10483 type = builtin_type (exp->gdbarch)->builtin_int;
10484 }
10485
10486 switch (op)
10487 {
10488 default:
10489 error (_("unexpected attribute encountered"));
10490 case OP_ATR_FIRST:
10491 low = ada_array_bound_from_type (type_arg, tem, 0);
10492 return value_from_longest (type, low);
10493 case OP_ATR_LAST:
10494 high = ada_array_bound_from_type (type_arg, tem, 1);
10495 return value_from_longest (type, high);
10496 case OP_ATR_LENGTH:
10497 low = ada_array_bound_from_type (type_arg, tem, 0);
10498 high = ada_array_bound_from_type (type_arg, tem, 1);
10499 return value_from_longest (type, high - low + 1);
10500 }
10501 }
10502 }
10503
10504 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10505
10506 struct value *
10507 ada_binop_minmax (struct type *expect_type,
10508 struct expression *exp,
10509 enum noside noside, enum exp_opcode op,
10510 struct value *arg1, struct value *arg2)
10511 {
10512 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10513 return value::zero (arg1->type (), not_lval);
10514 else
10515 {
10516 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10517 return value_binop (arg1, arg2, op);
10518 }
10519 }
10520
10521 /* A helper function for BINOP_EXP. */
10522
10523 struct value *
10524 ada_binop_exp (struct type *expect_type,
10525 struct expression *exp,
10526 enum noside noside, enum exp_opcode op,
10527 struct value *arg1, struct value *arg2)
10528 {
10529 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10530 return value::zero (arg1->type (), not_lval);
10531 else
10532 {
10533 /* For integer exponentiation operations,
10534 only promote the first argument. */
10535 if (is_integral_type (arg2->type ()))
10536 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10537 else
10538 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10539
10540 return value_binop (arg1, arg2, op);
10541 }
10542 }
10543
10544 namespace expr
10545 {
10546
10547 /* See ada-exp.h. */
10548
10549 operation_up
10550 ada_resolvable::replace (operation_up &&owner,
10551 struct expression *exp,
10552 bool deprocedure_p,
10553 bool parse_completion,
10554 innermost_block_tracker *tracker,
10555 struct type *context_type)
10556 {
10557 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10558 return (make_operation<ada_funcall_operation>
10559 (std::move (owner),
10560 std::vector<operation_up> ()));
10561 return std::move (owner);
10562 }
10563
10564 /* Convert the character literal whose value would be VAL to the
10565 appropriate value of type TYPE, if there is a translation.
10566 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10567 the literal 'A' (VAL == 65), returns 0. */
10568
10569 static LONGEST
10570 convert_char_literal (struct type *type, LONGEST val)
10571 {
10572 char name[12];
10573 int f;
10574
10575 if (type == NULL)
10576 return val;
10577 type = check_typedef (type);
10578 if (type->code () != TYPE_CODE_ENUM)
10579 return val;
10580
10581 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10582 xsnprintf (name, sizeof (name), "Q%c", (int) val);
10583 else if (val >= 0 && val < 256)
10584 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10585 else if (val >= 0 && val < 0x10000)
10586 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10587 else
10588 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10589 size_t len = strlen (name);
10590 for (f = 0; f < type->num_fields (); f += 1)
10591 {
10592 /* Check the suffix because an enum constant in a package will
10593 have a name like "pkg__QUxx". This is safe enough because we
10594 already have the correct type, and because mangling means
10595 there can't be clashes. */
10596 const char *ename = type->field (f).name ();
10597 size_t elen = strlen (ename);
10598
10599 if (elen >= len && strcmp (name, ename + elen - len) == 0)
10600 return type->field (f).loc_enumval ();
10601 }
10602 return val;
10603 }
10604
10605 value *
10606 ada_char_operation::evaluate (struct type *expect_type,
10607 struct expression *exp,
10608 enum noside noside)
10609 {
10610 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10611 if (expect_type != nullptr)
10612 result = ada_value_cast (expect_type, result);
10613 return result;
10614 }
10615
10616 /* See ada-exp.h. */
10617
10618 operation_up
10619 ada_char_operation::replace (operation_up &&owner,
10620 struct expression *exp,
10621 bool deprocedure_p,
10622 bool parse_completion,
10623 innermost_block_tracker *tracker,
10624 struct type *context_type)
10625 {
10626 operation_up result = std::move (owner);
10627
10628 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10629 {
10630 gdb_assert (result.get () == this);
10631 std::get<0> (m_storage) = context_type;
10632 std::get<1> (m_storage)
10633 = convert_char_literal (context_type, std::get<1> (m_storage));
10634 }
10635
10636 return result;
10637 }
10638
10639 value *
10640 ada_wrapped_operation::evaluate (struct type *expect_type,
10641 struct expression *exp,
10642 enum noside noside)
10643 {
10644 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10645 if (noside == EVAL_NORMAL)
10646 result = unwrap_value (result);
10647
10648 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10649 then we need to perform the conversion manually, because
10650 evaluate_subexp_standard doesn't do it. This conversion is
10651 necessary in Ada because the different kinds of float/fixed
10652 types in Ada have different representations.
10653
10654 Similarly, we need to perform the conversion from OP_LONG
10655 ourselves. */
10656 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10657 result = ada_value_cast (expect_type, result);
10658
10659 return result;
10660 }
10661
10662 void
10663 ada_wrapped_operation::do_generate_ax (struct expression *exp,
10664 struct agent_expr *ax,
10665 struct axs_value *value,
10666 struct type *cast_type)
10667 {
10668 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10669
10670 struct type *type = value->type;
10671 if (ada_is_aligner_type (type))
10672 error (_("Aligner types cannot be handled in agent expressions"));
10673 else if (find_base_type (type) != nullptr)
10674 error (_("Dynamic types cannot be handled in agent expressions"));
10675 }
10676
10677 value *
10678 ada_string_operation::evaluate (struct type *expect_type,
10679 struct expression *exp,
10680 enum noside noside)
10681 {
10682 struct type *char_type;
10683 if (expect_type != nullptr && ada_is_string_type (expect_type))
10684 char_type = ada_array_element_type (expect_type, 1);
10685 else
10686 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10687
10688 const std::string &str = std::get<0> (m_storage);
10689 const char *encoding;
10690 switch (char_type->length ())
10691 {
10692 case 1:
10693 {
10694 /* Simply copy over the data -- this isn't perhaps strictly
10695 correct according to the encodings, but it is gdb's
10696 historical behavior. */
10697 struct type *stringtype
10698 = lookup_array_range_type (char_type, 1, str.length ());
10699 struct value *val = value::allocate (stringtype);
10700 memcpy (val->contents_raw ().data (), str.c_str (),
10701 str.length ());
10702 return val;
10703 }
10704
10705 case 2:
10706 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10707 encoding = "UTF-16BE";
10708 else
10709 encoding = "UTF-16LE";
10710 break;
10711
10712 case 4:
10713 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10714 encoding = "UTF-32BE";
10715 else
10716 encoding = "UTF-32LE";
10717 break;
10718
10719 default:
10720 error (_("unexpected character type size %s"),
10721 pulongest (char_type->length ()));
10722 }
10723
10724 auto_obstack converted;
10725 convert_between_encodings (host_charset (), encoding,
10726 (const gdb_byte *) str.c_str (),
10727 str.length (), 1,
10728 &converted, translit_none);
10729
10730 struct type *stringtype
10731 = lookup_array_range_type (char_type, 1,
10732 obstack_object_size (&converted)
10733 / char_type->length ());
10734 struct value *val = value::allocate (stringtype);
10735 memcpy (val->contents_raw ().data (),
10736 obstack_base (&converted),
10737 obstack_object_size (&converted));
10738 return val;
10739 }
10740
10741 value *
10742 ada_concat_operation::evaluate (struct type *expect_type,
10743 struct expression *exp,
10744 enum noside noside)
10745 {
10746 /* If one side is a literal, evaluate the other side first so that
10747 the expected type can be set properly. */
10748 const operation_up &lhs_expr = std::get<0> (m_storage);
10749 const operation_up &rhs_expr = std::get<1> (m_storage);
10750
10751 value *lhs, *rhs;
10752 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10753 {
10754 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10755 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
10756 }
10757 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10758 {
10759 rhs = rhs_expr->evaluate (nullptr, exp, noside);
10760 struct type *rhs_type = check_typedef (rhs->type ());
10761 struct type *elt_type = nullptr;
10762 if (rhs_type->code () == TYPE_CODE_ARRAY)
10763 elt_type = rhs_type->target_type ();
10764 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10765 }
10766 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10767 {
10768 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10769 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
10770 }
10771 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10772 {
10773 lhs = lhs_expr->evaluate (nullptr, exp, noside);
10774 struct type *lhs_type = check_typedef (lhs->type ());
10775 struct type *elt_type = nullptr;
10776 if (lhs_type->code () == TYPE_CODE_ARRAY)
10777 elt_type = lhs_type->target_type ();
10778 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10779 }
10780 else
10781 return concat_operation::evaluate (expect_type, exp, noside);
10782
10783 return value_concat (lhs, rhs);
10784 }
10785
10786 value *
10787 ada_qual_operation::evaluate (struct type *expect_type,
10788 struct expression *exp,
10789 enum noside noside)
10790 {
10791 struct type *type = std::get<1> (m_storage);
10792 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10793 }
10794
10795 value *
10796 ada_ternop_range_operation::evaluate (struct type *expect_type,
10797 struct expression *exp,
10798 enum noside noside)
10799 {
10800 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10801 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10802 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10803 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10804 }
10805
10806 value *
10807 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10808 struct expression *exp,
10809 enum noside noside)
10810 {
10811 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10812 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10813
10814 auto do_op = [=] (LONGEST x, LONGEST y)
10815 {
10816 if (std::get<0> (m_storage) == BINOP_ADD)
10817 return x + y;
10818 return x - y;
10819 };
10820
10821 if (arg1->type ()->code () == TYPE_CODE_PTR)
10822 return (value_from_longest
10823 (arg1->type (),
10824 do_op (value_as_long (arg1), value_as_long (arg2))));
10825 if (arg2->type ()->code () == TYPE_CODE_PTR)
10826 return (value_from_longest
10827 (arg2->type (),
10828 do_op (value_as_long (arg1), value_as_long (arg2))));
10829 /* Preserve the original type for use by the range case below.
10830 We cannot cast the result to a reference type, so if ARG1 is
10831 a reference type, find its underlying type. */
10832 struct type *type = arg1->type ();
10833 while (type->code () == TYPE_CODE_REF)
10834 type = type->target_type ();
10835 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10836 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10837 /* We need to special-case the result with a range.
10838 This is done for the benefit of "ptype". gdb's Ada support
10839 historically used the LHS to set the result type here, so
10840 preserve this behavior. */
10841 if (type->code () == TYPE_CODE_RANGE)
10842 arg1 = value_cast (type, arg1);
10843 return arg1;
10844 }
10845
10846 value *
10847 ada_unop_atr_operation::evaluate (struct type *expect_type,
10848 struct expression *exp,
10849 enum noside noside)
10850 {
10851 struct type *type_arg = nullptr;
10852 value *val = nullptr;
10853
10854 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10855 {
10856 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10857 EVAL_AVOID_SIDE_EFFECTS);
10858 type_arg = tem->type ();
10859 }
10860 else
10861 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10862
10863 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10864 val, type_arg, std::get<2> (m_storage));
10865 }
10866
10867 value *
10868 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10869 struct expression *exp,
10870 enum noside noside)
10871 {
10872 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10873 return value::zero (expect_type, not_lval);
10874
10875 const bound_minimal_symbol &b = std::get<0> (m_storage);
10876 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10877
10878 val = ada_value_cast (expect_type, val);
10879
10880 /* Follow the Ada language semantics that do not allow taking
10881 an address of the result of a cast (view conversion in Ada). */
10882 if (val->lval () == lval_memory)
10883 {
10884 if (val->lazy ())
10885 val->fetch_lazy ();
10886 val->set_lval (not_lval);
10887 }
10888 return val;
10889 }
10890
10891 value *
10892 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10893 struct expression *exp,
10894 enum noside noside)
10895 {
10896 value *val = evaluate_var_value (noside,
10897 std::get<0> (m_storage).block,
10898 std::get<0> (m_storage).symbol);
10899
10900 val = ada_value_cast (expect_type, val);
10901
10902 /* Follow the Ada language semantics that do not allow taking
10903 an address of the result of a cast (view conversion in Ada). */
10904 if (val->lval () == lval_memory)
10905 {
10906 if (val->lazy ())
10907 val->fetch_lazy ();
10908 val->set_lval (not_lval);
10909 }
10910 return val;
10911 }
10912
10913 value *
10914 ada_var_value_operation::evaluate (struct type *expect_type,
10915 struct expression *exp,
10916 enum noside noside)
10917 {
10918 symbol *sym = std::get<0> (m_storage).symbol;
10919
10920 if (sym->domain () == UNDEF_DOMAIN)
10921 /* Only encountered when an unresolved symbol occurs in a
10922 context other than a function call, in which case, it is
10923 invalid. */
10924 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10925 sym->print_name ());
10926
10927 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10928 {
10929 struct type *type = static_unwrap_type (sym->type ());
10930 /* Check to see if this is a tagged type. We also need to handle
10931 the case where the type is a reference to a tagged type, but
10932 we have to be careful to exclude pointers to tagged types.
10933 The latter should be shown as usual (as a pointer), whereas
10934 a reference should mostly be transparent to the user. */
10935 if (ada_is_tagged_type (type, 0)
10936 || (type->code () == TYPE_CODE_REF
10937 && ada_is_tagged_type (type->target_type (), 0)))
10938 {
10939 /* Tagged types are a little special in the fact that the real
10940 type is dynamic and can only be determined by inspecting the
10941 object's tag. This means that we need to get the object's
10942 value first (EVAL_NORMAL) and then extract the actual object
10943 type from its tag.
10944
10945 Note that we cannot skip the final step where we extract
10946 the object type from its tag, because the EVAL_NORMAL phase
10947 results in dynamic components being resolved into fixed ones.
10948 This can cause problems when trying to print the type
10949 description of tagged types whose parent has a dynamic size:
10950 We use the type name of the "_parent" component in order
10951 to print the name of the ancestor type in the type description.
10952 If that component had a dynamic size, the resolution into
10953 a fixed type would result in the loss of that type name,
10954 thus preventing us from printing the name of the ancestor
10955 type in the type description. */
10956 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10957
10958 if (type->code () != TYPE_CODE_REF)
10959 {
10960 struct type *actual_type;
10961
10962 actual_type = type_from_tag (ada_value_tag (arg1));
10963 if (actual_type == NULL)
10964 /* If, for some reason, we were unable to determine
10965 the actual type from the tag, then use the static
10966 approximation that we just computed as a fallback.
10967 This can happen if the debugging information is
10968 incomplete, for instance. */
10969 actual_type = type;
10970 return value::zero (actual_type, not_lval);
10971 }
10972 else
10973 {
10974 /* In the case of a ref, ada_coerce_ref takes care
10975 of determining the actual type. But the evaluation
10976 should return a ref as it should be valid to ask
10977 for its address; so rebuild a ref after coerce. */
10978 arg1 = ada_coerce_ref (arg1);
10979 return value_ref (arg1, TYPE_CODE_REF);
10980 }
10981 }
10982
10983 /* Records and unions for which GNAT encodings have been
10984 generated need to be statically fixed as well.
10985 Otherwise, non-static fixing produces a type where
10986 all dynamic properties are removed, which prevents "ptype"
10987 from being able to completely describe the type.
10988 For instance, a case statement in a variant record would be
10989 replaced by the relevant components based on the actual
10990 value of the discriminants. */
10991 if ((type->code () == TYPE_CODE_STRUCT
10992 && dynamic_template_type (type) != NULL)
10993 || (type->code () == TYPE_CODE_UNION
10994 && ada_find_parallel_type (type, "___XVU") != NULL))
10995 return value::zero (to_static_fixed_type (type), not_lval);
10996 }
10997
10998 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10999 return ada_to_fixed_value (arg1);
11000 }
11001
11002 bool
11003 ada_var_value_operation::resolve (struct expression *exp,
11004 bool deprocedure_p,
11005 bool parse_completion,
11006 innermost_block_tracker *tracker,
11007 struct type *context_type)
11008 {
11009 symbol *sym = std::get<0> (m_storage).symbol;
11010 if (sym->domain () == UNDEF_DOMAIN)
11011 {
11012 block_symbol resolved
11013 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
11014 context_type, parse_completion,
11015 deprocedure_p, tracker);
11016 std::get<0> (m_storage) = resolved;
11017 }
11018
11019 if (deprocedure_p
11020 && (std::get<0> (m_storage).symbol->type ()->code ()
11021 == TYPE_CODE_FUNC))
11022 return true;
11023
11024 return false;
11025 }
11026
11027 void
11028 ada_var_value_operation::do_generate_ax (struct expression *exp,
11029 struct agent_expr *ax,
11030 struct axs_value *value,
11031 struct type *cast_type)
11032 {
11033 symbol *sym = std::get<0> (m_storage).symbol;
11034
11035 if (sym->domain () == UNDEF_DOMAIN)
11036 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11037 sym->print_name ());
11038
11039 struct type *type = static_unwrap_type (sym->type ());
11040 if (ada_is_tagged_type (type, 0)
11041 || (type->code () == TYPE_CODE_REF
11042 && ada_is_tagged_type (type->target_type (), 0)))
11043 error (_("Tagged types cannot be handled in agent expressions"));
11044
11045 if ((type->code () == TYPE_CODE_STRUCT
11046 && dynamic_template_type (type) != NULL)
11047 || (type->code () == TYPE_CODE_UNION
11048 && ada_find_parallel_type (type, "___XVU") != NULL))
11049 error (_("Dynamic types cannot be handled in agent expressions"));
11050
11051 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
11052 }
11053
11054 value *
11055 ada_atr_val_operation::evaluate (struct type *expect_type,
11056 struct expression *exp,
11057 enum noside noside)
11058 {
11059 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
11060 return ada_val_atr (noside, std::get<0> (m_storage), arg);
11061 }
11062
11063 value *
11064 ada_unop_ind_operation::evaluate (struct type *expect_type,
11065 struct expression *exp,
11066 enum noside noside)
11067 {
11068 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11069
11070 struct type *type = ada_check_typedef (arg1->type ());
11071 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11072 {
11073 if (ada_is_array_descriptor_type (type))
11074 /* GDB allows dereferencing GNAT array descriptors. */
11075 {
11076 struct type *arrType = ada_type_of_array (arg1, 0);
11077
11078 if (arrType == NULL)
11079 error (_("Attempt to dereference null array pointer."));
11080 return value_at_lazy (arrType, 0);
11081 }
11082 else if (type->code () == TYPE_CODE_PTR
11083 || type->code () == TYPE_CODE_REF
11084 /* In C you can dereference an array to get the 1st elt. */
11085 || type->code () == TYPE_CODE_ARRAY)
11086 {
11087 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11088 only be determined by inspecting the object's tag.
11089 This means that we need to evaluate completely the
11090 expression in order to get its type. */
11091
11092 if ((type->code () == TYPE_CODE_REF
11093 || type->code () == TYPE_CODE_PTR)
11094 && ada_is_tagged_type (type->target_type (), 0))
11095 {
11096 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11097 EVAL_NORMAL);
11098 type = ada_value_ind (arg1)->type ();
11099 }
11100 else
11101 {
11102 type = to_static_fixed_type
11103 (ada_aligned_type
11104 (ada_check_typedef (type->target_type ())));
11105 }
11106 return value::zero (type, lval_memory);
11107 }
11108 else if (type->code () == TYPE_CODE_INT)
11109 {
11110 /* GDB allows dereferencing an int. */
11111 if (expect_type == NULL)
11112 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11113 lval_memory);
11114 else
11115 {
11116 expect_type =
11117 to_static_fixed_type (ada_aligned_type (expect_type));
11118 return value::zero (expect_type, lval_memory);
11119 }
11120 }
11121 else
11122 error (_("Attempt to take contents of a non-pointer value."));
11123 }
11124 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11125 type = ada_check_typedef (arg1->type ());
11126
11127 if (type->code () == TYPE_CODE_INT)
11128 /* GDB allows dereferencing an int. If we were given
11129 the expect_type, then use that as the target type.
11130 Otherwise, assume that the target type is an int. */
11131 {
11132 if (expect_type != NULL)
11133 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11134 arg1));
11135 else
11136 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11137 (CORE_ADDR) value_as_address (arg1));
11138 }
11139
11140 if (ada_is_array_descriptor_type (type))
11141 /* GDB allows dereferencing GNAT array descriptors. */
11142 return ada_coerce_to_simple_array (arg1);
11143 else
11144 return ada_value_ind (arg1);
11145 }
11146
11147 value *
11148 ada_structop_operation::evaluate (struct type *expect_type,
11149 struct expression *exp,
11150 enum noside noside)
11151 {
11152 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11153 const char *str = std::get<1> (m_storage).c_str ();
11154 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11155 {
11156 struct type *type;
11157 struct type *type1 = arg1->type ();
11158
11159 if (ada_is_tagged_type (type1, 1))
11160 {
11161 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11162
11163 /* If the field is not found, check if it exists in the
11164 extension of this object's type. This means that we
11165 need to evaluate completely the expression. */
11166
11167 if (type == NULL)
11168 {
11169 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11170 EVAL_NORMAL);
11171 arg1 = ada_value_struct_elt (arg1, str, 0);
11172 arg1 = unwrap_value (arg1);
11173 type = ada_to_fixed_value (arg1)->type ();
11174 }
11175 }
11176 else
11177 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11178
11179 return value::zero (ada_aligned_type (type), lval_memory);
11180 }
11181 else
11182 {
11183 arg1 = ada_value_struct_elt (arg1, str, 0);
11184 arg1 = unwrap_value (arg1);
11185 return ada_to_fixed_value (arg1);
11186 }
11187 }
11188
11189 value *
11190 ada_funcall_operation::evaluate (struct type *expect_type,
11191 struct expression *exp,
11192 enum noside noside)
11193 {
11194 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11195 int nargs = args_up.size ();
11196 std::vector<value *> argvec (nargs);
11197 operation_up &callee_op = std::get<0> (m_storage);
11198
11199 ada_var_value_operation *avv
11200 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11201 if (avv != nullptr
11202 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
11203 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11204 avv->get_symbol ()->print_name ());
11205
11206 value *callee = callee_op->evaluate (nullptr, exp, noside);
11207 for (int i = 0; i < args_up.size (); ++i)
11208 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11209
11210 if (ada_is_constrained_packed_array_type
11211 (desc_base_type (callee->type ())))
11212 callee = ada_coerce_to_simple_array (callee);
11213 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11214 && TYPE_FIELD_BITSIZE (callee->type (), 0) != 0)
11215 /* This is a packed array that has already been fixed, and
11216 therefore already coerced to a simple array. Nothing further
11217 to do. */
11218 ;
11219 else if (callee->type ()->code () == TYPE_CODE_REF)
11220 {
11221 /* Make sure we dereference references so that all the code below
11222 feels like it's really handling the referenced value. Wrapping
11223 types (for alignment) may be there, so make sure we strip them as
11224 well. */
11225 callee = ada_to_fixed_value (coerce_ref (callee));
11226 }
11227 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11228 && callee->lval () == lval_memory)
11229 callee = value_addr (callee);
11230
11231 struct type *type = ada_check_typedef (callee->type ());
11232
11233 /* Ada allows us to implicitly dereference arrays when subscripting
11234 them. So, if this is an array typedef (encoding use for array
11235 access types encoded as fat pointers), strip it now. */
11236 if (type->code () == TYPE_CODE_TYPEDEF)
11237 type = ada_typedef_target_type (type);
11238
11239 if (type->code () == TYPE_CODE_PTR)
11240 {
11241 switch (ada_check_typedef (type->target_type ())->code ())
11242 {
11243 case TYPE_CODE_FUNC:
11244 type = ada_check_typedef (type->target_type ());
11245 break;
11246 case TYPE_CODE_ARRAY:
11247 break;
11248 case TYPE_CODE_STRUCT:
11249 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11250 callee = ada_value_ind (callee);
11251 type = ada_check_typedef (type->target_type ());
11252 break;
11253 default:
11254 error (_("cannot subscript or call something of type `%s'"),
11255 ada_type_name (callee->type ()));
11256 break;
11257 }
11258 }
11259
11260 switch (type->code ())
11261 {
11262 case TYPE_CODE_FUNC:
11263 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11264 {
11265 if (type->target_type () == NULL)
11266 error_call_unknown_return_type (NULL);
11267 return value::allocate (type->target_type ());
11268 }
11269 return call_function_by_hand (callee, NULL, argvec);
11270 case TYPE_CODE_INTERNAL_FUNCTION:
11271 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11272 /* We don't know anything about what the internal
11273 function might return, but we have to return
11274 something. */
11275 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
11276 not_lval);
11277 else
11278 return call_internal_function (exp->gdbarch, exp->language_defn,
11279 callee, nargs,
11280 argvec.data ());
11281
11282 case TYPE_CODE_STRUCT:
11283 {
11284 int arity;
11285
11286 arity = ada_array_arity (type);
11287 type = ada_array_element_type (type, nargs);
11288 if (type == NULL)
11289 error (_("cannot subscript or call a record"));
11290 if (arity != nargs)
11291 error (_("wrong number of subscripts; expecting %d"), arity);
11292 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11293 return value::zero (ada_aligned_type (type), lval_memory);
11294 return
11295 unwrap_value (ada_value_subscript
11296 (callee, nargs, argvec.data ()));
11297 }
11298 case TYPE_CODE_ARRAY:
11299 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11300 {
11301 type = ada_array_element_type (type, nargs);
11302 if (type == NULL)
11303 error (_("element type of array unknown"));
11304 else
11305 return value::zero (ada_aligned_type (type), lval_memory);
11306 }
11307 return
11308 unwrap_value (ada_value_subscript
11309 (ada_coerce_to_simple_array (callee),
11310 nargs, argvec.data ()));
11311 case TYPE_CODE_PTR: /* Pointer to array */
11312 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11313 {
11314 type = to_fixed_array_type (type->target_type (), NULL, 1);
11315 type = ada_array_element_type (type, nargs);
11316 if (type == NULL)
11317 error (_("element type of array unknown"));
11318 else
11319 return value::zero (ada_aligned_type (type), lval_memory);
11320 }
11321 return
11322 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11323 argvec.data ()));
11324
11325 default:
11326 error (_("Attempt to index or call something other than an "
11327 "array or function"));
11328 }
11329 }
11330
11331 bool
11332 ada_funcall_operation::resolve (struct expression *exp,
11333 bool deprocedure_p,
11334 bool parse_completion,
11335 innermost_block_tracker *tracker,
11336 struct type *context_type)
11337 {
11338 operation_up &callee_op = std::get<0> (m_storage);
11339
11340 ada_var_value_operation *avv
11341 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11342 if (avv == nullptr)
11343 return false;
11344
11345 symbol *sym = avv->get_symbol ();
11346 if (sym->domain () != UNDEF_DOMAIN)
11347 return false;
11348
11349 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11350 int nargs = args_up.size ();
11351 std::vector<value *> argvec (nargs);
11352
11353 for (int i = 0; i < args_up.size (); ++i)
11354 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11355
11356 const block *block = avv->get_block ();
11357 block_symbol resolved
11358 = ada_resolve_funcall (sym, block,
11359 context_type, parse_completion,
11360 nargs, argvec.data (),
11361 tracker);
11362
11363 std::get<0> (m_storage)
11364 = make_operation<ada_var_value_operation> (resolved);
11365 return false;
11366 }
11367
11368 bool
11369 ada_ternop_slice_operation::resolve (struct expression *exp,
11370 bool deprocedure_p,
11371 bool parse_completion,
11372 innermost_block_tracker *tracker,
11373 struct type *context_type)
11374 {
11375 /* Historically this check was done during resolution, so we
11376 continue that here. */
11377 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11378 EVAL_AVOID_SIDE_EFFECTS);
11379 if (ada_is_any_packed_array_type (v->type ()))
11380 error (_("cannot slice a packed array"));
11381 return false;
11382 }
11383
11384 }
11385
11386 \f
11387
11388 /* Return non-zero iff TYPE represents a System.Address type. */
11389
11390 int
11391 ada_is_system_address_type (struct type *type)
11392 {
11393 return (type->name () && strcmp (type->name (), "system__address") == 0);
11394 }
11395
11396 \f
11397
11398 /* Range types */
11399
11400 /* Scan STR beginning at position K for a discriminant name, and
11401 return the value of that discriminant field of DVAL in *PX. If
11402 PNEW_K is not null, put the position of the character beyond the
11403 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11404 not alter *PX and *PNEW_K if unsuccessful. */
11405
11406 static int
11407 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11408 int *pnew_k)
11409 {
11410 static std::string storage;
11411 const char *pstart, *pend, *bound;
11412 struct value *bound_val;
11413
11414 if (dval == NULL || str == NULL || str[k] == '\0')
11415 return 0;
11416
11417 pstart = str + k;
11418 pend = strstr (pstart, "__");
11419 if (pend == NULL)
11420 {
11421 bound = pstart;
11422 k += strlen (bound);
11423 }
11424 else
11425 {
11426 int len = pend - pstart;
11427
11428 /* Strip __ and beyond. */
11429 storage = std::string (pstart, len);
11430 bound = storage.c_str ();
11431 k = pend - str;
11432 }
11433
11434 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
11435 if (bound_val == NULL)
11436 return 0;
11437
11438 *px = value_as_long (bound_val);
11439 if (pnew_k != NULL)
11440 *pnew_k = k;
11441 return 1;
11442 }
11443
11444 /* Value of variable named NAME. Only exact matches are considered.
11445 If no such variable found, then if ERR_MSG is null, returns 0, and
11446 otherwise causes an error with message ERR_MSG. */
11447
11448 static struct value *
11449 get_var_value (const char *name, const char *err_msg)
11450 {
11451 std::string quoted_name = add_angle_brackets (name);
11452
11453 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11454
11455 std::vector<struct block_symbol> syms
11456 = ada_lookup_symbol_list_worker (lookup_name,
11457 get_selected_block (0),
11458 VAR_DOMAIN, 1);
11459
11460 if (syms.size () != 1)
11461 {
11462 if (err_msg == NULL)
11463 return 0;
11464 else
11465 error (("%s"), err_msg);
11466 }
11467
11468 return value_of_variable (syms[0].symbol, syms[0].block);
11469 }
11470
11471 /* Value of integer variable named NAME in the current environment.
11472 If no such variable is found, returns false. Otherwise, sets VALUE
11473 to the variable's value and returns true. */
11474
11475 bool
11476 get_int_var_value (const char *name, LONGEST &value)
11477 {
11478 struct value *var_val = get_var_value (name, 0);
11479
11480 if (var_val == 0)
11481 return false;
11482
11483 value = value_as_long (var_val);
11484 return true;
11485 }
11486
11487
11488 /* Return a range type whose base type is that of the range type named
11489 NAME in the current environment, and whose bounds are calculated
11490 from NAME according to the GNAT range encoding conventions.
11491 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11492 corresponding range type from debug information; fall back to using it
11493 if symbol lookup fails. If a new type must be created, allocate it
11494 like ORIG_TYPE was. The bounds information, in general, is encoded
11495 in NAME, the base type given in the named range type. */
11496
11497 static struct type *
11498 to_fixed_range_type (struct type *raw_type, struct value *dval)
11499 {
11500 const char *name;
11501 struct type *base_type;
11502 const char *subtype_info;
11503
11504 gdb_assert (raw_type != NULL);
11505 gdb_assert (raw_type->name () != NULL);
11506
11507 if (raw_type->code () == TYPE_CODE_RANGE)
11508 base_type = raw_type->target_type ();
11509 else
11510 base_type = raw_type;
11511
11512 name = raw_type->name ();
11513 subtype_info = strstr (name, "___XD");
11514 if (subtype_info == NULL)
11515 {
11516 LONGEST L = ada_discrete_type_low_bound (raw_type);
11517 LONGEST U = ada_discrete_type_high_bound (raw_type);
11518
11519 if (L < INT_MIN || U > INT_MAX)
11520 return raw_type;
11521 else
11522 {
11523 type_allocator alloc (raw_type);
11524 return create_static_range_type (alloc, raw_type, L, U);
11525 }
11526 }
11527 else
11528 {
11529 int prefix_len = subtype_info - name;
11530 LONGEST L, U;
11531 struct type *type;
11532 const char *bounds_str;
11533 int n;
11534
11535 subtype_info += 5;
11536 bounds_str = strchr (subtype_info, '_');
11537 n = 1;
11538
11539 if (*subtype_info == 'L')
11540 {
11541 if (!ada_scan_number (bounds_str, n, &L, &n)
11542 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11543 return raw_type;
11544 if (bounds_str[n] == '_')
11545 n += 2;
11546 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11547 n += 1;
11548 subtype_info += 1;
11549 }
11550 else
11551 {
11552 std::string name_buf = std::string (name, prefix_len) + "___L";
11553 if (!get_int_var_value (name_buf.c_str (), L))
11554 {
11555 lim_warning (_("Unknown lower bound, using 1."));
11556 L = 1;
11557 }
11558 }
11559
11560 if (*subtype_info == 'U')
11561 {
11562 if (!ada_scan_number (bounds_str, n, &U, &n)
11563 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11564 return raw_type;
11565 }
11566 else
11567 {
11568 std::string name_buf = std::string (name, prefix_len) + "___U";
11569 if (!get_int_var_value (name_buf.c_str (), U))
11570 {
11571 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11572 U = L;
11573 }
11574 }
11575
11576 type_allocator alloc (raw_type);
11577 type = create_static_range_type (alloc, base_type, L, U);
11578 /* create_static_range_type alters the resulting type's length
11579 to match the size of the base_type, which is not what we want.
11580 Set it back to the original range type's length. */
11581 type->set_length (raw_type->length ());
11582 type->set_name (name);
11583 return type;
11584 }
11585 }
11586
11587 /* True iff NAME is the name of a range type. */
11588
11589 int
11590 ada_is_range_type_name (const char *name)
11591 {
11592 return (name != NULL && strstr (name, "___XD"));
11593 }
11594 \f
11595
11596 /* Modular types */
11597
11598 /* True iff TYPE is an Ada modular type. */
11599
11600 int
11601 ada_is_modular_type (struct type *type)
11602 {
11603 struct type *subranged_type = get_base_type (type);
11604
11605 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11606 && subranged_type->code () == TYPE_CODE_INT
11607 && subranged_type->is_unsigned ());
11608 }
11609
11610 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11611
11612 ULONGEST
11613 ada_modulus (struct type *type)
11614 {
11615 const dynamic_prop &high = type->bounds ()->high;
11616
11617 if (high.kind () == PROP_CONST)
11618 return (ULONGEST) high.const_val () + 1;
11619
11620 /* If TYPE is unresolved, the high bound might be a location list. Return
11621 0, for lack of a better value to return. */
11622 return 0;
11623 }
11624 \f
11625
11626 /* Ada exception catchpoint support:
11627 ---------------------------------
11628
11629 We support 3 kinds of exception catchpoints:
11630 . catchpoints on Ada exceptions
11631 . catchpoints on unhandled Ada exceptions
11632 . catchpoints on failed assertions
11633
11634 Exceptions raised during failed assertions, or unhandled exceptions
11635 could perfectly be caught with the general catchpoint on Ada exceptions.
11636 However, we can easily differentiate these two special cases, and having
11637 the option to distinguish these two cases from the rest can be useful
11638 to zero-in on certain situations.
11639
11640 Exception catchpoints are a specialized form of breakpoint,
11641 since they rely on inserting breakpoints inside known routines
11642 of the GNAT runtime. The implementation therefore uses a standard
11643 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11644 of breakpoint_ops.
11645
11646 Support in the runtime for exception catchpoints have been changed
11647 a few times already, and these changes affect the implementation
11648 of these catchpoints. In order to be able to support several
11649 variants of the runtime, we use a sniffer that will determine
11650 the runtime variant used by the program being debugged. */
11651
11652 /* Ada's standard exceptions.
11653
11654 The Ada 83 standard also defined Numeric_Error. But there so many
11655 situations where it was unclear from the Ada 83 Reference Manual
11656 (RM) whether Constraint_Error or Numeric_Error should be raised,
11657 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11658 Interpretation saying that anytime the RM says that Numeric_Error
11659 should be raised, the implementation may raise Constraint_Error.
11660 Ada 95 went one step further and pretty much removed Numeric_Error
11661 from the list of standard exceptions (it made it a renaming of
11662 Constraint_Error, to help preserve compatibility when compiling
11663 an Ada83 compiler). As such, we do not include Numeric_Error from
11664 this list of standard exceptions. */
11665
11666 static const char * const standard_exc[] = {
11667 "constraint_error",
11668 "program_error",
11669 "storage_error",
11670 "tasking_error"
11671 };
11672
11673 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11674
11675 /* A structure that describes how to support exception catchpoints
11676 for a given executable. */
11677
11678 struct exception_support_info
11679 {
11680 /* The name of the symbol to break on in order to insert
11681 a catchpoint on exceptions. */
11682 const char *catch_exception_sym;
11683
11684 /* The name of the symbol to break on in order to insert
11685 a catchpoint on unhandled exceptions. */
11686 const char *catch_exception_unhandled_sym;
11687
11688 /* The name of the symbol to break on in order to insert
11689 a catchpoint on failed assertions. */
11690 const char *catch_assert_sym;
11691
11692 /* The name of the symbol to break on in order to insert
11693 a catchpoint on exception handling. */
11694 const char *catch_handlers_sym;
11695
11696 /* Assuming that the inferior just triggered an unhandled exception
11697 catchpoint, this function is responsible for returning the address
11698 in inferior memory where the name of that exception is stored.
11699 Return zero if the address could not be computed. */
11700 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11701 };
11702
11703 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11704 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11705
11706 /* The following exception support info structure describes how to
11707 implement exception catchpoints with the latest version of the
11708 Ada runtime (as of 2019-08-??). */
11709
11710 static const struct exception_support_info default_exception_support_info =
11711 {
11712 "__gnat_debug_raise_exception", /* catch_exception_sym */
11713 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11714 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11715 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11716 ada_unhandled_exception_name_addr
11717 };
11718
11719 /* The following exception support info structure describes how to
11720 implement exception catchpoints with an earlier version of the
11721 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11722
11723 static const struct exception_support_info exception_support_info_v0 =
11724 {
11725 "__gnat_debug_raise_exception", /* catch_exception_sym */
11726 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11727 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11728 "__gnat_begin_handler", /* catch_handlers_sym */
11729 ada_unhandled_exception_name_addr
11730 };
11731
11732 /* The following exception support info structure describes how to
11733 implement exception catchpoints with a slightly older version
11734 of the Ada runtime. */
11735
11736 static const struct exception_support_info exception_support_info_fallback =
11737 {
11738 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11739 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11740 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11741 "__gnat_begin_handler", /* catch_handlers_sym */
11742 ada_unhandled_exception_name_addr_from_raise
11743 };
11744
11745 /* Return nonzero if we can detect the exception support routines
11746 described in EINFO.
11747
11748 This function errors out if an abnormal situation is detected
11749 (for instance, if we find the exception support routines, but
11750 that support is found to be incomplete). */
11751
11752 static int
11753 ada_has_this_exception_support (const struct exception_support_info *einfo)
11754 {
11755 struct symbol *sym;
11756
11757 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11758 that should be compiled with debugging information. As a result, we
11759 expect to find that symbol in the symtabs. */
11760
11761 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11762 if (sym == NULL)
11763 {
11764 /* Perhaps we did not find our symbol because the Ada runtime was
11765 compiled without debugging info, or simply stripped of it.
11766 It happens on some GNU/Linux distributions for instance, where
11767 users have to install a separate debug package in order to get
11768 the runtime's debugging info. In that situation, let the user
11769 know why we cannot insert an Ada exception catchpoint.
11770
11771 Note: Just for the purpose of inserting our Ada exception
11772 catchpoint, we could rely purely on the associated minimal symbol.
11773 But we would be operating in degraded mode anyway, since we are
11774 still lacking the debugging info needed later on to extract
11775 the name of the exception being raised (this name is printed in
11776 the catchpoint message, and is also used when trying to catch
11777 a specific exception). We do not handle this case for now. */
11778 struct bound_minimal_symbol msym
11779 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11780
11781 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11782 error (_("Your Ada runtime appears to be missing some debugging "
11783 "information.\nCannot insert Ada exception catchpoint "
11784 "in this configuration."));
11785
11786 return 0;
11787 }
11788
11789 /* Make sure that the symbol we found corresponds to a function. */
11790
11791 if (sym->aclass () != LOC_BLOCK)
11792 error (_("Symbol \"%s\" is not a function (class = %d)"),
11793 sym->linkage_name (), sym->aclass ());
11794
11795 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11796 if (sym == NULL)
11797 {
11798 struct bound_minimal_symbol msym
11799 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11800
11801 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
11802 error (_("Your Ada runtime appears to be missing some debugging "
11803 "information.\nCannot insert Ada exception catchpoint "
11804 "in this configuration."));
11805
11806 return 0;
11807 }
11808
11809 /* Make sure that the symbol we found corresponds to a function. */
11810
11811 if (sym->aclass () != LOC_BLOCK)
11812 error (_("Symbol \"%s\" is not a function (class = %d)"),
11813 sym->linkage_name (), sym->aclass ());
11814
11815 return 1;
11816 }
11817
11818 /* Inspect the Ada runtime and determine which exception info structure
11819 should be used to provide support for exception catchpoints.
11820
11821 This function will always set the per-inferior exception_info,
11822 or raise an error. */
11823
11824 static void
11825 ada_exception_support_info_sniffer (void)
11826 {
11827 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11828
11829 /* If the exception info is already known, then no need to recompute it. */
11830 if (data->exception_info != NULL)
11831 return;
11832
11833 /* Check the latest (default) exception support info. */
11834 if (ada_has_this_exception_support (&default_exception_support_info))
11835 {
11836 data->exception_info = &default_exception_support_info;
11837 return;
11838 }
11839
11840 /* Try the v0 exception suport info. */
11841 if (ada_has_this_exception_support (&exception_support_info_v0))
11842 {
11843 data->exception_info = &exception_support_info_v0;
11844 return;
11845 }
11846
11847 /* Try our fallback exception suport info. */
11848 if (ada_has_this_exception_support (&exception_support_info_fallback))
11849 {
11850 data->exception_info = &exception_support_info_fallback;
11851 return;
11852 }
11853
11854 /* Sometimes, it is normal for us to not be able to find the routine
11855 we are looking for. This happens when the program is linked with
11856 the shared version of the GNAT runtime, and the program has not been
11857 started yet. Inform the user of these two possible causes if
11858 applicable. */
11859
11860 if (ada_update_initial_language (language_unknown) != language_ada)
11861 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
11862
11863 /* If the symbol does not exist, then check that the program is
11864 already started, to make sure that shared libraries have been
11865 loaded. If it is not started, this may mean that the symbol is
11866 in a shared library. */
11867
11868 if (inferior_ptid.pid () == 0)
11869 error (_("Unable to insert catchpoint. Try to start the program first."));
11870
11871 /* At this point, we know that we are debugging an Ada program and
11872 that the inferior has been started, but we still are not able to
11873 find the run-time symbols. That can mean that we are in
11874 configurable run time mode, or that a-except as been optimized
11875 out by the linker... In any case, at this point it is not worth
11876 supporting this feature. */
11877
11878 error (_("Cannot insert Ada exception catchpoints in this configuration."));
11879 }
11880
11881 /* True iff FRAME is very likely to be that of a function that is
11882 part of the runtime system. This is all very heuristic, but is
11883 intended to be used as advice as to what frames are uninteresting
11884 to most users. */
11885
11886 static int
11887 is_known_support_routine (frame_info_ptr frame)
11888 {
11889 enum language func_lang;
11890 int i;
11891 const char *fullname;
11892
11893 /* If this code does not have any debugging information (no symtab),
11894 This cannot be any user code. */
11895
11896 symtab_and_line sal = find_frame_sal (frame);
11897 if (sal.symtab == NULL)
11898 return 1;
11899
11900 /* If there is a symtab, but the associated source file cannot be
11901 located, then assume this is not user code: Selecting a frame
11902 for which we cannot display the code would not be very helpful
11903 for the user. This should also take care of case such as VxWorks
11904 where the kernel has some debugging info provided for a few units. */
11905
11906 fullname = symtab_to_fullname (sal.symtab);
11907 if (access (fullname, R_OK) != 0)
11908 return 1;
11909
11910 /* Check the unit filename against the Ada runtime file naming.
11911 We also check the name of the objfile against the name of some
11912 known system libraries that sometimes come with debugging info
11913 too. */
11914
11915 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11916 {
11917 re_comp (known_runtime_file_name_patterns[i]);
11918 if (re_exec (lbasename (sal.symtab->filename)))
11919 return 1;
11920 if (sal.symtab->compunit ()->objfile () != NULL
11921 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
11922 return 1;
11923 }
11924
11925 /* Check whether the function is a GNAT-generated entity. */
11926
11927 gdb::unique_xmalloc_ptr<char> func_name
11928 = find_frame_funname (frame, &func_lang, NULL);
11929 if (func_name == NULL)
11930 return 1;
11931
11932 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11933 {
11934 re_comp (known_auxiliary_function_name_patterns[i]);
11935 if (re_exec (func_name.get ()))
11936 return 1;
11937 }
11938
11939 return 0;
11940 }
11941
11942 /* Find the first frame that contains debugging information and that is not
11943 part of the Ada run-time, starting from FI and moving upward. */
11944
11945 void
11946 ada_find_printable_frame (frame_info_ptr fi)
11947 {
11948 for (; fi != NULL; fi = get_prev_frame (fi))
11949 {
11950 if (!is_known_support_routine (fi))
11951 {
11952 select_frame (fi);
11953 break;
11954 }
11955 }
11956
11957 }
11958
11959 /* Assuming that the inferior just triggered an unhandled exception
11960 catchpoint, return the address in inferior memory where the name
11961 of the exception is stored.
11962
11963 Return zero if the address could not be computed. */
11964
11965 static CORE_ADDR
11966 ada_unhandled_exception_name_addr (void)
11967 {
11968 return parse_and_eval_address ("e.full_name");
11969 }
11970
11971 /* Same as ada_unhandled_exception_name_addr, except that this function
11972 should be used when the inferior uses an older version of the runtime,
11973 where the exception name needs to be extracted from a specific frame
11974 several frames up in the callstack. */
11975
11976 static CORE_ADDR
11977 ada_unhandled_exception_name_addr_from_raise (void)
11978 {
11979 int frame_level;
11980 frame_info_ptr fi;
11981 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11982
11983 /* To determine the name of this exception, we need to select
11984 the frame corresponding to RAISE_SYM_NAME. This frame is
11985 at least 3 levels up, so we simply skip the first 3 frames
11986 without checking the name of their associated function. */
11987 fi = get_current_frame ();
11988 for (frame_level = 0; frame_level < 3; frame_level += 1)
11989 if (fi != NULL)
11990 fi = get_prev_frame (fi);
11991
11992 while (fi != NULL)
11993 {
11994 enum language func_lang;
11995
11996 gdb::unique_xmalloc_ptr<char> func_name
11997 = find_frame_funname (fi, &func_lang, NULL);
11998 if (func_name != NULL)
11999 {
12000 if (strcmp (func_name.get (),
12001 data->exception_info->catch_exception_sym) == 0)
12002 break; /* We found the frame we were looking for... */
12003 }
12004 fi = get_prev_frame (fi);
12005 }
12006
12007 if (fi == NULL)
12008 return 0;
12009
12010 select_frame (fi);
12011 return parse_and_eval_address ("id.full_name");
12012 }
12013
12014 /* Assuming the inferior just triggered an Ada exception catchpoint
12015 (of any type), return the address in inferior memory where the name
12016 of the exception is stored, if applicable.
12017
12018 Assumes the selected frame is the current frame.
12019
12020 Return zero if the address could not be computed, or if not relevant. */
12021
12022 static CORE_ADDR
12023 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
12024 {
12025 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12026
12027 switch (ex)
12028 {
12029 case ada_catch_exception:
12030 return (parse_and_eval_address ("e.full_name"));
12031 break;
12032
12033 case ada_catch_exception_unhandled:
12034 return data->exception_info->unhandled_exception_name_addr ();
12035 break;
12036
12037 case ada_catch_handlers:
12038 return 0; /* The runtimes does not provide access to the exception
12039 name. */
12040 break;
12041
12042 case ada_catch_assert:
12043 return 0; /* Exception name is not relevant in this case. */
12044 break;
12045
12046 default:
12047 internal_error (_("unexpected catchpoint type"));
12048 break;
12049 }
12050
12051 return 0; /* Should never be reached. */
12052 }
12053
12054 /* Assuming the inferior is stopped at an exception catchpoint,
12055 return the message which was associated to the exception, if
12056 available. Return NULL if the message could not be retrieved.
12057
12058 Note: The exception message can be associated to an exception
12059 either through the use of the Raise_Exception function, or
12060 more simply (Ada 2005 and later), via:
12061
12062 raise Exception_Name with "exception message";
12063
12064 */
12065
12066 static gdb::unique_xmalloc_ptr<char>
12067 ada_exception_message_1 (void)
12068 {
12069 struct value *e_msg_val;
12070 int e_msg_len;
12071
12072 /* For runtimes that support this feature, the exception message
12073 is passed as an unbounded string argument called "message". */
12074 e_msg_val = parse_and_eval ("message");
12075 if (e_msg_val == NULL)
12076 return NULL; /* Exception message not supported. */
12077
12078 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12079 gdb_assert (e_msg_val != NULL);
12080 e_msg_len = e_msg_val->type ()->length ();
12081
12082 /* If the message string is empty, then treat it as if there was
12083 no exception message. */
12084 if (e_msg_len <= 0)
12085 return NULL;
12086
12087 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12088 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
12089 e_msg_len);
12090 e_msg.get ()[e_msg_len] = '\0';
12091
12092 return e_msg;
12093 }
12094
12095 /* Same as ada_exception_message_1, except that all exceptions are
12096 contained here (returning NULL instead). */
12097
12098 static gdb::unique_xmalloc_ptr<char>
12099 ada_exception_message (void)
12100 {
12101 gdb::unique_xmalloc_ptr<char> e_msg;
12102
12103 try
12104 {
12105 e_msg = ada_exception_message_1 ();
12106 }
12107 catch (const gdb_exception_error &e)
12108 {
12109 e_msg.reset (nullptr);
12110 }
12111
12112 return e_msg;
12113 }
12114
12115 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12116 any error that ada_exception_name_addr_1 might cause to be thrown.
12117 When an error is intercepted, a warning with the error message is printed,
12118 and zero is returned. */
12119
12120 static CORE_ADDR
12121 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
12122 {
12123 CORE_ADDR result = 0;
12124
12125 try
12126 {
12127 result = ada_exception_name_addr_1 (ex);
12128 }
12129
12130 catch (const gdb_exception_error &e)
12131 {
12132 warning (_("failed to get exception name: %s"), e.what ());
12133 return 0;
12134 }
12135
12136 return result;
12137 }
12138
12139 static std::string ada_exception_catchpoint_cond_string
12140 (const char *excep_string,
12141 enum ada_exception_catchpoint_kind ex);
12142
12143 /* Ada catchpoints.
12144
12145 In the case of catchpoints on Ada exceptions, the catchpoint will
12146 stop the target on every exception the program throws. When a user
12147 specifies the name of a specific exception, we translate this
12148 request into a condition expression (in text form), and then parse
12149 it into an expression stored in each of the catchpoint's locations.
12150 We then use this condition to check whether the exception that was
12151 raised is the one the user is interested in. If not, then the
12152 target is resumed again. We store the name of the requested
12153 exception, in order to be able to re-set the condition expression
12154 when symbols change. */
12155
12156 /* An instance of this type is used to represent an Ada catchpoint. */
12157
12158 struct ada_catchpoint : public code_breakpoint
12159 {
12160 ada_catchpoint (struct gdbarch *gdbarch_,
12161 enum ada_exception_catchpoint_kind kind,
12162 struct symtab_and_line sal,
12163 const char *addr_string_,
12164 bool tempflag,
12165 bool enabled,
12166 bool from_tty)
12167 : code_breakpoint (gdbarch_, bp_catchpoint),
12168 m_kind (kind)
12169 {
12170 add_location (sal);
12171
12172 /* Unlike most code_breakpoint types, Ada catchpoints are
12173 pspace-specific. */
12174 gdb_assert (sal.pspace != nullptr);
12175 this->pspace = sal.pspace;
12176
12177 if (from_tty)
12178 {
12179 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12180 if (!loc_gdbarch)
12181 loc_gdbarch = gdbarch;
12182
12183 describe_other_breakpoints (loc_gdbarch,
12184 sal.pspace, sal.pc, sal.section, -1);
12185 /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12186 version for exception catchpoints, because two catchpoints
12187 used for different exception names will use the same address.
12188 In this case, a "breakpoint ... also set at..." warning is
12189 unproductive. Besides, the warning phrasing is also a bit
12190 inappropriate, we should use the word catchpoint, and tell
12191 the user what type of catchpoint it is. The above is good
12192 enough for now, though. */
12193 }
12194
12195 enable_state = enabled ? bp_enabled : bp_disabled;
12196 disposition = tempflag ? disp_del : disp_donttouch;
12197 locspec = string_to_location_spec (&addr_string_,
12198 language_def (language_ada));
12199 language = language_ada;
12200 }
12201
12202 struct bp_location *allocate_location () override;
12203 void re_set () override;
12204 void check_status (struct bpstat *bs) override;
12205 enum print_stop_action print_it (const bpstat *bs) const override;
12206 bool print_one (bp_location **) const override;
12207 void print_mention () const override;
12208 void print_recreate (struct ui_file *fp) const override;
12209
12210 /* The name of the specific exception the user specified. */
12211 std::string excep_string;
12212
12213 /* What kind of catchpoint this is. */
12214 enum ada_exception_catchpoint_kind m_kind;
12215 };
12216
12217 /* An instance of this type is used to represent an Ada catchpoint
12218 breakpoint location. */
12219
12220 class ada_catchpoint_location : public bp_location
12221 {
12222 public:
12223 explicit ada_catchpoint_location (ada_catchpoint *owner)
12224 : bp_location (owner, bp_loc_software_breakpoint)
12225 {}
12226
12227 /* The condition that checks whether the exception that was raised
12228 is the specific exception the user specified on catchpoint
12229 creation. */
12230 expression_up excep_cond_expr;
12231 };
12232
12233 /* Parse the exception condition string in the context of each of the
12234 catchpoint's locations, and store them for later evaluation. */
12235
12236 static void
12237 create_excep_cond_exprs (struct ada_catchpoint *c,
12238 enum ada_exception_catchpoint_kind ex)
12239 {
12240 /* Nothing to do if there's no specific exception to catch. */
12241 if (c->excep_string.empty ())
12242 return;
12243
12244 /* Same if there are no locations... */
12245 if (c->loc == NULL)
12246 return;
12247
12248 /* Compute the condition expression in text form, from the specific
12249 expection we want to catch. */
12250 std::string cond_string
12251 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12252
12253 /* Iterate over all the catchpoint's locations, and parse an
12254 expression for each. */
12255 for (bp_location *bl : c->locations ())
12256 {
12257 struct ada_catchpoint_location *ada_loc
12258 = (struct ada_catchpoint_location *) bl;
12259 expression_up exp;
12260
12261 if (!bl->shlib_disabled)
12262 {
12263 const char *s;
12264
12265 s = cond_string.c_str ();
12266 try
12267 {
12268 exp = parse_exp_1 (&s, bl->address,
12269 block_for_pc (bl->address),
12270 0);
12271 }
12272 catch (const gdb_exception_error &e)
12273 {
12274 warning (_("failed to reevaluate internal exception condition "
12275 "for catchpoint %d: %s"),
12276 c->number, e.what ());
12277 }
12278 }
12279
12280 ada_loc->excep_cond_expr = std::move (exp);
12281 }
12282 }
12283
12284 /* Implement the ALLOCATE_LOCATION method in the structure for all
12285 exception catchpoint kinds. */
12286
12287 struct bp_location *
12288 ada_catchpoint::allocate_location ()
12289 {
12290 return new ada_catchpoint_location (this);
12291 }
12292
12293 /* Implement the RE_SET method in the structure for all exception
12294 catchpoint kinds. */
12295
12296 void
12297 ada_catchpoint::re_set ()
12298 {
12299 /* Call the base class's method. This updates the catchpoint's
12300 locations. */
12301 this->code_breakpoint::re_set ();
12302
12303 /* Reparse the exception conditional expressions. One for each
12304 location. */
12305 create_excep_cond_exprs (this, m_kind);
12306 }
12307
12308 /* Returns true if we should stop for this breakpoint hit. If the
12309 user specified a specific exception, we only want to cause a stop
12310 if the program thrown that exception. */
12311
12312 static bool
12313 should_stop_exception (const struct bp_location *bl)
12314 {
12315 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12316 const struct ada_catchpoint_location *ada_loc
12317 = (const struct ada_catchpoint_location *) bl;
12318 bool stop;
12319
12320 struct internalvar *var = lookup_internalvar ("_ada_exception");
12321 if (c->m_kind == ada_catch_assert)
12322 clear_internalvar (var);
12323 else
12324 {
12325 try
12326 {
12327 const char *expr;
12328
12329 if (c->m_kind == ada_catch_handlers)
12330 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12331 ".all.occurrence.id");
12332 else
12333 expr = "e";
12334
12335 struct value *exc = parse_and_eval (expr);
12336 set_internalvar (var, exc);
12337 }
12338 catch (const gdb_exception_error &ex)
12339 {
12340 clear_internalvar (var);
12341 }
12342 }
12343
12344 /* With no specific exception, should always stop. */
12345 if (c->excep_string.empty ())
12346 return true;
12347
12348 if (ada_loc->excep_cond_expr == NULL)
12349 {
12350 /* We will have a NULL expression if back when we were creating
12351 the expressions, this location's had failed to parse. */
12352 return true;
12353 }
12354
12355 stop = true;
12356 try
12357 {
12358 scoped_value_mark mark;
12359 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
12360 }
12361 catch (const gdb_exception_error &ex)
12362 {
12363 exception_fprintf (gdb_stderr, ex,
12364 _("Error in testing exception condition:\n"));
12365 }
12366
12367 return stop;
12368 }
12369
12370 /* Implement the CHECK_STATUS method in the structure for all
12371 exception catchpoint kinds. */
12372
12373 void
12374 ada_catchpoint::check_status (bpstat *bs)
12375 {
12376 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12377 }
12378
12379 /* Implement the PRINT_IT method in the structure for all exception
12380 catchpoint kinds. */
12381
12382 enum print_stop_action
12383 ada_catchpoint::print_it (const bpstat *bs) const
12384 {
12385 struct ui_out *uiout = current_uiout;
12386
12387 annotate_catchpoint (number);
12388
12389 if (uiout->is_mi_like_p ())
12390 {
12391 uiout->field_string ("reason",
12392 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12393 uiout->field_string ("disp", bpdisp_text (disposition));
12394 }
12395
12396 uiout->text (disposition == disp_del
12397 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12398 print_num_locno (bs, uiout);
12399 uiout->text (", ");
12400
12401 /* ada_exception_name_addr relies on the selected frame being the
12402 current frame. Need to do this here because this function may be
12403 called more than once when printing a stop, and below, we'll
12404 select the first frame past the Ada run-time (see
12405 ada_find_printable_frame). */
12406 select_frame (get_current_frame ());
12407
12408 switch (m_kind)
12409 {
12410 case ada_catch_exception:
12411 case ada_catch_exception_unhandled:
12412 case ada_catch_handlers:
12413 {
12414 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
12415 char exception_name[256];
12416
12417 if (addr != 0)
12418 {
12419 read_memory (addr, (gdb_byte *) exception_name,
12420 sizeof (exception_name) - 1);
12421 exception_name [sizeof (exception_name) - 1] = '\0';
12422 }
12423 else
12424 {
12425 /* For some reason, we were unable to read the exception
12426 name. This could happen if the Runtime was compiled
12427 without debugging info, for instance. In that case,
12428 just replace the exception name by the generic string
12429 "exception" - it will read as "an exception" in the
12430 notification we are about to print. */
12431 memcpy (exception_name, "exception", sizeof ("exception"));
12432 }
12433 /* In the case of unhandled exception breakpoints, we print
12434 the exception name as "unhandled EXCEPTION_NAME", to make
12435 it clearer to the user which kind of catchpoint just got
12436 hit. We used ui_out_text to make sure that this extra
12437 info does not pollute the exception name in the MI case. */
12438 if (m_kind == ada_catch_exception_unhandled)
12439 uiout->text ("unhandled ");
12440 uiout->field_string ("exception-name", exception_name);
12441 }
12442 break;
12443 case ada_catch_assert:
12444 /* In this case, the name of the exception is not really
12445 important. Just print "failed assertion" to make it clearer
12446 that his program just hit an assertion-failure catchpoint.
12447 We used ui_out_text because this info does not belong in
12448 the MI output. */
12449 uiout->text ("failed assertion");
12450 break;
12451 }
12452
12453 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12454 if (exception_message != NULL)
12455 {
12456 uiout->text (" (");
12457 uiout->field_string ("exception-message", exception_message.get ());
12458 uiout->text (")");
12459 }
12460
12461 uiout->text (" at ");
12462 ada_find_printable_frame (get_current_frame ());
12463
12464 return PRINT_SRC_AND_LOC;
12465 }
12466
12467 /* Implement the PRINT_ONE method in the structure for all exception
12468 catchpoint kinds. */
12469
12470 bool
12471 ada_catchpoint::print_one (bp_location **last_loc) const
12472 {
12473 struct ui_out *uiout = current_uiout;
12474 struct value_print_options opts;
12475
12476 get_user_print_options (&opts);
12477
12478 if (opts.addressprint)
12479 uiout->field_skip ("addr");
12480
12481 annotate_field (5);
12482 switch (m_kind)
12483 {
12484 case ada_catch_exception:
12485 if (!excep_string.empty ())
12486 {
12487 std::string msg = string_printf (_("`%s' Ada exception"),
12488 excep_string.c_str ());
12489
12490 uiout->field_string ("what", msg);
12491 }
12492 else
12493 uiout->field_string ("what", "all Ada exceptions");
12494
12495 break;
12496
12497 case ada_catch_exception_unhandled:
12498 uiout->field_string ("what", "unhandled Ada exceptions");
12499 break;
12500
12501 case ada_catch_handlers:
12502 if (!excep_string.empty ())
12503 {
12504 uiout->field_fmt ("what",
12505 _("`%s' Ada exception handlers"),
12506 excep_string.c_str ());
12507 }
12508 else
12509 uiout->field_string ("what", "all Ada exceptions handlers");
12510 break;
12511
12512 case ada_catch_assert:
12513 uiout->field_string ("what", "failed Ada assertions");
12514 break;
12515
12516 default:
12517 internal_error (_("unexpected catchpoint type"));
12518 break;
12519 }
12520
12521 return true;
12522 }
12523
12524 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12525 for all exception catchpoint kinds. */
12526
12527 void
12528 ada_catchpoint::print_mention () const
12529 {
12530 struct ui_out *uiout = current_uiout;
12531
12532 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
12533 : _("Catchpoint "));
12534 uiout->field_signed ("bkptno", number);
12535 uiout->text (": ");
12536
12537 switch (m_kind)
12538 {
12539 case ada_catch_exception:
12540 if (!excep_string.empty ())
12541 {
12542 std::string info = string_printf (_("`%s' Ada exception"),
12543 excep_string.c_str ());
12544 uiout->text (info);
12545 }
12546 else
12547 uiout->text (_("all Ada exceptions"));
12548 break;
12549
12550 case ada_catch_exception_unhandled:
12551 uiout->text (_("unhandled Ada exceptions"));
12552 break;
12553
12554 case ada_catch_handlers:
12555 if (!excep_string.empty ())
12556 {
12557 std::string info
12558 = string_printf (_("`%s' Ada exception handlers"),
12559 excep_string.c_str ());
12560 uiout->text (info);
12561 }
12562 else
12563 uiout->text (_("all Ada exceptions handlers"));
12564 break;
12565
12566 case ada_catch_assert:
12567 uiout->text (_("failed Ada assertions"));
12568 break;
12569
12570 default:
12571 internal_error (_("unexpected catchpoint type"));
12572 break;
12573 }
12574 }
12575
12576 /* Implement the PRINT_RECREATE method in the structure for all
12577 exception catchpoint kinds. */
12578
12579 void
12580 ada_catchpoint::print_recreate (struct ui_file *fp) const
12581 {
12582 switch (m_kind)
12583 {
12584 case ada_catch_exception:
12585 gdb_printf (fp, "catch exception");
12586 if (!excep_string.empty ())
12587 gdb_printf (fp, " %s", excep_string.c_str ());
12588 break;
12589
12590 case ada_catch_exception_unhandled:
12591 gdb_printf (fp, "catch exception unhandled");
12592 break;
12593
12594 case ada_catch_handlers:
12595 gdb_printf (fp, "catch handlers");
12596 break;
12597
12598 case ada_catch_assert:
12599 gdb_printf (fp, "catch assert");
12600 break;
12601
12602 default:
12603 internal_error (_("unexpected catchpoint type"));
12604 }
12605 print_recreate_thread (fp);
12606 }
12607
12608 /* See ada-lang.h. */
12609
12610 bool
12611 is_ada_exception_catchpoint (breakpoint *bp)
12612 {
12613 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
12614 }
12615
12616 /* Split the arguments specified in a "catch exception" command.
12617 Set EX to the appropriate catchpoint type.
12618 Set EXCEP_STRING to the name of the specific exception if
12619 specified by the user.
12620 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12621 "catch handlers" command. False otherwise.
12622 If a condition is found at the end of the arguments, the condition
12623 expression is stored in COND_STRING (memory must be deallocated
12624 after use). Otherwise COND_STRING is set to NULL. */
12625
12626 static void
12627 catch_ada_exception_command_split (const char *args,
12628 bool is_catch_handlers_cmd,
12629 enum ada_exception_catchpoint_kind *ex,
12630 std::string *excep_string,
12631 std::string *cond_string)
12632 {
12633 std::string exception_name;
12634
12635 exception_name = extract_arg (&args);
12636 if (exception_name == "if")
12637 {
12638 /* This is not an exception name; this is the start of a condition
12639 expression for a catchpoint on all exceptions. So, "un-get"
12640 this token, and set exception_name to NULL. */
12641 exception_name.clear ();
12642 args -= 2;
12643 }
12644
12645 /* Check to see if we have a condition. */
12646
12647 args = skip_spaces (args);
12648 if (startswith (args, "if")
12649 && (isspace (args[2]) || args[2] == '\0'))
12650 {
12651 args += 2;
12652 args = skip_spaces (args);
12653
12654 if (args[0] == '\0')
12655 error (_("Condition missing after `if' keyword"));
12656 *cond_string = args;
12657
12658 args += strlen (args);
12659 }
12660
12661 /* Check that we do not have any more arguments. Anything else
12662 is unexpected. */
12663
12664 if (args[0] != '\0')
12665 error (_("Junk at end of expression"));
12666
12667 if (is_catch_handlers_cmd)
12668 {
12669 /* Catch handling of exceptions. */
12670 *ex = ada_catch_handlers;
12671 *excep_string = exception_name;
12672 }
12673 else if (exception_name.empty ())
12674 {
12675 /* Catch all exceptions. */
12676 *ex = ada_catch_exception;
12677 excep_string->clear ();
12678 }
12679 else if (exception_name == "unhandled")
12680 {
12681 /* Catch unhandled exceptions. */
12682 *ex = ada_catch_exception_unhandled;
12683 excep_string->clear ();
12684 }
12685 else
12686 {
12687 /* Catch a specific exception. */
12688 *ex = ada_catch_exception;
12689 *excep_string = exception_name;
12690 }
12691 }
12692
12693 /* Return the name of the symbol on which we should break in order to
12694 implement a catchpoint of the EX kind. */
12695
12696 static const char *
12697 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12698 {
12699 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12700
12701 gdb_assert (data->exception_info != NULL);
12702
12703 switch (ex)
12704 {
12705 case ada_catch_exception:
12706 return (data->exception_info->catch_exception_sym);
12707 break;
12708 case ada_catch_exception_unhandled:
12709 return (data->exception_info->catch_exception_unhandled_sym);
12710 break;
12711 case ada_catch_assert:
12712 return (data->exception_info->catch_assert_sym);
12713 break;
12714 case ada_catch_handlers:
12715 return (data->exception_info->catch_handlers_sym);
12716 break;
12717 default:
12718 internal_error (_("unexpected catchpoint kind (%d)"), ex);
12719 }
12720 }
12721
12722 /* Return the condition that will be used to match the current exception
12723 being raised with the exception that the user wants to catch. This
12724 assumes that this condition is used when the inferior just triggered
12725 an exception catchpoint.
12726 EX: the type of catchpoints used for catching Ada exceptions. */
12727
12728 static std::string
12729 ada_exception_catchpoint_cond_string (const char *excep_string,
12730 enum ada_exception_catchpoint_kind ex)
12731 {
12732 bool is_standard_exc = false;
12733 std::string result;
12734
12735 if (ex == ada_catch_handlers)
12736 {
12737 /* For exception handlers catchpoints, the condition string does
12738 not use the same parameter as for the other exceptions. */
12739 result = ("long_integer (GNAT_GCC_exception_Access"
12740 "(gcc_exception).all.occurrence.id)");
12741 }
12742 else
12743 result = "long_integer (e)";
12744
12745 /* The standard exceptions are a special case. They are defined in
12746 runtime units that have been compiled without debugging info; if
12747 EXCEP_STRING is the not-fully-qualified name of a standard
12748 exception (e.g. "constraint_error") then, during the evaluation
12749 of the condition expression, the symbol lookup on this name would
12750 *not* return this standard exception. The catchpoint condition
12751 may then be set only on user-defined exceptions which have the
12752 same not-fully-qualified name (e.g. my_package.constraint_error).
12753
12754 To avoid this unexcepted behavior, these standard exceptions are
12755 systematically prefixed by "standard". This means that "catch
12756 exception constraint_error" is rewritten into "catch exception
12757 standard.constraint_error".
12758
12759 If an exception named constraint_error is defined in another package of
12760 the inferior program, then the only way to specify this exception as a
12761 breakpoint condition is to use its fully-qualified named:
12762 e.g. my_package.constraint_error. */
12763
12764 for (const char *name : standard_exc)
12765 {
12766 if (strcmp (name, excep_string) == 0)
12767 {
12768 is_standard_exc = true;
12769 break;
12770 }
12771 }
12772
12773 result += " = ";
12774
12775 if (is_standard_exc)
12776 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12777 else
12778 string_appendf (result, "long_integer (&%s)", excep_string);
12779
12780 return result;
12781 }
12782
12783 /* Return the symtab_and_line that should be used to insert an exception
12784 catchpoint of the TYPE kind.
12785
12786 ADDR_STRING returns the name of the function where the real
12787 breakpoint that implements the catchpoints is set, depending on the
12788 type of catchpoint we need to create. */
12789
12790 static struct symtab_and_line
12791 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12792 std::string *addr_string)
12793 {
12794 const char *sym_name;
12795 struct symbol *sym;
12796
12797 /* First, find out which exception support info to use. */
12798 ada_exception_support_info_sniffer ();
12799
12800 /* Then lookup the function on which we will break in order to catch
12801 the Ada exceptions requested by the user. */
12802 sym_name = ada_exception_sym_name (ex);
12803 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12804
12805 if (sym == NULL)
12806 error (_("Catchpoint symbol not found: %s"), sym_name);
12807
12808 if (sym->aclass () != LOC_BLOCK)
12809 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12810
12811 /* Set ADDR_STRING. */
12812 *addr_string = sym_name;
12813
12814 return find_function_start_sal (sym, 1);
12815 }
12816
12817 /* Create an Ada exception catchpoint.
12818
12819 EX_KIND is the kind of exception catchpoint to be created.
12820
12821 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12822 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12823 of the exception to which this catchpoint applies.
12824
12825 COND_STRING, if not empty, is the catchpoint condition.
12826
12827 TEMPFLAG, if nonzero, means that the underlying breakpoint
12828 should be temporary.
12829
12830 FROM_TTY is the usual argument passed to all commands implementations. */
12831
12832 void
12833 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12834 enum ada_exception_catchpoint_kind ex_kind,
12835 const std::string &excep_string,
12836 const std::string &cond_string,
12837 int tempflag,
12838 int enabled,
12839 int from_tty)
12840 {
12841 std::string addr_string;
12842 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string);
12843
12844 std::unique_ptr<ada_catchpoint> c
12845 (new ada_catchpoint (gdbarch, ex_kind, sal, addr_string.c_str (),
12846 tempflag, enabled, from_tty));
12847 c->excep_string = excep_string;
12848 create_excep_cond_exprs (c.get (), ex_kind);
12849 if (!cond_string.empty ())
12850 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
12851 install_breakpoint (0, std::move (c), 1);
12852 }
12853
12854 /* Implement the "catch exception" command. */
12855
12856 static void
12857 catch_ada_exception_command (const char *arg_entry, int from_tty,
12858 struct cmd_list_element *command)
12859 {
12860 const char *arg = arg_entry;
12861 struct gdbarch *gdbarch = get_current_arch ();
12862 int tempflag;
12863 enum ada_exception_catchpoint_kind ex_kind;
12864 std::string excep_string;
12865 std::string cond_string;
12866
12867 tempflag = command->context () == CATCH_TEMPORARY;
12868
12869 if (!arg)
12870 arg = "";
12871 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12872 &cond_string);
12873 create_ada_exception_catchpoint (gdbarch, ex_kind,
12874 excep_string, cond_string,
12875 tempflag, 1 /* enabled */,
12876 from_tty);
12877 }
12878
12879 /* Implement the "catch handlers" command. */
12880
12881 static void
12882 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12883 struct cmd_list_element *command)
12884 {
12885 const char *arg = arg_entry;
12886 struct gdbarch *gdbarch = get_current_arch ();
12887 int tempflag;
12888 enum ada_exception_catchpoint_kind ex_kind;
12889 std::string excep_string;
12890 std::string cond_string;
12891
12892 tempflag = command->context () == CATCH_TEMPORARY;
12893
12894 if (!arg)
12895 arg = "";
12896 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12897 &cond_string);
12898 create_ada_exception_catchpoint (gdbarch, ex_kind,
12899 excep_string, cond_string,
12900 tempflag, 1 /* enabled */,
12901 from_tty);
12902 }
12903
12904 /* Completion function for the Ada "catch" commands. */
12905
12906 static void
12907 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12908 const char *text, const char *word)
12909 {
12910 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12911
12912 for (const ada_exc_info &info : exceptions)
12913 {
12914 if (startswith (info.name, word))
12915 tracker.add_completion (make_unique_xstrdup (info.name));
12916 }
12917 }
12918
12919 /* Split the arguments specified in a "catch assert" command.
12920
12921 ARGS contains the command's arguments (or the empty string if
12922 no arguments were passed).
12923
12924 If ARGS contains a condition, set COND_STRING to that condition
12925 (the memory needs to be deallocated after use). */
12926
12927 static void
12928 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12929 {
12930 args = skip_spaces (args);
12931
12932 /* Check whether a condition was provided. */
12933 if (startswith (args, "if")
12934 && (isspace (args[2]) || args[2] == '\0'))
12935 {
12936 args += 2;
12937 args = skip_spaces (args);
12938 if (args[0] == '\0')
12939 error (_("condition missing after `if' keyword"));
12940 cond_string.assign (args);
12941 }
12942
12943 /* Otherwise, there should be no other argument at the end of
12944 the command. */
12945 else if (args[0] != '\0')
12946 error (_("Junk at end of arguments."));
12947 }
12948
12949 /* Implement the "catch assert" command. */
12950
12951 static void
12952 catch_assert_command (const char *arg_entry, int from_tty,
12953 struct cmd_list_element *command)
12954 {
12955 const char *arg = arg_entry;
12956 struct gdbarch *gdbarch = get_current_arch ();
12957 int tempflag;
12958 std::string cond_string;
12959
12960 tempflag = command->context () == CATCH_TEMPORARY;
12961
12962 if (!arg)
12963 arg = "";
12964 catch_ada_assert_command_split (arg, cond_string);
12965 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12966 "", cond_string,
12967 tempflag, 1 /* enabled */,
12968 from_tty);
12969 }
12970
12971 /* Return non-zero if the symbol SYM is an Ada exception object. */
12972
12973 static int
12974 ada_is_exception_sym (struct symbol *sym)
12975 {
12976 const char *type_name = sym->type ()->name ();
12977
12978 return (sym->aclass () != LOC_TYPEDEF
12979 && sym->aclass () != LOC_BLOCK
12980 && sym->aclass () != LOC_CONST
12981 && sym->aclass () != LOC_UNRESOLVED
12982 && type_name != NULL && strcmp (type_name, "exception") == 0);
12983 }
12984
12985 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12986 Ada exception object. This matches all exceptions except the ones
12987 defined by the Ada language. */
12988
12989 static int
12990 ada_is_non_standard_exception_sym (struct symbol *sym)
12991 {
12992 if (!ada_is_exception_sym (sym))
12993 return 0;
12994
12995 for (const char *name : standard_exc)
12996 if (strcmp (sym->linkage_name (), name) == 0)
12997 return 0; /* A standard exception. */
12998
12999 /* Numeric_Error is also a standard exception, so exclude it.
13000 See the STANDARD_EXC description for more details as to why
13001 this exception is not listed in that array. */
13002 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
13003 return 0;
13004
13005 return 1;
13006 }
13007
13008 /* A helper function for std::sort, comparing two struct ada_exc_info
13009 objects.
13010
13011 The comparison is determined first by exception name, and then
13012 by exception address. */
13013
13014 bool
13015 ada_exc_info::operator< (const ada_exc_info &other) const
13016 {
13017 int result;
13018
13019 result = strcmp (name, other.name);
13020 if (result < 0)
13021 return true;
13022 if (result == 0 && addr < other.addr)
13023 return true;
13024 return false;
13025 }
13026
13027 bool
13028 ada_exc_info::operator== (const ada_exc_info &other) const
13029 {
13030 return addr == other.addr && strcmp (name, other.name) == 0;
13031 }
13032
13033 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13034 routine, but keeping the first SKIP elements untouched.
13035
13036 All duplicates are also removed. */
13037
13038 static void
13039 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13040 int skip)
13041 {
13042 std::sort (exceptions->begin () + skip, exceptions->end ());
13043 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13044 exceptions->end ());
13045 }
13046
13047 /* Add all exceptions defined by the Ada standard whose name match
13048 a regular expression.
13049
13050 If PREG is not NULL, then this regexp_t object is used to
13051 perform the symbol name matching. Otherwise, no name-based
13052 filtering is performed.
13053
13054 EXCEPTIONS is a vector of exceptions to which matching exceptions
13055 gets pushed. */
13056
13057 static void
13058 ada_add_standard_exceptions (compiled_regex *preg,
13059 std::vector<ada_exc_info> *exceptions)
13060 {
13061 for (const char *name : standard_exc)
13062 {
13063 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
13064 {
13065 symbol_name_match_type match_type = name_match_type_from_name (name);
13066 lookup_name_info lookup_name (name, match_type);
13067
13068 symbol_name_matcher_ftype *match_name
13069 = ada_get_symbol_name_matcher (lookup_name);
13070
13071 /* Iterate over all objfiles irrespective of scope or linker
13072 namespaces so we get all exceptions anywhere in the
13073 progspace. */
13074 for (objfile *objfile : current_program_space->objfiles ())
13075 {
13076 for (minimal_symbol *msymbol : objfile->msymbols ())
13077 {
13078 if (match_name (msymbol->linkage_name (), lookup_name,
13079 nullptr)
13080 && msymbol->type () != mst_solib_trampoline)
13081 {
13082 ada_exc_info info
13083 = {name, msymbol->value_address (objfile)};
13084
13085 exceptions->push_back (info);
13086 }
13087 }
13088 }
13089 }
13090 }
13091 }
13092
13093 /* Add all Ada exceptions defined locally and accessible from the given
13094 FRAME.
13095
13096 If PREG is not NULL, then this regexp_t object is used to
13097 perform the symbol name matching. Otherwise, no name-based
13098 filtering is performed.
13099
13100 EXCEPTIONS is a vector of exceptions to which matching exceptions
13101 gets pushed. */
13102
13103 static void
13104 ada_add_exceptions_from_frame (compiled_regex *preg,
13105 frame_info_ptr frame,
13106 std::vector<ada_exc_info> *exceptions)
13107 {
13108 const struct block *block = get_frame_block (frame, 0);
13109
13110 while (block != 0)
13111 {
13112 for (struct symbol *sym : block_iterator_range (block))
13113 {
13114 switch (sym->aclass ())
13115 {
13116 case LOC_TYPEDEF:
13117 case LOC_BLOCK:
13118 case LOC_CONST:
13119 break;
13120 default:
13121 if (ada_is_exception_sym (sym))
13122 {
13123 struct ada_exc_info info = {sym->print_name (),
13124 sym->value_address ()};
13125
13126 exceptions->push_back (info);
13127 }
13128 }
13129 }
13130 if (block->function () != NULL)
13131 break;
13132 block = block->superblock ();
13133 }
13134 }
13135
13136 /* Return true if NAME matches PREG or if PREG is NULL. */
13137
13138 static bool
13139 name_matches_regex (const char *name, compiled_regex *preg)
13140 {
13141 return (preg == NULL
13142 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13143 }
13144
13145 /* Add all exceptions defined globally whose name name match
13146 a regular expression, excluding standard exceptions.
13147
13148 The reason we exclude standard exceptions is that they need
13149 to be handled separately: Standard exceptions are defined inside
13150 a runtime unit which is normally not compiled with debugging info,
13151 and thus usually do not show up in our symbol search. However,
13152 if the unit was in fact built with debugging info, we need to
13153 exclude them because they would duplicate the entry we found
13154 during the special loop that specifically searches for those
13155 standard exceptions.
13156
13157 If PREG is not NULL, then this regexp_t object is used to
13158 perform the symbol name matching. Otherwise, no name-based
13159 filtering is performed.
13160
13161 EXCEPTIONS is a vector of exceptions to which matching exceptions
13162 gets pushed. */
13163
13164 static void
13165 ada_add_global_exceptions (compiled_regex *preg,
13166 std::vector<ada_exc_info> *exceptions)
13167 {
13168 /* In Ada, the symbol "search name" is a linkage name, whereas the
13169 regular expression used to do the matching refers to the natural
13170 name. So match against the decoded name. */
13171 expand_symtabs_matching (NULL,
13172 lookup_name_info::match_any (),
13173 [&] (const char *search_name)
13174 {
13175 std::string decoded = ada_decode (search_name);
13176 return name_matches_regex (decoded.c_str (), preg);
13177 },
13178 NULL,
13179 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13180 VARIABLES_DOMAIN);
13181
13182 /* Iterate over all objfiles irrespective of scope or linker namespaces
13183 so we get all exceptions anywhere in the progspace. */
13184 for (objfile *objfile : current_program_space->objfiles ())
13185 {
13186 for (compunit_symtab *s : objfile->compunits ())
13187 {
13188 const struct blockvector *bv = s->blockvector ();
13189 int i;
13190
13191 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13192 {
13193 const struct block *b = bv->block (i);
13194
13195 for (struct symbol *sym : block_iterator_range (b))
13196 if (ada_is_non_standard_exception_sym (sym)
13197 && name_matches_regex (sym->natural_name (), preg))
13198 {
13199 struct ada_exc_info info
13200 = {sym->print_name (), sym->value_address ()};
13201
13202 exceptions->push_back (info);
13203 }
13204 }
13205 }
13206 }
13207 }
13208
13209 /* Implements ada_exceptions_list with the regular expression passed
13210 as a regex_t, rather than a string.
13211
13212 If not NULL, PREG is used to filter out exceptions whose names
13213 do not match. Otherwise, all exceptions are listed. */
13214
13215 static std::vector<ada_exc_info>
13216 ada_exceptions_list_1 (compiled_regex *preg)
13217 {
13218 std::vector<ada_exc_info> result;
13219 int prev_len;
13220
13221 /* First, list the known standard exceptions. These exceptions
13222 need to be handled separately, as they are usually defined in
13223 runtime units that have been compiled without debugging info. */
13224
13225 ada_add_standard_exceptions (preg, &result);
13226
13227 /* Next, find all exceptions whose scope is local and accessible
13228 from the currently selected frame. */
13229
13230 if (has_stack_frames ())
13231 {
13232 prev_len = result.size ();
13233 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13234 &result);
13235 if (result.size () > prev_len)
13236 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13237 }
13238
13239 /* Add all exceptions whose scope is global. */
13240
13241 prev_len = result.size ();
13242 ada_add_global_exceptions (preg, &result);
13243 if (result.size () > prev_len)
13244 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13245
13246 return result;
13247 }
13248
13249 /* Return a vector of ada_exc_info.
13250
13251 If REGEXP is NULL, all exceptions are included in the result.
13252 Otherwise, it should contain a valid regular expression,
13253 and only the exceptions whose names match that regular expression
13254 are included in the result.
13255
13256 The exceptions are sorted in the following order:
13257 - Standard exceptions (defined by the Ada language), in
13258 alphabetical order;
13259 - Exceptions only visible from the current frame, in
13260 alphabetical order;
13261 - Exceptions whose scope is global, in alphabetical order. */
13262
13263 std::vector<ada_exc_info>
13264 ada_exceptions_list (const char *regexp)
13265 {
13266 if (regexp == NULL)
13267 return ada_exceptions_list_1 (NULL);
13268
13269 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13270 return ada_exceptions_list_1 (&reg);
13271 }
13272
13273 /* Implement the "info exceptions" command. */
13274
13275 static void
13276 info_exceptions_command (const char *regexp, int from_tty)
13277 {
13278 struct gdbarch *gdbarch = get_current_arch ();
13279
13280 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13281
13282 if (regexp != NULL)
13283 gdb_printf
13284 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13285 else
13286 gdb_printf (_("All defined Ada exceptions:\n"));
13287
13288 for (const ada_exc_info &info : exceptions)
13289 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13290 }
13291
13292 \f
13293 /* Language vector */
13294
13295 /* symbol_name_matcher_ftype adapter for wild_match. */
13296
13297 static bool
13298 do_wild_match (const char *symbol_search_name,
13299 const lookup_name_info &lookup_name,
13300 completion_match_result *comp_match_res)
13301 {
13302 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13303 }
13304
13305 /* symbol_name_matcher_ftype adapter for full_match. */
13306
13307 static bool
13308 do_full_match (const char *symbol_search_name,
13309 const lookup_name_info &lookup_name,
13310 completion_match_result *comp_match_res)
13311 {
13312 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13313
13314 /* If both symbols start with "_ada_", just let the loop below
13315 handle the comparison. However, if only the symbol name starts
13316 with "_ada_", skip the prefix and let the match proceed as
13317 usual. */
13318 if (startswith (symbol_search_name, "_ada_")
13319 && !startswith (lname, "_ada"))
13320 symbol_search_name += 5;
13321 /* Likewise for ghost entities. */
13322 if (startswith (symbol_search_name, "___ghost_")
13323 && !startswith (lname, "___ghost_"))
13324 symbol_search_name += 9;
13325
13326 int uscore_count = 0;
13327 while (*lname != '\0')
13328 {
13329 if (*symbol_search_name != *lname)
13330 {
13331 if (*symbol_search_name == 'B' && uscore_count == 2
13332 && symbol_search_name[1] == '_')
13333 {
13334 symbol_search_name += 2;
13335 while (isdigit (*symbol_search_name))
13336 ++symbol_search_name;
13337 if (symbol_search_name[0] == '_'
13338 && symbol_search_name[1] == '_')
13339 {
13340 symbol_search_name += 2;
13341 continue;
13342 }
13343 }
13344 return false;
13345 }
13346
13347 if (*symbol_search_name == '_')
13348 ++uscore_count;
13349 else
13350 uscore_count = 0;
13351
13352 ++symbol_search_name;
13353 ++lname;
13354 }
13355
13356 return is_name_suffix (symbol_search_name);
13357 }
13358
13359 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13360
13361 static bool
13362 do_exact_match (const char *symbol_search_name,
13363 const lookup_name_info &lookup_name,
13364 completion_match_result *comp_match_res)
13365 {
13366 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13367 }
13368
13369 /* Build the Ada lookup name for LOOKUP_NAME. */
13370
13371 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13372 {
13373 gdb::string_view user_name = lookup_name.name ();
13374
13375 if (!user_name.empty () && user_name[0] == '<')
13376 {
13377 if (user_name.back () == '>')
13378 m_encoded_name
13379 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
13380 else
13381 m_encoded_name
13382 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
13383 m_encoded_p = true;
13384 m_verbatim_p = true;
13385 m_wild_match_p = false;
13386 m_standard_p = false;
13387 }
13388 else
13389 {
13390 m_verbatim_p = false;
13391
13392 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
13393
13394 if (!m_encoded_p)
13395 {
13396 const char *folded = ada_fold_name (user_name);
13397 m_encoded_name = ada_encode_1 (folded, false);
13398 if (m_encoded_name.empty ())
13399 m_encoded_name = gdb::to_string (user_name);
13400 }
13401 else
13402 m_encoded_name = gdb::to_string (user_name);
13403
13404 /* Handle the 'package Standard' special case. See description
13405 of m_standard_p. */
13406 if (startswith (m_encoded_name.c_str (), "standard__"))
13407 {
13408 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13409 m_standard_p = true;
13410 }
13411 else
13412 m_standard_p = false;
13413
13414 /* If the name contains a ".", then the user is entering a fully
13415 qualified entity name, and the match must not be done in wild
13416 mode. Similarly, if the user wants to complete what looks
13417 like an encoded name, the match must not be done in wild
13418 mode. Also, in the standard__ special case always do
13419 non-wild matching. */
13420 m_wild_match_p
13421 = (lookup_name.match_type () != symbol_name_match_type::FULL
13422 && !m_encoded_p
13423 && !m_standard_p
13424 && user_name.find ('.') == std::string::npos);
13425 }
13426 }
13427
13428 /* symbol_name_matcher_ftype method for Ada. This only handles
13429 completion mode. */
13430
13431 static bool
13432 ada_symbol_name_matches (const char *symbol_search_name,
13433 const lookup_name_info &lookup_name,
13434 completion_match_result *comp_match_res)
13435 {
13436 return lookup_name.ada ().matches (symbol_search_name,
13437 lookup_name.match_type (),
13438 comp_match_res);
13439 }
13440
13441 /* A name matcher that matches the symbol name exactly, with
13442 strcmp. */
13443
13444 static bool
13445 literal_symbol_name_matcher (const char *symbol_search_name,
13446 const lookup_name_info &lookup_name,
13447 completion_match_result *comp_match_res)
13448 {
13449 gdb::string_view name_view = lookup_name.name ();
13450
13451 if (lookup_name.completion_mode ()
13452 ? (strncmp (symbol_search_name, name_view.data (),
13453 name_view.size ()) == 0)
13454 : symbol_search_name == name_view)
13455 {
13456 if (comp_match_res != NULL)
13457 comp_match_res->set_match (symbol_search_name);
13458 return true;
13459 }
13460 else
13461 return false;
13462 }
13463
13464 /* Implement the "get_symbol_name_matcher" language_defn method for
13465 Ada. */
13466
13467 static symbol_name_matcher_ftype *
13468 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13469 {
13470 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13471 return literal_symbol_name_matcher;
13472
13473 if (lookup_name.completion_mode ())
13474 return ada_symbol_name_matches;
13475 else
13476 {
13477 if (lookup_name.ada ().wild_match_p ())
13478 return do_wild_match;
13479 else if (lookup_name.ada ().verbatim_p ())
13480 return do_exact_match;
13481 else
13482 return do_full_match;
13483 }
13484 }
13485
13486 /* Class representing the Ada language. */
13487
13488 class ada_language : public language_defn
13489 {
13490 public:
13491 ada_language ()
13492 : language_defn (language_ada)
13493 { /* Nothing. */ }
13494
13495 /* See language.h. */
13496
13497 const char *name () const override
13498 { return "ada"; }
13499
13500 /* See language.h. */
13501
13502 const char *natural_name () const override
13503 { return "Ada"; }
13504
13505 /* See language.h. */
13506
13507 const std::vector<const char *> &filename_extensions () const override
13508 {
13509 static const std::vector<const char *> extensions
13510 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13511 return extensions;
13512 }
13513
13514 /* Print an array element index using the Ada syntax. */
13515
13516 void print_array_index (struct type *index_type,
13517 LONGEST index,
13518 struct ui_file *stream,
13519 const value_print_options *options) const override
13520 {
13521 struct value *index_value = val_atr (index_type, index);
13522
13523 value_print (index_value, stream, options);
13524 gdb_printf (stream, " => ");
13525 }
13526
13527 /* Implement the "read_var_value" language_defn method for Ada. */
13528
13529 struct value *read_var_value (struct symbol *var,
13530 const struct block *var_block,
13531 frame_info_ptr frame) const override
13532 {
13533 /* The only case where default_read_var_value is not sufficient
13534 is when VAR is a renaming... */
13535 if (frame != nullptr)
13536 {
13537 const struct block *frame_block = get_frame_block (frame, NULL);
13538 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13539 return ada_read_renaming_var_value (var, frame_block);
13540 }
13541
13542 /* This is a typical case where we expect the default_read_var_value
13543 function to work. */
13544 return language_defn::read_var_value (var, var_block, frame);
13545 }
13546
13547 /* See language.h. */
13548 bool symbol_printing_suppressed (struct symbol *symbol) const override
13549 {
13550 return symbol->is_artificial ();
13551 }
13552
13553 /* See language.h. */
13554 void language_arch_info (struct gdbarch *gdbarch,
13555 struct language_arch_info *lai) const override
13556 {
13557 const struct builtin_type *builtin = builtin_type (gdbarch);
13558
13559 /* Helper function to allow shorter lines below. */
13560 auto add = [&] (struct type *t)
13561 {
13562 lai->add_primitive_type (t);
13563 };
13564
13565 type_allocator alloc (gdbarch);
13566 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13567 0, "integer"));
13568 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
13569 0, "long_integer"));
13570 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
13571 0, "short_integer"));
13572 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
13573 1, "character");
13574 lai->set_string_char_type (char_type);
13575 add (char_type);
13576 add (init_character_type (alloc, 16, 1, "wide_character"));
13577 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
13578 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
13579 "float", gdbarch_float_format (gdbarch)));
13580 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
13581 "long_float", gdbarch_double_format (gdbarch)));
13582 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
13583 0, "long_long_integer"));
13584 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
13585 "long_long_float",
13586 gdbarch_long_double_format (gdbarch)));
13587 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13588 0, "natural"));
13589 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
13590 0, "positive"));
13591 add (builtin->builtin_void);
13592
13593 struct type *system_addr_ptr
13594 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13595 "void"));
13596 system_addr_ptr->set_name ("system__address");
13597 add (system_addr_ptr);
13598
13599 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13600 type. This is a signed integral type whose size is the same as
13601 the size of addresses. */
13602 unsigned int addr_length = system_addr_ptr->length ();
13603 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
13604 "storage_offset"));
13605
13606 lai->set_bool_type (builtin->builtin_bool);
13607 }
13608
13609 /* See language.h. */
13610
13611 bool iterate_over_symbols
13612 (const struct block *block, const lookup_name_info &name,
13613 domain_enum domain,
13614 gdb::function_view<symbol_found_callback_ftype> callback) const override
13615 {
13616 std::vector<struct block_symbol> results
13617 = ada_lookup_symbol_list_worker (name, block, domain, 0);
13618 for (block_symbol &sym : results)
13619 {
13620 if (!callback (&sym))
13621 return false;
13622 }
13623
13624 return true;
13625 }
13626
13627 /* See language.h. */
13628 bool sniff_from_mangled_name
13629 (const char *mangled,
13630 gdb::unique_xmalloc_ptr<char> *out) const override
13631 {
13632 std::string demangled = ada_decode (mangled);
13633
13634 *out = NULL;
13635
13636 if (demangled != mangled && demangled[0] != '<')
13637 {
13638 /* Set the gsymbol language to Ada, but still return 0.
13639 Two reasons for that:
13640
13641 1. For Ada, we prefer computing the symbol's decoded name
13642 on the fly rather than pre-compute it, in order to save
13643 memory (Ada projects are typically very large).
13644
13645 2. There are some areas in the definition of the GNAT
13646 encoding where, with a bit of bad luck, we might be able
13647 to decode a non-Ada symbol, generating an incorrect
13648 demangled name (Eg: names ending with "TB" for instance
13649 are identified as task bodies and so stripped from
13650 the decoded name returned).
13651
13652 Returning true, here, but not setting *DEMANGLED, helps us get
13653 a little bit of the best of both worlds. Because we're last,
13654 we should not affect any of the other languages that were
13655 able to demangle the symbol before us; we get to correctly
13656 tag Ada symbols as such; and even if we incorrectly tagged a
13657 non-Ada symbol, which should be rare, any routing through the
13658 Ada language should be transparent (Ada tries to behave much
13659 like C/C++ with non-Ada symbols). */
13660 return true;
13661 }
13662
13663 return false;
13664 }
13665
13666 /* See language.h. */
13667
13668 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13669 int options) const override
13670 {
13671 return make_unique_xstrdup (ada_decode (mangled).c_str ());
13672 }
13673
13674 /* See language.h. */
13675
13676 void print_type (struct type *type, const char *varstring,
13677 struct ui_file *stream, int show, int level,
13678 const struct type_print_options *flags) const override
13679 {
13680 ada_print_type (type, varstring, stream, show, level, flags);
13681 }
13682
13683 /* See language.h. */
13684
13685 const char *word_break_characters (void) const override
13686 {
13687 return ada_completer_word_break_characters;
13688 }
13689
13690 /* See language.h. */
13691
13692 void collect_symbol_completion_matches (completion_tracker &tracker,
13693 complete_symbol_mode mode,
13694 symbol_name_match_type name_match_type,
13695 const char *text, const char *word,
13696 enum type_code code) const override
13697 {
13698 const struct block *b, *surrounding_static_block = 0;
13699
13700 gdb_assert (code == TYPE_CODE_UNDEF);
13701
13702 lookup_name_info lookup_name (text, name_match_type, true);
13703
13704 /* First, look at the partial symtab symbols. */
13705 expand_symtabs_matching (NULL,
13706 lookup_name,
13707 NULL,
13708 NULL,
13709 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13710 ALL_DOMAIN);
13711
13712 /* At this point scan through the misc symbol vectors and add each
13713 symbol you find to the list. Eventually we want to ignore
13714 anything that isn't a text symbol (everything else will be
13715 handled by the psymtab code above). */
13716
13717 for (objfile *objfile : current_program_space->objfiles ())
13718 {
13719 for (minimal_symbol *msymbol : objfile->msymbols ())
13720 {
13721 QUIT;
13722
13723 if (completion_skip_symbol (mode, msymbol))
13724 continue;
13725
13726 language symbol_language = msymbol->language ();
13727
13728 /* Ada minimal symbols won't have their language set to Ada. If
13729 we let completion_list_add_name compare using the
13730 default/C-like matcher, then when completing e.g., symbols in a
13731 package named "pck", we'd match internal Ada symbols like
13732 "pckS", which are invalid in an Ada expression, unless you wrap
13733 them in '<' '>' to request a verbatim match.
13734
13735 Unfortunately, some Ada encoded names successfully demangle as
13736 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13737 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13738 with the wrong language set. Paper over that issue here. */
13739 if (symbol_language == language_auto
13740 || symbol_language == language_cplus)
13741 symbol_language = language_ada;
13742
13743 completion_list_add_name (tracker,
13744 symbol_language,
13745 msymbol->linkage_name (),
13746 lookup_name, text, word);
13747 }
13748 }
13749
13750 /* Search upwards from currently selected frame (so that we can
13751 complete on local vars. */
13752
13753 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
13754 {
13755 if (!b->superblock ())
13756 surrounding_static_block = b; /* For elmin of dups */
13757
13758 for (struct symbol *sym : block_iterator_range (b))
13759 {
13760 if (completion_skip_symbol (mode, sym))
13761 continue;
13762
13763 completion_list_add_name (tracker,
13764 sym->language (),
13765 sym->linkage_name (),
13766 lookup_name, text, word);
13767 }
13768 }
13769
13770 /* Go through the symtabs and check the externs and statics for
13771 symbols which match. */
13772
13773 for (objfile *objfile : current_program_space->objfiles ())
13774 {
13775 for (compunit_symtab *s : objfile->compunits ())
13776 {
13777 QUIT;
13778 b = s->blockvector ()->global_block ();
13779 for (struct symbol *sym : block_iterator_range (b))
13780 {
13781 if (completion_skip_symbol (mode, sym))
13782 continue;
13783
13784 completion_list_add_name (tracker,
13785 sym->language (),
13786 sym->linkage_name (),
13787 lookup_name, text, word);
13788 }
13789 }
13790 }
13791
13792 for (objfile *objfile : current_program_space->objfiles ())
13793 {
13794 for (compunit_symtab *s : objfile->compunits ())
13795 {
13796 QUIT;
13797 b = s->blockvector ()->static_block ();
13798 /* Don't do this block twice. */
13799 if (b == surrounding_static_block)
13800 continue;
13801 for (struct symbol *sym : block_iterator_range (b))
13802 {
13803 if (completion_skip_symbol (mode, sym))
13804 continue;
13805
13806 completion_list_add_name (tracker,
13807 sym->language (),
13808 sym->linkage_name (),
13809 lookup_name, text, word);
13810 }
13811 }
13812 }
13813 }
13814
13815 /* See language.h. */
13816
13817 gdb::unique_xmalloc_ptr<char> watch_location_expression
13818 (struct type *type, CORE_ADDR addr) const override
13819 {
13820 type = check_typedef (check_typedef (type)->target_type ());
13821 std::string name = type_to_string (type);
13822 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13823 }
13824
13825 /* See language.h. */
13826
13827 void value_print (struct value *val, struct ui_file *stream,
13828 const struct value_print_options *options) const override
13829 {
13830 return ada_value_print (val, stream, options);
13831 }
13832
13833 /* See language.h. */
13834
13835 void value_print_inner
13836 (struct value *val, struct ui_file *stream, int recurse,
13837 const struct value_print_options *options) const override
13838 {
13839 return ada_value_print_inner (val, stream, recurse, options);
13840 }
13841
13842 /* See language.h. */
13843
13844 struct block_symbol lookup_symbol_nonlocal
13845 (const char *name, const struct block *block,
13846 const domain_enum domain) const override
13847 {
13848 struct block_symbol sym;
13849
13850 sym = ada_lookup_symbol (name,
13851 (block == nullptr
13852 ? nullptr
13853 : block->static_block ()),
13854 domain);
13855 if (sym.symbol != NULL)
13856 return sym;
13857
13858 /* If we haven't found a match at this point, try the primitive
13859 types. In other languages, this search is performed before
13860 searching for global symbols in order to short-circuit that
13861 global-symbol search if it happens that the name corresponds
13862 to a primitive type. But we cannot do the same in Ada, because
13863 it is perfectly legitimate for a program to declare a type which
13864 has the same name as a standard type. If looking up a type in
13865 that situation, we have traditionally ignored the primitive type
13866 in favor of user-defined types. This is why, unlike most other
13867 languages, we search the primitive types this late and only after
13868 having searched the global symbols without success. */
13869
13870 if (domain == VAR_DOMAIN)
13871 {
13872 struct gdbarch *gdbarch;
13873
13874 if (block == NULL)
13875 gdbarch = target_gdbarch ();
13876 else
13877 gdbarch = block->gdbarch ();
13878 sym.symbol
13879 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13880 if (sym.symbol != NULL)
13881 return sym;
13882 }
13883
13884 return {};
13885 }
13886
13887 /* See language.h. */
13888
13889 int parser (struct parser_state *ps) const override
13890 {
13891 warnings_issued = 0;
13892 return ada_parse (ps);
13893 }
13894
13895 /* See language.h. */
13896
13897 void emitchar (int ch, struct type *chtype,
13898 struct ui_file *stream, int quoter) const override
13899 {
13900 ada_emit_char (ch, chtype, stream, quoter, 1);
13901 }
13902
13903 /* See language.h. */
13904
13905 void printchar (int ch, struct type *chtype,
13906 struct ui_file *stream) const override
13907 {
13908 ada_printchar (ch, chtype, stream);
13909 }
13910
13911 /* See language.h. */
13912
13913 void printstr (struct ui_file *stream, struct type *elttype,
13914 const gdb_byte *string, unsigned int length,
13915 const char *encoding, int force_ellipses,
13916 const struct value_print_options *options) const override
13917 {
13918 ada_printstr (stream, elttype, string, length, encoding,
13919 force_ellipses, options);
13920 }
13921
13922 /* See language.h. */
13923
13924 void print_typedef (struct type *type, struct symbol *new_symbol,
13925 struct ui_file *stream) const override
13926 {
13927 ada_print_typedef (type, new_symbol, stream);
13928 }
13929
13930 /* See language.h. */
13931
13932 bool is_string_type_p (struct type *type) const override
13933 {
13934 return ada_is_string_type (type);
13935 }
13936
13937 /* See language.h. */
13938
13939 const char *struct_too_deep_ellipsis () const override
13940 { return "(...)"; }
13941
13942 /* See language.h. */
13943
13944 bool c_style_arrays_p () const override
13945 { return false; }
13946
13947 /* See language.h. */
13948
13949 bool store_sym_names_in_linkage_form_p () const override
13950 { return true; }
13951
13952 /* See language.h. */
13953
13954 const struct lang_varobj_ops *varobj_ops () const override
13955 { return &ada_varobj_ops; }
13956
13957 protected:
13958 /* See language.h. */
13959
13960 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13961 (const lookup_name_info &lookup_name) const override
13962 {
13963 return ada_get_symbol_name_matcher (lookup_name);
13964 }
13965 };
13966
13967 /* Single instance of the Ada language class. */
13968
13969 static ada_language ada_language_defn;
13970
13971 /* Command-list for the "set/show ada" prefix command. */
13972 static struct cmd_list_element *set_ada_list;
13973 static struct cmd_list_element *show_ada_list;
13974
13975 /* This module's 'new_objfile' observer. */
13976
13977 static void
13978 ada_new_objfile_observer (struct objfile *objfile)
13979 {
13980 ada_clear_symbol_cache ();
13981 }
13982
13983 /* This module's 'free_objfile' observer. */
13984
13985 static void
13986 ada_free_objfile_observer (struct objfile *objfile)
13987 {
13988 ada_clear_symbol_cache ();
13989 }
13990
13991 /* Charsets known to GNAT. */
13992 static const char * const gnat_source_charsets[] =
13993 {
13994 /* Note that code below assumes that the default comes first.
13995 Latin-1 is the default here, because that is also GNAT's
13996 default. */
13997 "ISO-8859-1",
13998 "ISO-8859-2",
13999 "ISO-8859-3",
14000 "ISO-8859-4",
14001 "ISO-8859-5",
14002 "ISO-8859-15",
14003 "CP437",
14004 "CP850",
14005 /* Note that this value is special-cased in the encoder and
14006 decoder. */
14007 ada_utf8,
14008 nullptr
14009 };
14010
14011 void _initialize_ada_language ();
14012 void
14013 _initialize_ada_language ()
14014 {
14015 add_setshow_prefix_cmd
14016 ("ada", no_class,
14017 _("Prefix command for changing Ada-specific settings."),
14018 _("Generic command for showing Ada-specific settings."),
14019 &set_ada_list, &show_ada_list,
14020 &setlist, &showlist);
14021
14022 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
14023 &trust_pad_over_xvs, _("\
14024 Enable or disable an optimization trusting PAD types over XVS types."), _("\
14025 Show whether an optimization trusting PAD types over XVS types is activated."),
14026 _("\
14027 This is related to the encoding used by the GNAT compiler. The debugger\n\
14028 should normally trust the contents of PAD types, but certain older versions\n\
14029 of GNAT have a bug that sometimes causes the information in the PAD type\n\
14030 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
14031 work around this bug. It is always safe to turn this option \"off\", but\n\
14032 this incurs a slight performance penalty, so it is recommended to NOT change\n\
14033 this option to \"off\" unless necessary."),
14034 NULL, NULL, &set_ada_list, &show_ada_list);
14035
14036 add_setshow_boolean_cmd ("print-signatures", class_vars,
14037 &print_signatures, _("\
14038 Enable or disable the output of formal and return types for functions in the \
14039 overloads selection menu."), _("\
14040 Show whether the output of formal and return types for functions in the \
14041 overloads selection menu is activated."),
14042 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
14043
14044 ada_source_charset = gnat_source_charsets[0];
14045 add_setshow_enum_cmd ("source-charset", class_files,
14046 gnat_source_charsets,
14047 &ada_source_charset, _("\
14048 Set the Ada source character set."), _("\
14049 Show the Ada source character set."), _("\
14050 The character set used for Ada source files.\n\
14051 This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
14052 nullptr, nullptr,
14053 &set_ada_list, &show_ada_list);
14054
14055 add_catch_command ("exception", _("\
14056 Catch Ada exceptions, when raised.\n\
14057 Usage: catch exception [ARG] [if CONDITION]\n\
14058 Without any argument, stop when any Ada exception is raised.\n\
14059 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14060 being raised does not have a handler (and will therefore lead to the task's\n\
14061 termination).\n\
14062 Otherwise, the catchpoint only stops when the name of the exception being\n\
14063 raised is the same as ARG.\n\
14064 CONDITION is a boolean expression that is evaluated to see whether the\n\
14065 exception should cause a stop."),
14066 catch_ada_exception_command,
14067 catch_ada_completer,
14068 CATCH_PERMANENT,
14069 CATCH_TEMPORARY);
14070
14071 add_catch_command ("handlers", _("\
14072 Catch Ada exceptions, when handled.\n\
14073 Usage: catch handlers [ARG] [if CONDITION]\n\
14074 Without any argument, stop when any Ada exception is handled.\n\
14075 With an argument, catch only exceptions with the given name.\n\
14076 CONDITION is a boolean expression that is evaluated to see whether the\n\
14077 exception should cause a stop."),
14078 catch_ada_handlers_command,
14079 catch_ada_completer,
14080 CATCH_PERMANENT,
14081 CATCH_TEMPORARY);
14082 add_catch_command ("assert", _("\
14083 Catch failed Ada assertions, when raised.\n\
14084 Usage: catch assert [if CONDITION]\n\
14085 CONDITION is a boolean expression that is evaluated to see whether the\n\
14086 exception should cause a stop."),
14087 catch_assert_command,
14088 NULL,
14089 CATCH_PERMANENT,
14090 CATCH_TEMPORARY);
14091
14092 add_info ("exceptions", info_exceptions_command,
14093 _("\
14094 List all Ada exception names.\n\
14095 Usage: info exceptions [REGEXP]\n\
14096 If a regular expression is passed as an argument, only those matching\n\
14097 the regular expression are listed."));
14098
14099 add_setshow_prefix_cmd ("ada", class_maintenance,
14100 _("Set Ada maintenance-related variables."),
14101 _("Show Ada maintenance-related variables."),
14102 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14103 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
14104
14105 add_setshow_boolean_cmd
14106 ("ignore-descriptive-types", class_maintenance,
14107 &ada_ignore_descriptive_types_p,
14108 _("Set whether descriptive types generated by GNAT should be ignored."),
14109 _("Show whether descriptive types generated by GNAT should be ignored."),
14110 _("\
14111 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14112 DWARF attribute."),
14113 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14114
14115 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14116 htab_eq_string,
14117 NULL, xcalloc, xfree);
14118
14119 /* The ada-lang observers. */
14120 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14121 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14122 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14123 }