Introduce ada_unop_ind_operation
[deliverable/binutils-gdb.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2021 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 "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 "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
53 #include "value.h"
54 #include "mi/mi-common.h"
55 #include "arch-utils.h"
56 #include "cli/cli-utils.h"
57 #include "gdbsupport/function-view.h"
58 #include "gdbsupport/byte-vector.h"
59 #include <algorithm>
60 #include "ada-exp.h"
61
62 /* Define whether or not the C operator '/' truncates towards zero for
63 differently signed operands (truncation direction is undefined in C).
64 Copied from valarith.c. */
65
66 #ifndef TRUNCATION_TOWARDS_ZERO
67 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
68 #endif
69
70 static struct type *desc_base_type (struct type *);
71
72 static struct type *desc_bounds_type (struct type *);
73
74 static struct value *desc_bounds (struct value *);
75
76 static int fat_pntr_bounds_bitpos (struct type *);
77
78 static int fat_pntr_bounds_bitsize (struct type *);
79
80 static struct type *desc_data_target_type (struct type *);
81
82 static struct value *desc_data (struct value *);
83
84 static int fat_pntr_data_bitpos (struct type *);
85
86 static int fat_pntr_data_bitsize (struct type *);
87
88 static struct value *desc_one_bound (struct value *, int, int);
89
90 static int desc_bound_bitpos (struct type *, int, int);
91
92 static int desc_bound_bitsize (struct type *, int, int);
93
94 static struct type *desc_index_type (struct type *, int);
95
96 static int desc_arity (struct type *);
97
98 static int ada_type_match (struct type *, struct type *, int);
99
100 static int ada_args_match (struct symbol *, struct value **, int);
101
102 static struct value *make_array_descriptor (struct type *, struct value *);
103
104 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
106 const lookup_name_info &lookup_name,
107 domain_enum, struct objfile *);
108
109 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
110 const struct block *,
111 const lookup_name_info &lookup_name,
112 domain_enum, int, int *);
113
114 static int is_nonfunction (const std::vector<struct block_symbol> &);
115
116 static void add_defn_to_vec (std::vector<struct block_symbol> &,
117 struct symbol *,
118 const struct block *);
119
120 static struct value *resolve_subexp (expression_up *, int *, int,
121 struct type *, int,
122 innermost_block_tracker *);
123
124 static void replace_operator_with_call (expression_up *, int, int, int,
125 struct symbol *, const struct block *);
126
127 static int possible_user_operator_p (enum exp_opcode, struct value **);
128
129 static const char *ada_decoded_op_name (enum exp_opcode);
130
131 static int numeric_type_p (struct type *);
132
133 static int integer_type_p (struct type *);
134
135 static int scalar_type_p (struct type *);
136
137 static int discrete_type_p (struct type *);
138
139 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
140 int, int);
141
142 static struct value *evaluate_subexp_type (struct expression *, int *);
143
144 static struct type *ada_find_parallel_type_with_name (struct type *,
145 const char *);
146
147 static int is_dynamic_field (struct type *, int);
148
149 static struct type *to_fixed_variant_branch_type (struct type *,
150 const gdb_byte *,
151 CORE_ADDR, struct value *);
152
153 static struct type *to_fixed_array_type (struct type *, struct value *, int);
154
155 static struct type *to_fixed_range_type (struct type *, struct value *);
156
157 static struct type *to_static_fixed_type (struct type *);
158 static struct type *static_unwrap_type (struct type *type);
159
160 static struct value *unwrap_value (struct value *);
161
162 static struct type *constrained_packed_array_type (struct type *, long *);
163
164 static struct type *decode_constrained_packed_array_type (struct type *);
165
166 static long decode_packed_array_bitsize (struct type *);
167
168 static struct value *decode_constrained_packed_array (struct value *);
169
170 static int ada_is_unconstrained_packed_array_type (struct type *);
171
172 static struct value *value_subscript_packed (struct value *, int,
173 struct value **);
174
175 static struct value *coerce_unspec_val_to_type (struct value *,
176 struct type *);
177
178 static int lesseq_defined_than (struct symbol *, struct symbol *);
179
180 static int equiv_types (struct type *, struct type *);
181
182 static int is_name_suffix (const char *);
183
184 static int advance_wild_match (const char **, const char *, char);
185
186 static bool wild_match (const char *name, const char *patn);
187
188 static struct value *ada_coerce_ref (struct value *);
189
190 static LONGEST pos_atr (struct value *);
191
192 static struct value *val_atr (struct type *, LONGEST);
193
194 static struct symbol *standard_lookup (const char *, const struct block *,
195 domain_enum);
196
197 static struct value *ada_search_struct_field (const char *, struct value *, int,
198 struct type *);
199
200 static int find_struct_field (const char *, struct type *, int,
201 struct type **, int *, int *, int *, int *);
202
203 static int ada_resolve_function (std::vector<struct block_symbol> &,
204 struct value **, int, const char *,
205 struct type *, int);
206
207 static int ada_is_direct_array_type (struct type *);
208
209 static struct value *ada_index_struct_field (int, struct value *, int,
210 struct type *);
211
212 static struct value *assign_aggregate (struct value *, struct value *,
213 struct expression *,
214 int *, enum noside);
215
216 static void aggregate_assign_from_choices (struct value *, struct value *,
217 struct expression *,
218 int *, std::vector<LONGEST> &,
219 LONGEST, LONGEST);
220
221 static void aggregate_assign_positional (struct value *, struct value *,
222 struct expression *,
223 int *, std::vector<LONGEST> &,
224 LONGEST, LONGEST);
225
226
227 static void aggregate_assign_others (struct value *, struct value *,
228 struct expression *,
229 int *, std::vector<LONGEST> &,
230 LONGEST, LONGEST);
231
232
233 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
234
235
236 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
237 int *, enum noside);
238
239 static void ada_forward_operator_length (struct expression *, int, int *,
240 int *);
241
242 static struct type *ada_find_any_type (const char *name);
243
244 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
245 (const lookup_name_info &lookup_name);
246
247 \f
248
249 /* The result of a symbol lookup to be stored in our symbol cache. */
250
251 struct cache_entry
252 {
253 /* The name used to perform the lookup. */
254 const char *name;
255 /* The namespace used during the lookup. */
256 domain_enum domain;
257 /* The symbol returned by the lookup, or NULL if no matching symbol
258 was found. */
259 struct symbol *sym;
260 /* The block where the symbol was found, or NULL if no matching
261 symbol was found. */
262 const struct block *block;
263 /* A pointer to the next entry with the same hash. */
264 struct cache_entry *next;
265 };
266
267 /* The Ada symbol cache, used to store the result of Ada-mode symbol
268 lookups in the course of executing the user's commands.
269
270 The cache is implemented using a simple, fixed-sized hash.
271 The size is fixed on the grounds that there are not likely to be
272 all that many symbols looked up during any given session, regardless
273 of the size of the symbol table. If we decide to go to a resizable
274 table, let's just use the stuff from libiberty instead. */
275
276 #define HASH_SIZE 1009
277
278 struct ada_symbol_cache
279 {
280 /* An obstack used to store the entries in our cache. */
281 struct auto_obstack cache_space;
282
283 /* The root of the hash table used to implement our symbol cache. */
284 struct cache_entry *root[HASH_SIZE] {};
285 };
286
287 /* Maximum-sized dynamic type. */
288 static unsigned int varsize_limit;
289
290 static const char ada_completer_word_break_characters[] =
291 #ifdef VMS
292 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
293 #else
294 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
295 #endif
296
297 /* The name of the symbol to use to get the name of the main subprogram. */
298 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
299 = "__gnat_ada_main_program_name";
300
301 /* Limit on the number of warnings to raise per expression evaluation. */
302 static int warning_limit = 2;
303
304 /* Number of warning messages issued; reset to 0 by cleanups after
305 expression evaluation. */
306 static int warnings_issued = 0;
307
308 static const char * const known_runtime_file_name_patterns[] = {
309 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
310 };
311
312 static const char * const known_auxiliary_function_name_patterns[] = {
313 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
314 };
315
316 /* Maintenance-related settings for this module. */
317
318 static struct cmd_list_element *maint_set_ada_cmdlist;
319 static struct cmd_list_element *maint_show_ada_cmdlist;
320
321 /* The "maintenance ada set/show ignore-descriptive-type" value. */
322
323 static bool ada_ignore_descriptive_types_p = false;
324
325 /* Inferior-specific data. */
326
327 /* Per-inferior data for this module. */
328
329 struct ada_inferior_data
330 {
331 /* The ada__tags__type_specific_data type, which is used when decoding
332 tagged types. With older versions of GNAT, this type was directly
333 accessible through a component ("tsd") in the object tag. But this
334 is no longer the case, so we cache it for each inferior. */
335 struct type *tsd_type = nullptr;
336
337 /* The exception_support_info data. This data is used to determine
338 how to implement support for Ada exception catchpoints in a given
339 inferior. */
340 const struct exception_support_info *exception_info = nullptr;
341 };
342
343 /* Our key to this module's inferior data. */
344 static const struct inferior_key<ada_inferior_data> ada_inferior_data;
345
346 /* Return our inferior data for the given inferior (INF).
347
348 This function always returns a valid pointer to an allocated
349 ada_inferior_data structure. If INF's inferior data has not
350 been previously set, this functions creates a new one with all
351 fields set to zero, sets INF's inferior to it, and then returns
352 a pointer to that newly allocated ada_inferior_data. */
353
354 static struct ada_inferior_data *
355 get_ada_inferior_data (struct inferior *inf)
356 {
357 struct ada_inferior_data *data;
358
359 data = ada_inferior_data.get (inf);
360 if (data == NULL)
361 data = ada_inferior_data.emplace (inf);
362
363 return data;
364 }
365
366 /* Perform all necessary cleanups regarding our module's inferior data
367 that is required after the inferior INF just exited. */
368
369 static void
370 ada_inferior_exit (struct inferior *inf)
371 {
372 ada_inferior_data.clear (inf);
373 }
374
375
376 /* program-space-specific data. */
377
378 /* This module's per-program-space data. */
379 struct ada_pspace_data
380 {
381 /* The Ada symbol cache. */
382 std::unique_ptr<ada_symbol_cache> sym_cache;
383 };
384
385 /* Key to our per-program-space data. */
386 static const struct program_space_key<ada_pspace_data> ada_pspace_data_handle;
387
388 /* Return this module's data for the given program space (PSPACE).
389 If not is found, add a zero'ed one now.
390
391 This function always returns a valid object. */
392
393 static struct ada_pspace_data *
394 get_ada_pspace_data (struct program_space *pspace)
395 {
396 struct ada_pspace_data *data;
397
398 data = ada_pspace_data_handle.get (pspace);
399 if (data == NULL)
400 data = ada_pspace_data_handle.emplace (pspace);
401
402 return data;
403 }
404
405 /* Utilities */
406
407 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
408 all typedef layers have been peeled. Otherwise, return TYPE.
409
410 Normally, we really expect a typedef type to only have 1 typedef layer.
411 In other words, we really expect the target type of a typedef type to be
412 a non-typedef type. This is particularly true for Ada units, because
413 the language does not have a typedef vs not-typedef distinction.
414 In that respect, the Ada compiler has been trying to eliminate as many
415 typedef definitions in the debugging information, since they generally
416 do not bring any extra information (we still use typedef under certain
417 circumstances related mostly to the GNAT encoding).
418
419 Unfortunately, we have seen situations where the debugging information
420 generated by the compiler leads to such multiple typedef layers. For
421 instance, consider the following example with stabs:
422
423 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
424 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
425
426 This is an error in the debugging information which causes type
427 pck__float_array___XUP to be defined twice, and the second time,
428 it is defined as a typedef of a typedef.
429
430 This is on the fringe of legality as far as debugging information is
431 concerned, and certainly unexpected. But it is easy to handle these
432 situations correctly, so we can afford to be lenient in this case. */
433
434 static struct type *
435 ada_typedef_target_type (struct type *type)
436 {
437 while (type->code () == TYPE_CODE_TYPEDEF)
438 type = TYPE_TARGET_TYPE (type);
439 return type;
440 }
441
442 /* Given DECODED_NAME a string holding a symbol name in its
443 decoded form (ie using the Ada dotted notation), returns
444 its unqualified name. */
445
446 static const char *
447 ada_unqualified_name (const char *decoded_name)
448 {
449 const char *result;
450
451 /* If the decoded name starts with '<', it means that the encoded
452 name does not follow standard naming conventions, and thus that
453 it is not your typical Ada symbol name. Trying to unqualify it
454 is therefore pointless and possibly erroneous. */
455 if (decoded_name[0] == '<')
456 return decoded_name;
457
458 result = strrchr (decoded_name, '.');
459 if (result != NULL)
460 result++; /* Skip the dot... */
461 else
462 result = decoded_name;
463
464 return result;
465 }
466
467 /* Return a string starting with '<', followed by STR, and '>'. */
468
469 static std::string
470 add_angle_brackets (const char *str)
471 {
472 return string_printf ("<%s>", str);
473 }
474
475 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
476 suffix of FIELD_NAME beginning "___". */
477
478 static int
479 field_name_match (const char *field_name, const char *target)
480 {
481 int len = strlen (target);
482
483 return
484 (strncmp (field_name, target, len) == 0
485 && (field_name[len] == '\0'
486 || (startswith (field_name + len, "___")
487 && strcmp (field_name + strlen (field_name) - 6,
488 "___XVN") != 0)));
489 }
490
491
492 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
493 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
494 and return its index. This function also handles fields whose name
495 have ___ suffixes because the compiler sometimes alters their name
496 by adding such a suffix to represent fields with certain constraints.
497 If the field could not be found, return a negative number if
498 MAYBE_MISSING is set. Otherwise raise an error. */
499
500 int
501 ada_get_field_index (const struct type *type, const char *field_name,
502 int maybe_missing)
503 {
504 int fieldno;
505 struct type *struct_type = check_typedef ((struct type *) type);
506
507 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
508 if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
509 return fieldno;
510
511 if (!maybe_missing)
512 error (_("Unable to find field %s in struct %s. Aborting"),
513 field_name, struct_type->name ());
514
515 return -1;
516 }
517
518 /* The length of the prefix of NAME prior to any "___" suffix. */
519
520 int
521 ada_name_prefix_len (const char *name)
522 {
523 if (name == NULL)
524 return 0;
525 else
526 {
527 const char *p = strstr (name, "___");
528
529 if (p == NULL)
530 return strlen (name);
531 else
532 return p - name;
533 }
534 }
535
536 /* Return non-zero if SUFFIX is a suffix of STR.
537 Return zero if STR is null. */
538
539 static int
540 is_suffix (const char *str, const char *suffix)
541 {
542 int len1, len2;
543
544 if (str == NULL)
545 return 0;
546 len1 = strlen (str);
547 len2 = strlen (suffix);
548 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
549 }
550
551 /* The contents of value VAL, treated as a value of type TYPE. The
552 result is an lval in memory if VAL is. */
553
554 static struct value *
555 coerce_unspec_val_to_type (struct value *val, struct type *type)
556 {
557 type = ada_check_typedef (type);
558 if (value_type (val) == type)
559 return val;
560 else
561 {
562 struct value *result;
563
564 /* Make sure that the object size is not unreasonable before
565 trying to allocate some memory for it. */
566 ada_ensure_varsize_limit (type);
567
568 if (value_optimized_out (val))
569 result = allocate_optimized_out_value (type);
570 else if (value_lazy (val)
571 /* Be careful not to make a lazy not_lval value. */
572 || (VALUE_LVAL (val) != not_lval
573 && TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val))))
574 result = allocate_value_lazy (type);
575 else
576 {
577 result = allocate_value (type);
578 value_contents_copy (result, 0, val, 0, TYPE_LENGTH (type));
579 }
580 set_value_component_location (result, val);
581 set_value_bitsize (result, value_bitsize (val));
582 set_value_bitpos (result, value_bitpos (val));
583 if (VALUE_LVAL (result) == lval_memory)
584 set_value_address (result, value_address (val));
585 return result;
586 }
587 }
588
589 static const gdb_byte *
590 cond_offset_host (const gdb_byte *valaddr, long offset)
591 {
592 if (valaddr == NULL)
593 return NULL;
594 else
595 return valaddr + offset;
596 }
597
598 static CORE_ADDR
599 cond_offset_target (CORE_ADDR address, long offset)
600 {
601 if (address == 0)
602 return 0;
603 else
604 return address + offset;
605 }
606
607 /* Issue a warning (as for the definition of warning in utils.c, but
608 with exactly one argument rather than ...), unless the limit on the
609 number of warnings has passed during the evaluation of the current
610 expression. */
611
612 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
613 provided by "complaint". */
614 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
615
616 static void
617 lim_warning (const char *format, ...)
618 {
619 va_list args;
620
621 va_start (args, format);
622 warnings_issued += 1;
623 if (warnings_issued <= warning_limit)
624 vwarning (format, args);
625
626 va_end (args);
627 }
628
629 /* Issue an error if the size of an object of type T is unreasonable,
630 i.e. if it would be a bad idea to allocate a value of this type in
631 GDB. */
632
633 void
634 ada_ensure_varsize_limit (const struct type *type)
635 {
636 if (TYPE_LENGTH (type) > varsize_limit)
637 error (_("object size is larger than varsize-limit"));
638 }
639
640 /* Maximum value of a SIZE-byte signed integer type. */
641 static LONGEST
642 max_of_size (int size)
643 {
644 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
645
646 return top_bit | (top_bit - 1);
647 }
648
649 /* Minimum value of a SIZE-byte signed integer type. */
650 static LONGEST
651 min_of_size (int size)
652 {
653 return -max_of_size (size) - 1;
654 }
655
656 /* Maximum value of a SIZE-byte unsigned integer type. */
657 static ULONGEST
658 umax_of_size (int size)
659 {
660 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
661
662 return top_bit | (top_bit - 1);
663 }
664
665 /* Maximum value of integral type T, as a signed quantity. */
666 static LONGEST
667 max_of_type (struct type *t)
668 {
669 if (t->is_unsigned ())
670 return (LONGEST) umax_of_size (TYPE_LENGTH (t));
671 else
672 return max_of_size (TYPE_LENGTH (t));
673 }
674
675 /* Minimum value of integral type T, as a signed quantity. */
676 static LONGEST
677 min_of_type (struct type *t)
678 {
679 if (t->is_unsigned ())
680 return 0;
681 else
682 return min_of_size (TYPE_LENGTH (t));
683 }
684
685 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
686 LONGEST
687 ada_discrete_type_high_bound (struct type *type)
688 {
689 type = resolve_dynamic_type (type, {}, 0);
690 switch (type->code ())
691 {
692 case TYPE_CODE_RANGE:
693 {
694 const dynamic_prop &high = type->bounds ()->high;
695
696 if (high.kind () == PROP_CONST)
697 return high.const_val ();
698 else
699 {
700 gdb_assert (high.kind () == PROP_UNDEFINED);
701
702 /* This happens when trying to evaluate a type's dynamic bound
703 without a live target. There is nothing relevant for us to
704 return here, so return 0. */
705 return 0;
706 }
707 }
708 case TYPE_CODE_ENUM:
709 return TYPE_FIELD_ENUMVAL (type, type->num_fields () - 1);
710 case TYPE_CODE_BOOL:
711 return 1;
712 case TYPE_CODE_CHAR:
713 case TYPE_CODE_INT:
714 return max_of_type (type);
715 default:
716 error (_("Unexpected type in ada_discrete_type_high_bound."));
717 }
718 }
719
720 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
721 LONGEST
722 ada_discrete_type_low_bound (struct type *type)
723 {
724 type = resolve_dynamic_type (type, {}, 0);
725 switch (type->code ())
726 {
727 case TYPE_CODE_RANGE:
728 {
729 const dynamic_prop &low = type->bounds ()->low;
730
731 if (low.kind () == PROP_CONST)
732 return low.const_val ();
733 else
734 {
735 gdb_assert (low.kind () == PROP_UNDEFINED);
736
737 /* This happens when trying to evaluate a type's dynamic bound
738 without a live target. There is nothing relevant for us to
739 return here, so return 0. */
740 return 0;
741 }
742 }
743 case TYPE_CODE_ENUM:
744 return TYPE_FIELD_ENUMVAL (type, 0);
745 case TYPE_CODE_BOOL:
746 return 0;
747 case TYPE_CODE_CHAR:
748 case TYPE_CODE_INT:
749 return min_of_type (type);
750 default:
751 error (_("Unexpected type in ada_discrete_type_low_bound."));
752 }
753 }
754
755 /* The identity on non-range types. For range types, the underlying
756 non-range scalar type. */
757
758 static struct type *
759 get_base_type (struct type *type)
760 {
761 while (type != NULL && type->code () == TYPE_CODE_RANGE)
762 {
763 if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
764 return type;
765 type = TYPE_TARGET_TYPE (type);
766 }
767 return type;
768 }
769
770 /* Return a decoded version of the given VALUE. This means returning
771 a value whose type is obtained by applying all the GNAT-specific
772 encodings, making the resulting type a static but standard description
773 of the initial type. */
774
775 struct value *
776 ada_get_decoded_value (struct value *value)
777 {
778 struct type *type = ada_check_typedef (value_type (value));
779
780 if (ada_is_array_descriptor_type (type)
781 || (ada_is_constrained_packed_array_type (type)
782 && type->code () != TYPE_CODE_PTR))
783 {
784 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
785 value = ada_coerce_to_simple_array_ptr (value);
786 else
787 value = ada_coerce_to_simple_array (value);
788 }
789 else
790 value = ada_to_fixed_value (value);
791
792 return value;
793 }
794
795 /* Same as ada_get_decoded_value, but with the given TYPE.
796 Because there is no associated actual value for this type,
797 the resulting type might be a best-effort approximation in
798 the case of dynamic types. */
799
800 struct type *
801 ada_get_decoded_type (struct type *type)
802 {
803 type = to_static_fixed_type (type);
804 if (ada_is_constrained_packed_array_type (type))
805 type = ada_coerce_to_simple_array_type (type);
806 return type;
807 }
808
809 \f
810
811 /* Language Selection */
812
813 /* If the main program is in Ada, return language_ada, otherwise return LANG
814 (the main program is in Ada iif the adainit symbol is found). */
815
816 static enum language
817 ada_update_initial_language (enum language lang)
818 {
819 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
820 return language_ada;
821
822 return lang;
823 }
824
825 /* If the main procedure is written in Ada, then return its name.
826 The result is good until the next call. Return NULL if the main
827 procedure doesn't appear to be in Ada. */
828
829 char *
830 ada_main_name (void)
831 {
832 struct bound_minimal_symbol msym;
833 static gdb::unique_xmalloc_ptr<char> main_program_name;
834
835 /* For Ada, the name of the main procedure is stored in a specific
836 string constant, generated by the binder. Look for that symbol,
837 extract its address, and then read that string. If we didn't find
838 that string, then most probably the main procedure is not written
839 in Ada. */
840 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
841
842 if (msym.minsym != NULL)
843 {
844 CORE_ADDR main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
845 if (main_program_name_addr == 0)
846 error (_("Invalid address for Ada main program name."));
847
848 main_program_name = target_read_string (main_program_name_addr, 1024);
849 return main_program_name.get ();
850 }
851
852 /* The main procedure doesn't seem to be in Ada. */
853 return NULL;
854 }
855 \f
856 /* Symbols */
857
858 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
859 of NULLs. */
860
861 const struct ada_opname_map ada_opname_table[] = {
862 {"Oadd", "\"+\"", BINOP_ADD},
863 {"Osubtract", "\"-\"", BINOP_SUB},
864 {"Omultiply", "\"*\"", BINOP_MUL},
865 {"Odivide", "\"/\"", BINOP_DIV},
866 {"Omod", "\"mod\"", BINOP_MOD},
867 {"Orem", "\"rem\"", BINOP_REM},
868 {"Oexpon", "\"**\"", BINOP_EXP},
869 {"Olt", "\"<\"", BINOP_LESS},
870 {"Ole", "\"<=\"", BINOP_LEQ},
871 {"Ogt", "\">\"", BINOP_GTR},
872 {"Oge", "\">=\"", BINOP_GEQ},
873 {"Oeq", "\"=\"", BINOP_EQUAL},
874 {"One", "\"/=\"", BINOP_NOTEQUAL},
875 {"Oand", "\"and\"", BINOP_BITWISE_AND},
876 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
877 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
878 {"Oconcat", "\"&\"", BINOP_CONCAT},
879 {"Oabs", "\"abs\"", UNOP_ABS},
880 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
881 {"Oadd", "\"+\"", UNOP_PLUS},
882 {"Osubtract", "\"-\"", UNOP_NEG},
883 {NULL, NULL}
884 };
885
886 /* The "encoded" form of DECODED, according to GNAT conventions. If
887 THROW_ERRORS, throw an error if invalid operator name is found.
888 Otherwise, return the empty string in that case. */
889
890 static std::string
891 ada_encode_1 (const char *decoded, bool throw_errors)
892 {
893 if (decoded == NULL)
894 return {};
895
896 std::string encoding_buffer;
897 for (const char *p = decoded; *p != '\0'; p += 1)
898 {
899 if (*p == '.')
900 encoding_buffer.append ("__");
901 else if (*p == '"')
902 {
903 const struct ada_opname_map *mapping;
904
905 for (mapping = ada_opname_table;
906 mapping->encoded != NULL
907 && !startswith (p, mapping->decoded); mapping += 1)
908 ;
909 if (mapping->encoded == NULL)
910 {
911 if (throw_errors)
912 error (_("invalid Ada operator name: %s"), p);
913 else
914 return {};
915 }
916 encoding_buffer.append (mapping->encoded);
917 break;
918 }
919 else
920 encoding_buffer.push_back (*p);
921 }
922
923 return encoding_buffer;
924 }
925
926 /* The "encoded" form of DECODED, according to GNAT conventions. */
927
928 std::string
929 ada_encode (const char *decoded)
930 {
931 return ada_encode_1 (decoded, true);
932 }
933
934 /* Return NAME folded to lower case, or, if surrounded by single
935 quotes, unfolded, but with the quotes stripped away. Result good
936 to next call. */
937
938 static const char *
939 ada_fold_name (gdb::string_view name)
940 {
941 static std::string fold_storage;
942
943 if (!name.empty () && name[0] == '\'')
944 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
945 else
946 {
947 fold_storage = gdb::to_string (name);
948 for (int i = 0; i < name.size (); i += 1)
949 fold_storage[i] = tolower (fold_storage[i]);
950 }
951
952 return fold_storage.c_str ();
953 }
954
955 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
956
957 static int
958 is_lower_alphanum (const char c)
959 {
960 return (isdigit (c) || (isalpha (c) && islower (c)));
961 }
962
963 /* ENCODED is the linkage name of a symbol and LEN contains its length.
964 This function saves in LEN the length of that same symbol name but
965 without either of these suffixes:
966 . .{DIGIT}+
967 . ${DIGIT}+
968 . ___{DIGIT}+
969 . __{DIGIT}+.
970
971 These are suffixes introduced by the compiler for entities such as
972 nested subprogram for instance, in order to avoid name clashes.
973 They do not serve any purpose for the debugger. */
974
975 static void
976 ada_remove_trailing_digits (const char *encoded, int *len)
977 {
978 if (*len > 1 && isdigit (encoded[*len - 1]))
979 {
980 int i = *len - 2;
981
982 while (i > 0 && isdigit (encoded[i]))
983 i--;
984 if (i >= 0 && encoded[i] == '.')
985 *len = i;
986 else if (i >= 0 && encoded[i] == '$')
987 *len = i;
988 else if (i >= 2 && startswith (encoded + i - 2, "___"))
989 *len = i - 2;
990 else if (i >= 1 && startswith (encoded + i - 1, "__"))
991 *len = i - 1;
992 }
993 }
994
995 /* Remove the suffix introduced by the compiler for protected object
996 subprograms. */
997
998 static void
999 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1000 {
1001 /* Remove trailing N. */
1002
1003 /* Protected entry subprograms are broken into two
1004 separate subprograms: The first one is unprotected, and has
1005 a 'N' suffix; the second is the protected version, and has
1006 the 'P' suffix. The second calls the first one after handling
1007 the protection. Since the P subprograms are internally generated,
1008 we leave these names undecoded, giving the user a clue that this
1009 entity is internal. */
1010
1011 if (*len > 1
1012 && encoded[*len - 1] == 'N'
1013 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1014 *len = *len - 1;
1015 }
1016
1017 /* If ENCODED follows the GNAT entity encoding conventions, then return
1018 the decoded form of ENCODED. Otherwise, return "<%s>" where "%s" is
1019 replaced by ENCODED. */
1020
1021 std::string
1022 ada_decode (const char *encoded)
1023 {
1024 int i, j;
1025 int len0;
1026 const char *p;
1027 int at_start_name;
1028 std::string decoded;
1029
1030 /* With function descriptors on PPC64, the value of a symbol named
1031 ".FN", if it exists, is the entry point of the function "FN". */
1032 if (encoded[0] == '.')
1033 encoded += 1;
1034
1035 /* The name of the Ada main procedure starts with "_ada_".
1036 This prefix is not part of the decoded name, so skip this part
1037 if we see this prefix. */
1038 if (startswith (encoded, "_ada_"))
1039 encoded += 5;
1040
1041 /* If the name starts with '_', then it is not a properly encoded
1042 name, so do not attempt to decode it. Similarly, if the name
1043 starts with '<', the name should not be decoded. */
1044 if (encoded[0] == '_' || encoded[0] == '<')
1045 goto Suppress;
1046
1047 len0 = strlen (encoded);
1048
1049 ada_remove_trailing_digits (encoded, &len0);
1050 ada_remove_po_subprogram_suffix (encoded, &len0);
1051
1052 /* Remove the ___X.* suffix if present. Do not forget to verify that
1053 the suffix is located before the current "end" of ENCODED. We want
1054 to avoid re-matching parts of ENCODED that have previously been
1055 marked as discarded (by decrementing LEN0). */
1056 p = strstr (encoded, "___");
1057 if (p != NULL && p - encoded < len0 - 3)
1058 {
1059 if (p[3] == 'X')
1060 len0 = p - encoded;
1061 else
1062 goto Suppress;
1063 }
1064
1065 /* Remove any trailing TKB suffix. It tells us that this symbol
1066 is for the body of a task, but that information does not actually
1067 appear in the decoded name. */
1068
1069 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1070 len0 -= 3;
1071
1072 /* Remove any trailing TB suffix. The TB suffix is slightly different
1073 from the TKB suffix because it is used for non-anonymous task
1074 bodies. */
1075
1076 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1077 len0 -= 2;
1078
1079 /* Remove trailing "B" suffixes. */
1080 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1081
1082 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1083 len0 -= 1;
1084
1085 /* Make decoded big enough for possible expansion by operator name. */
1086
1087 decoded.resize (2 * len0 + 1, 'X');
1088
1089 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1090
1091 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1092 {
1093 i = len0 - 2;
1094 while ((i >= 0 && isdigit (encoded[i]))
1095 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1096 i -= 1;
1097 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1098 len0 = i - 1;
1099 else if (encoded[i] == '$')
1100 len0 = i;
1101 }
1102
1103 /* The first few characters that are not alphabetic are not part
1104 of any encoding we use, so we can copy them over verbatim. */
1105
1106 for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1107 decoded[j] = encoded[i];
1108
1109 at_start_name = 1;
1110 while (i < len0)
1111 {
1112 /* Is this a symbol function? */
1113 if (at_start_name && encoded[i] == 'O')
1114 {
1115 int k;
1116
1117 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1118 {
1119 int op_len = strlen (ada_opname_table[k].encoded);
1120 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1121 op_len - 1) == 0)
1122 && !isalnum (encoded[i + op_len]))
1123 {
1124 strcpy (&decoded.front() + j, ada_opname_table[k].decoded);
1125 at_start_name = 0;
1126 i += op_len;
1127 j += strlen (ada_opname_table[k].decoded);
1128 break;
1129 }
1130 }
1131 if (ada_opname_table[k].encoded != NULL)
1132 continue;
1133 }
1134 at_start_name = 0;
1135
1136 /* Replace "TK__" with "__", which will eventually be translated
1137 into "." (just below). */
1138
1139 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1140 i += 2;
1141
1142 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1143 be translated into "." (just below). These are internal names
1144 generated for anonymous blocks inside which our symbol is nested. */
1145
1146 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1147 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1148 && isdigit (encoded [i+4]))
1149 {
1150 int k = i + 5;
1151
1152 while (k < len0 && isdigit (encoded[k]))
1153 k++; /* Skip any extra digit. */
1154
1155 /* Double-check that the "__B_{DIGITS}+" sequence we found
1156 is indeed followed by "__". */
1157 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1158 i = k;
1159 }
1160
1161 /* Remove _E{DIGITS}+[sb] */
1162
1163 /* Just as for protected object subprograms, there are 2 categories
1164 of subprograms created by the compiler for each entry. The first
1165 one implements the actual entry code, and has a suffix following
1166 the convention above; the second one implements the barrier and
1167 uses the same convention as above, except that the 'E' is replaced
1168 by a 'B'.
1169
1170 Just as above, we do not decode the name of barrier functions
1171 to give the user a clue that the code he is debugging has been
1172 internally generated. */
1173
1174 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1175 && isdigit (encoded[i+2]))
1176 {
1177 int k = i + 3;
1178
1179 while (k < len0 && isdigit (encoded[k]))
1180 k++;
1181
1182 if (k < len0
1183 && (encoded[k] == 'b' || encoded[k] == 's'))
1184 {
1185 k++;
1186 /* Just as an extra precaution, make sure that if this
1187 suffix is followed by anything else, it is a '_'.
1188 Otherwise, we matched this sequence by accident. */
1189 if (k == len0
1190 || (k < len0 && encoded[k] == '_'))
1191 i = k;
1192 }
1193 }
1194
1195 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1196 the GNAT front-end in protected object subprograms. */
1197
1198 if (i < len0 + 3
1199 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1200 {
1201 /* Backtrack a bit up until we reach either the begining of
1202 the encoded name, or "__". Make sure that we only find
1203 digits or lowercase characters. */
1204 const char *ptr = encoded + i - 1;
1205
1206 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1207 ptr--;
1208 if (ptr < encoded
1209 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1210 i++;
1211 }
1212
1213 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1214 {
1215 /* This is a X[bn]* sequence not separated from the previous
1216 part of the name with a non-alpha-numeric character (in other
1217 words, immediately following an alpha-numeric character), then
1218 verify that it is placed at the end of the encoded name. If
1219 not, then the encoding is not valid and we should abort the
1220 decoding. Otherwise, just skip it, it is used in body-nested
1221 package names. */
1222 do
1223 i += 1;
1224 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1225 if (i < len0)
1226 goto Suppress;
1227 }
1228 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1229 {
1230 /* Replace '__' by '.'. */
1231 decoded[j] = '.';
1232 at_start_name = 1;
1233 i += 2;
1234 j += 1;
1235 }
1236 else
1237 {
1238 /* It's a character part of the decoded name, so just copy it
1239 over. */
1240 decoded[j] = encoded[i];
1241 i += 1;
1242 j += 1;
1243 }
1244 }
1245 decoded.resize (j);
1246
1247 /* Decoded names should never contain any uppercase character.
1248 Double-check this, and abort the decoding if we find one. */
1249
1250 for (i = 0; i < decoded.length(); ++i)
1251 if (isupper (decoded[i]) || decoded[i] == ' ')
1252 goto Suppress;
1253
1254 return decoded;
1255
1256 Suppress:
1257 if (encoded[0] == '<')
1258 decoded = encoded;
1259 else
1260 decoded = '<' + std::string(encoded) + '>';
1261 return decoded;
1262
1263 }
1264
1265 /* Table for keeping permanent unique copies of decoded names. Once
1266 allocated, names in this table are never released. While this is a
1267 storage leak, it should not be significant unless there are massive
1268 changes in the set of decoded names in successive versions of a
1269 symbol table loaded during a single session. */
1270 static struct htab *decoded_names_store;
1271
1272 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1273 in the language-specific part of GSYMBOL, if it has not been
1274 previously computed. Tries to save the decoded name in the same
1275 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1276 in any case, the decoded symbol has a lifetime at least that of
1277 GSYMBOL).
1278 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1279 const, but nevertheless modified to a semantically equivalent form
1280 when a decoded name is cached in it. */
1281
1282 const char *
1283 ada_decode_symbol (const struct general_symbol_info *arg)
1284 {
1285 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1286 const char **resultp =
1287 &gsymbol->language_specific.demangled_name;
1288
1289 if (!gsymbol->ada_mangled)
1290 {
1291 std::string decoded = ada_decode (gsymbol->linkage_name ());
1292 struct obstack *obstack = gsymbol->language_specific.obstack;
1293
1294 gsymbol->ada_mangled = 1;
1295
1296 if (obstack != NULL)
1297 *resultp = obstack_strdup (obstack, decoded.c_str ());
1298 else
1299 {
1300 /* Sometimes, we can't find a corresponding objfile, in
1301 which case, we put the result on the heap. Since we only
1302 decode when needed, we hope this usually does not cause a
1303 significant memory leak (FIXME). */
1304
1305 char **slot = (char **) htab_find_slot (decoded_names_store,
1306 decoded.c_str (), INSERT);
1307
1308 if (*slot == NULL)
1309 *slot = xstrdup (decoded.c_str ());
1310 *resultp = *slot;
1311 }
1312 }
1313
1314 return *resultp;
1315 }
1316
1317 static char *
1318 ada_la_decode (const char *encoded, int options)
1319 {
1320 return xstrdup (ada_decode (encoded).c_str ());
1321 }
1322
1323 \f
1324
1325 /* Arrays */
1326
1327 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1328 generated by the GNAT compiler to describe the index type used
1329 for each dimension of an array, check whether it follows the latest
1330 known encoding. If not, fix it up to conform to the latest encoding.
1331 Otherwise, do nothing. This function also does nothing if
1332 INDEX_DESC_TYPE is NULL.
1333
1334 The GNAT encoding used to describe the array index type evolved a bit.
1335 Initially, the information would be provided through the name of each
1336 field of the structure type only, while the type of these fields was
1337 described as unspecified and irrelevant. The debugger was then expected
1338 to perform a global type lookup using the name of that field in order
1339 to get access to the full index type description. Because these global
1340 lookups can be very expensive, the encoding was later enhanced to make
1341 the global lookup unnecessary by defining the field type as being
1342 the full index type description.
1343
1344 The purpose of this routine is to allow us to support older versions
1345 of the compiler by detecting the use of the older encoding, and by
1346 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1347 we essentially replace each field's meaningless type by the associated
1348 index subtype). */
1349
1350 void
1351 ada_fixup_array_indexes_type (struct type *index_desc_type)
1352 {
1353 int i;
1354
1355 if (index_desc_type == NULL)
1356 return;
1357 gdb_assert (index_desc_type->num_fields () > 0);
1358
1359 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1360 to check one field only, no need to check them all). If not, return
1361 now.
1362
1363 If our INDEX_DESC_TYPE was generated using the older encoding,
1364 the field type should be a meaningless integer type whose name
1365 is not equal to the field name. */
1366 if (index_desc_type->field (0).type ()->name () != NULL
1367 && strcmp (index_desc_type->field (0).type ()->name (),
1368 TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
1369 return;
1370
1371 /* Fixup each field of INDEX_DESC_TYPE. */
1372 for (i = 0; i < index_desc_type->num_fields (); i++)
1373 {
1374 const char *name = TYPE_FIELD_NAME (index_desc_type, i);
1375 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1376
1377 if (raw_type)
1378 index_desc_type->field (i).set_type (raw_type);
1379 }
1380 }
1381
1382 /* The desc_* routines return primitive portions of array descriptors
1383 (fat pointers). */
1384
1385 /* The descriptor or array type, if any, indicated by TYPE; removes
1386 level of indirection, if needed. */
1387
1388 static struct type *
1389 desc_base_type (struct type *type)
1390 {
1391 if (type == NULL)
1392 return NULL;
1393 type = ada_check_typedef (type);
1394 if (type->code () == TYPE_CODE_TYPEDEF)
1395 type = ada_typedef_target_type (type);
1396
1397 if (type != NULL
1398 && (type->code () == TYPE_CODE_PTR
1399 || type->code () == TYPE_CODE_REF))
1400 return ada_check_typedef (TYPE_TARGET_TYPE (type));
1401 else
1402 return type;
1403 }
1404
1405 /* True iff TYPE indicates a "thin" array pointer type. */
1406
1407 static int
1408 is_thin_pntr (struct type *type)
1409 {
1410 return
1411 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1412 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1413 }
1414
1415 /* The descriptor type for thin pointer type TYPE. */
1416
1417 static struct type *
1418 thin_descriptor_type (struct type *type)
1419 {
1420 struct type *base_type = desc_base_type (type);
1421
1422 if (base_type == NULL)
1423 return NULL;
1424 if (is_suffix (ada_type_name (base_type), "___XVE"))
1425 return base_type;
1426 else
1427 {
1428 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1429
1430 if (alt_type == NULL)
1431 return base_type;
1432 else
1433 return alt_type;
1434 }
1435 }
1436
1437 /* A pointer to the array data for thin-pointer value VAL. */
1438
1439 static struct value *
1440 thin_data_pntr (struct value *val)
1441 {
1442 struct type *type = ada_check_typedef (value_type (val));
1443 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1444
1445 data_type = lookup_pointer_type (data_type);
1446
1447 if (type->code () == TYPE_CODE_PTR)
1448 return value_cast (data_type, value_copy (val));
1449 else
1450 return value_from_longest (data_type, value_address (val));
1451 }
1452
1453 /* True iff TYPE indicates a "thick" array pointer type. */
1454
1455 static int
1456 is_thick_pntr (struct type *type)
1457 {
1458 type = desc_base_type (type);
1459 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1460 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1461 }
1462
1463 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1464 pointer to one, the type of its bounds data; otherwise, NULL. */
1465
1466 static struct type *
1467 desc_bounds_type (struct type *type)
1468 {
1469 struct type *r;
1470
1471 type = desc_base_type (type);
1472
1473 if (type == NULL)
1474 return NULL;
1475 else if (is_thin_pntr (type))
1476 {
1477 type = thin_descriptor_type (type);
1478 if (type == NULL)
1479 return NULL;
1480 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1481 if (r != NULL)
1482 return ada_check_typedef (r);
1483 }
1484 else if (type->code () == TYPE_CODE_STRUCT)
1485 {
1486 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1487 if (r != NULL)
1488 return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1489 }
1490 return NULL;
1491 }
1492
1493 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1494 one, a pointer to its bounds data. Otherwise NULL. */
1495
1496 static struct value *
1497 desc_bounds (struct value *arr)
1498 {
1499 struct type *type = ada_check_typedef (value_type (arr));
1500
1501 if (is_thin_pntr (type))
1502 {
1503 struct type *bounds_type =
1504 desc_bounds_type (thin_descriptor_type (type));
1505 LONGEST addr;
1506
1507 if (bounds_type == NULL)
1508 error (_("Bad GNAT array descriptor"));
1509
1510 /* NOTE: The following calculation is not really kosher, but
1511 since desc_type is an XVE-encoded type (and shouldn't be),
1512 the correct calculation is a real pain. FIXME (and fix GCC). */
1513 if (type->code () == TYPE_CODE_PTR)
1514 addr = value_as_long (arr);
1515 else
1516 addr = value_address (arr);
1517
1518 return
1519 value_from_longest (lookup_pointer_type (bounds_type),
1520 addr - TYPE_LENGTH (bounds_type));
1521 }
1522
1523 else if (is_thick_pntr (type))
1524 {
1525 struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1526 _("Bad GNAT array descriptor"));
1527 struct type *p_bounds_type = value_type (p_bounds);
1528
1529 if (p_bounds_type
1530 && p_bounds_type->code () == TYPE_CODE_PTR)
1531 {
1532 struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1533
1534 if (target_type->is_stub ())
1535 p_bounds = value_cast (lookup_pointer_type
1536 (ada_check_typedef (target_type)),
1537 p_bounds);
1538 }
1539 else
1540 error (_("Bad GNAT array descriptor"));
1541
1542 return p_bounds;
1543 }
1544 else
1545 return NULL;
1546 }
1547
1548 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1549 position of the field containing the address of the bounds data. */
1550
1551 static int
1552 fat_pntr_bounds_bitpos (struct type *type)
1553 {
1554 return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1555 }
1556
1557 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1558 size of the field containing the address of the bounds data. */
1559
1560 static int
1561 fat_pntr_bounds_bitsize (struct type *type)
1562 {
1563 type = desc_base_type (type);
1564
1565 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1566 return TYPE_FIELD_BITSIZE (type, 1);
1567 else
1568 return 8 * TYPE_LENGTH (ada_check_typedef (type->field (1).type ()));
1569 }
1570
1571 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1572 pointer to one, the type of its array data (a array-with-no-bounds type);
1573 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1574 data. */
1575
1576 static struct type *
1577 desc_data_target_type (struct type *type)
1578 {
1579 type = desc_base_type (type);
1580
1581 /* NOTE: The following is bogus; see comment in desc_bounds. */
1582 if (is_thin_pntr (type))
1583 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1584 else if (is_thick_pntr (type))
1585 {
1586 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1587
1588 if (data_type
1589 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1590 return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1591 }
1592
1593 return NULL;
1594 }
1595
1596 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1597 its array data. */
1598
1599 static struct value *
1600 desc_data (struct value *arr)
1601 {
1602 struct type *type = value_type (arr);
1603
1604 if (is_thin_pntr (type))
1605 return thin_data_pntr (arr);
1606 else if (is_thick_pntr (type))
1607 return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1608 _("Bad GNAT array descriptor"));
1609 else
1610 return NULL;
1611 }
1612
1613
1614 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1615 position of the field containing the address of the data. */
1616
1617 static int
1618 fat_pntr_data_bitpos (struct type *type)
1619 {
1620 return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1621 }
1622
1623 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1624 size of the field containing the address of the data. */
1625
1626 static int
1627 fat_pntr_data_bitsize (struct type *type)
1628 {
1629 type = desc_base_type (type);
1630
1631 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1632 return TYPE_FIELD_BITSIZE (type, 0);
1633 else
1634 return TARGET_CHAR_BIT * TYPE_LENGTH (type->field (0).type ());
1635 }
1636
1637 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1638 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1639 bound, if WHICH is 1. The first bound is I=1. */
1640
1641 static struct value *
1642 desc_one_bound (struct value *bounds, int i, int which)
1643 {
1644 char bound_name[20];
1645 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1646 which ? 'U' : 'L', i - 1);
1647 return value_struct_elt (&bounds, NULL, bound_name, NULL,
1648 _("Bad GNAT array descriptor bounds"));
1649 }
1650
1651 /* If BOUNDS is an array-bounds structure type, return the bit position
1652 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1653 bound, if WHICH is 1. The first bound is I=1. */
1654
1655 static int
1656 desc_bound_bitpos (struct type *type, int i, int which)
1657 {
1658 return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1659 }
1660
1661 /* If BOUNDS is an array-bounds structure type, return the bit field size
1662 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1663 bound, if WHICH is 1. The first bound is I=1. */
1664
1665 static int
1666 desc_bound_bitsize (struct type *type, int i, int which)
1667 {
1668 type = desc_base_type (type);
1669
1670 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1671 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1672 else
1673 return 8 * TYPE_LENGTH (type->field (2 * i + which - 2).type ());
1674 }
1675
1676 /* If TYPE is the type of an array-bounds structure, the type of its
1677 Ith bound (numbering from 1). Otherwise, NULL. */
1678
1679 static struct type *
1680 desc_index_type (struct type *type, int i)
1681 {
1682 type = desc_base_type (type);
1683
1684 if (type->code () == TYPE_CODE_STRUCT)
1685 {
1686 char bound_name[20];
1687 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
1688 return lookup_struct_elt_type (type, bound_name, 1);
1689 }
1690 else
1691 return NULL;
1692 }
1693
1694 /* The number of index positions in the array-bounds type TYPE.
1695 Return 0 if TYPE is NULL. */
1696
1697 static int
1698 desc_arity (struct type *type)
1699 {
1700 type = desc_base_type (type);
1701
1702 if (type != NULL)
1703 return type->num_fields () / 2;
1704 return 0;
1705 }
1706
1707 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
1708 an array descriptor type (representing an unconstrained array
1709 type). */
1710
1711 static int
1712 ada_is_direct_array_type (struct type *type)
1713 {
1714 if (type == NULL)
1715 return 0;
1716 type = ada_check_typedef (type);
1717 return (type->code () == TYPE_CODE_ARRAY
1718 || ada_is_array_descriptor_type (type));
1719 }
1720
1721 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1722 * to one. */
1723
1724 static int
1725 ada_is_array_type (struct type *type)
1726 {
1727 while (type != NULL
1728 && (type->code () == TYPE_CODE_PTR
1729 || type->code () == TYPE_CODE_REF))
1730 type = TYPE_TARGET_TYPE (type);
1731 return ada_is_direct_array_type (type);
1732 }
1733
1734 /* Non-zero iff TYPE is a simple array type or pointer to one. */
1735
1736 int
1737 ada_is_simple_array_type (struct type *type)
1738 {
1739 if (type == NULL)
1740 return 0;
1741 type = ada_check_typedef (type);
1742 return (type->code () == TYPE_CODE_ARRAY
1743 || (type->code () == TYPE_CODE_PTR
1744 && (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ()
1745 == TYPE_CODE_ARRAY)));
1746 }
1747
1748 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
1749
1750 int
1751 ada_is_array_descriptor_type (struct type *type)
1752 {
1753 struct type *data_type = desc_data_target_type (type);
1754
1755 if (type == NULL)
1756 return 0;
1757 type = ada_check_typedef (type);
1758 return (data_type != NULL
1759 && data_type->code () == TYPE_CODE_ARRAY
1760 && desc_arity (desc_bounds_type (type)) > 0);
1761 }
1762
1763 /* Non-zero iff type is a partially mal-formed GNAT array
1764 descriptor. FIXME: This is to compensate for some problems with
1765 debugging output from GNAT. Re-examine periodically to see if it
1766 is still needed. */
1767
1768 int
1769 ada_is_bogus_array_descriptor (struct type *type)
1770 {
1771 return
1772 type != NULL
1773 && type->code () == TYPE_CODE_STRUCT
1774 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1775 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1776 && !ada_is_array_descriptor_type (type);
1777 }
1778
1779
1780 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1781 (fat pointer) returns the type of the array data described---specifically,
1782 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
1783 in from the descriptor; otherwise, they are left unspecified. If
1784 the ARR denotes a null array descriptor and BOUNDS is non-zero,
1785 returns NULL. The result is simply the type of ARR if ARR is not
1786 a descriptor. */
1787
1788 static struct type *
1789 ada_type_of_array (struct value *arr, int bounds)
1790 {
1791 if (ada_is_constrained_packed_array_type (value_type (arr)))
1792 return decode_constrained_packed_array_type (value_type (arr));
1793
1794 if (!ada_is_array_descriptor_type (value_type (arr)))
1795 return value_type (arr);
1796
1797 if (!bounds)
1798 {
1799 struct type *array_type =
1800 ada_check_typedef (desc_data_target_type (value_type (arr)));
1801
1802 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1803 TYPE_FIELD_BITSIZE (array_type, 0) =
1804 decode_packed_array_bitsize (value_type (arr));
1805
1806 return array_type;
1807 }
1808 else
1809 {
1810 struct type *elt_type;
1811 int arity;
1812 struct value *descriptor;
1813
1814 elt_type = ada_array_element_type (value_type (arr), -1);
1815 arity = ada_array_arity (value_type (arr));
1816
1817 if (elt_type == NULL || arity == 0)
1818 return ada_check_typedef (value_type (arr));
1819
1820 descriptor = desc_bounds (arr);
1821 if (value_as_long (descriptor) == 0)
1822 return NULL;
1823 while (arity > 0)
1824 {
1825 struct type *range_type = alloc_type_copy (value_type (arr));
1826 struct type *array_type = alloc_type_copy (value_type (arr));
1827 struct value *low = desc_one_bound (descriptor, arity, 0);
1828 struct value *high = desc_one_bound (descriptor, arity, 1);
1829
1830 arity -= 1;
1831 create_static_range_type (range_type, value_type (low),
1832 longest_to_int (value_as_long (low)),
1833 longest_to_int (value_as_long (high)));
1834 elt_type = create_array_type (array_type, elt_type, range_type);
1835
1836 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1837 {
1838 /* We need to store the element packed bitsize, as well as
1839 recompute the array size, because it was previously
1840 computed based on the unpacked element size. */
1841 LONGEST lo = value_as_long (low);
1842 LONGEST hi = value_as_long (high);
1843
1844 TYPE_FIELD_BITSIZE (elt_type, 0) =
1845 decode_packed_array_bitsize (value_type (arr));
1846 /* If the array has no element, then the size is already
1847 zero, and does not need to be recomputed. */
1848 if (lo < hi)
1849 {
1850 int array_bitsize =
1851 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
1852
1853 TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
1854 }
1855 }
1856 }
1857
1858 return lookup_pointer_type (elt_type);
1859 }
1860 }
1861
1862 /* If ARR does not represent an array, returns ARR unchanged.
1863 Otherwise, returns either a standard GDB array with bounds set
1864 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1865 GDB array. Returns NULL if ARR is a null fat pointer. */
1866
1867 struct value *
1868 ada_coerce_to_simple_array_ptr (struct value *arr)
1869 {
1870 if (ada_is_array_descriptor_type (value_type (arr)))
1871 {
1872 struct type *arrType = ada_type_of_array (arr, 1);
1873
1874 if (arrType == NULL)
1875 return NULL;
1876 return value_cast (arrType, value_copy (desc_data (arr)));
1877 }
1878 else if (ada_is_constrained_packed_array_type (value_type (arr)))
1879 return decode_constrained_packed_array (arr);
1880 else
1881 return arr;
1882 }
1883
1884 /* If ARR does not represent an array, returns ARR unchanged.
1885 Otherwise, returns a standard GDB array describing ARR (which may
1886 be ARR itself if it already is in the proper form). */
1887
1888 struct value *
1889 ada_coerce_to_simple_array (struct value *arr)
1890 {
1891 if (ada_is_array_descriptor_type (value_type (arr)))
1892 {
1893 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1894
1895 if (arrVal == NULL)
1896 error (_("Bounds unavailable for null array pointer."));
1897 ada_ensure_varsize_limit (TYPE_TARGET_TYPE (value_type (arrVal)));
1898 return value_ind (arrVal);
1899 }
1900 else if (ada_is_constrained_packed_array_type (value_type (arr)))
1901 return decode_constrained_packed_array (arr);
1902 else
1903 return arr;
1904 }
1905
1906 /* If TYPE represents a GNAT array type, return it translated to an
1907 ordinary GDB array type (possibly with BITSIZE fields indicating
1908 packing). For other types, is the identity. */
1909
1910 struct type *
1911 ada_coerce_to_simple_array_type (struct type *type)
1912 {
1913 if (ada_is_constrained_packed_array_type (type))
1914 return decode_constrained_packed_array_type (type);
1915
1916 if (ada_is_array_descriptor_type (type))
1917 return ada_check_typedef (desc_data_target_type (type));
1918
1919 return type;
1920 }
1921
1922 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
1923
1924 static int
1925 ada_is_gnat_encoded_packed_array_type (struct type *type)
1926 {
1927 if (type == NULL)
1928 return 0;
1929 type = desc_base_type (type);
1930 type = ada_check_typedef (type);
1931 return
1932 ada_type_name (type) != NULL
1933 && strstr (ada_type_name (type), "___XP") != NULL;
1934 }
1935
1936 /* Non-zero iff TYPE represents a standard GNAT constrained
1937 packed-array type. */
1938
1939 int
1940 ada_is_constrained_packed_array_type (struct type *type)
1941 {
1942 return ada_is_gnat_encoded_packed_array_type (type)
1943 && !ada_is_array_descriptor_type (type);
1944 }
1945
1946 /* Non-zero iff TYPE represents an array descriptor for a
1947 unconstrained packed-array type. */
1948
1949 static int
1950 ada_is_unconstrained_packed_array_type (struct type *type)
1951 {
1952 if (!ada_is_array_descriptor_type (type))
1953 return 0;
1954
1955 if (ada_is_gnat_encoded_packed_array_type (type))
1956 return 1;
1957
1958 /* If we saw GNAT encodings, then the above code is sufficient.
1959 However, with minimal encodings, we will just have a thick
1960 pointer instead. */
1961 if (is_thick_pntr (type))
1962 {
1963 type = desc_base_type (type);
1964 /* The structure's first field is a pointer to an array, so this
1965 fetches the array type. */
1966 type = TYPE_TARGET_TYPE (type->field (0).type ());
1967 /* Now we can see if the array elements are packed. */
1968 return TYPE_FIELD_BITSIZE (type, 0) > 0;
1969 }
1970
1971 return 0;
1972 }
1973
1974 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
1975 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
1976
1977 static bool
1978 ada_is_any_packed_array_type (struct type *type)
1979 {
1980 return (ada_is_constrained_packed_array_type (type)
1981 || (type->code () == TYPE_CODE_ARRAY
1982 && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
1983 }
1984
1985 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
1986 return the size of its elements in bits. */
1987
1988 static long
1989 decode_packed_array_bitsize (struct type *type)
1990 {
1991 const char *raw_name;
1992 const char *tail;
1993 long bits;
1994
1995 /* Access to arrays implemented as fat pointers are encoded as a typedef
1996 of the fat pointer type. We need the name of the fat pointer type
1997 to do the decoding, so strip the typedef layer. */
1998 if (type->code () == TYPE_CODE_TYPEDEF)
1999 type = ada_typedef_target_type (type);
2000
2001 raw_name = ada_type_name (ada_check_typedef (type));
2002 if (!raw_name)
2003 raw_name = ada_type_name (desc_base_type (type));
2004
2005 if (!raw_name)
2006 return 0;
2007
2008 tail = strstr (raw_name, "___XP");
2009 if (tail == nullptr)
2010 {
2011 gdb_assert (is_thick_pntr (type));
2012 /* The structure's first field is a pointer to an array, so this
2013 fetches the array type. */
2014 type = TYPE_TARGET_TYPE (type->field (0).type ());
2015 /* Now we can see if the array elements are packed. */
2016 return TYPE_FIELD_BITSIZE (type, 0);
2017 }
2018
2019 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2020 {
2021 lim_warning
2022 (_("could not understand bit size information on packed array"));
2023 return 0;
2024 }
2025
2026 return bits;
2027 }
2028
2029 /* Given that TYPE is a standard GDB array type with all bounds filled
2030 in, and that the element size of its ultimate scalar constituents
2031 (that is, either its elements, or, if it is an array of arrays, its
2032 elements' elements, etc.) is *ELT_BITS, return an identical type,
2033 but with the bit sizes of its elements (and those of any
2034 constituent arrays) recorded in the BITSIZE components of its
2035 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2036 in bits.
2037
2038 Note that, for arrays whose index type has an XA encoding where
2039 a bound references a record discriminant, getting that discriminant,
2040 and therefore the actual value of that bound, is not possible
2041 because none of the given parameters gives us access to the record.
2042 This function assumes that it is OK in the context where it is being
2043 used to return an array whose bounds are still dynamic and where
2044 the length is arbitrary. */
2045
2046 static struct type *
2047 constrained_packed_array_type (struct type *type, long *elt_bits)
2048 {
2049 struct type *new_elt_type;
2050 struct type *new_type;
2051 struct type *index_type_desc;
2052 struct type *index_type;
2053 LONGEST low_bound, high_bound;
2054
2055 type = ada_check_typedef (type);
2056 if (type->code () != TYPE_CODE_ARRAY)
2057 return type;
2058
2059 index_type_desc = ada_find_parallel_type (type, "___XA");
2060 if (index_type_desc)
2061 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2062 NULL);
2063 else
2064 index_type = type->index_type ();
2065
2066 new_type = alloc_type_copy (type);
2067 new_elt_type =
2068 constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2069 elt_bits);
2070 create_array_type (new_type, new_elt_type, index_type);
2071 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2072 new_type->set_name (ada_type_name (type));
2073
2074 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2075 && is_dynamic_type (check_typedef (index_type)))
2076 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2077 low_bound = high_bound = 0;
2078 if (high_bound < low_bound)
2079 *elt_bits = TYPE_LENGTH (new_type) = 0;
2080 else
2081 {
2082 *elt_bits *= (high_bound - low_bound + 1);
2083 TYPE_LENGTH (new_type) =
2084 (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2085 }
2086
2087 new_type->set_is_fixed_instance (true);
2088 return new_type;
2089 }
2090
2091 /* The array type encoded by TYPE, where
2092 ada_is_constrained_packed_array_type (TYPE). */
2093
2094 static struct type *
2095 decode_constrained_packed_array_type (struct type *type)
2096 {
2097 const char *raw_name = ada_type_name (ada_check_typedef (type));
2098 char *name;
2099 const char *tail;
2100 struct type *shadow_type;
2101 long bits;
2102
2103 if (!raw_name)
2104 raw_name = ada_type_name (desc_base_type (type));
2105
2106 if (!raw_name)
2107 return NULL;
2108
2109 name = (char *) alloca (strlen (raw_name) + 1);
2110 tail = strstr (raw_name, "___XP");
2111 type = desc_base_type (type);
2112
2113 memcpy (name, raw_name, tail - raw_name);
2114 name[tail - raw_name] = '\000';
2115
2116 shadow_type = ada_find_parallel_type_with_name (type, name);
2117
2118 if (shadow_type == NULL)
2119 {
2120 lim_warning (_("could not find bounds information on packed array"));
2121 return NULL;
2122 }
2123 shadow_type = check_typedef (shadow_type);
2124
2125 if (shadow_type->code () != TYPE_CODE_ARRAY)
2126 {
2127 lim_warning (_("could not understand bounds "
2128 "information on packed array"));
2129 return NULL;
2130 }
2131
2132 bits = decode_packed_array_bitsize (type);
2133 return constrained_packed_array_type (shadow_type, &bits);
2134 }
2135
2136 /* Helper function for decode_constrained_packed_array. Set the field
2137 bitsize on a series of packed arrays. Returns the number of
2138 elements in TYPE. */
2139
2140 static LONGEST
2141 recursively_update_array_bitsize (struct type *type)
2142 {
2143 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2144
2145 LONGEST low, high;
2146 if (!get_discrete_bounds (type->index_type (), &low, &high)
2147 || low > high)
2148 return 0;
2149 LONGEST our_len = high - low + 1;
2150
2151 struct type *elt_type = TYPE_TARGET_TYPE (type);
2152 if (elt_type->code () == TYPE_CODE_ARRAY)
2153 {
2154 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2155 LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2156 TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2157
2158 TYPE_LENGTH (type) = ((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2159 / HOST_CHAR_BIT);
2160 }
2161
2162 return our_len;
2163 }
2164
2165 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2166 array, returns a simple array that denotes that array. Its type is a
2167 standard GDB array type except that the BITSIZEs of the array
2168 target types are set to the number of bits in each element, and the
2169 type length is set appropriately. */
2170
2171 static struct value *
2172 decode_constrained_packed_array (struct value *arr)
2173 {
2174 struct type *type;
2175
2176 /* If our value is a pointer, then dereference it. Likewise if
2177 the value is a reference. Make sure that this operation does not
2178 cause the target type to be fixed, as this would indirectly cause
2179 this array to be decoded. The rest of the routine assumes that
2180 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2181 and "value_ind" routines to perform the dereferencing, as opposed
2182 to using "ada_coerce_ref" or "ada_value_ind". */
2183 arr = coerce_ref (arr);
2184 if (ada_check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2185 arr = value_ind (arr);
2186
2187 type = decode_constrained_packed_array_type (value_type (arr));
2188 if (type == NULL)
2189 {
2190 error (_("can't unpack array"));
2191 return NULL;
2192 }
2193
2194 /* Decoding the packed array type could not correctly set the field
2195 bitsizes for any dimension except the innermost, because the
2196 bounds may be variable and were not passed to that function. So,
2197 we further resolve the array bounds here and then update the
2198 sizes. */
2199 const gdb_byte *valaddr = value_contents_for_printing (arr);
2200 CORE_ADDR address = value_address (arr);
2201 gdb::array_view<const gdb_byte> view
2202 = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
2203 type = resolve_dynamic_type (type, view, address);
2204 recursively_update_array_bitsize (type);
2205
2206 if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2207 && ada_is_modular_type (value_type (arr)))
2208 {
2209 /* This is a (right-justified) modular type representing a packed
2210 array with no wrapper. In order to interpret the value through
2211 the (left-justified) packed array type we just built, we must
2212 first left-justify it. */
2213 int bit_size, bit_pos;
2214 ULONGEST mod;
2215
2216 mod = ada_modulus (value_type (arr)) - 1;
2217 bit_size = 0;
2218 while (mod > 0)
2219 {
2220 bit_size += 1;
2221 mod >>= 1;
2222 }
2223 bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2224 arr = ada_value_primitive_packed_val (arr, NULL,
2225 bit_pos / HOST_CHAR_BIT,
2226 bit_pos % HOST_CHAR_BIT,
2227 bit_size,
2228 type);
2229 }
2230
2231 return coerce_unspec_val_to_type (arr, type);
2232 }
2233
2234
2235 /* The value of the element of packed array ARR at the ARITY indices
2236 given in IND. ARR must be a simple array. */
2237
2238 static struct value *
2239 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2240 {
2241 int i;
2242 int bits, elt_off, bit_off;
2243 long elt_total_bit_offset;
2244 struct type *elt_type;
2245 struct value *v;
2246
2247 bits = 0;
2248 elt_total_bit_offset = 0;
2249 elt_type = ada_check_typedef (value_type (arr));
2250 for (i = 0; i < arity; i += 1)
2251 {
2252 if (elt_type->code () != TYPE_CODE_ARRAY
2253 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2254 error
2255 (_("attempt to do packed indexing of "
2256 "something other than a packed array"));
2257 else
2258 {
2259 struct type *range_type = elt_type->index_type ();
2260 LONGEST lowerbound, upperbound;
2261 LONGEST idx;
2262
2263 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2264 {
2265 lim_warning (_("don't know bounds of array"));
2266 lowerbound = upperbound = 0;
2267 }
2268
2269 idx = pos_atr (ind[i]);
2270 if (idx < lowerbound || idx > upperbound)
2271 lim_warning (_("packed array index %ld out of bounds"),
2272 (long) idx);
2273 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2274 elt_total_bit_offset += (idx - lowerbound) * bits;
2275 elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2276 }
2277 }
2278 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2279 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2280
2281 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2282 bits, elt_type);
2283 return v;
2284 }
2285
2286 /* Non-zero iff TYPE includes negative integer values. */
2287
2288 static int
2289 has_negatives (struct type *type)
2290 {
2291 switch (type->code ())
2292 {
2293 default:
2294 return 0;
2295 case TYPE_CODE_INT:
2296 return !type->is_unsigned ();
2297 case TYPE_CODE_RANGE:
2298 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2299 }
2300 }
2301
2302 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2303 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2304 the unpacked buffer.
2305
2306 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2307 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2308
2309 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2310 zero otherwise.
2311
2312 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2313
2314 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2315
2316 static void
2317 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2318 gdb_byte *unpacked, int unpacked_len,
2319 int is_big_endian, int is_signed_type,
2320 int is_scalar)
2321 {
2322 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2323 int src_idx; /* Index into the source area */
2324 int src_bytes_left; /* Number of source bytes left to process. */
2325 int srcBitsLeft; /* Number of source bits left to move */
2326 int unusedLS; /* Number of bits in next significant
2327 byte of source that are unused */
2328
2329 int unpacked_idx; /* Index into the unpacked buffer */
2330 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2331
2332 unsigned long accum; /* Staging area for bits being transferred */
2333 int accumSize; /* Number of meaningful bits in accum */
2334 unsigned char sign;
2335
2336 /* Transmit bytes from least to most significant; delta is the direction
2337 the indices move. */
2338 int delta = is_big_endian ? -1 : 1;
2339
2340 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2341 bits from SRC. .*/
2342 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2343 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2344 bit_size, unpacked_len);
2345
2346 srcBitsLeft = bit_size;
2347 src_bytes_left = src_len;
2348 unpacked_bytes_left = unpacked_len;
2349 sign = 0;
2350
2351 if (is_big_endian)
2352 {
2353 src_idx = src_len - 1;
2354 if (is_signed_type
2355 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2356 sign = ~0;
2357
2358 unusedLS =
2359 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2360 % HOST_CHAR_BIT;
2361
2362 if (is_scalar)
2363 {
2364 accumSize = 0;
2365 unpacked_idx = unpacked_len - 1;
2366 }
2367 else
2368 {
2369 /* Non-scalar values must be aligned at a byte boundary... */
2370 accumSize =
2371 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2372 /* ... And are placed at the beginning (most-significant) bytes
2373 of the target. */
2374 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2375 unpacked_bytes_left = unpacked_idx + 1;
2376 }
2377 }
2378 else
2379 {
2380 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2381
2382 src_idx = unpacked_idx = 0;
2383 unusedLS = bit_offset;
2384 accumSize = 0;
2385
2386 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2387 sign = ~0;
2388 }
2389
2390 accum = 0;
2391 while (src_bytes_left > 0)
2392 {
2393 /* Mask for removing bits of the next source byte that are not
2394 part of the value. */
2395 unsigned int unusedMSMask =
2396 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2397 1;
2398 /* Sign-extend bits for this byte. */
2399 unsigned int signMask = sign & ~unusedMSMask;
2400
2401 accum |=
2402 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2403 accumSize += HOST_CHAR_BIT - unusedLS;
2404 if (accumSize >= HOST_CHAR_BIT)
2405 {
2406 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2407 accumSize -= HOST_CHAR_BIT;
2408 accum >>= HOST_CHAR_BIT;
2409 unpacked_bytes_left -= 1;
2410 unpacked_idx += delta;
2411 }
2412 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2413 unusedLS = 0;
2414 src_bytes_left -= 1;
2415 src_idx += delta;
2416 }
2417 while (unpacked_bytes_left > 0)
2418 {
2419 accum |= sign << accumSize;
2420 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2421 accumSize -= HOST_CHAR_BIT;
2422 if (accumSize < 0)
2423 accumSize = 0;
2424 accum >>= HOST_CHAR_BIT;
2425 unpacked_bytes_left -= 1;
2426 unpacked_idx += delta;
2427 }
2428 }
2429
2430 /* Create a new value of type TYPE from the contents of OBJ starting
2431 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2432 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2433 assigning through the result will set the field fetched from.
2434 VALADDR is ignored unless OBJ is NULL, in which case,
2435 VALADDR+OFFSET must address the start of storage containing the
2436 packed value. The value returned in this case is never an lval.
2437 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2438
2439 struct value *
2440 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2441 long offset, int bit_offset, int bit_size,
2442 struct type *type)
2443 {
2444 struct value *v;
2445 const gdb_byte *src; /* First byte containing data to unpack */
2446 gdb_byte *unpacked;
2447 const int is_scalar = is_scalar_type (type);
2448 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2449 gdb::byte_vector staging;
2450
2451 type = ada_check_typedef (type);
2452
2453 if (obj == NULL)
2454 src = valaddr + offset;
2455 else
2456 src = value_contents (obj) + offset;
2457
2458 if (is_dynamic_type (type))
2459 {
2460 /* The length of TYPE might by dynamic, so we need to resolve
2461 TYPE in order to know its actual size, which we then use
2462 to create the contents buffer of the value we return.
2463 The difficulty is that the data containing our object is
2464 packed, and therefore maybe not at a byte boundary. So, what
2465 we do, is unpack the data into a byte-aligned buffer, and then
2466 use that buffer as our object's value for resolving the type. */
2467 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2468 staging.resize (staging_len);
2469
2470 ada_unpack_from_contents (src, bit_offset, bit_size,
2471 staging.data (), staging.size (),
2472 is_big_endian, has_negatives (type),
2473 is_scalar);
2474 type = resolve_dynamic_type (type, staging, 0);
2475 if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2476 {
2477 /* This happens when the length of the object is dynamic,
2478 and is actually smaller than the space reserved for it.
2479 For instance, in an array of variant records, the bit_size
2480 we're given is the array stride, which is constant and
2481 normally equal to the maximum size of its element.
2482 But, in reality, each element only actually spans a portion
2483 of that stride. */
2484 bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2485 }
2486 }
2487
2488 if (obj == NULL)
2489 {
2490 v = allocate_value (type);
2491 src = valaddr + offset;
2492 }
2493 else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2494 {
2495 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2496 gdb_byte *buf;
2497
2498 v = value_at (type, value_address (obj) + offset);
2499 buf = (gdb_byte *) alloca (src_len);
2500 read_memory (value_address (v), buf, src_len);
2501 src = buf;
2502 }
2503 else
2504 {
2505 v = allocate_value (type);
2506 src = value_contents (obj) + offset;
2507 }
2508
2509 if (obj != NULL)
2510 {
2511 long new_offset = offset;
2512
2513 set_value_component_location (v, obj);
2514 set_value_bitpos (v, bit_offset + value_bitpos (obj));
2515 set_value_bitsize (v, bit_size);
2516 if (value_bitpos (v) >= HOST_CHAR_BIT)
2517 {
2518 ++new_offset;
2519 set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2520 }
2521 set_value_offset (v, new_offset);
2522
2523 /* Also set the parent value. This is needed when trying to
2524 assign a new value (in inferior memory). */
2525 set_value_parent (v, obj);
2526 }
2527 else
2528 set_value_bitsize (v, bit_size);
2529 unpacked = value_contents_writeable (v);
2530
2531 if (bit_size == 0)
2532 {
2533 memset (unpacked, 0, TYPE_LENGTH (type));
2534 return v;
2535 }
2536
2537 if (staging.size () == TYPE_LENGTH (type))
2538 {
2539 /* Small short-cut: If we've unpacked the data into a buffer
2540 of the same size as TYPE's length, then we can reuse that,
2541 instead of doing the unpacking again. */
2542 memcpy (unpacked, staging.data (), staging.size ());
2543 }
2544 else
2545 ada_unpack_from_contents (src, bit_offset, bit_size,
2546 unpacked, TYPE_LENGTH (type),
2547 is_big_endian, has_negatives (type), is_scalar);
2548
2549 return v;
2550 }
2551
2552 /* Store the contents of FROMVAL into the location of TOVAL.
2553 Return a new value with the location of TOVAL and contents of
2554 FROMVAL. Handles assignment into packed fields that have
2555 floating-point or non-scalar types. */
2556
2557 static struct value *
2558 ada_value_assign (struct value *toval, struct value *fromval)
2559 {
2560 struct type *type = value_type (toval);
2561 int bits = value_bitsize (toval);
2562
2563 toval = ada_coerce_ref (toval);
2564 fromval = ada_coerce_ref (fromval);
2565
2566 if (ada_is_direct_array_type (value_type (toval)))
2567 toval = ada_coerce_to_simple_array (toval);
2568 if (ada_is_direct_array_type (value_type (fromval)))
2569 fromval = ada_coerce_to_simple_array (fromval);
2570
2571 if (!deprecated_value_modifiable (toval))
2572 error (_("Left operand of assignment is not a modifiable lvalue."));
2573
2574 if (VALUE_LVAL (toval) == lval_memory
2575 && bits > 0
2576 && (type->code () == TYPE_CODE_FLT
2577 || type->code () == TYPE_CODE_STRUCT))
2578 {
2579 int len = (value_bitpos (toval)
2580 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2581 int from_size;
2582 gdb_byte *buffer = (gdb_byte *) alloca (len);
2583 struct value *val;
2584 CORE_ADDR to_addr = value_address (toval);
2585
2586 if (type->code () == TYPE_CODE_FLT)
2587 fromval = value_cast (type, fromval);
2588
2589 read_memory (to_addr, buffer, len);
2590 from_size = value_bitsize (fromval);
2591 if (from_size == 0)
2592 from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2593
2594 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2595 ULONGEST from_offset = 0;
2596 if (is_big_endian && is_scalar_type (value_type (fromval)))
2597 from_offset = from_size - bits;
2598 copy_bitwise (buffer, value_bitpos (toval),
2599 value_contents (fromval), from_offset,
2600 bits, is_big_endian);
2601 write_memory_with_notification (to_addr, buffer, len);
2602
2603 val = value_copy (toval);
2604 memcpy (value_contents_raw (val), value_contents (fromval),
2605 TYPE_LENGTH (type));
2606 deprecated_set_value_type (val, type);
2607
2608 return val;
2609 }
2610
2611 return value_assign (toval, fromval);
2612 }
2613
2614
2615 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2616 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2617 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2618 COMPONENT, and not the inferior's memory. The current contents
2619 of COMPONENT are ignored.
2620
2621 Although not part of the initial design, this function also works
2622 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2623 had a null address, and COMPONENT had an address which is equal to
2624 its offset inside CONTAINER. */
2625
2626 static void
2627 value_assign_to_component (struct value *container, struct value *component,
2628 struct value *val)
2629 {
2630 LONGEST offset_in_container =
2631 (LONGEST) (value_address (component) - value_address (container));
2632 int bit_offset_in_container =
2633 value_bitpos (component) - value_bitpos (container);
2634 int bits;
2635
2636 val = value_cast (value_type (component), val);
2637
2638 if (value_bitsize (component) == 0)
2639 bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2640 else
2641 bits = value_bitsize (component);
2642
2643 if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2644 {
2645 int src_offset;
2646
2647 if (is_scalar_type (check_typedef (value_type (component))))
2648 src_offset
2649 = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2650 else
2651 src_offset = 0;
2652 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2653 value_bitpos (container) + bit_offset_in_container,
2654 value_contents (val), src_offset, bits, 1);
2655 }
2656 else
2657 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2658 value_bitpos (container) + bit_offset_in_container,
2659 value_contents (val), 0, bits, 0);
2660 }
2661
2662 /* Determine if TYPE is an access to an unconstrained array. */
2663
2664 bool
2665 ada_is_access_to_unconstrained_array (struct type *type)
2666 {
2667 return (type->code () == TYPE_CODE_TYPEDEF
2668 && is_thick_pntr (ada_typedef_target_type (type)));
2669 }
2670
2671 /* The value of the element of array ARR at the ARITY indices given in IND.
2672 ARR may be either a simple array, GNAT array descriptor, or pointer
2673 thereto. */
2674
2675 struct value *
2676 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2677 {
2678 int k;
2679 struct value *elt;
2680 struct type *elt_type;
2681
2682 elt = ada_coerce_to_simple_array (arr);
2683
2684 elt_type = ada_check_typedef (value_type (elt));
2685 if (elt_type->code () == TYPE_CODE_ARRAY
2686 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2687 return value_subscript_packed (elt, arity, ind);
2688
2689 for (k = 0; k < arity; k += 1)
2690 {
2691 struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
2692
2693 if (elt_type->code () != TYPE_CODE_ARRAY)
2694 error (_("too many subscripts (%d expected)"), k);
2695
2696 elt = value_subscript (elt, pos_atr (ind[k]));
2697
2698 if (ada_is_access_to_unconstrained_array (saved_elt_type)
2699 && value_type (elt)->code () != TYPE_CODE_TYPEDEF)
2700 {
2701 /* The element is a typedef to an unconstrained array,
2702 except that the value_subscript call stripped the
2703 typedef layer. The typedef layer is GNAT's way to
2704 specify that the element is, at the source level, an
2705 access to the unconstrained array, rather than the
2706 unconstrained array. So, we need to restore that
2707 typedef layer, which we can do by forcing the element's
2708 type back to its original type. Otherwise, the returned
2709 value is going to be printed as the array, rather
2710 than as an access. Another symptom of the same issue
2711 would be that an expression trying to dereference the
2712 element would also be improperly rejected. */
2713 deprecated_set_value_type (elt, saved_elt_type);
2714 }
2715
2716 elt_type = ada_check_typedef (value_type (elt));
2717 }
2718
2719 return elt;
2720 }
2721
2722 /* Assuming ARR is a pointer to a GDB array, the value of the element
2723 of *ARR at the ARITY indices given in IND.
2724 Does not read the entire array into memory.
2725
2726 Note: Unlike what one would expect, this function is used instead of
2727 ada_value_subscript for basically all non-packed array types. The reason
2728 for this is that a side effect of doing our own pointer arithmetics instead
2729 of relying on value_subscript is that there is no implicit typedef peeling.
2730 This is important for arrays of array accesses, where it allows us to
2731 preserve the fact that the array's element is an array access, where the
2732 access part os encoded in a typedef layer. */
2733
2734 static struct value *
2735 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
2736 {
2737 int k;
2738 struct value *array_ind = ada_value_ind (arr);
2739 struct type *type
2740 = check_typedef (value_enclosing_type (array_ind));
2741
2742 if (type->code () == TYPE_CODE_ARRAY
2743 && TYPE_FIELD_BITSIZE (type, 0) > 0)
2744 return value_subscript_packed (array_ind, arity, ind);
2745
2746 for (k = 0; k < arity; k += 1)
2747 {
2748 LONGEST lwb, upb;
2749
2750 if (type->code () != TYPE_CODE_ARRAY)
2751 error (_("too many subscripts (%d expected)"), k);
2752 arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2753 value_copy (arr));
2754 get_discrete_bounds (type->index_type (), &lwb, &upb);
2755 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
2756 type = TYPE_TARGET_TYPE (type);
2757 }
2758
2759 return value_ind (arr);
2760 }
2761
2762 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2763 actual type of ARRAY_PTR is ignored), returns the Ada slice of
2764 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
2765 this array is LOW, as per Ada rules. */
2766 static struct value *
2767 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2768 int low, int high)
2769 {
2770 struct type *type0 = ada_check_typedef (type);
2771 struct type *base_index_type = TYPE_TARGET_TYPE (type0->index_type ());
2772 struct type *index_type
2773 = create_static_range_type (NULL, base_index_type, low, high);
2774 struct type *slice_type = create_array_type_with_stride
2775 (NULL, TYPE_TARGET_TYPE (type0), index_type,
2776 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
2777 TYPE_FIELD_BITSIZE (type0, 0));
2778 int base_low = ada_discrete_type_low_bound (type0->index_type ());
2779 gdb::optional<LONGEST> base_low_pos, low_pos;
2780 CORE_ADDR base;
2781
2782 low_pos = discrete_position (base_index_type, low);
2783 base_low_pos = discrete_position (base_index_type, base_low);
2784
2785 if (!low_pos.has_value () || !base_low_pos.has_value ())
2786 {
2787 warning (_("unable to get positions in slice, use bounds instead"));
2788 low_pos = low;
2789 base_low_pos = base_low;
2790 }
2791
2792 ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
2793 if (stride == 0)
2794 stride = TYPE_LENGTH (TYPE_TARGET_TYPE (type0));
2795
2796 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
2797 return value_at_lazy (slice_type, base);
2798 }
2799
2800
2801 static struct value *
2802 ada_value_slice (struct value *array, int low, int high)
2803 {
2804 struct type *type = ada_check_typedef (value_type (array));
2805 struct type *base_index_type = TYPE_TARGET_TYPE (type->index_type ());
2806 struct type *index_type
2807 = create_static_range_type (NULL, type->index_type (), low, high);
2808 struct type *slice_type = create_array_type_with_stride
2809 (NULL, TYPE_TARGET_TYPE (type), index_type,
2810 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
2811 TYPE_FIELD_BITSIZE (type, 0));
2812 gdb::optional<LONGEST> low_pos, high_pos;
2813
2814
2815 low_pos = discrete_position (base_index_type, low);
2816 high_pos = discrete_position (base_index_type, high);
2817
2818 if (!low_pos.has_value () || !high_pos.has_value ())
2819 {
2820 warning (_("unable to get positions in slice, use bounds instead"));
2821 low_pos = low;
2822 high_pos = high;
2823 }
2824
2825 return value_cast (slice_type,
2826 value_slice (array, low, *high_pos - *low_pos + 1));
2827 }
2828
2829 /* If type is a record type in the form of a standard GNAT array
2830 descriptor, returns the number of dimensions for type. If arr is a
2831 simple array, returns the number of "array of"s that prefix its
2832 type designation. Otherwise, returns 0. */
2833
2834 int
2835 ada_array_arity (struct type *type)
2836 {
2837 int arity;
2838
2839 if (type == NULL)
2840 return 0;
2841
2842 type = desc_base_type (type);
2843
2844 arity = 0;
2845 if (type->code () == TYPE_CODE_STRUCT)
2846 return desc_arity (desc_bounds_type (type));
2847 else
2848 while (type->code () == TYPE_CODE_ARRAY)
2849 {
2850 arity += 1;
2851 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2852 }
2853
2854 return arity;
2855 }
2856
2857 /* If TYPE is a record type in the form of a standard GNAT array
2858 descriptor or a simple array type, returns the element type for
2859 TYPE after indexing by NINDICES indices, or by all indices if
2860 NINDICES is -1. Otherwise, returns NULL. */
2861
2862 struct type *
2863 ada_array_element_type (struct type *type, int nindices)
2864 {
2865 type = desc_base_type (type);
2866
2867 if (type->code () == TYPE_CODE_STRUCT)
2868 {
2869 int k;
2870 struct type *p_array_type;
2871
2872 p_array_type = desc_data_target_type (type);
2873
2874 k = ada_array_arity (type);
2875 if (k == 0)
2876 return NULL;
2877
2878 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
2879 if (nindices >= 0 && k > nindices)
2880 k = nindices;
2881 while (k > 0 && p_array_type != NULL)
2882 {
2883 p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2884 k -= 1;
2885 }
2886 return p_array_type;
2887 }
2888 else if (type->code () == TYPE_CODE_ARRAY)
2889 {
2890 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
2891 {
2892 type = TYPE_TARGET_TYPE (type);
2893 nindices -= 1;
2894 }
2895 return type;
2896 }
2897
2898 return NULL;
2899 }
2900
2901 /* The type of nth index in arrays of given type (n numbering from 1).
2902 Does not examine memory. Throws an error if N is invalid or TYPE
2903 is not an array type. NAME is the name of the Ada attribute being
2904 evaluated ('range, 'first, 'last, or 'length); it is used in building
2905 the error message. */
2906
2907 static struct type *
2908 ada_index_type (struct type *type, int n, const char *name)
2909 {
2910 struct type *result_type;
2911
2912 type = desc_base_type (type);
2913
2914 if (n < 0 || n > ada_array_arity (type))
2915 error (_("invalid dimension number to '%s"), name);
2916
2917 if (ada_is_simple_array_type (type))
2918 {
2919 int i;
2920
2921 for (i = 1; i < n; i += 1)
2922 type = TYPE_TARGET_TYPE (type);
2923 result_type = TYPE_TARGET_TYPE (type->index_type ());
2924 /* FIXME: The stabs type r(0,0);bound;bound in an array type
2925 has a target type of TYPE_CODE_UNDEF. We compensate here, but
2926 perhaps stabsread.c would make more sense. */
2927 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
2928 result_type = NULL;
2929 }
2930 else
2931 {
2932 result_type = desc_index_type (desc_bounds_type (type), n);
2933 if (result_type == NULL)
2934 error (_("attempt to take bound of something that is not an array"));
2935 }
2936
2937 return result_type;
2938 }
2939
2940 /* Given that arr is an array type, returns the lower bound of the
2941 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2942 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
2943 array-descriptor type. It works for other arrays with bounds supplied
2944 by run-time quantities other than discriminants. */
2945
2946 static LONGEST
2947 ada_array_bound_from_type (struct type *arr_type, int n, int which)
2948 {
2949 struct type *type, *index_type_desc, *index_type;
2950 int i;
2951
2952 gdb_assert (which == 0 || which == 1);
2953
2954 if (ada_is_constrained_packed_array_type (arr_type))
2955 arr_type = decode_constrained_packed_array_type (arr_type);
2956
2957 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2958 return (LONGEST) - which;
2959
2960 if (arr_type->code () == TYPE_CODE_PTR)
2961 type = TYPE_TARGET_TYPE (arr_type);
2962 else
2963 type = arr_type;
2964
2965 if (type->is_fixed_instance ())
2966 {
2967 /* The array has already been fixed, so we do not need to
2968 check the parallel ___XA type again. That encoding has
2969 already been applied, so ignore it now. */
2970 index_type_desc = NULL;
2971 }
2972 else
2973 {
2974 index_type_desc = ada_find_parallel_type (type, "___XA");
2975 ada_fixup_array_indexes_type (index_type_desc);
2976 }
2977
2978 if (index_type_desc != NULL)
2979 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
2980 NULL);
2981 else
2982 {
2983 struct type *elt_type = check_typedef (type);
2984
2985 for (i = 1; i < n; i++)
2986 elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
2987
2988 index_type = elt_type->index_type ();
2989 }
2990
2991 return
2992 (LONGEST) (which == 0
2993 ? ada_discrete_type_low_bound (index_type)
2994 : ada_discrete_type_high_bound (index_type));
2995 }
2996
2997 /* Given that arr is an array value, returns the lower bound of the
2998 nth index (numbering from 1) if WHICH is 0, and the upper bound if
2999 WHICH is 1. This routine will also work for arrays with bounds
3000 supplied by run-time quantities other than discriminants. */
3001
3002 static LONGEST
3003 ada_array_bound (struct value *arr, int n, int which)
3004 {
3005 struct type *arr_type;
3006
3007 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3008 arr = value_ind (arr);
3009 arr_type = value_enclosing_type (arr);
3010
3011 if (ada_is_constrained_packed_array_type (arr_type))
3012 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3013 else if (ada_is_simple_array_type (arr_type))
3014 return ada_array_bound_from_type (arr_type, n, which);
3015 else
3016 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3017 }
3018
3019 /* Given that arr is an array value, returns the length of the
3020 nth index. This routine will also work for arrays with bounds
3021 supplied by run-time quantities other than discriminants.
3022 Does not work for arrays indexed by enumeration types with representation
3023 clauses at the moment. */
3024
3025 static LONGEST
3026 ada_array_length (struct value *arr, int n)
3027 {
3028 struct type *arr_type, *index_type;
3029 int low, high;
3030
3031 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3032 arr = value_ind (arr);
3033 arr_type = value_enclosing_type (arr);
3034
3035 if (ada_is_constrained_packed_array_type (arr_type))
3036 return ada_array_length (decode_constrained_packed_array (arr), n);
3037
3038 if (ada_is_simple_array_type (arr_type))
3039 {
3040 low = ada_array_bound_from_type (arr_type, n, 0);
3041 high = ada_array_bound_from_type (arr_type, n, 1);
3042 }
3043 else
3044 {
3045 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3046 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3047 }
3048
3049 arr_type = check_typedef (arr_type);
3050 index_type = ada_index_type (arr_type, n, "length");
3051 if (index_type != NULL)
3052 {
3053 struct type *base_type;
3054 if (index_type->code () == TYPE_CODE_RANGE)
3055 base_type = TYPE_TARGET_TYPE (index_type);
3056 else
3057 base_type = index_type;
3058
3059 low = pos_atr (value_from_longest (base_type, low));
3060 high = pos_atr (value_from_longest (base_type, high));
3061 }
3062 return high - low + 1;
3063 }
3064
3065 /* An array whose type is that of ARR_TYPE (an array type), with
3066 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3067 less than LOW, then LOW-1 is used. */
3068
3069 static struct value *
3070 empty_array (struct type *arr_type, int low, int high)
3071 {
3072 struct type *arr_type0 = ada_check_typedef (arr_type);
3073 struct type *index_type
3074 = create_static_range_type
3075 (NULL, TYPE_TARGET_TYPE (arr_type0->index_type ()), low,
3076 high < low ? low - 1 : high);
3077 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3078
3079 return allocate_value (create_array_type (NULL, elt_type, index_type));
3080 }
3081 \f
3082
3083 /* Name resolution */
3084
3085 /* The "decoded" name for the user-definable Ada operator corresponding
3086 to OP. */
3087
3088 static const char *
3089 ada_decoded_op_name (enum exp_opcode op)
3090 {
3091 int i;
3092
3093 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3094 {
3095 if (ada_opname_table[i].op == op)
3096 return ada_opname_table[i].decoded;
3097 }
3098 error (_("Could not find operator name for opcode"));
3099 }
3100
3101 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3102 in a listing of choices during disambiguation (see sort_choices, below).
3103 The idea is that overloadings of a subprogram name from the
3104 same package should sort in their source order. We settle for ordering
3105 such symbols by their trailing number (__N or $N). */
3106
3107 static int
3108 encoded_ordered_before (const char *N0, const char *N1)
3109 {
3110 if (N1 == NULL)
3111 return 0;
3112 else if (N0 == NULL)
3113 return 1;
3114 else
3115 {
3116 int k0, k1;
3117
3118 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3119 ;
3120 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3121 ;
3122 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3123 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3124 {
3125 int n0, n1;
3126
3127 n0 = k0;
3128 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3129 n0 -= 1;
3130 n1 = k1;
3131 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3132 n1 -= 1;
3133 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3134 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3135 }
3136 return (strcmp (N0, N1) < 0);
3137 }
3138 }
3139
3140 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3141 encoded names. */
3142
3143 static void
3144 sort_choices (struct block_symbol syms[], int nsyms)
3145 {
3146 int i;
3147
3148 for (i = 1; i < nsyms; i += 1)
3149 {
3150 struct block_symbol sym = syms[i];
3151 int j;
3152
3153 for (j = i - 1; j >= 0; j -= 1)
3154 {
3155 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3156 sym.symbol->linkage_name ()))
3157 break;
3158 syms[j + 1] = syms[j];
3159 }
3160 syms[j + 1] = sym;
3161 }
3162 }
3163
3164 /* Whether GDB should display formals and return types for functions in the
3165 overloads selection menu. */
3166 static bool print_signatures = true;
3167
3168 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3169 all but functions, the signature is just the name of the symbol. For
3170 functions, this is the name of the function, the list of types for formals
3171 and the return type (if any). */
3172
3173 static void
3174 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3175 const struct type_print_options *flags)
3176 {
3177 struct type *type = SYMBOL_TYPE (sym);
3178
3179 fprintf_filtered (stream, "%s", sym->print_name ());
3180 if (!print_signatures
3181 || type == NULL
3182 || type->code () != TYPE_CODE_FUNC)
3183 return;
3184
3185 if (type->num_fields () > 0)
3186 {
3187 int i;
3188
3189 fprintf_filtered (stream, " (");
3190 for (i = 0; i < type->num_fields (); ++i)
3191 {
3192 if (i > 0)
3193 fprintf_filtered (stream, "; ");
3194 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3195 flags);
3196 }
3197 fprintf_filtered (stream, ")");
3198 }
3199 if (TYPE_TARGET_TYPE (type) != NULL
3200 && TYPE_TARGET_TYPE (type)->code () != TYPE_CODE_VOID)
3201 {
3202 fprintf_filtered (stream, " return ");
3203 ada_print_type (TYPE_TARGET_TYPE (type), NULL, stream, -1, 0, flags);
3204 }
3205 }
3206
3207 /* Read and validate a set of numeric choices from the user in the
3208 range 0 .. N_CHOICES-1. Place the results in increasing
3209 order in CHOICES[0 .. N-1], and return N.
3210
3211 The user types choices as a sequence of numbers on one line
3212 separated by blanks, encoding them as follows:
3213
3214 + A choice of 0 means to cancel the selection, throwing an error.
3215 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3216 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3217
3218 The user is not allowed to choose more than MAX_RESULTS values.
3219
3220 ANNOTATION_SUFFIX, if present, is used to annotate the input
3221 prompts (for use with the -f switch). */
3222
3223 static int
3224 get_selections (int *choices, int n_choices, int max_results,
3225 int is_all_choice, const char *annotation_suffix)
3226 {
3227 const char *args;
3228 const char *prompt;
3229 int n_chosen;
3230 int first_choice = is_all_choice ? 2 : 1;
3231
3232 prompt = getenv ("PS2");
3233 if (prompt == NULL)
3234 prompt = "> ";
3235
3236 args = command_line_input (prompt, annotation_suffix);
3237
3238 if (args == NULL)
3239 error_no_arg (_("one or more choice numbers"));
3240
3241 n_chosen = 0;
3242
3243 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3244 order, as given in args. Choices are validated. */
3245 while (1)
3246 {
3247 char *args2;
3248 int choice, j;
3249
3250 args = skip_spaces (args);
3251 if (*args == '\0' && n_chosen == 0)
3252 error_no_arg (_("one or more choice numbers"));
3253 else if (*args == '\0')
3254 break;
3255
3256 choice = strtol (args, &args2, 10);
3257 if (args == args2 || choice < 0
3258 || choice > n_choices + first_choice - 1)
3259 error (_("Argument must be choice number"));
3260 args = args2;
3261
3262 if (choice == 0)
3263 error (_("cancelled"));
3264
3265 if (choice < first_choice)
3266 {
3267 n_chosen = n_choices;
3268 for (j = 0; j < n_choices; j += 1)
3269 choices[j] = j;
3270 break;
3271 }
3272 choice -= first_choice;
3273
3274 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3275 {
3276 }
3277
3278 if (j < 0 || choice != choices[j])
3279 {
3280 int k;
3281
3282 for (k = n_chosen - 1; k > j; k -= 1)
3283 choices[k + 1] = choices[k];
3284 choices[j + 1] = choice;
3285 n_chosen += 1;
3286 }
3287 }
3288
3289 if (n_chosen > max_results)
3290 error (_("Select no more than %d of the above"), max_results);
3291
3292 return n_chosen;
3293 }
3294
3295 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3296 by asking the user (if necessary), returning the number selected,
3297 and setting the first elements of SYMS items. Error if no symbols
3298 selected. */
3299
3300 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3301 to be re-integrated one of these days. */
3302
3303 static int
3304 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3305 {
3306 int i;
3307 int *chosen = XALLOCAVEC (int , nsyms);
3308 int n_chosen;
3309 int first_choice = (max_results == 1) ? 1 : 2;
3310 const char *select_mode = multiple_symbols_select_mode ();
3311
3312 if (max_results < 1)
3313 error (_("Request to select 0 symbols!"));
3314 if (nsyms <= 1)
3315 return nsyms;
3316
3317 if (select_mode == multiple_symbols_cancel)
3318 error (_("\
3319 canceled because the command is ambiguous\n\
3320 See set/show multiple-symbol."));
3321
3322 /* If select_mode is "all", then return all possible symbols.
3323 Only do that if more than one symbol can be selected, of course.
3324 Otherwise, display the menu as usual. */
3325 if (select_mode == multiple_symbols_all && max_results > 1)
3326 return nsyms;
3327
3328 printf_filtered (_("[0] cancel\n"));
3329 if (max_results > 1)
3330 printf_filtered (_("[1] all\n"));
3331
3332 sort_choices (syms, nsyms);
3333
3334 for (i = 0; i < nsyms; i += 1)
3335 {
3336 if (syms[i].symbol == NULL)
3337 continue;
3338
3339 if (SYMBOL_CLASS (syms[i].symbol) == LOC_BLOCK)
3340 {
3341 struct symtab_and_line sal =
3342 find_function_start_sal (syms[i].symbol, 1);
3343
3344 printf_filtered ("[%d] ", i + first_choice);
3345 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3346 &type_print_raw_options);
3347 if (sal.symtab == NULL)
3348 printf_filtered (_(" at %p[<no source file available>%p]:%d\n"),
3349 metadata_style.style ().ptr (), nullptr, sal.line);
3350 else
3351 printf_filtered
3352 (_(" at %ps:%d\n"),
3353 styled_string (file_name_style.style (),
3354 symtab_to_filename_for_display (sal.symtab)),
3355 sal.line);
3356 continue;
3357 }
3358 else
3359 {
3360 int is_enumeral =
3361 (SYMBOL_CLASS (syms[i].symbol) == LOC_CONST
3362 && SYMBOL_TYPE (syms[i].symbol) != NULL
3363 && SYMBOL_TYPE (syms[i].symbol)->code () == TYPE_CODE_ENUM);
3364 struct symtab *symtab = NULL;
3365
3366 if (SYMBOL_OBJFILE_OWNED (syms[i].symbol))
3367 symtab = symbol_symtab (syms[i].symbol);
3368
3369 if (SYMBOL_LINE (syms[i].symbol) != 0 && symtab != NULL)
3370 {
3371 printf_filtered ("[%d] ", i + first_choice);
3372 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3373 &type_print_raw_options);
3374 printf_filtered (_(" at %s:%d\n"),
3375 symtab_to_filename_for_display (symtab),
3376 SYMBOL_LINE (syms[i].symbol));
3377 }
3378 else if (is_enumeral
3379 && SYMBOL_TYPE (syms[i].symbol)->name () != NULL)
3380 {
3381 printf_filtered (("[%d] "), i + first_choice);
3382 ada_print_type (SYMBOL_TYPE (syms[i].symbol), NULL,
3383 gdb_stdout, -1, 0, &type_print_raw_options);
3384 printf_filtered (_("'(%s) (enumeral)\n"),
3385 syms[i].symbol->print_name ());
3386 }
3387 else
3388 {
3389 printf_filtered ("[%d] ", i + first_choice);
3390 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3391 &type_print_raw_options);
3392
3393 if (symtab != NULL)
3394 printf_filtered (is_enumeral
3395 ? _(" in %s (enumeral)\n")
3396 : _(" at %s:?\n"),
3397 symtab_to_filename_for_display (symtab));
3398 else
3399 printf_filtered (is_enumeral
3400 ? _(" (enumeral)\n")
3401 : _(" at ?\n"));
3402 }
3403 }
3404 }
3405
3406 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3407 "overload-choice");
3408
3409 for (i = 0; i < n_chosen; i += 1)
3410 syms[i] = syms[chosen[i]];
3411
3412 return n_chosen;
3413 }
3414
3415 /* See ada-lang.h. */
3416
3417 block_symbol
3418 ada_find_operator_symbol (enum exp_opcode op, int parse_completion,
3419 int nargs, value *argvec[])
3420 {
3421 if (possible_user_operator_p (op, argvec))
3422 {
3423 std::vector<struct block_symbol> candidates
3424 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3425 NULL, VAR_DOMAIN);
3426
3427 int i = ada_resolve_function (candidates, argvec,
3428 nargs, ada_decoded_op_name (op), NULL,
3429 parse_completion);
3430 if (i >= 0)
3431 return candidates[i];
3432 }
3433 return {};
3434 }
3435
3436 /* See ada-lang.h. */
3437
3438 block_symbol
3439 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3440 struct type *context_type,
3441 int parse_completion,
3442 int nargs, value *argvec[],
3443 innermost_block_tracker *tracker)
3444 {
3445 std::vector<struct block_symbol> candidates
3446 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3447
3448 int i;
3449 if (candidates.size () == 1)
3450 i = 0;
3451 else
3452 {
3453 i = ada_resolve_function
3454 (candidates,
3455 argvec, nargs,
3456 sym->linkage_name (),
3457 context_type, parse_completion);
3458 if (i < 0)
3459 error (_("Could not find a match for %s"), sym->print_name ());
3460 }
3461
3462 tracker->update (candidates[i]);
3463 return candidates[i];
3464 }
3465
3466 /* See ada-lang.h. */
3467
3468 block_symbol
3469 ada_resolve_variable (struct symbol *sym, const struct block *block,
3470 struct type *context_type,
3471 int parse_completion,
3472 int deprocedure_p,
3473 innermost_block_tracker *tracker)
3474 {
3475 std::vector<struct block_symbol> candidates
3476 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3477
3478 if (std::any_of (candidates.begin (),
3479 candidates.end (),
3480 [] (block_symbol &bsym)
3481 {
3482 switch (SYMBOL_CLASS (bsym.symbol))
3483 {
3484 case LOC_REGISTER:
3485 case LOC_ARG:
3486 case LOC_REF_ARG:
3487 case LOC_REGPARM_ADDR:
3488 case LOC_LOCAL:
3489 case LOC_COMPUTED:
3490 return true;
3491 default:
3492 return false;
3493 }
3494 }))
3495 {
3496 /* Types tend to get re-introduced locally, so if there
3497 are any local symbols that are not types, first filter
3498 out all types. */
3499 candidates.erase
3500 (std::remove_if
3501 (candidates.begin (),
3502 candidates.end (),
3503 [] (block_symbol &bsym)
3504 {
3505 return SYMBOL_CLASS (bsym.symbol) == LOC_TYPEDEF;
3506 }),
3507 candidates.end ());
3508 }
3509
3510 int i;
3511 if (candidates.empty ())
3512 error (_("No definition found for %s"), sym->print_name ());
3513 else if (candidates.size () == 1)
3514 i = 0;
3515 else if (deprocedure_p && !is_nonfunction (candidates))
3516 {
3517 i = ada_resolve_function
3518 (candidates, NULL, 0,
3519 sym->linkage_name (),
3520 context_type, parse_completion);
3521 if (i < 0)
3522 error (_("Could not find a match for %s"), sym->print_name ());
3523 }
3524 else
3525 {
3526 printf_filtered (_("Multiple matches for %s\n"), sym->print_name ());
3527 user_select_syms (candidates.data (), candidates.size (), 1);
3528 i = 0;
3529 }
3530
3531 tracker->update (candidates[i]);
3532 return candidates[i];
3533 }
3534
3535 /* Resolve the operator of the subexpression beginning at
3536 position *POS of *EXPP. "Resolving" consists of replacing
3537 the symbols that have undefined namespaces in OP_VAR_VALUE nodes
3538 with their resolutions, replacing built-in operators with
3539 function calls to user-defined operators, where appropriate, and,
3540 when DEPROCEDURE_P is non-zero, converting function-valued variables
3541 into parameterless calls. May expand *EXPP. The CONTEXT_TYPE functions
3542 are as in ada_resolve, above. */
3543
3544 static struct value *
3545 resolve_subexp (expression_up *expp, int *pos, int deprocedure_p,
3546 struct type *context_type, int parse_completion,
3547 innermost_block_tracker *tracker)
3548 {
3549 int pc = *pos;
3550 int i;
3551 struct expression *exp; /* Convenience: == *expp. */
3552 enum exp_opcode op = (*expp)->elts[pc].opcode;
3553 struct value **argvec; /* Vector of operand types (alloca'ed). */
3554 int nargs; /* Number of operands. */
3555 int oplen;
3556 /* If we're resolving an expression like ARRAY(ARG...), then we set
3557 this to the type of the array, so we can use the index types as
3558 the expected types for resolution. */
3559 struct type *array_type = nullptr;
3560 /* The arity of ARRAY_TYPE. */
3561 int array_arity = 0;
3562
3563 argvec = NULL;
3564 nargs = 0;
3565 exp = expp->get ();
3566
3567 /* Pass one: resolve operands, saving their types and updating *pos,
3568 if needed. */
3569 switch (op)
3570 {
3571 case OP_FUNCALL:
3572 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3573 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3574 *pos += 7;
3575 else
3576 {
3577 *pos += 3;
3578 struct value *lhs = resolve_subexp (expp, pos, 0, NULL,
3579 parse_completion, tracker);
3580 struct type *lhstype = ada_check_typedef (value_type (lhs));
3581 array_arity = ada_array_arity (lhstype);
3582 if (array_arity > 0)
3583 array_type = lhstype;
3584 }
3585 nargs = longest_to_int (exp->elts[pc + 1].longconst);
3586 break;
3587
3588 case UNOP_ADDR:
3589 *pos += 1;
3590 resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3591 break;
3592
3593 case UNOP_QUAL:
3594 *pos += 3;
3595 resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type),
3596 parse_completion, tracker);
3597 break;
3598
3599 case OP_ATR_MODULUS:
3600 case OP_ATR_SIZE:
3601 case OP_ATR_TAG:
3602 case OP_ATR_FIRST:
3603 case OP_ATR_LAST:
3604 case OP_ATR_LENGTH:
3605 case OP_ATR_POS:
3606 case OP_ATR_VAL:
3607 case OP_ATR_MIN:
3608 case OP_ATR_MAX:
3609 case TERNOP_IN_RANGE:
3610 case BINOP_IN_BOUNDS:
3611 case UNOP_IN_RANGE:
3612 case OP_AGGREGATE:
3613 case OP_OTHERS:
3614 case OP_CHOICES:
3615 case OP_POSITIONAL:
3616 case OP_DISCRETE_RANGE:
3617 case OP_NAME:
3618 ada_forward_operator_length (exp, pc, &oplen, &nargs);
3619 *pos += oplen;
3620 break;
3621
3622 case BINOP_ASSIGN:
3623 {
3624 struct value *arg1;
3625
3626 *pos += 1;
3627 arg1 = resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3628 if (arg1 == NULL)
3629 resolve_subexp (expp, pos, 1, NULL, parse_completion, tracker);
3630 else
3631 resolve_subexp (expp, pos, 1, value_type (arg1), parse_completion,
3632 tracker);
3633 break;
3634 }
3635
3636 case UNOP_CAST:
3637 *pos += 3;
3638 nargs = 1;
3639 break;
3640
3641 case BINOP_ADD:
3642 case BINOP_SUB:
3643 case BINOP_MUL:
3644 case BINOP_DIV:
3645 case BINOP_REM:
3646 case BINOP_MOD:
3647 case BINOP_EXP:
3648 case BINOP_CONCAT:
3649 case BINOP_LOGICAL_AND:
3650 case BINOP_LOGICAL_OR:
3651 case BINOP_BITWISE_AND:
3652 case BINOP_BITWISE_IOR:
3653 case BINOP_BITWISE_XOR:
3654
3655 case BINOP_EQUAL:
3656 case BINOP_NOTEQUAL:
3657 case BINOP_LESS:
3658 case BINOP_GTR:
3659 case BINOP_LEQ:
3660 case BINOP_GEQ:
3661
3662 case BINOP_REPEAT:
3663 case BINOP_SUBSCRIPT:
3664 case BINOP_COMMA:
3665 *pos += 1;
3666 nargs = 2;
3667 break;
3668
3669 case UNOP_NEG:
3670 case UNOP_PLUS:
3671 case UNOP_LOGICAL_NOT:
3672 case UNOP_ABS:
3673 case UNOP_IND:
3674 *pos += 1;
3675 nargs = 1;
3676 break;
3677
3678 case OP_LONG:
3679 case OP_FLOAT:
3680 case OP_VAR_VALUE:
3681 case OP_VAR_MSYM_VALUE:
3682 *pos += 4;
3683 break;
3684
3685 case OP_TYPE:
3686 case OP_BOOL:
3687 case OP_LAST:
3688 case OP_INTERNALVAR:
3689 *pos += 3;
3690 break;
3691
3692 case UNOP_MEMVAL:
3693 *pos += 3;
3694 nargs = 1;
3695 break;
3696
3697 case OP_REGISTER:
3698 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3699 break;
3700
3701 case STRUCTOP_STRUCT:
3702 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3703 nargs = 1;
3704 break;
3705
3706 case TERNOP_SLICE:
3707 *pos += 1;
3708 nargs = 3;
3709 break;
3710
3711 case OP_STRING:
3712 break;
3713
3714 default:
3715 error (_("Unexpected operator during name resolution"));
3716 }
3717
3718 argvec = XALLOCAVEC (struct value *, nargs + 1);
3719 for (i = 0; i < nargs; i += 1)
3720 {
3721 struct type *subtype = nullptr;
3722 if (i < array_arity)
3723 subtype = ada_index_type (array_type, i + 1, "array type");
3724 argvec[i] = resolve_subexp (expp, pos, 1, subtype, parse_completion,
3725 tracker);
3726 }
3727 argvec[i] = NULL;
3728 exp = expp->get ();
3729
3730 /* Pass two: perform any resolution on principal operator. */
3731 switch (op)
3732 {
3733 default:
3734 break;
3735
3736 case OP_VAR_VALUE:
3737 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
3738 {
3739 block_symbol resolved
3740 = ada_resolve_variable (exp->elts[pc + 2].symbol,
3741 exp->elts[pc + 1].block,
3742 context_type, parse_completion,
3743 deprocedure_p, tracker);
3744 exp->elts[pc + 1].block = resolved.block;
3745 exp->elts[pc + 2].symbol = resolved.symbol;
3746 }
3747
3748 if (deprocedure_p
3749 && (SYMBOL_TYPE (exp->elts[pc + 2].symbol)->code ()
3750 == TYPE_CODE_FUNC))
3751 {
3752 replace_operator_with_call (expp, pc, 0, 4,
3753 exp->elts[pc + 2].symbol,
3754 exp->elts[pc + 1].block);
3755 exp = expp->get ();
3756 }
3757 break;
3758
3759 case OP_FUNCALL:
3760 {
3761 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3762 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3763 {
3764 block_symbol resolved
3765 = ada_resolve_funcall (exp->elts[pc + 5].symbol,
3766 exp->elts[pc + 4].block,
3767 context_type, parse_completion,
3768 nargs, argvec,
3769 tracker);
3770 exp->elts[pc + 4].block = resolved.block;
3771 exp->elts[pc + 5].symbol = resolved.symbol;
3772 }
3773 }
3774 break;
3775 case BINOP_ADD:
3776 case BINOP_SUB:
3777 case BINOP_MUL:
3778 case BINOP_DIV:
3779 case BINOP_REM:
3780 case BINOP_MOD:
3781 case BINOP_CONCAT:
3782 case BINOP_BITWISE_AND:
3783 case BINOP_BITWISE_IOR:
3784 case BINOP_BITWISE_XOR:
3785 case BINOP_EQUAL:
3786 case BINOP_NOTEQUAL:
3787 case BINOP_LESS:
3788 case BINOP_GTR:
3789 case BINOP_LEQ:
3790 case BINOP_GEQ:
3791 case BINOP_EXP:
3792 case UNOP_NEG:
3793 case UNOP_PLUS:
3794 case UNOP_LOGICAL_NOT:
3795 case UNOP_ABS:
3796 {
3797 block_symbol found = ada_find_operator_symbol (op, parse_completion,
3798 nargs, argvec);
3799 if (found.symbol == nullptr)
3800 break;
3801
3802 replace_operator_with_call (expp, pc, nargs, 1,
3803 found.symbol, found.block);
3804 exp = expp->get ();
3805 }
3806 break;
3807
3808 case OP_TYPE:
3809 case OP_REGISTER:
3810 return NULL;
3811 }
3812
3813 *pos = pc;
3814 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
3815 return evaluate_var_msym_value (EVAL_AVOID_SIDE_EFFECTS,
3816 exp->elts[pc + 1].objfile,
3817 exp->elts[pc + 2].msymbol);
3818 else
3819 return evaluate_subexp_type (exp, pos);
3820 }
3821
3822 /* Return non-zero if formal type FTYPE matches actual type ATYPE. If
3823 MAY_DEREF is non-zero, the formal may be a pointer and the actual
3824 a non-pointer. */
3825 /* The term "match" here is rather loose. The match is heuristic and
3826 liberal. */
3827
3828 static int
3829 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
3830 {
3831 ftype = ada_check_typedef (ftype);
3832 atype = ada_check_typedef (atype);
3833
3834 if (ftype->code () == TYPE_CODE_REF)
3835 ftype = TYPE_TARGET_TYPE (ftype);
3836 if (atype->code () == TYPE_CODE_REF)
3837 atype = TYPE_TARGET_TYPE (atype);
3838
3839 switch (ftype->code ())
3840 {
3841 default:
3842 return ftype->code () == atype->code ();
3843 case TYPE_CODE_PTR:
3844 if (atype->code () == TYPE_CODE_PTR)
3845 return ada_type_match (TYPE_TARGET_TYPE (ftype),
3846 TYPE_TARGET_TYPE (atype), 0);
3847 else
3848 return (may_deref
3849 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
3850 case TYPE_CODE_INT:
3851 case TYPE_CODE_ENUM:
3852 case TYPE_CODE_RANGE:
3853 switch (atype->code ())
3854 {
3855 case TYPE_CODE_INT:
3856 case TYPE_CODE_ENUM:
3857 case TYPE_CODE_RANGE:
3858 return 1;
3859 default:
3860 return 0;
3861 }
3862
3863 case TYPE_CODE_ARRAY:
3864 return (atype->code () == TYPE_CODE_ARRAY
3865 || ada_is_array_descriptor_type (atype));
3866
3867 case TYPE_CODE_STRUCT:
3868 if (ada_is_array_descriptor_type (ftype))
3869 return (atype->code () == TYPE_CODE_ARRAY
3870 || ada_is_array_descriptor_type (atype));
3871 else
3872 return (atype->code () == TYPE_CODE_STRUCT
3873 && !ada_is_array_descriptor_type (atype));
3874
3875 case TYPE_CODE_UNION:
3876 case TYPE_CODE_FLT:
3877 return (atype->code () == ftype->code ());
3878 }
3879 }
3880
3881 /* Return non-zero if the formals of FUNC "sufficiently match" the
3882 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3883 may also be an enumeral, in which case it is treated as a 0-
3884 argument function. */
3885
3886 static int
3887 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3888 {
3889 int i;
3890 struct type *func_type = SYMBOL_TYPE (func);
3891
3892 if (SYMBOL_CLASS (func) == LOC_CONST
3893 && func_type->code () == TYPE_CODE_ENUM)
3894 return (n_actuals == 0);
3895 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3896 return 0;
3897
3898 if (func_type->num_fields () != n_actuals)
3899 return 0;
3900
3901 for (i = 0; i < n_actuals; i += 1)
3902 {
3903 if (actuals[i] == NULL)
3904 return 0;
3905 else
3906 {
3907 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3908 struct type *atype = ada_check_typedef (value_type (actuals[i]));
3909
3910 if (!ada_type_match (ftype, atype, 1))
3911 return 0;
3912 }
3913 }
3914 return 1;
3915 }
3916
3917 /* False iff function type FUNC_TYPE definitely does not produce a value
3918 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
3919 FUNC_TYPE is not a valid function type with a non-null return type
3920 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
3921
3922 static int
3923 return_match (struct type *func_type, struct type *context_type)
3924 {
3925 struct type *return_type;
3926
3927 if (func_type == NULL)
3928 return 1;
3929
3930 if (func_type->code () == TYPE_CODE_FUNC)
3931 return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3932 else
3933 return_type = get_base_type (func_type);
3934 if (return_type == NULL)
3935 return 1;
3936
3937 context_type = get_base_type (context_type);
3938
3939 if (return_type->code () == TYPE_CODE_ENUM)
3940 return context_type == NULL || return_type == context_type;
3941 else if (context_type == NULL)
3942 return return_type->code () != TYPE_CODE_VOID;
3943 else
3944 return return_type->code () == context_type->code ();
3945 }
3946
3947
3948 /* Returns the index in SYMS that contains the symbol for the
3949 function (if any) that matches the types of the NARGS arguments in
3950 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
3951 that returns that type, then eliminate matches that don't. If
3952 CONTEXT_TYPE is void and there is at least one match that does not
3953 return void, eliminate all matches that do.
3954
3955 Asks the user if there is more than one match remaining. Returns -1
3956 if there is no such symbol or none is selected. NAME is used
3957 solely for messages. May re-arrange and modify SYMS in
3958 the process; the index returned is for the modified vector. */
3959
3960 static int
3961 ada_resolve_function (std::vector<struct block_symbol> &syms,
3962 struct value **args, int nargs,
3963 const char *name, struct type *context_type,
3964 int parse_completion)
3965 {
3966 int fallback;
3967 int k;
3968 int m; /* Number of hits */
3969
3970 m = 0;
3971 /* In the first pass of the loop, we only accept functions matching
3972 context_type. If none are found, we add a second pass of the loop
3973 where every function is accepted. */
3974 for (fallback = 0; m == 0 && fallback < 2; fallback++)
3975 {
3976 for (k = 0; k < syms.size (); k += 1)
3977 {
3978 struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].symbol));
3979
3980 if (ada_args_match (syms[k].symbol, args, nargs)
3981 && (fallback || return_match (type, context_type)))
3982 {
3983 syms[m] = syms[k];
3984 m += 1;
3985 }
3986 }
3987 }
3988
3989 /* If we got multiple matches, ask the user which one to use. Don't do this
3990 interactive thing during completion, though, as the purpose of the
3991 completion is providing a list of all possible matches. Prompting the
3992 user to filter it down would be completely unexpected in this case. */
3993 if (m == 0)
3994 return -1;
3995 else if (m > 1 && !parse_completion)
3996 {
3997 printf_filtered (_("Multiple matches for %s\n"), name);
3998 user_select_syms (syms.data (), m, 1);
3999 return 0;
4000 }
4001 return 0;
4002 }
4003
4004 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
4005 on the function identified by SYM and BLOCK, and taking NARGS
4006 arguments. Update *EXPP as needed to hold more space. */
4007
4008 static void
4009 replace_operator_with_call (expression_up *expp, int pc, int nargs,
4010 int oplen, struct symbol *sym,
4011 const struct block *block)
4012 {
4013 /* We want to add 6 more elements (3 for funcall, 4 for function
4014 symbol, -OPLEN for operator being replaced) to the
4015 expression. */
4016 struct expression *exp = expp->get ();
4017 int save_nelts = exp->nelts;
4018 int extra_elts = 7 - oplen;
4019 exp->nelts += extra_elts;
4020
4021 if (extra_elts > 0)
4022 exp->resize (exp->nelts);
4023 memmove (exp->elts + pc + 7, exp->elts + pc + oplen,
4024 EXP_ELEM_TO_BYTES (save_nelts - pc - oplen));
4025 if (extra_elts < 0)
4026 exp->resize (exp->nelts);
4027
4028 exp->elts[pc].opcode = exp->elts[pc + 2].opcode = OP_FUNCALL;
4029 exp->elts[pc + 1].longconst = (LONGEST) nargs;
4030
4031 exp->elts[pc + 3].opcode = exp->elts[pc + 6].opcode = OP_VAR_VALUE;
4032 exp->elts[pc + 4].block = block;
4033 exp->elts[pc + 5].symbol = sym;
4034 }
4035
4036 /* Type-class predicates */
4037
4038 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4039 or FLOAT). */
4040
4041 static int
4042 numeric_type_p (struct type *type)
4043 {
4044 if (type == NULL)
4045 return 0;
4046 else
4047 {
4048 switch (type->code ())
4049 {
4050 case TYPE_CODE_INT:
4051 case TYPE_CODE_FLT:
4052 return 1;
4053 case TYPE_CODE_RANGE:
4054 return (type == TYPE_TARGET_TYPE (type)
4055 || numeric_type_p (TYPE_TARGET_TYPE (type)));
4056 default:
4057 return 0;
4058 }
4059 }
4060 }
4061
4062 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4063
4064 static int
4065 integer_type_p (struct type *type)
4066 {
4067 if (type == NULL)
4068 return 0;
4069 else
4070 {
4071 switch (type->code ())
4072 {
4073 case TYPE_CODE_INT:
4074 return 1;
4075 case TYPE_CODE_RANGE:
4076 return (type == TYPE_TARGET_TYPE (type)
4077 || integer_type_p (TYPE_TARGET_TYPE (type)));
4078 default:
4079 return 0;
4080 }
4081 }
4082 }
4083
4084 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4085
4086 static int
4087 scalar_type_p (struct type *type)
4088 {
4089 if (type == NULL)
4090 return 0;
4091 else
4092 {
4093 switch (type->code ())
4094 {
4095 case TYPE_CODE_INT:
4096 case TYPE_CODE_RANGE:
4097 case TYPE_CODE_ENUM:
4098 case TYPE_CODE_FLT:
4099 return 1;
4100 default:
4101 return 0;
4102 }
4103 }
4104 }
4105
4106 /* True iff TYPE is discrete (INT, RANGE, ENUM). */
4107
4108 static int
4109 discrete_type_p (struct type *type)
4110 {
4111 if (type == NULL)
4112 return 0;
4113 else
4114 {
4115 switch (type->code ())
4116 {
4117 case TYPE_CODE_INT:
4118 case TYPE_CODE_RANGE:
4119 case TYPE_CODE_ENUM:
4120 case TYPE_CODE_BOOL:
4121 return 1;
4122 default:
4123 return 0;
4124 }
4125 }
4126 }
4127
4128 /* Returns non-zero if OP with operands in the vector ARGS could be
4129 a user-defined function. Errs on the side of pre-defined operators
4130 (i.e., result 0). */
4131
4132 static int
4133 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4134 {
4135 struct type *type0 =
4136 (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
4137 struct type *type1 =
4138 (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
4139
4140 if (type0 == NULL)
4141 return 0;
4142
4143 switch (op)
4144 {
4145 default:
4146 return 0;
4147
4148 case BINOP_ADD:
4149 case BINOP_SUB:
4150 case BINOP_MUL:
4151 case BINOP_DIV:
4152 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4153
4154 case BINOP_REM:
4155 case BINOP_MOD:
4156 case BINOP_BITWISE_AND:
4157 case BINOP_BITWISE_IOR:
4158 case BINOP_BITWISE_XOR:
4159 return (!(integer_type_p (type0) && integer_type_p (type1)));
4160
4161 case BINOP_EQUAL:
4162 case BINOP_NOTEQUAL:
4163 case BINOP_LESS:
4164 case BINOP_GTR:
4165 case BINOP_LEQ:
4166 case BINOP_GEQ:
4167 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4168
4169 case BINOP_CONCAT:
4170 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4171
4172 case BINOP_EXP:
4173 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4174
4175 case UNOP_NEG:
4176 case UNOP_PLUS:
4177 case UNOP_LOGICAL_NOT:
4178 case UNOP_ABS:
4179 return (!numeric_type_p (type0));
4180
4181 }
4182 }
4183 \f
4184 /* Renaming */
4185
4186 /* NOTES:
4187
4188 1. In the following, we assume that a renaming type's name may
4189 have an ___XD suffix. It would be nice if this went away at some
4190 point.
4191 2. We handle both the (old) purely type-based representation of
4192 renamings and the (new) variable-based encoding. At some point,
4193 it is devoutly to be hoped that the former goes away
4194 (FIXME: hilfinger-2007-07-09).
4195 3. Subprogram renamings are not implemented, although the XRS
4196 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4197
4198 /* If SYM encodes a renaming,
4199
4200 <renaming> renames <renamed entity>,
4201
4202 sets *LEN to the length of the renamed entity's name,
4203 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4204 the string describing the subcomponent selected from the renamed
4205 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4206 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4207 are undefined). Otherwise, returns a value indicating the category
4208 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4209 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4210 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4211 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4212 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4213 may be NULL, in which case they are not assigned.
4214
4215 [Currently, however, GCC does not generate subprogram renamings.] */
4216
4217 enum ada_renaming_category
4218 ada_parse_renaming (struct symbol *sym,
4219 const char **renamed_entity, int *len,
4220 const char **renaming_expr)
4221 {
4222 enum ada_renaming_category kind;
4223 const char *info;
4224 const char *suffix;
4225
4226 if (sym == NULL)
4227 return ADA_NOT_RENAMING;
4228 switch (SYMBOL_CLASS (sym))
4229 {
4230 default:
4231 return ADA_NOT_RENAMING;
4232 case LOC_LOCAL:
4233 case LOC_STATIC:
4234 case LOC_COMPUTED:
4235 case LOC_OPTIMIZED_OUT:
4236 info = strstr (sym->linkage_name (), "___XR");
4237 if (info == NULL)
4238 return ADA_NOT_RENAMING;
4239 switch (info[5])
4240 {
4241 case '_':
4242 kind = ADA_OBJECT_RENAMING;
4243 info += 6;
4244 break;
4245 case 'E':
4246 kind = ADA_EXCEPTION_RENAMING;
4247 info += 7;
4248 break;
4249 case 'P':
4250 kind = ADA_PACKAGE_RENAMING;
4251 info += 7;
4252 break;
4253 case 'S':
4254 kind = ADA_SUBPROGRAM_RENAMING;
4255 info += 7;
4256 break;
4257 default:
4258 return ADA_NOT_RENAMING;
4259 }
4260 }
4261
4262 if (renamed_entity != NULL)
4263 *renamed_entity = info;
4264 suffix = strstr (info, "___XE");
4265 if (suffix == NULL || suffix == info)
4266 return ADA_NOT_RENAMING;
4267 if (len != NULL)
4268 *len = strlen (info) - strlen (suffix);
4269 suffix += 5;
4270 if (renaming_expr != NULL)
4271 *renaming_expr = suffix;
4272 return kind;
4273 }
4274
4275 /* Compute the value of the given RENAMING_SYM, which is expected to
4276 be a symbol encoding a renaming expression. BLOCK is the block
4277 used to evaluate the renaming. */
4278
4279 static struct value *
4280 ada_read_renaming_var_value (struct symbol *renaming_sym,
4281 const struct block *block)
4282 {
4283 const char *sym_name;
4284
4285 sym_name = renaming_sym->linkage_name ();
4286 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4287 return evaluate_expression (expr.get ());
4288 }
4289 \f
4290
4291 /* Evaluation: Function Calls */
4292
4293 /* Return an lvalue containing the value VAL. This is the identity on
4294 lvalues, and otherwise has the side-effect of allocating memory
4295 in the inferior where a copy of the value contents is copied. */
4296
4297 static struct value *
4298 ensure_lval (struct value *val)
4299 {
4300 if (VALUE_LVAL (val) == not_lval
4301 || VALUE_LVAL (val) == lval_internalvar)
4302 {
4303 int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4304 const CORE_ADDR addr =
4305 value_as_long (value_allocate_space_in_inferior (len));
4306
4307 VALUE_LVAL (val) = lval_memory;
4308 set_value_address (val, addr);
4309 write_memory (addr, value_contents (val), len);
4310 }
4311
4312 return val;
4313 }
4314
4315 /* Given ARG, a value of type (pointer or reference to a)*
4316 structure/union, extract the component named NAME from the ultimate
4317 target structure/union and return it as a value with its
4318 appropriate type.
4319
4320 The routine searches for NAME among all members of the structure itself
4321 and (recursively) among all members of any wrapper members
4322 (e.g., '_parent').
4323
4324 If NO_ERR, then simply return NULL in case of error, rather than
4325 calling error. */
4326
4327 static struct value *
4328 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4329 {
4330 struct type *t, *t1;
4331 struct value *v;
4332 int check_tag;
4333
4334 v = NULL;
4335 t1 = t = ada_check_typedef (value_type (arg));
4336 if (t->code () == TYPE_CODE_REF)
4337 {
4338 t1 = TYPE_TARGET_TYPE (t);
4339 if (t1 == NULL)
4340 goto BadValue;
4341 t1 = ada_check_typedef (t1);
4342 if (t1->code () == TYPE_CODE_PTR)
4343 {
4344 arg = coerce_ref (arg);
4345 t = t1;
4346 }
4347 }
4348
4349 while (t->code () == TYPE_CODE_PTR)
4350 {
4351 t1 = TYPE_TARGET_TYPE (t);
4352 if (t1 == NULL)
4353 goto BadValue;
4354 t1 = ada_check_typedef (t1);
4355 if (t1->code () == TYPE_CODE_PTR)
4356 {
4357 arg = value_ind (arg);
4358 t = t1;
4359 }
4360 else
4361 break;
4362 }
4363
4364 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4365 goto BadValue;
4366
4367 if (t1 == t)
4368 v = ada_search_struct_field (name, arg, 0, t);
4369 else
4370 {
4371 int bit_offset, bit_size, byte_offset;
4372 struct type *field_type;
4373 CORE_ADDR address;
4374
4375 if (t->code () == TYPE_CODE_PTR)
4376 address = value_address (ada_value_ind (arg));
4377 else
4378 address = value_address (ada_coerce_ref (arg));
4379
4380 /* Check to see if this is a tagged type. We also need to handle
4381 the case where the type is a reference to a tagged type, but
4382 we have to be careful to exclude pointers to tagged types.
4383 The latter should be shown as usual (as a pointer), whereas
4384 a reference should mostly be transparent to the user. */
4385
4386 if (ada_is_tagged_type (t1, 0)
4387 || (t1->code () == TYPE_CODE_REF
4388 && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
4389 {
4390 /* We first try to find the searched field in the current type.
4391 If not found then let's look in the fixed type. */
4392
4393 if (!find_struct_field (name, t1, 0,
4394 &field_type, &byte_offset, &bit_offset,
4395 &bit_size, NULL))
4396 check_tag = 1;
4397 else
4398 check_tag = 0;
4399 }
4400 else
4401 check_tag = 0;
4402
4403 /* Convert to fixed type in all cases, so that we have proper
4404 offsets to each field in unconstrained record types. */
4405 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4406 address, NULL, check_tag);
4407
4408 /* Resolve the dynamic type as well. */
4409 arg = value_from_contents_and_address (t1, nullptr, address);
4410 t1 = value_type (arg);
4411
4412 if (find_struct_field (name, t1, 0,
4413 &field_type, &byte_offset, &bit_offset,
4414 &bit_size, NULL))
4415 {
4416 if (bit_size != 0)
4417 {
4418 if (t->code () == TYPE_CODE_REF)
4419 arg = ada_coerce_ref (arg);
4420 else
4421 arg = ada_value_ind (arg);
4422 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4423 bit_offset, bit_size,
4424 field_type);
4425 }
4426 else
4427 v = value_at_lazy (field_type, address + byte_offset);
4428 }
4429 }
4430
4431 if (v != NULL || no_err)
4432 return v;
4433 else
4434 error (_("There is no member named %s."), name);
4435
4436 BadValue:
4437 if (no_err)
4438 return NULL;
4439 else
4440 error (_("Attempt to extract a component of "
4441 "a value that is not a record."));
4442 }
4443
4444 /* Return the value ACTUAL, converted to be an appropriate value for a
4445 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4446 allocating any necessary descriptors (fat pointers), or copies of
4447 values not residing in memory, updating it as needed. */
4448
4449 struct value *
4450 ada_convert_actual (struct value *actual, struct type *formal_type0)
4451 {
4452 struct type *actual_type = ada_check_typedef (value_type (actual));
4453 struct type *formal_type = ada_check_typedef (formal_type0);
4454 struct type *formal_target =
4455 formal_type->code () == TYPE_CODE_PTR
4456 ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4457 struct type *actual_target =
4458 actual_type->code () == TYPE_CODE_PTR
4459 ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4460
4461 if (ada_is_array_descriptor_type (formal_target)
4462 && actual_target->code () == TYPE_CODE_ARRAY)
4463 return make_array_descriptor (formal_type, actual);
4464 else if (formal_type->code () == TYPE_CODE_PTR
4465 || formal_type->code () == TYPE_CODE_REF)
4466 {
4467 struct value *result;
4468
4469 if (formal_target->code () == TYPE_CODE_ARRAY
4470 && ada_is_array_descriptor_type (actual_target))
4471 result = desc_data (actual);
4472 else if (formal_type->code () != TYPE_CODE_PTR)
4473 {
4474 if (VALUE_LVAL (actual) != lval_memory)
4475 {
4476 struct value *val;
4477
4478 actual_type = ada_check_typedef (value_type (actual));
4479 val = allocate_value (actual_type);
4480 memcpy ((char *) value_contents_raw (val),
4481 (char *) value_contents (actual),
4482 TYPE_LENGTH (actual_type));
4483 actual = ensure_lval (val);
4484 }
4485 result = value_addr (actual);
4486 }
4487 else
4488 return actual;
4489 return value_cast_pointers (formal_type, result, 0);
4490 }
4491 else if (actual_type->code () == TYPE_CODE_PTR)
4492 return ada_value_ind (actual);
4493 else if (ada_is_aligner_type (formal_type))
4494 {
4495 /* We need to turn this parameter into an aligner type
4496 as well. */
4497 struct value *aligner = allocate_value (formal_type);
4498 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4499
4500 value_assign_to_component (aligner, component, actual);
4501 return aligner;
4502 }
4503
4504 return actual;
4505 }
4506
4507 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4508 type TYPE. This is usually an inefficient no-op except on some targets
4509 (such as AVR) where the representation of a pointer and an address
4510 differs. */
4511
4512 static CORE_ADDR
4513 value_pointer (struct value *value, struct type *type)
4514 {
4515 unsigned len = TYPE_LENGTH (type);
4516 gdb_byte *buf = (gdb_byte *) alloca (len);
4517 CORE_ADDR addr;
4518
4519 addr = value_address (value);
4520 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4521 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4522 return addr;
4523 }
4524
4525
4526 /* Push a descriptor of type TYPE for array value ARR on the stack at
4527 *SP, updating *SP to reflect the new descriptor. Return either
4528 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4529 to-descriptor type rather than a descriptor type), a struct value *
4530 representing a pointer to this descriptor. */
4531
4532 static struct value *
4533 make_array_descriptor (struct type *type, struct value *arr)
4534 {
4535 struct type *bounds_type = desc_bounds_type (type);
4536 struct type *desc_type = desc_base_type (type);
4537 struct value *descriptor = allocate_value (desc_type);
4538 struct value *bounds = allocate_value (bounds_type);
4539 int i;
4540
4541 for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4542 i > 0; i -= 1)
4543 {
4544 modify_field (value_type (bounds), value_contents_writeable (bounds),
4545 ada_array_bound (arr, i, 0),
4546 desc_bound_bitpos (bounds_type, i, 0),
4547 desc_bound_bitsize (bounds_type, i, 0));
4548 modify_field (value_type (bounds), value_contents_writeable (bounds),
4549 ada_array_bound (arr, i, 1),
4550 desc_bound_bitpos (bounds_type, i, 1),
4551 desc_bound_bitsize (bounds_type, i, 1));
4552 }
4553
4554 bounds = ensure_lval (bounds);
4555
4556 modify_field (value_type (descriptor),
4557 value_contents_writeable (descriptor),
4558 value_pointer (ensure_lval (arr),
4559 desc_type->field (0).type ()),
4560 fat_pntr_data_bitpos (desc_type),
4561 fat_pntr_data_bitsize (desc_type));
4562
4563 modify_field (value_type (descriptor),
4564 value_contents_writeable (descriptor),
4565 value_pointer (bounds,
4566 desc_type->field (1).type ()),
4567 fat_pntr_bounds_bitpos (desc_type),
4568 fat_pntr_bounds_bitsize (desc_type));
4569
4570 descriptor = ensure_lval (descriptor);
4571
4572 if (type->code () == TYPE_CODE_PTR)
4573 return value_addr (descriptor);
4574 else
4575 return descriptor;
4576 }
4577 \f
4578 /* Symbol Cache Module */
4579
4580 /* Performance measurements made as of 2010-01-15 indicate that
4581 this cache does bring some noticeable improvements. Depending
4582 on the type of entity being printed, the cache can make it as much
4583 as an order of magnitude faster than without it.
4584
4585 The descriptive type DWARF extension has significantly reduced
4586 the need for this cache, at least when DWARF is being used. However,
4587 even in this case, some expensive name-based symbol searches are still
4588 sometimes necessary - to find an XVZ variable, mostly. */
4589
4590 /* Return the symbol cache associated to the given program space PSPACE.
4591 If not allocated for this PSPACE yet, allocate and initialize one. */
4592
4593 static struct ada_symbol_cache *
4594 ada_get_symbol_cache (struct program_space *pspace)
4595 {
4596 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4597
4598 if (pspace_data->sym_cache == nullptr)
4599 pspace_data->sym_cache.reset (new ada_symbol_cache);
4600
4601 return pspace_data->sym_cache.get ();
4602 }
4603
4604 /* Clear all entries from the symbol cache. */
4605
4606 static void
4607 ada_clear_symbol_cache ()
4608 {
4609 struct ada_pspace_data *pspace_data
4610 = get_ada_pspace_data (current_program_space);
4611
4612 if (pspace_data->sym_cache != nullptr)
4613 pspace_data->sym_cache.reset ();
4614 }
4615
4616 /* Search our cache for an entry matching NAME and DOMAIN.
4617 Return it if found, or NULL otherwise. */
4618
4619 static struct cache_entry **
4620 find_entry (const char *name, domain_enum domain)
4621 {
4622 struct ada_symbol_cache *sym_cache
4623 = ada_get_symbol_cache (current_program_space);
4624 int h = msymbol_hash (name) % HASH_SIZE;
4625 struct cache_entry **e;
4626
4627 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4628 {
4629 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4630 return e;
4631 }
4632 return NULL;
4633 }
4634
4635 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4636 Return 1 if found, 0 otherwise.
4637
4638 If an entry was found and SYM is not NULL, set *SYM to the entry's
4639 SYM. Same principle for BLOCK if not NULL. */
4640
4641 static int
4642 lookup_cached_symbol (const char *name, domain_enum domain,
4643 struct symbol **sym, const struct block **block)
4644 {
4645 struct cache_entry **e = find_entry (name, domain);
4646
4647 if (e == NULL)
4648 return 0;
4649 if (sym != NULL)
4650 *sym = (*e)->sym;
4651 if (block != NULL)
4652 *block = (*e)->block;
4653 return 1;
4654 }
4655
4656 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4657 in domain DOMAIN, save this result in our symbol cache. */
4658
4659 static void
4660 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4661 const struct block *block)
4662 {
4663 struct ada_symbol_cache *sym_cache
4664 = ada_get_symbol_cache (current_program_space);
4665 int h;
4666 struct cache_entry *e;
4667
4668 /* Symbols for builtin types don't have a block.
4669 For now don't cache such symbols. */
4670 if (sym != NULL && !SYMBOL_OBJFILE_OWNED (sym))
4671 return;
4672
4673 /* If the symbol is a local symbol, then do not cache it, as a search
4674 for that symbol depends on the context. To determine whether
4675 the symbol is local or not, we check the block where we found it
4676 against the global and static blocks of its associated symtab. */
4677 if (sym
4678 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4679 GLOBAL_BLOCK) != block
4680 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4681 STATIC_BLOCK) != block)
4682 return;
4683
4684 h = msymbol_hash (name) % HASH_SIZE;
4685 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4686 e->next = sym_cache->root[h];
4687 sym_cache->root[h] = e;
4688 e->name = obstack_strdup (&sym_cache->cache_space, name);
4689 e->sym = sym;
4690 e->domain = domain;
4691 e->block = block;
4692 }
4693 \f
4694 /* Symbol Lookup */
4695
4696 /* Return the symbol name match type that should be used used when
4697 searching for all symbols matching LOOKUP_NAME.
4698
4699 LOOKUP_NAME is expected to be a symbol name after transformation
4700 for Ada lookups. */
4701
4702 static symbol_name_match_type
4703 name_match_type_from_name (const char *lookup_name)
4704 {
4705 return (strstr (lookup_name, "__") == NULL
4706 ? symbol_name_match_type::WILD
4707 : symbol_name_match_type::FULL);
4708 }
4709
4710 /* Return the result of a standard (literal, C-like) lookup of NAME in
4711 given DOMAIN, visible from lexical block BLOCK. */
4712
4713 static struct symbol *
4714 standard_lookup (const char *name, const struct block *block,
4715 domain_enum domain)
4716 {
4717 /* Initialize it just to avoid a GCC false warning. */
4718 struct block_symbol sym = {};
4719
4720 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4721 return sym.symbol;
4722 ada_lookup_encoded_symbol (name, block, domain, &sym);
4723 cache_symbol (name, domain, sym.symbol, sym.block);
4724 return sym.symbol;
4725 }
4726
4727
4728 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4729 in the symbol fields of SYMS. We treat enumerals as functions,
4730 since they contend in overloading in the same way. */
4731 static int
4732 is_nonfunction (const std::vector<struct block_symbol> &syms)
4733 {
4734 for (const block_symbol &sym : syms)
4735 if (SYMBOL_TYPE (sym.symbol)->code () != TYPE_CODE_FUNC
4736 && (SYMBOL_TYPE (sym.symbol)->code () != TYPE_CODE_ENUM
4737 || SYMBOL_CLASS (sym.symbol) != LOC_CONST))
4738 return 1;
4739
4740 return 0;
4741 }
4742
4743 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4744 struct types. Otherwise, they may not. */
4745
4746 static int
4747 equiv_types (struct type *type0, struct type *type1)
4748 {
4749 if (type0 == type1)
4750 return 1;
4751 if (type0 == NULL || type1 == NULL
4752 || type0->code () != type1->code ())
4753 return 0;
4754 if ((type0->code () == TYPE_CODE_STRUCT
4755 || type0->code () == TYPE_CODE_ENUM)
4756 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4757 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4758 return 1;
4759
4760 return 0;
4761 }
4762
4763 /* True iff SYM0 represents the same entity as SYM1, or one that is
4764 no more defined than that of SYM1. */
4765
4766 static int
4767 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4768 {
4769 if (sym0 == sym1)
4770 return 1;
4771 if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
4772 || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
4773 return 0;
4774
4775 switch (SYMBOL_CLASS (sym0))
4776 {
4777 case LOC_UNDEF:
4778 return 1;
4779 case LOC_TYPEDEF:
4780 {
4781 struct type *type0 = SYMBOL_TYPE (sym0);
4782 struct type *type1 = SYMBOL_TYPE (sym1);
4783 const char *name0 = sym0->linkage_name ();
4784 const char *name1 = sym1->linkage_name ();
4785 int len0 = strlen (name0);
4786
4787 return
4788 type0->code () == type1->code ()
4789 && (equiv_types (type0, type1)
4790 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4791 && startswith (name1 + len0, "___XV")));
4792 }
4793 case LOC_CONST:
4794 return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4795 && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
4796
4797 case LOC_STATIC:
4798 {
4799 const char *name0 = sym0->linkage_name ();
4800 const char *name1 = sym1->linkage_name ();
4801 return (strcmp (name0, name1) == 0
4802 && SYMBOL_VALUE_ADDRESS (sym0) == SYMBOL_VALUE_ADDRESS (sym1));
4803 }
4804
4805 default:
4806 return 0;
4807 }
4808 }
4809
4810 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4811 records in RESULT. Do nothing if SYM is a duplicate. */
4812
4813 static void
4814 add_defn_to_vec (std::vector<struct block_symbol> &result,
4815 struct symbol *sym,
4816 const struct block *block)
4817 {
4818 /* Do not try to complete stub types, as the debugger is probably
4819 already scanning all symbols matching a certain name at the
4820 time when this function is called. Trying to replace the stub
4821 type by its associated full type will cause us to restart a scan
4822 which may lead to an infinite recursion. Instead, the client
4823 collecting the matching symbols will end up collecting several
4824 matches, with at least one of them complete. It can then filter
4825 out the stub ones if needed. */
4826
4827 for (int i = result.size () - 1; i >= 0; i -= 1)
4828 {
4829 if (lesseq_defined_than (sym, result[i].symbol))
4830 return;
4831 else if (lesseq_defined_than (result[i].symbol, sym))
4832 {
4833 result[i].symbol = sym;
4834 result[i].block = block;
4835 return;
4836 }
4837 }
4838
4839 struct block_symbol info;
4840 info.symbol = sym;
4841 info.block = block;
4842 result.push_back (info);
4843 }
4844
4845 /* Return a bound minimal symbol matching NAME according to Ada
4846 decoding rules. Returns an invalid symbol if there is no such
4847 minimal symbol. Names prefixed with "standard__" are handled
4848 specially: "standard__" is first stripped off, and only static and
4849 global symbols are searched. */
4850
4851 struct bound_minimal_symbol
4852 ada_lookup_simple_minsym (const char *name)
4853 {
4854 struct bound_minimal_symbol result;
4855
4856 memset (&result, 0, sizeof (result));
4857
4858 symbol_name_match_type match_type = name_match_type_from_name (name);
4859 lookup_name_info lookup_name (name, match_type);
4860
4861 symbol_name_matcher_ftype *match_name
4862 = ada_get_symbol_name_matcher (lookup_name);
4863
4864 for (objfile *objfile : current_program_space->objfiles ())
4865 {
4866 for (minimal_symbol *msymbol : objfile->msymbols ())
4867 {
4868 if (match_name (msymbol->linkage_name (), lookup_name, NULL)
4869 && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4870 {
4871 result.minsym = msymbol;
4872 result.objfile = objfile;
4873 break;
4874 }
4875 }
4876 }
4877
4878 return result;
4879 }
4880
4881 /* For all subprograms that statically enclose the subprogram of the
4882 selected frame, add symbols matching identifier NAME in DOMAIN
4883 and their blocks to the list of data in RESULT, as for
4884 ada_add_block_symbols (q.v.). If WILD_MATCH_P, treat as NAME
4885 with a wildcard prefix. */
4886
4887 static void
4888 add_symbols_from_enclosing_procs (std::vector<struct block_symbol> &result,
4889 const lookup_name_info &lookup_name,
4890 domain_enum domain)
4891 {
4892 }
4893
4894 /* True if TYPE is definitely an artificial type supplied to a symbol
4895 for which no debugging information was given in the symbol file. */
4896
4897 static int
4898 is_nondebugging_type (struct type *type)
4899 {
4900 const char *name = ada_type_name (type);
4901
4902 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4903 }
4904
4905 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4906 that are deemed "identical" for practical purposes.
4907
4908 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4909 types and that their number of enumerals is identical (in other
4910 words, type1->num_fields () == type2->num_fields ()). */
4911
4912 static int
4913 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4914 {
4915 int i;
4916
4917 /* The heuristic we use here is fairly conservative. We consider
4918 that 2 enumerate types are identical if they have the same
4919 number of enumerals and that all enumerals have the same
4920 underlying value and name. */
4921
4922 /* All enums in the type should have an identical underlying value. */
4923 for (i = 0; i < type1->num_fields (); i++)
4924 if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
4925 return 0;
4926
4927 /* All enumerals should also have the same name (modulo any numerical
4928 suffix). */
4929 for (i = 0; i < type1->num_fields (); i++)
4930 {
4931 const char *name_1 = TYPE_FIELD_NAME (type1, i);
4932 const char *name_2 = TYPE_FIELD_NAME (type2, i);
4933 int len_1 = strlen (name_1);
4934 int len_2 = strlen (name_2);
4935
4936 ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
4937 ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
4938 if (len_1 != len_2
4939 || strncmp (TYPE_FIELD_NAME (type1, i),
4940 TYPE_FIELD_NAME (type2, i),
4941 len_1) != 0)
4942 return 0;
4943 }
4944
4945 return 1;
4946 }
4947
4948 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4949 that are deemed "identical" for practical purposes. Sometimes,
4950 enumerals are not strictly identical, but their types are so similar
4951 that they can be considered identical.
4952
4953 For instance, consider the following code:
4954
4955 type Color is (Black, Red, Green, Blue, White);
4956 type RGB_Color is new Color range Red .. Blue;
4957
4958 Type RGB_Color is a subrange of an implicit type which is a copy
4959 of type Color. If we call that implicit type RGB_ColorB ("B" is
4960 for "Base Type"), then type RGB_ColorB is a copy of type Color.
4961 As a result, when an expression references any of the enumeral
4962 by name (Eg. "print green"), the expression is technically
4963 ambiguous and the user should be asked to disambiguate. But
4964 doing so would only hinder the user, since it wouldn't matter
4965 what choice he makes, the outcome would always be the same.
4966 So, for practical purposes, we consider them as the same. */
4967
4968 static int
4969 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
4970 {
4971 int i;
4972
4973 /* Before performing a thorough comparison check of each type,
4974 we perform a series of inexpensive checks. We expect that these
4975 checks will quickly fail in the vast majority of cases, and thus
4976 help prevent the unnecessary use of a more expensive comparison.
4977 Said comparison also expects us to make some of these checks
4978 (see ada_identical_enum_types_p). */
4979
4980 /* Quick check: All symbols should have an enum type. */
4981 for (i = 0; i < syms.size (); i++)
4982 if (SYMBOL_TYPE (syms[i].symbol)->code () != TYPE_CODE_ENUM)
4983 return 0;
4984
4985 /* Quick check: They should all have the same value. */
4986 for (i = 1; i < syms.size (); i++)
4987 if (SYMBOL_VALUE (syms[i].symbol) != SYMBOL_VALUE (syms[0].symbol))
4988 return 0;
4989
4990 /* Quick check: They should all have the same number of enumerals. */
4991 for (i = 1; i < syms.size (); i++)
4992 if (SYMBOL_TYPE (syms[i].symbol)->num_fields ()
4993 != SYMBOL_TYPE (syms[0].symbol)->num_fields ())
4994 return 0;
4995
4996 /* All the sanity checks passed, so we might have a set of
4997 identical enumeration types. Perform a more complete
4998 comparison of the type of each symbol. */
4999 for (i = 1; i < syms.size (); i++)
5000 if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].symbol),
5001 SYMBOL_TYPE (syms[0].symbol)))
5002 return 0;
5003
5004 return 1;
5005 }
5006
5007 /* Remove any non-debugging symbols in SYMS that definitely
5008 duplicate other symbols in the list (The only case I know of where
5009 this happens is when object files containing stabs-in-ecoff are
5010 linked with files containing ordinary ecoff debugging symbols (or no
5011 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5012
5013 static void
5014 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5015 {
5016 int i, j;
5017
5018 /* We should never be called with less than 2 symbols, as there
5019 cannot be any extra symbol in that case. But it's easy to
5020 handle, since we have nothing to do in that case. */
5021 if (syms->size () < 2)
5022 return;
5023
5024 i = 0;
5025 while (i < syms->size ())
5026 {
5027 int remove_p = 0;
5028
5029 /* If two symbols have the same name and one of them is a stub type,
5030 the get rid of the stub. */
5031
5032 if (SYMBOL_TYPE ((*syms)[i].symbol)->is_stub ()
5033 && (*syms)[i].symbol->linkage_name () != NULL)
5034 {
5035 for (j = 0; j < syms->size (); j++)
5036 {
5037 if (j != i
5038 && !SYMBOL_TYPE ((*syms)[j].symbol)->is_stub ()
5039 && (*syms)[j].symbol->linkage_name () != NULL
5040 && strcmp ((*syms)[i].symbol->linkage_name (),
5041 (*syms)[j].symbol->linkage_name ()) == 0)
5042 remove_p = 1;
5043 }
5044 }
5045
5046 /* Two symbols with the same name, same class and same address
5047 should be identical. */
5048
5049 else if ((*syms)[i].symbol->linkage_name () != NULL
5050 && SYMBOL_CLASS ((*syms)[i].symbol) == LOC_STATIC
5051 && is_nondebugging_type (SYMBOL_TYPE ((*syms)[i].symbol)))
5052 {
5053 for (j = 0; j < syms->size (); j += 1)
5054 {
5055 if (i != j
5056 && (*syms)[j].symbol->linkage_name () != NULL
5057 && strcmp ((*syms)[i].symbol->linkage_name (),
5058 (*syms)[j].symbol->linkage_name ()) == 0
5059 && SYMBOL_CLASS ((*syms)[i].symbol)
5060 == SYMBOL_CLASS ((*syms)[j].symbol)
5061 && SYMBOL_VALUE_ADDRESS ((*syms)[i].symbol)
5062 == SYMBOL_VALUE_ADDRESS ((*syms)[j].symbol))
5063 remove_p = 1;
5064 }
5065 }
5066
5067 if (remove_p)
5068 syms->erase (syms->begin () + i);
5069 else
5070 i += 1;
5071 }
5072
5073 /* If all the remaining symbols are identical enumerals, then
5074 just keep the first one and discard the rest.
5075
5076 Unlike what we did previously, we do not discard any entry
5077 unless they are ALL identical. This is because the symbol
5078 comparison is not a strict comparison, but rather a practical
5079 comparison. If all symbols are considered identical, then
5080 we can just go ahead and use the first one and discard the rest.
5081 But if we cannot reduce the list to a single element, we have
5082 to ask the user to disambiguate anyways. And if we have to
5083 present a multiple-choice menu, it's less confusing if the list
5084 isn't missing some choices that were identical and yet distinct. */
5085 if (symbols_are_identical_enums (*syms))
5086 syms->resize (1);
5087 }
5088
5089 /* Given a type that corresponds to a renaming entity, use the type name
5090 to extract the scope (package name or function name, fully qualified,
5091 and following the GNAT encoding convention) where this renaming has been
5092 defined. */
5093
5094 static std::string
5095 xget_renaming_scope (struct type *renaming_type)
5096 {
5097 /* The renaming types adhere to the following convention:
5098 <scope>__<rename>___<XR extension>.
5099 So, to extract the scope, we search for the "___XR" extension,
5100 and then backtrack until we find the first "__". */
5101
5102 const char *name = renaming_type->name ();
5103 const char *suffix = strstr (name, "___XR");
5104 const char *last;
5105
5106 /* Now, backtrack a bit until we find the first "__". Start looking
5107 at suffix - 3, as the <rename> part is at least one character long. */
5108
5109 for (last = suffix - 3; last > name; last--)
5110 if (last[0] == '_' && last[1] == '_')
5111 break;
5112
5113 /* Make a copy of scope and return it. */
5114 return std::string (name, last);
5115 }
5116
5117 /* Return nonzero if NAME corresponds to a package name. */
5118
5119 static int
5120 is_package_name (const char *name)
5121 {
5122 /* Here, We take advantage of the fact that no symbols are generated
5123 for packages, while symbols are generated for each function.
5124 So the condition for NAME represent a package becomes equivalent
5125 to NAME not existing in our list of symbols. There is only one
5126 small complication with library-level functions (see below). */
5127
5128 /* If it is a function that has not been defined at library level,
5129 then we should be able to look it up in the symbols. */
5130 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5131 return 0;
5132
5133 /* Library-level function names start with "_ada_". See if function
5134 "_ada_" followed by NAME can be found. */
5135
5136 /* Do a quick check that NAME does not contain "__", since library-level
5137 functions names cannot contain "__" in them. */
5138 if (strstr (name, "__") != NULL)
5139 return 0;
5140
5141 std::string fun_name = string_printf ("_ada_%s", name);
5142
5143 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5144 }
5145
5146 /* Return nonzero if SYM corresponds to a renaming entity that is
5147 not visible from FUNCTION_NAME. */
5148
5149 static int
5150 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5151 {
5152 if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
5153 return 0;
5154
5155 std::string scope = xget_renaming_scope (SYMBOL_TYPE (sym));
5156
5157 /* If the rename has been defined in a package, then it is visible. */
5158 if (is_package_name (scope.c_str ()))
5159 return 0;
5160
5161 /* Check that the rename is in the current function scope by checking
5162 that its name starts with SCOPE. */
5163
5164 /* If the function name starts with "_ada_", it means that it is
5165 a library-level function. Strip this prefix before doing the
5166 comparison, as the encoding for the renaming does not contain
5167 this prefix. */
5168 if (startswith (function_name, "_ada_"))
5169 function_name += 5;
5170
5171 return !startswith (function_name, scope.c_str ());
5172 }
5173
5174 /* Remove entries from SYMS that corresponds to a renaming entity that
5175 is not visible from the function associated with CURRENT_BLOCK or
5176 that is superfluous due to the presence of more specific renaming
5177 information. Places surviving symbols in the initial entries of
5178 SYMS.
5179
5180 Rationale:
5181 First, in cases where an object renaming is implemented as a
5182 reference variable, GNAT may produce both the actual reference
5183 variable and the renaming encoding. In this case, we discard the
5184 latter.
5185
5186 Second, GNAT emits a type following a specified encoding for each renaming
5187 entity. Unfortunately, STABS currently does not support the definition
5188 of types that are local to a given lexical block, so all renamings types
5189 are emitted at library level. As a consequence, if an application
5190 contains two renaming entities using the same name, and a user tries to
5191 print the value of one of these entities, the result of the ada symbol
5192 lookup will also contain the wrong renaming type.
5193
5194 This function partially covers for this limitation by attempting to
5195 remove from the SYMS list renaming symbols that should be visible
5196 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5197 method with the current information available. The implementation
5198 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5199
5200 - When the user tries to print a rename in a function while there
5201 is another rename entity defined in a package: Normally, the
5202 rename in the function has precedence over the rename in the
5203 package, so the latter should be removed from the list. This is
5204 currently not the case.
5205
5206 - This function will incorrectly remove valid renames if
5207 the CURRENT_BLOCK corresponds to a function which symbol name
5208 has been changed by an "Export" pragma. As a consequence,
5209 the user will be unable to print such rename entities. */
5210
5211 static void
5212 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5213 const struct block *current_block)
5214 {
5215 struct symbol *current_function;
5216 const char *current_function_name;
5217 int i;
5218 int is_new_style_renaming;
5219
5220 /* If there is both a renaming foo___XR... encoded as a variable and
5221 a simple variable foo in the same block, discard the latter.
5222 First, zero out such symbols, then compress. */
5223 is_new_style_renaming = 0;
5224 for (i = 0; i < syms->size (); i += 1)
5225 {
5226 struct symbol *sym = (*syms)[i].symbol;
5227 const struct block *block = (*syms)[i].block;
5228 const char *name;
5229 const char *suffix;
5230
5231 if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
5232 continue;
5233 name = sym->linkage_name ();
5234 suffix = strstr (name, "___XR");
5235
5236 if (suffix != NULL)
5237 {
5238 int name_len = suffix - name;
5239 int j;
5240
5241 is_new_style_renaming = 1;
5242 for (j = 0; j < syms->size (); j += 1)
5243 if (i != j && (*syms)[j].symbol != NULL
5244 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5245 name_len) == 0
5246 && block == (*syms)[j].block)
5247 (*syms)[j].symbol = NULL;
5248 }
5249 }
5250 if (is_new_style_renaming)
5251 {
5252 int j, k;
5253
5254 for (j = k = 0; j < syms->size (); j += 1)
5255 if ((*syms)[j].symbol != NULL)
5256 {
5257 (*syms)[k] = (*syms)[j];
5258 k += 1;
5259 }
5260 syms->resize (k);
5261 return;
5262 }
5263
5264 /* Extract the function name associated to CURRENT_BLOCK.
5265 Abort if unable to do so. */
5266
5267 if (current_block == NULL)
5268 return;
5269
5270 current_function = block_linkage_function (current_block);
5271 if (current_function == NULL)
5272 return;
5273
5274 current_function_name = current_function->linkage_name ();
5275 if (current_function_name == NULL)
5276 return;
5277
5278 /* Check each of the symbols, and remove it from the list if it is
5279 a type corresponding to a renaming that is out of the scope of
5280 the current block. */
5281
5282 i = 0;
5283 while (i < syms->size ())
5284 {
5285 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5286 == ADA_OBJECT_RENAMING
5287 && old_renaming_is_invisible ((*syms)[i].symbol,
5288 current_function_name))
5289 syms->erase (syms->begin () + i);
5290 else
5291 i += 1;
5292 }
5293 }
5294
5295 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5296 whose name and domain match NAME and DOMAIN respectively.
5297 If no match was found, then extend the search to "enclosing"
5298 routines (in other words, if we're inside a nested function,
5299 search the symbols defined inside the enclosing functions).
5300 If WILD_MATCH_P is nonzero, perform the naming matching in
5301 "wild" mode (see function "wild_match" for more info).
5302
5303 Note: This function assumes that RESULT has 0 (zero) element in it. */
5304
5305 static void
5306 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5307 const lookup_name_info &lookup_name,
5308 const struct block *block, domain_enum domain)
5309 {
5310 int block_depth = 0;
5311
5312 while (block != NULL)
5313 {
5314 block_depth += 1;
5315 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5316
5317 /* If we found a non-function match, assume that's the one. */
5318 if (is_nonfunction (result))
5319 return;
5320
5321 block = BLOCK_SUPERBLOCK (block);
5322 }
5323
5324 /* If no luck so far, try to find NAME as a local symbol in some lexically
5325 enclosing subprogram. */
5326 if (result.empty () && block_depth > 2)
5327 add_symbols_from_enclosing_procs (result, lookup_name, domain);
5328 }
5329
5330 /* An object of this type is used as the user_data argument when
5331 calling the map_matching_symbols method. */
5332
5333 struct match_data
5334 {
5335 explicit match_data (std::vector<struct block_symbol> *rp)
5336 : resultp (rp)
5337 {
5338 }
5339 DISABLE_COPY_AND_ASSIGN (match_data);
5340
5341 struct objfile *objfile = nullptr;
5342 std::vector<struct block_symbol> *resultp;
5343 struct symbol *arg_sym = nullptr;
5344 bool found_sym = false;
5345 };
5346
5347 /* A callback for add_nonlocal_symbols that adds symbol, found in BSYM,
5348 to a list of symbols. DATA is a pointer to a struct match_data *
5349 containing the vector that collects the symbol list, the file that SYM
5350 must come from, a flag indicating whether a non-argument symbol has
5351 been found in the current block, and the last argument symbol
5352 passed in SYM within the current block (if any). When SYM is null,
5353 marking the end of a block, the argument symbol is added if no
5354 other has been found. */
5355
5356 static bool
5357 aux_add_nonlocal_symbols (struct block_symbol *bsym,
5358 struct match_data *data)
5359 {
5360 const struct block *block = bsym->block;
5361 struct symbol *sym = bsym->symbol;
5362
5363 if (sym == NULL)
5364 {
5365 if (!data->found_sym && data->arg_sym != NULL)
5366 add_defn_to_vec (*data->resultp,
5367 fixup_symbol_section (data->arg_sym, data->objfile),
5368 block);
5369 data->found_sym = false;
5370 data->arg_sym = NULL;
5371 }
5372 else
5373 {
5374 if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5375 return true;
5376 else if (SYMBOL_IS_ARGUMENT (sym))
5377 data->arg_sym = sym;
5378 else
5379 {
5380 data->found_sym = true;
5381 add_defn_to_vec (*data->resultp,
5382 fixup_symbol_section (sym, data->objfile),
5383 block);
5384 }
5385 }
5386 return true;
5387 }
5388
5389 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5390 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5391 symbols to RESULT. Return whether we found such symbols. */
5392
5393 static int
5394 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5395 const struct block *block,
5396 const lookup_name_info &lookup_name,
5397 domain_enum domain)
5398 {
5399 struct using_direct *renaming;
5400 int defns_mark = result.size ();
5401
5402 symbol_name_matcher_ftype *name_match
5403 = ada_get_symbol_name_matcher (lookup_name);
5404
5405 for (renaming = block_using (block);
5406 renaming != NULL;
5407 renaming = renaming->next)
5408 {
5409 const char *r_name;
5410
5411 /* Avoid infinite recursions: skip this renaming if we are actually
5412 already traversing it.
5413
5414 Currently, symbol lookup in Ada don't use the namespace machinery from
5415 C++/Fortran support: skip namespace imports that use them. */
5416 if (renaming->searched
5417 || (renaming->import_src != NULL
5418 && renaming->import_src[0] != '\0')
5419 || (renaming->import_dest != NULL
5420 && renaming->import_dest[0] != '\0'))
5421 continue;
5422 renaming->searched = 1;
5423
5424 /* TODO: here, we perform another name-based symbol lookup, which can
5425 pull its own multiple overloads. In theory, we should be able to do
5426 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5427 not a simple name. But in order to do this, we would need to enhance
5428 the DWARF reader to associate a symbol to this renaming, instead of a
5429 name. So, for now, we do something simpler: re-use the C++/Fortran
5430 namespace machinery. */
5431 r_name = (renaming->alias != NULL
5432 ? renaming->alias
5433 : renaming->declaration);
5434 if (name_match (r_name, lookup_name, NULL))
5435 {
5436 lookup_name_info decl_lookup_name (renaming->declaration,
5437 lookup_name.match_type ());
5438 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5439 1, NULL);
5440 }
5441 renaming->searched = 0;
5442 }
5443 return result.size () != defns_mark;
5444 }
5445
5446 /* Implements compare_names, but only applying the comparision using
5447 the given CASING. */
5448
5449 static int
5450 compare_names_with_case (const char *string1, const char *string2,
5451 enum case_sensitivity casing)
5452 {
5453 while (*string1 != '\0' && *string2 != '\0')
5454 {
5455 char c1, c2;
5456
5457 if (isspace (*string1) || isspace (*string2))
5458 return strcmp_iw_ordered (string1, string2);
5459
5460 if (casing == case_sensitive_off)
5461 {
5462 c1 = tolower (*string1);
5463 c2 = tolower (*string2);
5464 }
5465 else
5466 {
5467 c1 = *string1;
5468 c2 = *string2;
5469 }
5470 if (c1 != c2)
5471 break;
5472
5473 string1 += 1;
5474 string2 += 1;
5475 }
5476
5477 switch (*string1)
5478 {
5479 case '(':
5480 return strcmp_iw_ordered (string1, string2);
5481 case '_':
5482 if (*string2 == '\0')
5483 {
5484 if (is_name_suffix (string1))
5485 return 0;
5486 else
5487 return 1;
5488 }
5489 /* FALLTHROUGH */
5490 default:
5491 if (*string2 == '(')
5492 return strcmp_iw_ordered (string1, string2);
5493 else
5494 {
5495 if (casing == case_sensitive_off)
5496 return tolower (*string1) - tolower (*string2);
5497 else
5498 return *string1 - *string2;
5499 }
5500 }
5501 }
5502
5503 /* Compare STRING1 to STRING2, with results as for strcmp.
5504 Compatible with strcmp_iw_ordered in that...
5505
5506 strcmp_iw_ordered (STRING1, STRING2) <= 0
5507
5508 ... implies...
5509
5510 compare_names (STRING1, STRING2) <= 0
5511
5512 (they may differ as to what symbols compare equal). */
5513
5514 static int
5515 compare_names (const char *string1, const char *string2)
5516 {
5517 int result;
5518
5519 /* Similar to what strcmp_iw_ordered does, we need to perform
5520 a case-insensitive comparison first, and only resort to
5521 a second, case-sensitive, comparison if the first one was
5522 not sufficient to differentiate the two strings. */
5523
5524 result = compare_names_with_case (string1, string2, case_sensitive_off);
5525 if (result == 0)
5526 result = compare_names_with_case (string1, string2, case_sensitive_on);
5527
5528 return result;
5529 }
5530
5531 /* Convenience function to get at the Ada encoded lookup name for
5532 LOOKUP_NAME, as a C string. */
5533
5534 static const char *
5535 ada_lookup_name (const lookup_name_info &lookup_name)
5536 {
5537 return lookup_name.ada ().lookup_name ().c_str ();
5538 }
5539
5540 /* Add to RESULT all non-local symbols whose name and domain match
5541 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5542 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5543 symbols otherwise. */
5544
5545 static void
5546 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5547 const lookup_name_info &lookup_name,
5548 domain_enum domain, int global)
5549 {
5550 struct match_data data (&result);
5551
5552 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5553
5554 auto callback = [&] (struct block_symbol *bsym)
5555 {
5556 return aux_add_nonlocal_symbols (bsym, &data);
5557 };
5558
5559 for (objfile *objfile : current_program_space->objfiles ())
5560 {
5561 data.objfile = objfile;
5562
5563 if (objfile->sf != nullptr)
5564 objfile->sf->qf->map_matching_symbols (objfile, lookup_name,
5565 domain, global, callback,
5566 (is_wild_match
5567 ? NULL : compare_names));
5568
5569 for (compunit_symtab *cu : objfile->compunits ())
5570 {
5571 const struct block *global_block
5572 = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cu), GLOBAL_BLOCK);
5573
5574 if (ada_add_block_renamings (result, global_block, lookup_name,
5575 domain))
5576 data.found_sym = true;
5577 }
5578 }
5579
5580 if (result.empty () && global && !is_wild_match)
5581 {
5582 const char *name = ada_lookup_name (lookup_name);
5583 std::string bracket_name = std::string ("<_ada_") + name + '>';
5584 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5585
5586 for (objfile *objfile : current_program_space->objfiles ())
5587 {
5588 data.objfile = objfile;
5589 if (objfile->sf != nullptr)
5590 objfile->sf->qf->map_matching_symbols (objfile, name1,
5591 domain, global, callback,
5592 compare_names);
5593 }
5594 }
5595 }
5596
5597 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5598 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5599 returning the number of matches. Add these to RESULT.
5600
5601 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5602 symbol match within the nest of blocks whose innermost member is BLOCK,
5603 is the one match returned (no other matches in that or
5604 enclosing blocks is returned). If there are any matches in or
5605 surrounding BLOCK, then these alone are returned.
5606
5607 Names prefixed with "standard__" are handled specially:
5608 "standard__" is first stripped off (by the lookup_name
5609 constructor), and only static and global symbols are searched.
5610
5611 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5612 to lookup global symbols. */
5613
5614 static void
5615 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5616 const struct block *block,
5617 const lookup_name_info &lookup_name,
5618 domain_enum domain,
5619 int full_search,
5620 int *made_global_lookup_p)
5621 {
5622 struct symbol *sym;
5623
5624 if (made_global_lookup_p)
5625 *made_global_lookup_p = 0;
5626
5627 /* Special case: If the user specifies a symbol name inside package
5628 Standard, do a non-wild matching of the symbol name without
5629 the "standard__" prefix. This was primarily introduced in order
5630 to allow the user to specifically access the standard exceptions
5631 using, for instance, Standard.Constraint_Error when Constraint_Error
5632 is ambiguous (due to the user defining its own Constraint_Error
5633 entity inside its program). */
5634 if (lookup_name.ada ().standard_p ())
5635 block = NULL;
5636
5637 /* Check the non-global symbols. If we have ANY match, then we're done. */
5638
5639 if (block != NULL)
5640 {
5641 if (full_search)
5642 ada_add_local_symbols (result, lookup_name, block, domain);
5643 else
5644 {
5645 /* In the !full_search case we're are being called by
5646 iterate_over_symbols, and we don't want to search
5647 superblocks. */
5648 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5649 }
5650 if (!result.empty () || !full_search)
5651 return;
5652 }
5653
5654 /* No non-global symbols found. Check our cache to see if we have
5655 already performed this search before. If we have, then return
5656 the same result. */
5657
5658 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5659 domain, &sym, &block))
5660 {
5661 if (sym != NULL)
5662 add_defn_to_vec (result, sym, block);
5663 return;
5664 }
5665
5666 if (made_global_lookup_p)
5667 *made_global_lookup_p = 1;
5668
5669 /* Search symbols from all global blocks. */
5670
5671 add_nonlocal_symbols (result, lookup_name, domain, 1);
5672
5673 /* Now add symbols from all per-file blocks if we've gotten no hits
5674 (not strictly correct, but perhaps better than an error). */
5675
5676 if (result.empty ())
5677 add_nonlocal_symbols (result, lookup_name, domain, 0);
5678 }
5679
5680 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5681 is non-zero, enclosing scope and in global scopes.
5682
5683 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5684 blocks and symbol tables (if any) in which they were found.
5685
5686 When full_search is non-zero, any non-function/non-enumeral
5687 symbol match within the nest of blocks whose innermost member is BLOCK,
5688 is the one match returned (no other matches in that or
5689 enclosing blocks is returned). If there are any matches in or
5690 surrounding BLOCK, then these alone are returned.
5691
5692 Names prefixed with "standard__" are handled specially: "standard__"
5693 is first stripped off, and only static and global symbols are searched. */
5694
5695 static std::vector<struct block_symbol>
5696 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5697 const struct block *block,
5698 domain_enum domain,
5699 int full_search)
5700 {
5701 int syms_from_global_search;
5702 std::vector<struct block_symbol> results;
5703
5704 ada_add_all_symbols (results, block, lookup_name,
5705 domain, full_search, &syms_from_global_search);
5706
5707 remove_extra_symbols (&results);
5708
5709 if (results.empty () && full_search && syms_from_global_search)
5710 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5711
5712 if (results.size () == 1 && full_search && syms_from_global_search)
5713 cache_symbol (ada_lookup_name (lookup_name), domain,
5714 results[0].symbol, results[0].block);
5715
5716 remove_irrelevant_renamings (&results, block);
5717 return results;
5718 }
5719
5720 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5721 in global scopes, returning (SYM,BLOCK) tuples.
5722
5723 See ada_lookup_symbol_list_worker for further details. */
5724
5725 std::vector<struct block_symbol>
5726 ada_lookup_symbol_list (const char *name, const struct block *block,
5727 domain_enum domain)
5728 {
5729 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5730 lookup_name_info lookup_name (name, name_match_type);
5731
5732 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5733 }
5734
5735 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5736 to 1, but choosing the first symbol found if there are multiple
5737 choices.
5738
5739 The result is stored in *INFO, which must be non-NULL.
5740 If no match is found, INFO->SYM is set to NULL. */
5741
5742 void
5743 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5744 domain_enum domain,
5745 struct block_symbol *info)
5746 {
5747 /* Since we already have an encoded name, wrap it in '<>' to force a
5748 verbatim match. Otherwise, if the name happens to not look like
5749 an encoded name (because it doesn't include a "__"),
5750 ada_lookup_name_info would re-encode/fold it again, and that
5751 would e.g., incorrectly lowercase object renaming names like
5752 "R28b" -> "r28b". */
5753 std::string verbatim = add_angle_brackets (name);
5754
5755 gdb_assert (info != NULL);
5756 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5757 }
5758
5759 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5760 scope and in global scopes, or NULL if none. NAME is folded and
5761 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5762 choosing the first symbol if there are multiple choices. */
5763
5764 struct block_symbol
5765 ada_lookup_symbol (const char *name, const struct block *block0,
5766 domain_enum domain)
5767 {
5768 std::vector<struct block_symbol> candidates
5769 = ada_lookup_symbol_list (name, block0, domain);
5770
5771 if (candidates.empty ())
5772 return {};
5773
5774 block_symbol info = candidates[0];
5775 info.symbol = fixup_symbol_section (info.symbol, NULL);
5776 return info;
5777 }
5778
5779
5780 /* True iff STR is a possible encoded suffix of a normal Ada name
5781 that is to be ignored for matching purposes. Suffixes of parallel
5782 names (e.g., XVE) are not included here. Currently, the possible suffixes
5783 are given by any of the regular expressions:
5784
5785 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5786 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5787 TKB [subprogram suffix for task bodies]
5788 _E[0-9]+[bs]$ [protected object entry suffixes]
5789 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5790
5791 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5792 match is performed. This sequence is used to differentiate homonyms,
5793 is an optional part of a valid name suffix. */
5794
5795 static int
5796 is_name_suffix (const char *str)
5797 {
5798 int k;
5799 const char *matching;
5800 const int len = strlen (str);
5801
5802 /* Skip optional leading __[0-9]+. */
5803
5804 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5805 {
5806 str += 3;
5807 while (isdigit (str[0]))
5808 str += 1;
5809 }
5810
5811 /* [.$][0-9]+ */
5812
5813 if (str[0] == '.' || str[0] == '$')
5814 {
5815 matching = str + 1;
5816 while (isdigit (matching[0]))
5817 matching += 1;
5818 if (matching[0] == '\0')
5819 return 1;
5820 }
5821
5822 /* ___[0-9]+ */
5823
5824 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5825 {
5826 matching = str + 3;
5827 while (isdigit (matching[0]))
5828 matching += 1;
5829 if (matching[0] == '\0')
5830 return 1;
5831 }
5832
5833 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5834
5835 if (strcmp (str, "TKB") == 0)
5836 return 1;
5837
5838 #if 0
5839 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5840 with a N at the end. Unfortunately, the compiler uses the same
5841 convention for other internal types it creates. So treating
5842 all entity names that end with an "N" as a name suffix causes
5843 some regressions. For instance, consider the case of an enumerated
5844 type. To support the 'Image attribute, it creates an array whose
5845 name ends with N.
5846 Having a single character like this as a suffix carrying some
5847 information is a bit risky. Perhaps we should change the encoding
5848 to be something like "_N" instead. In the meantime, do not do
5849 the following check. */
5850 /* Protected Object Subprograms */
5851 if (len == 1 && str [0] == 'N')
5852 return 1;
5853 #endif
5854
5855 /* _E[0-9]+[bs]$ */
5856 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5857 {
5858 matching = str + 3;
5859 while (isdigit (matching[0]))
5860 matching += 1;
5861 if ((matching[0] == 'b' || matching[0] == 's')
5862 && matching [1] == '\0')
5863 return 1;
5864 }
5865
5866 /* ??? We should not modify STR directly, as we are doing below. This
5867 is fine in this case, but may become problematic later if we find
5868 that this alternative did not work, and want to try matching
5869 another one from the begining of STR. Since we modified it, we
5870 won't be able to find the begining of the string anymore! */
5871 if (str[0] == 'X')
5872 {
5873 str += 1;
5874 while (str[0] != '_' && str[0] != '\0')
5875 {
5876 if (str[0] != 'n' && str[0] != 'b')
5877 return 0;
5878 str += 1;
5879 }
5880 }
5881
5882 if (str[0] == '\000')
5883 return 1;
5884
5885 if (str[0] == '_')
5886 {
5887 if (str[1] != '_' || str[2] == '\000')
5888 return 0;
5889 if (str[2] == '_')
5890 {
5891 if (strcmp (str + 3, "JM") == 0)
5892 return 1;
5893 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5894 the LJM suffix in favor of the JM one. But we will
5895 still accept LJM as a valid suffix for a reasonable
5896 amount of time, just to allow ourselves to debug programs
5897 compiled using an older version of GNAT. */
5898 if (strcmp (str + 3, "LJM") == 0)
5899 return 1;
5900 if (str[3] != 'X')
5901 return 0;
5902 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5903 || str[4] == 'U' || str[4] == 'P')
5904 return 1;
5905 if (str[4] == 'R' && str[5] != 'T')
5906 return 1;
5907 return 0;
5908 }
5909 if (!isdigit (str[2]))
5910 return 0;
5911 for (k = 3; str[k] != '\0'; k += 1)
5912 if (!isdigit (str[k]) && str[k] != '_')
5913 return 0;
5914 return 1;
5915 }
5916 if (str[0] == '$' && isdigit (str[1]))
5917 {
5918 for (k = 2; str[k] != '\0'; k += 1)
5919 if (!isdigit (str[k]) && str[k] != '_')
5920 return 0;
5921 return 1;
5922 }
5923 return 0;
5924 }
5925
5926 /* Return non-zero if the string starting at NAME and ending before
5927 NAME_END contains no capital letters. */
5928
5929 static int
5930 is_valid_name_for_wild_match (const char *name0)
5931 {
5932 std::string decoded_name = ada_decode (name0);
5933 int i;
5934
5935 /* If the decoded name starts with an angle bracket, it means that
5936 NAME0 does not follow the GNAT encoding format. It should then
5937 not be allowed as a possible wild match. */
5938 if (decoded_name[0] == '<')
5939 return 0;
5940
5941 for (i=0; decoded_name[i] != '\0'; i++)
5942 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5943 return 0;
5944
5945 return 1;
5946 }
5947
5948 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5949 character which could start a simple name. Assumes that *NAMEP points
5950 somewhere inside the string beginning at NAME0. */
5951
5952 static int
5953 advance_wild_match (const char **namep, const char *name0, char target0)
5954 {
5955 const char *name = *namep;
5956
5957 while (1)
5958 {
5959 char t0, t1;
5960
5961 t0 = *name;
5962 if (t0 == '_')
5963 {
5964 t1 = name[1];
5965 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5966 {
5967 name += 1;
5968 if (name == name0 + 5 && startswith (name0, "_ada"))
5969 break;
5970 else
5971 name += 1;
5972 }
5973 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5974 || name[2] == target0))
5975 {
5976 name += 2;
5977 break;
5978 }
5979 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5980 {
5981 /* Names like "pkg__B_N__name", where N is a number, are
5982 block-local. We can handle these by simply skipping
5983 the "B_" here. */
5984 name += 4;
5985 }
5986 else
5987 return 0;
5988 }
5989 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5990 name += 1;
5991 else
5992 return 0;
5993 }
5994
5995 *namep = name;
5996 return 1;
5997 }
5998
5999 /* Return true iff NAME encodes a name of the form prefix.PATN.
6000 Ignores any informational suffixes of NAME (i.e., for which
6001 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6002 simple name. */
6003
6004 static bool
6005 wild_match (const char *name, const char *patn)
6006 {
6007 const char *p;
6008 const char *name0 = name;
6009
6010 while (1)
6011 {
6012 const char *match = name;
6013
6014 if (*name == *patn)
6015 {
6016 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6017 if (*p != *name)
6018 break;
6019 if (*p == '\0' && is_name_suffix (name))
6020 return match == name0 || is_valid_name_for_wild_match (name0);
6021
6022 if (name[-1] == '_')
6023 name -= 1;
6024 }
6025 if (!advance_wild_match (&name, name0, *patn))
6026 return false;
6027 }
6028 }
6029
6030 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6031 necessary). OBJFILE is the section containing BLOCK. */
6032
6033 static void
6034 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6035 const struct block *block,
6036 const lookup_name_info &lookup_name,
6037 domain_enum domain, struct objfile *objfile)
6038 {
6039 struct block_iterator iter;
6040 /* A matching argument symbol, if any. */
6041 struct symbol *arg_sym;
6042 /* Set true when we find a matching non-argument symbol. */
6043 bool found_sym;
6044 struct symbol *sym;
6045
6046 arg_sym = NULL;
6047 found_sym = false;
6048 for (sym = block_iter_match_first (block, lookup_name, &iter);
6049 sym != NULL;
6050 sym = block_iter_match_next (lookup_name, &iter))
6051 {
6052 if (symbol_matches_domain (sym->language (), SYMBOL_DOMAIN (sym), domain))
6053 {
6054 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6055 {
6056 if (SYMBOL_IS_ARGUMENT (sym))
6057 arg_sym = sym;
6058 else
6059 {
6060 found_sym = true;
6061 add_defn_to_vec (result,
6062 fixup_symbol_section (sym, objfile),
6063 block);
6064 }
6065 }
6066 }
6067 }
6068
6069 /* Handle renamings. */
6070
6071 if (ada_add_block_renamings (result, block, lookup_name, domain))
6072 found_sym = true;
6073
6074 if (!found_sym && arg_sym != NULL)
6075 {
6076 add_defn_to_vec (result,
6077 fixup_symbol_section (arg_sym, objfile),
6078 block);
6079 }
6080
6081 if (!lookup_name.ada ().wild_match_p ())
6082 {
6083 arg_sym = NULL;
6084 found_sym = false;
6085 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6086 const char *name = ada_lookup_name.c_str ();
6087 size_t name_len = ada_lookup_name.size ();
6088
6089 ALL_BLOCK_SYMBOLS (block, iter, sym)
6090 {
6091 if (symbol_matches_domain (sym->language (),
6092 SYMBOL_DOMAIN (sym), domain))
6093 {
6094 int cmp;
6095
6096 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6097 if (cmp == 0)
6098 {
6099 cmp = !startswith (sym->linkage_name (), "_ada_");
6100 if (cmp == 0)
6101 cmp = strncmp (name, sym->linkage_name () + 5,
6102 name_len);
6103 }
6104
6105 if (cmp == 0
6106 && is_name_suffix (sym->linkage_name () + name_len + 5))
6107 {
6108 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6109 {
6110 if (SYMBOL_IS_ARGUMENT (sym))
6111 arg_sym = sym;
6112 else
6113 {
6114 found_sym = true;
6115 add_defn_to_vec (result,
6116 fixup_symbol_section (sym, objfile),
6117 block);
6118 }
6119 }
6120 }
6121 }
6122 }
6123
6124 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6125 They aren't parameters, right? */
6126 if (!found_sym && arg_sym != NULL)
6127 {
6128 add_defn_to_vec (result,
6129 fixup_symbol_section (arg_sym, objfile),
6130 block);
6131 }
6132 }
6133 }
6134 \f
6135
6136 /* Symbol Completion */
6137
6138 /* See symtab.h. */
6139
6140 bool
6141 ada_lookup_name_info::matches
6142 (const char *sym_name,
6143 symbol_name_match_type match_type,
6144 completion_match_result *comp_match_res) const
6145 {
6146 bool match = false;
6147 const char *text = m_encoded_name.c_str ();
6148 size_t text_len = m_encoded_name.size ();
6149
6150 /* First, test against the fully qualified name of the symbol. */
6151
6152 if (strncmp (sym_name, text, text_len) == 0)
6153 match = true;
6154
6155 std::string decoded_name = ada_decode (sym_name);
6156 if (match && !m_encoded_p)
6157 {
6158 /* One needed check before declaring a positive match is to verify
6159 that iff we are doing a verbatim match, the decoded version
6160 of the symbol name starts with '<'. Otherwise, this symbol name
6161 is not a suitable completion. */
6162
6163 bool has_angle_bracket = (decoded_name[0] == '<');
6164 match = (has_angle_bracket == m_verbatim_p);
6165 }
6166
6167 if (match && !m_verbatim_p)
6168 {
6169 /* When doing non-verbatim match, another check that needs to
6170 be done is to verify that the potentially matching symbol name
6171 does not include capital letters, because the ada-mode would
6172 not be able to understand these symbol names without the
6173 angle bracket notation. */
6174 const char *tmp;
6175
6176 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6177 if (*tmp != '\0')
6178 match = false;
6179 }
6180
6181 /* Second: Try wild matching... */
6182
6183 if (!match && m_wild_match_p)
6184 {
6185 /* Since we are doing wild matching, this means that TEXT
6186 may represent an unqualified symbol name. We therefore must
6187 also compare TEXT against the unqualified name of the symbol. */
6188 sym_name = ada_unqualified_name (decoded_name.c_str ());
6189
6190 if (strncmp (sym_name, text, text_len) == 0)
6191 match = true;
6192 }
6193
6194 /* Finally: If we found a match, prepare the result to return. */
6195
6196 if (!match)
6197 return false;
6198
6199 if (comp_match_res != NULL)
6200 {
6201 std::string &match_str = comp_match_res->match.storage ();
6202
6203 if (!m_encoded_p)
6204 match_str = ada_decode (sym_name);
6205 else
6206 {
6207 if (m_verbatim_p)
6208 match_str = add_angle_brackets (sym_name);
6209 else
6210 match_str = sym_name;
6211
6212 }
6213
6214 comp_match_res->set_match (match_str.c_str ());
6215 }
6216
6217 return true;
6218 }
6219
6220 /* Field Access */
6221
6222 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6223 for tagged types. */
6224
6225 static int
6226 ada_is_dispatch_table_ptr_type (struct type *type)
6227 {
6228 const char *name;
6229
6230 if (type->code () != TYPE_CODE_PTR)
6231 return 0;
6232
6233 name = TYPE_TARGET_TYPE (type)->name ();
6234 if (name == NULL)
6235 return 0;
6236
6237 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6238 }
6239
6240 /* Return non-zero if TYPE is an interface tag. */
6241
6242 static int
6243 ada_is_interface_tag (struct type *type)
6244 {
6245 const char *name = type->name ();
6246
6247 if (name == NULL)
6248 return 0;
6249
6250 return (strcmp (name, "ada__tags__interface_tag") == 0);
6251 }
6252
6253 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6254 to be invisible to users. */
6255
6256 int
6257 ada_is_ignored_field (struct type *type, int field_num)
6258 {
6259 if (field_num < 0 || field_num > type->num_fields ())
6260 return 1;
6261
6262 /* Check the name of that field. */
6263 {
6264 const char *name = TYPE_FIELD_NAME (type, field_num);
6265
6266 /* Anonymous field names should not be printed.
6267 brobecker/2007-02-20: I don't think this can actually happen
6268 but we don't want to print the value of anonymous fields anyway. */
6269 if (name == NULL)
6270 return 1;
6271
6272 /* Normally, fields whose name start with an underscore ("_")
6273 are fields that have been internally generated by the compiler,
6274 and thus should not be printed. The "_parent" field is special,
6275 however: This is a field internally generated by the compiler
6276 for tagged types, and it contains the components inherited from
6277 the parent type. This field should not be printed as is, but
6278 should not be ignored either. */
6279 if (name[0] == '_' && !startswith (name, "_parent"))
6280 return 1;
6281 }
6282
6283 /* If this is the dispatch table of a tagged type or an interface tag,
6284 then ignore. */
6285 if (ada_is_tagged_type (type, 1)
6286 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6287 || ada_is_interface_tag (type->field (field_num).type ())))
6288 return 1;
6289
6290 /* Not a special field, so it should not be ignored. */
6291 return 0;
6292 }
6293
6294 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6295 pointer or reference type whose ultimate target has a tag field. */
6296
6297 int
6298 ada_is_tagged_type (struct type *type, int refok)
6299 {
6300 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6301 }
6302
6303 /* True iff TYPE represents the type of X'Tag */
6304
6305 int
6306 ada_is_tag_type (struct type *type)
6307 {
6308 type = ada_check_typedef (type);
6309
6310 if (type == NULL || type->code () != TYPE_CODE_PTR)
6311 return 0;
6312 else
6313 {
6314 const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
6315
6316 return (name != NULL
6317 && strcmp (name, "ada__tags__dispatch_table") == 0);
6318 }
6319 }
6320
6321 /* The type of the tag on VAL. */
6322
6323 static struct type *
6324 ada_tag_type (struct value *val)
6325 {
6326 return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6327 }
6328
6329 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6330 retired at Ada 05). */
6331
6332 static int
6333 is_ada95_tag (struct value *tag)
6334 {
6335 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6336 }
6337
6338 /* The value of the tag on VAL. */
6339
6340 static struct value *
6341 ada_value_tag (struct value *val)
6342 {
6343 return ada_value_struct_elt (val, "_tag", 0);
6344 }
6345
6346 /* The value of the tag on the object of type TYPE whose contents are
6347 saved at VALADDR, if it is non-null, or is at memory address
6348 ADDRESS. */
6349
6350 static struct value *
6351 value_tag_from_contents_and_address (struct type *type,
6352 const gdb_byte *valaddr,
6353 CORE_ADDR address)
6354 {
6355 int tag_byte_offset;
6356 struct type *tag_type;
6357
6358 if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
6359 NULL, NULL, NULL))
6360 {
6361 const gdb_byte *valaddr1 = ((valaddr == NULL)
6362 ? NULL
6363 : valaddr + tag_byte_offset);
6364 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6365
6366 return value_from_contents_and_address (tag_type, valaddr1, address1);
6367 }
6368 return NULL;
6369 }
6370
6371 static struct type *
6372 type_from_tag (struct value *tag)
6373 {
6374 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6375
6376 if (type_name != NULL)
6377 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6378 return NULL;
6379 }
6380
6381 /* Given a value OBJ of a tagged type, return a value of this
6382 type at the base address of the object. The base address, as
6383 defined in Ada.Tags, it is the address of the primary tag of
6384 the object, and therefore where the field values of its full
6385 view can be fetched. */
6386
6387 struct value *
6388 ada_tag_value_at_base_address (struct value *obj)
6389 {
6390 struct value *val;
6391 LONGEST offset_to_top = 0;
6392 struct type *ptr_type, *obj_type;
6393 struct value *tag;
6394 CORE_ADDR base_address;
6395
6396 obj_type = value_type (obj);
6397
6398 /* It is the responsability of the caller to deref pointers. */
6399
6400 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6401 return obj;
6402
6403 tag = ada_value_tag (obj);
6404 if (!tag)
6405 return obj;
6406
6407 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6408
6409 if (is_ada95_tag (tag))
6410 return obj;
6411
6412 ptr_type = language_lookup_primitive_type
6413 (language_def (language_ada), target_gdbarch(), "storage_offset");
6414 ptr_type = lookup_pointer_type (ptr_type);
6415 val = value_cast (ptr_type, tag);
6416 if (!val)
6417 return obj;
6418
6419 /* It is perfectly possible that an exception be raised while
6420 trying to determine the base address, just like for the tag;
6421 see ada_tag_name for more details. We do not print the error
6422 message for the same reason. */
6423
6424 try
6425 {
6426 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6427 }
6428
6429 catch (const gdb_exception_error &e)
6430 {
6431 return obj;
6432 }
6433
6434 /* If offset is null, nothing to do. */
6435
6436 if (offset_to_top == 0)
6437 return obj;
6438
6439 /* -1 is a special case in Ada.Tags; however, what should be done
6440 is not quite clear from the documentation. So do nothing for
6441 now. */
6442
6443 if (offset_to_top == -1)
6444 return obj;
6445
6446 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6447 from the base address. This was however incompatible with
6448 C++ dispatch table: C++ uses a *negative* value to *add*
6449 to the base address. Ada's convention has therefore been
6450 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6451 use the same convention. Here, we support both cases by
6452 checking the sign of OFFSET_TO_TOP. */
6453
6454 if (offset_to_top > 0)
6455 offset_to_top = -offset_to_top;
6456
6457 base_address = value_address (obj) + offset_to_top;
6458 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6459
6460 /* Make sure that we have a proper tag at the new address.
6461 Otherwise, offset_to_top is bogus (which can happen when
6462 the object is not initialized yet). */
6463
6464 if (!tag)
6465 return obj;
6466
6467 obj_type = type_from_tag (tag);
6468
6469 if (!obj_type)
6470 return obj;
6471
6472 return value_from_contents_and_address (obj_type, NULL, base_address);
6473 }
6474
6475 /* Return the "ada__tags__type_specific_data" type. */
6476
6477 static struct type *
6478 ada_get_tsd_type (struct inferior *inf)
6479 {
6480 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6481
6482 if (data->tsd_type == 0)
6483 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6484 return data->tsd_type;
6485 }
6486
6487 /* Return the TSD (type-specific data) associated to the given TAG.
6488 TAG is assumed to be the tag of a tagged-type entity.
6489
6490 May return NULL if we are unable to get the TSD. */
6491
6492 static struct value *
6493 ada_get_tsd_from_tag (struct value *tag)
6494 {
6495 struct value *val;
6496 struct type *type;
6497
6498 /* First option: The TSD is simply stored as a field of our TAG.
6499 Only older versions of GNAT would use this format, but we have
6500 to test it first, because there are no visible markers for
6501 the current approach except the absence of that field. */
6502
6503 val = ada_value_struct_elt (tag, "tsd", 1);
6504 if (val)
6505 return val;
6506
6507 /* Try the second representation for the dispatch table (in which
6508 there is no explicit 'tsd' field in the referent of the tag pointer,
6509 and instead the tsd pointer is stored just before the dispatch
6510 table. */
6511
6512 type = ada_get_tsd_type (current_inferior());
6513 if (type == NULL)
6514 return NULL;
6515 type = lookup_pointer_type (lookup_pointer_type (type));
6516 val = value_cast (type, tag);
6517 if (val == NULL)
6518 return NULL;
6519 return value_ind (value_ptradd (val, -1));
6520 }
6521
6522 /* Given the TSD of a tag (type-specific data), return a string
6523 containing the name of the associated type.
6524
6525 May return NULL if we are unable to determine the tag name. */
6526
6527 static gdb::unique_xmalloc_ptr<char>
6528 ada_tag_name_from_tsd (struct value *tsd)
6529 {
6530 char *p;
6531 struct value *val;
6532
6533 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6534 if (val == NULL)
6535 return NULL;
6536 gdb::unique_xmalloc_ptr<char> buffer
6537 = target_read_string (value_as_address (val), INT_MAX);
6538 if (buffer == nullptr)
6539 return nullptr;
6540
6541 for (p = buffer.get (); *p != '\0'; ++p)
6542 {
6543 if (isalpha (*p))
6544 *p = tolower (*p);
6545 }
6546
6547 return buffer;
6548 }
6549
6550 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6551 a C string.
6552
6553 Return NULL if the TAG is not an Ada tag, or if we were unable to
6554 determine the name of that tag. */
6555
6556 gdb::unique_xmalloc_ptr<char>
6557 ada_tag_name (struct value *tag)
6558 {
6559 gdb::unique_xmalloc_ptr<char> name;
6560
6561 if (!ada_is_tag_type (value_type (tag)))
6562 return NULL;
6563
6564 /* It is perfectly possible that an exception be raised while trying
6565 to determine the TAG's name, even under normal circumstances:
6566 The associated variable may be uninitialized or corrupted, for
6567 instance. We do not let any exception propagate past this point.
6568 instead we return NULL.
6569
6570 We also do not print the error message either (which often is very
6571 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6572 the caller print a more meaningful message if necessary. */
6573 try
6574 {
6575 struct value *tsd = ada_get_tsd_from_tag (tag);
6576
6577 if (tsd != NULL)
6578 name = ada_tag_name_from_tsd (tsd);
6579 }
6580 catch (const gdb_exception_error &e)
6581 {
6582 }
6583
6584 return name;
6585 }
6586
6587 /* The parent type of TYPE, or NULL if none. */
6588
6589 struct type *
6590 ada_parent_type (struct type *type)
6591 {
6592 int i;
6593
6594 type = ada_check_typedef (type);
6595
6596 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6597 return NULL;
6598
6599 for (i = 0; i < type->num_fields (); i += 1)
6600 if (ada_is_parent_field (type, i))
6601 {
6602 struct type *parent_type = type->field (i).type ();
6603
6604 /* If the _parent field is a pointer, then dereference it. */
6605 if (parent_type->code () == TYPE_CODE_PTR)
6606 parent_type = TYPE_TARGET_TYPE (parent_type);
6607 /* If there is a parallel XVS type, get the actual base type. */
6608 parent_type = ada_get_base_type (parent_type);
6609
6610 return ada_check_typedef (parent_type);
6611 }
6612
6613 return NULL;
6614 }
6615
6616 /* True iff field number FIELD_NUM of structure type TYPE contains the
6617 parent-type (inherited) fields of a derived type. Assumes TYPE is
6618 a structure type with at least FIELD_NUM+1 fields. */
6619
6620 int
6621 ada_is_parent_field (struct type *type, int field_num)
6622 {
6623 const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
6624
6625 return (name != NULL
6626 && (startswith (name, "PARENT")
6627 || startswith (name, "_parent")));
6628 }
6629
6630 /* True iff field number FIELD_NUM of structure type TYPE is a
6631 transparent wrapper field (which should be silently traversed when doing
6632 field selection and flattened when printing). Assumes TYPE is a
6633 structure type with at least FIELD_NUM+1 fields. Such fields are always
6634 structures. */
6635
6636 int
6637 ada_is_wrapper_field (struct type *type, int field_num)
6638 {
6639 const char *name = TYPE_FIELD_NAME (type, field_num);
6640
6641 if (name != NULL && strcmp (name, "RETVAL") == 0)
6642 {
6643 /* This happens in functions with "out" or "in out" parameters
6644 which are passed by copy. For such functions, GNAT describes
6645 the function's return type as being a struct where the return
6646 value is in a field called RETVAL, and where the other "out"
6647 or "in out" parameters are fields of that struct. This is not
6648 a wrapper. */
6649 return 0;
6650 }
6651
6652 return (name != NULL
6653 && (startswith (name, "PARENT")
6654 || strcmp (name, "REP") == 0
6655 || startswith (name, "_parent")
6656 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6657 }
6658
6659 /* True iff field number FIELD_NUM of structure or union type TYPE
6660 is a variant wrapper. Assumes TYPE is a structure type with at least
6661 FIELD_NUM+1 fields. */
6662
6663 int
6664 ada_is_variant_part (struct type *type, int field_num)
6665 {
6666 /* Only Ada types are eligible. */
6667 if (!ADA_TYPE_P (type))
6668 return 0;
6669
6670 struct type *field_type = type->field (field_num).type ();
6671
6672 return (field_type->code () == TYPE_CODE_UNION
6673 || (is_dynamic_field (type, field_num)
6674 && (TYPE_TARGET_TYPE (field_type)->code ()
6675 == TYPE_CODE_UNION)));
6676 }
6677
6678 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6679 whose discriminants are contained in the record type OUTER_TYPE,
6680 returns the type of the controlling discriminant for the variant.
6681 May return NULL if the type could not be found. */
6682
6683 struct type *
6684 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6685 {
6686 const char *name = ada_variant_discrim_name (var_type);
6687
6688 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6689 }
6690
6691 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6692 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6693 represents a 'when others' clause; otherwise 0. */
6694
6695 static int
6696 ada_is_others_clause (struct type *type, int field_num)
6697 {
6698 const char *name = TYPE_FIELD_NAME (type, field_num);
6699
6700 return (name != NULL && name[0] == 'O');
6701 }
6702
6703 /* Assuming that TYPE0 is the type of the variant part of a record,
6704 returns the name of the discriminant controlling the variant.
6705 The value is valid until the next call to ada_variant_discrim_name. */
6706
6707 const char *
6708 ada_variant_discrim_name (struct type *type0)
6709 {
6710 static std::string result;
6711 struct type *type;
6712 const char *name;
6713 const char *discrim_end;
6714 const char *discrim_start;
6715
6716 if (type0->code () == TYPE_CODE_PTR)
6717 type = TYPE_TARGET_TYPE (type0);
6718 else
6719 type = type0;
6720
6721 name = ada_type_name (type);
6722
6723 if (name == NULL || name[0] == '\000')
6724 return "";
6725
6726 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6727 discrim_end -= 1)
6728 {
6729 if (startswith (discrim_end, "___XVN"))
6730 break;
6731 }
6732 if (discrim_end == name)
6733 return "";
6734
6735 for (discrim_start = discrim_end; discrim_start != name + 3;
6736 discrim_start -= 1)
6737 {
6738 if (discrim_start == name + 1)
6739 return "";
6740 if ((discrim_start > name + 3
6741 && startswith (discrim_start - 3, "___"))
6742 || discrim_start[-1] == '.')
6743 break;
6744 }
6745
6746 result = std::string (discrim_start, discrim_end - discrim_start);
6747 return result.c_str ();
6748 }
6749
6750 /* Scan STR for a subtype-encoded number, beginning at position K.
6751 Put the position of the character just past the number scanned in
6752 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6753 Return 1 if there was a valid number at the given position, and 0
6754 otherwise. A "subtype-encoded" number consists of the absolute value
6755 in decimal, followed by the letter 'm' to indicate a negative number.
6756 Assumes 0m does not occur. */
6757
6758 int
6759 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6760 {
6761 ULONGEST RU;
6762
6763 if (!isdigit (str[k]))
6764 return 0;
6765
6766 /* Do it the hard way so as not to make any assumption about
6767 the relationship of unsigned long (%lu scan format code) and
6768 LONGEST. */
6769 RU = 0;
6770 while (isdigit (str[k]))
6771 {
6772 RU = RU * 10 + (str[k] - '0');
6773 k += 1;
6774 }
6775
6776 if (str[k] == 'm')
6777 {
6778 if (R != NULL)
6779 *R = (-(LONGEST) (RU - 1)) - 1;
6780 k += 1;
6781 }
6782 else if (R != NULL)
6783 *R = (LONGEST) RU;
6784
6785 /* NOTE on the above: Technically, C does not say what the results of
6786 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6787 number representable as a LONGEST (although either would probably work
6788 in most implementations). When RU>0, the locution in the then branch
6789 above is always equivalent to the negative of RU. */
6790
6791 if (new_k != NULL)
6792 *new_k = k;
6793 return 1;
6794 }
6795
6796 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6797 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6798 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6799
6800 static int
6801 ada_in_variant (LONGEST val, struct type *type, int field_num)
6802 {
6803 const char *name = TYPE_FIELD_NAME (type, field_num);
6804 int p;
6805
6806 p = 0;
6807 while (1)
6808 {
6809 switch (name[p])
6810 {
6811 case '\0':
6812 return 0;
6813 case 'S':
6814 {
6815 LONGEST W;
6816
6817 if (!ada_scan_number (name, p + 1, &W, &p))
6818 return 0;
6819 if (val == W)
6820 return 1;
6821 break;
6822 }
6823 case 'R':
6824 {
6825 LONGEST L, U;
6826
6827 if (!ada_scan_number (name, p + 1, &L, &p)
6828 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6829 return 0;
6830 if (val >= L && val <= U)
6831 return 1;
6832 break;
6833 }
6834 case 'O':
6835 return 1;
6836 default:
6837 return 0;
6838 }
6839 }
6840 }
6841
6842 /* FIXME: Lots of redundancy below. Try to consolidate. */
6843
6844 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6845 ARG_TYPE, extract and return the value of one of its (non-static)
6846 fields. FIELDNO says which field. Differs from value_primitive_field
6847 only in that it can handle packed values of arbitrary type. */
6848
6849 struct value *
6850 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6851 struct type *arg_type)
6852 {
6853 struct type *type;
6854
6855 arg_type = ada_check_typedef (arg_type);
6856 type = arg_type->field (fieldno).type ();
6857
6858 /* Handle packed fields. It might be that the field is not packed
6859 relative to its containing structure, but the structure itself is
6860 packed; in this case we must take the bit-field path. */
6861 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
6862 {
6863 int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
6864 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6865
6866 return ada_value_primitive_packed_val (arg1, value_contents (arg1),
6867 offset + bit_pos / 8,
6868 bit_pos % 8, bit_size, type);
6869 }
6870 else
6871 return value_primitive_field (arg1, offset, fieldno, arg_type);
6872 }
6873
6874 /* Find field with name NAME in object of type TYPE. If found,
6875 set the following for each argument that is non-null:
6876 - *FIELD_TYPE_P to the field's type;
6877 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6878 an object of that type;
6879 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6880 - *BIT_SIZE_P to its size in bits if the field is packed, and
6881 0 otherwise;
6882 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6883 fields up to but not including the desired field, or by the total
6884 number of fields if not found. A NULL value of NAME never
6885 matches; the function just counts visible fields in this case.
6886
6887 Notice that we need to handle when a tagged record hierarchy
6888 has some components with the same name, like in this scenario:
6889
6890 type Top_T is tagged record
6891 N : Integer := 1;
6892 U : Integer := 974;
6893 A : Integer := 48;
6894 end record;
6895
6896 type Middle_T is new Top.Top_T with record
6897 N : Character := 'a';
6898 C : Integer := 3;
6899 end record;
6900
6901 type Bottom_T is new Middle.Middle_T with record
6902 N : Float := 4.0;
6903 C : Character := '5';
6904 X : Integer := 6;
6905 A : Character := 'J';
6906 end record;
6907
6908 Let's say we now have a variable declared and initialized as follow:
6909
6910 TC : Top_A := new Bottom_T;
6911
6912 And then we use this variable to call this function
6913
6914 procedure Assign (Obj: in out Top_T; TV : Integer);
6915
6916 as follow:
6917
6918 Assign (Top_T (B), 12);
6919
6920 Now, we're in the debugger, and we're inside that procedure
6921 then and we want to print the value of obj.c:
6922
6923 Usually, the tagged record or one of the parent type owns the
6924 component to print and there's no issue but in this particular
6925 case, what does it mean to ask for Obj.C? Since the actual
6926 type for object is type Bottom_T, it could mean two things: type
6927 component C from the Middle_T view, but also component C from
6928 Bottom_T. So in that "undefined" case, when the component is
6929 not found in the non-resolved type (which includes all the
6930 components of the parent type), then resolve it and see if we
6931 get better luck once expanded.
6932
6933 In the case of homonyms in the derived tagged type, we don't
6934 guaranty anything, and pick the one that's easiest for us
6935 to program.
6936
6937 Returns 1 if found, 0 otherwise. */
6938
6939 static int
6940 find_struct_field (const char *name, struct type *type, int offset,
6941 struct type **field_type_p,
6942 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6943 int *index_p)
6944 {
6945 int i;
6946 int parent_offset = -1;
6947
6948 type = ada_check_typedef (type);
6949
6950 if (field_type_p != NULL)
6951 *field_type_p = NULL;
6952 if (byte_offset_p != NULL)
6953 *byte_offset_p = 0;
6954 if (bit_offset_p != NULL)
6955 *bit_offset_p = 0;
6956 if (bit_size_p != NULL)
6957 *bit_size_p = 0;
6958
6959 for (i = 0; i < type->num_fields (); i += 1)
6960 {
6961 int bit_pos = TYPE_FIELD_BITPOS (type, i);
6962 int fld_offset = offset + bit_pos / 8;
6963 const char *t_field_name = TYPE_FIELD_NAME (type, i);
6964
6965 if (t_field_name == NULL)
6966 continue;
6967
6968 else if (ada_is_parent_field (type, i))
6969 {
6970 /* This is a field pointing us to the parent type of a tagged
6971 type. As hinted in this function's documentation, we give
6972 preference to fields in the current record first, so what
6973 we do here is just record the index of this field before
6974 we skip it. If it turns out we couldn't find our field
6975 in the current record, then we'll get back to it and search
6976 inside it whether the field might exist in the parent. */
6977
6978 parent_offset = i;
6979 continue;
6980 }
6981
6982 else if (name != NULL && field_name_match (t_field_name, name))
6983 {
6984 int bit_size = TYPE_FIELD_BITSIZE (type, i);
6985
6986 if (field_type_p != NULL)
6987 *field_type_p = type->field (i).type ();
6988 if (byte_offset_p != NULL)
6989 *byte_offset_p = fld_offset;
6990 if (bit_offset_p != NULL)
6991 *bit_offset_p = bit_pos % 8;
6992 if (bit_size_p != NULL)
6993 *bit_size_p = bit_size;
6994 return 1;
6995 }
6996 else if (ada_is_wrapper_field (type, i))
6997 {
6998 if (find_struct_field (name, type->field (i).type (), fld_offset,
6999 field_type_p, byte_offset_p, bit_offset_p,
7000 bit_size_p, index_p))
7001 return 1;
7002 }
7003 else if (ada_is_variant_part (type, i))
7004 {
7005 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7006 fixed type?? */
7007 int j;
7008 struct type *field_type
7009 = ada_check_typedef (type->field (i).type ());
7010
7011 for (j = 0; j < field_type->num_fields (); j += 1)
7012 {
7013 if (find_struct_field (name, field_type->field (j).type (),
7014 fld_offset
7015 + TYPE_FIELD_BITPOS (field_type, j) / 8,
7016 field_type_p, byte_offset_p,
7017 bit_offset_p, bit_size_p, index_p))
7018 return 1;
7019 }
7020 }
7021 else if (index_p != NULL)
7022 *index_p += 1;
7023 }
7024
7025 /* Field not found so far. If this is a tagged type which
7026 has a parent, try finding that field in the parent now. */
7027
7028 if (parent_offset != -1)
7029 {
7030 int bit_pos = TYPE_FIELD_BITPOS (type, parent_offset);
7031 int fld_offset = offset + bit_pos / 8;
7032
7033 if (find_struct_field (name, type->field (parent_offset).type (),
7034 fld_offset, field_type_p, byte_offset_p,
7035 bit_offset_p, bit_size_p, index_p))
7036 return 1;
7037 }
7038
7039 return 0;
7040 }
7041
7042 /* Number of user-visible fields in record type TYPE. */
7043
7044 static int
7045 num_visible_fields (struct type *type)
7046 {
7047 int n;
7048
7049 n = 0;
7050 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7051 return n;
7052 }
7053
7054 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7055 and search in it assuming it has (class) type TYPE.
7056 If found, return value, else return NULL.
7057
7058 Searches recursively through wrapper fields (e.g., '_parent').
7059
7060 In the case of homonyms in the tagged types, please refer to the
7061 long explanation in find_struct_field's function documentation. */
7062
7063 static struct value *
7064 ada_search_struct_field (const char *name, struct value *arg, int offset,
7065 struct type *type)
7066 {
7067 int i;
7068 int parent_offset = -1;
7069
7070 type = ada_check_typedef (type);
7071 for (i = 0; i < type->num_fields (); i += 1)
7072 {
7073 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7074
7075 if (t_field_name == NULL)
7076 continue;
7077
7078 else if (ada_is_parent_field (type, i))
7079 {
7080 /* This is a field pointing us to the parent type of a tagged
7081 type. As hinted in this function's documentation, we give
7082 preference to fields in the current record first, so what
7083 we do here is just record the index of this field before
7084 we skip it. If it turns out we couldn't find our field
7085 in the current record, then we'll get back to it and search
7086 inside it whether the field might exist in the parent. */
7087
7088 parent_offset = i;
7089 continue;
7090 }
7091
7092 else if (field_name_match (t_field_name, name))
7093 return ada_value_primitive_field (arg, offset, i, type);
7094
7095 else if (ada_is_wrapper_field (type, i))
7096 {
7097 struct value *v = /* Do not let indent join lines here. */
7098 ada_search_struct_field (name, arg,
7099 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7100 type->field (i).type ());
7101
7102 if (v != NULL)
7103 return v;
7104 }
7105
7106 else if (ada_is_variant_part (type, i))
7107 {
7108 /* PNH: Do we ever get here? See find_struct_field. */
7109 int j;
7110 struct type *field_type = ada_check_typedef (type->field (i).type ());
7111 int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
7112
7113 for (j = 0; j < field_type->num_fields (); j += 1)
7114 {
7115 struct value *v = ada_search_struct_field /* Force line
7116 break. */
7117 (name, arg,
7118 var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
7119 field_type->field (j).type ());
7120
7121 if (v != NULL)
7122 return v;
7123 }
7124 }
7125 }
7126
7127 /* Field not found so far. If this is a tagged type which
7128 has a parent, try finding that field in the parent now. */
7129
7130 if (parent_offset != -1)
7131 {
7132 struct value *v = ada_search_struct_field (
7133 name, arg, offset + TYPE_FIELD_BITPOS (type, parent_offset) / 8,
7134 type->field (parent_offset).type ());
7135
7136 if (v != NULL)
7137 return v;
7138 }
7139
7140 return NULL;
7141 }
7142
7143 static struct value *ada_index_struct_field_1 (int *, struct value *,
7144 int, struct type *);
7145
7146
7147 /* Return field #INDEX in ARG, where the index is that returned by
7148 * find_struct_field through its INDEX_P argument. Adjust the address
7149 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7150 * If found, return value, else return NULL. */
7151
7152 static struct value *
7153 ada_index_struct_field (int index, struct value *arg, int offset,
7154 struct type *type)
7155 {
7156 return ada_index_struct_field_1 (&index, arg, offset, type);
7157 }
7158
7159
7160 /* Auxiliary function for ada_index_struct_field. Like
7161 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7162 * *INDEX_P. */
7163
7164 static struct value *
7165 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7166 struct type *type)
7167 {
7168 int i;
7169 type = ada_check_typedef (type);
7170
7171 for (i = 0; i < type->num_fields (); i += 1)
7172 {
7173 if (TYPE_FIELD_NAME (type, i) == NULL)
7174 continue;
7175 else if (ada_is_wrapper_field (type, i))
7176 {
7177 struct value *v = /* Do not let indent join lines here. */
7178 ada_index_struct_field_1 (index_p, arg,
7179 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7180 type->field (i).type ());
7181
7182 if (v != NULL)
7183 return v;
7184 }
7185
7186 else if (ada_is_variant_part (type, i))
7187 {
7188 /* PNH: Do we ever get here? See ada_search_struct_field,
7189 find_struct_field. */
7190 error (_("Cannot assign this kind of variant record"));
7191 }
7192 else if (*index_p == 0)
7193 return ada_value_primitive_field (arg, offset, i, type);
7194 else
7195 *index_p -= 1;
7196 }
7197 return NULL;
7198 }
7199
7200 /* Return a string representation of type TYPE. */
7201
7202 static std::string
7203 type_as_string (struct type *type)
7204 {
7205 string_file tmp_stream;
7206
7207 type_print (type, "", &tmp_stream, -1);
7208
7209 return std::move (tmp_stream.string ());
7210 }
7211
7212 /* Given a type TYPE, look up the type of the component of type named NAME.
7213 If DISPP is non-null, add its byte displacement from the beginning of a
7214 structure (pointed to by a value) of type TYPE to *DISPP (does not
7215 work for packed fields).
7216
7217 Matches any field whose name has NAME as a prefix, possibly
7218 followed by "___".
7219
7220 TYPE can be either a struct or union. If REFOK, TYPE may also
7221 be a (pointer or reference)+ to a struct or union, and the
7222 ultimate target type will be searched.
7223
7224 Looks recursively into variant clauses and parent types.
7225
7226 In the case of homonyms in the tagged types, please refer to the
7227 long explanation in find_struct_field's function documentation.
7228
7229 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7230 TYPE is not a type of the right kind. */
7231
7232 static struct type *
7233 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7234 int noerr)
7235 {
7236 int i;
7237 int parent_offset = -1;
7238
7239 if (name == NULL)
7240 goto BadName;
7241
7242 if (refok && type != NULL)
7243 while (1)
7244 {
7245 type = ada_check_typedef (type);
7246 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7247 break;
7248 type = TYPE_TARGET_TYPE (type);
7249 }
7250
7251 if (type == NULL
7252 || (type->code () != TYPE_CODE_STRUCT
7253 && type->code () != TYPE_CODE_UNION))
7254 {
7255 if (noerr)
7256 return NULL;
7257
7258 error (_("Type %s is not a structure or union type"),
7259 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7260 }
7261
7262 type = to_static_fixed_type (type);
7263
7264 for (i = 0; i < type->num_fields (); i += 1)
7265 {
7266 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7267 struct type *t;
7268
7269 if (t_field_name == NULL)
7270 continue;
7271
7272 else if (ada_is_parent_field (type, i))
7273 {
7274 /* This is a field pointing us to the parent type of a tagged
7275 type. As hinted in this function's documentation, we give
7276 preference to fields in the current record first, so what
7277 we do here is just record the index of this field before
7278 we skip it. If it turns out we couldn't find our field
7279 in the current record, then we'll get back to it and search
7280 inside it whether the field might exist in the parent. */
7281
7282 parent_offset = i;
7283 continue;
7284 }
7285
7286 else if (field_name_match (t_field_name, name))
7287 return type->field (i).type ();
7288
7289 else if (ada_is_wrapper_field (type, i))
7290 {
7291 t = ada_lookup_struct_elt_type (type->field (i).type (), name,
7292 0, 1);
7293 if (t != NULL)
7294 return t;
7295 }
7296
7297 else if (ada_is_variant_part (type, i))
7298 {
7299 int j;
7300 struct type *field_type = ada_check_typedef (type->field (i).type ());
7301
7302 for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7303 {
7304 /* FIXME pnh 2008/01/26: We check for a field that is
7305 NOT wrapped in a struct, since the compiler sometimes
7306 generates these for unchecked variant types. Revisit
7307 if the compiler changes this practice. */
7308 const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
7309
7310 if (v_field_name != NULL
7311 && field_name_match (v_field_name, name))
7312 t = field_type->field (j).type ();
7313 else
7314 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
7315 name, 0, 1);
7316
7317 if (t != NULL)
7318 return t;
7319 }
7320 }
7321
7322 }
7323
7324 /* Field not found so far. If this is a tagged type which
7325 has a parent, try finding that field in the parent now. */
7326
7327 if (parent_offset != -1)
7328 {
7329 struct type *t;
7330
7331 t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7332 name, 0, 1);
7333 if (t != NULL)
7334 return t;
7335 }
7336
7337 BadName:
7338 if (!noerr)
7339 {
7340 const char *name_str = name != NULL ? name : _("<null>");
7341
7342 error (_("Type %s has no component named %s"),
7343 type_as_string (type).c_str (), name_str);
7344 }
7345
7346 return NULL;
7347 }
7348
7349 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7350 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7351 represents an unchecked union (that is, the variant part of a
7352 record that is named in an Unchecked_Union pragma). */
7353
7354 static int
7355 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7356 {
7357 const char *discrim_name = ada_variant_discrim_name (var_type);
7358
7359 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7360 }
7361
7362
7363 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7364 within OUTER, determine which variant clause (field number in VAR_TYPE,
7365 numbering from 0) is applicable. Returns -1 if none are. */
7366
7367 int
7368 ada_which_variant_applies (struct type *var_type, struct value *outer)
7369 {
7370 int others_clause;
7371 int i;
7372 const char *discrim_name = ada_variant_discrim_name (var_type);
7373 struct value *discrim;
7374 LONGEST discrim_val;
7375
7376 /* Using plain value_from_contents_and_address here causes problems
7377 because we will end up trying to resolve a type that is currently
7378 being constructed. */
7379 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7380 if (discrim == NULL)
7381 return -1;
7382 discrim_val = value_as_long (discrim);
7383
7384 others_clause = -1;
7385 for (i = 0; i < var_type->num_fields (); i += 1)
7386 {
7387 if (ada_is_others_clause (var_type, i))
7388 others_clause = i;
7389 else if (ada_in_variant (discrim_val, var_type, i))
7390 return i;
7391 }
7392
7393 return others_clause;
7394 }
7395 \f
7396
7397
7398 /* Dynamic-Sized Records */
7399
7400 /* Strategy: The type ostensibly attached to a value with dynamic size
7401 (i.e., a size that is not statically recorded in the debugging
7402 data) does not accurately reflect the size or layout of the value.
7403 Our strategy is to convert these values to values with accurate,
7404 conventional types that are constructed on the fly. */
7405
7406 /* There is a subtle and tricky problem here. In general, we cannot
7407 determine the size of dynamic records without its data. However,
7408 the 'struct value' data structure, which GDB uses to represent
7409 quantities in the inferior process (the target), requires the size
7410 of the type at the time of its allocation in order to reserve space
7411 for GDB's internal copy of the data. That's why the
7412 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7413 rather than struct value*s.
7414
7415 However, GDB's internal history variables ($1, $2, etc.) are
7416 struct value*s containing internal copies of the data that are not, in
7417 general, the same as the data at their corresponding addresses in
7418 the target. Fortunately, the types we give to these values are all
7419 conventional, fixed-size types (as per the strategy described
7420 above), so that we don't usually have to perform the
7421 'to_fixed_xxx_type' conversions to look at their values.
7422 Unfortunately, there is one exception: if one of the internal
7423 history variables is an array whose elements are unconstrained
7424 records, then we will need to create distinct fixed types for each
7425 element selected. */
7426
7427 /* The upshot of all of this is that many routines take a (type, host
7428 address, target address) triple as arguments to represent a value.
7429 The host address, if non-null, is supposed to contain an internal
7430 copy of the relevant data; otherwise, the program is to consult the
7431 target at the target address. */
7432
7433 /* Assuming that VAL0 represents a pointer value, the result of
7434 dereferencing it. Differs from value_ind in its treatment of
7435 dynamic-sized types. */
7436
7437 struct value *
7438 ada_value_ind (struct value *val0)
7439 {
7440 struct value *val = value_ind (val0);
7441
7442 if (ada_is_tagged_type (value_type (val), 0))
7443 val = ada_tag_value_at_base_address (val);
7444
7445 return ada_to_fixed_value (val);
7446 }
7447
7448 /* The value resulting from dereferencing any "reference to"
7449 qualifiers on VAL0. */
7450
7451 static struct value *
7452 ada_coerce_ref (struct value *val0)
7453 {
7454 if (value_type (val0)->code () == TYPE_CODE_REF)
7455 {
7456 struct value *val = val0;
7457
7458 val = coerce_ref (val);
7459
7460 if (ada_is_tagged_type (value_type (val), 0))
7461 val = ada_tag_value_at_base_address (val);
7462
7463 return ada_to_fixed_value (val);
7464 }
7465 else
7466 return val0;
7467 }
7468
7469 /* Return the bit alignment required for field #F of template type TYPE. */
7470
7471 static unsigned int
7472 field_alignment (struct type *type, int f)
7473 {
7474 const char *name = TYPE_FIELD_NAME (type, f);
7475 int len;
7476 int align_offset;
7477
7478 /* The field name should never be null, unless the debugging information
7479 is somehow malformed. In this case, we assume the field does not
7480 require any alignment. */
7481 if (name == NULL)
7482 return 1;
7483
7484 len = strlen (name);
7485
7486 if (!isdigit (name[len - 1]))
7487 return 1;
7488
7489 if (isdigit (name[len - 2]))
7490 align_offset = len - 2;
7491 else
7492 align_offset = len - 1;
7493
7494 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7495 return TARGET_CHAR_BIT;
7496
7497 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7498 }
7499
7500 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7501
7502 static struct symbol *
7503 ada_find_any_type_symbol (const char *name)
7504 {
7505 struct symbol *sym;
7506
7507 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7508 if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
7509 return sym;
7510
7511 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7512 return sym;
7513 }
7514
7515 /* Find a type named NAME. Ignores ambiguity. This routine will look
7516 solely for types defined by debug info, it will not search the GDB
7517 primitive types. */
7518
7519 static struct type *
7520 ada_find_any_type (const char *name)
7521 {
7522 struct symbol *sym = ada_find_any_type_symbol (name);
7523
7524 if (sym != NULL)
7525 return SYMBOL_TYPE (sym);
7526
7527 return NULL;
7528 }
7529
7530 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7531 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7532 symbol, in which case it is returned. Otherwise, this looks for
7533 symbols whose name is that of NAME_SYM suffixed with "___XR".
7534 Return symbol if found, and NULL otherwise. */
7535
7536 static bool
7537 ada_is_renaming_symbol (struct symbol *name_sym)
7538 {
7539 const char *name = name_sym->linkage_name ();
7540 return strstr (name, "___XR") != NULL;
7541 }
7542
7543 /* Because of GNAT encoding conventions, several GDB symbols may match a
7544 given type name. If the type denoted by TYPE0 is to be preferred to
7545 that of TYPE1 for purposes of type printing, return non-zero;
7546 otherwise return 0. */
7547
7548 int
7549 ada_prefer_type (struct type *type0, struct type *type1)
7550 {
7551 if (type1 == NULL)
7552 return 1;
7553 else if (type0 == NULL)
7554 return 0;
7555 else if (type1->code () == TYPE_CODE_VOID)
7556 return 1;
7557 else if (type0->code () == TYPE_CODE_VOID)
7558 return 0;
7559 else if (type1->name () == NULL && type0->name () != NULL)
7560 return 1;
7561 else if (ada_is_constrained_packed_array_type (type0))
7562 return 1;
7563 else if (ada_is_array_descriptor_type (type0)
7564 && !ada_is_array_descriptor_type (type1))
7565 return 1;
7566 else
7567 {
7568 const char *type0_name = type0->name ();
7569 const char *type1_name = type1->name ();
7570
7571 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7572 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7573 return 1;
7574 }
7575 return 0;
7576 }
7577
7578 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7579 null. */
7580
7581 const char *
7582 ada_type_name (struct type *type)
7583 {
7584 if (type == NULL)
7585 return NULL;
7586 return type->name ();
7587 }
7588
7589 /* Search the list of "descriptive" types associated to TYPE for a type
7590 whose name is NAME. */
7591
7592 static struct type *
7593 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7594 {
7595 struct type *result, *tmp;
7596
7597 if (ada_ignore_descriptive_types_p)
7598 return NULL;
7599
7600 /* If there no descriptive-type info, then there is no parallel type
7601 to be found. */
7602 if (!HAVE_GNAT_AUX_INFO (type))
7603 return NULL;
7604
7605 result = TYPE_DESCRIPTIVE_TYPE (type);
7606 while (result != NULL)
7607 {
7608 const char *result_name = ada_type_name (result);
7609
7610 if (result_name == NULL)
7611 {
7612 warning (_("unexpected null name on descriptive type"));
7613 return NULL;
7614 }
7615
7616 /* If the names match, stop. */
7617 if (strcmp (result_name, name) == 0)
7618 break;
7619
7620 /* Otherwise, look at the next item on the list, if any. */
7621 if (HAVE_GNAT_AUX_INFO (result))
7622 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7623 else
7624 tmp = NULL;
7625
7626 /* If not found either, try after having resolved the typedef. */
7627 if (tmp != NULL)
7628 result = tmp;
7629 else
7630 {
7631 result = check_typedef (result);
7632 if (HAVE_GNAT_AUX_INFO (result))
7633 result = TYPE_DESCRIPTIVE_TYPE (result);
7634 else
7635 result = NULL;
7636 }
7637 }
7638
7639 /* If we didn't find a match, see whether this is a packed array. With
7640 older compilers, the descriptive type information is either absent or
7641 irrelevant when it comes to packed arrays so the above lookup fails.
7642 Fall back to using a parallel lookup by name in this case. */
7643 if (result == NULL && ada_is_constrained_packed_array_type (type))
7644 return ada_find_any_type (name);
7645
7646 return result;
7647 }
7648
7649 /* Find a parallel type to TYPE with the specified NAME, using the
7650 descriptive type taken from the debugging information, if available,
7651 and otherwise using the (slower) name-based method. */
7652
7653 static struct type *
7654 ada_find_parallel_type_with_name (struct type *type, const char *name)
7655 {
7656 struct type *result = NULL;
7657
7658 if (HAVE_GNAT_AUX_INFO (type))
7659 result = find_parallel_type_by_descriptive_type (type, name);
7660 else
7661 result = ada_find_any_type (name);
7662
7663 return result;
7664 }
7665
7666 /* Same as above, but specify the name of the parallel type by appending
7667 SUFFIX to the name of TYPE. */
7668
7669 struct type *
7670 ada_find_parallel_type (struct type *type, const char *suffix)
7671 {
7672 char *name;
7673 const char *type_name = ada_type_name (type);
7674 int len;
7675
7676 if (type_name == NULL)
7677 return NULL;
7678
7679 len = strlen (type_name);
7680
7681 name = (char *) alloca (len + strlen (suffix) + 1);
7682
7683 strcpy (name, type_name);
7684 strcpy (name + len, suffix);
7685
7686 return ada_find_parallel_type_with_name (type, name);
7687 }
7688
7689 /* If TYPE is a variable-size record type, return the corresponding template
7690 type describing its fields. Otherwise, return NULL. */
7691
7692 static struct type *
7693 dynamic_template_type (struct type *type)
7694 {
7695 type = ada_check_typedef (type);
7696
7697 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7698 || ada_type_name (type) == NULL)
7699 return NULL;
7700 else
7701 {
7702 int len = strlen (ada_type_name (type));
7703
7704 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7705 return type;
7706 else
7707 return ada_find_parallel_type (type, "___XVE");
7708 }
7709 }
7710
7711 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7712 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7713
7714 static int
7715 is_dynamic_field (struct type *templ_type, int field_num)
7716 {
7717 const char *name = TYPE_FIELD_NAME (templ_type, field_num);
7718
7719 return name != NULL
7720 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7721 && strstr (name, "___XVL") != NULL;
7722 }
7723
7724 /* The index of the variant field of TYPE, or -1 if TYPE does not
7725 represent a variant record type. */
7726
7727 static int
7728 variant_field_index (struct type *type)
7729 {
7730 int f;
7731
7732 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7733 return -1;
7734
7735 for (f = 0; f < type->num_fields (); f += 1)
7736 {
7737 if (ada_is_variant_part (type, f))
7738 return f;
7739 }
7740 return -1;
7741 }
7742
7743 /* A record type with no fields. */
7744
7745 static struct type *
7746 empty_record (struct type *templ)
7747 {
7748 struct type *type = alloc_type_copy (templ);
7749
7750 type->set_code (TYPE_CODE_STRUCT);
7751 INIT_NONE_SPECIFIC (type);
7752 type->set_name ("<empty>");
7753 TYPE_LENGTH (type) = 0;
7754 return type;
7755 }
7756
7757 /* An ordinary record type (with fixed-length fields) that describes
7758 the value of type TYPE at VALADDR or ADDRESS (see comments at
7759 the beginning of this section) VAL according to GNAT conventions.
7760 DVAL0 should describe the (portion of a) record that contains any
7761 necessary discriminants. It should be NULL if value_type (VAL) is
7762 an outer-level type (i.e., as opposed to a branch of a variant.) A
7763 variant field (unless unchecked) is replaced by a particular branch
7764 of the variant.
7765
7766 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7767 length are not statically known are discarded. As a consequence,
7768 VALADDR, ADDRESS and DVAL0 are ignored.
7769
7770 NOTE: Limitations: For now, we assume that dynamic fields and
7771 variants occupy whole numbers of bytes. However, they need not be
7772 byte-aligned. */
7773
7774 struct type *
7775 ada_template_to_fixed_record_type_1 (struct type *type,
7776 const gdb_byte *valaddr,
7777 CORE_ADDR address, struct value *dval0,
7778 int keep_dynamic_fields)
7779 {
7780 struct value *mark = value_mark ();
7781 struct value *dval;
7782 struct type *rtype;
7783 int nfields, bit_len;
7784 int variant_field;
7785 long off;
7786 int fld_bit_len;
7787 int f;
7788
7789 /* Compute the number of fields in this record type that are going
7790 to be processed: unless keep_dynamic_fields, this includes only
7791 fields whose position and length are static will be processed. */
7792 if (keep_dynamic_fields)
7793 nfields = type->num_fields ();
7794 else
7795 {
7796 nfields = 0;
7797 while (nfields < type->num_fields ()
7798 && !ada_is_variant_part (type, nfields)
7799 && !is_dynamic_field (type, nfields))
7800 nfields++;
7801 }
7802
7803 rtype = alloc_type_copy (type);
7804 rtype->set_code (TYPE_CODE_STRUCT);
7805 INIT_NONE_SPECIFIC (rtype);
7806 rtype->set_num_fields (nfields);
7807 rtype->set_fields
7808 ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7809 rtype->set_name (ada_type_name (type));
7810 rtype->set_is_fixed_instance (true);
7811
7812 off = 0;
7813 bit_len = 0;
7814 variant_field = -1;
7815
7816 for (f = 0; f < nfields; f += 1)
7817 {
7818 off = align_up (off, field_alignment (type, f))
7819 + TYPE_FIELD_BITPOS (type, f);
7820 SET_FIELD_BITPOS (rtype->field (f), off);
7821 TYPE_FIELD_BITSIZE (rtype, f) = 0;
7822
7823 if (ada_is_variant_part (type, f))
7824 {
7825 variant_field = f;
7826 fld_bit_len = 0;
7827 }
7828 else if (is_dynamic_field (type, f))
7829 {
7830 const gdb_byte *field_valaddr = valaddr;
7831 CORE_ADDR field_address = address;
7832 struct type *field_type =
7833 TYPE_TARGET_TYPE (type->field (f).type ());
7834
7835 if (dval0 == NULL)
7836 {
7837 /* rtype's length is computed based on the run-time
7838 value of discriminants. If the discriminants are not
7839 initialized, the type size may be completely bogus and
7840 GDB may fail to allocate a value for it. So check the
7841 size first before creating the value. */
7842 ada_ensure_varsize_limit (rtype);
7843 /* Using plain value_from_contents_and_address here
7844 causes problems because we will end up trying to
7845 resolve a type that is currently being
7846 constructed. */
7847 dval = value_from_contents_and_address_unresolved (rtype,
7848 valaddr,
7849 address);
7850 rtype = value_type (dval);
7851 }
7852 else
7853 dval = dval0;
7854
7855 /* If the type referenced by this field is an aligner type, we need
7856 to unwrap that aligner type, because its size might not be set.
7857 Keeping the aligner type would cause us to compute the wrong
7858 size for this field, impacting the offset of the all the fields
7859 that follow this one. */
7860 if (ada_is_aligner_type (field_type))
7861 {
7862 long field_offset = TYPE_FIELD_BITPOS (field_type, f);
7863
7864 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7865 field_address = cond_offset_target (field_address, field_offset);
7866 field_type = ada_aligned_type (field_type);
7867 }
7868
7869 field_valaddr = cond_offset_host (field_valaddr,
7870 off / TARGET_CHAR_BIT);
7871 field_address = cond_offset_target (field_address,
7872 off / TARGET_CHAR_BIT);
7873
7874 /* Get the fixed type of the field. Note that, in this case,
7875 we do not want to get the real type out of the tag: if
7876 the current field is the parent part of a tagged record,
7877 we will get the tag of the object. Clearly wrong: the real
7878 type of the parent is not the real type of the child. We
7879 would end up in an infinite loop. */
7880 field_type = ada_get_base_type (field_type);
7881 field_type = ada_to_fixed_type (field_type, field_valaddr,
7882 field_address, dval, 0);
7883 /* If the field size is already larger than the maximum
7884 object size, then the record itself will necessarily
7885 be larger than the maximum object size. We need to make
7886 this check now, because the size might be so ridiculously
7887 large (due to an uninitialized variable in the inferior)
7888 that it would cause an overflow when adding it to the
7889 record size. */
7890 ada_ensure_varsize_limit (field_type);
7891
7892 rtype->field (f).set_type (field_type);
7893 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7894 /* The multiplication can potentially overflow. But because
7895 the field length has been size-checked just above, and
7896 assuming that the maximum size is a reasonable value,
7897 an overflow should not happen in practice. So rather than
7898 adding overflow recovery code to this already complex code,
7899 we just assume that it's not going to happen. */
7900 fld_bit_len =
7901 TYPE_LENGTH (rtype->field (f).type ()) * TARGET_CHAR_BIT;
7902 }
7903 else
7904 {
7905 /* Note: If this field's type is a typedef, it is important
7906 to preserve the typedef layer.
7907
7908 Otherwise, we might be transforming a typedef to a fat
7909 pointer (encoding a pointer to an unconstrained array),
7910 into a basic fat pointer (encoding an unconstrained
7911 array). As both types are implemented using the same
7912 structure, the typedef is the only clue which allows us
7913 to distinguish between the two options. Stripping it
7914 would prevent us from printing this field appropriately. */
7915 rtype->field (f).set_type (type->field (f).type ());
7916 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7917 if (TYPE_FIELD_BITSIZE (type, f) > 0)
7918 fld_bit_len =
7919 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7920 else
7921 {
7922 struct type *field_type = type->field (f).type ();
7923
7924 /* We need to be careful of typedefs when computing
7925 the length of our field. If this is a typedef,
7926 get the length of the target type, not the length
7927 of the typedef. */
7928 if (field_type->code () == TYPE_CODE_TYPEDEF)
7929 field_type = ada_typedef_target_type (field_type);
7930
7931 fld_bit_len =
7932 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
7933 }
7934 }
7935 if (off + fld_bit_len > bit_len)
7936 bit_len = off + fld_bit_len;
7937 off += fld_bit_len;
7938 TYPE_LENGTH (rtype) =
7939 align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7940 }
7941
7942 /* We handle the variant part, if any, at the end because of certain
7943 odd cases in which it is re-ordered so as NOT to be the last field of
7944 the record. This can happen in the presence of representation
7945 clauses. */
7946 if (variant_field >= 0)
7947 {
7948 struct type *branch_type;
7949
7950 off = TYPE_FIELD_BITPOS (rtype, variant_field);
7951
7952 if (dval0 == NULL)
7953 {
7954 /* Using plain value_from_contents_and_address here causes
7955 problems because we will end up trying to resolve a type
7956 that is currently being constructed. */
7957 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7958 address);
7959 rtype = value_type (dval);
7960 }
7961 else
7962 dval = dval0;
7963
7964 branch_type =
7965 to_fixed_variant_branch_type
7966 (type->field (variant_field).type (),
7967 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7968 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7969 if (branch_type == NULL)
7970 {
7971 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7972 rtype->field (f - 1) = rtype->field (f);
7973 rtype->set_num_fields (rtype->num_fields () - 1);
7974 }
7975 else
7976 {
7977 rtype->field (variant_field).set_type (branch_type);
7978 TYPE_FIELD_NAME (rtype, variant_field) = "S";
7979 fld_bit_len =
7980 TYPE_LENGTH (rtype->field (variant_field).type ()) *
7981 TARGET_CHAR_BIT;
7982 if (off + fld_bit_len > bit_len)
7983 bit_len = off + fld_bit_len;
7984 TYPE_LENGTH (rtype) =
7985 align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7986 }
7987 }
7988
7989 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7990 should contain the alignment of that record, which should be a strictly
7991 positive value. If null or negative, then something is wrong, most
7992 probably in the debug info. In that case, we don't round up the size
7993 of the resulting type. If this record is not part of another structure,
7994 the current RTYPE length might be good enough for our purposes. */
7995 if (TYPE_LENGTH (type) <= 0)
7996 {
7997 if (rtype->name ())
7998 warning (_("Invalid type size for `%s' detected: %s."),
7999 rtype->name (), pulongest (TYPE_LENGTH (type)));
8000 else
8001 warning (_("Invalid type size for <unnamed> detected: %s."),
8002 pulongest (TYPE_LENGTH (type)));
8003 }
8004 else
8005 {
8006 TYPE_LENGTH (rtype) = align_up (TYPE_LENGTH (rtype),
8007 TYPE_LENGTH (type));
8008 }
8009
8010 value_free_to_mark (mark);
8011 if (TYPE_LENGTH (rtype) > varsize_limit)
8012 error (_("record type with dynamic size is larger than varsize-limit"));
8013 return rtype;
8014 }
8015
8016 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8017 of 1. */
8018
8019 static struct type *
8020 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8021 CORE_ADDR address, struct value *dval0)
8022 {
8023 return ada_template_to_fixed_record_type_1 (type, valaddr,
8024 address, dval0, 1);
8025 }
8026
8027 /* An ordinary record type in which ___XVL-convention fields and
8028 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8029 static approximations, containing all possible fields. Uses
8030 no runtime values. Useless for use in values, but that's OK,
8031 since the results are used only for type determinations. Works on both
8032 structs and unions. Representation note: to save space, we memorize
8033 the result of this function in the TYPE_TARGET_TYPE of the
8034 template type. */
8035
8036 static struct type *
8037 template_to_static_fixed_type (struct type *type0)
8038 {
8039 struct type *type;
8040 int nfields;
8041 int f;
8042
8043 /* No need no do anything if the input type is already fixed. */
8044 if (type0->is_fixed_instance ())
8045 return type0;
8046
8047 /* Likewise if we already have computed the static approximation. */
8048 if (TYPE_TARGET_TYPE (type0) != NULL)
8049 return TYPE_TARGET_TYPE (type0);
8050
8051 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8052 type = type0;
8053 nfields = type0->num_fields ();
8054
8055 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8056 recompute all over next time. */
8057 TYPE_TARGET_TYPE (type0) = type;
8058
8059 for (f = 0; f < nfields; f += 1)
8060 {
8061 struct type *field_type = type0->field (f).type ();
8062 struct type *new_type;
8063
8064 if (is_dynamic_field (type0, f))
8065 {
8066 field_type = ada_check_typedef (field_type);
8067 new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
8068 }
8069 else
8070 new_type = static_unwrap_type (field_type);
8071
8072 if (new_type != field_type)
8073 {
8074 /* Clone TYPE0 only the first time we get a new field type. */
8075 if (type == type0)
8076 {
8077 TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
8078 type->set_code (type0->code ());
8079 INIT_NONE_SPECIFIC (type);
8080 type->set_num_fields (nfields);
8081
8082 field *fields =
8083 ((struct field *)
8084 TYPE_ALLOC (type, nfields * sizeof (struct field)));
8085 memcpy (fields, type0->fields (),
8086 sizeof (struct field) * nfields);
8087 type->set_fields (fields);
8088
8089 type->set_name (ada_type_name (type0));
8090 type->set_is_fixed_instance (true);
8091 TYPE_LENGTH (type) = 0;
8092 }
8093 type->field (f).set_type (new_type);
8094 TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
8095 }
8096 }
8097
8098 return type;
8099 }
8100
8101 /* Given an object of type TYPE whose contents are at VALADDR and
8102 whose address in memory is ADDRESS, returns a revision of TYPE,
8103 which should be a non-dynamic-sized record, in which the variant
8104 part, if any, is replaced with the appropriate branch. Looks
8105 for discriminant values in DVAL0, which can be NULL if the record
8106 contains the necessary discriminant values. */
8107
8108 static struct type *
8109 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8110 CORE_ADDR address, struct value *dval0)
8111 {
8112 struct value *mark = value_mark ();
8113 struct value *dval;
8114 struct type *rtype;
8115 struct type *branch_type;
8116 int nfields = type->num_fields ();
8117 int variant_field = variant_field_index (type);
8118
8119 if (variant_field == -1)
8120 return type;
8121
8122 if (dval0 == NULL)
8123 {
8124 dval = value_from_contents_and_address (type, valaddr, address);
8125 type = value_type (dval);
8126 }
8127 else
8128 dval = dval0;
8129
8130 rtype = alloc_type_copy (type);
8131 rtype->set_code (TYPE_CODE_STRUCT);
8132 INIT_NONE_SPECIFIC (rtype);
8133 rtype->set_num_fields (nfields);
8134
8135 field *fields =
8136 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8137 memcpy (fields, type->fields (), sizeof (struct field) * nfields);
8138 rtype->set_fields (fields);
8139
8140 rtype->set_name (ada_type_name (type));
8141 rtype->set_is_fixed_instance (true);
8142 TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
8143
8144 branch_type = to_fixed_variant_branch_type
8145 (type->field (variant_field).type (),
8146 cond_offset_host (valaddr,
8147 TYPE_FIELD_BITPOS (type, variant_field)
8148 / TARGET_CHAR_BIT),
8149 cond_offset_target (address,
8150 TYPE_FIELD_BITPOS (type, variant_field)
8151 / TARGET_CHAR_BIT), dval);
8152 if (branch_type == NULL)
8153 {
8154 int f;
8155
8156 for (f = variant_field + 1; f < nfields; f += 1)
8157 rtype->field (f - 1) = rtype->field (f);
8158 rtype->set_num_fields (rtype->num_fields () - 1);
8159 }
8160 else
8161 {
8162 rtype->field (variant_field).set_type (branch_type);
8163 TYPE_FIELD_NAME (rtype, variant_field) = "S";
8164 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8165 TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
8166 }
8167 TYPE_LENGTH (rtype) -= TYPE_LENGTH (type->field (variant_field).type ());
8168
8169 value_free_to_mark (mark);
8170 return rtype;
8171 }
8172
8173 /* An ordinary record type (with fixed-length fields) that describes
8174 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8175 beginning of this section]. Any necessary discriminants' values
8176 should be in DVAL, a record value; it may be NULL if the object
8177 at ADDR itself contains any necessary discriminant values.
8178 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8179 values from the record are needed. Except in the case that DVAL,
8180 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8181 unchecked) is replaced by a particular branch of the variant.
8182
8183 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8184 is questionable and may be removed. It can arise during the
8185 processing of an unconstrained-array-of-record type where all the
8186 variant branches have exactly the same size. This is because in
8187 such cases, the compiler does not bother to use the XVS convention
8188 when encoding the record. I am currently dubious of this
8189 shortcut and suspect the compiler should be altered. FIXME. */
8190
8191 static struct type *
8192 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8193 CORE_ADDR address, struct value *dval)
8194 {
8195 struct type *templ_type;
8196
8197 if (type0->is_fixed_instance ())
8198 return type0;
8199
8200 templ_type = dynamic_template_type (type0);
8201
8202 if (templ_type != NULL)
8203 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8204 else if (variant_field_index (type0) >= 0)
8205 {
8206 if (dval == NULL && valaddr == NULL && address == 0)
8207 return type0;
8208 return to_record_with_fixed_variant_part (type0, valaddr, address,
8209 dval);
8210 }
8211 else
8212 {
8213 type0->set_is_fixed_instance (true);
8214 return type0;
8215 }
8216
8217 }
8218
8219 /* An ordinary record type (with fixed-length fields) that describes
8220 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8221 union type. Any necessary discriminants' values should be in DVAL,
8222 a record value. That is, this routine selects the appropriate
8223 branch of the union at ADDR according to the discriminant value
8224 indicated in the union's type name. Returns VAR_TYPE0 itself if
8225 it represents a variant subject to a pragma Unchecked_Union. */
8226
8227 static struct type *
8228 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8229 CORE_ADDR address, struct value *dval)
8230 {
8231 int which;
8232 struct type *templ_type;
8233 struct type *var_type;
8234
8235 if (var_type0->code () == TYPE_CODE_PTR)
8236 var_type = TYPE_TARGET_TYPE (var_type0);
8237 else
8238 var_type = var_type0;
8239
8240 templ_type = ada_find_parallel_type (var_type, "___XVU");
8241
8242 if (templ_type != NULL)
8243 var_type = templ_type;
8244
8245 if (is_unchecked_variant (var_type, value_type (dval)))
8246 return var_type0;
8247 which = ada_which_variant_applies (var_type, dval);
8248
8249 if (which < 0)
8250 return empty_record (var_type);
8251 else if (is_dynamic_field (var_type, which))
8252 return to_fixed_record_type
8253 (TYPE_TARGET_TYPE (var_type->field (which).type ()),
8254 valaddr, address, dval);
8255 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8256 return
8257 to_fixed_record_type
8258 (var_type->field (which).type (), valaddr, address, dval);
8259 else
8260 return var_type->field (which).type ();
8261 }
8262
8263 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8264 ENCODING_TYPE, a type following the GNAT conventions for discrete
8265 type encodings, only carries redundant information. */
8266
8267 static int
8268 ada_is_redundant_range_encoding (struct type *range_type,
8269 struct type *encoding_type)
8270 {
8271 const char *bounds_str;
8272 int n;
8273 LONGEST lo, hi;
8274
8275 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8276
8277 if (get_base_type (range_type)->code ()
8278 != get_base_type (encoding_type)->code ())
8279 {
8280 /* The compiler probably used a simple base type to describe
8281 the range type instead of the range's actual base type,
8282 expecting us to get the real base type from the encoding
8283 anyway. In this situation, the encoding cannot be ignored
8284 as redundant. */
8285 return 0;
8286 }
8287
8288 if (is_dynamic_type (range_type))
8289 return 0;
8290
8291 if (encoding_type->name () == NULL)
8292 return 0;
8293
8294 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8295 if (bounds_str == NULL)
8296 return 0;
8297
8298 n = 8; /* Skip "___XDLU_". */
8299 if (!ada_scan_number (bounds_str, n, &lo, &n))
8300 return 0;
8301 if (range_type->bounds ()->low.const_val () != lo)
8302 return 0;
8303
8304 n += 2; /* Skip the "__" separator between the two bounds. */
8305 if (!ada_scan_number (bounds_str, n, &hi, &n))
8306 return 0;
8307 if (range_type->bounds ()->high.const_val () != hi)
8308 return 0;
8309
8310 return 1;
8311 }
8312
8313 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8314 a type following the GNAT encoding for describing array type
8315 indices, only carries redundant information. */
8316
8317 static int
8318 ada_is_redundant_index_type_desc (struct type *array_type,
8319 struct type *desc_type)
8320 {
8321 struct type *this_layer = check_typedef (array_type);
8322 int i;
8323
8324 for (i = 0; i < desc_type->num_fields (); i++)
8325 {
8326 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8327 desc_type->field (i).type ()))
8328 return 0;
8329 this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
8330 }
8331
8332 return 1;
8333 }
8334
8335 /* Assuming that TYPE0 is an array type describing the type of a value
8336 at ADDR, and that DVAL describes a record containing any
8337 discriminants used in TYPE0, returns a type for the value that
8338 contains no dynamic components (that is, no components whose sizes
8339 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8340 true, gives an error message if the resulting type's size is over
8341 varsize_limit. */
8342
8343 static struct type *
8344 to_fixed_array_type (struct type *type0, struct value *dval,
8345 int ignore_too_big)
8346 {
8347 struct type *index_type_desc;
8348 struct type *result;
8349 int constrained_packed_array_p;
8350 static const char *xa_suffix = "___XA";
8351
8352 type0 = ada_check_typedef (type0);
8353 if (type0->is_fixed_instance ())
8354 return type0;
8355
8356 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8357 if (constrained_packed_array_p)
8358 {
8359 type0 = decode_constrained_packed_array_type (type0);
8360 if (type0 == nullptr)
8361 error (_("could not decode constrained packed array type"));
8362 }
8363
8364 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8365
8366 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8367 encoding suffixed with 'P' may still be generated. If so,
8368 it should be used to find the XA type. */
8369
8370 if (index_type_desc == NULL)
8371 {
8372 const char *type_name = ada_type_name (type0);
8373
8374 if (type_name != NULL)
8375 {
8376 const int len = strlen (type_name);
8377 char *name = (char *) alloca (len + strlen (xa_suffix));
8378
8379 if (type_name[len - 1] == 'P')
8380 {
8381 strcpy (name, type_name);
8382 strcpy (name + len - 1, xa_suffix);
8383 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8384 }
8385 }
8386 }
8387
8388 ada_fixup_array_indexes_type (index_type_desc);
8389 if (index_type_desc != NULL
8390 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8391 {
8392 /* Ignore this ___XA parallel type, as it does not bring any
8393 useful information. This allows us to avoid creating fixed
8394 versions of the array's index types, which would be identical
8395 to the original ones. This, in turn, can also help avoid
8396 the creation of fixed versions of the array itself. */
8397 index_type_desc = NULL;
8398 }
8399
8400 if (index_type_desc == NULL)
8401 {
8402 struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8403
8404 /* NOTE: elt_type---the fixed version of elt_type0---should never
8405 depend on the contents of the array in properly constructed
8406 debugging data. */
8407 /* Create a fixed version of the array element type.
8408 We're not providing the address of an element here,
8409 and thus the actual object value cannot be inspected to do
8410 the conversion. This should not be a problem, since arrays of
8411 unconstrained objects are not allowed. In particular, all
8412 the elements of an array of a tagged type should all be of
8413 the same type specified in the debugging info. No need to
8414 consult the object tag. */
8415 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8416
8417 /* Make sure we always create a new array type when dealing with
8418 packed array types, since we're going to fix-up the array
8419 type length and element bitsize a little further down. */
8420 if (elt_type0 == elt_type && !constrained_packed_array_p)
8421 result = type0;
8422 else
8423 result = create_array_type (alloc_type_copy (type0),
8424 elt_type, type0->index_type ());
8425 }
8426 else
8427 {
8428 int i;
8429 struct type *elt_type0;
8430
8431 elt_type0 = type0;
8432 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8433 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8434
8435 /* NOTE: result---the fixed version of elt_type0---should never
8436 depend on the contents of the array in properly constructed
8437 debugging data. */
8438 /* Create a fixed version of the array element type.
8439 We're not providing the address of an element here,
8440 and thus the actual object value cannot be inspected to do
8441 the conversion. This should not be a problem, since arrays of
8442 unconstrained objects are not allowed. In particular, all
8443 the elements of an array of a tagged type should all be of
8444 the same type specified in the debugging info. No need to
8445 consult the object tag. */
8446 result =
8447 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8448
8449 elt_type0 = type0;
8450 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8451 {
8452 struct type *range_type =
8453 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8454
8455 result = create_array_type (alloc_type_copy (elt_type0),
8456 result, range_type);
8457 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8458 }
8459 if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
8460 error (_("array type with dynamic size is larger than varsize-limit"));
8461 }
8462
8463 /* We want to preserve the type name. This can be useful when
8464 trying to get the type name of a value that has already been
8465 printed (for instance, if the user did "print VAR; whatis $". */
8466 result->set_name (type0->name ());
8467
8468 if (constrained_packed_array_p)
8469 {
8470 /* So far, the resulting type has been created as if the original
8471 type was a regular (non-packed) array type. As a result, the
8472 bitsize of the array elements needs to be set again, and the array
8473 length needs to be recomputed based on that bitsize. */
8474 int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8475 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8476
8477 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8478 TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8479 if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8480 TYPE_LENGTH (result)++;
8481 }
8482
8483 result->set_is_fixed_instance (true);
8484 return result;
8485 }
8486
8487
8488 /* A standard type (containing no dynamically sized components)
8489 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8490 DVAL describes a record containing any discriminants used in TYPE0,
8491 and may be NULL if there are none, or if the object of type TYPE at
8492 ADDRESS or in VALADDR contains these discriminants.
8493
8494 If CHECK_TAG is not null, in the case of tagged types, this function
8495 attempts to locate the object's tag and use it to compute the actual
8496 type. However, when ADDRESS is null, we cannot use it to determine the
8497 location of the tag, and therefore compute the tagged type's actual type.
8498 So we return the tagged type without consulting the tag. */
8499
8500 static struct type *
8501 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8502 CORE_ADDR address, struct value *dval, int check_tag)
8503 {
8504 type = ada_check_typedef (type);
8505
8506 /* Only un-fixed types need to be handled here. */
8507 if (!HAVE_GNAT_AUX_INFO (type))
8508 return type;
8509
8510 switch (type->code ())
8511 {
8512 default:
8513 return type;
8514 case TYPE_CODE_STRUCT:
8515 {
8516 struct type *static_type = to_static_fixed_type (type);
8517 struct type *fixed_record_type =
8518 to_fixed_record_type (type, valaddr, address, NULL);
8519
8520 /* If STATIC_TYPE is a tagged type and we know the object's address,
8521 then we can determine its tag, and compute the object's actual
8522 type from there. Note that we have to use the fixed record
8523 type (the parent part of the record may have dynamic fields
8524 and the way the location of _tag is expressed may depend on
8525 them). */
8526
8527 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8528 {
8529 struct value *tag =
8530 value_tag_from_contents_and_address
8531 (fixed_record_type,
8532 valaddr,
8533 address);
8534 struct type *real_type = type_from_tag (tag);
8535 struct value *obj =
8536 value_from_contents_and_address (fixed_record_type,
8537 valaddr,
8538 address);
8539 fixed_record_type = value_type (obj);
8540 if (real_type != NULL)
8541 return to_fixed_record_type
8542 (real_type, NULL,
8543 value_address (ada_tag_value_at_base_address (obj)), NULL);
8544 }
8545
8546 /* Check to see if there is a parallel ___XVZ variable.
8547 If there is, then it provides the actual size of our type. */
8548 else if (ada_type_name (fixed_record_type) != NULL)
8549 {
8550 const char *name = ada_type_name (fixed_record_type);
8551 char *xvz_name
8552 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8553 bool xvz_found = false;
8554 LONGEST size;
8555
8556 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8557 try
8558 {
8559 xvz_found = get_int_var_value (xvz_name, size);
8560 }
8561 catch (const gdb_exception_error &except)
8562 {
8563 /* We found the variable, but somehow failed to read
8564 its value. Rethrow the same error, but with a little
8565 bit more information, to help the user understand
8566 what went wrong (Eg: the variable might have been
8567 optimized out). */
8568 throw_error (except.error,
8569 _("unable to read value of %s (%s)"),
8570 xvz_name, except.what ());
8571 }
8572
8573 if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
8574 {
8575 fixed_record_type = copy_type (fixed_record_type);
8576 TYPE_LENGTH (fixed_record_type) = size;
8577
8578 /* The FIXED_RECORD_TYPE may have be a stub. We have
8579 observed this when the debugging info is STABS, and
8580 apparently it is something that is hard to fix.
8581
8582 In practice, we don't need the actual type definition
8583 at all, because the presence of the XVZ variable allows us
8584 to assume that there must be a XVS type as well, which we
8585 should be able to use later, when we need the actual type
8586 definition.
8587
8588 In the meantime, pretend that the "fixed" type we are
8589 returning is NOT a stub, because this can cause trouble
8590 when using this type to create new types targeting it.
8591 Indeed, the associated creation routines often check
8592 whether the target type is a stub and will try to replace
8593 it, thus using a type with the wrong size. This, in turn,
8594 might cause the new type to have the wrong size too.
8595 Consider the case of an array, for instance, where the size
8596 of the array is computed from the number of elements in
8597 our array multiplied by the size of its element. */
8598 fixed_record_type->set_is_stub (false);
8599 }
8600 }
8601 return fixed_record_type;
8602 }
8603 case TYPE_CODE_ARRAY:
8604 return to_fixed_array_type (type, dval, 1);
8605 case TYPE_CODE_UNION:
8606 if (dval == NULL)
8607 return type;
8608 else
8609 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8610 }
8611 }
8612
8613 /* The same as ada_to_fixed_type_1, except that it preserves the type
8614 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8615
8616 The typedef layer needs be preserved in order to differentiate between
8617 arrays and array pointers when both types are implemented using the same
8618 fat pointer. In the array pointer case, the pointer is encoded as
8619 a typedef of the pointer type. For instance, considering:
8620
8621 type String_Access is access String;
8622 S1 : String_Access := null;
8623
8624 To the debugger, S1 is defined as a typedef of type String. But
8625 to the user, it is a pointer. So if the user tries to print S1,
8626 we should not dereference the array, but print the array address
8627 instead.
8628
8629 If we didn't preserve the typedef layer, we would lose the fact that
8630 the type is to be presented as a pointer (needs de-reference before
8631 being printed). And we would also use the source-level type name. */
8632
8633 struct type *
8634 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8635 CORE_ADDR address, struct value *dval, int check_tag)
8636
8637 {
8638 struct type *fixed_type =
8639 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8640
8641 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8642 then preserve the typedef layer.
8643
8644 Implementation note: We can only check the main-type portion of
8645 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8646 from TYPE now returns a type that has the same instance flags
8647 as TYPE. For instance, if TYPE is a "typedef const", and its
8648 target type is a "struct", then the typedef elimination will return
8649 a "const" version of the target type. See check_typedef for more
8650 details about how the typedef layer elimination is done.
8651
8652 brobecker/2010-11-19: It seems to me that the only case where it is
8653 useful to preserve the typedef layer is when dealing with fat pointers.
8654 Perhaps, we could add a check for that and preserve the typedef layer
8655 only in that situation. But this seems unnecessary so far, probably
8656 because we call check_typedef/ada_check_typedef pretty much everywhere.
8657 */
8658 if (type->code () == TYPE_CODE_TYPEDEF
8659 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8660 == TYPE_MAIN_TYPE (fixed_type)))
8661 return type;
8662
8663 return fixed_type;
8664 }
8665
8666 /* A standard (static-sized) type corresponding as well as possible to
8667 TYPE0, but based on no runtime data. */
8668
8669 static struct type *
8670 to_static_fixed_type (struct type *type0)
8671 {
8672 struct type *type;
8673
8674 if (type0 == NULL)
8675 return NULL;
8676
8677 if (type0->is_fixed_instance ())
8678 return type0;
8679
8680 type0 = ada_check_typedef (type0);
8681
8682 switch (type0->code ())
8683 {
8684 default:
8685 return type0;
8686 case TYPE_CODE_STRUCT:
8687 type = dynamic_template_type (type0);
8688 if (type != NULL)
8689 return template_to_static_fixed_type (type);
8690 else
8691 return template_to_static_fixed_type (type0);
8692 case TYPE_CODE_UNION:
8693 type = ada_find_parallel_type (type0, "___XVU");
8694 if (type != NULL)
8695 return template_to_static_fixed_type (type);
8696 else
8697 return template_to_static_fixed_type (type0);
8698 }
8699 }
8700
8701 /* A static approximation of TYPE with all type wrappers removed. */
8702
8703 static struct type *
8704 static_unwrap_type (struct type *type)
8705 {
8706 if (ada_is_aligner_type (type))
8707 {
8708 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8709 if (ada_type_name (type1) == NULL)
8710 type1->set_name (ada_type_name (type));
8711
8712 return static_unwrap_type (type1);
8713 }
8714 else
8715 {
8716 struct type *raw_real_type = ada_get_base_type (type);
8717
8718 if (raw_real_type == type)
8719 return type;
8720 else
8721 return to_static_fixed_type (raw_real_type);
8722 }
8723 }
8724
8725 /* In some cases, incomplete and private types require
8726 cross-references that are not resolved as records (for example,
8727 type Foo;
8728 type FooP is access Foo;
8729 V: FooP;
8730 type Foo is array ...;
8731 ). In these cases, since there is no mechanism for producing
8732 cross-references to such types, we instead substitute for FooP a
8733 stub enumeration type that is nowhere resolved, and whose tag is
8734 the name of the actual type. Call these types "non-record stubs". */
8735
8736 /* A type equivalent to TYPE that is not a non-record stub, if one
8737 exists, otherwise TYPE. */
8738
8739 struct type *
8740 ada_check_typedef (struct type *type)
8741 {
8742 if (type == NULL)
8743 return NULL;
8744
8745 /* If our type is an access to an unconstrained array, which is encoded
8746 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8747 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8748 what allows us to distinguish between fat pointers that represent
8749 array types, and fat pointers that represent array access types
8750 (in both cases, the compiler implements them as fat pointers). */
8751 if (ada_is_access_to_unconstrained_array (type))
8752 return type;
8753
8754 type = check_typedef (type);
8755 if (type == NULL || type->code () != TYPE_CODE_ENUM
8756 || !type->is_stub ()
8757 || type->name () == NULL)
8758 return type;
8759 else
8760 {
8761 const char *name = type->name ();
8762 struct type *type1 = ada_find_any_type (name);
8763
8764 if (type1 == NULL)
8765 return type;
8766
8767 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8768 stubs pointing to arrays, as we don't create symbols for array
8769 types, only for the typedef-to-array types). If that's the case,
8770 strip the typedef layer. */
8771 if (type1->code () == TYPE_CODE_TYPEDEF)
8772 type1 = ada_check_typedef (type1);
8773
8774 return type1;
8775 }
8776 }
8777
8778 /* A value representing the data at VALADDR/ADDRESS as described by
8779 type TYPE0, but with a standard (static-sized) type that correctly
8780 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8781 type, then return VAL0 [this feature is simply to avoid redundant
8782 creation of struct values]. */
8783
8784 static struct value *
8785 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8786 struct value *val0)
8787 {
8788 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8789
8790 if (type == type0 && val0 != NULL)
8791 return val0;
8792
8793 if (VALUE_LVAL (val0) != lval_memory)
8794 {
8795 /* Our value does not live in memory; it could be a convenience
8796 variable, for instance. Create a not_lval value using val0's
8797 contents. */
8798 return value_from_contents (type, value_contents (val0));
8799 }
8800
8801 return value_from_contents_and_address (type, 0, address);
8802 }
8803
8804 /* A value representing VAL, but with a standard (static-sized) type
8805 that correctly describes it. Does not necessarily create a new
8806 value. */
8807
8808 struct value *
8809 ada_to_fixed_value (struct value *val)
8810 {
8811 val = unwrap_value (val);
8812 val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
8813 return val;
8814 }
8815 \f
8816
8817 /* Attributes */
8818
8819 /* Table mapping attribute numbers to names.
8820 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
8821
8822 static const char * const attribute_names[] = {
8823 "<?>",
8824
8825 "first",
8826 "last",
8827 "length",
8828 "image",
8829 "max",
8830 "min",
8831 "modulus",
8832 "pos",
8833 "size",
8834 "tag",
8835 "val",
8836 0
8837 };
8838
8839 static const char *
8840 ada_attribute_name (enum exp_opcode n)
8841 {
8842 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8843 return attribute_names[n - OP_ATR_FIRST + 1];
8844 else
8845 return attribute_names[0];
8846 }
8847
8848 /* Evaluate the 'POS attribute applied to ARG. */
8849
8850 static LONGEST
8851 pos_atr (struct value *arg)
8852 {
8853 struct value *val = coerce_ref (arg);
8854 struct type *type = value_type (val);
8855
8856 if (!discrete_type_p (type))
8857 error (_("'POS only defined on discrete types"));
8858
8859 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8860 if (!result.has_value ())
8861 error (_("enumeration value is invalid: can't find 'POS"));
8862
8863 return *result;
8864 }
8865
8866 struct value *
8867 ada_pos_atr (struct type *expect_type,
8868 struct expression *exp,
8869 enum noside noside, enum exp_opcode op,
8870 struct value *arg)
8871 {
8872 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8873 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8874 return value_zero (type, not_lval);
8875 return value_from_longest (type, pos_atr (arg));
8876 }
8877
8878 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8879
8880 static struct value *
8881 val_atr (struct type *type, LONGEST val)
8882 {
8883 gdb_assert (discrete_type_p (type));
8884 if (type->code () == TYPE_CODE_RANGE)
8885 type = TYPE_TARGET_TYPE (type);
8886 if (type->code () == TYPE_CODE_ENUM)
8887 {
8888 if (val < 0 || val >= type->num_fields ())
8889 error (_("argument to 'VAL out of range"));
8890 val = TYPE_FIELD_ENUMVAL (type, val);
8891 }
8892 return value_from_longest (type, val);
8893 }
8894
8895 struct value *
8896 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8897 {
8898 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8899 return value_zero (type, not_lval);
8900
8901 if (!discrete_type_p (type))
8902 error (_("'VAL only defined on discrete types"));
8903 if (!integer_type_p (value_type (arg)))
8904 error (_("'VAL requires integral argument"));
8905
8906 return val_atr (type, value_as_long (arg));
8907 }
8908 \f
8909
8910 /* Evaluation */
8911
8912 /* True if TYPE appears to be an Ada character type.
8913 [At the moment, this is true only for Character and Wide_Character;
8914 It is a heuristic test that could stand improvement]. */
8915
8916 bool
8917 ada_is_character_type (struct type *type)
8918 {
8919 const char *name;
8920
8921 /* If the type code says it's a character, then assume it really is,
8922 and don't check any further. */
8923 if (type->code () == TYPE_CODE_CHAR)
8924 return true;
8925
8926 /* Otherwise, assume it's a character type iff it is a discrete type
8927 with a known character type name. */
8928 name = ada_type_name (type);
8929 return (name != NULL
8930 && (type->code () == TYPE_CODE_INT
8931 || type->code () == TYPE_CODE_RANGE)
8932 && (strcmp (name, "character") == 0
8933 || strcmp (name, "wide_character") == 0
8934 || strcmp (name, "wide_wide_character") == 0
8935 || strcmp (name, "unsigned char") == 0));
8936 }
8937
8938 /* True if TYPE appears to be an Ada string type. */
8939
8940 bool
8941 ada_is_string_type (struct type *type)
8942 {
8943 type = ada_check_typedef (type);
8944 if (type != NULL
8945 && type->code () != TYPE_CODE_PTR
8946 && (ada_is_simple_array_type (type)
8947 || ada_is_array_descriptor_type (type))
8948 && ada_array_arity (type) == 1)
8949 {
8950 struct type *elttype = ada_array_element_type (type, 1);
8951
8952 return ada_is_character_type (elttype);
8953 }
8954 else
8955 return false;
8956 }
8957
8958 /* The compiler sometimes provides a parallel XVS type for a given
8959 PAD type. Normally, it is safe to follow the PAD type directly,
8960 but older versions of the compiler have a bug that causes the offset
8961 of its "F" field to be wrong. Following that field in that case
8962 would lead to incorrect results, but this can be worked around
8963 by ignoring the PAD type and using the associated XVS type instead.
8964
8965 Set to True if the debugger should trust the contents of PAD types.
8966 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8967 static bool trust_pad_over_xvs = true;
8968
8969 /* True if TYPE is a struct type introduced by the compiler to force the
8970 alignment of a value. Such types have a single field with a
8971 distinctive name. */
8972
8973 int
8974 ada_is_aligner_type (struct type *type)
8975 {
8976 type = ada_check_typedef (type);
8977
8978 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8979 return 0;
8980
8981 return (type->code () == TYPE_CODE_STRUCT
8982 && type->num_fields () == 1
8983 && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
8984 }
8985
8986 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8987 the parallel type. */
8988
8989 struct type *
8990 ada_get_base_type (struct type *raw_type)
8991 {
8992 struct type *real_type_namer;
8993 struct type *raw_real_type;
8994
8995 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8996 return raw_type;
8997
8998 if (ada_is_aligner_type (raw_type))
8999 /* The encoding specifies that we should always use the aligner type.
9000 So, even if this aligner type has an associated XVS type, we should
9001 simply ignore it.
9002
9003 According to the compiler gurus, an XVS type parallel to an aligner
9004 type may exist because of a stabs limitation. In stabs, aligner
9005 types are empty because the field has a variable-sized type, and
9006 thus cannot actually be used as an aligner type. As a result,
9007 we need the associated parallel XVS type to decode the type.
9008 Since the policy in the compiler is to not change the internal
9009 representation based on the debugging info format, we sometimes
9010 end up having a redundant XVS type parallel to the aligner type. */
9011 return raw_type;
9012
9013 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9014 if (real_type_namer == NULL
9015 || real_type_namer->code () != TYPE_CODE_STRUCT
9016 || real_type_namer->num_fields () != 1)
9017 return raw_type;
9018
9019 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
9020 {
9021 /* This is an older encoding form where the base type needs to be
9022 looked up by name. We prefer the newer encoding because it is
9023 more efficient. */
9024 raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
9025 if (raw_real_type == NULL)
9026 return raw_type;
9027 else
9028 return raw_real_type;
9029 }
9030
9031 /* The field in our XVS type is a reference to the base type. */
9032 return TYPE_TARGET_TYPE (real_type_namer->field (0).type ());
9033 }
9034
9035 /* The type of value designated by TYPE, with all aligners removed. */
9036
9037 struct type *
9038 ada_aligned_type (struct type *type)
9039 {
9040 if (ada_is_aligner_type (type))
9041 return ada_aligned_type (type->field (0).type ());
9042 else
9043 return ada_get_base_type (type);
9044 }
9045
9046
9047 /* The address of the aligned value in an object at address VALADDR
9048 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9049
9050 const gdb_byte *
9051 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9052 {
9053 if (ada_is_aligner_type (type))
9054 return ada_aligned_value_addr (type->field (0).type (),
9055 valaddr +
9056 TYPE_FIELD_BITPOS (type,
9057 0) / TARGET_CHAR_BIT);
9058 else
9059 return valaddr;
9060 }
9061
9062
9063
9064 /* The printed representation of an enumeration literal with encoded
9065 name NAME. The value is good to the next call of ada_enum_name. */
9066 const char *
9067 ada_enum_name (const char *name)
9068 {
9069 static std::string storage;
9070 const char *tmp;
9071
9072 /* First, unqualify the enumeration name:
9073 1. Search for the last '.' character. If we find one, then skip
9074 all the preceding characters, the unqualified name starts
9075 right after that dot.
9076 2. Otherwise, we may be debugging on a target where the compiler
9077 translates dots into "__". Search forward for double underscores,
9078 but stop searching when we hit an overloading suffix, which is
9079 of the form "__" followed by digits. */
9080
9081 tmp = strrchr (name, '.');
9082 if (tmp != NULL)
9083 name = tmp + 1;
9084 else
9085 {
9086 while ((tmp = strstr (name, "__")) != NULL)
9087 {
9088 if (isdigit (tmp[2]))
9089 break;
9090 else
9091 name = tmp + 2;
9092 }
9093 }
9094
9095 if (name[0] == 'Q')
9096 {
9097 int v;
9098
9099 if (name[1] == 'U' || name[1] == 'W')
9100 {
9101 if (sscanf (name + 2, "%x", &v) != 1)
9102 return name;
9103 }
9104 else if (((name[1] >= '0' && name[1] <= '9')
9105 || (name[1] >= 'a' && name[1] <= 'z'))
9106 && name[2] == '\0')
9107 {
9108 storage = string_printf ("'%c'", name[1]);
9109 return storage.c_str ();
9110 }
9111 else
9112 return name;
9113
9114 if (isascii (v) && isprint (v))
9115 storage = string_printf ("'%c'", v);
9116 else if (name[1] == 'U')
9117 storage = string_printf ("[\"%02x\"]", v);
9118 else
9119 storage = string_printf ("[\"%04x\"]", v);
9120
9121 return storage.c_str ();
9122 }
9123 else
9124 {
9125 tmp = strstr (name, "__");
9126 if (tmp == NULL)
9127 tmp = strstr (name, "$");
9128 if (tmp != NULL)
9129 {
9130 storage = std::string (name, tmp - name);
9131 return storage.c_str ();
9132 }
9133
9134 return name;
9135 }
9136 }
9137
9138 /* Evaluate the subexpression of EXP starting at *POS as for
9139 evaluate_type, updating *POS to point just past the evaluated
9140 expression. */
9141
9142 static struct value *
9143 evaluate_subexp_type (struct expression *exp, int *pos)
9144 {
9145 return evaluate_subexp (nullptr, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
9146 }
9147
9148 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9149 value it wraps. */
9150
9151 static struct value *
9152 unwrap_value (struct value *val)
9153 {
9154 struct type *type = ada_check_typedef (value_type (val));
9155
9156 if (ada_is_aligner_type (type))
9157 {
9158 struct value *v = ada_value_struct_elt (val, "F", 0);
9159 struct type *val_type = ada_check_typedef (value_type (v));
9160
9161 if (ada_type_name (val_type) == NULL)
9162 val_type->set_name (ada_type_name (type));
9163
9164 return unwrap_value (v);
9165 }
9166 else
9167 {
9168 struct type *raw_real_type =
9169 ada_check_typedef (ada_get_base_type (type));
9170
9171 /* If there is no parallel XVS or XVE type, then the value is
9172 already unwrapped. Return it without further modification. */
9173 if ((type == raw_real_type)
9174 && ada_find_parallel_type (type, "___XVE") == NULL)
9175 return val;
9176
9177 return
9178 coerce_unspec_val_to_type
9179 (val, ada_to_fixed_type (raw_real_type, 0,
9180 value_address (val),
9181 NULL, 1));
9182 }
9183 }
9184
9185 /* Given two array types T1 and T2, return nonzero iff both arrays
9186 contain the same number of elements. */
9187
9188 static int
9189 ada_same_array_size_p (struct type *t1, struct type *t2)
9190 {
9191 LONGEST lo1, hi1, lo2, hi2;
9192
9193 /* Get the array bounds in order to verify that the size of
9194 the two arrays match. */
9195 if (!get_array_bounds (t1, &lo1, &hi1)
9196 || !get_array_bounds (t2, &lo2, &hi2))
9197 error (_("unable to determine array bounds"));
9198
9199 /* To make things easier for size comparison, normalize a bit
9200 the case of empty arrays by making sure that the difference
9201 between upper bound and lower bound is always -1. */
9202 if (lo1 > hi1)
9203 hi1 = lo1 - 1;
9204 if (lo2 > hi2)
9205 hi2 = lo2 - 1;
9206
9207 return (hi1 - lo1 == hi2 - lo2);
9208 }
9209
9210 /* Assuming that VAL is an array of integrals, and TYPE represents
9211 an array with the same number of elements, but with wider integral
9212 elements, return an array "casted" to TYPE. In practice, this
9213 means that the returned array is built by casting each element
9214 of the original array into TYPE's (wider) element type. */
9215
9216 static struct value *
9217 ada_promote_array_of_integrals (struct type *type, struct value *val)
9218 {
9219 struct type *elt_type = TYPE_TARGET_TYPE (type);
9220 LONGEST lo, hi;
9221 struct value *res;
9222 LONGEST i;
9223
9224 /* Verify that both val and type are arrays of scalars, and
9225 that the size of val's elements is smaller than the size
9226 of type's element. */
9227 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9228 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
9229 gdb_assert (value_type (val)->code () == TYPE_CODE_ARRAY);
9230 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
9231 gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
9232 > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
9233
9234 if (!get_array_bounds (type, &lo, &hi))
9235 error (_("unable to determine array bounds"));
9236
9237 res = allocate_value (type);
9238
9239 /* Promote each array element. */
9240 for (i = 0; i < hi - lo + 1; i++)
9241 {
9242 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9243
9244 memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
9245 value_contents_all (elt), TYPE_LENGTH (elt_type));
9246 }
9247
9248 return res;
9249 }
9250
9251 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9252 return the converted value. */
9253
9254 static struct value *
9255 coerce_for_assign (struct type *type, struct value *val)
9256 {
9257 struct type *type2 = value_type (val);
9258
9259 if (type == type2)
9260 return val;
9261
9262 type2 = ada_check_typedef (type2);
9263 type = ada_check_typedef (type);
9264
9265 if (type2->code () == TYPE_CODE_PTR
9266 && type->code () == TYPE_CODE_ARRAY)
9267 {
9268 val = ada_value_ind (val);
9269 type2 = value_type (val);
9270 }
9271
9272 if (type2->code () == TYPE_CODE_ARRAY
9273 && type->code () == TYPE_CODE_ARRAY)
9274 {
9275 if (!ada_same_array_size_p (type, type2))
9276 error (_("cannot assign arrays of different length"));
9277
9278 if (is_integral_type (TYPE_TARGET_TYPE (type))
9279 && is_integral_type (TYPE_TARGET_TYPE (type2))
9280 && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9281 < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9282 {
9283 /* Allow implicit promotion of the array elements to
9284 a wider type. */
9285 return ada_promote_array_of_integrals (type, val);
9286 }
9287
9288 if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9289 != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9290 error (_("Incompatible types in assignment"));
9291 deprecated_set_value_type (val, type);
9292 }
9293 return val;
9294 }
9295
9296 static struct value *
9297 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9298 {
9299 struct value *val;
9300 struct type *type1, *type2;
9301 LONGEST v, v1, v2;
9302
9303 arg1 = coerce_ref (arg1);
9304 arg2 = coerce_ref (arg2);
9305 type1 = get_base_type (ada_check_typedef (value_type (arg1)));
9306 type2 = get_base_type (ada_check_typedef (value_type (arg2)));
9307
9308 if (type1->code () != TYPE_CODE_INT
9309 || type2->code () != TYPE_CODE_INT)
9310 return value_binop (arg1, arg2, op);
9311
9312 switch (op)
9313 {
9314 case BINOP_MOD:
9315 case BINOP_DIV:
9316 case BINOP_REM:
9317 break;
9318 default:
9319 return value_binop (arg1, arg2, op);
9320 }
9321
9322 v2 = value_as_long (arg2);
9323 if (v2 == 0)
9324 error (_("second operand of %s must not be zero."), op_string (op));
9325
9326 if (type1->is_unsigned () || op == BINOP_MOD)
9327 return value_binop (arg1, arg2, op);
9328
9329 v1 = value_as_long (arg1);
9330 switch (op)
9331 {
9332 case BINOP_DIV:
9333 v = v1 / v2;
9334 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9335 v += v > 0 ? -1 : 1;
9336 break;
9337 case BINOP_REM:
9338 v = v1 % v2;
9339 if (v * v1 < 0)
9340 v -= v2;
9341 break;
9342 default:
9343 /* Should not reach this point. */
9344 v = 0;
9345 }
9346
9347 val = allocate_value (type1);
9348 store_unsigned_integer (value_contents_raw (val),
9349 TYPE_LENGTH (value_type (val)),
9350 type_byte_order (type1), v);
9351 return val;
9352 }
9353
9354 static int
9355 ada_value_equal (struct value *arg1, struct value *arg2)
9356 {
9357 if (ada_is_direct_array_type (value_type (arg1))
9358 || ada_is_direct_array_type (value_type (arg2)))
9359 {
9360 struct type *arg1_type, *arg2_type;
9361
9362 /* Automatically dereference any array reference before
9363 we attempt to perform the comparison. */
9364 arg1 = ada_coerce_ref (arg1);
9365 arg2 = ada_coerce_ref (arg2);
9366
9367 arg1 = ada_coerce_to_simple_array (arg1);
9368 arg2 = ada_coerce_to_simple_array (arg2);
9369
9370 arg1_type = ada_check_typedef (value_type (arg1));
9371 arg2_type = ada_check_typedef (value_type (arg2));
9372
9373 if (arg1_type->code () != TYPE_CODE_ARRAY
9374 || arg2_type->code () != TYPE_CODE_ARRAY)
9375 error (_("Attempt to compare array with non-array"));
9376 /* FIXME: The following works only for types whose
9377 representations use all bits (no padding or undefined bits)
9378 and do not have user-defined equality. */
9379 return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9380 && memcmp (value_contents (arg1), value_contents (arg2),
9381 TYPE_LENGTH (arg1_type)) == 0);
9382 }
9383 return value_equal (arg1, arg2);
9384 }
9385
9386 /* Assign the result of evaluating EXP starting at *POS to the INDEXth
9387 component of LHS (a simple array or a record), updating *POS past
9388 the expression, assuming that LHS is contained in CONTAINER. Does
9389 not modify the inferior's memory, nor does it modify LHS (unless
9390 LHS == CONTAINER). */
9391
9392 static void
9393 assign_component (struct value *container, struct value *lhs, LONGEST index,
9394 struct expression *exp, int *pos)
9395 {
9396 struct value *mark = value_mark ();
9397 struct value *elt;
9398 struct type *lhs_type = check_typedef (value_type (lhs));
9399
9400 if (lhs_type->code () == TYPE_CODE_ARRAY)
9401 {
9402 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9403 struct value *index_val = value_from_longest (index_type, index);
9404
9405 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9406 }
9407 else
9408 {
9409 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9410 elt = ada_to_fixed_value (elt);
9411 }
9412
9413 if (exp->elts[*pos].opcode == OP_AGGREGATE)
9414 assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
9415 else
9416 value_assign_to_component (container, elt,
9417 ada_evaluate_subexp (NULL, exp, pos,
9418 EVAL_NORMAL));
9419
9420 value_free_to_mark (mark);
9421 }
9422
9423 /* Assuming that LHS represents an lvalue having a record or array
9424 type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
9425 of that aggregate's value to LHS, advancing *POS past the
9426 aggregate. NOSIDE is as for evaluate_subexp. CONTAINER is an
9427 lvalue containing LHS (possibly LHS itself). Does not modify
9428 the inferior's memory, nor does it modify the contents of
9429 LHS (unless == CONTAINER). Returns the modified CONTAINER. */
9430
9431 static struct value *
9432 assign_aggregate (struct value *container,
9433 struct value *lhs, struct expression *exp,
9434 int *pos, enum noside noside)
9435 {
9436 struct type *lhs_type;
9437 int n = exp->elts[*pos+1].longconst;
9438 LONGEST low_index, high_index;
9439 int i;
9440
9441 *pos += 3;
9442 if (noside != EVAL_NORMAL)
9443 {
9444 for (i = 0; i < n; i += 1)
9445 ada_evaluate_subexp (NULL, exp, pos, noside);
9446 return container;
9447 }
9448
9449 container = ada_coerce_ref (container);
9450 if (ada_is_direct_array_type (value_type (container)))
9451 container = ada_coerce_to_simple_array (container);
9452 lhs = ada_coerce_ref (lhs);
9453 if (!deprecated_value_modifiable (lhs))
9454 error (_("Left operand of assignment is not a modifiable lvalue."));
9455
9456 lhs_type = check_typedef (value_type (lhs));
9457 if (ada_is_direct_array_type (lhs_type))
9458 {
9459 lhs = ada_coerce_to_simple_array (lhs);
9460 lhs_type = check_typedef (value_type (lhs));
9461 low_index = lhs_type->bounds ()->low.const_val ();
9462 high_index = lhs_type->bounds ()->high.const_val ();
9463 }
9464 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9465 {
9466 low_index = 0;
9467 high_index = num_visible_fields (lhs_type) - 1;
9468 }
9469 else
9470 error (_("Left-hand side must be array or record."));
9471
9472 std::vector<LONGEST> indices (4);
9473 indices[0] = indices[1] = low_index - 1;
9474 indices[2] = indices[3] = high_index + 1;
9475
9476 for (i = 0; i < n; i += 1)
9477 {
9478 switch (exp->elts[*pos].opcode)
9479 {
9480 case OP_CHOICES:
9481 aggregate_assign_from_choices (container, lhs, exp, pos, indices,
9482 low_index, high_index);
9483 break;
9484 case OP_POSITIONAL:
9485 aggregate_assign_positional (container, lhs, exp, pos, indices,
9486 low_index, high_index);
9487 break;
9488 case OP_OTHERS:
9489 if (i != n-1)
9490 error (_("Misplaced 'others' clause"));
9491 aggregate_assign_others (container, lhs, exp, pos, indices,
9492 low_index, high_index);
9493 break;
9494 default:
9495 error (_("Internal error: bad aggregate clause"));
9496 }
9497 }
9498
9499 return container;
9500 }
9501
9502 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9503 construct at *POS, updating *POS past the construct, given that
9504 the positions are relative to lower bound LOW, where HIGH is the
9505 upper bound. Record the position in INDICES. CONTAINER is as for
9506 assign_aggregate. */
9507 static void
9508 aggregate_assign_positional (struct value *container,
9509 struct value *lhs, struct expression *exp,
9510 int *pos, std::vector<LONGEST> &indices,
9511 LONGEST low, LONGEST high)
9512 {
9513 LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
9514
9515 if (ind - 1 == high)
9516 warning (_("Extra components in aggregate ignored."));
9517 if (ind <= high)
9518 {
9519 add_component_interval (ind, ind, indices);
9520 *pos += 3;
9521 assign_component (container, lhs, ind, exp, pos);
9522 }
9523 else
9524 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9525 }
9526
9527 /* Assign into the components of LHS indexed by the OP_CHOICES
9528 construct at *POS, updating *POS past the construct, given that
9529 the allowable indices are LOW..HIGH. Record the indices assigned
9530 to in INDICES. CONTAINER is as for assign_aggregate. */
9531 static void
9532 aggregate_assign_from_choices (struct value *container,
9533 struct value *lhs, struct expression *exp,
9534 int *pos, std::vector<LONGEST> &indices,
9535 LONGEST low, LONGEST high)
9536 {
9537 int j;
9538 int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
9539 int choice_pos, expr_pc;
9540 int is_array = ada_is_direct_array_type (value_type (lhs));
9541
9542 choice_pos = *pos += 3;
9543
9544 for (j = 0; j < n_choices; j += 1)
9545 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9546 expr_pc = *pos;
9547 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9548
9549 for (j = 0; j < n_choices; j += 1)
9550 {
9551 LONGEST lower, upper;
9552 enum exp_opcode op = exp->elts[choice_pos].opcode;
9553
9554 if (op == OP_DISCRETE_RANGE)
9555 {
9556 choice_pos += 1;
9557 lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
9558 EVAL_NORMAL));
9559 upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
9560 EVAL_NORMAL));
9561 }
9562 else if (is_array)
9563 {
9564 lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos,
9565 EVAL_NORMAL));
9566 upper = lower;
9567 }
9568 else
9569 {
9570 int ind;
9571 const char *name;
9572
9573 switch (op)
9574 {
9575 case OP_NAME:
9576 name = &exp->elts[choice_pos + 2].string;
9577 break;
9578 case OP_VAR_VALUE:
9579 name = exp->elts[choice_pos + 2].symbol->natural_name ();
9580 break;
9581 default:
9582 error (_("Invalid record component association."));
9583 }
9584 ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
9585 ind = 0;
9586 if (! find_struct_field (name, value_type (lhs), 0,
9587 NULL, NULL, NULL, NULL, &ind))
9588 error (_("Unknown component name: %s."), name);
9589 lower = upper = ind;
9590 }
9591
9592 if (lower <= upper && (lower < low || upper > high))
9593 error (_("Index in component association out of bounds."));
9594
9595 add_component_interval (lower, upper, indices);
9596 while (lower <= upper)
9597 {
9598 int pos1;
9599
9600 pos1 = expr_pc;
9601 assign_component (container, lhs, lower, exp, &pos1);
9602 lower += 1;
9603 }
9604 }
9605 }
9606
9607 /* Assign the value of the expression in the OP_OTHERS construct in
9608 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9609 have not been previously assigned. The index intervals already assigned
9610 are in INDICES. Updates *POS to after the OP_OTHERS clause.
9611 CONTAINER is as for assign_aggregate. */
9612 static void
9613 aggregate_assign_others (struct value *container,
9614 struct value *lhs, struct expression *exp,
9615 int *pos, std::vector<LONGEST> &indices,
9616 LONGEST low, LONGEST high)
9617 {
9618 int i;
9619 int expr_pc = *pos + 1;
9620
9621 int num_indices = indices.size ();
9622 for (i = 0; i < num_indices - 2; i += 2)
9623 {
9624 LONGEST ind;
9625
9626 for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9627 {
9628 int localpos;
9629
9630 localpos = expr_pc;
9631 assign_component (container, lhs, ind, exp, &localpos);
9632 }
9633 }
9634 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9635 }
9636
9637 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9638 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9639 overlap. */
9640 static void
9641 add_component_interval (LONGEST low, LONGEST high,
9642 std::vector<LONGEST> &indices)
9643 {
9644 int i, j;
9645
9646 int size = indices.size ();
9647 for (i = 0; i < size; i += 2) {
9648 if (high >= indices[i] && low <= indices[i + 1])
9649 {
9650 int kh;
9651
9652 for (kh = i + 2; kh < size; kh += 2)
9653 if (high < indices[kh])
9654 break;
9655 if (low < indices[i])
9656 indices[i] = low;
9657 indices[i + 1] = indices[kh - 1];
9658 if (high > indices[i + 1])
9659 indices[i + 1] = high;
9660 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9661 indices.resize (kh - i - 2);
9662 return;
9663 }
9664 else if (high < indices[i])
9665 break;
9666 }
9667
9668 indices.resize (indices.size () + 2);
9669 for (j = indices.size () - 1; j >= i + 2; j -= 1)
9670 indices[j] = indices[j - 2];
9671 indices[i] = low;
9672 indices[i + 1] = high;
9673 }
9674
9675 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9676 is different. */
9677
9678 static struct value *
9679 ada_value_cast (struct type *type, struct value *arg2)
9680 {
9681 if (type == ada_check_typedef (value_type (arg2)))
9682 return arg2;
9683
9684 return value_cast (type, arg2);
9685 }
9686
9687 /* Evaluating Ada expressions, and printing their result.
9688 ------------------------------------------------------
9689
9690 1. Introduction:
9691 ----------------
9692
9693 We usually evaluate an Ada expression in order to print its value.
9694 We also evaluate an expression in order to print its type, which
9695 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9696 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9697 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9698 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9699 similar.
9700
9701 Evaluating expressions is a little more complicated for Ada entities
9702 than it is for entities in languages such as C. The main reason for
9703 this is that Ada provides types whose definition might be dynamic.
9704 One example of such types is variant records. Or another example
9705 would be an array whose bounds can only be known at run time.
9706
9707 The following description is a general guide as to what should be
9708 done (and what should NOT be done) in order to evaluate an expression
9709 involving such types, and when. This does not cover how the semantic
9710 information is encoded by GNAT as this is covered separatly. For the
9711 document used as the reference for the GNAT encoding, see exp_dbug.ads
9712 in the GNAT sources.
9713
9714 Ideally, we should embed each part of this description next to its
9715 associated code. Unfortunately, the amount of code is so vast right
9716 now that it's hard to see whether the code handling a particular
9717 situation might be duplicated or not. One day, when the code is
9718 cleaned up, this guide might become redundant with the comments
9719 inserted in the code, and we might want to remove it.
9720
9721 2. ``Fixing'' an Entity, the Simple Case:
9722 -----------------------------------------
9723
9724 When evaluating Ada expressions, the tricky issue is that they may
9725 reference entities whose type contents and size are not statically
9726 known. Consider for instance a variant record:
9727
9728 type Rec (Empty : Boolean := True) is record
9729 case Empty is
9730 when True => null;
9731 when False => Value : Integer;
9732 end case;
9733 end record;
9734 Yes : Rec := (Empty => False, Value => 1);
9735 No : Rec := (empty => True);
9736
9737 The size and contents of that record depends on the value of the
9738 descriminant (Rec.Empty). At this point, neither the debugging
9739 information nor the associated type structure in GDB are able to
9740 express such dynamic types. So what the debugger does is to create
9741 "fixed" versions of the type that applies to the specific object.
9742 We also informally refer to this operation as "fixing" an object,
9743 which means creating its associated fixed type.
9744
9745 Example: when printing the value of variable "Yes" above, its fixed
9746 type would look like this:
9747
9748 type Rec is record
9749 Empty : Boolean;
9750 Value : Integer;
9751 end record;
9752
9753 On the other hand, if we printed the value of "No", its fixed type
9754 would become:
9755
9756 type Rec is record
9757 Empty : Boolean;
9758 end record;
9759
9760 Things become a little more complicated when trying to fix an entity
9761 with a dynamic type that directly contains another dynamic type,
9762 such as an array of variant records, for instance. There are
9763 two possible cases: Arrays, and records.
9764
9765 3. ``Fixing'' Arrays:
9766 ---------------------
9767
9768 The type structure in GDB describes an array in terms of its bounds,
9769 and the type of its elements. By design, all elements in the array
9770 have the same type and we cannot represent an array of variant elements
9771 using the current type structure in GDB. When fixing an array,
9772 we cannot fix the array element, as we would potentially need one
9773 fixed type per element of the array. As a result, the best we can do
9774 when fixing an array is to produce an array whose bounds and size
9775 are correct (allowing us to read it from memory), but without having
9776 touched its element type. Fixing each element will be done later,
9777 when (if) necessary.
9778
9779 Arrays are a little simpler to handle than records, because the same
9780 amount of memory is allocated for each element of the array, even if
9781 the amount of space actually used by each element differs from element
9782 to element. Consider for instance the following array of type Rec:
9783
9784 type Rec_Array is array (1 .. 2) of Rec;
9785
9786 The actual amount of memory occupied by each element might be different
9787 from element to element, depending on the value of their discriminant.
9788 But the amount of space reserved for each element in the array remains
9789 fixed regardless. So we simply need to compute that size using
9790 the debugging information available, from which we can then determine
9791 the array size (we multiply the number of elements of the array by
9792 the size of each element).
9793
9794 The simplest case is when we have an array of a constrained element
9795 type. For instance, consider the following type declarations:
9796
9797 type Bounded_String (Max_Size : Integer) is
9798 Length : Integer;
9799 Buffer : String (1 .. Max_Size);
9800 end record;
9801 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9802
9803 In this case, the compiler describes the array as an array of
9804 variable-size elements (identified by its XVS suffix) for which
9805 the size can be read in the parallel XVZ variable.
9806
9807 In the case of an array of an unconstrained element type, the compiler
9808 wraps the array element inside a private PAD type. This type should not
9809 be shown to the user, and must be "unwrap"'ed before printing. Note
9810 that we also use the adjective "aligner" in our code to designate
9811 these wrapper types.
9812
9813 In some cases, the size allocated for each element is statically
9814 known. In that case, the PAD type already has the correct size,
9815 and the array element should remain unfixed.
9816
9817 But there are cases when this size is not statically known.
9818 For instance, assuming that "Five" is an integer variable:
9819
9820 type Dynamic is array (1 .. Five) of Integer;
9821 type Wrapper (Has_Length : Boolean := False) is record
9822 Data : Dynamic;
9823 case Has_Length is
9824 when True => Length : Integer;
9825 when False => null;
9826 end case;
9827 end record;
9828 type Wrapper_Array is array (1 .. 2) of Wrapper;
9829
9830 Hello : Wrapper_Array := (others => (Has_Length => True,
9831 Data => (others => 17),
9832 Length => 1));
9833
9834
9835 The debugging info would describe variable Hello as being an
9836 array of a PAD type. The size of that PAD type is not statically
9837 known, but can be determined using a parallel XVZ variable.
9838 In that case, a copy of the PAD type with the correct size should
9839 be used for the fixed array.
9840
9841 3. ``Fixing'' record type objects:
9842 ----------------------------------
9843
9844 Things are slightly different from arrays in the case of dynamic
9845 record types. In this case, in order to compute the associated
9846 fixed type, we need to determine the size and offset of each of
9847 its components. This, in turn, requires us to compute the fixed
9848 type of each of these components.
9849
9850 Consider for instance the example:
9851
9852 type Bounded_String (Max_Size : Natural) is record
9853 Str : String (1 .. Max_Size);
9854 Length : Natural;
9855 end record;
9856 My_String : Bounded_String (Max_Size => 10);
9857
9858 In that case, the position of field "Length" depends on the size
9859 of field Str, which itself depends on the value of the Max_Size
9860 discriminant. In order to fix the type of variable My_String,
9861 we need to fix the type of field Str. Therefore, fixing a variant
9862 record requires us to fix each of its components.
9863
9864 However, if a component does not have a dynamic size, the component
9865 should not be fixed. In particular, fields that use a PAD type
9866 should not fixed. Here is an example where this might happen
9867 (assuming type Rec above):
9868
9869 type Container (Big : Boolean) is record
9870 First : Rec;
9871 After : Integer;
9872 case Big is
9873 when True => Another : Integer;
9874 when False => null;
9875 end case;
9876 end record;
9877 My_Container : Container := (Big => False,
9878 First => (Empty => True),
9879 After => 42);
9880
9881 In that example, the compiler creates a PAD type for component First,
9882 whose size is constant, and then positions the component After just
9883 right after it. The offset of component After is therefore constant
9884 in this case.
9885
9886 The debugger computes the position of each field based on an algorithm
9887 that uses, among other things, the actual position and size of the field
9888 preceding it. Let's now imagine that the user is trying to print
9889 the value of My_Container. If the type fixing was recursive, we would
9890 end up computing the offset of field After based on the size of the
9891 fixed version of field First. And since in our example First has
9892 only one actual field, the size of the fixed type is actually smaller
9893 than the amount of space allocated to that field, and thus we would
9894 compute the wrong offset of field After.
9895
9896 To make things more complicated, we need to watch out for dynamic
9897 components of variant records (identified by the ___XVL suffix in
9898 the component name). Even if the target type is a PAD type, the size
9899 of that type might not be statically known. So the PAD type needs
9900 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9901 we might end up with the wrong size for our component. This can be
9902 observed with the following type declarations:
9903
9904 type Octal is new Integer range 0 .. 7;
9905 type Octal_Array is array (Positive range <>) of Octal;
9906 pragma Pack (Octal_Array);
9907
9908 type Octal_Buffer (Size : Positive) is record
9909 Buffer : Octal_Array (1 .. Size);
9910 Length : Integer;
9911 end record;
9912
9913 In that case, Buffer is a PAD type whose size is unset and needs
9914 to be computed by fixing the unwrapped type.
9915
9916 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
9917 ----------------------------------------------------------
9918
9919 Lastly, when should the sub-elements of an entity that remained unfixed
9920 thus far, be actually fixed?
9921
9922 The answer is: Only when referencing that element. For instance
9923 when selecting one component of a record, this specific component
9924 should be fixed at that point in time. Or when printing the value
9925 of a record, each component should be fixed before its value gets
9926 printed. Similarly for arrays, the element of the array should be
9927 fixed when printing each element of the array, or when extracting
9928 one element out of that array. On the other hand, fixing should
9929 not be performed on the elements when taking a slice of an array!
9930
9931 Note that one of the side effects of miscomputing the offset and
9932 size of each field is that we end up also miscomputing the size
9933 of the containing type. This can have adverse results when computing
9934 the value of an entity. GDB fetches the value of an entity based
9935 on the size of its type, and thus a wrong size causes GDB to fetch
9936 the wrong amount of memory. In the case where the computed size is
9937 too small, GDB fetches too little data to print the value of our
9938 entity. Results in this case are unpredictable, as we usually read
9939 past the buffer containing the data =:-o. */
9940
9941 /* Evaluate a subexpression of EXP, at index *POS, and return a value
9942 for that subexpression cast to TO_TYPE. Advance *POS over the
9943 subexpression. */
9944
9945 static value *
9946 ada_evaluate_subexp_for_cast (expression *exp, int *pos,
9947 enum noside noside, struct type *to_type)
9948 {
9949 int pc = *pos;
9950
9951 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE
9952 || exp->elts[pc].opcode == OP_VAR_VALUE)
9953 {
9954 (*pos) += 4;
9955
9956 value *val;
9957 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
9958 {
9959 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9960 return value_zero (to_type, not_lval);
9961
9962 val = evaluate_var_msym_value (noside,
9963 exp->elts[pc + 1].objfile,
9964 exp->elts[pc + 2].msymbol);
9965 }
9966 else
9967 val = evaluate_var_value (noside,
9968 exp->elts[pc + 1].block,
9969 exp->elts[pc + 2].symbol);
9970
9971 if (noside == EVAL_SKIP)
9972 return eval_skip_value (exp);
9973
9974 val = ada_value_cast (to_type, val);
9975
9976 /* Follow the Ada language semantics that do not allow taking
9977 an address of the result of a cast (view conversion in Ada). */
9978 if (VALUE_LVAL (val) == lval_memory)
9979 {
9980 if (value_lazy (val))
9981 value_fetch_lazy (val);
9982 VALUE_LVAL (val) = not_lval;
9983 }
9984 return val;
9985 }
9986
9987 value *val = evaluate_subexp (to_type, exp, pos, noside);
9988 if (noside == EVAL_SKIP)
9989 return eval_skip_value (exp);
9990 return ada_value_cast (to_type, val);
9991 }
9992
9993 /* A helper function for TERNOP_IN_RANGE. */
9994
9995 static value *
9996 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
9997 enum noside noside,
9998 value *arg1, value *arg2, value *arg3)
9999 {
10000 if (noside == EVAL_SKIP)
10001 return eval_skip_value (exp);
10002
10003 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10004 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10005 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10006 return
10007 value_from_longest (type,
10008 (value_less (arg1, arg3)
10009 || value_equal (arg1, arg3))
10010 && (value_less (arg2, arg1)
10011 || value_equal (arg2, arg1)));
10012 }
10013
10014 /* A helper function for UNOP_NEG. */
10015
10016 value *
10017 ada_unop_neg (struct type *expect_type,
10018 struct expression *exp,
10019 enum noside noside, enum exp_opcode op,
10020 struct value *arg1)
10021 {
10022 if (noside == EVAL_SKIP)
10023 return eval_skip_value (exp);
10024 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10025 return value_neg (arg1);
10026 }
10027
10028 /* A helper function for UNOP_IN_RANGE. */
10029
10030 value *
10031 ada_unop_in_range (struct type *expect_type,
10032 struct expression *exp,
10033 enum noside noside, enum exp_opcode op,
10034 struct value *arg1, struct type *type)
10035 {
10036 if (noside == EVAL_SKIP)
10037 return eval_skip_value (exp);
10038
10039 struct value *arg2, *arg3;
10040 switch (type->code ())
10041 {
10042 default:
10043 lim_warning (_("Membership test incompletely implemented; "
10044 "always returns true"));
10045 type = language_bool_type (exp->language_defn, exp->gdbarch);
10046 return value_from_longest (type, (LONGEST) 1);
10047
10048 case TYPE_CODE_RANGE:
10049 arg2 = value_from_longest (type,
10050 type->bounds ()->low.const_val ());
10051 arg3 = value_from_longest (type,
10052 type->bounds ()->high.const_val ());
10053 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10054 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10055 type = language_bool_type (exp->language_defn, exp->gdbarch);
10056 return
10057 value_from_longest (type,
10058 (value_less (arg1, arg3)
10059 || value_equal (arg1, arg3))
10060 && (value_less (arg2, arg1)
10061 || value_equal (arg2, arg1)));
10062 }
10063 }
10064
10065 /* A helper function for OP_ATR_TAG. */
10066
10067 value *
10068 ada_atr_tag (struct type *expect_type,
10069 struct expression *exp,
10070 enum noside noside, enum exp_opcode op,
10071 struct value *arg1)
10072 {
10073 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10074 return value_zero (ada_tag_type (arg1), not_lval);
10075
10076 return ada_value_tag (arg1);
10077 }
10078
10079 /* A helper function for OP_ATR_SIZE. */
10080
10081 value *
10082 ada_atr_size (struct type *expect_type,
10083 struct expression *exp,
10084 enum noside noside, enum exp_opcode op,
10085 struct value *arg1)
10086 {
10087 struct type *type = value_type (arg1);
10088
10089 /* If the argument is a reference, then dereference its type, since
10090 the user is really asking for the size of the actual object,
10091 not the size of the pointer. */
10092 if (type->code () == TYPE_CODE_REF)
10093 type = TYPE_TARGET_TYPE (type);
10094
10095 if (noside == EVAL_SKIP)
10096 return eval_skip_value (exp);
10097 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10098 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10099 else
10100 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10101 TARGET_CHAR_BIT * TYPE_LENGTH (type));
10102 }
10103
10104 /* A helper function for UNOP_ABS. */
10105
10106 value *
10107 ada_abs (struct type *expect_type,
10108 struct expression *exp,
10109 enum noside noside, enum exp_opcode op,
10110 struct value *arg1)
10111 {
10112 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10113 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10114 return value_neg (arg1);
10115 else
10116 return arg1;
10117 }
10118
10119 /* A helper function for BINOP_MUL. */
10120
10121 value *
10122 ada_mult_binop (struct type *expect_type,
10123 struct expression *exp,
10124 enum noside noside, enum exp_opcode op,
10125 struct value *arg1, struct value *arg2)
10126 {
10127 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10128 {
10129 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10130 return value_zero (value_type (arg1), not_lval);
10131 }
10132 else
10133 {
10134 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10135 return ada_value_binop (arg1, arg2, op);
10136 }
10137 }
10138
10139 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10140
10141 value *
10142 ada_equal_binop (struct type *expect_type,
10143 struct expression *exp,
10144 enum noside noside, enum exp_opcode op,
10145 struct value *arg1, struct value *arg2)
10146 {
10147 int tem;
10148 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10149 tem = 0;
10150 else
10151 {
10152 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10153 tem = ada_value_equal (arg1, arg2);
10154 }
10155 if (op == BINOP_NOTEQUAL)
10156 tem = !tem;
10157 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10158 return value_from_longest (type, (LONGEST) tem);
10159 }
10160
10161 /* A helper function for TERNOP_SLICE. */
10162
10163 value *
10164 ada_ternop_slice (struct expression *exp,
10165 enum noside noside,
10166 struct value *array, struct value *low_bound_val,
10167 struct value *high_bound_val)
10168 {
10169 LONGEST low_bound;
10170 LONGEST high_bound;
10171
10172 low_bound_val = coerce_ref (low_bound_val);
10173 high_bound_val = coerce_ref (high_bound_val);
10174 low_bound = value_as_long (low_bound_val);
10175 high_bound = value_as_long (high_bound_val);
10176
10177 /* If this is a reference to an aligner type, then remove all
10178 the aligners. */
10179 if (value_type (array)->code () == TYPE_CODE_REF
10180 && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
10181 TYPE_TARGET_TYPE (value_type (array)) =
10182 ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
10183
10184 if (ada_is_any_packed_array_type (value_type (array)))
10185 error (_("cannot slice a packed array"));
10186
10187 /* If this is a reference to an array or an array lvalue,
10188 convert to a pointer. */
10189 if (value_type (array)->code () == TYPE_CODE_REF
10190 || (value_type (array)->code () == TYPE_CODE_ARRAY
10191 && VALUE_LVAL (array) == lval_memory))
10192 array = value_addr (array);
10193
10194 if (noside == EVAL_AVOID_SIDE_EFFECTS
10195 && ada_is_array_descriptor_type (ada_check_typedef
10196 (value_type (array))))
10197 return empty_array (ada_type_of_array (array, 0), low_bound,
10198 high_bound);
10199
10200 array = ada_coerce_to_simple_array_ptr (array);
10201
10202 /* If we have more than one level of pointer indirection,
10203 dereference the value until we get only one level. */
10204 while (value_type (array)->code () == TYPE_CODE_PTR
10205 && (TYPE_TARGET_TYPE (value_type (array))->code ()
10206 == TYPE_CODE_PTR))
10207 array = value_ind (array);
10208
10209 /* Make sure we really do have an array type before going further,
10210 to avoid a SEGV when trying to get the index type or the target
10211 type later down the road if the debug info generated by
10212 the compiler is incorrect or incomplete. */
10213 if (!ada_is_simple_array_type (value_type (array)))
10214 error (_("cannot take slice of non-array"));
10215
10216 if (ada_check_typedef (value_type (array))->code ()
10217 == TYPE_CODE_PTR)
10218 {
10219 struct type *type0 = ada_check_typedef (value_type (array));
10220
10221 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10222 return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
10223 else
10224 {
10225 struct type *arr_type0 =
10226 to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
10227
10228 return ada_value_slice_from_ptr (array, arr_type0,
10229 longest_to_int (low_bound),
10230 longest_to_int (high_bound));
10231 }
10232 }
10233 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10234 return array;
10235 else if (high_bound < low_bound)
10236 return empty_array (value_type (array), low_bound, high_bound);
10237 else
10238 return ada_value_slice (array, longest_to_int (low_bound),
10239 longest_to_int (high_bound));
10240 }
10241
10242 /* A helper function for BINOP_IN_BOUNDS. */
10243
10244 value *
10245 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10246 struct value *arg1, struct value *arg2, int n)
10247 {
10248 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10249 {
10250 struct type *type = language_bool_type (exp->language_defn,
10251 exp->gdbarch);
10252 return value_zero (type, not_lval);
10253 }
10254
10255 struct type *type = ada_index_type (value_type (arg2), n, "range");
10256 if (!type)
10257 type = value_type (arg1);
10258
10259 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10260 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10261
10262 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10263 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10264 type = language_bool_type (exp->language_defn, exp->gdbarch);
10265 return value_from_longest (type,
10266 (value_less (arg1, arg3)
10267 || value_equal (arg1, arg3))
10268 && (value_less (arg2, arg1)
10269 || value_equal (arg2, arg1)));
10270 }
10271
10272 /* A helper function for some attribute operations. */
10273
10274 static value *
10275 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10276 struct value *arg1, struct type *type_arg, int tem)
10277 {
10278 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10279 {
10280 if (type_arg == NULL)
10281 type_arg = value_type (arg1);
10282
10283 if (ada_is_constrained_packed_array_type (type_arg))
10284 type_arg = decode_constrained_packed_array_type (type_arg);
10285
10286 if (!discrete_type_p (type_arg))
10287 {
10288 switch (op)
10289 {
10290 default: /* Should never happen. */
10291 error (_("unexpected attribute encountered"));
10292 case OP_ATR_FIRST:
10293 case OP_ATR_LAST:
10294 type_arg = ada_index_type (type_arg, tem,
10295 ada_attribute_name (op));
10296 break;
10297 case OP_ATR_LENGTH:
10298 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10299 break;
10300 }
10301 }
10302
10303 return value_zero (type_arg, not_lval);
10304 }
10305 else if (type_arg == NULL)
10306 {
10307 arg1 = ada_coerce_ref (arg1);
10308
10309 if (ada_is_constrained_packed_array_type (value_type (arg1)))
10310 arg1 = ada_coerce_to_simple_array (arg1);
10311
10312 struct type *type;
10313 if (op == OP_ATR_LENGTH)
10314 type = builtin_type (exp->gdbarch)->builtin_int;
10315 else
10316 {
10317 type = ada_index_type (value_type (arg1), tem,
10318 ada_attribute_name (op));
10319 if (type == NULL)
10320 type = builtin_type (exp->gdbarch)->builtin_int;
10321 }
10322
10323 switch (op)
10324 {
10325 default: /* Should never happen. */
10326 error (_("unexpected attribute encountered"));
10327 case OP_ATR_FIRST:
10328 return value_from_longest
10329 (type, ada_array_bound (arg1, tem, 0));
10330 case OP_ATR_LAST:
10331 return value_from_longest
10332 (type, ada_array_bound (arg1, tem, 1));
10333 case OP_ATR_LENGTH:
10334 return value_from_longest
10335 (type, ada_array_length (arg1, tem));
10336 }
10337 }
10338 else if (discrete_type_p (type_arg))
10339 {
10340 struct type *range_type;
10341 const char *name = ada_type_name (type_arg);
10342
10343 range_type = NULL;
10344 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10345 range_type = to_fixed_range_type (type_arg, NULL);
10346 if (range_type == NULL)
10347 range_type = type_arg;
10348 switch (op)
10349 {
10350 default:
10351 error (_("unexpected attribute encountered"));
10352 case OP_ATR_FIRST:
10353 return value_from_longest
10354 (range_type, ada_discrete_type_low_bound (range_type));
10355 case OP_ATR_LAST:
10356 return value_from_longest
10357 (range_type, ada_discrete_type_high_bound (range_type));
10358 case OP_ATR_LENGTH:
10359 error (_("the 'length attribute applies only to array types"));
10360 }
10361 }
10362 else if (type_arg->code () == TYPE_CODE_FLT)
10363 error (_("unimplemented type attribute"));
10364 else
10365 {
10366 LONGEST low, high;
10367
10368 if (ada_is_constrained_packed_array_type (type_arg))
10369 type_arg = decode_constrained_packed_array_type (type_arg);
10370
10371 struct type *type;
10372 if (op == OP_ATR_LENGTH)
10373 type = builtin_type (exp->gdbarch)->builtin_int;
10374 else
10375 {
10376 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10377 if (type == NULL)
10378 type = builtin_type (exp->gdbarch)->builtin_int;
10379 }
10380
10381 switch (op)
10382 {
10383 default:
10384 error (_("unexpected attribute encountered"));
10385 case OP_ATR_FIRST:
10386 low = ada_array_bound_from_type (type_arg, tem, 0);
10387 return value_from_longest (type, low);
10388 case OP_ATR_LAST:
10389 high = ada_array_bound_from_type (type_arg, tem, 1);
10390 return value_from_longest (type, high);
10391 case OP_ATR_LENGTH:
10392 low = ada_array_bound_from_type (type_arg, tem, 0);
10393 high = ada_array_bound_from_type (type_arg, tem, 1);
10394 return value_from_longest (type, high - low + 1);
10395 }
10396 }
10397 }
10398
10399 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10400
10401 struct value *
10402 ada_binop_minmax (struct type *expect_type,
10403 struct expression *exp,
10404 enum noside noside, enum exp_opcode op,
10405 struct value *arg1, struct value *arg2)
10406 {
10407 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10408 return value_zero (value_type (arg1), not_lval);
10409 else
10410 {
10411 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10412 return value_binop (arg1, arg2,
10413 op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
10414 }
10415 }
10416
10417 /* A helper function for BINOP_EXP. */
10418
10419 struct value *
10420 ada_binop_exp (struct type *expect_type,
10421 struct expression *exp,
10422 enum noside noside, enum exp_opcode op,
10423 struct value *arg1, struct value *arg2)
10424 {
10425 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10426 return value_zero (value_type (arg1), not_lval);
10427 else
10428 {
10429 /* For integer exponentiation operations,
10430 only promote the first argument. */
10431 if (is_integral_type (value_type (arg2)))
10432 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10433 else
10434 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10435
10436 return value_binop (arg1, arg2, op);
10437 }
10438 }
10439
10440 namespace expr
10441 {
10442
10443 value *
10444 ada_wrapped_operation::evaluate (struct type *expect_type,
10445 struct expression *exp,
10446 enum noside noside)
10447 {
10448 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10449 if (noside == EVAL_NORMAL)
10450 result = unwrap_value (result);
10451
10452 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10453 then we need to perform the conversion manually, because
10454 evaluate_subexp_standard doesn't do it. This conversion is
10455 necessary in Ada because the different kinds of float/fixed
10456 types in Ada have different representations.
10457
10458 Similarly, we need to perform the conversion from OP_LONG
10459 ourselves. */
10460 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10461 result = ada_value_cast (expect_type, result);
10462
10463 return result;
10464 }
10465
10466 value *
10467 ada_string_operation::evaluate (struct type *expect_type,
10468 struct expression *exp,
10469 enum noside noside)
10470 {
10471 value *result = string_operation::evaluate (expect_type, exp, noside);
10472 /* The result type will have code OP_STRING, bashed there from
10473 OP_ARRAY. Bash it back. */
10474 if (value_type (result)->code () == TYPE_CODE_STRING)
10475 value_type (result)->set_code (TYPE_CODE_ARRAY);
10476 return result;
10477 }
10478
10479 value *
10480 ada_qual_operation::evaluate (struct type *expect_type,
10481 struct expression *exp,
10482 enum noside noside)
10483 {
10484 struct type *type = std::get<1> (m_storage);
10485 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10486 }
10487
10488 value *
10489 ada_ternop_range_operation::evaluate (struct type *expect_type,
10490 struct expression *exp,
10491 enum noside noside)
10492 {
10493 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10494 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10495 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10496 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10497 }
10498
10499 value *
10500 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10501 struct expression *exp,
10502 enum noside noside)
10503 {
10504 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10505 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10506
10507 auto do_op = [=] (LONGEST x, LONGEST y)
10508 {
10509 if (std::get<0> (m_storage) == BINOP_ADD)
10510 return x + y;
10511 return x - y;
10512 };
10513
10514 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10515 return (value_from_longest
10516 (value_type (arg1),
10517 do_op (value_as_long (arg1), value_as_long (arg2))));
10518 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10519 return (value_from_longest
10520 (value_type (arg2),
10521 do_op (value_as_long (arg1), value_as_long (arg2))));
10522 /* Preserve the original type for use by the range case below.
10523 We cannot cast the result to a reference type, so if ARG1 is
10524 a reference type, find its underlying type. */
10525 struct type *type = value_type (arg1);
10526 while (type->code () == TYPE_CODE_REF)
10527 type = TYPE_TARGET_TYPE (type);
10528 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10529 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10530 /* We need to special-case the result with a range.
10531 This is done for the benefit of "ptype". gdb's Ada support
10532 historically used the LHS to set the result type here, so
10533 preserve this behavior. */
10534 if (type->code () == TYPE_CODE_RANGE)
10535 arg1 = value_cast (type, arg1);
10536 return arg1;
10537 }
10538
10539 value *
10540 ada_unop_atr_operation::evaluate (struct type *expect_type,
10541 struct expression *exp,
10542 enum noside noside)
10543 {
10544 struct type *type_arg = nullptr;
10545 value *val = nullptr;
10546
10547 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10548 {
10549 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10550 EVAL_AVOID_SIDE_EFFECTS);
10551 type_arg = value_type (tem);
10552 }
10553 else
10554 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10555
10556 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10557 val, type_arg, std::get<2> (m_storage));
10558 }
10559
10560 value *
10561 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10562 struct expression *exp,
10563 enum noside noside)
10564 {
10565 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10566 return value_zero (expect_type, not_lval);
10567
10568 value *val = evaluate_var_msym_value (noside,
10569 std::get<1> (m_storage),
10570 std::get<0> (m_storage));
10571
10572 val = ada_value_cast (expect_type, val);
10573
10574 /* Follow the Ada language semantics that do not allow taking
10575 an address of the result of a cast (view conversion in Ada). */
10576 if (VALUE_LVAL (val) == lval_memory)
10577 {
10578 if (value_lazy (val))
10579 value_fetch_lazy (val);
10580 VALUE_LVAL (val) = not_lval;
10581 }
10582 return val;
10583 }
10584
10585 value *
10586 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10587 struct expression *exp,
10588 enum noside noside)
10589 {
10590 value *val = evaluate_var_value (noside,
10591 std::get<1> (m_storage),
10592 std::get<0> (m_storage));
10593
10594 val = ada_value_cast (expect_type, val);
10595
10596 /* Follow the Ada language semantics that do not allow taking
10597 an address of the result of a cast (view conversion in Ada). */
10598 if (VALUE_LVAL (val) == lval_memory)
10599 {
10600 if (value_lazy (val))
10601 value_fetch_lazy (val);
10602 VALUE_LVAL (val) = not_lval;
10603 }
10604 return val;
10605 }
10606
10607 value *
10608 ada_var_value_operation::evaluate (struct type *expect_type,
10609 struct expression *exp,
10610 enum noside noside)
10611 {
10612 symbol *sym = std::get<0> (m_storage);
10613
10614 if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
10615 /* Only encountered when an unresolved symbol occurs in a
10616 context other than a function call, in which case, it is
10617 invalid. */
10618 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10619 sym->print_name ());
10620
10621 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10622 {
10623 struct type *type = static_unwrap_type (SYMBOL_TYPE (sym));
10624 /* Check to see if this is a tagged type. We also need to handle
10625 the case where the type is a reference to a tagged type, but
10626 we have to be careful to exclude pointers to tagged types.
10627 The latter should be shown as usual (as a pointer), whereas
10628 a reference should mostly be transparent to the user. */
10629 if (ada_is_tagged_type (type, 0)
10630 || (type->code () == TYPE_CODE_REF
10631 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10632 {
10633 /* Tagged types are a little special in the fact that the real
10634 type is dynamic and can only be determined by inspecting the
10635 object's tag. This means that we need to get the object's
10636 value first (EVAL_NORMAL) and then extract the actual object
10637 type from its tag.
10638
10639 Note that we cannot skip the final step where we extract
10640 the object type from its tag, because the EVAL_NORMAL phase
10641 results in dynamic components being resolved into fixed ones.
10642 This can cause problems when trying to print the type
10643 description of tagged types whose parent has a dynamic size:
10644 We use the type name of the "_parent" component in order
10645 to print the name of the ancestor type in the type description.
10646 If that component had a dynamic size, the resolution into
10647 a fixed type would result in the loss of that type name,
10648 thus preventing us from printing the name of the ancestor
10649 type in the type description. */
10650 value *arg1 = var_value_operation::evaluate (nullptr, exp,
10651 EVAL_NORMAL);
10652
10653 if (type->code () != TYPE_CODE_REF)
10654 {
10655 struct type *actual_type;
10656
10657 actual_type = type_from_tag (ada_value_tag (arg1));
10658 if (actual_type == NULL)
10659 /* If, for some reason, we were unable to determine
10660 the actual type from the tag, then use the static
10661 approximation that we just computed as a fallback.
10662 This can happen if the debugging information is
10663 incomplete, for instance. */
10664 actual_type = type;
10665 return value_zero (actual_type, not_lval);
10666 }
10667 else
10668 {
10669 /* In the case of a ref, ada_coerce_ref takes care
10670 of determining the actual type. But the evaluation
10671 should return a ref as it should be valid to ask
10672 for its address; so rebuild a ref after coerce. */
10673 arg1 = ada_coerce_ref (arg1);
10674 return value_ref (arg1, TYPE_CODE_REF);
10675 }
10676 }
10677
10678 /* Records and unions for which GNAT encodings have been
10679 generated need to be statically fixed as well.
10680 Otherwise, non-static fixing produces a type where
10681 all dynamic properties are removed, which prevents "ptype"
10682 from being able to completely describe the type.
10683 For instance, a case statement in a variant record would be
10684 replaced by the relevant components based on the actual
10685 value of the discriminants. */
10686 if ((type->code () == TYPE_CODE_STRUCT
10687 && dynamic_template_type (type) != NULL)
10688 || (type->code () == TYPE_CODE_UNION
10689 && ada_find_parallel_type (type, "___XVU") != NULL))
10690 return value_zero (to_static_fixed_type (type), not_lval);
10691 }
10692
10693 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10694 return ada_to_fixed_value (arg1);
10695 }
10696
10697 value *
10698 ada_atr_val_operation::evaluate (struct type *expect_type,
10699 struct expression *exp,
10700 enum noside noside)
10701 {
10702 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10703 return ada_val_atr (noside, std::get<0> (m_storage), arg);
10704 }
10705
10706 value *
10707 ada_unop_ind_operation::evaluate (struct type *expect_type,
10708 struct expression *exp,
10709 enum noside noside)
10710 {
10711 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10712
10713 struct type *type = ada_check_typedef (value_type (arg1));
10714 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10715 {
10716 if (ada_is_array_descriptor_type (type))
10717 /* GDB allows dereferencing GNAT array descriptors. */
10718 {
10719 struct type *arrType = ada_type_of_array (arg1, 0);
10720
10721 if (arrType == NULL)
10722 error (_("Attempt to dereference null array pointer."));
10723 return value_at_lazy (arrType, 0);
10724 }
10725 else if (type->code () == TYPE_CODE_PTR
10726 || type->code () == TYPE_CODE_REF
10727 /* In C you can dereference an array to get the 1st elt. */
10728 || type->code () == TYPE_CODE_ARRAY)
10729 {
10730 /* As mentioned in the OP_VAR_VALUE case, tagged types can
10731 only be determined by inspecting the object's tag.
10732 This means that we need to evaluate completely the
10733 expression in order to get its type. */
10734
10735 if ((type->code () == TYPE_CODE_REF
10736 || type->code () == TYPE_CODE_PTR)
10737 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
10738 {
10739 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
10740 EVAL_NORMAL);
10741 type = value_type (ada_value_ind (arg1));
10742 }
10743 else
10744 {
10745 type = to_static_fixed_type
10746 (ada_aligned_type
10747 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
10748 }
10749 ada_ensure_varsize_limit (type);
10750 return value_zero (type, lval_memory);
10751 }
10752 else if (type->code () == TYPE_CODE_INT)
10753 {
10754 /* GDB allows dereferencing an int. */
10755 if (expect_type == NULL)
10756 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10757 lval_memory);
10758 else
10759 {
10760 expect_type =
10761 to_static_fixed_type (ada_aligned_type (expect_type));
10762 return value_zero (expect_type, lval_memory);
10763 }
10764 }
10765 else
10766 error (_("Attempt to take contents of a non-pointer value."));
10767 }
10768 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
10769 type = ada_check_typedef (value_type (arg1));
10770
10771 if (type->code () == TYPE_CODE_INT)
10772 /* GDB allows dereferencing an int. If we were given
10773 the expect_type, then use that as the target type.
10774 Otherwise, assume that the target type is an int. */
10775 {
10776 if (expect_type != NULL)
10777 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
10778 arg1));
10779 else
10780 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
10781 (CORE_ADDR) value_as_address (arg1));
10782 }
10783
10784 if (ada_is_array_descriptor_type (type))
10785 /* GDB allows dereferencing GNAT array descriptors. */
10786 return ada_coerce_to_simple_array (arg1);
10787 else
10788 return ada_value_ind (arg1);
10789 }
10790
10791 }
10792
10793 /* Implement the evaluate_exp routine in the exp_descriptor structure
10794 for the Ada language. */
10795
10796 static struct value *
10797 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
10798 int *pos, enum noside noside)
10799 {
10800 enum exp_opcode op;
10801 int tem;
10802 int pc;
10803 int preeval_pos;
10804 struct value *arg1 = NULL, *arg2 = NULL, *arg3;
10805 struct type *type;
10806 int nargs, oplen;
10807 struct value **argvec;
10808
10809 pc = *pos;
10810 *pos += 1;
10811 op = exp->elts[pc].opcode;
10812
10813 switch (op)
10814 {
10815 default:
10816 *pos -= 1;
10817 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
10818
10819 if (noside == EVAL_NORMAL)
10820 arg1 = unwrap_value (arg1);
10821
10822 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10823 then we need to perform the conversion manually, because
10824 evaluate_subexp_standard doesn't do it. This conversion is
10825 necessary in Ada because the different kinds of float/fixed
10826 types in Ada have different representations.
10827
10828 Similarly, we need to perform the conversion from OP_LONG
10829 ourselves. */
10830 if ((op == OP_FLOAT || op == OP_LONG) && expect_type != NULL)
10831 arg1 = ada_value_cast (expect_type, arg1);
10832
10833 return arg1;
10834
10835 case OP_STRING:
10836 {
10837 struct value *result;
10838
10839 *pos -= 1;
10840 result = evaluate_subexp_standard (expect_type, exp, pos, noside);
10841 /* The result type will have code OP_STRING, bashed there from
10842 OP_ARRAY. Bash it back. */
10843 if (value_type (result)->code () == TYPE_CODE_STRING)
10844 value_type (result)->set_code (TYPE_CODE_ARRAY);
10845 return result;
10846 }
10847
10848 case UNOP_CAST:
10849 (*pos) += 2;
10850 type = exp->elts[pc + 1].type;
10851 return ada_evaluate_subexp_for_cast (exp, pos, noside, type);
10852
10853 case UNOP_QUAL:
10854 (*pos) += 2;
10855 type = exp->elts[pc + 1].type;
10856 return ada_evaluate_subexp (type, exp, pos, noside);
10857
10858 case BINOP_ASSIGN:
10859 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
10860 if (exp->elts[*pos].opcode == OP_AGGREGATE)
10861 {
10862 arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
10863 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
10864 return arg1;
10865 return ada_value_assign (arg1, arg1);
10866 }
10867 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
10868 except if the lhs of our assignment is a convenience variable.
10869 In the case of assigning to a convenience variable, the lhs
10870 should be exactly the result of the evaluation of the rhs. */
10871 type = value_type (arg1);
10872 if (VALUE_LVAL (arg1) == lval_internalvar)
10873 type = NULL;
10874 arg2 = evaluate_subexp (type, exp, pos, noside);
10875 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
10876 return arg1;
10877 if (VALUE_LVAL (arg1) == lval_internalvar)
10878 {
10879 /* Nothing. */
10880 }
10881 else
10882 arg2 = coerce_for_assign (value_type (arg1), arg2);
10883 return ada_value_assign (arg1, arg2);
10884
10885 case BINOP_ADD:
10886 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
10887 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
10888 if (noside == EVAL_SKIP)
10889 goto nosideret;
10890 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10891 return (value_from_longest
10892 (value_type (arg1),
10893 value_as_long (arg1) + value_as_long (arg2)));
10894 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10895 return (value_from_longest
10896 (value_type (arg2),
10897 value_as_long (arg1) + value_as_long (arg2)));
10898 /* Preserve the original type for use by the range case below.
10899 We cannot cast the result to a reference type, so if ARG1 is
10900 a reference type, find its underlying type. */
10901 type = value_type (arg1);
10902 while (type->code () == TYPE_CODE_REF)
10903 type = TYPE_TARGET_TYPE (type);
10904 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10905 arg1 = value_binop (arg1, arg2, BINOP_ADD);
10906 /* We need to special-case the result of adding to a range.
10907 This is done for the benefit of "ptype". gdb's Ada support
10908 historically used the LHS to set the result type here, so
10909 preserve this behavior. */
10910 if (type->code () == TYPE_CODE_RANGE)
10911 arg1 = value_cast (type, arg1);
10912 return arg1;
10913
10914 case BINOP_SUB:
10915 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
10916 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
10917 if (noside == EVAL_SKIP)
10918 goto nosideret;
10919 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10920 return (value_from_longest
10921 (value_type (arg1),
10922 value_as_long (arg1) - value_as_long (arg2)));
10923 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10924 return (value_from_longest
10925 (value_type (arg2),
10926 value_as_long (arg1) - value_as_long (arg2)));
10927 /* Preserve the original type for use by the range case below.
10928 We cannot cast the result to a reference type, so if ARG1 is
10929 a reference type, find its underlying type. */
10930 type = value_type (arg1);
10931 while (type->code () == TYPE_CODE_REF)
10932 type = TYPE_TARGET_TYPE (type);
10933 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10934 arg1 = value_binop (arg1, arg2, BINOP_SUB);
10935 /* We need to special-case the result of adding to a range.
10936 This is done for the benefit of "ptype". gdb's Ada support
10937 historically used the LHS to set the result type here, so
10938 preserve this behavior. */
10939 if (type->code () == TYPE_CODE_RANGE)
10940 arg1 = value_cast (type, arg1);
10941 return arg1;
10942
10943 case BINOP_MUL:
10944 case BINOP_DIV:
10945 case BINOP_REM:
10946 case BINOP_MOD:
10947 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
10948 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
10949 if (noside == EVAL_SKIP)
10950 goto nosideret;
10951 return ada_mult_binop (expect_type, exp, noside, op,
10952 arg1, arg2);
10953
10954 case BINOP_EQUAL:
10955 case BINOP_NOTEQUAL:
10956 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
10957 arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
10958 if (noside == EVAL_SKIP)
10959 goto nosideret;
10960 return ada_equal_binop (expect_type, exp, noside, op, arg1, arg2);
10961
10962 case UNOP_NEG:
10963 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
10964 return ada_unop_neg (expect_type, exp, noside, op, arg1);
10965
10966 case BINOP_LOGICAL_AND:
10967 case BINOP_LOGICAL_OR:
10968 case UNOP_LOGICAL_NOT:
10969 {
10970 struct value *val;
10971
10972 *pos -= 1;
10973 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
10974 type = language_bool_type (exp->language_defn, exp->gdbarch);
10975 return value_cast (type, val);
10976 }
10977
10978 case BINOP_BITWISE_AND:
10979 case BINOP_BITWISE_IOR:
10980 case BINOP_BITWISE_XOR:
10981 {
10982 struct value *val;
10983
10984 arg1 = evaluate_subexp (nullptr, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
10985 *pos = pc;
10986 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
10987
10988 return value_cast (value_type (arg1), val);
10989 }
10990
10991 case OP_VAR_VALUE:
10992 *pos -= 1;
10993
10994 if (noside == EVAL_SKIP)
10995 {
10996 *pos += 4;
10997 goto nosideret;
10998 }
10999
11000 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
11001 /* Only encountered when an unresolved symbol occurs in a
11002 context other than a function call, in which case, it is
11003 invalid. */
11004 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11005 exp->elts[pc + 2].symbol->print_name ());
11006
11007 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11008 {
11009 type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
11010 /* Check to see if this is a tagged type. We also need to handle
11011 the case where the type is a reference to a tagged type, but
11012 we have to be careful to exclude pointers to tagged types.
11013 The latter should be shown as usual (as a pointer), whereas
11014 a reference should mostly be transparent to the user. */
11015 if (ada_is_tagged_type (type, 0)
11016 || (type->code () == TYPE_CODE_REF
11017 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
11018 {
11019 /* Tagged types are a little special in the fact that the real
11020 type is dynamic and can only be determined by inspecting the
11021 object's tag. This means that we need to get the object's
11022 value first (EVAL_NORMAL) and then extract the actual object
11023 type from its tag.
11024
11025 Note that we cannot skip the final step where we extract
11026 the object type from its tag, because the EVAL_NORMAL phase
11027 results in dynamic components being resolved into fixed ones.
11028 This can cause problems when trying to print the type
11029 description of tagged types whose parent has a dynamic size:
11030 We use the type name of the "_parent" component in order
11031 to print the name of the ancestor type in the type description.
11032 If that component had a dynamic size, the resolution into
11033 a fixed type would result in the loss of that type name,
11034 thus preventing us from printing the name of the ancestor
11035 type in the type description. */
11036 arg1 = evaluate_subexp (nullptr, exp, pos, EVAL_NORMAL);
11037
11038 if (type->code () != TYPE_CODE_REF)
11039 {
11040 struct type *actual_type;
11041
11042 actual_type = type_from_tag (ada_value_tag (arg1));
11043 if (actual_type == NULL)
11044 /* If, for some reason, we were unable to determine
11045 the actual type from the tag, then use the static
11046 approximation that we just computed as a fallback.
11047 This can happen if the debugging information is
11048 incomplete, for instance. */
11049 actual_type = type;
11050 return value_zero (actual_type, not_lval);
11051 }
11052 else
11053 {
11054 /* In the case of a ref, ada_coerce_ref takes care
11055 of determining the actual type. But the evaluation
11056 should return a ref as it should be valid to ask
11057 for its address; so rebuild a ref after coerce. */
11058 arg1 = ada_coerce_ref (arg1);
11059 return value_ref (arg1, TYPE_CODE_REF);
11060 }
11061 }
11062
11063 /* Records and unions for which GNAT encodings have been
11064 generated need to be statically fixed as well.
11065 Otherwise, non-static fixing produces a type where
11066 all dynamic properties are removed, which prevents "ptype"
11067 from being able to completely describe the type.
11068 For instance, a case statement in a variant record would be
11069 replaced by the relevant components based on the actual
11070 value of the discriminants. */
11071 if ((type->code () == TYPE_CODE_STRUCT
11072 && dynamic_template_type (type) != NULL)
11073 || (type->code () == TYPE_CODE_UNION
11074 && ada_find_parallel_type (type, "___XVU") != NULL))
11075 {
11076 *pos += 4;
11077 return value_zero (to_static_fixed_type (type), not_lval);
11078 }
11079 }
11080
11081 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
11082 return ada_to_fixed_value (arg1);
11083
11084 case OP_FUNCALL:
11085 (*pos) += 2;
11086
11087 /* Allocate arg vector, including space for the function to be
11088 called in argvec[0] and a terminating NULL. */
11089 nargs = longest_to_int (exp->elts[pc + 1].longconst);
11090 argvec = XALLOCAVEC (struct value *, nargs + 2);
11091
11092 if (exp->elts[*pos].opcode == OP_VAR_VALUE
11093 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
11094 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11095 exp->elts[pc + 5].symbol->print_name ());
11096 else
11097 {
11098 for (tem = 0; tem <= nargs; tem += 1)
11099 argvec[tem] = evaluate_subexp (nullptr, exp, pos, noside);
11100 argvec[tem] = 0;
11101
11102 if (noside == EVAL_SKIP)
11103 goto nosideret;
11104 }
11105
11106 if (ada_is_constrained_packed_array_type
11107 (desc_base_type (value_type (argvec[0]))))
11108 argvec[0] = ada_coerce_to_simple_array (argvec[0]);
11109 else if (value_type (argvec[0])->code () == TYPE_CODE_ARRAY
11110 && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
11111 /* This is a packed array that has already been fixed, and
11112 therefore already coerced to a simple array. Nothing further
11113 to do. */
11114 ;
11115 else if (value_type (argvec[0])->code () == TYPE_CODE_REF)
11116 {
11117 /* Make sure we dereference references so that all the code below
11118 feels like it's really handling the referenced value. Wrapping
11119 types (for alignment) may be there, so make sure we strip them as
11120 well. */
11121 argvec[0] = ada_to_fixed_value (coerce_ref (argvec[0]));
11122 }
11123 else if (value_type (argvec[0])->code () == TYPE_CODE_ARRAY
11124 && VALUE_LVAL (argvec[0]) == lval_memory)
11125 argvec[0] = value_addr (argvec[0]);
11126
11127 type = ada_check_typedef (value_type (argvec[0]));
11128
11129 /* Ada allows us to implicitly dereference arrays when subscripting
11130 them. So, if this is an array typedef (encoding use for array
11131 access types encoded as fat pointers), strip it now. */
11132 if (type->code () == TYPE_CODE_TYPEDEF)
11133 type = ada_typedef_target_type (type);
11134
11135 if (type->code () == TYPE_CODE_PTR)
11136 {
11137 switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
11138 {
11139 case TYPE_CODE_FUNC:
11140 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11141 break;
11142 case TYPE_CODE_ARRAY:
11143 break;
11144 case TYPE_CODE_STRUCT:
11145 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11146 argvec[0] = ada_value_ind (argvec[0]);
11147 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11148 break;
11149 default:
11150 error (_("cannot subscript or call something of type `%s'"),
11151 ada_type_name (value_type (argvec[0])));
11152 break;
11153 }
11154 }
11155
11156 switch (type->code ())
11157 {
11158 case TYPE_CODE_FUNC:
11159 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11160 {
11161 if (TYPE_TARGET_TYPE (type) == NULL)
11162 error_call_unknown_return_type (NULL);
11163 return allocate_value (TYPE_TARGET_TYPE (type));
11164 }
11165 return call_function_by_hand (argvec[0], NULL,
11166 gdb::make_array_view (argvec + 1,
11167 nargs));
11168 case TYPE_CODE_INTERNAL_FUNCTION:
11169 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11170 /* We don't know anything about what the internal
11171 function might return, but we have to return
11172 something. */
11173 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11174 not_lval);
11175 else
11176 return call_internal_function (exp->gdbarch, exp->language_defn,
11177 argvec[0], nargs, argvec + 1);
11178
11179 case TYPE_CODE_STRUCT:
11180 {
11181 int arity;
11182
11183 arity = ada_array_arity (type);
11184 type = ada_array_element_type (type, nargs);
11185 if (type == NULL)
11186 error (_("cannot subscript or call a record"));
11187 if (arity != nargs)
11188 error (_("wrong number of subscripts; expecting %d"), arity);
11189 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11190 return value_zero (ada_aligned_type (type), lval_memory);
11191 return
11192 unwrap_value (ada_value_subscript
11193 (argvec[0], nargs, argvec + 1));
11194 }
11195 case TYPE_CODE_ARRAY:
11196 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11197 {
11198 type = ada_array_element_type (type, nargs);
11199 if (type == NULL)
11200 error (_("element type of array unknown"));
11201 else
11202 return value_zero (ada_aligned_type (type), lval_memory);
11203 }
11204 return
11205 unwrap_value (ada_value_subscript
11206 (ada_coerce_to_simple_array (argvec[0]),
11207 nargs, argvec + 1));
11208 case TYPE_CODE_PTR: /* Pointer to array */
11209 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11210 {
11211 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
11212 type = ada_array_element_type (type, nargs);
11213 if (type == NULL)
11214 error (_("element type of array unknown"));
11215 else
11216 return value_zero (ada_aligned_type (type), lval_memory);
11217 }
11218 return
11219 unwrap_value (ada_value_ptr_subscript (argvec[0],
11220 nargs, argvec + 1));
11221
11222 default:
11223 error (_("Attempt to index or call something other than an "
11224 "array or function"));
11225 }
11226
11227 case TERNOP_SLICE:
11228 {
11229 struct value *array = evaluate_subexp (nullptr, exp, pos, noside);
11230 struct value *low_bound_val
11231 = evaluate_subexp (nullptr, exp, pos, noside);
11232 struct value *high_bound_val
11233 = evaluate_subexp (nullptr, exp, pos, noside);
11234
11235 if (noside == EVAL_SKIP)
11236 goto nosideret;
11237
11238 return ada_ternop_slice (exp, noside, array, low_bound_val,
11239 high_bound_val);
11240 }
11241
11242 case UNOP_IN_RANGE:
11243 (*pos) += 2;
11244 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11245 type = check_typedef (exp->elts[pc + 1].type);
11246 return ada_unop_in_range (expect_type, exp, noside, op, arg1, type);
11247
11248 case BINOP_IN_BOUNDS:
11249 (*pos) += 2;
11250 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11251 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11252
11253 if (noside == EVAL_SKIP)
11254 goto nosideret;
11255
11256 tem = longest_to_int (exp->elts[pc + 1].longconst);
11257
11258 return ada_binop_in_bounds (exp, noside, arg1, arg2, tem);
11259
11260 case TERNOP_IN_RANGE:
11261 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11262 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11263 arg3 = evaluate_subexp (nullptr, exp, pos, noside);
11264
11265 return eval_ternop_in_range (expect_type, exp, noside, arg1, arg2, arg3);
11266
11267 case OP_ATR_FIRST:
11268 case OP_ATR_LAST:
11269 case OP_ATR_LENGTH:
11270 {
11271 struct type *type_arg;
11272
11273 if (exp->elts[*pos].opcode == OP_TYPE)
11274 {
11275 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11276 arg1 = NULL;
11277 type_arg = check_typedef (exp->elts[pc + 2].type);
11278 }
11279 else
11280 {
11281 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11282 type_arg = NULL;
11283 }
11284
11285 if (exp->elts[*pos].opcode != OP_LONG)
11286 error (_("Invalid operand to '%s"), ada_attribute_name (op));
11287 tem = longest_to_int (exp->elts[*pos + 2].longconst);
11288 *pos += 4;
11289
11290 if (noside == EVAL_SKIP)
11291 goto nosideret;
11292
11293 return ada_unop_atr (exp, noside, op, arg1, type_arg, tem);
11294 }
11295
11296 case OP_ATR_TAG:
11297 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11298 if (noside == EVAL_SKIP)
11299 goto nosideret;
11300 return ada_atr_tag (expect_type, exp, noside, op, arg1);
11301
11302 case OP_ATR_MIN:
11303 case OP_ATR_MAX:
11304 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11305 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11306 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11307 if (noside == EVAL_SKIP)
11308 goto nosideret;
11309 return ada_binop_minmax (expect_type, exp, noside, op, arg1, arg2);
11310
11311 case OP_ATR_MODULUS:
11312 {
11313 struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
11314
11315 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11316 if (noside == EVAL_SKIP)
11317 goto nosideret;
11318
11319 if (!ada_is_modular_type (type_arg))
11320 error (_("'modulus must be applied to modular type"));
11321
11322 return value_from_longest (TYPE_TARGET_TYPE (type_arg),
11323 ada_modulus (type_arg));
11324 }
11325
11326
11327 case OP_ATR_POS:
11328 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11329 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11330 if (noside == EVAL_SKIP)
11331 goto nosideret;
11332 return ada_pos_atr (expect_type, exp, noside, op, arg1);
11333
11334 case OP_ATR_SIZE:
11335 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11336 return ada_atr_size (expect_type, exp, noside, op, arg1);
11337
11338 case OP_ATR_VAL:
11339 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11340 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11341 type = exp->elts[pc + 2].type;
11342 if (noside == EVAL_SKIP)
11343 goto nosideret;
11344 return ada_val_atr (noside, type, arg1);
11345
11346 case BINOP_EXP:
11347 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11348 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11349 if (noside == EVAL_SKIP)
11350 goto nosideret;
11351 return ada_binop_exp (expect_type, exp, noside, op, arg1, arg2);
11352
11353 case UNOP_PLUS:
11354 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11355 if (noside == EVAL_SKIP)
11356 goto nosideret;
11357 else
11358 return arg1;
11359
11360 case UNOP_ABS:
11361 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11362 if (noside == EVAL_SKIP)
11363 goto nosideret;
11364 return ada_abs (expect_type, exp, noside, op, arg1);
11365
11366 case UNOP_IND:
11367 preeval_pos = *pos;
11368 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11369 if (noside == EVAL_SKIP)
11370 goto nosideret;
11371 type = ada_check_typedef (value_type (arg1));
11372 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11373 {
11374 if (ada_is_array_descriptor_type (type))
11375 /* GDB allows dereferencing GNAT array descriptors. */
11376 {
11377 struct type *arrType = ada_type_of_array (arg1, 0);
11378
11379 if (arrType == NULL)
11380 error (_("Attempt to dereference null array pointer."));
11381 return value_at_lazy (arrType, 0);
11382 }
11383 else if (type->code () == TYPE_CODE_PTR
11384 || type->code () == TYPE_CODE_REF
11385 /* In C you can dereference an array to get the 1st elt. */
11386 || type->code () == TYPE_CODE_ARRAY)
11387 {
11388 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11389 only be determined by inspecting the object's tag.
11390 This means that we need to evaluate completely the
11391 expression in order to get its type. */
11392
11393 if ((type->code () == TYPE_CODE_REF
11394 || type->code () == TYPE_CODE_PTR)
11395 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11396 {
11397 arg1
11398 = evaluate_subexp (nullptr, exp, &preeval_pos, EVAL_NORMAL);
11399 type = value_type (ada_value_ind (arg1));
11400 }
11401 else
11402 {
11403 type = to_static_fixed_type
11404 (ada_aligned_type
11405 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
11406 }
11407 ada_ensure_varsize_limit (type);
11408 return value_zero (type, lval_memory);
11409 }
11410 else if (type->code () == TYPE_CODE_INT)
11411 {
11412 /* GDB allows dereferencing an int. */
11413 if (expect_type == NULL)
11414 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11415 lval_memory);
11416 else
11417 {
11418 expect_type =
11419 to_static_fixed_type (ada_aligned_type (expect_type));
11420 return value_zero (expect_type, lval_memory);
11421 }
11422 }
11423 else
11424 error (_("Attempt to take contents of a non-pointer value."));
11425 }
11426 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11427 type = ada_check_typedef (value_type (arg1));
11428
11429 if (type->code () == TYPE_CODE_INT)
11430 /* GDB allows dereferencing an int. If we were given
11431 the expect_type, then use that as the target type.
11432 Otherwise, assume that the target type is an int. */
11433 {
11434 if (expect_type != NULL)
11435 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11436 arg1));
11437 else
11438 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11439 (CORE_ADDR) value_as_address (arg1));
11440 }
11441
11442 if (ada_is_array_descriptor_type (type))
11443 /* GDB allows dereferencing GNAT array descriptors. */
11444 return ada_coerce_to_simple_array (arg1);
11445 else
11446 return ada_value_ind (arg1);
11447
11448 case STRUCTOP_STRUCT:
11449 tem = longest_to_int (exp->elts[pc + 1].longconst);
11450 (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
11451 preeval_pos = *pos;
11452 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11453 if (noside == EVAL_SKIP)
11454 goto nosideret;
11455 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11456 {
11457 struct type *type1 = value_type (arg1);
11458
11459 if (ada_is_tagged_type (type1, 1))
11460 {
11461 type = ada_lookup_struct_elt_type (type1,
11462 &exp->elts[pc + 2].string,
11463 1, 1);
11464
11465 /* If the field is not found, check if it exists in the
11466 extension of this object's type. This means that we
11467 need to evaluate completely the expression. */
11468
11469 if (type == NULL)
11470 {
11471 arg1
11472 = evaluate_subexp (nullptr, exp, &preeval_pos, EVAL_NORMAL);
11473 arg1 = ada_value_struct_elt (arg1,
11474 &exp->elts[pc + 2].string,
11475 0);
11476 arg1 = unwrap_value (arg1);
11477 type = value_type (ada_to_fixed_value (arg1));
11478 }
11479 }
11480 else
11481 type =
11482 ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
11483 0);
11484
11485 return value_zero (ada_aligned_type (type), lval_memory);
11486 }
11487 else
11488 {
11489 arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
11490 arg1 = unwrap_value (arg1);
11491 return ada_to_fixed_value (arg1);
11492 }
11493
11494 case OP_TYPE:
11495 /* The value is not supposed to be used. This is here to make it
11496 easier to accommodate expressions that contain types. */
11497 (*pos) += 2;
11498 if (noside == EVAL_SKIP)
11499 goto nosideret;
11500 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11501 return allocate_value (exp->elts[pc + 1].type);
11502 else
11503 error (_("Attempt to use a type name as an expression"));
11504
11505 case OP_AGGREGATE:
11506 case OP_CHOICES:
11507 case OP_OTHERS:
11508 case OP_DISCRETE_RANGE:
11509 case OP_POSITIONAL:
11510 case OP_NAME:
11511 if (noside == EVAL_NORMAL)
11512 switch (op)
11513 {
11514 case OP_NAME:
11515 error (_("Undefined name, ambiguous name, or renaming used in "
11516 "component association: %s."), &exp->elts[pc+2].string);
11517 case OP_AGGREGATE:
11518 error (_("Aggregates only allowed on the right of an assignment"));
11519 default:
11520 internal_error (__FILE__, __LINE__,
11521 _("aggregate apparently mangled"));
11522 }
11523
11524 ada_forward_operator_length (exp, pc, &oplen, &nargs);
11525 *pos += oplen - 1;
11526 for (tem = 0; tem < nargs; tem += 1)
11527 ada_evaluate_subexp (NULL, exp, pos, noside);
11528 goto nosideret;
11529 }
11530
11531 nosideret:
11532 return eval_skip_value (exp);
11533 }
11534 \f
11535
11536 /* Return non-zero iff TYPE represents a System.Address type. */
11537
11538 int
11539 ada_is_system_address_type (struct type *type)
11540 {
11541 return (type->name () && strcmp (type->name (), "system__address") == 0);
11542 }
11543
11544 \f
11545
11546 /* Range types */
11547
11548 /* Scan STR beginning at position K for a discriminant name, and
11549 return the value of that discriminant field of DVAL in *PX. If
11550 PNEW_K is not null, put the position of the character beyond the
11551 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11552 not alter *PX and *PNEW_K if unsuccessful. */
11553
11554 static int
11555 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11556 int *pnew_k)
11557 {
11558 static std::string storage;
11559 const char *pstart, *pend, *bound;
11560 struct value *bound_val;
11561
11562 if (dval == NULL || str == NULL || str[k] == '\0')
11563 return 0;
11564
11565 pstart = str + k;
11566 pend = strstr (pstart, "__");
11567 if (pend == NULL)
11568 {
11569 bound = pstart;
11570 k += strlen (bound);
11571 }
11572 else
11573 {
11574 int len = pend - pstart;
11575
11576 /* Strip __ and beyond. */
11577 storage = std::string (pstart, len);
11578 bound = storage.c_str ();
11579 k = pend - str;
11580 }
11581
11582 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
11583 if (bound_val == NULL)
11584 return 0;
11585
11586 *px = value_as_long (bound_val);
11587 if (pnew_k != NULL)
11588 *pnew_k = k;
11589 return 1;
11590 }
11591
11592 /* Value of variable named NAME. Only exact matches are considered.
11593 If no such variable found, then if ERR_MSG is null, returns 0, and
11594 otherwise causes an error with message ERR_MSG. */
11595
11596 static struct value *
11597 get_var_value (const char *name, const char *err_msg)
11598 {
11599 std::string quoted_name = add_angle_brackets (name);
11600
11601 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
11602
11603 std::vector<struct block_symbol> syms
11604 = ada_lookup_symbol_list_worker (lookup_name,
11605 get_selected_block (0),
11606 VAR_DOMAIN, 1);
11607
11608 if (syms.size () != 1)
11609 {
11610 if (err_msg == NULL)
11611 return 0;
11612 else
11613 error (("%s"), err_msg);
11614 }
11615
11616 return value_of_variable (syms[0].symbol, syms[0].block);
11617 }
11618
11619 /* Value of integer variable named NAME in the current environment.
11620 If no such variable is found, returns false. Otherwise, sets VALUE
11621 to the variable's value and returns true. */
11622
11623 bool
11624 get_int_var_value (const char *name, LONGEST &value)
11625 {
11626 struct value *var_val = get_var_value (name, 0);
11627
11628 if (var_val == 0)
11629 return false;
11630
11631 value = value_as_long (var_val);
11632 return true;
11633 }
11634
11635
11636 /* Return a range type whose base type is that of the range type named
11637 NAME in the current environment, and whose bounds are calculated
11638 from NAME according to the GNAT range encoding conventions.
11639 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11640 corresponding range type from debug information; fall back to using it
11641 if symbol lookup fails. If a new type must be created, allocate it
11642 like ORIG_TYPE was. The bounds information, in general, is encoded
11643 in NAME, the base type given in the named range type. */
11644
11645 static struct type *
11646 to_fixed_range_type (struct type *raw_type, struct value *dval)
11647 {
11648 const char *name;
11649 struct type *base_type;
11650 const char *subtype_info;
11651
11652 gdb_assert (raw_type != NULL);
11653 gdb_assert (raw_type->name () != NULL);
11654
11655 if (raw_type->code () == TYPE_CODE_RANGE)
11656 base_type = TYPE_TARGET_TYPE (raw_type);
11657 else
11658 base_type = raw_type;
11659
11660 name = raw_type->name ();
11661 subtype_info = strstr (name, "___XD");
11662 if (subtype_info == NULL)
11663 {
11664 LONGEST L = ada_discrete_type_low_bound (raw_type);
11665 LONGEST U = ada_discrete_type_high_bound (raw_type);
11666
11667 if (L < INT_MIN || U > INT_MAX)
11668 return raw_type;
11669 else
11670 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
11671 L, U);
11672 }
11673 else
11674 {
11675 int prefix_len = subtype_info - name;
11676 LONGEST L, U;
11677 struct type *type;
11678 const char *bounds_str;
11679 int n;
11680
11681 subtype_info += 5;
11682 bounds_str = strchr (subtype_info, '_');
11683 n = 1;
11684
11685 if (*subtype_info == 'L')
11686 {
11687 if (!ada_scan_number (bounds_str, n, &L, &n)
11688 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11689 return raw_type;
11690 if (bounds_str[n] == '_')
11691 n += 2;
11692 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11693 n += 1;
11694 subtype_info += 1;
11695 }
11696 else
11697 {
11698 std::string name_buf = std::string (name, prefix_len) + "___L";
11699 if (!get_int_var_value (name_buf.c_str (), L))
11700 {
11701 lim_warning (_("Unknown lower bound, using 1."));
11702 L = 1;
11703 }
11704 }
11705
11706 if (*subtype_info == 'U')
11707 {
11708 if (!ada_scan_number (bounds_str, n, &U, &n)
11709 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11710 return raw_type;
11711 }
11712 else
11713 {
11714 std::string name_buf = std::string (name, prefix_len) + "___U";
11715 if (!get_int_var_value (name_buf.c_str (), U))
11716 {
11717 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11718 U = L;
11719 }
11720 }
11721
11722 type = create_static_range_type (alloc_type_copy (raw_type),
11723 base_type, L, U);
11724 /* create_static_range_type alters the resulting type's length
11725 to match the size of the base_type, which is not what we want.
11726 Set it back to the original range type's length. */
11727 TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
11728 type->set_name (name);
11729 return type;
11730 }
11731 }
11732
11733 /* True iff NAME is the name of a range type. */
11734
11735 int
11736 ada_is_range_type_name (const char *name)
11737 {
11738 return (name != NULL && strstr (name, "___XD"));
11739 }
11740 \f
11741
11742 /* Modular types */
11743
11744 /* True iff TYPE is an Ada modular type. */
11745
11746 int
11747 ada_is_modular_type (struct type *type)
11748 {
11749 struct type *subranged_type = get_base_type (type);
11750
11751 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11752 && subranged_type->code () == TYPE_CODE_INT
11753 && subranged_type->is_unsigned ());
11754 }
11755
11756 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11757
11758 ULONGEST
11759 ada_modulus (struct type *type)
11760 {
11761 const dynamic_prop &high = type->bounds ()->high;
11762
11763 if (high.kind () == PROP_CONST)
11764 return (ULONGEST) high.const_val () + 1;
11765
11766 /* If TYPE is unresolved, the high bound might be a location list. Return
11767 0, for lack of a better value to return. */
11768 return 0;
11769 }
11770 \f
11771
11772 /* Ada exception catchpoint support:
11773 ---------------------------------
11774
11775 We support 3 kinds of exception catchpoints:
11776 . catchpoints on Ada exceptions
11777 . catchpoints on unhandled Ada exceptions
11778 . catchpoints on failed assertions
11779
11780 Exceptions raised during failed assertions, or unhandled exceptions
11781 could perfectly be caught with the general catchpoint on Ada exceptions.
11782 However, we can easily differentiate these two special cases, and having
11783 the option to distinguish these two cases from the rest can be useful
11784 to zero-in on certain situations.
11785
11786 Exception catchpoints are a specialized form of breakpoint,
11787 since they rely on inserting breakpoints inside known routines
11788 of the GNAT runtime. The implementation therefore uses a standard
11789 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11790 of breakpoint_ops.
11791
11792 Support in the runtime for exception catchpoints have been changed
11793 a few times already, and these changes affect the implementation
11794 of these catchpoints. In order to be able to support several
11795 variants of the runtime, we use a sniffer that will determine
11796 the runtime variant used by the program being debugged. */
11797
11798 /* Ada's standard exceptions.
11799
11800 The Ada 83 standard also defined Numeric_Error. But there so many
11801 situations where it was unclear from the Ada 83 Reference Manual
11802 (RM) whether Constraint_Error or Numeric_Error should be raised,
11803 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11804 Interpretation saying that anytime the RM says that Numeric_Error
11805 should be raised, the implementation may raise Constraint_Error.
11806 Ada 95 went one step further and pretty much removed Numeric_Error
11807 from the list of standard exceptions (it made it a renaming of
11808 Constraint_Error, to help preserve compatibility when compiling
11809 an Ada83 compiler). As such, we do not include Numeric_Error from
11810 this list of standard exceptions. */
11811
11812 static const char * const standard_exc[] = {
11813 "constraint_error",
11814 "program_error",
11815 "storage_error",
11816 "tasking_error"
11817 };
11818
11819 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11820
11821 /* A structure that describes how to support exception catchpoints
11822 for a given executable. */
11823
11824 struct exception_support_info
11825 {
11826 /* The name of the symbol to break on in order to insert
11827 a catchpoint on exceptions. */
11828 const char *catch_exception_sym;
11829
11830 /* The name of the symbol to break on in order to insert
11831 a catchpoint on unhandled exceptions. */
11832 const char *catch_exception_unhandled_sym;
11833
11834 /* The name of the symbol to break on in order to insert
11835 a catchpoint on failed assertions. */
11836 const char *catch_assert_sym;
11837
11838 /* The name of the symbol to break on in order to insert
11839 a catchpoint on exception handling. */
11840 const char *catch_handlers_sym;
11841
11842 /* Assuming that the inferior just triggered an unhandled exception
11843 catchpoint, this function is responsible for returning the address
11844 in inferior memory where the name of that exception is stored.
11845 Return zero if the address could not be computed. */
11846 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11847 };
11848
11849 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11850 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11851
11852 /* The following exception support info structure describes how to
11853 implement exception catchpoints with the latest version of the
11854 Ada runtime (as of 2019-08-??). */
11855
11856 static const struct exception_support_info default_exception_support_info =
11857 {
11858 "__gnat_debug_raise_exception", /* catch_exception_sym */
11859 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11860 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11861 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11862 ada_unhandled_exception_name_addr
11863 };
11864
11865 /* The following exception support info structure describes how to
11866 implement exception catchpoints with an earlier version of the
11867 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11868
11869 static const struct exception_support_info exception_support_info_v0 =
11870 {
11871 "__gnat_debug_raise_exception", /* catch_exception_sym */
11872 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11873 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11874 "__gnat_begin_handler", /* catch_handlers_sym */
11875 ada_unhandled_exception_name_addr
11876 };
11877
11878 /* The following exception support info structure describes how to
11879 implement exception catchpoints with a slightly older version
11880 of the Ada runtime. */
11881
11882 static const struct exception_support_info exception_support_info_fallback =
11883 {
11884 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11885 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11886 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11887 "__gnat_begin_handler", /* catch_handlers_sym */
11888 ada_unhandled_exception_name_addr_from_raise
11889 };
11890
11891 /* Return nonzero if we can detect the exception support routines
11892 described in EINFO.
11893
11894 This function errors out if an abnormal situation is detected
11895 (for instance, if we find the exception support routines, but
11896 that support is found to be incomplete). */
11897
11898 static int
11899 ada_has_this_exception_support (const struct exception_support_info *einfo)
11900 {
11901 struct symbol *sym;
11902
11903 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11904 that should be compiled with debugging information. As a result, we
11905 expect to find that symbol in the symtabs. */
11906
11907 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11908 if (sym == NULL)
11909 {
11910 /* Perhaps we did not find our symbol because the Ada runtime was
11911 compiled without debugging info, or simply stripped of it.
11912 It happens on some GNU/Linux distributions for instance, where
11913 users have to install a separate debug package in order to get
11914 the runtime's debugging info. In that situation, let the user
11915 know why we cannot insert an Ada exception catchpoint.
11916
11917 Note: Just for the purpose of inserting our Ada exception
11918 catchpoint, we could rely purely on the associated minimal symbol.
11919 But we would be operating in degraded mode anyway, since we are
11920 still lacking the debugging info needed later on to extract
11921 the name of the exception being raised (this name is printed in
11922 the catchpoint message, and is also used when trying to catch
11923 a specific exception). We do not handle this case for now. */
11924 struct bound_minimal_symbol msym
11925 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11926
11927 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11928 error (_("Your Ada runtime appears to be missing some debugging "
11929 "information.\nCannot insert Ada exception catchpoint "
11930 "in this configuration."));
11931
11932 return 0;
11933 }
11934
11935 /* Make sure that the symbol we found corresponds to a function. */
11936
11937 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11938 {
11939 error (_("Symbol \"%s\" is not a function (class = %d)"),
11940 sym->linkage_name (), SYMBOL_CLASS (sym));
11941 return 0;
11942 }
11943
11944 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11945 if (sym == NULL)
11946 {
11947 struct bound_minimal_symbol msym
11948 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11949
11950 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11951 error (_("Your Ada runtime appears to be missing some debugging "
11952 "information.\nCannot insert Ada exception catchpoint "
11953 "in this configuration."));
11954
11955 return 0;
11956 }
11957
11958 /* Make sure that the symbol we found corresponds to a function. */
11959
11960 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11961 {
11962 error (_("Symbol \"%s\" is not a function (class = %d)"),
11963 sym->linkage_name (), SYMBOL_CLASS (sym));
11964 return 0;
11965 }
11966
11967 return 1;
11968 }
11969
11970 /* Inspect the Ada runtime and determine which exception info structure
11971 should be used to provide support for exception catchpoints.
11972
11973 This function will always set the per-inferior exception_info,
11974 or raise an error. */
11975
11976 static void
11977 ada_exception_support_info_sniffer (void)
11978 {
11979 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11980
11981 /* If the exception info is already known, then no need to recompute it. */
11982 if (data->exception_info != NULL)
11983 return;
11984
11985 /* Check the latest (default) exception support info. */
11986 if (ada_has_this_exception_support (&default_exception_support_info))
11987 {
11988 data->exception_info = &default_exception_support_info;
11989 return;
11990 }
11991
11992 /* Try the v0 exception suport info. */
11993 if (ada_has_this_exception_support (&exception_support_info_v0))
11994 {
11995 data->exception_info = &exception_support_info_v0;
11996 return;
11997 }
11998
11999 /* Try our fallback exception suport info. */
12000 if (ada_has_this_exception_support (&exception_support_info_fallback))
12001 {
12002 data->exception_info = &exception_support_info_fallback;
12003 return;
12004 }
12005
12006 /* Sometimes, it is normal for us to not be able to find the routine
12007 we are looking for. This happens when the program is linked with
12008 the shared version of the GNAT runtime, and the program has not been
12009 started yet. Inform the user of these two possible causes if
12010 applicable. */
12011
12012 if (ada_update_initial_language (language_unknown) != language_ada)
12013 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
12014
12015 /* If the symbol does not exist, then check that the program is
12016 already started, to make sure that shared libraries have been
12017 loaded. If it is not started, this may mean that the symbol is
12018 in a shared library. */
12019
12020 if (inferior_ptid.pid () == 0)
12021 error (_("Unable to insert catchpoint. Try to start the program first."));
12022
12023 /* At this point, we know that we are debugging an Ada program and
12024 that the inferior has been started, but we still are not able to
12025 find the run-time symbols. That can mean that we are in
12026 configurable run time mode, or that a-except as been optimized
12027 out by the linker... In any case, at this point it is not worth
12028 supporting this feature. */
12029
12030 error (_("Cannot insert Ada exception catchpoints in this configuration."));
12031 }
12032
12033 /* True iff FRAME is very likely to be that of a function that is
12034 part of the runtime system. This is all very heuristic, but is
12035 intended to be used as advice as to what frames are uninteresting
12036 to most users. */
12037
12038 static int
12039 is_known_support_routine (struct frame_info *frame)
12040 {
12041 enum language func_lang;
12042 int i;
12043 const char *fullname;
12044
12045 /* If this code does not have any debugging information (no symtab),
12046 This cannot be any user code. */
12047
12048 symtab_and_line sal = find_frame_sal (frame);
12049 if (sal.symtab == NULL)
12050 return 1;
12051
12052 /* If there is a symtab, but the associated source file cannot be
12053 located, then assume this is not user code: Selecting a frame
12054 for which we cannot display the code would not be very helpful
12055 for the user. This should also take care of case such as VxWorks
12056 where the kernel has some debugging info provided for a few units. */
12057
12058 fullname = symtab_to_fullname (sal.symtab);
12059 if (access (fullname, R_OK) != 0)
12060 return 1;
12061
12062 /* Check the unit filename against the Ada runtime file naming.
12063 We also check the name of the objfile against the name of some
12064 known system libraries that sometimes come with debugging info
12065 too. */
12066
12067 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
12068 {
12069 re_comp (known_runtime_file_name_patterns[i]);
12070 if (re_exec (lbasename (sal.symtab->filename)))
12071 return 1;
12072 if (SYMTAB_OBJFILE (sal.symtab) != NULL
12073 && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
12074 return 1;
12075 }
12076
12077 /* Check whether the function is a GNAT-generated entity. */
12078
12079 gdb::unique_xmalloc_ptr<char> func_name
12080 = find_frame_funname (frame, &func_lang, NULL);
12081 if (func_name == NULL)
12082 return 1;
12083
12084 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
12085 {
12086 re_comp (known_auxiliary_function_name_patterns[i]);
12087 if (re_exec (func_name.get ()))
12088 return 1;
12089 }
12090
12091 return 0;
12092 }
12093
12094 /* Find the first frame that contains debugging information and that is not
12095 part of the Ada run-time, starting from FI and moving upward. */
12096
12097 void
12098 ada_find_printable_frame (struct frame_info *fi)
12099 {
12100 for (; fi != NULL; fi = get_prev_frame (fi))
12101 {
12102 if (!is_known_support_routine (fi))
12103 {
12104 select_frame (fi);
12105 break;
12106 }
12107 }
12108
12109 }
12110
12111 /* Assuming that the inferior just triggered an unhandled exception
12112 catchpoint, return the address in inferior memory where the name
12113 of the exception is stored.
12114
12115 Return zero if the address could not be computed. */
12116
12117 static CORE_ADDR
12118 ada_unhandled_exception_name_addr (void)
12119 {
12120 return parse_and_eval_address ("e.full_name");
12121 }
12122
12123 /* Same as ada_unhandled_exception_name_addr, except that this function
12124 should be used when the inferior uses an older version of the runtime,
12125 where the exception name needs to be extracted from a specific frame
12126 several frames up in the callstack. */
12127
12128 static CORE_ADDR
12129 ada_unhandled_exception_name_addr_from_raise (void)
12130 {
12131 int frame_level;
12132 struct frame_info *fi;
12133 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12134
12135 /* To determine the name of this exception, we need to select
12136 the frame corresponding to RAISE_SYM_NAME. This frame is
12137 at least 3 levels up, so we simply skip the first 3 frames
12138 without checking the name of their associated function. */
12139 fi = get_current_frame ();
12140 for (frame_level = 0; frame_level < 3; frame_level += 1)
12141 if (fi != NULL)
12142 fi = get_prev_frame (fi);
12143
12144 while (fi != NULL)
12145 {
12146 enum language func_lang;
12147
12148 gdb::unique_xmalloc_ptr<char> func_name
12149 = find_frame_funname (fi, &func_lang, NULL);
12150 if (func_name != NULL)
12151 {
12152 if (strcmp (func_name.get (),
12153 data->exception_info->catch_exception_sym) == 0)
12154 break; /* We found the frame we were looking for... */
12155 }
12156 fi = get_prev_frame (fi);
12157 }
12158
12159 if (fi == NULL)
12160 return 0;
12161
12162 select_frame (fi);
12163 return parse_and_eval_address ("id.full_name");
12164 }
12165
12166 /* Assuming the inferior just triggered an Ada exception catchpoint
12167 (of any type), return the address in inferior memory where the name
12168 of the exception is stored, if applicable.
12169
12170 Assumes the selected frame is the current frame.
12171
12172 Return zero if the address could not be computed, or if not relevant. */
12173
12174 static CORE_ADDR
12175 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
12176 struct breakpoint *b)
12177 {
12178 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12179
12180 switch (ex)
12181 {
12182 case ada_catch_exception:
12183 return (parse_and_eval_address ("e.full_name"));
12184 break;
12185
12186 case ada_catch_exception_unhandled:
12187 return data->exception_info->unhandled_exception_name_addr ();
12188 break;
12189
12190 case ada_catch_handlers:
12191 return 0; /* The runtimes does not provide access to the exception
12192 name. */
12193 break;
12194
12195 case ada_catch_assert:
12196 return 0; /* Exception name is not relevant in this case. */
12197 break;
12198
12199 default:
12200 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12201 break;
12202 }
12203
12204 return 0; /* Should never be reached. */
12205 }
12206
12207 /* Assuming the inferior is stopped at an exception catchpoint,
12208 return the message which was associated to the exception, if
12209 available. Return NULL if the message could not be retrieved.
12210
12211 Note: The exception message can be associated to an exception
12212 either through the use of the Raise_Exception function, or
12213 more simply (Ada 2005 and later), via:
12214
12215 raise Exception_Name with "exception message";
12216
12217 */
12218
12219 static gdb::unique_xmalloc_ptr<char>
12220 ada_exception_message_1 (void)
12221 {
12222 struct value *e_msg_val;
12223 int e_msg_len;
12224
12225 /* For runtimes that support this feature, the exception message
12226 is passed as an unbounded string argument called "message". */
12227 e_msg_val = parse_and_eval ("message");
12228 if (e_msg_val == NULL)
12229 return NULL; /* Exception message not supported. */
12230
12231 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12232 gdb_assert (e_msg_val != NULL);
12233 e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
12234
12235 /* If the message string is empty, then treat it as if there was
12236 no exception message. */
12237 if (e_msg_len <= 0)
12238 return NULL;
12239
12240 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12241 read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
12242 e_msg_len);
12243 e_msg.get ()[e_msg_len] = '\0';
12244
12245 return e_msg;
12246 }
12247
12248 /* Same as ada_exception_message_1, except that all exceptions are
12249 contained here (returning NULL instead). */
12250
12251 static gdb::unique_xmalloc_ptr<char>
12252 ada_exception_message (void)
12253 {
12254 gdb::unique_xmalloc_ptr<char> e_msg;
12255
12256 try
12257 {
12258 e_msg = ada_exception_message_1 ();
12259 }
12260 catch (const gdb_exception_error &e)
12261 {
12262 e_msg.reset (nullptr);
12263 }
12264
12265 return e_msg;
12266 }
12267
12268 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12269 any error that ada_exception_name_addr_1 might cause to be thrown.
12270 When an error is intercepted, a warning with the error message is printed,
12271 and zero is returned. */
12272
12273 static CORE_ADDR
12274 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
12275 struct breakpoint *b)
12276 {
12277 CORE_ADDR result = 0;
12278
12279 try
12280 {
12281 result = ada_exception_name_addr_1 (ex, b);
12282 }
12283
12284 catch (const gdb_exception_error &e)
12285 {
12286 warning (_("failed to get exception name: %s"), e.what ());
12287 return 0;
12288 }
12289
12290 return result;
12291 }
12292
12293 static std::string ada_exception_catchpoint_cond_string
12294 (const char *excep_string,
12295 enum ada_exception_catchpoint_kind ex);
12296
12297 /* Ada catchpoints.
12298
12299 In the case of catchpoints on Ada exceptions, the catchpoint will
12300 stop the target on every exception the program throws. When a user
12301 specifies the name of a specific exception, we translate this
12302 request into a condition expression (in text form), and then parse
12303 it into an expression stored in each of the catchpoint's locations.
12304 We then use this condition to check whether the exception that was
12305 raised is the one the user is interested in. If not, then the
12306 target is resumed again. We store the name of the requested
12307 exception, in order to be able to re-set the condition expression
12308 when symbols change. */
12309
12310 /* An instance of this type is used to represent an Ada catchpoint
12311 breakpoint location. */
12312
12313 class ada_catchpoint_location : public bp_location
12314 {
12315 public:
12316 ada_catchpoint_location (breakpoint *owner)
12317 : bp_location (owner, bp_loc_software_breakpoint)
12318 {}
12319
12320 /* The condition that checks whether the exception that was raised
12321 is the specific exception the user specified on catchpoint
12322 creation. */
12323 expression_up excep_cond_expr;
12324 };
12325
12326 /* An instance of this type is used to represent an Ada catchpoint. */
12327
12328 struct ada_catchpoint : public breakpoint
12329 {
12330 explicit ada_catchpoint (enum ada_exception_catchpoint_kind kind)
12331 : m_kind (kind)
12332 {
12333 }
12334
12335 /* The name of the specific exception the user specified. */
12336 std::string excep_string;
12337
12338 /* What kind of catchpoint this is. */
12339 enum ada_exception_catchpoint_kind m_kind;
12340 };
12341
12342 /* Parse the exception condition string in the context of each of the
12343 catchpoint's locations, and store them for later evaluation. */
12344
12345 static void
12346 create_excep_cond_exprs (struct ada_catchpoint *c,
12347 enum ada_exception_catchpoint_kind ex)
12348 {
12349 struct bp_location *bl;
12350
12351 /* Nothing to do if there's no specific exception to catch. */
12352 if (c->excep_string.empty ())
12353 return;
12354
12355 /* Same if there are no locations... */
12356 if (c->loc == NULL)
12357 return;
12358
12359 /* Compute the condition expression in text form, from the specific
12360 expection we want to catch. */
12361 std::string cond_string
12362 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12363
12364 /* Iterate over all the catchpoint's locations, and parse an
12365 expression for each. */
12366 for (bl = c->loc; bl != NULL; bl = bl->next)
12367 {
12368 struct ada_catchpoint_location *ada_loc
12369 = (struct ada_catchpoint_location *) bl;
12370 expression_up exp;
12371
12372 if (!bl->shlib_disabled)
12373 {
12374 const char *s;
12375
12376 s = cond_string.c_str ();
12377 try
12378 {
12379 exp = parse_exp_1 (&s, bl->address,
12380 block_for_pc (bl->address),
12381 0);
12382 }
12383 catch (const gdb_exception_error &e)
12384 {
12385 warning (_("failed to reevaluate internal exception condition "
12386 "for catchpoint %d: %s"),
12387 c->number, e.what ());
12388 }
12389 }
12390
12391 ada_loc->excep_cond_expr = std::move (exp);
12392 }
12393 }
12394
12395 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
12396 structure for all exception catchpoint kinds. */
12397
12398 static struct bp_location *
12399 allocate_location_exception (struct breakpoint *self)
12400 {
12401 return new ada_catchpoint_location (self);
12402 }
12403
12404 /* Implement the RE_SET method in the breakpoint_ops structure for all
12405 exception catchpoint kinds. */
12406
12407 static void
12408 re_set_exception (struct breakpoint *b)
12409 {
12410 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12411
12412 /* Call the base class's method. This updates the catchpoint's
12413 locations. */
12414 bkpt_breakpoint_ops.re_set (b);
12415
12416 /* Reparse the exception conditional expressions. One for each
12417 location. */
12418 create_excep_cond_exprs (c, c->m_kind);
12419 }
12420
12421 /* Returns true if we should stop for this breakpoint hit. If the
12422 user specified a specific exception, we only want to cause a stop
12423 if the program thrown that exception. */
12424
12425 static int
12426 should_stop_exception (const struct bp_location *bl)
12427 {
12428 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12429 const struct ada_catchpoint_location *ada_loc
12430 = (const struct ada_catchpoint_location *) bl;
12431 int stop;
12432
12433 struct internalvar *var = lookup_internalvar ("_ada_exception");
12434 if (c->m_kind == ada_catch_assert)
12435 clear_internalvar (var);
12436 else
12437 {
12438 try
12439 {
12440 const char *expr;
12441
12442 if (c->m_kind == ada_catch_handlers)
12443 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12444 ".all.occurrence.id");
12445 else
12446 expr = "e";
12447
12448 struct value *exc = parse_and_eval (expr);
12449 set_internalvar (var, exc);
12450 }
12451 catch (const gdb_exception_error &ex)
12452 {
12453 clear_internalvar (var);
12454 }
12455 }
12456
12457 /* With no specific exception, should always stop. */
12458 if (c->excep_string.empty ())
12459 return 1;
12460
12461 if (ada_loc->excep_cond_expr == NULL)
12462 {
12463 /* We will have a NULL expression if back when we were creating
12464 the expressions, this location's had failed to parse. */
12465 return 1;
12466 }
12467
12468 stop = 1;
12469 try
12470 {
12471 struct value *mark;
12472
12473 mark = value_mark ();
12474 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
12475 value_free_to_mark (mark);
12476 }
12477 catch (const gdb_exception &ex)
12478 {
12479 exception_fprintf (gdb_stderr, ex,
12480 _("Error in testing exception condition:\n"));
12481 }
12482
12483 return stop;
12484 }
12485
12486 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
12487 for all exception catchpoint kinds. */
12488
12489 static void
12490 check_status_exception (bpstat bs)
12491 {
12492 bs->stop = should_stop_exception (bs->bp_location_at.get ());
12493 }
12494
12495 /* Implement the PRINT_IT method in the breakpoint_ops structure
12496 for all exception catchpoint kinds. */
12497
12498 static enum print_stop_action
12499 print_it_exception (bpstat bs)
12500 {
12501 struct ui_out *uiout = current_uiout;
12502 struct breakpoint *b = bs->breakpoint_at;
12503
12504 annotate_catchpoint (b->number);
12505
12506 if (uiout->is_mi_like_p ())
12507 {
12508 uiout->field_string ("reason",
12509 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12510 uiout->field_string ("disp", bpdisp_text (b->disposition));
12511 }
12512
12513 uiout->text (b->disposition == disp_del
12514 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12515 uiout->field_signed ("bkptno", b->number);
12516 uiout->text (", ");
12517
12518 /* ada_exception_name_addr relies on the selected frame being the
12519 current frame. Need to do this here because this function may be
12520 called more than once when printing a stop, and below, we'll
12521 select the first frame past the Ada run-time (see
12522 ada_find_printable_frame). */
12523 select_frame (get_current_frame ());
12524
12525 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12526 switch (c->m_kind)
12527 {
12528 case ada_catch_exception:
12529 case ada_catch_exception_unhandled:
12530 case ada_catch_handlers:
12531 {
12532 const CORE_ADDR addr = ada_exception_name_addr (c->m_kind, b);
12533 char exception_name[256];
12534
12535 if (addr != 0)
12536 {
12537 read_memory (addr, (gdb_byte *) exception_name,
12538 sizeof (exception_name) - 1);
12539 exception_name [sizeof (exception_name) - 1] = '\0';
12540 }
12541 else
12542 {
12543 /* For some reason, we were unable to read the exception
12544 name. This could happen if the Runtime was compiled
12545 without debugging info, for instance. In that case,
12546 just replace the exception name by the generic string
12547 "exception" - it will read as "an exception" in the
12548 notification we are about to print. */
12549 memcpy (exception_name, "exception", sizeof ("exception"));
12550 }
12551 /* In the case of unhandled exception breakpoints, we print
12552 the exception name as "unhandled EXCEPTION_NAME", to make
12553 it clearer to the user which kind of catchpoint just got
12554 hit. We used ui_out_text to make sure that this extra
12555 info does not pollute the exception name in the MI case. */
12556 if (c->m_kind == ada_catch_exception_unhandled)
12557 uiout->text ("unhandled ");
12558 uiout->field_string ("exception-name", exception_name);
12559 }
12560 break;
12561 case ada_catch_assert:
12562 /* In this case, the name of the exception is not really
12563 important. Just print "failed assertion" to make it clearer
12564 that his program just hit an assertion-failure catchpoint.
12565 We used ui_out_text because this info does not belong in
12566 the MI output. */
12567 uiout->text ("failed assertion");
12568 break;
12569 }
12570
12571 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12572 if (exception_message != NULL)
12573 {
12574 uiout->text (" (");
12575 uiout->field_string ("exception-message", exception_message.get ());
12576 uiout->text (")");
12577 }
12578
12579 uiout->text (" at ");
12580 ada_find_printable_frame (get_current_frame ());
12581
12582 return PRINT_SRC_AND_LOC;
12583 }
12584
12585 /* Implement the PRINT_ONE method in the breakpoint_ops structure
12586 for all exception catchpoint kinds. */
12587
12588 static void
12589 print_one_exception (struct breakpoint *b, struct bp_location **last_loc)
12590 {
12591 struct ui_out *uiout = current_uiout;
12592 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12593 struct value_print_options opts;
12594
12595 get_user_print_options (&opts);
12596
12597 if (opts.addressprint)
12598 uiout->field_skip ("addr");
12599
12600 annotate_field (5);
12601 switch (c->m_kind)
12602 {
12603 case ada_catch_exception:
12604 if (!c->excep_string.empty ())
12605 {
12606 std::string msg = string_printf (_("`%s' Ada exception"),
12607 c->excep_string.c_str ());
12608
12609 uiout->field_string ("what", msg);
12610 }
12611 else
12612 uiout->field_string ("what", "all Ada exceptions");
12613
12614 break;
12615
12616 case ada_catch_exception_unhandled:
12617 uiout->field_string ("what", "unhandled Ada exceptions");
12618 break;
12619
12620 case ada_catch_handlers:
12621 if (!c->excep_string.empty ())
12622 {
12623 uiout->field_fmt ("what",
12624 _("`%s' Ada exception handlers"),
12625 c->excep_string.c_str ());
12626 }
12627 else
12628 uiout->field_string ("what", "all Ada exceptions handlers");
12629 break;
12630
12631 case ada_catch_assert:
12632 uiout->field_string ("what", "failed Ada assertions");
12633 break;
12634
12635 default:
12636 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12637 break;
12638 }
12639 }
12640
12641 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12642 for all exception catchpoint kinds. */
12643
12644 static void
12645 print_mention_exception (struct breakpoint *b)
12646 {
12647 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12648 struct ui_out *uiout = current_uiout;
12649
12650 uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
12651 : _("Catchpoint "));
12652 uiout->field_signed ("bkptno", b->number);
12653 uiout->text (": ");
12654
12655 switch (c->m_kind)
12656 {
12657 case ada_catch_exception:
12658 if (!c->excep_string.empty ())
12659 {
12660 std::string info = string_printf (_("`%s' Ada exception"),
12661 c->excep_string.c_str ());
12662 uiout->text (info.c_str ());
12663 }
12664 else
12665 uiout->text (_("all Ada exceptions"));
12666 break;
12667
12668 case ada_catch_exception_unhandled:
12669 uiout->text (_("unhandled Ada exceptions"));
12670 break;
12671
12672 case ada_catch_handlers:
12673 if (!c->excep_string.empty ())
12674 {
12675 std::string info
12676 = string_printf (_("`%s' Ada exception handlers"),
12677 c->excep_string.c_str ());
12678 uiout->text (info.c_str ());
12679 }
12680 else
12681 uiout->text (_("all Ada exceptions handlers"));
12682 break;
12683
12684 case ada_catch_assert:
12685 uiout->text (_("failed Ada assertions"));
12686 break;
12687
12688 default:
12689 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12690 break;
12691 }
12692 }
12693
12694 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
12695 for all exception catchpoint kinds. */
12696
12697 static void
12698 print_recreate_exception (struct breakpoint *b, struct ui_file *fp)
12699 {
12700 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12701
12702 switch (c->m_kind)
12703 {
12704 case ada_catch_exception:
12705 fprintf_filtered (fp, "catch exception");
12706 if (!c->excep_string.empty ())
12707 fprintf_filtered (fp, " %s", c->excep_string.c_str ());
12708 break;
12709
12710 case ada_catch_exception_unhandled:
12711 fprintf_filtered (fp, "catch exception unhandled");
12712 break;
12713
12714 case ada_catch_handlers:
12715 fprintf_filtered (fp, "catch handlers");
12716 break;
12717
12718 case ada_catch_assert:
12719 fprintf_filtered (fp, "catch assert");
12720 break;
12721
12722 default:
12723 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12724 }
12725 print_recreate_thread (b, fp);
12726 }
12727
12728 /* Virtual tables for various breakpoint types. */
12729 static struct breakpoint_ops catch_exception_breakpoint_ops;
12730 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
12731 static struct breakpoint_ops catch_assert_breakpoint_ops;
12732 static struct breakpoint_ops catch_handlers_breakpoint_ops;
12733
12734 /* See ada-lang.h. */
12735
12736 bool
12737 is_ada_exception_catchpoint (breakpoint *bp)
12738 {
12739 return (bp->ops == &catch_exception_breakpoint_ops
12740 || bp->ops == &catch_exception_unhandled_breakpoint_ops
12741 || bp->ops == &catch_assert_breakpoint_ops
12742 || bp->ops == &catch_handlers_breakpoint_ops);
12743 }
12744
12745 /* Split the arguments specified in a "catch exception" command.
12746 Set EX to the appropriate catchpoint type.
12747 Set EXCEP_STRING to the name of the specific exception if
12748 specified by the user.
12749 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12750 "catch handlers" command. False otherwise.
12751 If a condition is found at the end of the arguments, the condition
12752 expression is stored in COND_STRING (memory must be deallocated
12753 after use). Otherwise COND_STRING is set to NULL. */
12754
12755 static void
12756 catch_ada_exception_command_split (const char *args,
12757 bool is_catch_handlers_cmd,
12758 enum ada_exception_catchpoint_kind *ex,
12759 std::string *excep_string,
12760 std::string *cond_string)
12761 {
12762 std::string exception_name;
12763
12764 exception_name = extract_arg (&args);
12765 if (exception_name == "if")
12766 {
12767 /* This is not an exception name; this is the start of a condition
12768 expression for a catchpoint on all exceptions. So, "un-get"
12769 this token, and set exception_name to NULL. */
12770 exception_name.clear ();
12771 args -= 2;
12772 }
12773
12774 /* Check to see if we have a condition. */
12775
12776 args = skip_spaces (args);
12777 if (startswith (args, "if")
12778 && (isspace (args[2]) || args[2] == '\0'))
12779 {
12780 args += 2;
12781 args = skip_spaces (args);
12782
12783 if (args[0] == '\0')
12784 error (_("Condition missing after `if' keyword"));
12785 *cond_string = args;
12786
12787 args += strlen (args);
12788 }
12789
12790 /* Check that we do not have any more arguments. Anything else
12791 is unexpected. */
12792
12793 if (args[0] != '\0')
12794 error (_("Junk at end of expression"));
12795
12796 if (is_catch_handlers_cmd)
12797 {
12798 /* Catch handling of exceptions. */
12799 *ex = ada_catch_handlers;
12800 *excep_string = exception_name;
12801 }
12802 else if (exception_name.empty ())
12803 {
12804 /* Catch all exceptions. */
12805 *ex = ada_catch_exception;
12806 excep_string->clear ();
12807 }
12808 else if (exception_name == "unhandled")
12809 {
12810 /* Catch unhandled exceptions. */
12811 *ex = ada_catch_exception_unhandled;
12812 excep_string->clear ();
12813 }
12814 else
12815 {
12816 /* Catch a specific exception. */
12817 *ex = ada_catch_exception;
12818 *excep_string = exception_name;
12819 }
12820 }
12821
12822 /* Return the name of the symbol on which we should break in order to
12823 implement a catchpoint of the EX kind. */
12824
12825 static const char *
12826 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12827 {
12828 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12829
12830 gdb_assert (data->exception_info != NULL);
12831
12832 switch (ex)
12833 {
12834 case ada_catch_exception:
12835 return (data->exception_info->catch_exception_sym);
12836 break;
12837 case ada_catch_exception_unhandled:
12838 return (data->exception_info->catch_exception_unhandled_sym);
12839 break;
12840 case ada_catch_assert:
12841 return (data->exception_info->catch_assert_sym);
12842 break;
12843 case ada_catch_handlers:
12844 return (data->exception_info->catch_handlers_sym);
12845 break;
12846 default:
12847 internal_error (__FILE__, __LINE__,
12848 _("unexpected catchpoint kind (%d)"), ex);
12849 }
12850 }
12851
12852 /* Return the breakpoint ops "virtual table" used for catchpoints
12853 of the EX kind. */
12854
12855 static const struct breakpoint_ops *
12856 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
12857 {
12858 switch (ex)
12859 {
12860 case ada_catch_exception:
12861 return (&catch_exception_breakpoint_ops);
12862 break;
12863 case ada_catch_exception_unhandled:
12864 return (&catch_exception_unhandled_breakpoint_ops);
12865 break;
12866 case ada_catch_assert:
12867 return (&catch_assert_breakpoint_ops);
12868 break;
12869 case ada_catch_handlers:
12870 return (&catch_handlers_breakpoint_ops);
12871 break;
12872 default:
12873 internal_error (__FILE__, __LINE__,
12874 _("unexpected catchpoint kind (%d)"), ex);
12875 }
12876 }
12877
12878 /* Return the condition that will be used to match the current exception
12879 being raised with the exception that the user wants to catch. This
12880 assumes that this condition is used when the inferior just triggered
12881 an exception catchpoint.
12882 EX: the type of catchpoints used for catching Ada exceptions. */
12883
12884 static std::string
12885 ada_exception_catchpoint_cond_string (const char *excep_string,
12886 enum ada_exception_catchpoint_kind ex)
12887 {
12888 int i;
12889 bool is_standard_exc = false;
12890 std::string result;
12891
12892 if (ex == ada_catch_handlers)
12893 {
12894 /* For exception handlers catchpoints, the condition string does
12895 not use the same parameter as for the other exceptions. */
12896 result = ("long_integer (GNAT_GCC_exception_Access"
12897 "(gcc_exception).all.occurrence.id)");
12898 }
12899 else
12900 result = "long_integer (e)";
12901
12902 /* The standard exceptions are a special case. They are defined in
12903 runtime units that have been compiled without debugging info; if
12904 EXCEP_STRING is the not-fully-qualified name of a standard
12905 exception (e.g. "constraint_error") then, during the evaluation
12906 of the condition expression, the symbol lookup on this name would
12907 *not* return this standard exception. The catchpoint condition
12908 may then be set only on user-defined exceptions which have the
12909 same not-fully-qualified name (e.g. my_package.constraint_error).
12910
12911 To avoid this unexcepted behavior, these standard exceptions are
12912 systematically prefixed by "standard". This means that "catch
12913 exception constraint_error" is rewritten into "catch exception
12914 standard.constraint_error".
12915
12916 If an exception named constraint_error is defined in another package of
12917 the inferior program, then the only way to specify this exception as a
12918 breakpoint condition is to use its fully-qualified named:
12919 e.g. my_package.constraint_error. */
12920
12921 for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
12922 {
12923 if (strcmp (standard_exc [i], excep_string) == 0)
12924 {
12925 is_standard_exc = true;
12926 break;
12927 }
12928 }
12929
12930 result += " = ";
12931
12932 if (is_standard_exc)
12933 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12934 else
12935 string_appendf (result, "long_integer (&%s)", excep_string);
12936
12937 return result;
12938 }
12939
12940 /* Return the symtab_and_line that should be used to insert an exception
12941 catchpoint of the TYPE kind.
12942
12943 ADDR_STRING returns the name of the function where the real
12944 breakpoint that implements the catchpoints is set, depending on the
12945 type of catchpoint we need to create. */
12946
12947 static struct symtab_and_line
12948 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12949 std::string *addr_string, const struct breakpoint_ops **ops)
12950 {
12951 const char *sym_name;
12952 struct symbol *sym;
12953
12954 /* First, find out which exception support info to use. */
12955 ada_exception_support_info_sniffer ();
12956
12957 /* Then lookup the function on which we will break in order to catch
12958 the Ada exceptions requested by the user. */
12959 sym_name = ada_exception_sym_name (ex);
12960 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12961
12962 if (sym == NULL)
12963 error (_("Catchpoint symbol not found: %s"), sym_name);
12964
12965 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12966 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12967
12968 /* Set ADDR_STRING. */
12969 *addr_string = sym_name;
12970
12971 /* Set OPS. */
12972 *ops = ada_exception_breakpoint_ops (ex);
12973
12974 return find_function_start_sal (sym, 1);
12975 }
12976
12977 /* Create an Ada exception catchpoint.
12978
12979 EX_KIND is the kind of exception catchpoint to be created.
12980
12981 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12982 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12983 of the exception to which this catchpoint applies.
12984
12985 COND_STRING, if not empty, is the catchpoint condition.
12986
12987 TEMPFLAG, if nonzero, means that the underlying breakpoint
12988 should be temporary.
12989
12990 FROM_TTY is the usual argument passed to all commands implementations. */
12991
12992 void
12993 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12994 enum ada_exception_catchpoint_kind ex_kind,
12995 const std::string &excep_string,
12996 const std::string &cond_string,
12997 int tempflag,
12998 int disabled,
12999 int from_tty)
13000 {
13001 std::string addr_string;
13002 const struct breakpoint_ops *ops = NULL;
13003 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
13004
13005 std::unique_ptr<ada_catchpoint> c (new ada_catchpoint (ex_kind));
13006 init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
13007 ops, tempflag, disabled, from_tty);
13008 c->excep_string = excep_string;
13009 create_excep_cond_exprs (c.get (), ex_kind);
13010 if (!cond_string.empty ())
13011 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
13012 install_breakpoint (0, std::move (c), 1);
13013 }
13014
13015 /* Implement the "catch exception" command. */
13016
13017 static void
13018 catch_ada_exception_command (const char *arg_entry, int from_tty,
13019 struct cmd_list_element *command)
13020 {
13021 const char *arg = arg_entry;
13022 struct gdbarch *gdbarch = get_current_arch ();
13023 int tempflag;
13024 enum ada_exception_catchpoint_kind ex_kind;
13025 std::string excep_string;
13026 std::string cond_string;
13027
13028 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13029
13030 if (!arg)
13031 arg = "";
13032 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
13033 &cond_string);
13034 create_ada_exception_catchpoint (gdbarch, ex_kind,
13035 excep_string, cond_string,
13036 tempflag, 1 /* enabled */,
13037 from_tty);
13038 }
13039
13040 /* Implement the "catch handlers" command. */
13041
13042 static void
13043 catch_ada_handlers_command (const char *arg_entry, int from_tty,
13044 struct cmd_list_element *command)
13045 {
13046 const char *arg = arg_entry;
13047 struct gdbarch *gdbarch = get_current_arch ();
13048 int tempflag;
13049 enum ada_exception_catchpoint_kind ex_kind;
13050 std::string excep_string;
13051 std::string cond_string;
13052
13053 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13054
13055 if (!arg)
13056 arg = "";
13057 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
13058 &cond_string);
13059 create_ada_exception_catchpoint (gdbarch, ex_kind,
13060 excep_string, cond_string,
13061 tempflag, 1 /* enabled */,
13062 from_tty);
13063 }
13064
13065 /* Completion function for the Ada "catch" commands. */
13066
13067 static void
13068 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
13069 const char *text, const char *word)
13070 {
13071 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
13072
13073 for (const ada_exc_info &info : exceptions)
13074 {
13075 if (startswith (info.name, word))
13076 tracker.add_completion (make_unique_xstrdup (info.name));
13077 }
13078 }
13079
13080 /* Split the arguments specified in a "catch assert" command.
13081
13082 ARGS contains the command's arguments (or the empty string if
13083 no arguments were passed).
13084
13085 If ARGS contains a condition, set COND_STRING to that condition
13086 (the memory needs to be deallocated after use). */
13087
13088 static void
13089 catch_ada_assert_command_split (const char *args, std::string &cond_string)
13090 {
13091 args = skip_spaces (args);
13092
13093 /* Check whether a condition was provided. */
13094 if (startswith (args, "if")
13095 && (isspace (args[2]) || args[2] == '\0'))
13096 {
13097 args += 2;
13098 args = skip_spaces (args);
13099 if (args[0] == '\0')
13100 error (_("condition missing after `if' keyword"));
13101 cond_string.assign (args);
13102 }
13103
13104 /* Otherwise, there should be no other argument at the end of
13105 the command. */
13106 else if (args[0] != '\0')
13107 error (_("Junk at end of arguments."));
13108 }
13109
13110 /* Implement the "catch assert" command. */
13111
13112 static void
13113 catch_assert_command (const char *arg_entry, int from_tty,
13114 struct cmd_list_element *command)
13115 {
13116 const char *arg = arg_entry;
13117 struct gdbarch *gdbarch = get_current_arch ();
13118 int tempflag;
13119 std::string cond_string;
13120
13121 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13122
13123 if (!arg)
13124 arg = "";
13125 catch_ada_assert_command_split (arg, cond_string);
13126 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
13127 "", cond_string,
13128 tempflag, 1 /* enabled */,
13129 from_tty);
13130 }
13131
13132 /* Return non-zero if the symbol SYM is an Ada exception object. */
13133
13134 static int
13135 ada_is_exception_sym (struct symbol *sym)
13136 {
13137 const char *type_name = SYMBOL_TYPE (sym)->name ();
13138
13139 return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
13140 && SYMBOL_CLASS (sym) != LOC_BLOCK
13141 && SYMBOL_CLASS (sym) != LOC_CONST
13142 && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
13143 && type_name != NULL && strcmp (type_name, "exception") == 0);
13144 }
13145
13146 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
13147 Ada exception object. This matches all exceptions except the ones
13148 defined by the Ada language. */
13149
13150 static int
13151 ada_is_non_standard_exception_sym (struct symbol *sym)
13152 {
13153 int i;
13154
13155 if (!ada_is_exception_sym (sym))
13156 return 0;
13157
13158 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13159 if (strcmp (sym->linkage_name (), standard_exc[i]) == 0)
13160 return 0; /* A standard exception. */
13161
13162 /* Numeric_Error is also a standard exception, so exclude it.
13163 See the STANDARD_EXC description for more details as to why
13164 this exception is not listed in that array. */
13165 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
13166 return 0;
13167
13168 return 1;
13169 }
13170
13171 /* A helper function for std::sort, comparing two struct ada_exc_info
13172 objects.
13173
13174 The comparison is determined first by exception name, and then
13175 by exception address. */
13176
13177 bool
13178 ada_exc_info::operator< (const ada_exc_info &other) const
13179 {
13180 int result;
13181
13182 result = strcmp (name, other.name);
13183 if (result < 0)
13184 return true;
13185 if (result == 0 && addr < other.addr)
13186 return true;
13187 return false;
13188 }
13189
13190 bool
13191 ada_exc_info::operator== (const ada_exc_info &other) const
13192 {
13193 return addr == other.addr && strcmp (name, other.name) == 0;
13194 }
13195
13196 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13197 routine, but keeping the first SKIP elements untouched.
13198
13199 All duplicates are also removed. */
13200
13201 static void
13202 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13203 int skip)
13204 {
13205 std::sort (exceptions->begin () + skip, exceptions->end ());
13206 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13207 exceptions->end ());
13208 }
13209
13210 /* Add all exceptions defined by the Ada standard whose name match
13211 a regular expression.
13212
13213 If PREG is not NULL, then this regexp_t object is used to
13214 perform the symbol name matching. Otherwise, no name-based
13215 filtering is performed.
13216
13217 EXCEPTIONS is a vector of exceptions to which matching exceptions
13218 gets pushed. */
13219
13220 static void
13221 ada_add_standard_exceptions (compiled_regex *preg,
13222 std::vector<ada_exc_info> *exceptions)
13223 {
13224 int i;
13225
13226 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13227 {
13228 if (preg == NULL
13229 || preg->exec (standard_exc[i], 0, NULL, 0) == 0)
13230 {
13231 struct bound_minimal_symbol msymbol
13232 = ada_lookup_simple_minsym (standard_exc[i]);
13233
13234 if (msymbol.minsym != NULL)
13235 {
13236 struct ada_exc_info info
13237 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};
13238
13239 exceptions->push_back (info);
13240 }
13241 }
13242 }
13243 }
13244
13245 /* Add all Ada exceptions defined locally and accessible from the given
13246 FRAME.
13247
13248 If PREG is not NULL, then this regexp_t object is used to
13249 perform the symbol name matching. Otherwise, no name-based
13250 filtering is performed.
13251
13252 EXCEPTIONS is a vector of exceptions to which matching exceptions
13253 gets pushed. */
13254
13255 static void
13256 ada_add_exceptions_from_frame (compiled_regex *preg,
13257 struct frame_info *frame,
13258 std::vector<ada_exc_info> *exceptions)
13259 {
13260 const struct block *block = get_frame_block (frame, 0);
13261
13262 while (block != 0)
13263 {
13264 struct block_iterator iter;
13265 struct symbol *sym;
13266
13267 ALL_BLOCK_SYMBOLS (block, iter, sym)
13268 {
13269 switch (SYMBOL_CLASS (sym))
13270 {
13271 case LOC_TYPEDEF:
13272 case LOC_BLOCK:
13273 case LOC_CONST:
13274 break;
13275 default:
13276 if (ada_is_exception_sym (sym))
13277 {
13278 struct ada_exc_info info = {sym->print_name (),
13279 SYMBOL_VALUE_ADDRESS (sym)};
13280
13281 exceptions->push_back (info);
13282 }
13283 }
13284 }
13285 if (BLOCK_FUNCTION (block) != NULL)
13286 break;
13287 block = BLOCK_SUPERBLOCK (block);
13288 }
13289 }
13290
13291 /* Return true if NAME matches PREG or if PREG is NULL. */
13292
13293 static bool
13294 name_matches_regex (const char *name, compiled_regex *preg)
13295 {
13296 return (preg == NULL
13297 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13298 }
13299
13300 /* Add all exceptions defined globally whose name name match
13301 a regular expression, excluding standard exceptions.
13302
13303 The reason we exclude standard exceptions is that they need
13304 to be handled separately: Standard exceptions are defined inside
13305 a runtime unit which is normally not compiled with debugging info,
13306 and thus usually do not show up in our symbol search. However,
13307 if the unit was in fact built with debugging info, we need to
13308 exclude them because they would duplicate the entry we found
13309 during the special loop that specifically searches for those
13310 standard exceptions.
13311
13312 If PREG is not NULL, then this regexp_t object is used to
13313 perform the symbol name matching. Otherwise, no name-based
13314 filtering is performed.
13315
13316 EXCEPTIONS is a vector of exceptions to which matching exceptions
13317 gets pushed. */
13318
13319 static void
13320 ada_add_global_exceptions (compiled_regex *preg,
13321 std::vector<ada_exc_info> *exceptions)
13322 {
13323 /* In Ada, the symbol "search name" is a linkage name, whereas the
13324 regular expression used to do the matching refers to the natural
13325 name. So match against the decoded name. */
13326 expand_symtabs_matching (NULL,
13327 lookup_name_info::match_any (),
13328 [&] (const char *search_name)
13329 {
13330 std::string decoded = ada_decode (search_name);
13331 return name_matches_regex (decoded.c_str (), preg);
13332 },
13333 NULL,
13334 VARIABLES_DOMAIN);
13335
13336 for (objfile *objfile : current_program_space->objfiles ())
13337 {
13338 for (compunit_symtab *s : objfile->compunits ())
13339 {
13340 const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
13341 int i;
13342
13343 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13344 {
13345 const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
13346 struct block_iterator iter;
13347 struct symbol *sym;
13348
13349 ALL_BLOCK_SYMBOLS (b, iter, sym)
13350 if (ada_is_non_standard_exception_sym (sym)
13351 && name_matches_regex (sym->natural_name (), preg))
13352 {
13353 struct ada_exc_info info
13354 = {sym->print_name (), SYMBOL_VALUE_ADDRESS (sym)};
13355
13356 exceptions->push_back (info);
13357 }
13358 }
13359 }
13360 }
13361 }
13362
13363 /* Implements ada_exceptions_list with the regular expression passed
13364 as a regex_t, rather than a string.
13365
13366 If not NULL, PREG is used to filter out exceptions whose names
13367 do not match. Otherwise, all exceptions are listed. */
13368
13369 static std::vector<ada_exc_info>
13370 ada_exceptions_list_1 (compiled_regex *preg)
13371 {
13372 std::vector<ada_exc_info> result;
13373 int prev_len;
13374
13375 /* First, list the known standard exceptions. These exceptions
13376 need to be handled separately, as they are usually defined in
13377 runtime units that have been compiled without debugging info. */
13378
13379 ada_add_standard_exceptions (preg, &result);
13380
13381 /* Next, find all exceptions whose scope is local and accessible
13382 from the currently selected frame. */
13383
13384 if (has_stack_frames ())
13385 {
13386 prev_len = result.size ();
13387 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13388 &result);
13389 if (result.size () > prev_len)
13390 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13391 }
13392
13393 /* Add all exceptions whose scope is global. */
13394
13395 prev_len = result.size ();
13396 ada_add_global_exceptions (preg, &result);
13397 if (result.size () > prev_len)
13398 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13399
13400 return result;
13401 }
13402
13403 /* Return a vector of ada_exc_info.
13404
13405 If REGEXP is NULL, all exceptions are included in the result.
13406 Otherwise, it should contain a valid regular expression,
13407 and only the exceptions whose names match that regular expression
13408 are included in the result.
13409
13410 The exceptions are sorted in the following order:
13411 - Standard exceptions (defined by the Ada language), in
13412 alphabetical order;
13413 - Exceptions only visible from the current frame, in
13414 alphabetical order;
13415 - Exceptions whose scope is global, in alphabetical order. */
13416
13417 std::vector<ada_exc_info>
13418 ada_exceptions_list (const char *regexp)
13419 {
13420 if (regexp == NULL)
13421 return ada_exceptions_list_1 (NULL);
13422
13423 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13424 return ada_exceptions_list_1 (&reg);
13425 }
13426
13427 /* Implement the "info exceptions" command. */
13428
13429 static void
13430 info_exceptions_command (const char *regexp, int from_tty)
13431 {
13432 struct gdbarch *gdbarch = get_current_arch ();
13433
13434 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13435
13436 if (regexp != NULL)
13437 printf_filtered
13438 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13439 else
13440 printf_filtered (_("All defined Ada exceptions:\n"));
13441
13442 for (const ada_exc_info &info : exceptions)
13443 printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13444 }
13445
13446 /* Operators */
13447 /* Information about operators given special treatment in functions
13448 below. */
13449 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>). */
13450
13451 #define ADA_OPERATORS \
13452 OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
13453 OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
13454 OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
13455 OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
13456 OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
13457 OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
13458 OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
13459 OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
13460 OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
13461 OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
13462 OP_DEFN (OP_ATR_POS, 1, 2, 0) \
13463 OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
13464 OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
13465 OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
13466 OP_DEFN (UNOP_QUAL, 3, 1, 0) \
13467 OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
13468 OP_DEFN (OP_OTHERS, 1, 1, 0) \
13469 OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
13470 OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
13471
13472 static void
13473 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
13474 int *argsp)
13475 {
13476 switch (exp->elts[pc - 1].opcode)
13477 {
13478 default:
13479 operator_length_standard (exp, pc, oplenp, argsp);
13480 break;
13481
13482 #define OP_DEFN(op, len, args, binop) \
13483 case op: *oplenp = len; *argsp = args; break;
13484 ADA_OPERATORS;
13485 #undef OP_DEFN
13486
13487 case OP_AGGREGATE:
13488 *oplenp = 3;
13489 *argsp = longest_to_int (exp->elts[pc - 2].longconst);
13490 break;
13491
13492 case OP_CHOICES:
13493 *oplenp = 3;
13494 *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
13495 break;
13496 }
13497 }
13498
13499 /* Implementation of the exp_descriptor method operator_check. */
13500
13501 static int
13502 ada_operator_check (struct expression *exp, int pos,
13503 int (*objfile_func) (struct objfile *objfile, void *data),
13504 void *data)
13505 {
13506 const union exp_element *const elts = exp->elts;
13507 struct type *type = NULL;
13508
13509 switch (elts[pos].opcode)
13510 {
13511 case UNOP_IN_RANGE:
13512 case UNOP_QUAL:
13513 type = elts[pos + 1].type;
13514 break;
13515
13516 default:
13517 return operator_check_standard (exp, pos, objfile_func, data);
13518 }
13519
13520 /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL. */
13521
13522 if (type != nullptr && type->objfile_owner () != nullptr
13523 && objfile_func (type->objfile_owner (), data))
13524 return 1;
13525
13526 return 0;
13527 }
13528
13529 /* As for operator_length, but assumes PC is pointing at the first
13530 element of the operator, and gives meaningful results only for the
13531 Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise. */
13532
13533 static void
13534 ada_forward_operator_length (struct expression *exp, int pc,
13535 int *oplenp, int *argsp)
13536 {
13537 switch (exp->elts[pc].opcode)
13538 {
13539 default:
13540 *oplenp = *argsp = 0;
13541 break;
13542
13543 #define OP_DEFN(op, len, args, binop) \
13544 case op: *oplenp = len; *argsp = args; break;
13545 ADA_OPERATORS;
13546 #undef OP_DEFN
13547
13548 case OP_AGGREGATE:
13549 *oplenp = 3;
13550 *argsp = longest_to_int (exp->elts[pc + 1].longconst);
13551 break;
13552
13553 case OP_CHOICES:
13554 *oplenp = 3;
13555 *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
13556 break;
13557
13558 case OP_STRING:
13559 case OP_NAME:
13560 {
13561 int len = longest_to_int (exp->elts[pc + 1].longconst);
13562
13563 *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
13564 *argsp = 0;
13565 break;
13566 }
13567 }
13568 }
13569
13570 static int
13571 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
13572 {
13573 enum exp_opcode op = exp->elts[elt].opcode;
13574 int oplen, nargs;
13575 int pc = elt;
13576 int i;
13577
13578 ada_forward_operator_length (exp, elt, &oplen, &nargs);
13579
13580 switch (op)
13581 {
13582 /* Ada attributes ('Foo). */
13583 case OP_ATR_FIRST:
13584 case OP_ATR_LAST:
13585 case OP_ATR_LENGTH:
13586 case OP_ATR_IMAGE:
13587 case OP_ATR_MAX:
13588 case OP_ATR_MIN:
13589 case OP_ATR_MODULUS:
13590 case OP_ATR_POS:
13591 case OP_ATR_SIZE:
13592 case OP_ATR_TAG:
13593 case OP_ATR_VAL:
13594 break;
13595
13596 case UNOP_IN_RANGE:
13597 case UNOP_QUAL:
13598 /* XXX: gdb_sprint_host_address, type_sprint */
13599 fprintf_filtered (stream, _("Type @"));
13600 gdb_print_host_address (exp->elts[pc + 1].type, stream);
13601 fprintf_filtered (stream, " (");
13602 type_print (exp->elts[pc + 1].type, NULL, stream, 0);
13603 fprintf_filtered (stream, ")");
13604 break;
13605 case BINOP_IN_BOUNDS:
13606 fprintf_filtered (stream, " (%d)",
13607 longest_to_int (exp->elts[pc + 2].longconst));
13608 break;
13609 case TERNOP_IN_RANGE:
13610 break;
13611
13612 case OP_AGGREGATE:
13613 case OP_OTHERS:
13614 case OP_DISCRETE_RANGE:
13615 case OP_POSITIONAL:
13616 case OP_CHOICES:
13617 break;
13618
13619 case OP_NAME:
13620 case OP_STRING:
13621 {
13622 char *name = &exp->elts[elt + 2].string;
13623 int len = longest_to_int (exp->elts[elt + 1].longconst);
13624
13625 fprintf_filtered (stream, "Text: `%.*s'", len, name);
13626 break;
13627 }
13628
13629 default:
13630 return dump_subexp_body_standard (exp, stream, elt);
13631 }
13632
13633 elt += oplen;
13634 for (i = 0; i < nargs; i += 1)
13635 elt = dump_subexp (exp, stream, elt);
13636
13637 return elt;
13638 }
13639
13640 /* The Ada extension of print_subexp (q.v.). */
13641
13642 static void
13643 ada_print_subexp (struct expression *exp, int *pos,
13644 struct ui_file *stream, enum precedence prec)
13645 {
13646 int oplen, nargs, i;
13647 int pc = *pos;
13648 enum exp_opcode op = exp->elts[pc].opcode;
13649
13650 ada_forward_operator_length (exp, pc, &oplen, &nargs);
13651
13652 *pos += oplen;
13653 switch (op)
13654 {
13655 default:
13656 *pos -= oplen;
13657 print_subexp_standard (exp, pos, stream, prec);
13658 return;
13659
13660 case OP_VAR_VALUE:
13661 fputs_filtered (exp->elts[pc + 2].symbol->natural_name (), stream);
13662 return;
13663
13664 case BINOP_IN_BOUNDS:
13665 /* XXX: sprint_subexp */
13666 print_subexp (exp, pos, stream, PREC_SUFFIX);
13667 fputs_filtered (" in ", stream);
13668 print_subexp (exp, pos, stream, PREC_SUFFIX);
13669 fputs_filtered ("'range", stream);
13670 if (exp->elts[pc + 1].longconst > 1)
13671 fprintf_filtered (stream, "(%ld)",
13672 (long) exp->elts[pc + 1].longconst);
13673 return;
13674
13675 case TERNOP_IN_RANGE:
13676 if (prec >= PREC_EQUAL)
13677 fputs_filtered ("(", stream);
13678 /* XXX: sprint_subexp */
13679 print_subexp (exp, pos, stream, PREC_SUFFIX);
13680 fputs_filtered (" in ", stream);
13681 print_subexp (exp, pos, stream, PREC_EQUAL);
13682 fputs_filtered (" .. ", stream);
13683 print_subexp (exp, pos, stream, PREC_EQUAL);
13684 if (prec >= PREC_EQUAL)
13685 fputs_filtered (")", stream);
13686 return;
13687
13688 case OP_ATR_FIRST:
13689 case OP_ATR_LAST:
13690 case OP_ATR_LENGTH:
13691 case OP_ATR_IMAGE:
13692 case OP_ATR_MAX:
13693 case OP_ATR_MIN:
13694 case OP_ATR_MODULUS:
13695 case OP_ATR_POS:
13696 case OP_ATR_SIZE:
13697 case OP_ATR_TAG:
13698 case OP_ATR_VAL:
13699 if (exp->elts[*pos].opcode == OP_TYPE)
13700 {
13701 if (exp->elts[*pos + 1].type->code () != TYPE_CODE_VOID)
13702 LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
13703 &type_print_raw_options);
13704 *pos += 3;
13705 }
13706 else
13707 print_subexp (exp, pos, stream, PREC_SUFFIX);
13708 fprintf_filtered (stream, "'%s", ada_attribute_name (op));
13709 if (nargs > 1)
13710 {
13711 int tem;
13712
13713 for (tem = 1; tem < nargs; tem += 1)
13714 {
13715 fputs_filtered ((tem == 1) ? " (" : ", ", stream);
13716 print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
13717 }
13718 fputs_filtered (")", stream);
13719 }
13720 return;
13721
13722 case UNOP_QUAL:
13723 type_print (exp->elts[pc + 1].type, "", stream, 0);
13724 fputs_filtered ("'(", stream);
13725 print_subexp (exp, pos, stream, PREC_PREFIX);
13726 fputs_filtered (")", stream);
13727 return;
13728
13729 case UNOP_IN_RANGE:
13730 /* XXX: sprint_subexp */
13731 print_subexp (exp, pos, stream, PREC_SUFFIX);
13732 fputs_filtered (" in ", stream);
13733 LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
13734 &type_print_raw_options);
13735 return;
13736
13737 case OP_DISCRETE_RANGE:
13738 print_subexp (exp, pos, stream, PREC_SUFFIX);
13739 fputs_filtered ("..", stream);
13740 print_subexp (exp, pos, stream, PREC_SUFFIX);
13741 return;
13742
13743 case OP_OTHERS:
13744 fputs_filtered ("others => ", stream);
13745 print_subexp (exp, pos, stream, PREC_SUFFIX);
13746 return;
13747
13748 case OP_CHOICES:
13749 for (i = 0; i < nargs-1; i += 1)
13750 {
13751 if (i > 0)
13752 fputs_filtered ("|", stream);
13753 print_subexp (exp, pos, stream, PREC_SUFFIX);
13754 }
13755 fputs_filtered (" => ", stream);
13756 print_subexp (exp, pos, stream, PREC_SUFFIX);
13757 return;
13758
13759 case OP_POSITIONAL:
13760 print_subexp (exp, pos, stream, PREC_SUFFIX);
13761 return;
13762
13763 case OP_AGGREGATE:
13764 fputs_filtered ("(", stream);
13765 for (i = 0; i < nargs; i += 1)
13766 {
13767 if (i > 0)
13768 fputs_filtered (", ", stream);
13769 print_subexp (exp, pos, stream, PREC_SUFFIX);
13770 }
13771 fputs_filtered (")", stream);
13772 return;
13773 }
13774 }
13775
13776 /* Table mapping opcodes into strings for printing operators
13777 and precedences of the operators. */
13778
13779 static const struct op_print ada_op_print_tab[] = {
13780 {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
13781 {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
13782 {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
13783 {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
13784 {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
13785 {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
13786 {"=", BINOP_EQUAL, PREC_EQUAL, 0},
13787 {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
13788 {"<=", BINOP_LEQ, PREC_ORDER, 0},
13789 {">=", BINOP_GEQ, PREC_ORDER, 0},
13790 {">", BINOP_GTR, PREC_ORDER, 0},
13791 {"<", BINOP_LESS, PREC_ORDER, 0},
13792 {">>", BINOP_RSH, PREC_SHIFT, 0},
13793 {"<<", BINOP_LSH, PREC_SHIFT, 0},
13794 {"+", BINOP_ADD, PREC_ADD, 0},
13795 {"-", BINOP_SUB, PREC_ADD, 0},
13796 {"&", BINOP_CONCAT, PREC_ADD, 0},
13797 {"*", BINOP_MUL, PREC_MUL, 0},
13798 {"/", BINOP_DIV, PREC_MUL, 0},
13799 {"rem", BINOP_REM, PREC_MUL, 0},
13800 {"mod", BINOP_MOD, PREC_MUL, 0},
13801 {"**", BINOP_EXP, PREC_REPEAT, 0},
13802 {"@", BINOP_REPEAT, PREC_REPEAT, 0},
13803 {"-", UNOP_NEG, PREC_PREFIX, 0},
13804 {"+", UNOP_PLUS, PREC_PREFIX, 0},
13805 {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
13806 {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
13807 {"abs ", UNOP_ABS, PREC_PREFIX, 0},
13808 {".all", UNOP_IND, PREC_SUFFIX, 1},
13809 {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
13810 {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
13811 {NULL, OP_NULL, PREC_SUFFIX, 0}
13812 };
13813 \f
13814 /* Language vector */
13815
13816 static const struct exp_descriptor ada_exp_descriptor = {
13817 ada_print_subexp,
13818 ada_operator_length,
13819 ada_operator_check,
13820 ada_dump_subexp_body,
13821 ada_evaluate_subexp
13822 };
13823
13824 /* symbol_name_matcher_ftype adapter for wild_match. */
13825
13826 static bool
13827 do_wild_match (const char *symbol_search_name,
13828 const lookup_name_info &lookup_name,
13829 completion_match_result *comp_match_res)
13830 {
13831 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13832 }
13833
13834 /* symbol_name_matcher_ftype adapter for full_match. */
13835
13836 static bool
13837 do_full_match (const char *symbol_search_name,
13838 const lookup_name_info &lookup_name,
13839 completion_match_result *comp_match_res)
13840 {
13841 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13842
13843 /* If both symbols start with "_ada_", just let the loop below
13844 handle the comparison. However, if only the symbol name starts
13845 with "_ada_", skip the prefix and let the match proceed as
13846 usual. */
13847 if (startswith (symbol_search_name, "_ada_")
13848 && !startswith (lname, "_ada"))
13849 symbol_search_name += 5;
13850
13851 int uscore_count = 0;
13852 while (*lname != '\0')
13853 {
13854 if (*symbol_search_name != *lname)
13855 {
13856 if (*symbol_search_name == 'B' && uscore_count == 2
13857 && symbol_search_name[1] == '_')
13858 {
13859 symbol_search_name += 2;
13860 while (isdigit (*symbol_search_name))
13861 ++symbol_search_name;
13862 if (symbol_search_name[0] == '_'
13863 && symbol_search_name[1] == '_')
13864 {
13865 symbol_search_name += 2;
13866 continue;
13867 }
13868 }
13869 return false;
13870 }
13871
13872 if (*symbol_search_name == '_')
13873 ++uscore_count;
13874 else
13875 uscore_count = 0;
13876
13877 ++symbol_search_name;
13878 ++lname;
13879 }
13880
13881 return is_name_suffix (symbol_search_name);
13882 }
13883
13884 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13885
13886 static bool
13887 do_exact_match (const char *symbol_search_name,
13888 const lookup_name_info &lookup_name,
13889 completion_match_result *comp_match_res)
13890 {
13891 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13892 }
13893
13894 /* Build the Ada lookup name for LOOKUP_NAME. */
13895
13896 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13897 {
13898 gdb::string_view user_name = lookup_name.name ();
13899
13900 if (!user_name.empty () && user_name[0] == '<')
13901 {
13902 if (user_name.back () == '>')
13903 m_encoded_name
13904 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
13905 else
13906 m_encoded_name
13907 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
13908 m_encoded_p = true;
13909 m_verbatim_p = true;
13910 m_wild_match_p = false;
13911 m_standard_p = false;
13912 }
13913 else
13914 {
13915 m_verbatim_p = false;
13916
13917 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
13918
13919 if (!m_encoded_p)
13920 {
13921 const char *folded = ada_fold_name (user_name);
13922 m_encoded_name = ada_encode_1 (folded, false);
13923 if (m_encoded_name.empty ())
13924 m_encoded_name = gdb::to_string (user_name);
13925 }
13926 else
13927 m_encoded_name = gdb::to_string (user_name);
13928
13929 /* Handle the 'package Standard' special case. See description
13930 of m_standard_p. */
13931 if (startswith (m_encoded_name.c_str (), "standard__"))
13932 {
13933 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13934 m_standard_p = true;
13935 }
13936 else
13937 m_standard_p = false;
13938
13939 /* If the name contains a ".", then the user is entering a fully
13940 qualified entity name, and the match must not be done in wild
13941 mode. Similarly, if the user wants to complete what looks
13942 like an encoded name, the match must not be done in wild
13943 mode. Also, in the standard__ special case always do
13944 non-wild matching. */
13945 m_wild_match_p
13946 = (lookup_name.match_type () != symbol_name_match_type::FULL
13947 && !m_encoded_p
13948 && !m_standard_p
13949 && user_name.find ('.') == std::string::npos);
13950 }
13951 }
13952
13953 /* symbol_name_matcher_ftype method for Ada. This only handles
13954 completion mode. */
13955
13956 static bool
13957 ada_symbol_name_matches (const char *symbol_search_name,
13958 const lookup_name_info &lookup_name,
13959 completion_match_result *comp_match_res)
13960 {
13961 return lookup_name.ada ().matches (symbol_search_name,
13962 lookup_name.match_type (),
13963 comp_match_res);
13964 }
13965
13966 /* A name matcher that matches the symbol name exactly, with
13967 strcmp. */
13968
13969 static bool
13970 literal_symbol_name_matcher (const char *symbol_search_name,
13971 const lookup_name_info &lookup_name,
13972 completion_match_result *comp_match_res)
13973 {
13974 gdb::string_view name_view = lookup_name.name ();
13975
13976 if (lookup_name.completion_mode ()
13977 ? (strncmp (symbol_search_name, name_view.data (),
13978 name_view.size ()) == 0)
13979 : symbol_search_name == name_view)
13980 {
13981 if (comp_match_res != NULL)
13982 comp_match_res->set_match (symbol_search_name);
13983 return true;
13984 }
13985 else
13986 return false;
13987 }
13988
13989 /* Implement the "get_symbol_name_matcher" language_defn method for
13990 Ada. */
13991
13992 static symbol_name_matcher_ftype *
13993 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13994 {
13995 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13996 return literal_symbol_name_matcher;
13997
13998 if (lookup_name.completion_mode ())
13999 return ada_symbol_name_matches;
14000 else
14001 {
14002 if (lookup_name.ada ().wild_match_p ())
14003 return do_wild_match;
14004 else if (lookup_name.ada ().verbatim_p ())
14005 return do_exact_match;
14006 else
14007 return do_full_match;
14008 }
14009 }
14010
14011 /* Class representing the Ada language. */
14012
14013 class ada_language : public language_defn
14014 {
14015 public:
14016 ada_language ()
14017 : language_defn (language_ada)
14018 { /* Nothing. */ }
14019
14020 /* See language.h. */
14021
14022 const char *name () const override
14023 { return "ada"; }
14024
14025 /* See language.h. */
14026
14027 const char *natural_name () const override
14028 { return "Ada"; }
14029
14030 /* See language.h. */
14031
14032 const std::vector<const char *> &filename_extensions () const override
14033 {
14034 static const std::vector<const char *> extensions
14035 = { ".adb", ".ads", ".a", ".ada", ".dg" };
14036 return extensions;
14037 }
14038
14039 /* Print an array element index using the Ada syntax. */
14040
14041 void print_array_index (struct type *index_type,
14042 LONGEST index,
14043 struct ui_file *stream,
14044 const value_print_options *options) const override
14045 {
14046 struct value *index_value = val_atr (index_type, index);
14047
14048 value_print (index_value, stream, options);
14049 fprintf_filtered (stream, " => ");
14050 }
14051
14052 /* Implement the "read_var_value" language_defn method for Ada. */
14053
14054 struct value *read_var_value (struct symbol *var,
14055 const struct block *var_block,
14056 struct frame_info *frame) const override
14057 {
14058 /* The only case where default_read_var_value is not sufficient
14059 is when VAR is a renaming... */
14060 if (frame != nullptr)
14061 {
14062 const struct block *frame_block = get_frame_block (frame, NULL);
14063 if (frame_block != nullptr && ada_is_renaming_symbol (var))
14064 return ada_read_renaming_var_value (var, frame_block);
14065 }
14066
14067 /* This is a typical case where we expect the default_read_var_value
14068 function to work. */
14069 return language_defn::read_var_value (var, var_block, frame);
14070 }
14071
14072 /* See language.h. */
14073 void language_arch_info (struct gdbarch *gdbarch,
14074 struct language_arch_info *lai) const override
14075 {
14076 const struct builtin_type *builtin = builtin_type (gdbarch);
14077
14078 /* Helper function to allow shorter lines below. */
14079 auto add = [&] (struct type *t)
14080 {
14081 lai->add_primitive_type (t);
14082 };
14083
14084 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14085 0, "integer"));
14086 add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
14087 0, "long_integer"));
14088 add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
14089 0, "short_integer"));
14090 struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
14091 0, "character");
14092 lai->set_string_char_type (char_type);
14093 add (char_type);
14094 add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
14095 "float", gdbarch_float_format (gdbarch)));
14096 add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
14097 "long_float", gdbarch_double_format (gdbarch)));
14098 add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
14099 0, "long_long_integer"));
14100 add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
14101 "long_long_float",
14102 gdbarch_long_double_format (gdbarch)));
14103 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14104 0, "natural"));
14105 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14106 0, "positive"));
14107 add (builtin->builtin_void);
14108
14109 struct type *system_addr_ptr
14110 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
14111 "void"));
14112 system_addr_ptr->set_name ("system__address");
14113 add (system_addr_ptr);
14114
14115 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
14116 type. This is a signed integral type whose size is the same as
14117 the size of addresses. */
14118 unsigned int addr_length = TYPE_LENGTH (system_addr_ptr);
14119 add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
14120 "storage_offset"));
14121
14122 lai->set_bool_type (builtin->builtin_bool);
14123 }
14124
14125 /* See language.h. */
14126
14127 bool iterate_over_symbols
14128 (const struct block *block, const lookup_name_info &name,
14129 domain_enum domain,
14130 gdb::function_view<symbol_found_callback_ftype> callback) const override
14131 {
14132 std::vector<struct block_symbol> results
14133 = ada_lookup_symbol_list_worker (name, block, domain, 0);
14134 for (block_symbol &sym : results)
14135 {
14136 if (!callback (&sym))
14137 return false;
14138 }
14139
14140 return true;
14141 }
14142
14143 /* See language.h. */
14144 bool sniff_from_mangled_name (const char *mangled,
14145 char **out) const override
14146 {
14147 std::string demangled = ada_decode (mangled);
14148
14149 *out = NULL;
14150
14151 if (demangled != mangled && demangled[0] != '<')
14152 {
14153 /* Set the gsymbol language to Ada, but still return 0.
14154 Two reasons for that:
14155
14156 1. For Ada, we prefer computing the symbol's decoded name
14157 on the fly rather than pre-compute it, in order to save
14158 memory (Ada projects are typically very large).
14159
14160 2. There are some areas in the definition of the GNAT
14161 encoding where, with a bit of bad luck, we might be able
14162 to decode a non-Ada symbol, generating an incorrect
14163 demangled name (Eg: names ending with "TB" for instance
14164 are identified as task bodies and so stripped from
14165 the decoded name returned).
14166
14167 Returning true, here, but not setting *DEMANGLED, helps us get
14168 a little bit of the best of both worlds. Because we're last,
14169 we should not affect any of the other languages that were
14170 able to demangle the symbol before us; we get to correctly
14171 tag Ada symbols as such; and even if we incorrectly tagged a
14172 non-Ada symbol, which should be rare, any routing through the
14173 Ada language should be transparent (Ada tries to behave much
14174 like C/C++ with non-Ada symbols). */
14175 return true;
14176 }
14177
14178 return false;
14179 }
14180
14181 /* See language.h. */
14182
14183 char *demangle_symbol (const char *mangled, int options) const override
14184 {
14185 return ada_la_decode (mangled, options);
14186 }
14187
14188 /* See language.h. */
14189
14190 void print_type (struct type *type, const char *varstring,
14191 struct ui_file *stream, int show, int level,
14192 const struct type_print_options *flags) const override
14193 {
14194 ada_print_type (type, varstring, stream, show, level, flags);
14195 }
14196
14197 /* See language.h. */
14198
14199 const char *word_break_characters (void) const override
14200 {
14201 return ada_completer_word_break_characters;
14202 }
14203
14204 /* See language.h. */
14205
14206 void collect_symbol_completion_matches (completion_tracker &tracker,
14207 complete_symbol_mode mode,
14208 symbol_name_match_type name_match_type,
14209 const char *text, const char *word,
14210 enum type_code code) const override
14211 {
14212 struct symbol *sym;
14213 const struct block *b, *surrounding_static_block = 0;
14214 struct block_iterator iter;
14215
14216 gdb_assert (code == TYPE_CODE_UNDEF);
14217
14218 lookup_name_info lookup_name (text, name_match_type, true);
14219
14220 /* First, look at the partial symtab symbols. */
14221 expand_symtabs_matching (NULL,
14222 lookup_name,
14223 NULL,
14224 NULL,
14225 ALL_DOMAIN);
14226
14227 /* At this point scan through the misc symbol vectors and add each
14228 symbol you find to the list. Eventually we want to ignore
14229 anything that isn't a text symbol (everything else will be
14230 handled by the psymtab code above). */
14231
14232 for (objfile *objfile : current_program_space->objfiles ())
14233 {
14234 for (minimal_symbol *msymbol : objfile->msymbols ())
14235 {
14236 QUIT;
14237
14238 if (completion_skip_symbol (mode, msymbol))
14239 continue;
14240
14241 language symbol_language = msymbol->language ();
14242
14243 /* Ada minimal symbols won't have their language set to Ada. If
14244 we let completion_list_add_name compare using the
14245 default/C-like matcher, then when completing e.g., symbols in a
14246 package named "pck", we'd match internal Ada symbols like
14247 "pckS", which are invalid in an Ada expression, unless you wrap
14248 them in '<' '>' to request a verbatim match.
14249
14250 Unfortunately, some Ada encoded names successfully demangle as
14251 C++ symbols (using an old mangling scheme), such as "name__2Xn"
14252 -> "Xn::name(void)" and thus some Ada minimal symbols end up
14253 with the wrong language set. Paper over that issue here. */
14254 if (symbol_language == language_auto
14255 || symbol_language == language_cplus)
14256 symbol_language = language_ada;
14257
14258 completion_list_add_name (tracker,
14259 symbol_language,
14260 msymbol->linkage_name (),
14261 lookup_name, text, word);
14262 }
14263 }
14264
14265 /* Search upwards from currently selected frame (so that we can
14266 complete on local vars. */
14267
14268 for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
14269 {
14270 if (!BLOCK_SUPERBLOCK (b))
14271 surrounding_static_block = b; /* For elmin of dups */
14272
14273 ALL_BLOCK_SYMBOLS (b, iter, sym)
14274 {
14275 if (completion_skip_symbol (mode, sym))
14276 continue;
14277
14278 completion_list_add_name (tracker,
14279 sym->language (),
14280 sym->linkage_name (),
14281 lookup_name, text, word);
14282 }
14283 }
14284
14285 /* Go through the symtabs and check the externs and statics for
14286 symbols which match. */
14287
14288 for (objfile *objfile : current_program_space->objfiles ())
14289 {
14290 for (compunit_symtab *s : objfile->compunits ())
14291 {
14292 QUIT;
14293 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
14294 ALL_BLOCK_SYMBOLS (b, iter, sym)
14295 {
14296 if (completion_skip_symbol (mode, sym))
14297 continue;
14298
14299 completion_list_add_name (tracker,
14300 sym->language (),
14301 sym->linkage_name (),
14302 lookup_name, text, word);
14303 }
14304 }
14305 }
14306
14307 for (objfile *objfile : current_program_space->objfiles ())
14308 {
14309 for (compunit_symtab *s : objfile->compunits ())
14310 {
14311 QUIT;
14312 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
14313 /* Don't do this block twice. */
14314 if (b == surrounding_static_block)
14315 continue;
14316 ALL_BLOCK_SYMBOLS (b, iter, sym)
14317 {
14318 if (completion_skip_symbol (mode, sym))
14319 continue;
14320
14321 completion_list_add_name (tracker,
14322 sym->language (),
14323 sym->linkage_name (),
14324 lookup_name, text, word);
14325 }
14326 }
14327 }
14328 }
14329
14330 /* See language.h. */
14331
14332 gdb::unique_xmalloc_ptr<char> watch_location_expression
14333 (struct type *type, CORE_ADDR addr) const override
14334 {
14335 type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
14336 std::string name = type_to_string (type);
14337 return gdb::unique_xmalloc_ptr<char>
14338 (xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr)));
14339 }
14340
14341 /* See language.h. */
14342
14343 void value_print (struct value *val, struct ui_file *stream,
14344 const struct value_print_options *options) const override
14345 {
14346 return ada_value_print (val, stream, options);
14347 }
14348
14349 /* See language.h. */
14350
14351 void value_print_inner
14352 (struct value *val, struct ui_file *stream, int recurse,
14353 const struct value_print_options *options) const override
14354 {
14355 return ada_value_print_inner (val, stream, recurse, options);
14356 }
14357
14358 /* See language.h. */
14359
14360 struct block_symbol lookup_symbol_nonlocal
14361 (const char *name, const struct block *block,
14362 const domain_enum domain) const override
14363 {
14364 struct block_symbol sym;
14365
14366 sym = ada_lookup_symbol (name, block_static_block (block), domain);
14367 if (sym.symbol != NULL)
14368 return sym;
14369
14370 /* If we haven't found a match at this point, try the primitive
14371 types. In other languages, this search is performed before
14372 searching for global symbols in order to short-circuit that
14373 global-symbol search if it happens that the name corresponds
14374 to a primitive type. But we cannot do the same in Ada, because
14375 it is perfectly legitimate for a program to declare a type which
14376 has the same name as a standard type. If looking up a type in
14377 that situation, we have traditionally ignored the primitive type
14378 in favor of user-defined types. This is why, unlike most other
14379 languages, we search the primitive types this late and only after
14380 having searched the global symbols without success. */
14381
14382 if (domain == VAR_DOMAIN)
14383 {
14384 struct gdbarch *gdbarch;
14385
14386 if (block == NULL)
14387 gdbarch = target_gdbarch ();
14388 else
14389 gdbarch = block_gdbarch (block);
14390 sym.symbol
14391 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
14392 if (sym.symbol != NULL)
14393 return sym;
14394 }
14395
14396 return {};
14397 }
14398
14399 /* See language.h. */
14400
14401 int parser (struct parser_state *ps) const override
14402 {
14403 warnings_issued = 0;
14404 return ada_parse (ps);
14405 }
14406
14407 /* See language.h.
14408
14409 Same as evaluate_type (*EXP), but resolves ambiguous symbol references
14410 (marked by OP_VAR_VALUE nodes in which the symbol has an undefined
14411 namespace) and converts operators that are user-defined into
14412 appropriate function calls. If CONTEXT_TYPE is non-null, it provides
14413 a preferred result type [at the moment, only type void has any
14414 effect---causing procedures to be preferred over functions in calls].
14415 A null CONTEXT_TYPE indicates that a non-void return type is
14416 preferred. May change (expand) *EXP. */
14417
14418 void post_parser (expression_up *expp, struct parser_state *ps)
14419 const override
14420 {
14421 struct type *context_type = NULL;
14422 int pc = 0;
14423
14424 if (ps->void_context_p)
14425 context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
14426
14427 resolve_subexp (expp, &pc, 1, context_type, ps->parse_completion,
14428 ps->block_tracker);
14429 }
14430
14431 /* See language.h. */
14432
14433 void emitchar (int ch, struct type *chtype,
14434 struct ui_file *stream, int quoter) const override
14435 {
14436 ada_emit_char (ch, chtype, stream, quoter, 1);
14437 }
14438
14439 /* See language.h. */
14440
14441 void printchar (int ch, struct type *chtype,
14442 struct ui_file *stream) const override
14443 {
14444 ada_printchar (ch, chtype, stream);
14445 }
14446
14447 /* See language.h. */
14448
14449 void printstr (struct ui_file *stream, struct type *elttype,
14450 const gdb_byte *string, unsigned int length,
14451 const char *encoding, int force_ellipses,
14452 const struct value_print_options *options) const override
14453 {
14454 ada_printstr (stream, elttype, string, length, encoding,
14455 force_ellipses, options);
14456 }
14457
14458 /* See language.h. */
14459
14460 void print_typedef (struct type *type, struct symbol *new_symbol,
14461 struct ui_file *stream) const override
14462 {
14463 ada_print_typedef (type, new_symbol, stream);
14464 }
14465
14466 /* See language.h. */
14467
14468 bool is_string_type_p (struct type *type) const override
14469 {
14470 return ada_is_string_type (type);
14471 }
14472
14473 /* See language.h. */
14474
14475 const char *struct_too_deep_ellipsis () const override
14476 { return "(...)"; }
14477
14478 /* See language.h. */
14479
14480 bool c_style_arrays_p () const override
14481 { return false; }
14482
14483 /* See language.h. */
14484
14485 bool store_sym_names_in_linkage_form_p () const override
14486 { return true; }
14487
14488 /* See language.h. */
14489
14490 const struct lang_varobj_ops *varobj_ops () const override
14491 { return &ada_varobj_ops; }
14492
14493 /* See language.h. */
14494
14495 const struct exp_descriptor *expression_ops () const override
14496 { return &ada_exp_descriptor; }
14497
14498 /* See language.h. */
14499
14500 const struct op_print *opcode_print_table () const override
14501 { return ada_op_print_tab; }
14502
14503 protected:
14504 /* See language.h. */
14505
14506 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
14507 (const lookup_name_info &lookup_name) const override
14508 {
14509 return ada_get_symbol_name_matcher (lookup_name);
14510 }
14511 };
14512
14513 /* Single instance of the Ada language class. */
14514
14515 static ada_language ada_language_defn;
14516
14517 /* Command-list for the "set/show ada" prefix command. */
14518 static struct cmd_list_element *set_ada_list;
14519 static struct cmd_list_element *show_ada_list;
14520
14521 static void
14522 initialize_ada_catchpoint_ops (void)
14523 {
14524 struct breakpoint_ops *ops;
14525
14526 initialize_breakpoint_ops ();
14527
14528 ops = &catch_exception_breakpoint_ops;
14529 *ops = bkpt_breakpoint_ops;
14530 ops->allocate_location = allocate_location_exception;
14531 ops->re_set = re_set_exception;
14532 ops->check_status = check_status_exception;
14533 ops->print_it = print_it_exception;
14534 ops->print_one = print_one_exception;
14535 ops->print_mention = print_mention_exception;
14536 ops->print_recreate = print_recreate_exception;
14537
14538 ops = &catch_exception_unhandled_breakpoint_ops;
14539 *ops = bkpt_breakpoint_ops;
14540 ops->allocate_location = allocate_location_exception;
14541 ops->re_set = re_set_exception;
14542 ops->check_status = check_status_exception;
14543 ops->print_it = print_it_exception;
14544 ops->print_one = print_one_exception;
14545 ops->print_mention = print_mention_exception;
14546 ops->print_recreate = print_recreate_exception;
14547
14548 ops = &catch_assert_breakpoint_ops;
14549 *ops = bkpt_breakpoint_ops;
14550 ops->allocate_location = allocate_location_exception;
14551 ops->re_set = re_set_exception;
14552 ops->check_status = check_status_exception;
14553 ops->print_it = print_it_exception;
14554 ops->print_one = print_one_exception;
14555 ops->print_mention = print_mention_exception;
14556 ops->print_recreate = print_recreate_exception;
14557
14558 ops = &catch_handlers_breakpoint_ops;
14559 *ops = bkpt_breakpoint_ops;
14560 ops->allocate_location = allocate_location_exception;
14561 ops->re_set = re_set_exception;
14562 ops->check_status = check_status_exception;
14563 ops->print_it = print_it_exception;
14564 ops->print_one = print_one_exception;
14565 ops->print_mention = print_mention_exception;
14566 ops->print_recreate = print_recreate_exception;
14567 }
14568
14569 /* This module's 'new_objfile' observer. */
14570
14571 static void
14572 ada_new_objfile_observer (struct objfile *objfile)
14573 {
14574 ada_clear_symbol_cache ();
14575 }
14576
14577 /* This module's 'free_objfile' observer. */
14578
14579 static void
14580 ada_free_objfile_observer (struct objfile *objfile)
14581 {
14582 ada_clear_symbol_cache ();
14583 }
14584
14585 void _initialize_ada_language ();
14586 void
14587 _initialize_ada_language ()
14588 {
14589 initialize_ada_catchpoint_ops ();
14590
14591 add_basic_prefix_cmd ("ada", no_class,
14592 _("Prefix command for changing Ada-specific settings."),
14593 &set_ada_list, "set ada ", 0, &setlist);
14594
14595 add_show_prefix_cmd ("ada", no_class,
14596 _("Generic command for showing Ada-specific settings."),
14597 &show_ada_list, "show ada ", 0, &showlist);
14598
14599 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
14600 &trust_pad_over_xvs, _("\
14601 Enable or disable an optimization trusting PAD types over XVS types."), _("\
14602 Show whether an optimization trusting PAD types over XVS types is activated."),
14603 _("\
14604 This is related to the encoding used by the GNAT compiler. The debugger\n\
14605 should normally trust the contents of PAD types, but certain older versions\n\
14606 of GNAT have a bug that sometimes causes the information in the PAD type\n\
14607 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
14608 work around this bug. It is always safe to turn this option \"off\", but\n\
14609 this incurs a slight performance penalty, so it is recommended to NOT change\n\
14610 this option to \"off\" unless necessary."),
14611 NULL, NULL, &set_ada_list, &show_ada_list);
14612
14613 add_setshow_boolean_cmd ("print-signatures", class_vars,
14614 &print_signatures, _("\
14615 Enable or disable the output of formal and return types for functions in the \
14616 overloads selection menu."), _("\
14617 Show whether the output of formal and return types for functions in the \
14618 overloads selection menu is activated."),
14619 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
14620
14621 add_catch_command ("exception", _("\
14622 Catch Ada exceptions, when raised.\n\
14623 Usage: catch exception [ARG] [if CONDITION]\n\
14624 Without any argument, stop when any Ada exception is raised.\n\
14625 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14626 being raised does not have a handler (and will therefore lead to the task's\n\
14627 termination).\n\
14628 Otherwise, the catchpoint only stops when the name of the exception being\n\
14629 raised is the same as ARG.\n\
14630 CONDITION is a boolean expression that is evaluated to see whether the\n\
14631 exception should cause a stop."),
14632 catch_ada_exception_command,
14633 catch_ada_completer,
14634 CATCH_PERMANENT,
14635 CATCH_TEMPORARY);
14636
14637 add_catch_command ("handlers", _("\
14638 Catch Ada exceptions, when handled.\n\
14639 Usage: catch handlers [ARG] [if CONDITION]\n\
14640 Without any argument, stop when any Ada exception is handled.\n\
14641 With an argument, catch only exceptions with the given name.\n\
14642 CONDITION is a boolean expression that is evaluated to see whether the\n\
14643 exception should cause a stop."),
14644 catch_ada_handlers_command,
14645 catch_ada_completer,
14646 CATCH_PERMANENT,
14647 CATCH_TEMPORARY);
14648 add_catch_command ("assert", _("\
14649 Catch failed Ada assertions, when raised.\n\
14650 Usage: catch assert [if CONDITION]\n\
14651 CONDITION is a boolean expression that is evaluated to see whether the\n\
14652 exception should cause a stop."),
14653 catch_assert_command,
14654 NULL,
14655 CATCH_PERMANENT,
14656 CATCH_TEMPORARY);
14657
14658 varsize_limit = 65536;
14659 add_setshow_uinteger_cmd ("varsize-limit", class_support,
14660 &varsize_limit, _("\
14661 Set the maximum number of bytes allowed in a variable-size object."), _("\
14662 Show the maximum number of bytes allowed in a variable-size object."), _("\
14663 Attempts to access an object whose size is not a compile-time constant\n\
14664 and exceeds this limit will cause an error."),
14665 NULL, NULL, &setlist, &showlist);
14666
14667 add_info ("exceptions", info_exceptions_command,
14668 _("\
14669 List all Ada exception names.\n\
14670 Usage: info exceptions [REGEXP]\n\
14671 If a regular expression is passed as an argument, only those matching\n\
14672 the regular expression are listed."));
14673
14674 add_basic_prefix_cmd ("ada", class_maintenance,
14675 _("Set Ada maintenance-related variables."),
14676 &maint_set_ada_cmdlist, "maintenance set ada ",
14677 0/*allow-unknown*/, &maintenance_set_cmdlist);
14678
14679 add_show_prefix_cmd ("ada", class_maintenance,
14680 _("Show Ada maintenance-related variables."),
14681 &maint_show_ada_cmdlist, "maintenance show ada ",
14682 0/*allow-unknown*/, &maintenance_show_cmdlist);
14683
14684 add_setshow_boolean_cmd
14685 ("ignore-descriptive-types", class_maintenance,
14686 &ada_ignore_descriptive_types_p,
14687 _("Set whether descriptive types generated by GNAT should be ignored."),
14688 _("Show whether descriptive types generated by GNAT should be ignored."),
14689 _("\
14690 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14691 DWARF attribute."),
14692 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14693
14694 decoded_names_store = htab_create_alloc (256, htab_hash_string, streq_hash,
14695 NULL, xcalloc, xfree);
14696
14697 /* The ada-lang observers. */
14698 gdb::observers::new_objfile.attach (ada_new_objfile_observer);
14699 gdb::observers::free_objfile.attach (ada_free_objfile_observer);
14700 gdb::observers::inferior_exit.attach (ada_inferior_exit);
14701 }
This page took 0.313351 seconds and 5 git commands to generate.