Implement Ada assignment
[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 namespace expr
9638 {
9639
9640 bool
9641 check_objfile (const std::unique_ptr<ada_component> &comp,
9642 struct objfile *objfile)
9643 {
9644 return comp->uses_objfile (objfile);
9645 }
9646
9647 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9648 component of LHS (a simple array or a record). Does not modify the
9649 inferior's memory, nor does it modify LHS (unless LHS ==
9650 CONTAINER). */
9651
9652 static void
9653 assign_component (struct value *container, struct value *lhs, LONGEST index,
9654 struct expression *exp, operation_up &arg)
9655 {
9656 scoped_value_mark mark;
9657
9658 struct value *elt;
9659 struct type *lhs_type = check_typedef (value_type (lhs));
9660
9661 if (lhs_type->code () == TYPE_CODE_ARRAY)
9662 {
9663 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9664 struct value *index_val = value_from_longest (index_type, index);
9665
9666 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9667 }
9668 else
9669 {
9670 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9671 elt = ada_to_fixed_value (elt);
9672 }
9673
9674 ada_aggregate_operation *ag_op
9675 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9676 if (ag_op != nullptr)
9677 ag_op->assign_aggregate (container, elt, exp);
9678 else
9679 value_assign_to_component (container, elt,
9680 arg->evaluate (nullptr, exp,
9681 EVAL_NORMAL));
9682 }
9683
9684 bool
9685 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9686 {
9687 for (const auto &item : m_components)
9688 if (item->uses_objfile (objfile))
9689 return true;
9690 return false;
9691 }
9692
9693 void
9694 ada_aggregate_component::dump (ui_file *stream, int depth)
9695 {
9696 fprintf_filtered (stream, _("%*sAggregate\n"), depth, "");
9697 for (const auto &item : m_components)
9698 item->dump (stream, depth + 1);
9699 }
9700
9701 void
9702 ada_aggregate_component::assign (struct value *container,
9703 struct value *lhs, struct expression *exp,
9704 std::vector<LONGEST> &indices,
9705 LONGEST low, LONGEST high)
9706 {
9707 for (auto &item : m_components)
9708 item->assign (container, lhs, exp, indices, low, high);
9709 }
9710
9711 void
9712 ada_aggregate_operation::assign_aggregate (struct value *container,
9713 struct value *lhs,
9714 struct expression *exp)
9715 {
9716 struct type *lhs_type;
9717 LONGEST low_index, high_index;
9718
9719 container = ada_coerce_ref (container);
9720 if (ada_is_direct_array_type (value_type (container)))
9721 container = ada_coerce_to_simple_array (container);
9722 lhs = ada_coerce_ref (lhs);
9723 if (!deprecated_value_modifiable (lhs))
9724 error (_("Left operand of assignment is not a modifiable lvalue."));
9725
9726 lhs_type = check_typedef (value_type (lhs));
9727 if (ada_is_direct_array_type (lhs_type))
9728 {
9729 lhs = ada_coerce_to_simple_array (lhs);
9730 lhs_type = check_typedef (value_type (lhs));
9731 low_index = lhs_type->bounds ()->low.const_val ();
9732 high_index = lhs_type->bounds ()->high.const_val ();
9733 }
9734 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9735 {
9736 low_index = 0;
9737 high_index = num_visible_fields (lhs_type) - 1;
9738 }
9739 else
9740 error (_("Left-hand side must be array or record."));
9741
9742 std::vector<LONGEST> indices (4);
9743 indices[0] = indices[1] = low_index - 1;
9744 indices[2] = indices[3] = high_index + 1;
9745
9746 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9747 low_index, high_index);
9748 }
9749
9750 bool
9751 ada_positional_component::uses_objfile (struct objfile *objfile)
9752 {
9753 return m_op->uses_objfile (objfile);
9754 }
9755
9756 void
9757 ada_positional_component::dump (ui_file *stream, int depth)
9758 {
9759 fprintf_filtered (stream, _("%*sPositional, index = %d\n"),
9760 depth, "", m_index);
9761 m_op->dump (stream, depth + 1);
9762 }
9763
9764 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9765 construct, given that the positions are relative to lower bound
9766 LOW, where HIGH is the upper bound. Record the position in
9767 INDICES. CONTAINER is as for assign_aggregate. */
9768 void
9769 ada_positional_component::assign (struct value *container,
9770 struct value *lhs, struct expression *exp,
9771 std::vector<LONGEST> &indices,
9772 LONGEST low, LONGEST high)
9773 {
9774 LONGEST ind = m_index + low;
9775
9776 if (ind - 1 == high)
9777 warning (_("Extra components in aggregate ignored."));
9778 if (ind <= high)
9779 {
9780 add_component_interval (ind, ind, indices);
9781 assign_component (container, lhs, ind, exp, m_op);
9782 }
9783 }
9784
9785 bool
9786 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9787 {
9788 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9789 }
9790
9791 void
9792 ada_discrete_range_association::dump (ui_file *stream, int depth)
9793 {
9794 fprintf_filtered (stream, _("%*sDiscrete range:\n"), depth, "");
9795 m_low->dump (stream, depth + 1);
9796 m_high->dump (stream, depth + 1);
9797 }
9798
9799 void
9800 ada_discrete_range_association::assign (struct value *container,
9801 struct value *lhs,
9802 struct expression *exp,
9803 std::vector<LONGEST> &indices,
9804 LONGEST low, LONGEST high,
9805 operation_up &op)
9806 {
9807 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9808 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9809
9810 if (lower <= upper && (lower < low || upper > high))
9811 error (_("Index in component association out of bounds."));
9812
9813 add_component_interval (lower, upper, indices);
9814 while (lower <= upper)
9815 {
9816 assign_component (container, lhs, lower, exp, op);
9817 lower += 1;
9818 }
9819 }
9820
9821 bool
9822 ada_name_association::uses_objfile (struct objfile *objfile)
9823 {
9824 return m_val->uses_objfile (objfile);
9825 }
9826
9827 void
9828 ada_name_association::dump (ui_file *stream, int depth)
9829 {
9830 fprintf_filtered (stream, _("%*sName:\n"), depth, "");
9831 m_val->dump (stream, depth + 1);
9832 }
9833
9834 void
9835 ada_name_association::assign (struct value *container,
9836 struct value *lhs,
9837 struct expression *exp,
9838 std::vector<LONGEST> &indices,
9839 LONGEST low, LONGEST high,
9840 operation_up &op)
9841 {
9842 int index;
9843
9844 if (ada_is_direct_array_type (value_type (lhs)))
9845 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9846 EVAL_NORMAL)));
9847 else
9848 {
9849 ada_string_operation *strop
9850 = dynamic_cast<ada_string_operation *> (m_val.get ());
9851
9852 const char *name;
9853 if (strop != nullptr)
9854 name = strop->get_name ();
9855 else
9856 {
9857 ada_var_value_operation *vvo
9858 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9859 if (vvo != nullptr)
9860 error (_("Invalid record component association."));
9861 name = vvo->get_symbol ()->natural_name ();
9862 }
9863
9864 index = 0;
9865 if (! find_struct_field (name, value_type (lhs), 0,
9866 NULL, NULL, NULL, NULL, &index))
9867 error (_("Unknown component name: %s."), name);
9868 }
9869
9870 add_component_interval (index, index, indices);
9871 assign_component (container, lhs, index, exp, op);
9872 }
9873
9874 bool
9875 ada_choices_component::uses_objfile (struct objfile *objfile)
9876 {
9877 if (m_op->uses_objfile (objfile))
9878 return true;
9879 for (const auto &item : m_assocs)
9880 if (item->uses_objfile (objfile))
9881 return true;
9882 return false;
9883 }
9884
9885 void
9886 ada_choices_component::dump (ui_file *stream, int depth)
9887 {
9888 fprintf_filtered (stream, _("%*sChoices:\n"), depth, "");
9889 m_op->dump (stream, depth + 1);
9890 for (const auto &item : m_assocs)
9891 item->dump (stream, depth + 1);
9892 }
9893
9894 /* Assign into the components of LHS indexed by the OP_CHOICES
9895 construct at *POS, updating *POS past the construct, given that
9896 the allowable indices are LOW..HIGH. Record the indices assigned
9897 to in INDICES. CONTAINER is as for assign_aggregate. */
9898 void
9899 ada_choices_component::assign (struct value *container,
9900 struct value *lhs, struct expression *exp,
9901 std::vector<LONGEST> &indices,
9902 LONGEST low, LONGEST high)
9903 {
9904 for (auto &item : m_assocs)
9905 item->assign (container, lhs, exp, indices, low, high, m_op);
9906 }
9907
9908 bool
9909 ada_others_component::uses_objfile (struct objfile *objfile)
9910 {
9911 return m_op->uses_objfile (objfile);
9912 }
9913
9914 void
9915 ada_others_component::dump (ui_file *stream, int depth)
9916 {
9917 fprintf_filtered (stream, _("%*sOthers:\n"), depth, "");
9918 m_op->dump (stream, depth + 1);
9919 }
9920
9921 /* Assign the value of the expression in the OP_OTHERS construct in
9922 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9923 have not been previously assigned. The index intervals already assigned
9924 are in INDICES. CONTAINER is as for assign_aggregate. */
9925 void
9926 ada_others_component::assign (struct value *container,
9927 struct value *lhs, struct expression *exp,
9928 std::vector<LONGEST> &indices,
9929 LONGEST low, LONGEST high)
9930 {
9931 int num_indices = indices.size ();
9932 for (int i = 0; i < num_indices - 2; i += 2)
9933 {
9934 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9935 assign_component (container, lhs, ind, exp, m_op);
9936 }
9937 }
9938
9939 struct value *
9940 ada_assign_operation::evaluate (struct type *expect_type,
9941 struct expression *exp,
9942 enum noside noside)
9943 {
9944 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9945
9946 ada_aggregate_operation *ag_op
9947 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9948 if (ag_op != nullptr)
9949 {
9950 if (noside != EVAL_NORMAL)
9951 return arg1;
9952
9953 ag_op->assign_aggregate (arg1, arg1, exp);
9954 return ada_value_assign (arg1, arg1);
9955 }
9956 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9957 except if the lhs of our assignment is a convenience variable.
9958 In the case of assigning to a convenience variable, the lhs
9959 should be exactly the result of the evaluation of the rhs. */
9960 struct type *type = value_type (arg1);
9961 if (VALUE_LVAL (arg1) == lval_internalvar)
9962 type = NULL;
9963 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9964 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
9965 return arg1;
9966 if (VALUE_LVAL (arg1) == lval_internalvar)
9967 {
9968 /* Nothing. */
9969 }
9970 else
9971 arg2 = coerce_for_assign (value_type (arg1), arg2);
9972 return ada_value_assign (arg1, arg2);
9973 }
9974
9975 } /* namespace expr */
9976
9977 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9978 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9979 overlap. */
9980 static void
9981 add_component_interval (LONGEST low, LONGEST high,
9982 std::vector<LONGEST> &indices)
9983 {
9984 int i, j;
9985
9986 int size = indices.size ();
9987 for (i = 0; i < size; i += 2) {
9988 if (high >= indices[i] && low <= indices[i + 1])
9989 {
9990 int kh;
9991
9992 for (kh = i + 2; kh < size; kh += 2)
9993 if (high < indices[kh])
9994 break;
9995 if (low < indices[i])
9996 indices[i] = low;
9997 indices[i + 1] = indices[kh - 1];
9998 if (high > indices[i + 1])
9999 indices[i + 1] = high;
10000 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
10001 indices.resize (kh - i - 2);
10002 return;
10003 }
10004 else if (high < indices[i])
10005 break;
10006 }
10007
10008 indices.resize (indices.size () + 2);
10009 for (j = indices.size () - 1; j >= i + 2; j -= 1)
10010 indices[j] = indices[j - 2];
10011 indices[i] = low;
10012 indices[i + 1] = high;
10013 }
10014
10015 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
10016 is different. */
10017
10018 static struct value *
10019 ada_value_cast (struct type *type, struct value *arg2)
10020 {
10021 if (type == ada_check_typedef (value_type (arg2)))
10022 return arg2;
10023
10024 return value_cast (type, arg2);
10025 }
10026
10027 /* Evaluating Ada expressions, and printing their result.
10028 ------------------------------------------------------
10029
10030 1. Introduction:
10031 ----------------
10032
10033 We usually evaluate an Ada expression in order to print its value.
10034 We also evaluate an expression in order to print its type, which
10035 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
10036 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
10037 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
10038 the evaluation compared to the EVAL_NORMAL, but is otherwise very
10039 similar.
10040
10041 Evaluating expressions is a little more complicated for Ada entities
10042 than it is for entities in languages such as C. The main reason for
10043 this is that Ada provides types whose definition might be dynamic.
10044 One example of such types is variant records. Or another example
10045 would be an array whose bounds can only be known at run time.
10046
10047 The following description is a general guide as to what should be
10048 done (and what should NOT be done) in order to evaluate an expression
10049 involving such types, and when. This does not cover how the semantic
10050 information is encoded by GNAT as this is covered separatly. For the
10051 document used as the reference for the GNAT encoding, see exp_dbug.ads
10052 in the GNAT sources.
10053
10054 Ideally, we should embed each part of this description next to its
10055 associated code. Unfortunately, the amount of code is so vast right
10056 now that it's hard to see whether the code handling a particular
10057 situation might be duplicated or not. One day, when the code is
10058 cleaned up, this guide might become redundant with the comments
10059 inserted in the code, and we might want to remove it.
10060
10061 2. ``Fixing'' an Entity, the Simple Case:
10062 -----------------------------------------
10063
10064 When evaluating Ada expressions, the tricky issue is that they may
10065 reference entities whose type contents and size are not statically
10066 known. Consider for instance a variant record:
10067
10068 type Rec (Empty : Boolean := True) is record
10069 case Empty is
10070 when True => null;
10071 when False => Value : Integer;
10072 end case;
10073 end record;
10074 Yes : Rec := (Empty => False, Value => 1);
10075 No : Rec := (empty => True);
10076
10077 The size and contents of that record depends on the value of the
10078 descriminant (Rec.Empty). At this point, neither the debugging
10079 information nor the associated type structure in GDB are able to
10080 express such dynamic types. So what the debugger does is to create
10081 "fixed" versions of the type that applies to the specific object.
10082 We also informally refer to this operation as "fixing" an object,
10083 which means creating its associated fixed type.
10084
10085 Example: when printing the value of variable "Yes" above, its fixed
10086 type would look like this:
10087
10088 type Rec is record
10089 Empty : Boolean;
10090 Value : Integer;
10091 end record;
10092
10093 On the other hand, if we printed the value of "No", its fixed type
10094 would become:
10095
10096 type Rec is record
10097 Empty : Boolean;
10098 end record;
10099
10100 Things become a little more complicated when trying to fix an entity
10101 with a dynamic type that directly contains another dynamic type,
10102 such as an array of variant records, for instance. There are
10103 two possible cases: Arrays, and records.
10104
10105 3. ``Fixing'' Arrays:
10106 ---------------------
10107
10108 The type structure in GDB describes an array in terms of its bounds,
10109 and the type of its elements. By design, all elements in the array
10110 have the same type and we cannot represent an array of variant elements
10111 using the current type structure in GDB. When fixing an array,
10112 we cannot fix the array element, as we would potentially need one
10113 fixed type per element of the array. As a result, the best we can do
10114 when fixing an array is to produce an array whose bounds and size
10115 are correct (allowing us to read it from memory), but without having
10116 touched its element type. Fixing each element will be done later,
10117 when (if) necessary.
10118
10119 Arrays are a little simpler to handle than records, because the same
10120 amount of memory is allocated for each element of the array, even if
10121 the amount of space actually used by each element differs from element
10122 to element. Consider for instance the following array of type Rec:
10123
10124 type Rec_Array is array (1 .. 2) of Rec;
10125
10126 The actual amount of memory occupied by each element might be different
10127 from element to element, depending on the value of their discriminant.
10128 But the amount of space reserved for each element in the array remains
10129 fixed regardless. So we simply need to compute that size using
10130 the debugging information available, from which we can then determine
10131 the array size (we multiply the number of elements of the array by
10132 the size of each element).
10133
10134 The simplest case is when we have an array of a constrained element
10135 type. For instance, consider the following type declarations:
10136
10137 type Bounded_String (Max_Size : Integer) is
10138 Length : Integer;
10139 Buffer : String (1 .. Max_Size);
10140 end record;
10141 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
10142
10143 In this case, the compiler describes the array as an array of
10144 variable-size elements (identified by its XVS suffix) for which
10145 the size can be read in the parallel XVZ variable.
10146
10147 In the case of an array of an unconstrained element type, the compiler
10148 wraps the array element inside a private PAD type. This type should not
10149 be shown to the user, and must be "unwrap"'ed before printing. Note
10150 that we also use the adjective "aligner" in our code to designate
10151 these wrapper types.
10152
10153 In some cases, the size allocated for each element is statically
10154 known. In that case, the PAD type already has the correct size,
10155 and the array element should remain unfixed.
10156
10157 But there are cases when this size is not statically known.
10158 For instance, assuming that "Five" is an integer variable:
10159
10160 type Dynamic is array (1 .. Five) of Integer;
10161 type Wrapper (Has_Length : Boolean := False) is record
10162 Data : Dynamic;
10163 case Has_Length is
10164 when True => Length : Integer;
10165 when False => null;
10166 end case;
10167 end record;
10168 type Wrapper_Array is array (1 .. 2) of Wrapper;
10169
10170 Hello : Wrapper_Array := (others => (Has_Length => True,
10171 Data => (others => 17),
10172 Length => 1));
10173
10174
10175 The debugging info would describe variable Hello as being an
10176 array of a PAD type. The size of that PAD type is not statically
10177 known, but can be determined using a parallel XVZ variable.
10178 In that case, a copy of the PAD type with the correct size should
10179 be used for the fixed array.
10180
10181 3. ``Fixing'' record type objects:
10182 ----------------------------------
10183
10184 Things are slightly different from arrays in the case of dynamic
10185 record types. In this case, in order to compute the associated
10186 fixed type, we need to determine the size and offset of each of
10187 its components. This, in turn, requires us to compute the fixed
10188 type of each of these components.
10189
10190 Consider for instance the example:
10191
10192 type Bounded_String (Max_Size : Natural) is record
10193 Str : String (1 .. Max_Size);
10194 Length : Natural;
10195 end record;
10196 My_String : Bounded_String (Max_Size => 10);
10197
10198 In that case, the position of field "Length" depends on the size
10199 of field Str, which itself depends on the value of the Max_Size
10200 discriminant. In order to fix the type of variable My_String,
10201 we need to fix the type of field Str. Therefore, fixing a variant
10202 record requires us to fix each of its components.
10203
10204 However, if a component does not have a dynamic size, the component
10205 should not be fixed. In particular, fields that use a PAD type
10206 should not fixed. Here is an example where this might happen
10207 (assuming type Rec above):
10208
10209 type Container (Big : Boolean) is record
10210 First : Rec;
10211 After : Integer;
10212 case Big is
10213 when True => Another : Integer;
10214 when False => null;
10215 end case;
10216 end record;
10217 My_Container : Container := (Big => False,
10218 First => (Empty => True),
10219 After => 42);
10220
10221 In that example, the compiler creates a PAD type for component First,
10222 whose size is constant, and then positions the component After just
10223 right after it. The offset of component After is therefore constant
10224 in this case.
10225
10226 The debugger computes the position of each field based on an algorithm
10227 that uses, among other things, the actual position and size of the field
10228 preceding it. Let's now imagine that the user is trying to print
10229 the value of My_Container. If the type fixing was recursive, we would
10230 end up computing the offset of field After based on the size of the
10231 fixed version of field First. And since in our example First has
10232 only one actual field, the size of the fixed type is actually smaller
10233 than the amount of space allocated to that field, and thus we would
10234 compute the wrong offset of field After.
10235
10236 To make things more complicated, we need to watch out for dynamic
10237 components of variant records (identified by the ___XVL suffix in
10238 the component name). Even if the target type is a PAD type, the size
10239 of that type might not be statically known. So the PAD type needs
10240 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10241 we might end up with the wrong size for our component. This can be
10242 observed with the following type declarations:
10243
10244 type Octal is new Integer range 0 .. 7;
10245 type Octal_Array is array (Positive range <>) of Octal;
10246 pragma Pack (Octal_Array);
10247
10248 type Octal_Buffer (Size : Positive) is record
10249 Buffer : Octal_Array (1 .. Size);
10250 Length : Integer;
10251 end record;
10252
10253 In that case, Buffer is a PAD type whose size is unset and needs
10254 to be computed by fixing the unwrapped type.
10255
10256 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10257 ----------------------------------------------------------
10258
10259 Lastly, when should the sub-elements of an entity that remained unfixed
10260 thus far, be actually fixed?
10261
10262 The answer is: Only when referencing that element. For instance
10263 when selecting one component of a record, this specific component
10264 should be fixed at that point in time. Or when printing the value
10265 of a record, each component should be fixed before its value gets
10266 printed. Similarly for arrays, the element of the array should be
10267 fixed when printing each element of the array, or when extracting
10268 one element out of that array. On the other hand, fixing should
10269 not be performed on the elements when taking a slice of an array!
10270
10271 Note that one of the side effects of miscomputing the offset and
10272 size of each field is that we end up also miscomputing the size
10273 of the containing type. This can have adverse results when computing
10274 the value of an entity. GDB fetches the value of an entity based
10275 on the size of its type, and thus a wrong size causes GDB to fetch
10276 the wrong amount of memory. In the case where the computed size is
10277 too small, GDB fetches too little data to print the value of our
10278 entity. Results in this case are unpredictable, as we usually read
10279 past the buffer containing the data =:-o. */
10280
10281 /* Evaluate a subexpression of EXP, at index *POS, and return a value
10282 for that subexpression cast to TO_TYPE. Advance *POS over the
10283 subexpression. */
10284
10285 static value *
10286 ada_evaluate_subexp_for_cast (expression *exp, int *pos,
10287 enum noside noside, struct type *to_type)
10288 {
10289 int pc = *pos;
10290
10291 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE
10292 || exp->elts[pc].opcode == OP_VAR_VALUE)
10293 {
10294 (*pos) += 4;
10295
10296 value *val;
10297 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
10298 {
10299 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10300 return value_zero (to_type, not_lval);
10301
10302 val = evaluate_var_msym_value (noside,
10303 exp->elts[pc + 1].objfile,
10304 exp->elts[pc + 2].msymbol);
10305 }
10306 else
10307 val = evaluate_var_value (noside,
10308 exp->elts[pc + 1].block,
10309 exp->elts[pc + 2].symbol);
10310
10311 if (noside == EVAL_SKIP)
10312 return eval_skip_value (exp);
10313
10314 val = ada_value_cast (to_type, val);
10315
10316 /* Follow the Ada language semantics that do not allow taking
10317 an address of the result of a cast (view conversion in Ada). */
10318 if (VALUE_LVAL (val) == lval_memory)
10319 {
10320 if (value_lazy (val))
10321 value_fetch_lazy (val);
10322 VALUE_LVAL (val) = not_lval;
10323 }
10324 return val;
10325 }
10326
10327 value *val = evaluate_subexp (to_type, exp, pos, noside);
10328 if (noside == EVAL_SKIP)
10329 return eval_skip_value (exp);
10330 return ada_value_cast (to_type, val);
10331 }
10332
10333 /* A helper function for TERNOP_IN_RANGE. */
10334
10335 static value *
10336 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10337 enum noside noside,
10338 value *arg1, value *arg2, value *arg3)
10339 {
10340 if (noside == EVAL_SKIP)
10341 return eval_skip_value (exp);
10342
10343 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10344 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10345 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10346 return
10347 value_from_longest (type,
10348 (value_less (arg1, arg3)
10349 || value_equal (arg1, arg3))
10350 && (value_less (arg2, arg1)
10351 || value_equal (arg2, arg1)));
10352 }
10353
10354 /* A helper function for UNOP_NEG. */
10355
10356 value *
10357 ada_unop_neg (struct type *expect_type,
10358 struct expression *exp,
10359 enum noside noside, enum exp_opcode op,
10360 struct value *arg1)
10361 {
10362 if (noside == EVAL_SKIP)
10363 return eval_skip_value (exp);
10364 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10365 return value_neg (arg1);
10366 }
10367
10368 /* A helper function for UNOP_IN_RANGE. */
10369
10370 value *
10371 ada_unop_in_range (struct type *expect_type,
10372 struct expression *exp,
10373 enum noside noside, enum exp_opcode op,
10374 struct value *arg1, struct type *type)
10375 {
10376 if (noside == EVAL_SKIP)
10377 return eval_skip_value (exp);
10378
10379 struct value *arg2, *arg3;
10380 switch (type->code ())
10381 {
10382 default:
10383 lim_warning (_("Membership test incompletely implemented; "
10384 "always returns true"));
10385 type = language_bool_type (exp->language_defn, exp->gdbarch);
10386 return value_from_longest (type, (LONGEST) 1);
10387
10388 case TYPE_CODE_RANGE:
10389 arg2 = value_from_longest (type,
10390 type->bounds ()->low.const_val ());
10391 arg3 = value_from_longest (type,
10392 type->bounds ()->high.const_val ());
10393 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10394 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10395 type = language_bool_type (exp->language_defn, exp->gdbarch);
10396 return
10397 value_from_longest (type,
10398 (value_less (arg1, arg3)
10399 || value_equal (arg1, arg3))
10400 && (value_less (arg2, arg1)
10401 || value_equal (arg2, arg1)));
10402 }
10403 }
10404
10405 /* A helper function for OP_ATR_TAG. */
10406
10407 value *
10408 ada_atr_tag (struct type *expect_type,
10409 struct expression *exp,
10410 enum noside noside, enum exp_opcode op,
10411 struct value *arg1)
10412 {
10413 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10414 return value_zero (ada_tag_type (arg1), not_lval);
10415
10416 return ada_value_tag (arg1);
10417 }
10418
10419 /* A helper function for OP_ATR_SIZE. */
10420
10421 value *
10422 ada_atr_size (struct type *expect_type,
10423 struct expression *exp,
10424 enum noside noside, enum exp_opcode op,
10425 struct value *arg1)
10426 {
10427 struct type *type = value_type (arg1);
10428
10429 /* If the argument is a reference, then dereference its type, since
10430 the user is really asking for the size of the actual object,
10431 not the size of the pointer. */
10432 if (type->code () == TYPE_CODE_REF)
10433 type = TYPE_TARGET_TYPE (type);
10434
10435 if (noside == EVAL_SKIP)
10436 return eval_skip_value (exp);
10437 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10438 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10439 else
10440 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10441 TARGET_CHAR_BIT * TYPE_LENGTH (type));
10442 }
10443
10444 /* A helper function for UNOP_ABS. */
10445
10446 value *
10447 ada_abs (struct type *expect_type,
10448 struct expression *exp,
10449 enum noside noside, enum exp_opcode op,
10450 struct value *arg1)
10451 {
10452 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10453 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10454 return value_neg (arg1);
10455 else
10456 return arg1;
10457 }
10458
10459 /* A helper function for BINOP_MUL. */
10460
10461 value *
10462 ada_mult_binop (struct type *expect_type,
10463 struct expression *exp,
10464 enum noside noside, enum exp_opcode op,
10465 struct value *arg1, struct value *arg2)
10466 {
10467 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10468 {
10469 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10470 return value_zero (value_type (arg1), not_lval);
10471 }
10472 else
10473 {
10474 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10475 return ada_value_binop (arg1, arg2, op);
10476 }
10477 }
10478
10479 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10480
10481 value *
10482 ada_equal_binop (struct type *expect_type,
10483 struct expression *exp,
10484 enum noside noside, enum exp_opcode op,
10485 struct value *arg1, struct value *arg2)
10486 {
10487 int tem;
10488 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10489 tem = 0;
10490 else
10491 {
10492 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10493 tem = ada_value_equal (arg1, arg2);
10494 }
10495 if (op == BINOP_NOTEQUAL)
10496 tem = !tem;
10497 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10498 return value_from_longest (type, (LONGEST) tem);
10499 }
10500
10501 /* A helper function for TERNOP_SLICE. */
10502
10503 value *
10504 ada_ternop_slice (struct expression *exp,
10505 enum noside noside,
10506 struct value *array, struct value *low_bound_val,
10507 struct value *high_bound_val)
10508 {
10509 LONGEST low_bound;
10510 LONGEST high_bound;
10511
10512 low_bound_val = coerce_ref (low_bound_val);
10513 high_bound_val = coerce_ref (high_bound_val);
10514 low_bound = value_as_long (low_bound_val);
10515 high_bound = value_as_long (high_bound_val);
10516
10517 /* If this is a reference to an aligner type, then remove all
10518 the aligners. */
10519 if (value_type (array)->code () == TYPE_CODE_REF
10520 && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
10521 TYPE_TARGET_TYPE (value_type (array)) =
10522 ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
10523
10524 if (ada_is_any_packed_array_type (value_type (array)))
10525 error (_("cannot slice a packed array"));
10526
10527 /* If this is a reference to an array or an array lvalue,
10528 convert to a pointer. */
10529 if (value_type (array)->code () == TYPE_CODE_REF
10530 || (value_type (array)->code () == TYPE_CODE_ARRAY
10531 && VALUE_LVAL (array) == lval_memory))
10532 array = value_addr (array);
10533
10534 if (noside == EVAL_AVOID_SIDE_EFFECTS
10535 && ada_is_array_descriptor_type (ada_check_typedef
10536 (value_type (array))))
10537 return empty_array (ada_type_of_array (array, 0), low_bound,
10538 high_bound);
10539
10540 array = ada_coerce_to_simple_array_ptr (array);
10541
10542 /* If we have more than one level of pointer indirection,
10543 dereference the value until we get only one level. */
10544 while (value_type (array)->code () == TYPE_CODE_PTR
10545 && (TYPE_TARGET_TYPE (value_type (array))->code ()
10546 == TYPE_CODE_PTR))
10547 array = value_ind (array);
10548
10549 /* Make sure we really do have an array type before going further,
10550 to avoid a SEGV when trying to get the index type or the target
10551 type later down the road if the debug info generated by
10552 the compiler is incorrect or incomplete. */
10553 if (!ada_is_simple_array_type (value_type (array)))
10554 error (_("cannot take slice of non-array"));
10555
10556 if (ada_check_typedef (value_type (array))->code ()
10557 == TYPE_CODE_PTR)
10558 {
10559 struct type *type0 = ada_check_typedef (value_type (array));
10560
10561 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10562 return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
10563 else
10564 {
10565 struct type *arr_type0 =
10566 to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
10567
10568 return ada_value_slice_from_ptr (array, arr_type0,
10569 longest_to_int (low_bound),
10570 longest_to_int (high_bound));
10571 }
10572 }
10573 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10574 return array;
10575 else if (high_bound < low_bound)
10576 return empty_array (value_type (array), low_bound, high_bound);
10577 else
10578 return ada_value_slice (array, longest_to_int (low_bound),
10579 longest_to_int (high_bound));
10580 }
10581
10582 /* A helper function for BINOP_IN_BOUNDS. */
10583
10584 value *
10585 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10586 struct value *arg1, struct value *arg2, int n)
10587 {
10588 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10589 {
10590 struct type *type = language_bool_type (exp->language_defn,
10591 exp->gdbarch);
10592 return value_zero (type, not_lval);
10593 }
10594
10595 struct type *type = ada_index_type (value_type (arg2), n, "range");
10596 if (!type)
10597 type = value_type (arg1);
10598
10599 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10600 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10601
10602 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10603 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10604 type = language_bool_type (exp->language_defn, exp->gdbarch);
10605 return value_from_longest (type,
10606 (value_less (arg1, arg3)
10607 || value_equal (arg1, arg3))
10608 && (value_less (arg2, arg1)
10609 || value_equal (arg2, arg1)));
10610 }
10611
10612 /* A helper function for some attribute operations. */
10613
10614 static value *
10615 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10616 struct value *arg1, struct type *type_arg, int tem)
10617 {
10618 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10619 {
10620 if (type_arg == NULL)
10621 type_arg = value_type (arg1);
10622
10623 if (ada_is_constrained_packed_array_type (type_arg))
10624 type_arg = decode_constrained_packed_array_type (type_arg);
10625
10626 if (!discrete_type_p (type_arg))
10627 {
10628 switch (op)
10629 {
10630 default: /* Should never happen. */
10631 error (_("unexpected attribute encountered"));
10632 case OP_ATR_FIRST:
10633 case OP_ATR_LAST:
10634 type_arg = ada_index_type (type_arg, tem,
10635 ada_attribute_name (op));
10636 break;
10637 case OP_ATR_LENGTH:
10638 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10639 break;
10640 }
10641 }
10642
10643 return value_zero (type_arg, not_lval);
10644 }
10645 else if (type_arg == NULL)
10646 {
10647 arg1 = ada_coerce_ref (arg1);
10648
10649 if (ada_is_constrained_packed_array_type (value_type (arg1)))
10650 arg1 = ada_coerce_to_simple_array (arg1);
10651
10652 struct type *type;
10653 if (op == OP_ATR_LENGTH)
10654 type = builtin_type (exp->gdbarch)->builtin_int;
10655 else
10656 {
10657 type = ada_index_type (value_type (arg1), tem,
10658 ada_attribute_name (op));
10659 if (type == NULL)
10660 type = builtin_type (exp->gdbarch)->builtin_int;
10661 }
10662
10663 switch (op)
10664 {
10665 default: /* Should never happen. */
10666 error (_("unexpected attribute encountered"));
10667 case OP_ATR_FIRST:
10668 return value_from_longest
10669 (type, ada_array_bound (arg1, tem, 0));
10670 case OP_ATR_LAST:
10671 return value_from_longest
10672 (type, ada_array_bound (arg1, tem, 1));
10673 case OP_ATR_LENGTH:
10674 return value_from_longest
10675 (type, ada_array_length (arg1, tem));
10676 }
10677 }
10678 else if (discrete_type_p (type_arg))
10679 {
10680 struct type *range_type;
10681 const char *name = ada_type_name (type_arg);
10682
10683 range_type = NULL;
10684 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10685 range_type = to_fixed_range_type (type_arg, NULL);
10686 if (range_type == NULL)
10687 range_type = type_arg;
10688 switch (op)
10689 {
10690 default:
10691 error (_("unexpected attribute encountered"));
10692 case OP_ATR_FIRST:
10693 return value_from_longest
10694 (range_type, ada_discrete_type_low_bound (range_type));
10695 case OP_ATR_LAST:
10696 return value_from_longest
10697 (range_type, ada_discrete_type_high_bound (range_type));
10698 case OP_ATR_LENGTH:
10699 error (_("the 'length attribute applies only to array types"));
10700 }
10701 }
10702 else if (type_arg->code () == TYPE_CODE_FLT)
10703 error (_("unimplemented type attribute"));
10704 else
10705 {
10706 LONGEST low, high;
10707
10708 if (ada_is_constrained_packed_array_type (type_arg))
10709 type_arg = decode_constrained_packed_array_type (type_arg);
10710
10711 struct type *type;
10712 if (op == OP_ATR_LENGTH)
10713 type = builtin_type (exp->gdbarch)->builtin_int;
10714 else
10715 {
10716 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10717 if (type == NULL)
10718 type = builtin_type (exp->gdbarch)->builtin_int;
10719 }
10720
10721 switch (op)
10722 {
10723 default:
10724 error (_("unexpected attribute encountered"));
10725 case OP_ATR_FIRST:
10726 low = ada_array_bound_from_type (type_arg, tem, 0);
10727 return value_from_longest (type, low);
10728 case OP_ATR_LAST:
10729 high = ada_array_bound_from_type (type_arg, tem, 1);
10730 return value_from_longest (type, high);
10731 case OP_ATR_LENGTH:
10732 low = ada_array_bound_from_type (type_arg, tem, 0);
10733 high = ada_array_bound_from_type (type_arg, tem, 1);
10734 return value_from_longest (type, high - low + 1);
10735 }
10736 }
10737 }
10738
10739 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10740
10741 struct value *
10742 ada_binop_minmax (struct type *expect_type,
10743 struct expression *exp,
10744 enum noside noside, enum exp_opcode op,
10745 struct value *arg1, struct value *arg2)
10746 {
10747 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10748 return value_zero (value_type (arg1), not_lval);
10749 else
10750 {
10751 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10752 return value_binop (arg1, arg2,
10753 op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
10754 }
10755 }
10756
10757 /* A helper function for BINOP_EXP. */
10758
10759 struct value *
10760 ada_binop_exp (struct type *expect_type,
10761 struct expression *exp,
10762 enum noside noside, enum exp_opcode op,
10763 struct value *arg1, struct value *arg2)
10764 {
10765 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10766 return value_zero (value_type (arg1), not_lval);
10767 else
10768 {
10769 /* For integer exponentiation operations,
10770 only promote the first argument. */
10771 if (is_integral_type (value_type (arg2)))
10772 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10773 else
10774 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10775
10776 return value_binop (arg1, arg2, op);
10777 }
10778 }
10779
10780 namespace expr
10781 {
10782
10783 value *
10784 ada_wrapped_operation::evaluate (struct type *expect_type,
10785 struct expression *exp,
10786 enum noside noside)
10787 {
10788 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10789 if (noside == EVAL_NORMAL)
10790 result = unwrap_value (result);
10791
10792 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10793 then we need to perform the conversion manually, because
10794 evaluate_subexp_standard doesn't do it. This conversion is
10795 necessary in Ada because the different kinds of float/fixed
10796 types in Ada have different representations.
10797
10798 Similarly, we need to perform the conversion from OP_LONG
10799 ourselves. */
10800 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10801 result = ada_value_cast (expect_type, result);
10802
10803 return result;
10804 }
10805
10806 value *
10807 ada_string_operation::evaluate (struct type *expect_type,
10808 struct expression *exp,
10809 enum noside noside)
10810 {
10811 value *result = string_operation::evaluate (expect_type, exp, noside);
10812 /* The result type will have code OP_STRING, bashed there from
10813 OP_ARRAY. Bash it back. */
10814 if (value_type (result)->code () == TYPE_CODE_STRING)
10815 value_type (result)->set_code (TYPE_CODE_ARRAY);
10816 return result;
10817 }
10818
10819 value *
10820 ada_qual_operation::evaluate (struct type *expect_type,
10821 struct expression *exp,
10822 enum noside noside)
10823 {
10824 struct type *type = std::get<1> (m_storage);
10825 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10826 }
10827
10828 value *
10829 ada_ternop_range_operation::evaluate (struct type *expect_type,
10830 struct expression *exp,
10831 enum noside noside)
10832 {
10833 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10834 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10835 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10836 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10837 }
10838
10839 value *
10840 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10841 struct expression *exp,
10842 enum noside noside)
10843 {
10844 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10845 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10846
10847 auto do_op = [=] (LONGEST x, LONGEST y)
10848 {
10849 if (std::get<0> (m_storage) == BINOP_ADD)
10850 return x + y;
10851 return x - y;
10852 };
10853
10854 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10855 return (value_from_longest
10856 (value_type (arg1),
10857 do_op (value_as_long (arg1), value_as_long (arg2))));
10858 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10859 return (value_from_longest
10860 (value_type (arg2),
10861 do_op (value_as_long (arg1), value_as_long (arg2))));
10862 /* Preserve the original type for use by the range case below.
10863 We cannot cast the result to a reference type, so if ARG1 is
10864 a reference type, find its underlying type. */
10865 struct type *type = value_type (arg1);
10866 while (type->code () == TYPE_CODE_REF)
10867 type = TYPE_TARGET_TYPE (type);
10868 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10869 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10870 /* We need to special-case the result with a range.
10871 This is done for the benefit of "ptype". gdb's Ada support
10872 historically used the LHS to set the result type here, so
10873 preserve this behavior. */
10874 if (type->code () == TYPE_CODE_RANGE)
10875 arg1 = value_cast (type, arg1);
10876 return arg1;
10877 }
10878
10879 value *
10880 ada_unop_atr_operation::evaluate (struct type *expect_type,
10881 struct expression *exp,
10882 enum noside noside)
10883 {
10884 struct type *type_arg = nullptr;
10885 value *val = nullptr;
10886
10887 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10888 {
10889 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10890 EVAL_AVOID_SIDE_EFFECTS);
10891 type_arg = value_type (tem);
10892 }
10893 else
10894 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10895
10896 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10897 val, type_arg, std::get<2> (m_storage));
10898 }
10899
10900 value *
10901 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10902 struct expression *exp,
10903 enum noside noside)
10904 {
10905 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10906 return value_zero (expect_type, not_lval);
10907
10908 value *val = evaluate_var_msym_value (noside,
10909 std::get<1> (m_storage),
10910 std::get<0> (m_storage));
10911
10912 val = ada_value_cast (expect_type, val);
10913
10914 /* Follow the Ada language semantics that do not allow taking
10915 an address of the result of a cast (view conversion in Ada). */
10916 if (VALUE_LVAL (val) == lval_memory)
10917 {
10918 if (value_lazy (val))
10919 value_fetch_lazy (val);
10920 VALUE_LVAL (val) = not_lval;
10921 }
10922 return val;
10923 }
10924
10925 value *
10926 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10927 struct expression *exp,
10928 enum noside noside)
10929 {
10930 value *val = evaluate_var_value (noside,
10931 std::get<1> (m_storage),
10932 std::get<0> (m_storage));
10933
10934 val = ada_value_cast (expect_type, val);
10935
10936 /* Follow the Ada language semantics that do not allow taking
10937 an address of the result of a cast (view conversion in Ada). */
10938 if (VALUE_LVAL (val) == lval_memory)
10939 {
10940 if (value_lazy (val))
10941 value_fetch_lazy (val);
10942 VALUE_LVAL (val) = not_lval;
10943 }
10944 return val;
10945 }
10946
10947 value *
10948 ada_var_value_operation::evaluate (struct type *expect_type,
10949 struct expression *exp,
10950 enum noside noside)
10951 {
10952 symbol *sym = std::get<0> (m_storage);
10953
10954 if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
10955 /* Only encountered when an unresolved symbol occurs in a
10956 context other than a function call, in which case, it is
10957 invalid. */
10958 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10959 sym->print_name ());
10960
10961 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10962 {
10963 struct type *type = static_unwrap_type (SYMBOL_TYPE (sym));
10964 /* Check to see if this is a tagged type. We also need to handle
10965 the case where the type is a reference to a tagged type, but
10966 we have to be careful to exclude pointers to tagged types.
10967 The latter should be shown as usual (as a pointer), whereas
10968 a reference should mostly be transparent to the user. */
10969 if (ada_is_tagged_type (type, 0)
10970 || (type->code () == TYPE_CODE_REF
10971 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10972 {
10973 /* Tagged types are a little special in the fact that the real
10974 type is dynamic and can only be determined by inspecting the
10975 object's tag. This means that we need to get the object's
10976 value first (EVAL_NORMAL) and then extract the actual object
10977 type from its tag.
10978
10979 Note that we cannot skip the final step where we extract
10980 the object type from its tag, because the EVAL_NORMAL phase
10981 results in dynamic components being resolved into fixed ones.
10982 This can cause problems when trying to print the type
10983 description of tagged types whose parent has a dynamic size:
10984 We use the type name of the "_parent" component in order
10985 to print the name of the ancestor type in the type description.
10986 If that component had a dynamic size, the resolution into
10987 a fixed type would result in the loss of that type name,
10988 thus preventing us from printing the name of the ancestor
10989 type in the type description. */
10990 value *arg1 = var_value_operation::evaluate (nullptr, exp,
10991 EVAL_NORMAL);
10992
10993 if (type->code () != TYPE_CODE_REF)
10994 {
10995 struct type *actual_type;
10996
10997 actual_type = type_from_tag (ada_value_tag (arg1));
10998 if (actual_type == NULL)
10999 /* If, for some reason, we were unable to determine
11000 the actual type from the tag, then use the static
11001 approximation that we just computed as a fallback.
11002 This can happen if the debugging information is
11003 incomplete, for instance. */
11004 actual_type = type;
11005 return value_zero (actual_type, not_lval);
11006 }
11007 else
11008 {
11009 /* In the case of a ref, ada_coerce_ref takes care
11010 of determining the actual type. But the evaluation
11011 should return a ref as it should be valid to ask
11012 for its address; so rebuild a ref after coerce. */
11013 arg1 = ada_coerce_ref (arg1);
11014 return value_ref (arg1, TYPE_CODE_REF);
11015 }
11016 }
11017
11018 /* Records and unions for which GNAT encodings have been
11019 generated need to be statically fixed as well.
11020 Otherwise, non-static fixing produces a type where
11021 all dynamic properties are removed, which prevents "ptype"
11022 from being able to completely describe the type.
11023 For instance, a case statement in a variant record would be
11024 replaced by the relevant components based on the actual
11025 value of the discriminants. */
11026 if ((type->code () == TYPE_CODE_STRUCT
11027 && dynamic_template_type (type) != NULL)
11028 || (type->code () == TYPE_CODE_UNION
11029 && ada_find_parallel_type (type, "___XVU") != NULL))
11030 return value_zero (to_static_fixed_type (type), not_lval);
11031 }
11032
11033 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
11034 return ada_to_fixed_value (arg1);
11035 }
11036
11037 bool
11038 ada_var_value_operation::resolve (struct expression *exp,
11039 bool deprocedure_p,
11040 bool parse_completion,
11041 innermost_block_tracker *tracker,
11042 struct type *context_type)
11043 {
11044 symbol *sym = std::get<0> (m_storage);
11045 if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
11046 {
11047 block_symbol resolved
11048 = ada_resolve_variable (sym, std::get<1> (m_storage),
11049 context_type, parse_completion,
11050 deprocedure_p, tracker);
11051 std::get<0> (m_storage) = resolved.symbol;
11052 std::get<1> (m_storage) = resolved.block;
11053 }
11054
11055 if (deprocedure_p
11056 && SYMBOL_TYPE (std::get<0> (m_storage))->code () == TYPE_CODE_FUNC)
11057 return true;
11058
11059 return false;
11060 }
11061
11062 value *
11063 ada_atr_val_operation::evaluate (struct type *expect_type,
11064 struct expression *exp,
11065 enum noside noside)
11066 {
11067 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
11068 return ada_val_atr (noside, std::get<0> (m_storage), arg);
11069 }
11070
11071 value *
11072 ada_unop_ind_operation::evaluate (struct type *expect_type,
11073 struct expression *exp,
11074 enum noside noside)
11075 {
11076 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11077
11078 struct type *type = ada_check_typedef (value_type (arg1));
11079 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11080 {
11081 if (ada_is_array_descriptor_type (type))
11082 /* GDB allows dereferencing GNAT array descriptors. */
11083 {
11084 struct type *arrType = ada_type_of_array (arg1, 0);
11085
11086 if (arrType == NULL)
11087 error (_("Attempt to dereference null array pointer."));
11088 return value_at_lazy (arrType, 0);
11089 }
11090 else if (type->code () == TYPE_CODE_PTR
11091 || type->code () == TYPE_CODE_REF
11092 /* In C you can dereference an array to get the 1st elt. */
11093 || type->code () == TYPE_CODE_ARRAY)
11094 {
11095 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11096 only be determined by inspecting the object's tag.
11097 This means that we need to evaluate completely the
11098 expression in order to get its type. */
11099
11100 if ((type->code () == TYPE_CODE_REF
11101 || type->code () == TYPE_CODE_PTR)
11102 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11103 {
11104 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11105 EVAL_NORMAL);
11106 type = value_type (ada_value_ind (arg1));
11107 }
11108 else
11109 {
11110 type = to_static_fixed_type
11111 (ada_aligned_type
11112 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
11113 }
11114 ada_ensure_varsize_limit (type);
11115 return value_zero (type, lval_memory);
11116 }
11117 else if (type->code () == TYPE_CODE_INT)
11118 {
11119 /* GDB allows dereferencing an int. */
11120 if (expect_type == NULL)
11121 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11122 lval_memory);
11123 else
11124 {
11125 expect_type =
11126 to_static_fixed_type (ada_aligned_type (expect_type));
11127 return value_zero (expect_type, lval_memory);
11128 }
11129 }
11130 else
11131 error (_("Attempt to take contents of a non-pointer value."));
11132 }
11133 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11134 type = ada_check_typedef (value_type (arg1));
11135
11136 if (type->code () == TYPE_CODE_INT)
11137 /* GDB allows dereferencing an int. If we were given
11138 the expect_type, then use that as the target type.
11139 Otherwise, assume that the target type is an int. */
11140 {
11141 if (expect_type != NULL)
11142 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11143 arg1));
11144 else
11145 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11146 (CORE_ADDR) value_as_address (arg1));
11147 }
11148
11149 if (ada_is_array_descriptor_type (type))
11150 /* GDB allows dereferencing GNAT array descriptors. */
11151 return ada_coerce_to_simple_array (arg1);
11152 else
11153 return ada_value_ind (arg1);
11154 }
11155
11156 value *
11157 ada_structop_operation::evaluate (struct type *expect_type,
11158 struct expression *exp,
11159 enum noside noside)
11160 {
11161 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11162 const char *str = std::get<1> (m_storage).c_str ();
11163 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11164 {
11165 struct type *type;
11166 struct type *type1 = value_type (arg1);
11167
11168 if (ada_is_tagged_type (type1, 1))
11169 {
11170 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11171
11172 /* If the field is not found, check if it exists in the
11173 extension of this object's type. This means that we
11174 need to evaluate completely the expression. */
11175
11176 if (type == NULL)
11177 {
11178 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11179 EVAL_NORMAL);
11180 arg1 = ada_value_struct_elt (arg1, str, 0);
11181 arg1 = unwrap_value (arg1);
11182 type = value_type (ada_to_fixed_value (arg1));
11183 }
11184 }
11185 else
11186 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11187
11188 return value_zero (ada_aligned_type (type), lval_memory);
11189 }
11190 else
11191 {
11192 arg1 = ada_value_struct_elt (arg1, str, 0);
11193 arg1 = unwrap_value (arg1);
11194 return ada_to_fixed_value (arg1);
11195 }
11196 }
11197
11198 value *
11199 ada_funcall_operation::evaluate (struct type *expect_type,
11200 struct expression *exp,
11201 enum noside noside)
11202 {
11203 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11204 int nargs = args_up.size ();
11205 std::vector<value *> argvec (nargs);
11206 operation_up &callee_op = std::get<0> (m_storage);
11207
11208 ada_var_value_operation *avv
11209 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11210 if (avv != nullptr
11211 && SYMBOL_DOMAIN (avv->get_symbol ()) == UNDEF_DOMAIN)
11212 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11213 avv->get_symbol ()->print_name ());
11214
11215 value *callee = callee_op->evaluate (nullptr, exp, noside);
11216 for (int i = 0; i < args_up.size (); ++i)
11217 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11218
11219 if (ada_is_constrained_packed_array_type
11220 (desc_base_type (value_type (callee))))
11221 callee = ada_coerce_to_simple_array (callee);
11222 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11223 && TYPE_FIELD_BITSIZE (value_type (callee), 0) != 0)
11224 /* This is a packed array that has already been fixed, and
11225 therefore already coerced to a simple array. Nothing further
11226 to do. */
11227 ;
11228 else if (value_type (callee)->code () == TYPE_CODE_REF)
11229 {
11230 /* Make sure we dereference references so that all the code below
11231 feels like it's really handling the referenced value. Wrapping
11232 types (for alignment) may be there, so make sure we strip them as
11233 well. */
11234 callee = ada_to_fixed_value (coerce_ref (callee));
11235 }
11236 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11237 && VALUE_LVAL (callee) == lval_memory)
11238 callee = value_addr (callee);
11239
11240 struct type *type = ada_check_typedef (value_type (callee));
11241
11242 /* Ada allows us to implicitly dereference arrays when subscripting
11243 them. So, if this is an array typedef (encoding use for array
11244 access types encoded as fat pointers), strip it now. */
11245 if (type->code () == TYPE_CODE_TYPEDEF)
11246 type = ada_typedef_target_type (type);
11247
11248 if (type->code () == TYPE_CODE_PTR)
11249 {
11250 switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
11251 {
11252 case TYPE_CODE_FUNC:
11253 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11254 break;
11255 case TYPE_CODE_ARRAY:
11256 break;
11257 case TYPE_CODE_STRUCT:
11258 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11259 callee = ada_value_ind (callee);
11260 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11261 break;
11262 default:
11263 error (_("cannot subscript or call something of type `%s'"),
11264 ada_type_name (value_type (callee)));
11265 break;
11266 }
11267 }
11268
11269 switch (type->code ())
11270 {
11271 case TYPE_CODE_FUNC:
11272 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11273 {
11274 if (TYPE_TARGET_TYPE (type) == NULL)
11275 error_call_unknown_return_type (NULL);
11276 return allocate_value (TYPE_TARGET_TYPE (type));
11277 }
11278 return call_function_by_hand (callee, NULL, argvec);
11279 case TYPE_CODE_INTERNAL_FUNCTION:
11280 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11281 /* We don't know anything about what the internal
11282 function might return, but we have to return
11283 something. */
11284 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11285 not_lval);
11286 else
11287 return call_internal_function (exp->gdbarch, exp->language_defn,
11288 callee, nargs,
11289 argvec.data ());
11290
11291 case TYPE_CODE_STRUCT:
11292 {
11293 int arity;
11294
11295 arity = ada_array_arity (type);
11296 type = ada_array_element_type (type, nargs);
11297 if (type == NULL)
11298 error (_("cannot subscript or call a record"));
11299 if (arity != nargs)
11300 error (_("wrong number of subscripts; expecting %d"), arity);
11301 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11302 return value_zero (ada_aligned_type (type), lval_memory);
11303 return
11304 unwrap_value (ada_value_subscript
11305 (callee, nargs, argvec.data ()));
11306 }
11307 case TYPE_CODE_ARRAY:
11308 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11309 {
11310 type = ada_array_element_type (type, nargs);
11311 if (type == NULL)
11312 error (_("element type of array unknown"));
11313 else
11314 return value_zero (ada_aligned_type (type), lval_memory);
11315 }
11316 return
11317 unwrap_value (ada_value_subscript
11318 (ada_coerce_to_simple_array (callee),
11319 nargs, argvec.data ()));
11320 case TYPE_CODE_PTR: /* Pointer to array */
11321 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11322 {
11323 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
11324 type = ada_array_element_type (type, nargs);
11325 if (type == NULL)
11326 error (_("element type of array unknown"));
11327 else
11328 return value_zero (ada_aligned_type (type), lval_memory);
11329 }
11330 return
11331 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11332 argvec.data ()));
11333
11334 default:
11335 error (_("Attempt to index or call something other than an "
11336 "array or function"));
11337 }
11338 }
11339
11340 bool
11341 ada_funcall_operation::resolve (struct expression *exp,
11342 bool deprocedure_p,
11343 bool parse_completion,
11344 innermost_block_tracker *tracker,
11345 struct type *context_type)
11346 {
11347 operation_up &callee_op = std::get<0> (m_storage);
11348
11349 ada_var_value_operation *avv
11350 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11351 if (avv == nullptr)
11352 return false;
11353
11354 symbol *sym = avv->get_symbol ();
11355 if (SYMBOL_DOMAIN (sym) != UNDEF_DOMAIN)
11356 return false;
11357
11358 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11359 int nargs = args_up.size ();
11360 std::vector<value *> argvec (nargs);
11361
11362 for (int i = 0; i < args_up.size (); ++i)
11363 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11364
11365 const block *block = avv->get_block ();
11366 block_symbol resolved
11367 = ada_resolve_funcall (sym, block,
11368 context_type, parse_completion,
11369 nargs, argvec.data (),
11370 tracker);
11371
11372 std::get<0> (m_storage)
11373 = make_operation<ada_var_value_operation> (resolved.symbol,
11374 resolved.block);
11375 return false;
11376 }
11377
11378 bool
11379 ada_ternop_slice_operation::resolve (struct expression *exp,
11380 bool deprocedure_p,
11381 bool parse_completion,
11382 innermost_block_tracker *tracker,
11383 struct type *context_type)
11384 {
11385 /* Historically this check was done during resolution, so we
11386 continue that here. */
11387 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11388 EVAL_AVOID_SIDE_EFFECTS);
11389 if (ada_is_any_packed_array_type (value_type (v)))
11390 error (_("cannot slice a packed array"));
11391 return false;
11392 }
11393
11394 }
11395
11396 /* Implement the evaluate_exp routine in the exp_descriptor structure
11397 for the Ada language. */
11398
11399 static struct value *
11400 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
11401 int *pos, enum noside noside)
11402 {
11403 enum exp_opcode op;
11404 int tem;
11405 int pc;
11406 int preeval_pos;
11407 struct value *arg1 = NULL, *arg2 = NULL, *arg3;
11408 struct type *type;
11409 int nargs, oplen;
11410 struct value **argvec;
11411
11412 pc = *pos;
11413 *pos += 1;
11414 op = exp->elts[pc].opcode;
11415
11416 switch (op)
11417 {
11418 default:
11419 *pos -= 1;
11420 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
11421
11422 if (noside == EVAL_NORMAL)
11423 arg1 = unwrap_value (arg1);
11424
11425 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
11426 then we need to perform the conversion manually, because
11427 evaluate_subexp_standard doesn't do it. This conversion is
11428 necessary in Ada because the different kinds of float/fixed
11429 types in Ada have different representations.
11430
11431 Similarly, we need to perform the conversion from OP_LONG
11432 ourselves. */
11433 if ((op == OP_FLOAT || op == OP_LONG) && expect_type != NULL)
11434 arg1 = ada_value_cast (expect_type, arg1);
11435
11436 return arg1;
11437
11438 case OP_STRING:
11439 {
11440 struct value *result;
11441
11442 *pos -= 1;
11443 result = evaluate_subexp_standard (expect_type, exp, pos, noside);
11444 /* The result type will have code OP_STRING, bashed there from
11445 OP_ARRAY. Bash it back. */
11446 if (value_type (result)->code () == TYPE_CODE_STRING)
11447 value_type (result)->set_code (TYPE_CODE_ARRAY);
11448 return result;
11449 }
11450
11451 case UNOP_CAST:
11452 (*pos) += 2;
11453 type = exp->elts[pc + 1].type;
11454 return ada_evaluate_subexp_for_cast (exp, pos, noside, type);
11455
11456 case UNOP_QUAL:
11457 (*pos) += 2;
11458 type = exp->elts[pc + 1].type;
11459 return ada_evaluate_subexp (type, exp, pos, noside);
11460
11461 case BINOP_ASSIGN:
11462 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11463 if (exp->elts[*pos].opcode == OP_AGGREGATE)
11464 {
11465 arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
11466 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
11467 return arg1;
11468 return ada_value_assign (arg1, arg1);
11469 }
11470 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
11471 except if the lhs of our assignment is a convenience variable.
11472 In the case of assigning to a convenience variable, the lhs
11473 should be exactly the result of the evaluation of the rhs. */
11474 type = value_type (arg1);
11475 if (VALUE_LVAL (arg1) == lval_internalvar)
11476 type = NULL;
11477 arg2 = evaluate_subexp (type, exp, pos, noside);
11478 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
11479 return arg1;
11480 if (VALUE_LVAL (arg1) == lval_internalvar)
11481 {
11482 /* Nothing. */
11483 }
11484 else
11485 arg2 = coerce_for_assign (value_type (arg1), arg2);
11486 return ada_value_assign (arg1, arg2);
11487
11488 case BINOP_ADD:
11489 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
11490 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
11491 if (noside == EVAL_SKIP)
11492 goto nosideret;
11493 if (value_type (arg1)->code () == TYPE_CODE_PTR)
11494 return (value_from_longest
11495 (value_type (arg1),
11496 value_as_long (arg1) + value_as_long (arg2)));
11497 if (value_type (arg2)->code () == TYPE_CODE_PTR)
11498 return (value_from_longest
11499 (value_type (arg2),
11500 value_as_long (arg1) + value_as_long (arg2)));
11501 /* Preserve the original type for use by the range case below.
11502 We cannot cast the result to a reference type, so if ARG1 is
11503 a reference type, find its underlying type. */
11504 type = value_type (arg1);
11505 while (type->code () == TYPE_CODE_REF)
11506 type = TYPE_TARGET_TYPE (type);
11507 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11508 arg1 = value_binop (arg1, arg2, BINOP_ADD);
11509 /* We need to special-case the result of adding to a range.
11510 This is done for the benefit of "ptype". gdb's Ada support
11511 historically used the LHS to set the result type here, so
11512 preserve this behavior. */
11513 if (type->code () == TYPE_CODE_RANGE)
11514 arg1 = value_cast (type, arg1);
11515 return arg1;
11516
11517 case BINOP_SUB:
11518 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
11519 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
11520 if (noside == EVAL_SKIP)
11521 goto nosideret;
11522 if (value_type (arg1)->code () == TYPE_CODE_PTR)
11523 return (value_from_longest
11524 (value_type (arg1),
11525 value_as_long (arg1) - value_as_long (arg2)));
11526 if (value_type (arg2)->code () == TYPE_CODE_PTR)
11527 return (value_from_longest
11528 (value_type (arg2),
11529 value_as_long (arg1) - value_as_long (arg2)));
11530 /* Preserve the original type for use by the range case below.
11531 We cannot cast the result to a reference type, so if ARG1 is
11532 a reference type, find its underlying type. */
11533 type = value_type (arg1);
11534 while (type->code () == TYPE_CODE_REF)
11535 type = TYPE_TARGET_TYPE (type);
11536 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11537 arg1 = value_binop (arg1, arg2, BINOP_SUB);
11538 /* We need to special-case the result of adding to a range.
11539 This is done for the benefit of "ptype". gdb's Ada support
11540 historically used the LHS to set the result type here, so
11541 preserve this behavior. */
11542 if (type->code () == TYPE_CODE_RANGE)
11543 arg1 = value_cast (type, arg1);
11544 return arg1;
11545
11546 case BINOP_MUL:
11547 case BINOP_DIV:
11548 case BINOP_REM:
11549 case BINOP_MOD:
11550 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11551 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11552 if (noside == EVAL_SKIP)
11553 goto nosideret;
11554 return ada_mult_binop (expect_type, exp, noside, op,
11555 arg1, arg2);
11556
11557 case BINOP_EQUAL:
11558 case BINOP_NOTEQUAL:
11559 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11560 arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
11561 if (noside == EVAL_SKIP)
11562 goto nosideret;
11563 return ada_equal_binop (expect_type, exp, noside, op, arg1, arg2);
11564
11565 case UNOP_NEG:
11566 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11567 return ada_unop_neg (expect_type, exp, noside, op, arg1);
11568
11569 case BINOP_LOGICAL_AND:
11570 case BINOP_LOGICAL_OR:
11571 case UNOP_LOGICAL_NOT:
11572 {
11573 struct value *val;
11574
11575 *pos -= 1;
11576 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
11577 type = language_bool_type (exp->language_defn, exp->gdbarch);
11578 return value_cast (type, val);
11579 }
11580
11581 case BINOP_BITWISE_AND:
11582 case BINOP_BITWISE_IOR:
11583 case BINOP_BITWISE_XOR:
11584 {
11585 struct value *val;
11586
11587 arg1 = evaluate_subexp (nullptr, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
11588 *pos = pc;
11589 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
11590
11591 return value_cast (value_type (arg1), val);
11592 }
11593
11594 case OP_VAR_VALUE:
11595 *pos -= 1;
11596
11597 if (noside == EVAL_SKIP)
11598 {
11599 *pos += 4;
11600 goto nosideret;
11601 }
11602
11603 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
11604 /* Only encountered when an unresolved symbol occurs in a
11605 context other than a function call, in which case, it is
11606 invalid. */
11607 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11608 exp->elts[pc + 2].symbol->print_name ());
11609
11610 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11611 {
11612 type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
11613 /* Check to see if this is a tagged type. We also need to handle
11614 the case where the type is a reference to a tagged type, but
11615 we have to be careful to exclude pointers to tagged types.
11616 The latter should be shown as usual (as a pointer), whereas
11617 a reference should mostly be transparent to the user. */
11618 if (ada_is_tagged_type (type, 0)
11619 || (type->code () == TYPE_CODE_REF
11620 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
11621 {
11622 /* Tagged types are a little special in the fact that the real
11623 type is dynamic and can only be determined by inspecting the
11624 object's tag. This means that we need to get the object's
11625 value first (EVAL_NORMAL) and then extract the actual object
11626 type from its tag.
11627
11628 Note that we cannot skip the final step where we extract
11629 the object type from its tag, because the EVAL_NORMAL phase
11630 results in dynamic components being resolved into fixed ones.
11631 This can cause problems when trying to print the type
11632 description of tagged types whose parent has a dynamic size:
11633 We use the type name of the "_parent" component in order
11634 to print the name of the ancestor type in the type description.
11635 If that component had a dynamic size, the resolution into
11636 a fixed type would result in the loss of that type name,
11637 thus preventing us from printing the name of the ancestor
11638 type in the type description. */
11639 arg1 = evaluate_subexp (nullptr, exp, pos, EVAL_NORMAL);
11640
11641 if (type->code () != TYPE_CODE_REF)
11642 {
11643 struct type *actual_type;
11644
11645 actual_type = type_from_tag (ada_value_tag (arg1));
11646 if (actual_type == NULL)
11647 /* If, for some reason, we were unable to determine
11648 the actual type from the tag, then use the static
11649 approximation that we just computed as a fallback.
11650 This can happen if the debugging information is
11651 incomplete, for instance. */
11652 actual_type = type;
11653 return value_zero (actual_type, not_lval);
11654 }
11655 else
11656 {
11657 /* In the case of a ref, ada_coerce_ref takes care
11658 of determining the actual type. But the evaluation
11659 should return a ref as it should be valid to ask
11660 for its address; so rebuild a ref after coerce. */
11661 arg1 = ada_coerce_ref (arg1);
11662 return value_ref (arg1, TYPE_CODE_REF);
11663 }
11664 }
11665
11666 /* Records and unions for which GNAT encodings have been
11667 generated need to be statically fixed as well.
11668 Otherwise, non-static fixing produces a type where
11669 all dynamic properties are removed, which prevents "ptype"
11670 from being able to completely describe the type.
11671 For instance, a case statement in a variant record would be
11672 replaced by the relevant components based on the actual
11673 value of the discriminants. */
11674 if ((type->code () == TYPE_CODE_STRUCT
11675 && dynamic_template_type (type) != NULL)
11676 || (type->code () == TYPE_CODE_UNION
11677 && ada_find_parallel_type (type, "___XVU") != NULL))
11678 {
11679 *pos += 4;
11680 return value_zero (to_static_fixed_type (type), not_lval);
11681 }
11682 }
11683
11684 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
11685 return ada_to_fixed_value (arg1);
11686
11687 case OP_FUNCALL:
11688 (*pos) += 2;
11689
11690 /* Allocate arg vector, including space for the function to be
11691 called in argvec[0] and a terminating NULL. */
11692 nargs = longest_to_int (exp->elts[pc + 1].longconst);
11693 argvec = XALLOCAVEC (struct value *, nargs + 2);
11694
11695 if (exp->elts[*pos].opcode == OP_VAR_VALUE
11696 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
11697 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11698 exp->elts[pc + 5].symbol->print_name ());
11699 else
11700 {
11701 for (tem = 0; tem <= nargs; tem += 1)
11702 argvec[tem] = evaluate_subexp (nullptr, exp, pos, noside);
11703 argvec[tem] = 0;
11704
11705 if (noside == EVAL_SKIP)
11706 goto nosideret;
11707 }
11708
11709 if (ada_is_constrained_packed_array_type
11710 (desc_base_type (value_type (argvec[0]))))
11711 argvec[0] = ada_coerce_to_simple_array (argvec[0]);
11712 else if (value_type (argvec[0])->code () == TYPE_CODE_ARRAY
11713 && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
11714 /* This is a packed array that has already been fixed, and
11715 therefore already coerced to a simple array. Nothing further
11716 to do. */
11717 ;
11718 else if (value_type (argvec[0])->code () == TYPE_CODE_REF)
11719 {
11720 /* Make sure we dereference references so that all the code below
11721 feels like it's really handling the referenced value. Wrapping
11722 types (for alignment) may be there, so make sure we strip them as
11723 well. */
11724 argvec[0] = ada_to_fixed_value (coerce_ref (argvec[0]));
11725 }
11726 else if (value_type (argvec[0])->code () == TYPE_CODE_ARRAY
11727 && VALUE_LVAL (argvec[0]) == lval_memory)
11728 argvec[0] = value_addr (argvec[0]);
11729
11730 type = ada_check_typedef (value_type (argvec[0]));
11731
11732 /* Ada allows us to implicitly dereference arrays when subscripting
11733 them. So, if this is an array typedef (encoding use for array
11734 access types encoded as fat pointers), strip it now. */
11735 if (type->code () == TYPE_CODE_TYPEDEF)
11736 type = ada_typedef_target_type (type);
11737
11738 if (type->code () == TYPE_CODE_PTR)
11739 {
11740 switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
11741 {
11742 case TYPE_CODE_FUNC:
11743 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11744 break;
11745 case TYPE_CODE_ARRAY:
11746 break;
11747 case TYPE_CODE_STRUCT:
11748 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11749 argvec[0] = ada_value_ind (argvec[0]);
11750 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11751 break;
11752 default:
11753 error (_("cannot subscript or call something of type `%s'"),
11754 ada_type_name (value_type (argvec[0])));
11755 break;
11756 }
11757 }
11758
11759 switch (type->code ())
11760 {
11761 case TYPE_CODE_FUNC:
11762 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11763 {
11764 if (TYPE_TARGET_TYPE (type) == NULL)
11765 error_call_unknown_return_type (NULL);
11766 return allocate_value (TYPE_TARGET_TYPE (type));
11767 }
11768 return call_function_by_hand (argvec[0], NULL,
11769 gdb::make_array_view (argvec + 1,
11770 nargs));
11771 case TYPE_CODE_INTERNAL_FUNCTION:
11772 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11773 /* We don't know anything about what the internal
11774 function might return, but we have to return
11775 something. */
11776 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11777 not_lval);
11778 else
11779 return call_internal_function (exp->gdbarch, exp->language_defn,
11780 argvec[0], nargs, argvec + 1);
11781
11782 case TYPE_CODE_STRUCT:
11783 {
11784 int arity;
11785
11786 arity = ada_array_arity (type);
11787 type = ada_array_element_type (type, nargs);
11788 if (type == NULL)
11789 error (_("cannot subscript or call a record"));
11790 if (arity != nargs)
11791 error (_("wrong number of subscripts; expecting %d"), arity);
11792 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11793 return value_zero (ada_aligned_type (type), lval_memory);
11794 return
11795 unwrap_value (ada_value_subscript
11796 (argvec[0], nargs, argvec + 1));
11797 }
11798 case TYPE_CODE_ARRAY:
11799 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11800 {
11801 type = ada_array_element_type (type, nargs);
11802 if (type == NULL)
11803 error (_("element type of array unknown"));
11804 else
11805 return value_zero (ada_aligned_type (type), lval_memory);
11806 }
11807 return
11808 unwrap_value (ada_value_subscript
11809 (ada_coerce_to_simple_array (argvec[0]),
11810 nargs, argvec + 1));
11811 case TYPE_CODE_PTR: /* Pointer to array */
11812 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11813 {
11814 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
11815 type = ada_array_element_type (type, nargs);
11816 if (type == NULL)
11817 error (_("element type of array unknown"));
11818 else
11819 return value_zero (ada_aligned_type (type), lval_memory);
11820 }
11821 return
11822 unwrap_value (ada_value_ptr_subscript (argvec[0],
11823 nargs, argvec + 1));
11824
11825 default:
11826 error (_("Attempt to index or call something other than an "
11827 "array or function"));
11828 }
11829
11830 case TERNOP_SLICE:
11831 {
11832 struct value *array = evaluate_subexp (nullptr, exp, pos, noside);
11833 struct value *low_bound_val
11834 = evaluate_subexp (nullptr, exp, pos, noside);
11835 struct value *high_bound_val
11836 = evaluate_subexp (nullptr, exp, pos, noside);
11837
11838 if (noside == EVAL_SKIP)
11839 goto nosideret;
11840
11841 return ada_ternop_slice (exp, noside, array, low_bound_val,
11842 high_bound_val);
11843 }
11844
11845 case UNOP_IN_RANGE:
11846 (*pos) += 2;
11847 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11848 type = check_typedef (exp->elts[pc + 1].type);
11849 return ada_unop_in_range (expect_type, exp, noside, op, arg1, type);
11850
11851 case BINOP_IN_BOUNDS:
11852 (*pos) += 2;
11853 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11854 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11855
11856 if (noside == EVAL_SKIP)
11857 goto nosideret;
11858
11859 tem = longest_to_int (exp->elts[pc + 1].longconst);
11860
11861 return ada_binop_in_bounds (exp, noside, arg1, arg2, tem);
11862
11863 case TERNOP_IN_RANGE:
11864 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11865 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11866 arg3 = evaluate_subexp (nullptr, exp, pos, noside);
11867
11868 return eval_ternop_in_range (expect_type, exp, noside, arg1, arg2, arg3);
11869
11870 case OP_ATR_FIRST:
11871 case OP_ATR_LAST:
11872 case OP_ATR_LENGTH:
11873 {
11874 struct type *type_arg;
11875
11876 if (exp->elts[*pos].opcode == OP_TYPE)
11877 {
11878 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11879 arg1 = NULL;
11880 type_arg = check_typedef (exp->elts[pc + 2].type);
11881 }
11882 else
11883 {
11884 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11885 type_arg = NULL;
11886 }
11887
11888 if (exp->elts[*pos].opcode != OP_LONG)
11889 error (_("Invalid operand to '%s"), ada_attribute_name (op));
11890 tem = longest_to_int (exp->elts[*pos + 2].longconst);
11891 *pos += 4;
11892
11893 if (noside == EVAL_SKIP)
11894 goto nosideret;
11895
11896 return ada_unop_atr (exp, noside, op, arg1, type_arg, tem);
11897 }
11898
11899 case OP_ATR_TAG:
11900 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11901 if (noside == EVAL_SKIP)
11902 goto nosideret;
11903 return ada_atr_tag (expect_type, exp, noside, op, arg1);
11904
11905 case OP_ATR_MIN:
11906 case OP_ATR_MAX:
11907 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11908 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11909 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11910 if (noside == EVAL_SKIP)
11911 goto nosideret;
11912 return ada_binop_minmax (expect_type, exp, noside, op, arg1, arg2);
11913
11914 case OP_ATR_MODULUS:
11915 {
11916 struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
11917
11918 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11919 if (noside == EVAL_SKIP)
11920 goto nosideret;
11921
11922 if (!ada_is_modular_type (type_arg))
11923 error (_("'modulus must be applied to modular type"));
11924
11925 return value_from_longest (TYPE_TARGET_TYPE (type_arg),
11926 ada_modulus (type_arg));
11927 }
11928
11929
11930 case OP_ATR_POS:
11931 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11932 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11933 if (noside == EVAL_SKIP)
11934 goto nosideret;
11935 return ada_pos_atr (expect_type, exp, noside, op, arg1);
11936
11937 case OP_ATR_SIZE:
11938 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11939 return ada_atr_size (expect_type, exp, noside, op, arg1);
11940
11941 case OP_ATR_VAL:
11942 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11943 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11944 type = exp->elts[pc + 2].type;
11945 if (noside == EVAL_SKIP)
11946 goto nosideret;
11947 return ada_val_atr (noside, type, arg1);
11948
11949 case BINOP_EXP:
11950 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11951 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11952 if (noside == EVAL_SKIP)
11953 goto nosideret;
11954 return ada_binop_exp (expect_type, exp, noside, op, arg1, arg2);
11955
11956 case UNOP_PLUS:
11957 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11958 if (noside == EVAL_SKIP)
11959 goto nosideret;
11960 else
11961 return arg1;
11962
11963 case UNOP_ABS:
11964 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11965 if (noside == EVAL_SKIP)
11966 goto nosideret;
11967 return ada_abs (expect_type, exp, noside, op, arg1);
11968
11969 case UNOP_IND:
11970 preeval_pos = *pos;
11971 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11972 if (noside == EVAL_SKIP)
11973 goto nosideret;
11974 type = ada_check_typedef (value_type (arg1));
11975 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11976 {
11977 if (ada_is_array_descriptor_type (type))
11978 /* GDB allows dereferencing GNAT array descriptors. */
11979 {
11980 struct type *arrType = ada_type_of_array (arg1, 0);
11981
11982 if (arrType == NULL)
11983 error (_("Attempt to dereference null array pointer."));
11984 return value_at_lazy (arrType, 0);
11985 }
11986 else if (type->code () == TYPE_CODE_PTR
11987 || type->code () == TYPE_CODE_REF
11988 /* In C you can dereference an array to get the 1st elt. */
11989 || type->code () == TYPE_CODE_ARRAY)
11990 {
11991 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11992 only be determined by inspecting the object's tag.
11993 This means that we need to evaluate completely the
11994 expression in order to get its type. */
11995
11996 if ((type->code () == TYPE_CODE_REF
11997 || type->code () == TYPE_CODE_PTR)
11998 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11999 {
12000 arg1
12001 = evaluate_subexp (nullptr, exp, &preeval_pos, EVAL_NORMAL);
12002 type = value_type (ada_value_ind (arg1));
12003 }
12004 else
12005 {
12006 type = to_static_fixed_type
12007 (ada_aligned_type
12008 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
12009 }
12010 ada_ensure_varsize_limit (type);
12011 return value_zero (type, lval_memory);
12012 }
12013 else if (type->code () == TYPE_CODE_INT)
12014 {
12015 /* GDB allows dereferencing an int. */
12016 if (expect_type == NULL)
12017 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
12018 lval_memory);
12019 else
12020 {
12021 expect_type =
12022 to_static_fixed_type (ada_aligned_type (expect_type));
12023 return value_zero (expect_type, lval_memory);
12024 }
12025 }
12026 else
12027 error (_("Attempt to take contents of a non-pointer value."));
12028 }
12029 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
12030 type = ada_check_typedef (value_type (arg1));
12031
12032 if (type->code () == TYPE_CODE_INT)
12033 /* GDB allows dereferencing an int. If we were given
12034 the expect_type, then use that as the target type.
12035 Otherwise, assume that the target type is an int. */
12036 {
12037 if (expect_type != NULL)
12038 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
12039 arg1));
12040 else
12041 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
12042 (CORE_ADDR) value_as_address (arg1));
12043 }
12044
12045 if (ada_is_array_descriptor_type (type))
12046 /* GDB allows dereferencing GNAT array descriptors. */
12047 return ada_coerce_to_simple_array (arg1);
12048 else
12049 return ada_value_ind (arg1);
12050
12051 case STRUCTOP_STRUCT:
12052 tem = longest_to_int (exp->elts[pc + 1].longconst);
12053 (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
12054 preeval_pos = *pos;
12055 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
12056 if (noside == EVAL_SKIP)
12057 goto nosideret;
12058 if (noside == EVAL_AVOID_SIDE_EFFECTS)
12059 {
12060 struct type *type1 = value_type (arg1);
12061
12062 if (ada_is_tagged_type (type1, 1))
12063 {
12064 type = ada_lookup_struct_elt_type (type1,
12065 &exp->elts[pc + 2].string,
12066 1, 1);
12067
12068 /* If the field is not found, check if it exists in the
12069 extension of this object's type. This means that we
12070 need to evaluate completely the expression. */
12071
12072 if (type == NULL)
12073 {
12074 arg1
12075 = evaluate_subexp (nullptr, exp, &preeval_pos, EVAL_NORMAL);
12076 arg1 = ada_value_struct_elt (arg1,
12077 &exp->elts[pc + 2].string,
12078 0);
12079 arg1 = unwrap_value (arg1);
12080 type = value_type (ada_to_fixed_value (arg1));
12081 }
12082 }
12083 else
12084 type =
12085 ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
12086 0);
12087
12088 return value_zero (ada_aligned_type (type), lval_memory);
12089 }
12090 else
12091 {
12092 arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
12093 arg1 = unwrap_value (arg1);
12094 return ada_to_fixed_value (arg1);
12095 }
12096
12097 case OP_TYPE:
12098 /* The value is not supposed to be used. This is here to make it
12099 easier to accommodate expressions that contain types. */
12100 (*pos) += 2;
12101 if (noside == EVAL_SKIP)
12102 goto nosideret;
12103 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
12104 return allocate_value (exp->elts[pc + 1].type);
12105 else
12106 error (_("Attempt to use a type name as an expression"));
12107
12108 case OP_AGGREGATE:
12109 case OP_CHOICES:
12110 case OP_OTHERS:
12111 case OP_DISCRETE_RANGE:
12112 case OP_POSITIONAL:
12113 case OP_NAME:
12114 if (noside == EVAL_NORMAL)
12115 switch (op)
12116 {
12117 case OP_NAME:
12118 error (_("Undefined name, ambiguous name, or renaming used in "
12119 "component association: %s."), &exp->elts[pc+2].string);
12120 case OP_AGGREGATE:
12121 error (_("Aggregates only allowed on the right of an assignment"));
12122 default:
12123 internal_error (__FILE__, __LINE__,
12124 _("aggregate apparently mangled"));
12125 }
12126
12127 ada_forward_operator_length (exp, pc, &oplen, &nargs);
12128 *pos += oplen - 1;
12129 for (tem = 0; tem < nargs; tem += 1)
12130 ada_evaluate_subexp (NULL, exp, pos, noside);
12131 goto nosideret;
12132 }
12133
12134 nosideret:
12135 return eval_skip_value (exp);
12136 }
12137 \f
12138
12139 /* Return non-zero iff TYPE represents a System.Address type. */
12140
12141 int
12142 ada_is_system_address_type (struct type *type)
12143 {
12144 return (type->name () && strcmp (type->name (), "system__address") == 0);
12145 }
12146
12147 \f
12148
12149 /* Range types */
12150
12151 /* Scan STR beginning at position K for a discriminant name, and
12152 return the value of that discriminant field of DVAL in *PX. If
12153 PNEW_K is not null, put the position of the character beyond the
12154 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
12155 not alter *PX and *PNEW_K if unsuccessful. */
12156
12157 static int
12158 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
12159 int *pnew_k)
12160 {
12161 static std::string storage;
12162 const char *pstart, *pend, *bound;
12163 struct value *bound_val;
12164
12165 if (dval == NULL || str == NULL || str[k] == '\0')
12166 return 0;
12167
12168 pstart = str + k;
12169 pend = strstr (pstart, "__");
12170 if (pend == NULL)
12171 {
12172 bound = pstart;
12173 k += strlen (bound);
12174 }
12175 else
12176 {
12177 int len = pend - pstart;
12178
12179 /* Strip __ and beyond. */
12180 storage = std::string (pstart, len);
12181 bound = storage.c_str ();
12182 k = pend - str;
12183 }
12184
12185 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
12186 if (bound_val == NULL)
12187 return 0;
12188
12189 *px = value_as_long (bound_val);
12190 if (pnew_k != NULL)
12191 *pnew_k = k;
12192 return 1;
12193 }
12194
12195 /* Value of variable named NAME. Only exact matches are considered.
12196 If no such variable found, then if ERR_MSG is null, returns 0, and
12197 otherwise causes an error with message ERR_MSG. */
12198
12199 static struct value *
12200 get_var_value (const char *name, const char *err_msg)
12201 {
12202 std::string quoted_name = add_angle_brackets (name);
12203
12204 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
12205
12206 std::vector<struct block_symbol> syms
12207 = ada_lookup_symbol_list_worker (lookup_name,
12208 get_selected_block (0),
12209 VAR_DOMAIN, 1);
12210
12211 if (syms.size () != 1)
12212 {
12213 if (err_msg == NULL)
12214 return 0;
12215 else
12216 error (("%s"), err_msg);
12217 }
12218
12219 return value_of_variable (syms[0].symbol, syms[0].block);
12220 }
12221
12222 /* Value of integer variable named NAME in the current environment.
12223 If no such variable is found, returns false. Otherwise, sets VALUE
12224 to the variable's value and returns true. */
12225
12226 bool
12227 get_int_var_value (const char *name, LONGEST &value)
12228 {
12229 struct value *var_val = get_var_value (name, 0);
12230
12231 if (var_val == 0)
12232 return false;
12233
12234 value = value_as_long (var_val);
12235 return true;
12236 }
12237
12238
12239 /* Return a range type whose base type is that of the range type named
12240 NAME in the current environment, and whose bounds are calculated
12241 from NAME according to the GNAT range encoding conventions.
12242 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
12243 corresponding range type from debug information; fall back to using it
12244 if symbol lookup fails. If a new type must be created, allocate it
12245 like ORIG_TYPE was. The bounds information, in general, is encoded
12246 in NAME, the base type given in the named range type. */
12247
12248 static struct type *
12249 to_fixed_range_type (struct type *raw_type, struct value *dval)
12250 {
12251 const char *name;
12252 struct type *base_type;
12253 const char *subtype_info;
12254
12255 gdb_assert (raw_type != NULL);
12256 gdb_assert (raw_type->name () != NULL);
12257
12258 if (raw_type->code () == TYPE_CODE_RANGE)
12259 base_type = TYPE_TARGET_TYPE (raw_type);
12260 else
12261 base_type = raw_type;
12262
12263 name = raw_type->name ();
12264 subtype_info = strstr (name, "___XD");
12265 if (subtype_info == NULL)
12266 {
12267 LONGEST L = ada_discrete_type_low_bound (raw_type);
12268 LONGEST U = ada_discrete_type_high_bound (raw_type);
12269
12270 if (L < INT_MIN || U > INT_MAX)
12271 return raw_type;
12272 else
12273 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
12274 L, U);
12275 }
12276 else
12277 {
12278 int prefix_len = subtype_info - name;
12279 LONGEST L, U;
12280 struct type *type;
12281 const char *bounds_str;
12282 int n;
12283
12284 subtype_info += 5;
12285 bounds_str = strchr (subtype_info, '_');
12286 n = 1;
12287
12288 if (*subtype_info == 'L')
12289 {
12290 if (!ada_scan_number (bounds_str, n, &L, &n)
12291 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
12292 return raw_type;
12293 if (bounds_str[n] == '_')
12294 n += 2;
12295 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
12296 n += 1;
12297 subtype_info += 1;
12298 }
12299 else
12300 {
12301 std::string name_buf = std::string (name, prefix_len) + "___L";
12302 if (!get_int_var_value (name_buf.c_str (), L))
12303 {
12304 lim_warning (_("Unknown lower bound, using 1."));
12305 L = 1;
12306 }
12307 }
12308
12309 if (*subtype_info == 'U')
12310 {
12311 if (!ada_scan_number (bounds_str, n, &U, &n)
12312 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
12313 return raw_type;
12314 }
12315 else
12316 {
12317 std::string name_buf = std::string (name, prefix_len) + "___U";
12318 if (!get_int_var_value (name_buf.c_str (), U))
12319 {
12320 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
12321 U = L;
12322 }
12323 }
12324
12325 type = create_static_range_type (alloc_type_copy (raw_type),
12326 base_type, L, U);
12327 /* create_static_range_type alters the resulting type's length
12328 to match the size of the base_type, which is not what we want.
12329 Set it back to the original range type's length. */
12330 TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
12331 type->set_name (name);
12332 return type;
12333 }
12334 }
12335
12336 /* True iff NAME is the name of a range type. */
12337
12338 int
12339 ada_is_range_type_name (const char *name)
12340 {
12341 return (name != NULL && strstr (name, "___XD"));
12342 }
12343 \f
12344
12345 /* Modular types */
12346
12347 /* True iff TYPE is an Ada modular type. */
12348
12349 int
12350 ada_is_modular_type (struct type *type)
12351 {
12352 struct type *subranged_type = get_base_type (type);
12353
12354 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
12355 && subranged_type->code () == TYPE_CODE_INT
12356 && subranged_type->is_unsigned ());
12357 }
12358
12359 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
12360
12361 ULONGEST
12362 ada_modulus (struct type *type)
12363 {
12364 const dynamic_prop &high = type->bounds ()->high;
12365
12366 if (high.kind () == PROP_CONST)
12367 return (ULONGEST) high.const_val () + 1;
12368
12369 /* If TYPE is unresolved, the high bound might be a location list. Return
12370 0, for lack of a better value to return. */
12371 return 0;
12372 }
12373 \f
12374
12375 /* Ada exception catchpoint support:
12376 ---------------------------------
12377
12378 We support 3 kinds of exception catchpoints:
12379 . catchpoints on Ada exceptions
12380 . catchpoints on unhandled Ada exceptions
12381 . catchpoints on failed assertions
12382
12383 Exceptions raised during failed assertions, or unhandled exceptions
12384 could perfectly be caught with the general catchpoint on Ada exceptions.
12385 However, we can easily differentiate these two special cases, and having
12386 the option to distinguish these two cases from the rest can be useful
12387 to zero-in on certain situations.
12388
12389 Exception catchpoints are a specialized form of breakpoint,
12390 since they rely on inserting breakpoints inside known routines
12391 of the GNAT runtime. The implementation therefore uses a standard
12392 breakpoint structure of the BP_BREAKPOINT type, but with its own set
12393 of breakpoint_ops.
12394
12395 Support in the runtime for exception catchpoints have been changed
12396 a few times already, and these changes affect the implementation
12397 of these catchpoints. In order to be able to support several
12398 variants of the runtime, we use a sniffer that will determine
12399 the runtime variant used by the program being debugged. */
12400
12401 /* Ada's standard exceptions.
12402
12403 The Ada 83 standard also defined Numeric_Error. But there so many
12404 situations where it was unclear from the Ada 83 Reference Manual
12405 (RM) whether Constraint_Error or Numeric_Error should be raised,
12406 that the ARG (Ada Rapporteur Group) eventually issued a Binding
12407 Interpretation saying that anytime the RM says that Numeric_Error
12408 should be raised, the implementation may raise Constraint_Error.
12409 Ada 95 went one step further and pretty much removed Numeric_Error
12410 from the list of standard exceptions (it made it a renaming of
12411 Constraint_Error, to help preserve compatibility when compiling
12412 an Ada83 compiler). As such, we do not include Numeric_Error from
12413 this list of standard exceptions. */
12414
12415 static const char * const standard_exc[] = {
12416 "constraint_error",
12417 "program_error",
12418 "storage_error",
12419 "tasking_error"
12420 };
12421
12422 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
12423
12424 /* A structure that describes how to support exception catchpoints
12425 for a given executable. */
12426
12427 struct exception_support_info
12428 {
12429 /* The name of the symbol to break on in order to insert
12430 a catchpoint on exceptions. */
12431 const char *catch_exception_sym;
12432
12433 /* The name of the symbol to break on in order to insert
12434 a catchpoint on unhandled exceptions. */
12435 const char *catch_exception_unhandled_sym;
12436
12437 /* The name of the symbol to break on in order to insert
12438 a catchpoint on failed assertions. */
12439 const char *catch_assert_sym;
12440
12441 /* The name of the symbol to break on in order to insert
12442 a catchpoint on exception handling. */
12443 const char *catch_handlers_sym;
12444
12445 /* Assuming that the inferior just triggered an unhandled exception
12446 catchpoint, this function is responsible for returning the address
12447 in inferior memory where the name of that exception is stored.
12448 Return zero if the address could not be computed. */
12449 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
12450 };
12451
12452 static CORE_ADDR ada_unhandled_exception_name_addr (void);
12453 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
12454
12455 /* The following exception support info structure describes how to
12456 implement exception catchpoints with the latest version of the
12457 Ada runtime (as of 2019-08-??). */
12458
12459 static const struct exception_support_info default_exception_support_info =
12460 {
12461 "__gnat_debug_raise_exception", /* catch_exception_sym */
12462 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12463 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
12464 "__gnat_begin_handler_v1", /* catch_handlers_sym */
12465 ada_unhandled_exception_name_addr
12466 };
12467
12468 /* The following exception support info structure describes how to
12469 implement exception catchpoints with an earlier version of the
12470 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
12471
12472 static const struct exception_support_info exception_support_info_v0 =
12473 {
12474 "__gnat_debug_raise_exception", /* catch_exception_sym */
12475 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12476 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
12477 "__gnat_begin_handler", /* catch_handlers_sym */
12478 ada_unhandled_exception_name_addr
12479 };
12480
12481 /* The following exception support info structure describes how to
12482 implement exception catchpoints with a slightly older version
12483 of the Ada runtime. */
12484
12485 static const struct exception_support_info exception_support_info_fallback =
12486 {
12487 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
12488 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12489 "system__assertions__raise_assert_failure", /* catch_assert_sym */
12490 "__gnat_begin_handler", /* catch_handlers_sym */
12491 ada_unhandled_exception_name_addr_from_raise
12492 };
12493
12494 /* Return nonzero if we can detect the exception support routines
12495 described in EINFO.
12496
12497 This function errors out if an abnormal situation is detected
12498 (for instance, if we find the exception support routines, but
12499 that support is found to be incomplete). */
12500
12501 static int
12502 ada_has_this_exception_support (const struct exception_support_info *einfo)
12503 {
12504 struct symbol *sym;
12505
12506 /* The symbol we're looking up is provided by a unit in the GNAT runtime
12507 that should be compiled with debugging information. As a result, we
12508 expect to find that symbol in the symtabs. */
12509
12510 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
12511 if (sym == NULL)
12512 {
12513 /* Perhaps we did not find our symbol because the Ada runtime was
12514 compiled without debugging info, or simply stripped of it.
12515 It happens on some GNU/Linux distributions for instance, where
12516 users have to install a separate debug package in order to get
12517 the runtime's debugging info. In that situation, let the user
12518 know why we cannot insert an Ada exception catchpoint.
12519
12520 Note: Just for the purpose of inserting our Ada exception
12521 catchpoint, we could rely purely on the associated minimal symbol.
12522 But we would be operating in degraded mode anyway, since we are
12523 still lacking the debugging info needed later on to extract
12524 the name of the exception being raised (this name is printed in
12525 the catchpoint message, and is also used when trying to catch
12526 a specific exception). We do not handle this case for now. */
12527 struct bound_minimal_symbol msym
12528 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
12529
12530 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
12531 error (_("Your Ada runtime appears to be missing some debugging "
12532 "information.\nCannot insert Ada exception catchpoint "
12533 "in this configuration."));
12534
12535 return 0;
12536 }
12537
12538 /* Make sure that the symbol we found corresponds to a function. */
12539
12540 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12541 {
12542 error (_("Symbol \"%s\" is not a function (class = %d)"),
12543 sym->linkage_name (), SYMBOL_CLASS (sym));
12544 return 0;
12545 }
12546
12547 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
12548 if (sym == NULL)
12549 {
12550 struct bound_minimal_symbol msym
12551 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
12552
12553 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
12554 error (_("Your Ada runtime appears to be missing some debugging "
12555 "information.\nCannot insert Ada exception catchpoint "
12556 "in this configuration."));
12557
12558 return 0;
12559 }
12560
12561 /* Make sure that the symbol we found corresponds to a function. */
12562
12563 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12564 {
12565 error (_("Symbol \"%s\" is not a function (class = %d)"),
12566 sym->linkage_name (), SYMBOL_CLASS (sym));
12567 return 0;
12568 }
12569
12570 return 1;
12571 }
12572
12573 /* Inspect the Ada runtime and determine which exception info structure
12574 should be used to provide support for exception catchpoints.
12575
12576 This function will always set the per-inferior exception_info,
12577 or raise an error. */
12578
12579 static void
12580 ada_exception_support_info_sniffer (void)
12581 {
12582 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12583
12584 /* If the exception info is already known, then no need to recompute it. */
12585 if (data->exception_info != NULL)
12586 return;
12587
12588 /* Check the latest (default) exception support info. */
12589 if (ada_has_this_exception_support (&default_exception_support_info))
12590 {
12591 data->exception_info = &default_exception_support_info;
12592 return;
12593 }
12594
12595 /* Try the v0 exception suport info. */
12596 if (ada_has_this_exception_support (&exception_support_info_v0))
12597 {
12598 data->exception_info = &exception_support_info_v0;
12599 return;
12600 }
12601
12602 /* Try our fallback exception suport info. */
12603 if (ada_has_this_exception_support (&exception_support_info_fallback))
12604 {
12605 data->exception_info = &exception_support_info_fallback;
12606 return;
12607 }
12608
12609 /* Sometimes, it is normal for us to not be able to find the routine
12610 we are looking for. This happens when the program is linked with
12611 the shared version of the GNAT runtime, and the program has not been
12612 started yet. Inform the user of these two possible causes if
12613 applicable. */
12614
12615 if (ada_update_initial_language (language_unknown) != language_ada)
12616 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
12617
12618 /* If the symbol does not exist, then check that the program is
12619 already started, to make sure that shared libraries have been
12620 loaded. If it is not started, this may mean that the symbol is
12621 in a shared library. */
12622
12623 if (inferior_ptid.pid () == 0)
12624 error (_("Unable to insert catchpoint. Try to start the program first."));
12625
12626 /* At this point, we know that we are debugging an Ada program and
12627 that the inferior has been started, but we still are not able to
12628 find the run-time symbols. That can mean that we are in
12629 configurable run time mode, or that a-except as been optimized
12630 out by the linker... In any case, at this point it is not worth
12631 supporting this feature. */
12632
12633 error (_("Cannot insert Ada exception catchpoints in this configuration."));
12634 }
12635
12636 /* True iff FRAME is very likely to be that of a function that is
12637 part of the runtime system. This is all very heuristic, but is
12638 intended to be used as advice as to what frames are uninteresting
12639 to most users. */
12640
12641 static int
12642 is_known_support_routine (struct frame_info *frame)
12643 {
12644 enum language func_lang;
12645 int i;
12646 const char *fullname;
12647
12648 /* If this code does not have any debugging information (no symtab),
12649 This cannot be any user code. */
12650
12651 symtab_and_line sal = find_frame_sal (frame);
12652 if (sal.symtab == NULL)
12653 return 1;
12654
12655 /* If there is a symtab, but the associated source file cannot be
12656 located, then assume this is not user code: Selecting a frame
12657 for which we cannot display the code would not be very helpful
12658 for the user. This should also take care of case such as VxWorks
12659 where the kernel has some debugging info provided for a few units. */
12660
12661 fullname = symtab_to_fullname (sal.symtab);
12662 if (access (fullname, R_OK) != 0)
12663 return 1;
12664
12665 /* Check the unit filename against the Ada runtime file naming.
12666 We also check the name of the objfile against the name of some
12667 known system libraries that sometimes come with debugging info
12668 too. */
12669
12670 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
12671 {
12672 re_comp (known_runtime_file_name_patterns[i]);
12673 if (re_exec (lbasename (sal.symtab->filename)))
12674 return 1;
12675 if (SYMTAB_OBJFILE (sal.symtab) != NULL
12676 && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
12677 return 1;
12678 }
12679
12680 /* Check whether the function is a GNAT-generated entity. */
12681
12682 gdb::unique_xmalloc_ptr<char> func_name
12683 = find_frame_funname (frame, &func_lang, NULL);
12684 if (func_name == NULL)
12685 return 1;
12686
12687 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
12688 {
12689 re_comp (known_auxiliary_function_name_patterns[i]);
12690 if (re_exec (func_name.get ()))
12691 return 1;
12692 }
12693
12694 return 0;
12695 }
12696
12697 /* Find the first frame that contains debugging information and that is not
12698 part of the Ada run-time, starting from FI and moving upward. */
12699
12700 void
12701 ada_find_printable_frame (struct frame_info *fi)
12702 {
12703 for (; fi != NULL; fi = get_prev_frame (fi))
12704 {
12705 if (!is_known_support_routine (fi))
12706 {
12707 select_frame (fi);
12708 break;
12709 }
12710 }
12711
12712 }
12713
12714 /* Assuming that the inferior just triggered an unhandled exception
12715 catchpoint, return the address in inferior memory where the name
12716 of the exception is stored.
12717
12718 Return zero if the address could not be computed. */
12719
12720 static CORE_ADDR
12721 ada_unhandled_exception_name_addr (void)
12722 {
12723 return parse_and_eval_address ("e.full_name");
12724 }
12725
12726 /* Same as ada_unhandled_exception_name_addr, except that this function
12727 should be used when the inferior uses an older version of the runtime,
12728 where the exception name needs to be extracted from a specific frame
12729 several frames up in the callstack. */
12730
12731 static CORE_ADDR
12732 ada_unhandled_exception_name_addr_from_raise (void)
12733 {
12734 int frame_level;
12735 struct frame_info *fi;
12736 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12737
12738 /* To determine the name of this exception, we need to select
12739 the frame corresponding to RAISE_SYM_NAME. This frame is
12740 at least 3 levels up, so we simply skip the first 3 frames
12741 without checking the name of their associated function. */
12742 fi = get_current_frame ();
12743 for (frame_level = 0; frame_level < 3; frame_level += 1)
12744 if (fi != NULL)
12745 fi = get_prev_frame (fi);
12746
12747 while (fi != NULL)
12748 {
12749 enum language func_lang;
12750
12751 gdb::unique_xmalloc_ptr<char> func_name
12752 = find_frame_funname (fi, &func_lang, NULL);
12753 if (func_name != NULL)
12754 {
12755 if (strcmp (func_name.get (),
12756 data->exception_info->catch_exception_sym) == 0)
12757 break; /* We found the frame we were looking for... */
12758 }
12759 fi = get_prev_frame (fi);
12760 }
12761
12762 if (fi == NULL)
12763 return 0;
12764
12765 select_frame (fi);
12766 return parse_and_eval_address ("id.full_name");
12767 }
12768
12769 /* Assuming the inferior just triggered an Ada exception catchpoint
12770 (of any type), return the address in inferior memory where the name
12771 of the exception is stored, if applicable.
12772
12773 Assumes the selected frame is the current frame.
12774
12775 Return zero if the address could not be computed, or if not relevant. */
12776
12777 static CORE_ADDR
12778 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
12779 struct breakpoint *b)
12780 {
12781 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12782
12783 switch (ex)
12784 {
12785 case ada_catch_exception:
12786 return (parse_and_eval_address ("e.full_name"));
12787 break;
12788
12789 case ada_catch_exception_unhandled:
12790 return data->exception_info->unhandled_exception_name_addr ();
12791 break;
12792
12793 case ada_catch_handlers:
12794 return 0; /* The runtimes does not provide access to the exception
12795 name. */
12796 break;
12797
12798 case ada_catch_assert:
12799 return 0; /* Exception name is not relevant in this case. */
12800 break;
12801
12802 default:
12803 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12804 break;
12805 }
12806
12807 return 0; /* Should never be reached. */
12808 }
12809
12810 /* Assuming the inferior is stopped at an exception catchpoint,
12811 return the message which was associated to the exception, if
12812 available. Return NULL if the message could not be retrieved.
12813
12814 Note: The exception message can be associated to an exception
12815 either through the use of the Raise_Exception function, or
12816 more simply (Ada 2005 and later), via:
12817
12818 raise Exception_Name with "exception message";
12819
12820 */
12821
12822 static gdb::unique_xmalloc_ptr<char>
12823 ada_exception_message_1 (void)
12824 {
12825 struct value *e_msg_val;
12826 int e_msg_len;
12827
12828 /* For runtimes that support this feature, the exception message
12829 is passed as an unbounded string argument called "message". */
12830 e_msg_val = parse_and_eval ("message");
12831 if (e_msg_val == NULL)
12832 return NULL; /* Exception message not supported. */
12833
12834 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12835 gdb_assert (e_msg_val != NULL);
12836 e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
12837
12838 /* If the message string is empty, then treat it as if there was
12839 no exception message. */
12840 if (e_msg_len <= 0)
12841 return NULL;
12842
12843 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12844 read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
12845 e_msg_len);
12846 e_msg.get ()[e_msg_len] = '\0';
12847
12848 return e_msg;
12849 }
12850
12851 /* Same as ada_exception_message_1, except that all exceptions are
12852 contained here (returning NULL instead). */
12853
12854 static gdb::unique_xmalloc_ptr<char>
12855 ada_exception_message (void)
12856 {
12857 gdb::unique_xmalloc_ptr<char> e_msg;
12858
12859 try
12860 {
12861 e_msg = ada_exception_message_1 ();
12862 }
12863 catch (const gdb_exception_error &e)
12864 {
12865 e_msg.reset (nullptr);
12866 }
12867
12868 return e_msg;
12869 }
12870
12871 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12872 any error that ada_exception_name_addr_1 might cause to be thrown.
12873 When an error is intercepted, a warning with the error message is printed,
12874 and zero is returned. */
12875
12876 static CORE_ADDR
12877 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
12878 struct breakpoint *b)
12879 {
12880 CORE_ADDR result = 0;
12881
12882 try
12883 {
12884 result = ada_exception_name_addr_1 (ex, b);
12885 }
12886
12887 catch (const gdb_exception_error &e)
12888 {
12889 warning (_("failed to get exception name: %s"), e.what ());
12890 return 0;
12891 }
12892
12893 return result;
12894 }
12895
12896 static std::string ada_exception_catchpoint_cond_string
12897 (const char *excep_string,
12898 enum ada_exception_catchpoint_kind ex);
12899
12900 /* Ada catchpoints.
12901
12902 In the case of catchpoints on Ada exceptions, the catchpoint will
12903 stop the target on every exception the program throws. When a user
12904 specifies the name of a specific exception, we translate this
12905 request into a condition expression (in text form), and then parse
12906 it into an expression stored in each of the catchpoint's locations.
12907 We then use this condition to check whether the exception that was
12908 raised is the one the user is interested in. If not, then the
12909 target is resumed again. We store the name of the requested
12910 exception, in order to be able to re-set the condition expression
12911 when symbols change. */
12912
12913 /* An instance of this type is used to represent an Ada catchpoint
12914 breakpoint location. */
12915
12916 class ada_catchpoint_location : public bp_location
12917 {
12918 public:
12919 ada_catchpoint_location (breakpoint *owner)
12920 : bp_location (owner, bp_loc_software_breakpoint)
12921 {}
12922
12923 /* The condition that checks whether the exception that was raised
12924 is the specific exception the user specified on catchpoint
12925 creation. */
12926 expression_up excep_cond_expr;
12927 };
12928
12929 /* An instance of this type is used to represent an Ada catchpoint. */
12930
12931 struct ada_catchpoint : public breakpoint
12932 {
12933 explicit ada_catchpoint (enum ada_exception_catchpoint_kind kind)
12934 : m_kind (kind)
12935 {
12936 }
12937
12938 /* The name of the specific exception the user specified. */
12939 std::string excep_string;
12940
12941 /* What kind of catchpoint this is. */
12942 enum ada_exception_catchpoint_kind m_kind;
12943 };
12944
12945 /* Parse the exception condition string in the context of each of the
12946 catchpoint's locations, and store them for later evaluation. */
12947
12948 static void
12949 create_excep_cond_exprs (struct ada_catchpoint *c,
12950 enum ada_exception_catchpoint_kind ex)
12951 {
12952 struct bp_location *bl;
12953
12954 /* Nothing to do if there's no specific exception to catch. */
12955 if (c->excep_string.empty ())
12956 return;
12957
12958 /* Same if there are no locations... */
12959 if (c->loc == NULL)
12960 return;
12961
12962 /* Compute the condition expression in text form, from the specific
12963 expection we want to catch. */
12964 std::string cond_string
12965 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12966
12967 /* Iterate over all the catchpoint's locations, and parse an
12968 expression for each. */
12969 for (bl = c->loc; bl != NULL; bl = bl->next)
12970 {
12971 struct ada_catchpoint_location *ada_loc
12972 = (struct ada_catchpoint_location *) bl;
12973 expression_up exp;
12974
12975 if (!bl->shlib_disabled)
12976 {
12977 const char *s;
12978
12979 s = cond_string.c_str ();
12980 try
12981 {
12982 exp = parse_exp_1 (&s, bl->address,
12983 block_for_pc (bl->address),
12984 0);
12985 }
12986 catch (const gdb_exception_error &e)
12987 {
12988 warning (_("failed to reevaluate internal exception condition "
12989 "for catchpoint %d: %s"),
12990 c->number, e.what ());
12991 }
12992 }
12993
12994 ada_loc->excep_cond_expr = std::move (exp);
12995 }
12996 }
12997
12998 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
12999 structure for all exception catchpoint kinds. */
13000
13001 static struct bp_location *
13002 allocate_location_exception (struct breakpoint *self)
13003 {
13004 return new ada_catchpoint_location (self);
13005 }
13006
13007 /* Implement the RE_SET method in the breakpoint_ops structure for all
13008 exception catchpoint kinds. */
13009
13010 static void
13011 re_set_exception (struct breakpoint *b)
13012 {
13013 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13014
13015 /* Call the base class's method. This updates the catchpoint's
13016 locations. */
13017 bkpt_breakpoint_ops.re_set (b);
13018
13019 /* Reparse the exception conditional expressions. One for each
13020 location. */
13021 create_excep_cond_exprs (c, c->m_kind);
13022 }
13023
13024 /* Returns true if we should stop for this breakpoint hit. If the
13025 user specified a specific exception, we only want to cause a stop
13026 if the program thrown that exception. */
13027
13028 static int
13029 should_stop_exception (const struct bp_location *bl)
13030 {
13031 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
13032 const struct ada_catchpoint_location *ada_loc
13033 = (const struct ada_catchpoint_location *) bl;
13034 int stop;
13035
13036 struct internalvar *var = lookup_internalvar ("_ada_exception");
13037 if (c->m_kind == ada_catch_assert)
13038 clear_internalvar (var);
13039 else
13040 {
13041 try
13042 {
13043 const char *expr;
13044
13045 if (c->m_kind == ada_catch_handlers)
13046 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
13047 ".all.occurrence.id");
13048 else
13049 expr = "e";
13050
13051 struct value *exc = parse_and_eval (expr);
13052 set_internalvar (var, exc);
13053 }
13054 catch (const gdb_exception_error &ex)
13055 {
13056 clear_internalvar (var);
13057 }
13058 }
13059
13060 /* With no specific exception, should always stop. */
13061 if (c->excep_string.empty ())
13062 return 1;
13063
13064 if (ada_loc->excep_cond_expr == NULL)
13065 {
13066 /* We will have a NULL expression if back when we were creating
13067 the expressions, this location's had failed to parse. */
13068 return 1;
13069 }
13070
13071 stop = 1;
13072 try
13073 {
13074 struct value *mark;
13075
13076 mark = value_mark ();
13077 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
13078 value_free_to_mark (mark);
13079 }
13080 catch (const gdb_exception &ex)
13081 {
13082 exception_fprintf (gdb_stderr, ex,
13083 _("Error in testing exception condition:\n"));
13084 }
13085
13086 return stop;
13087 }
13088
13089 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
13090 for all exception catchpoint kinds. */
13091
13092 static void
13093 check_status_exception (bpstat bs)
13094 {
13095 bs->stop = should_stop_exception (bs->bp_location_at.get ());
13096 }
13097
13098 /* Implement the PRINT_IT method in the breakpoint_ops structure
13099 for all exception catchpoint kinds. */
13100
13101 static enum print_stop_action
13102 print_it_exception (bpstat bs)
13103 {
13104 struct ui_out *uiout = current_uiout;
13105 struct breakpoint *b = bs->breakpoint_at;
13106
13107 annotate_catchpoint (b->number);
13108
13109 if (uiout->is_mi_like_p ())
13110 {
13111 uiout->field_string ("reason",
13112 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13113 uiout->field_string ("disp", bpdisp_text (b->disposition));
13114 }
13115
13116 uiout->text (b->disposition == disp_del
13117 ? "\nTemporary catchpoint " : "\nCatchpoint ");
13118 uiout->field_signed ("bkptno", b->number);
13119 uiout->text (", ");
13120
13121 /* ada_exception_name_addr relies on the selected frame being the
13122 current frame. Need to do this here because this function may be
13123 called more than once when printing a stop, and below, we'll
13124 select the first frame past the Ada run-time (see
13125 ada_find_printable_frame). */
13126 select_frame (get_current_frame ());
13127
13128 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13129 switch (c->m_kind)
13130 {
13131 case ada_catch_exception:
13132 case ada_catch_exception_unhandled:
13133 case ada_catch_handlers:
13134 {
13135 const CORE_ADDR addr = ada_exception_name_addr (c->m_kind, b);
13136 char exception_name[256];
13137
13138 if (addr != 0)
13139 {
13140 read_memory (addr, (gdb_byte *) exception_name,
13141 sizeof (exception_name) - 1);
13142 exception_name [sizeof (exception_name) - 1] = '\0';
13143 }
13144 else
13145 {
13146 /* For some reason, we were unable to read the exception
13147 name. This could happen if the Runtime was compiled
13148 without debugging info, for instance. In that case,
13149 just replace the exception name by the generic string
13150 "exception" - it will read as "an exception" in the
13151 notification we are about to print. */
13152 memcpy (exception_name, "exception", sizeof ("exception"));
13153 }
13154 /* In the case of unhandled exception breakpoints, we print
13155 the exception name as "unhandled EXCEPTION_NAME", to make
13156 it clearer to the user which kind of catchpoint just got
13157 hit. We used ui_out_text to make sure that this extra
13158 info does not pollute the exception name in the MI case. */
13159 if (c->m_kind == ada_catch_exception_unhandled)
13160 uiout->text ("unhandled ");
13161 uiout->field_string ("exception-name", exception_name);
13162 }
13163 break;
13164 case ada_catch_assert:
13165 /* In this case, the name of the exception is not really
13166 important. Just print "failed assertion" to make it clearer
13167 that his program just hit an assertion-failure catchpoint.
13168 We used ui_out_text because this info does not belong in
13169 the MI output. */
13170 uiout->text ("failed assertion");
13171 break;
13172 }
13173
13174 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
13175 if (exception_message != NULL)
13176 {
13177 uiout->text (" (");
13178 uiout->field_string ("exception-message", exception_message.get ());
13179 uiout->text (")");
13180 }
13181
13182 uiout->text (" at ");
13183 ada_find_printable_frame (get_current_frame ());
13184
13185 return PRINT_SRC_AND_LOC;
13186 }
13187
13188 /* Implement the PRINT_ONE method in the breakpoint_ops structure
13189 for all exception catchpoint kinds. */
13190
13191 static void
13192 print_one_exception (struct breakpoint *b, struct bp_location **last_loc)
13193 {
13194 struct ui_out *uiout = current_uiout;
13195 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13196 struct value_print_options opts;
13197
13198 get_user_print_options (&opts);
13199
13200 if (opts.addressprint)
13201 uiout->field_skip ("addr");
13202
13203 annotate_field (5);
13204 switch (c->m_kind)
13205 {
13206 case ada_catch_exception:
13207 if (!c->excep_string.empty ())
13208 {
13209 std::string msg = string_printf (_("`%s' Ada exception"),
13210 c->excep_string.c_str ());
13211
13212 uiout->field_string ("what", msg);
13213 }
13214 else
13215 uiout->field_string ("what", "all Ada exceptions");
13216
13217 break;
13218
13219 case ada_catch_exception_unhandled:
13220 uiout->field_string ("what", "unhandled Ada exceptions");
13221 break;
13222
13223 case ada_catch_handlers:
13224 if (!c->excep_string.empty ())
13225 {
13226 uiout->field_fmt ("what",
13227 _("`%s' Ada exception handlers"),
13228 c->excep_string.c_str ());
13229 }
13230 else
13231 uiout->field_string ("what", "all Ada exceptions handlers");
13232 break;
13233
13234 case ada_catch_assert:
13235 uiout->field_string ("what", "failed Ada assertions");
13236 break;
13237
13238 default:
13239 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
13240 break;
13241 }
13242 }
13243
13244 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
13245 for all exception catchpoint kinds. */
13246
13247 static void
13248 print_mention_exception (struct breakpoint *b)
13249 {
13250 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13251 struct ui_out *uiout = current_uiout;
13252
13253 uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
13254 : _("Catchpoint "));
13255 uiout->field_signed ("bkptno", b->number);
13256 uiout->text (": ");
13257
13258 switch (c->m_kind)
13259 {
13260 case ada_catch_exception:
13261 if (!c->excep_string.empty ())
13262 {
13263 std::string info = string_printf (_("`%s' Ada exception"),
13264 c->excep_string.c_str ());
13265 uiout->text (info.c_str ());
13266 }
13267 else
13268 uiout->text (_("all Ada exceptions"));
13269 break;
13270
13271 case ada_catch_exception_unhandled:
13272 uiout->text (_("unhandled Ada exceptions"));
13273 break;
13274
13275 case ada_catch_handlers:
13276 if (!c->excep_string.empty ())
13277 {
13278 std::string info
13279 = string_printf (_("`%s' Ada exception handlers"),
13280 c->excep_string.c_str ());
13281 uiout->text (info.c_str ());
13282 }
13283 else
13284 uiout->text (_("all Ada exceptions handlers"));
13285 break;
13286
13287 case ada_catch_assert:
13288 uiout->text (_("failed Ada assertions"));
13289 break;
13290
13291 default:
13292 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
13293 break;
13294 }
13295 }
13296
13297 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
13298 for all exception catchpoint kinds. */
13299
13300 static void
13301 print_recreate_exception (struct breakpoint *b, struct ui_file *fp)
13302 {
13303 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13304
13305 switch (c->m_kind)
13306 {
13307 case ada_catch_exception:
13308 fprintf_filtered (fp, "catch exception");
13309 if (!c->excep_string.empty ())
13310 fprintf_filtered (fp, " %s", c->excep_string.c_str ());
13311 break;
13312
13313 case ada_catch_exception_unhandled:
13314 fprintf_filtered (fp, "catch exception unhandled");
13315 break;
13316
13317 case ada_catch_handlers:
13318 fprintf_filtered (fp, "catch handlers");
13319 break;
13320
13321 case ada_catch_assert:
13322 fprintf_filtered (fp, "catch assert");
13323 break;
13324
13325 default:
13326 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
13327 }
13328 print_recreate_thread (b, fp);
13329 }
13330
13331 /* Virtual tables for various breakpoint types. */
13332 static struct breakpoint_ops catch_exception_breakpoint_ops;
13333 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
13334 static struct breakpoint_ops catch_assert_breakpoint_ops;
13335 static struct breakpoint_ops catch_handlers_breakpoint_ops;
13336
13337 /* See ada-lang.h. */
13338
13339 bool
13340 is_ada_exception_catchpoint (breakpoint *bp)
13341 {
13342 return (bp->ops == &catch_exception_breakpoint_ops
13343 || bp->ops == &catch_exception_unhandled_breakpoint_ops
13344 || bp->ops == &catch_assert_breakpoint_ops
13345 || bp->ops == &catch_handlers_breakpoint_ops);
13346 }
13347
13348 /* Split the arguments specified in a "catch exception" command.
13349 Set EX to the appropriate catchpoint type.
13350 Set EXCEP_STRING to the name of the specific exception if
13351 specified by the user.
13352 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
13353 "catch handlers" command. False otherwise.
13354 If a condition is found at the end of the arguments, the condition
13355 expression is stored in COND_STRING (memory must be deallocated
13356 after use). Otherwise COND_STRING is set to NULL. */
13357
13358 static void
13359 catch_ada_exception_command_split (const char *args,
13360 bool is_catch_handlers_cmd,
13361 enum ada_exception_catchpoint_kind *ex,
13362 std::string *excep_string,
13363 std::string *cond_string)
13364 {
13365 std::string exception_name;
13366
13367 exception_name = extract_arg (&args);
13368 if (exception_name == "if")
13369 {
13370 /* This is not an exception name; this is the start of a condition
13371 expression for a catchpoint on all exceptions. So, "un-get"
13372 this token, and set exception_name to NULL. */
13373 exception_name.clear ();
13374 args -= 2;
13375 }
13376
13377 /* Check to see if we have a condition. */
13378
13379 args = skip_spaces (args);
13380 if (startswith (args, "if")
13381 && (isspace (args[2]) || args[2] == '\0'))
13382 {
13383 args += 2;
13384 args = skip_spaces (args);
13385
13386 if (args[0] == '\0')
13387 error (_("Condition missing after `if' keyword"));
13388 *cond_string = args;
13389
13390 args += strlen (args);
13391 }
13392
13393 /* Check that we do not have any more arguments. Anything else
13394 is unexpected. */
13395
13396 if (args[0] != '\0')
13397 error (_("Junk at end of expression"));
13398
13399 if (is_catch_handlers_cmd)
13400 {
13401 /* Catch handling of exceptions. */
13402 *ex = ada_catch_handlers;
13403 *excep_string = exception_name;
13404 }
13405 else if (exception_name.empty ())
13406 {
13407 /* Catch all exceptions. */
13408 *ex = ada_catch_exception;
13409 excep_string->clear ();
13410 }
13411 else if (exception_name == "unhandled")
13412 {
13413 /* Catch unhandled exceptions. */
13414 *ex = ada_catch_exception_unhandled;
13415 excep_string->clear ();
13416 }
13417 else
13418 {
13419 /* Catch a specific exception. */
13420 *ex = ada_catch_exception;
13421 *excep_string = exception_name;
13422 }
13423 }
13424
13425 /* Return the name of the symbol on which we should break in order to
13426 implement a catchpoint of the EX kind. */
13427
13428 static const char *
13429 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
13430 {
13431 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
13432
13433 gdb_assert (data->exception_info != NULL);
13434
13435 switch (ex)
13436 {
13437 case ada_catch_exception:
13438 return (data->exception_info->catch_exception_sym);
13439 break;
13440 case ada_catch_exception_unhandled:
13441 return (data->exception_info->catch_exception_unhandled_sym);
13442 break;
13443 case ada_catch_assert:
13444 return (data->exception_info->catch_assert_sym);
13445 break;
13446 case ada_catch_handlers:
13447 return (data->exception_info->catch_handlers_sym);
13448 break;
13449 default:
13450 internal_error (__FILE__, __LINE__,
13451 _("unexpected catchpoint kind (%d)"), ex);
13452 }
13453 }
13454
13455 /* Return the breakpoint ops "virtual table" used for catchpoints
13456 of the EX kind. */
13457
13458 static const struct breakpoint_ops *
13459 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
13460 {
13461 switch (ex)
13462 {
13463 case ada_catch_exception:
13464 return (&catch_exception_breakpoint_ops);
13465 break;
13466 case ada_catch_exception_unhandled:
13467 return (&catch_exception_unhandled_breakpoint_ops);
13468 break;
13469 case ada_catch_assert:
13470 return (&catch_assert_breakpoint_ops);
13471 break;
13472 case ada_catch_handlers:
13473 return (&catch_handlers_breakpoint_ops);
13474 break;
13475 default:
13476 internal_error (__FILE__, __LINE__,
13477 _("unexpected catchpoint kind (%d)"), ex);
13478 }
13479 }
13480
13481 /* Return the condition that will be used to match the current exception
13482 being raised with the exception that the user wants to catch. This
13483 assumes that this condition is used when the inferior just triggered
13484 an exception catchpoint.
13485 EX: the type of catchpoints used for catching Ada exceptions. */
13486
13487 static std::string
13488 ada_exception_catchpoint_cond_string (const char *excep_string,
13489 enum ada_exception_catchpoint_kind ex)
13490 {
13491 int i;
13492 bool is_standard_exc = false;
13493 std::string result;
13494
13495 if (ex == ada_catch_handlers)
13496 {
13497 /* For exception handlers catchpoints, the condition string does
13498 not use the same parameter as for the other exceptions. */
13499 result = ("long_integer (GNAT_GCC_exception_Access"
13500 "(gcc_exception).all.occurrence.id)");
13501 }
13502 else
13503 result = "long_integer (e)";
13504
13505 /* The standard exceptions are a special case. They are defined in
13506 runtime units that have been compiled without debugging info; if
13507 EXCEP_STRING is the not-fully-qualified name of a standard
13508 exception (e.g. "constraint_error") then, during the evaluation
13509 of the condition expression, the symbol lookup on this name would
13510 *not* return this standard exception. The catchpoint condition
13511 may then be set only on user-defined exceptions which have the
13512 same not-fully-qualified name (e.g. my_package.constraint_error).
13513
13514 To avoid this unexcepted behavior, these standard exceptions are
13515 systematically prefixed by "standard". This means that "catch
13516 exception constraint_error" is rewritten into "catch exception
13517 standard.constraint_error".
13518
13519 If an exception named constraint_error is defined in another package of
13520 the inferior program, then the only way to specify this exception as a
13521 breakpoint condition is to use its fully-qualified named:
13522 e.g. my_package.constraint_error. */
13523
13524 for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
13525 {
13526 if (strcmp (standard_exc [i], excep_string) == 0)
13527 {
13528 is_standard_exc = true;
13529 break;
13530 }
13531 }
13532
13533 result += " = ";
13534
13535 if (is_standard_exc)
13536 string_appendf (result, "long_integer (&standard.%s)", excep_string);
13537 else
13538 string_appendf (result, "long_integer (&%s)", excep_string);
13539
13540 return result;
13541 }
13542
13543 /* Return the symtab_and_line that should be used to insert an exception
13544 catchpoint of the TYPE kind.
13545
13546 ADDR_STRING returns the name of the function where the real
13547 breakpoint that implements the catchpoints is set, depending on the
13548 type of catchpoint we need to create. */
13549
13550 static struct symtab_and_line
13551 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
13552 std::string *addr_string, const struct breakpoint_ops **ops)
13553 {
13554 const char *sym_name;
13555 struct symbol *sym;
13556
13557 /* First, find out which exception support info to use. */
13558 ada_exception_support_info_sniffer ();
13559
13560 /* Then lookup the function on which we will break in order to catch
13561 the Ada exceptions requested by the user. */
13562 sym_name = ada_exception_sym_name (ex);
13563 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
13564
13565 if (sym == NULL)
13566 error (_("Catchpoint symbol not found: %s"), sym_name);
13567
13568 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
13569 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
13570
13571 /* Set ADDR_STRING. */
13572 *addr_string = sym_name;
13573
13574 /* Set OPS. */
13575 *ops = ada_exception_breakpoint_ops (ex);
13576
13577 return find_function_start_sal (sym, 1);
13578 }
13579
13580 /* Create an Ada exception catchpoint.
13581
13582 EX_KIND is the kind of exception catchpoint to be created.
13583
13584 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
13585 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
13586 of the exception to which this catchpoint applies.
13587
13588 COND_STRING, if not empty, is the catchpoint condition.
13589
13590 TEMPFLAG, if nonzero, means that the underlying breakpoint
13591 should be temporary.
13592
13593 FROM_TTY is the usual argument passed to all commands implementations. */
13594
13595 void
13596 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
13597 enum ada_exception_catchpoint_kind ex_kind,
13598 const std::string &excep_string,
13599 const std::string &cond_string,
13600 int tempflag,
13601 int disabled,
13602 int from_tty)
13603 {
13604 std::string addr_string;
13605 const struct breakpoint_ops *ops = NULL;
13606 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
13607
13608 std::unique_ptr<ada_catchpoint> c (new ada_catchpoint (ex_kind));
13609 init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
13610 ops, tempflag, disabled, from_tty);
13611 c->excep_string = excep_string;
13612 create_excep_cond_exprs (c.get (), ex_kind);
13613 if (!cond_string.empty ())
13614 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
13615 install_breakpoint (0, std::move (c), 1);
13616 }
13617
13618 /* Implement the "catch exception" command. */
13619
13620 static void
13621 catch_ada_exception_command (const char *arg_entry, int from_tty,
13622 struct cmd_list_element *command)
13623 {
13624 const char *arg = arg_entry;
13625 struct gdbarch *gdbarch = get_current_arch ();
13626 int tempflag;
13627 enum ada_exception_catchpoint_kind ex_kind;
13628 std::string excep_string;
13629 std::string cond_string;
13630
13631 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13632
13633 if (!arg)
13634 arg = "";
13635 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
13636 &cond_string);
13637 create_ada_exception_catchpoint (gdbarch, ex_kind,
13638 excep_string, cond_string,
13639 tempflag, 1 /* enabled */,
13640 from_tty);
13641 }
13642
13643 /* Implement the "catch handlers" command. */
13644
13645 static void
13646 catch_ada_handlers_command (const char *arg_entry, int from_tty,
13647 struct cmd_list_element *command)
13648 {
13649 const char *arg = arg_entry;
13650 struct gdbarch *gdbarch = get_current_arch ();
13651 int tempflag;
13652 enum ada_exception_catchpoint_kind ex_kind;
13653 std::string excep_string;
13654 std::string cond_string;
13655
13656 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13657
13658 if (!arg)
13659 arg = "";
13660 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
13661 &cond_string);
13662 create_ada_exception_catchpoint (gdbarch, ex_kind,
13663 excep_string, cond_string,
13664 tempflag, 1 /* enabled */,
13665 from_tty);
13666 }
13667
13668 /* Completion function for the Ada "catch" commands. */
13669
13670 static void
13671 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
13672 const char *text, const char *word)
13673 {
13674 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
13675
13676 for (const ada_exc_info &info : exceptions)
13677 {
13678 if (startswith (info.name, word))
13679 tracker.add_completion (make_unique_xstrdup (info.name));
13680 }
13681 }
13682
13683 /* Split the arguments specified in a "catch assert" command.
13684
13685 ARGS contains the command's arguments (or the empty string if
13686 no arguments were passed).
13687
13688 If ARGS contains a condition, set COND_STRING to that condition
13689 (the memory needs to be deallocated after use). */
13690
13691 static void
13692 catch_ada_assert_command_split (const char *args, std::string &cond_string)
13693 {
13694 args = skip_spaces (args);
13695
13696 /* Check whether a condition was provided. */
13697 if (startswith (args, "if")
13698 && (isspace (args[2]) || args[2] == '\0'))
13699 {
13700 args += 2;
13701 args = skip_spaces (args);
13702 if (args[0] == '\0')
13703 error (_("condition missing after `if' keyword"));
13704 cond_string.assign (args);
13705 }
13706
13707 /* Otherwise, there should be no other argument at the end of
13708 the command. */
13709 else if (args[0] != '\0')
13710 error (_("Junk at end of arguments."));
13711 }
13712
13713 /* Implement the "catch assert" command. */
13714
13715 static void
13716 catch_assert_command (const char *arg_entry, int from_tty,
13717 struct cmd_list_element *command)
13718 {
13719 const char *arg = arg_entry;
13720 struct gdbarch *gdbarch = get_current_arch ();
13721 int tempflag;
13722 std::string cond_string;
13723
13724 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13725
13726 if (!arg)
13727 arg = "";
13728 catch_ada_assert_command_split (arg, cond_string);
13729 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
13730 "", cond_string,
13731 tempflag, 1 /* enabled */,
13732 from_tty);
13733 }
13734
13735 /* Return non-zero if the symbol SYM is an Ada exception object. */
13736
13737 static int
13738 ada_is_exception_sym (struct symbol *sym)
13739 {
13740 const char *type_name = SYMBOL_TYPE (sym)->name ();
13741
13742 return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
13743 && SYMBOL_CLASS (sym) != LOC_BLOCK
13744 && SYMBOL_CLASS (sym) != LOC_CONST
13745 && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
13746 && type_name != NULL && strcmp (type_name, "exception") == 0);
13747 }
13748
13749 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
13750 Ada exception object. This matches all exceptions except the ones
13751 defined by the Ada language. */
13752
13753 static int
13754 ada_is_non_standard_exception_sym (struct symbol *sym)
13755 {
13756 int i;
13757
13758 if (!ada_is_exception_sym (sym))
13759 return 0;
13760
13761 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13762 if (strcmp (sym->linkage_name (), standard_exc[i]) == 0)
13763 return 0; /* A standard exception. */
13764
13765 /* Numeric_Error is also a standard exception, so exclude it.
13766 See the STANDARD_EXC description for more details as to why
13767 this exception is not listed in that array. */
13768 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
13769 return 0;
13770
13771 return 1;
13772 }
13773
13774 /* A helper function for std::sort, comparing two struct ada_exc_info
13775 objects.
13776
13777 The comparison is determined first by exception name, and then
13778 by exception address. */
13779
13780 bool
13781 ada_exc_info::operator< (const ada_exc_info &other) const
13782 {
13783 int result;
13784
13785 result = strcmp (name, other.name);
13786 if (result < 0)
13787 return true;
13788 if (result == 0 && addr < other.addr)
13789 return true;
13790 return false;
13791 }
13792
13793 bool
13794 ada_exc_info::operator== (const ada_exc_info &other) const
13795 {
13796 return addr == other.addr && strcmp (name, other.name) == 0;
13797 }
13798
13799 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13800 routine, but keeping the first SKIP elements untouched.
13801
13802 All duplicates are also removed. */
13803
13804 static void
13805 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13806 int skip)
13807 {
13808 std::sort (exceptions->begin () + skip, exceptions->end ());
13809 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13810 exceptions->end ());
13811 }
13812
13813 /* Add all exceptions defined by the Ada standard whose name match
13814 a regular expression.
13815
13816 If PREG is not NULL, then this regexp_t object is used to
13817 perform the symbol name matching. Otherwise, no name-based
13818 filtering is performed.
13819
13820 EXCEPTIONS is a vector of exceptions to which matching exceptions
13821 gets pushed. */
13822
13823 static void
13824 ada_add_standard_exceptions (compiled_regex *preg,
13825 std::vector<ada_exc_info> *exceptions)
13826 {
13827 int i;
13828
13829 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13830 {
13831 if (preg == NULL
13832 || preg->exec (standard_exc[i], 0, NULL, 0) == 0)
13833 {
13834 struct bound_minimal_symbol msymbol
13835 = ada_lookup_simple_minsym (standard_exc[i]);
13836
13837 if (msymbol.minsym != NULL)
13838 {
13839 struct ada_exc_info info
13840 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};
13841
13842 exceptions->push_back (info);
13843 }
13844 }
13845 }
13846 }
13847
13848 /* Add all Ada exceptions defined locally and accessible from the given
13849 FRAME.
13850
13851 If PREG is not NULL, then this regexp_t object is used to
13852 perform the symbol name matching. Otherwise, no name-based
13853 filtering is performed.
13854
13855 EXCEPTIONS is a vector of exceptions to which matching exceptions
13856 gets pushed. */
13857
13858 static void
13859 ada_add_exceptions_from_frame (compiled_regex *preg,
13860 struct frame_info *frame,
13861 std::vector<ada_exc_info> *exceptions)
13862 {
13863 const struct block *block = get_frame_block (frame, 0);
13864
13865 while (block != 0)
13866 {
13867 struct block_iterator iter;
13868 struct symbol *sym;
13869
13870 ALL_BLOCK_SYMBOLS (block, iter, sym)
13871 {
13872 switch (SYMBOL_CLASS (sym))
13873 {
13874 case LOC_TYPEDEF:
13875 case LOC_BLOCK:
13876 case LOC_CONST:
13877 break;
13878 default:
13879 if (ada_is_exception_sym (sym))
13880 {
13881 struct ada_exc_info info = {sym->print_name (),
13882 SYMBOL_VALUE_ADDRESS (sym)};
13883
13884 exceptions->push_back (info);
13885 }
13886 }
13887 }
13888 if (BLOCK_FUNCTION (block) != NULL)
13889 break;
13890 block = BLOCK_SUPERBLOCK (block);
13891 }
13892 }
13893
13894 /* Return true if NAME matches PREG or if PREG is NULL. */
13895
13896 static bool
13897 name_matches_regex (const char *name, compiled_regex *preg)
13898 {
13899 return (preg == NULL
13900 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13901 }
13902
13903 /* Add all exceptions defined globally whose name name match
13904 a regular expression, excluding standard exceptions.
13905
13906 The reason we exclude standard exceptions is that they need
13907 to be handled separately: Standard exceptions are defined inside
13908 a runtime unit which is normally not compiled with debugging info,
13909 and thus usually do not show up in our symbol search. However,
13910 if the unit was in fact built with debugging info, we need to
13911 exclude them because they would duplicate the entry we found
13912 during the special loop that specifically searches for those
13913 standard exceptions.
13914
13915 If PREG is not NULL, then this regexp_t object is used to
13916 perform the symbol name matching. Otherwise, no name-based
13917 filtering is performed.
13918
13919 EXCEPTIONS is a vector of exceptions to which matching exceptions
13920 gets pushed. */
13921
13922 static void
13923 ada_add_global_exceptions (compiled_regex *preg,
13924 std::vector<ada_exc_info> *exceptions)
13925 {
13926 /* In Ada, the symbol "search name" is a linkage name, whereas the
13927 regular expression used to do the matching refers to the natural
13928 name. So match against the decoded name. */
13929 expand_symtabs_matching (NULL,
13930 lookup_name_info::match_any (),
13931 [&] (const char *search_name)
13932 {
13933 std::string decoded = ada_decode (search_name);
13934 return name_matches_regex (decoded.c_str (), preg);
13935 },
13936 NULL,
13937 VARIABLES_DOMAIN);
13938
13939 for (objfile *objfile : current_program_space->objfiles ())
13940 {
13941 for (compunit_symtab *s : objfile->compunits ())
13942 {
13943 const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
13944 int i;
13945
13946 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13947 {
13948 const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
13949 struct block_iterator iter;
13950 struct symbol *sym;
13951
13952 ALL_BLOCK_SYMBOLS (b, iter, sym)
13953 if (ada_is_non_standard_exception_sym (sym)
13954 && name_matches_regex (sym->natural_name (), preg))
13955 {
13956 struct ada_exc_info info
13957 = {sym->print_name (), SYMBOL_VALUE_ADDRESS (sym)};
13958
13959 exceptions->push_back (info);
13960 }
13961 }
13962 }
13963 }
13964 }
13965
13966 /* Implements ada_exceptions_list with the regular expression passed
13967 as a regex_t, rather than a string.
13968
13969 If not NULL, PREG is used to filter out exceptions whose names
13970 do not match. Otherwise, all exceptions are listed. */
13971
13972 static std::vector<ada_exc_info>
13973 ada_exceptions_list_1 (compiled_regex *preg)
13974 {
13975 std::vector<ada_exc_info> result;
13976 int prev_len;
13977
13978 /* First, list the known standard exceptions. These exceptions
13979 need to be handled separately, as they are usually defined in
13980 runtime units that have been compiled without debugging info. */
13981
13982 ada_add_standard_exceptions (preg, &result);
13983
13984 /* Next, find all exceptions whose scope is local and accessible
13985 from the currently selected frame. */
13986
13987 if (has_stack_frames ())
13988 {
13989 prev_len = result.size ();
13990 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13991 &result);
13992 if (result.size () > prev_len)
13993 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13994 }
13995
13996 /* Add all exceptions whose scope is global. */
13997
13998 prev_len = result.size ();
13999 ada_add_global_exceptions (preg, &result);
14000 if (result.size () > prev_len)
14001 sort_remove_dups_ada_exceptions_list (&result, prev_len);
14002
14003 return result;
14004 }
14005
14006 /* Return a vector of ada_exc_info.
14007
14008 If REGEXP is NULL, all exceptions are included in the result.
14009 Otherwise, it should contain a valid regular expression,
14010 and only the exceptions whose names match that regular expression
14011 are included in the result.
14012
14013 The exceptions are sorted in the following order:
14014 - Standard exceptions (defined by the Ada language), in
14015 alphabetical order;
14016 - Exceptions only visible from the current frame, in
14017 alphabetical order;
14018 - Exceptions whose scope is global, in alphabetical order. */
14019
14020 std::vector<ada_exc_info>
14021 ada_exceptions_list (const char *regexp)
14022 {
14023 if (regexp == NULL)
14024 return ada_exceptions_list_1 (NULL);
14025
14026 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
14027 return ada_exceptions_list_1 (&reg);
14028 }
14029
14030 /* Implement the "info exceptions" command. */
14031
14032 static void
14033 info_exceptions_command (const char *regexp, int from_tty)
14034 {
14035 struct gdbarch *gdbarch = get_current_arch ();
14036
14037 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
14038
14039 if (regexp != NULL)
14040 printf_filtered
14041 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
14042 else
14043 printf_filtered (_("All defined Ada exceptions:\n"));
14044
14045 for (const ada_exc_info &info : exceptions)
14046 printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
14047 }
14048
14049 /* Operators */
14050 /* Information about operators given special treatment in functions
14051 below. */
14052 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>). */
14053
14054 #define ADA_OPERATORS \
14055 OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
14056 OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
14057 OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
14058 OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
14059 OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
14060 OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
14061 OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
14062 OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
14063 OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
14064 OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
14065 OP_DEFN (OP_ATR_POS, 1, 2, 0) \
14066 OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
14067 OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
14068 OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
14069 OP_DEFN (UNOP_QUAL, 3, 1, 0) \
14070 OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
14071 OP_DEFN (OP_OTHERS, 1, 1, 0) \
14072 OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
14073 OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
14074
14075 static void
14076 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
14077 int *argsp)
14078 {
14079 switch (exp->elts[pc - 1].opcode)
14080 {
14081 default:
14082 operator_length_standard (exp, pc, oplenp, argsp);
14083 break;
14084
14085 #define OP_DEFN(op, len, args, binop) \
14086 case op: *oplenp = len; *argsp = args; break;
14087 ADA_OPERATORS;
14088 #undef OP_DEFN
14089
14090 case OP_AGGREGATE:
14091 *oplenp = 3;
14092 *argsp = longest_to_int (exp->elts[pc - 2].longconst);
14093 break;
14094
14095 case OP_CHOICES:
14096 *oplenp = 3;
14097 *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
14098 break;
14099 }
14100 }
14101
14102 /* Implementation of the exp_descriptor method operator_check. */
14103
14104 static int
14105 ada_operator_check (struct expression *exp, int pos,
14106 int (*objfile_func) (struct objfile *objfile, void *data),
14107 void *data)
14108 {
14109 const union exp_element *const elts = exp->elts;
14110 struct type *type = NULL;
14111
14112 switch (elts[pos].opcode)
14113 {
14114 case UNOP_IN_RANGE:
14115 case UNOP_QUAL:
14116 type = elts[pos + 1].type;
14117 break;
14118
14119 default:
14120 return operator_check_standard (exp, pos, objfile_func, data);
14121 }
14122
14123 /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL. */
14124
14125 if (type != nullptr && type->objfile_owner () != nullptr
14126 && objfile_func (type->objfile_owner (), data))
14127 return 1;
14128
14129 return 0;
14130 }
14131
14132 /* As for operator_length, but assumes PC is pointing at the first
14133 element of the operator, and gives meaningful results only for the
14134 Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise. */
14135
14136 static void
14137 ada_forward_operator_length (struct expression *exp, int pc,
14138 int *oplenp, int *argsp)
14139 {
14140 switch (exp->elts[pc].opcode)
14141 {
14142 default:
14143 *oplenp = *argsp = 0;
14144 break;
14145
14146 #define OP_DEFN(op, len, args, binop) \
14147 case op: *oplenp = len; *argsp = args; break;
14148 ADA_OPERATORS;
14149 #undef OP_DEFN
14150
14151 case OP_AGGREGATE:
14152 *oplenp = 3;
14153 *argsp = longest_to_int (exp->elts[pc + 1].longconst);
14154 break;
14155
14156 case OP_CHOICES:
14157 *oplenp = 3;
14158 *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
14159 break;
14160
14161 case OP_STRING:
14162 case OP_NAME:
14163 {
14164 int len = longest_to_int (exp->elts[pc + 1].longconst);
14165
14166 *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
14167 *argsp = 0;
14168 break;
14169 }
14170 }
14171 }
14172
14173 static int
14174 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
14175 {
14176 enum exp_opcode op = exp->elts[elt].opcode;
14177 int oplen, nargs;
14178 int pc = elt;
14179 int i;
14180
14181 ada_forward_operator_length (exp, elt, &oplen, &nargs);
14182
14183 switch (op)
14184 {
14185 /* Ada attributes ('Foo). */
14186 case OP_ATR_FIRST:
14187 case OP_ATR_LAST:
14188 case OP_ATR_LENGTH:
14189 case OP_ATR_IMAGE:
14190 case OP_ATR_MAX:
14191 case OP_ATR_MIN:
14192 case OP_ATR_MODULUS:
14193 case OP_ATR_POS:
14194 case OP_ATR_SIZE:
14195 case OP_ATR_TAG:
14196 case OP_ATR_VAL:
14197 break;
14198
14199 case UNOP_IN_RANGE:
14200 case UNOP_QUAL:
14201 /* XXX: gdb_sprint_host_address, type_sprint */
14202 fprintf_filtered (stream, _("Type @"));
14203 gdb_print_host_address (exp->elts[pc + 1].type, stream);
14204 fprintf_filtered (stream, " (");
14205 type_print (exp->elts[pc + 1].type, NULL, stream, 0);
14206 fprintf_filtered (stream, ")");
14207 break;
14208 case BINOP_IN_BOUNDS:
14209 fprintf_filtered (stream, " (%d)",
14210 longest_to_int (exp->elts[pc + 2].longconst));
14211 break;
14212 case TERNOP_IN_RANGE:
14213 break;
14214
14215 case OP_AGGREGATE:
14216 case OP_OTHERS:
14217 case OP_DISCRETE_RANGE:
14218 case OP_POSITIONAL:
14219 case OP_CHOICES:
14220 break;
14221
14222 case OP_NAME:
14223 case OP_STRING:
14224 {
14225 char *name = &exp->elts[elt + 2].string;
14226 int len = longest_to_int (exp->elts[elt + 1].longconst);
14227
14228 fprintf_filtered (stream, "Text: `%.*s'", len, name);
14229 break;
14230 }
14231
14232 default:
14233 return dump_subexp_body_standard (exp, stream, elt);
14234 }
14235
14236 elt += oplen;
14237 for (i = 0; i < nargs; i += 1)
14238 elt = dump_subexp (exp, stream, elt);
14239
14240 return elt;
14241 }
14242
14243 /* The Ada extension of print_subexp (q.v.). */
14244
14245 static void
14246 ada_print_subexp (struct expression *exp, int *pos,
14247 struct ui_file *stream, enum precedence prec)
14248 {
14249 int oplen, nargs, i;
14250 int pc = *pos;
14251 enum exp_opcode op = exp->elts[pc].opcode;
14252
14253 ada_forward_operator_length (exp, pc, &oplen, &nargs);
14254
14255 *pos += oplen;
14256 switch (op)
14257 {
14258 default:
14259 *pos -= oplen;
14260 print_subexp_standard (exp, pos, stream, prec);
14261 return;
14262
14263 case OP_VAR_VALUE:
14264 fputs_filtered (exp->elts[pc + 2].symbol->natural_name (), stream);
14265 return;
14266
14267 case BINOP_IN_BOUNDS:
14268 /* XXX: sprint_subexp */
14269 print_subexp (exp, pos, stream, PREC_SUFFIX);
14270 fputs_filtered (" in ", stream);
14271 print_subexp (exp, pos, stream, PREC_SUFFIX);
14272 fputs_filtered ("'range", stream);
14273 if (exp->elts[pc + 1].longconst > 1)
14274 fprintf_filtered (stream, "(%ld)",
14275 (long) exp->elts[pc + 1].longconst);
14276 return;
14277
14278 case TERNOP_IN_RANGE:
14279 if (prec >= PREC_EQUAL)
14280 fputs_filtered ("(", stream);
14281 /* XXX: sprint_subexp */
14282 print_subexp (exp, pos, stream, PREC_SUFFIX);
14283 fputs_filtered (" in ", stream);
14284 print_subexp (exp, pos, stream, PREC_EQUAL);
14285 fputs_filtered (" .. ", stream);
14286 print_subexp (exp, pos, stream, PREC_EQUAL);
14287 if (prec >= PREC_EQUAL)
14288 fputs_filtered (")", stream);
14289 return;
14290
14291 case OP_ATR_FIRST:
14292 case OP_ATR_LAST:
14293 case OP_ATR_LENGTH:
14294 case OP_ATR_IMAGE:
14295 case OP_ATR_MAX:
14296 case OP_ATR_MIN:
14297 case OP_ATR_MODULUS:
14298 case OP_ATR_POS:
14299 case OP_ATR_SIZE:
14300 case OP_ATR_TAG:
14301 case OP_ATR_VAL:
14302 if (exp->elts[*pos].opcode == OP_TYPE)
14303 {
14304 if (exp->elts[*pos + 1].type->code () != TYPE_CODE_VOID)
14305 LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
14306 &type_print_raw_options);
14307 *pos += 3;
14308 }
14309 else
14310 print_subexp (exp, pos, stream, PREC_SUFFIX);
14311 fprintf_filtered (stream, "'%s", ada_attribute_name (op));
14312 if (nargs > 1)
14313 {
14314 int tem;
14315
14316 for (tem = 1; tem < nargs; tem += 1)
14317 {
14318 fputs_filtered ((tem == 1) ? " (" : ", ", stream);
14319 print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
14320 }
14321 fputs_filtered (")", stream);
14322 }
14323 return;
14324
14325 case UNOP_QUAL:
14326 type_print (exp->elts[pc + 1].type, "", stream, 0);
14327 fputs_filtered ("'(", stream);
14328 print_subexp (exp, pos, stream, PREC_PREFIX);
14329 fputs_filtered (")", stream);
14330 return;
14331
14332 case UNOP_IN_RANGE:
14333 /* XXX: sprint_subexp */
14334 print_subexp (exp, pos, stream, PREC_SUFFIX);
14335 fputs_filtered (" in ", stream);
14336 LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
14337 &type_print_raw_options);
14338 return;
14339
14340 case OP_DISCRETE_RANGE:
14341 print_subexp (exp, pos, stream, PREC_SUFFIX);
14342 fputs_filtered ("..", stream);
14343 print_subexp (exp, pos, stream, PREC_SUFFIX);
14344 return;
14345
14346 case OP_OTHERS:
14347 fputs_filtered ("others => ", stream);
14348 print_subexp (exp, pos, stream, PREC_SUFFIX);
14349 return;
14350
14351 case OP_CHOICES:
14352 for (i = 0; i < nargs-1; i += 1)
14353 {
14354 if (i > 0)
14355 fputs_filtered ("|", stream);
14356 print_subexp (exp, pos, stream, PREC_SUFFIX);
14357 }
14358 fputs_filtered (" => ", stream);
14359 print_subexp (exp, pos, stream, PREC_SUFFIX);
14360 return;
14361
14362 case OP_POSITIONAL:
14363 print_subexp (exp, pos, stream, PREC_SUFFIX);
14364 return;
14365
14366 case OP_AGGREGATE:
14367 fputs_filtered ("(", stream);
14368 for (i = 0; i < nargs; i += 1)
14369 {
14370 if (i > 0)
14371 fputs_filtered (", ", stream);
14372 print_subexp (exp, pos, stream, PREC_SUFFIX);
14373 }
14374 fputs_filtered (")", stream);
14375 return;
14376 }
14377 }
14378
14379 /* Table mapping opcodes into strings for printing operators
14380 and precedences of the operators. */
14381
14382 static const struct op_print ada_op_print_tab[] = {
14383 {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
14384 {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
14385 {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
14386 {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
14387 {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
14388 {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
14389 {"=", BINOP_EQUAL, PREC_EQUAL, 0},
14390 {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
14391 {"<=", BINOP_LEQ, PREC_ORDER, 0},
14392 {">=", BINOP_GEQ, PREC_ORDER, 0},
14393 {">", BINOP_GTR, PREC_ORDER, 0},
14394 {"<", BINOP_LESS, PREC_ORDER, 0},
14395 {">>", BINOP_RSH, PREC_SHIFT, 0},
14396 {"<<", BINOP_LSH, PREC_SHIFT, 0},
14397 {"+", BINOP_ADD, PREC_ADD, 0},
14398 {"-", BINOP_SUB, PREC_ADD, 0},
14399 {"&", BINOP_CONCAT, PREC_ADD, 0},
14400 {"*", BINOP_MUL, PREC_MUL, 0},
14401 {"/", BINOP_DIV, PREC_MUL, 0},
14402 {"rem", BINOP_REM, PREC_MUL, 0},
14403 {"mod", BINOP_MOD, PREC_MUL, 0},
14404 {"**", BINOP_EXP, PREC_REPEAT, 0},
14405 {"@", BINOP_REPEAT, PREC_REPEAT, 0},
14406 {"-", UNOP_NEG, PREC_PREFIX, 0},
14407 {"+", UNOP_PLUS, PREC_PREFIX, 0},
14408 {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
14409 {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
14410 {"abs ", UNOP_ABS, PREC_PREFIX, 0},
14411 {".all", UNOP_IND, PREC_SUFFIX, 1},
14412 {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
14413 {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
14414 {NULL, OP_NULL, PREC_SUFFIX, 0}
14415 };
14416 \f
14417 /* Language vector */
14418
14419 static const struct exp_descriptor ada_exp_descriptor = {
14420 ada_print_subexp,
14421 ada_operator_length,
14422 ada_operator_check,
14423 ada_dump_subexp_body,
14424 ada_evaluate_subexp
14425 };
14426
14427 /* symbol_name_matcher_ftype adapter for wild_match. */
14428
14429 static bool
14430 do_wild_match (const char *symbol_search_name,
14431 const lookup_name_info &lookup_name,
14432 completion_match_result *comp_match_res)
14433 {
14434 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
14435 }
14436
14437 /* symbol_name_matcher_ftype adapter for full_match. */
14438
14439 static bool
14440 do_full_match (const char *symbol_search_name,
14441 const lookup_name_info &lookup_name,
14442 completion_match_result *comp_match_res)
14443 {
14444 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
14445
14446 /* If both symbols start with "_ada_", just let the loop below
14447 handle the comparison. However, if only the symbol name starts
14448 with "_ada_", skip the prefix and let the match proceed as
14449 usual. */
14450 if (startswith (symbol_search_name, "_ada_")
14451 && !startswith (lname, "_ada"))
14452 symbol_search_name += 5;
14453
14454 int uscore_count = 0;
14455 while (*lname != '\0')
14456 {
14457 if (*symbol_search_name != *lname)
14458 {
14459 if (*symbol_search_name == 'B' && uscore_count == 2
14460 && symbol_search_name[1] == '_')
14461 {
14462 symbol_search_name += 2;
14463 while (isdigit (*symbol_search_name))
14464 ++symbol_search_name;
14465 if (symbol_search_name[0] == '_'
14466 && symbol_search_name[1] == '_')
14467 {
14468 symbol_search_name += 2;
14469 continue;
14470 }
14471 }
14472 return false;
14473 }
14474
14475 if (*symbol_search_name == '_')
14476 ++uscore_count;
14477 else
14478 uscore_count = 0;
14479
14480 ++symbol_search_name;
14481 ++lname;
14482 }
14483
14484 return is_name_suffix (symbol_search_name);
14485 }
14486
14487 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
14488
14489 static bool
14490 do_exact_match (const char *symbol_search_name,
14491 const lookup_name_info &lookup_name,
14492 completion_match_result *comp_match_res)
14493 {
14494 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
14495 }
14496
14497 /* Build the Ada lookup name for LOOKUP_NAME. */
14498
14499 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
14500 {
14501 gdb::string_view user_name = lookup_name.name ();
14502
14503 if (!user_name.empty () && user_name[0] == '<')
14504 {
14505 if (user_name.back () == '>')
14506 m_encoded_name
14507 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
14508 else
14509 m_encoded_name
14510 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
14511 m_encoded_p = true;
14512 m_verbatim_p = true;
14513 m_wild_match_p = false;
14514 m_standard_p = false;
14515 }
14516 else
14517 {
14518 m_verbatim_p = false;
14519
14520 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
14521
14522 if (!m_encoded_p)
14523 {
14524 const char *folded = ada_fold_name (user_name);
14525 m_encoded_name = ada_encode_1 (folded, false);
14526 if (m_encoded_name.empty ())
14527 m_encoded_name = gdb::to_string (user_name);
14528 }
14529 else
14530 m_encoded_name = gdb::to_string (user_name);
14531
14532 /* Handle the 'package Standard' special case. See description
14533 of m_standard_p. */
14534 if (startswith (m_encoded_name.c_str (), "standard__"))
14535 {
14536 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
14537 m_standard_p = true;
14538 }
14539 else
14540 m_standard_p = false;
14541
14542 /* If the name contains a ".", then the user is entering a fully
14543 qualified entity name, and the match must not be done in wild
14544 mode. Similarly, if the user wants to complete what looks
14545 like an encoded name, the match must not be done in wild
14546 mode. Also, in the standard__ special case always do
14547 non-wild matching. */
14548 m_wild_match_p
14549 = (lookup_name.match_type () != symbol_name_match_type::FULL
14550 && !m_encoded_p
14551 && !m_standard_p
14552 && user_name.find ('.') == std::string::npos);
14553 }
14554 }
14555
14556 /* symbol_name_matcher_ftype method for Ada. This only handles
14557 completion mode. */
14558
14559 static bool
14560 ada_symbol_name_matches (const char *symbol_search_name,
14561 const lookup_name_info &lookup_name,
14562 completion_match_result *comp_match_res)
14563 {
14564 return lookup_name.ada ().matches (symbol_search_name,
14565 lookup_name.match_type (),
14566 comp_match_res);
14567 }
14568
14569 /* A name matcher that matches the symbol name exactly, with
14570 strcmp. */
14571
14572 static bool
14573 literal_symbol_name_matcher (const char *symbol_search_name,
14574 const lookup_name_info &lookup_name,
14575 completion_match_result *comp_match_res)
14576 {
14577 gdb::string_view name_view = lookup_name.name ();
14578
14579 if (lookup_name.completion_mode ()
14580 ? (strncmp (symbol_search_name, name_view.data (),
14581 name_view.size ()) == 0)
14582 : symbol_search_name == name_view)
14583 {
14584 if (comp_match_res != NULL)
14585 comp_match_res->set_match (symbol_search_name);
14586 return true;
14587 }
14588 else
14589 return false;
14590 }
14591
14592 /* Implement the "get_symbol_name_matcher" language_defn method for
14593 Ada. */
14594
14595 static symbol_name_matcher_ftype *
14596 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
14597 {
14598 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
14599 return literal_symbol_name_matcher;
14600
14601 if (lookup_name.completion_mode ())
14602 return ada_symbol_name_matches;
14603 else
14604 {
14605 if (lookup_name.ada ().wild_match_p ())
14606 return do_wild_match;
14607 else if (lookup_name.ada ().verbatim_p ())
14608 return do_exact_match;
14609 else
14610 return do_full_match;
14611 }
14612 }
14613
14614 /* Class representing the Ada language. */
14615
14616 class ada_language : public language_defn
14617 {
14618 public:
14619 ada_language ()
14620 : language_defn (language_ada)
14621 { /* Nothing. */ }
14622
14623 /* See language.h. */
14624
14625 const char *name () const override
14626 { return "ada"; }
14627
14628 /* See language.h. */
14629
14630 const char *natural_name () const override
14631 { return "Ada"; }
14632
14633 /* See language.h. */
14634
14635 const std::vector<const char *> &filename_extensions () const override
14636 {
14637 static const std::vector<const char *> extensions
14638 = { ".adb", ".ads", ".a", ".ada", ".dg" };
14639 return extensions;
14640 }
14641
14642 /* Print an array element index using the Ada syntax. */
14643
14644 void print_array_index (struct type *index_type,
14645 LONGEST index,
14646 struct ui_file *stream,
14647 const value_print_options *options) const override
14648 {
14649 struct value *index_value = val_atr (index_type, index);
14650
14651 value_print (index_value, stream, options);
14652 fprintf_filtered (stream, " => ");
14653 }
14654
14655 /* Implement the "read_var_value" language_defn method for Ada. */
14656
14657 struct value *read_var_value (struct symbol *var,
14658 const struct block *var_block,
14659 struct frame_info *frame) const override
14660 {
14661 /* The only case where default_read_var_value is not sufficient
14662 is when VAR is a renaming... */
14663 if (frame != nullptr)
14664 {
14665 const struct block *frame_block = get_frame_block (frame, NULL);
14666 if (frame_block != nullptr && ada_is_renaming_symbol (var))
14667 return ada_read_renaming_var_value (var, frame_block);
14668 }
14669
14670 /* This is a typical case where we expect the default_read_var_value
14671 function to work. */
14672 return language_defn::read_var_value (var, var_block, frame);
14673 }
14674
14675 /* See language.h. */
14676 void language_arch_info (struct gdbarch *gdbarch,
14677 struct language_arch_info *lai) const override
14678 {
14679 const struct builtin_type *builtin = builtin_type (gdbarch);
14680
14681 /* Helper function to allow shorter lines below. */
14682 auto add = [&] (struct type *t)
14683 {
14684 lai->add_primitive_type (t);
14685 };
14686
14687 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14688 0, "integer"));
14689 add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
14690 0, "long_integer"));
14691 add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
14692 0, "short_integer"));
14693 struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
14694 0, "character");
14695 lai->set_string_char_type (char_type);
14696 add (char_type);
14697 add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
14698 "float", gdbarch_float_format (gdbarch)));
14699 add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
14700 "long_float", gdbarch_double_format (gdbarch)));
14701 add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
14702 0, "long_long_integer"));
14703 add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
14704 "long_long_float",
14705 gdbarch_long_double_format (gdbarch)));
14706 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14707 0, "natural"));
14708 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14709 0, "positive"));
14710 add (builtin->builtin_void);
14711
14712 struct type *system_addr_ptr
14713 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
14714 "void"));
14715 system_addr_ptr->set_name ("system__address");
14716 add (system_addr_ptr);
14717
14718 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
14719 type. This is a signed integral type whose size is the same as
14720 the size of addresses. */
14721 unsigned int addr_length = TYPE_LENGTH (system_addr_ptr);
14722 add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
14723 "storage_offset"));
14724
14725 lai->set_bool_type (builtin->builtin_bool);
14726 }
14727
14728 /* See language.h. */
14729
14730 bool iterate_over_symbols
14731 (const struct block *block, const lookup_name_info &name,
14732 domain_enum domain,
14733 gdb::function_view<symbol_found_callback_ftype> callback) const override
14734 {
14735 std::vector<struct block_symbol> results
14736 = ada_lookup_symbol_list_worker (name, block, domain, 0);
14737 for (block_symbol &sym : results)
14738 {
14739 if (!callback (&sym))
14740 return false;
14741 }
14742
14743 return true;
14744 }
14745
14746 /* See language.h. */
14747 bool sniff_from_mangled_name (const char *mangled,
14748 char **out) const override
14749 {
14750 std::string demangled = ada_decode (mangled);
14751
14752 *out = NULL;
14753
14754 if (demangled != mangled && demangled[0] != '<')
14755 {
14756 /* Set the gsymbol language to Ada, but still return 0.
14757 Two reasons for that:
14758
14759 1. For Ada, we prefer computing the symbol's decoded name
14760 on the fly rather than pre-compute it, in order to save
14761 memory (Ada projects are typically very large).
14762
14763 2. There are some areas in the definition of the GNAT
14764 encoding where, with a bit of bad luck, we might be able
14765 to decode a non-Ada symbol, generating an incorrect
14766 demangled name (Eg: names ending with "TB" for instance
14767 are identified as task bodies and so stripped from
14768 the decoded name returned).
14769
14770 Returning true, here, but not setting *DEMANGLED, helps us get
14771 a little bit of the best of both worlds. Because we're last,
14772 we should not affect any of the other languages that were
14773 able to demangle the symbol before us; we get to correctly
14774 tag Ada symbols as such; and even if we incorrectly tagged a
14775 non-Ada symbol, which should be rare, any routing through the
14776 Ada language should be transparent (Ada tries to behave much
14777 like C/C++ with non-Ada symbols). */
14778 return true;
14779 }
14780
14781 return false;
14782 }
14783
14784 /* See language.h. */
14785
14786 char *demangle_symbol (const char *mangled, int options) const override
14787 {
14788 return ada_la_decode (mangled, options);
14789 }
14790
14791 /* See language.h. */
14792
14793 void print_type (struct type *type, const char *varstring,
14794 struct ui_file *stream, int show, int level,
14795 const struct type_print_options *flags) const override
14796 {
14797 ada_print_type (type, varstring, stream, show, level, flags);
14798 }
14799
14800 /* See language.h. */
14801
14802 const char *word_break_characters (void) const override
14803 {
14804 return ada_completer_word_break_characters;
14805 }
14806
14807 /* See language.h. */
14808
14809 void collect_symbol_completion_matches (completion_tracker &tracker,
14810 complete_symbol_mode mode,
14811 symbol_name_match_type name_match_type,
14812 const char *text, const char *word,
14813 enum type_code code) const override
14814 {
14815 struct symbol *sym;
14816 const struct block *b, *surrounding_static_block = 0;
14817 struct block_iterator iter;
14818
14819 gdb_assert (code == TYPE_CODE_UNDEF);
14820
14821 lookup_name_info lookup_name (text, name_match_type, true);
14822
14823 /* First, look at the partial symtab symbols. */
14824 expand_symtabs_matching (NULL,
14825 lookup_name,
14826 NULL,
14827 NULL,
14828 ALL_DOMAIN);
14829
14830 /* At this point scan through the misc symbol vectors and add each
14831 symbol you find to the list. Eventually we want to ignore
14832 anything that isn't a text symbol (everything else will be
14833 handled by the psymtab code above). */
14834
14835 for (objfile *objfile : current_program_space->objfiles ())
14836 {
14837 for (minimal_symbol *msymbol : objfile->msymbols ())
14838 {
14839 QUIT;
14840
14841 if (completion_skip_symbol (mode, msymbol))
14842 continue;
14843
14844 language symbol_language = msymbol->language ();
14845
14846 /* Ada minimal symbols won't have their language set to Ada. If
14847 we let completion_list_add_name compare using the
14848 default/C-like matcher, then when completing e.g., symbols in a
14849 package named "pck", we'd match internal Ada symbols like
14850 "pckS", which are invalid in an Ada expression, unless you wrap
14851 them in '<' '>' to request a verbatim match.
14852
14853 Unfortunately, some Ada encoded names successfully demangle as
14854 C++ symbols (using an old mangling scheme), such as "name__2Xn"
14855 -> "Xn::name(void)" and thus some Ada minimal symbols end up
14856 with the wrong language set. Paper over that issue here. */
14857 if (symbol_language == language_auto
14858 || symbol_language == language_cplus)
14859 symbol_language = language_ada;
14860
14861 completion_list_add_name (tracker,
14862 symbol_language,
14863 msymbol->linkage_name (),
14864 lookup_name, text, word);
14865 }
14866 }
14867
14868 /* Search upwards from currently selected frame (so that we can
14869 complete on local vars. */
14870
14871 for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
14872 {
14873 if (!BLOCK_SUPERBLOCK (b))
14874 surrounding_static_block = b; /* For elmin of dups */
14875
14876 ALL_BLOCK_SYMBOLS (b, iter, sym)
14877 {
14878 if (completion_skip_symbol (mode, sym))
14879 continue;
14880
14881 completion_list_add_name (tracker,
14882 sym->language (),
14883 sym->linkage_name (),
14884 lookup_name, text, word);
14885 }
14886 }
14887
14888 /* Go through the symtabs and check the externs and statics for
14889 symbols which match. */
14890
14891 for (objfile *objfile : current_program_space->objfiles ())
14892 {
14893 for (compunit_symtab *s : objfile->compunits ())
14894 {
14895 QUIT;
14896 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
14897 ALL_BLOCK_SYMBOLS (b, iter, sym)
14898 {
14899 if (completion_skip_symbol (mode, sym))
14900 continue;
14901
14902 completion_list_add_name (tracker,
14903 sym->language (),
14904 sym->linkage_name (),
14905 lookup_name, text, word);
14906 }
14907 }
14908 }
14909
14910 for (objfile *objfile : current_program_space->objfiles ())
14911 {
14912 for (compunit_symtab *s : objfile->compunits ())
14913 {
14914 QUIT;
14915 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
14916 /* Don't do this block twice. */
14917 if (b == surrounding_static_block)
14918 continue;
14919 ALL_BLOCK_SYMBOLS (b, iter, sym)
14920 {
14921 if (completion_skip_symbol (mode, sym))
14922 continue;
14923
14924 completion_list_add_name (tracker,
14925 sym->language (),
14926 sym->linkage_name (),
14927 lookup_name, text, word);
14928 }
14929 }
14930 }
14931 }
14932
14933 /* See language.h. */
14934
14935 gdb::unique_xmalloc_ptr<char> watch_location_expression
14936 (struct type *type, CORE_ADDR addr) const override
14937 {
14938 type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
14939 std::string name = type_to_string (type);
14940 return gdb::unique_xmalloc_ptr<char>
14941 (xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr)));
14942 }
14943
14944 /* See language.h. */
14945
14946 void value_print (struct value *val, struct ui_file *stream,
14947 const struct value_print_options *options) const override
14948 {
14949 return ada_value_print (val, stream, options);
14950 }
14951
14952 /* See language.h. */
14953
14954 void value_print_inner
14955 (struct value *val, struct ui_file *stream, int recurse,
14956 const struct value_print_options *options) const override
14957 {
14958 return ada_value_print_inner (val, stream, recurse, options);
14959 }
14960
14961 /* See language.h. */
14962
14963 struct block_symbol lookup_symbol_nonlocal
14964 (const char *name, const struct block *block,
14965 const domain_enum domain) const override
14966 {
14967 struct block_symbol sym;
14968
14969 sym = ada_lookup_symbol (name, block_static_block (block), domain);
14970 if (sym.symbol != NULL)
14971 return sym;
14972
14973 /* If we haven't found a match at this point, try the primitive
14974 types. In other languages, this search is performed before
14975 searching for global symbols in order to short-circuit that
14976 global-symbol search if it happens that the name corresponds
14977 to a primitive type. But we cannot do the same in Ada, because
14978 it is perfectly legitimate for a program to declare a type which
14979 has the same name as a standard type. If looking up a type in
14980 that situation, we have traditionally ignored the primitive type
14981 in favor of user-defined types. This is why, unlike most other
14982 languages, we search the primitive types this late and only after
14983 having searched the global symbols without success. */
14984
14985 if (domain == VAR_DOMAIN)
14986 {
14987 struct gdbarch *gdbarch;
14988
14989 if (block == NULL)
14990 gdbarch = target_gdbarch ();
14991 else
14992 gdbarch = block_gdbarch (block);
14993 sym.symbol
14994 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
14995 if (sym.symbol != NULL)
14996 return sym;
14997 }
14998
14999 return {};
15000 }
15001
15002 /* See language.h. */
15003
15004 int parser (struct parser_state *ps) const override
15005 {
15006 warnings_issued = 0;
15007 return ada_parse (ps);
15008 }
15009
15010 /* See language.h.
15011
15012 Same as evaluate_type (*EXP), but resolves ambiguous symbol references
15013 (marked by OP_VAR_VALUE nodes in which the symbol has an undefined
15014 namespace) and converts operators that are user-defined into
15015 appropriate function calls. If CONTEXT_TYPE is non-null, it provides
15016 a preferred result type [at the moment, only type void has any
15017 effect---causing procedures to be preferred over functions in calls].
15018 A null CONTEXT_TYPE indicates that a non-void return type is
15019 preferred. May change (expand) *EXP. */
15020
15021 void post_parser (expression_up *expp, struct parser_state *ps)
15022 const override
15023 {
15024 struct type *context_type = NULL;
15025 int pc = 0;
15026
15027 if (ps->void_context_p)
15028 context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
15029
15030 resolve_subexp (expp, &pc, 1, context_type, ps->parse_completion,
15031 ps->block_tracker);
15032 }
15033
15034 /* See language.h. */
15035
15036 void emitchar (int ch, struct type *chtype,
15037 struct ui_file *stream, int quoter) const override
15038 {
15039 ada_emit_char (ch, chtype, stream, quoter, 1);
15040 }
15041
15042 /* See language.h. */
15043
15044 void printchar (int ch, struct type *chtype,
15045 struct ui_file *stream) const override
15046 {
15047 ada_printchar (ch, chtype, stream);
15048 }
15049
15050 /* See language.h. */
15051
15052 void printstr (struct ui_file *stream, struct type *elttype,
15053 const gdb_byte *string, unsigned int length,
15054 const char *encoding, int force_ellipses,
15055 const struct value_print_options *options) const override
15056 {
15057 ada_printstr (stream, elttype, string, length, encoding,
15058 force_ellipses, options);
15059 }
15060
15061 /* See language.h. */
15062
15063 void print_typedef (struct type *type, struct symbol *new_symbol,
15064 struct ui_file *stream) const override
15065 {
15066 ada_print_typedef (type, new_symbol, stream);
15067 }
15068
15069 /* See language.h. */
15070
15071 bool is_string_type_p (struct type *type) const override
15072 {
15073 return ada_is_string_type (type);
15074 }
15075
15076 /* See language.h. */
15077
15078 const char *struct_too_deep_ellipsis () const override
15079 { return "(...)"; }
15080
15081 /* See language.h. */
15082
15083 bool c_style_arrays_p () const override
15084 { return false; }
15085
15086 /* See language.h. */
15087
15088 bool store_sym_names_in_linkage_form_p () const override
15089 { return true; }
15090
15091 /* See language.h. */
15092
15093 const struct lang_varobj_ops *varobj_ops () const override
15094 { return &ada_varobj_ops; }
15095
15096 /* See language.h. */
15097
15098 const struct exp_descriptor *expression_ops () const override
15099 { return &ada_exp_descriptor; }
15100
15101 /* See language.h. */
15102
15103 const struct op_print *opcode_print_table () const override
15104 { return ada_op_print_tab; }
15105
15106 protected:
15107 /* See language.h. */
15108
15109 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
15110 (const lookup_name_info &lookup_name) const override
15111 {
15112 return ada_get_symbol_name_matcher (lookup_name);
15113 }
15114 };
15115
15116 /* Single instance of the Ada language class. */
15117
15118 static ada_language ada_language_defn;
15119
15120 /* Command-list for the "set/show ada" prefix command. */
15121 static struct cmd_list_element *set_ada_list;
15122 static struct cmd_list_element *show_ada_list;
15123
15124 static void
15125 initialize_ada_catchpoint_ops (void)
15126 {
15127 struct breakpoint_ops *ops;
15128
15129 initialize_breakpoint_ops ();
15130
15131 ops = &catch_exception_breakpoint_ops;
15132 *ops = bkpt_breakpoint_ops;
15133 ops->allocate_location = allocate_location_exception;
15134 ops->re_set = re_set_exception;
15135 ops->check_status = check_status_exception;
15136 ops->print_it = print_it_exception;
15137 ops->print_one = print_one_exception;
15138 ops->print_mention = print_mention_exception;
15139 ops->print_recreate = print_recreate_exception;
15140
15141 ops = &catch_exception_unhandled_breakpoint_ops;
15142 *ops = bkpt_breakpoint_ops;
15143 ops->allocate_location = allocate_location_exception;
15144 ops->re_set = re_set_exception;
15145 ops->check_status = check_status_exception;
15146 ops->print_it = print_it_exception;
15147 ops->print_one = print_one_exception;
15148 ops->print_mention = print_mention_exception;
15149 ops->print_recreate = print_recreate_exception;
15150
15151 ops = &catch_assert_breakpoint_ops;
15152 *ops = bkpt_breakpoint_ops;
15153 ops->allocate_location = allocate_location_exception;
15154 ops->re_set = re_set_exception;
15155 ops->check_status = check_status_exception;
15156 ops->print_it = print_it_exception;
15157 ops->print_one = print_one_exception;
15158 ops->print_mention = print_mention_exception;
15159 ops->print_recreate = print_recreate_exception;
15160
15161 ops = &catch_handlers_breakpoint_ops;
15162 *ops = bkpt_breakpoint_ops;
15163 ops->allocate_location = allocate_location_exception;
15164 ops->re_set = re_set_exception;
15165 ops->check_status = check_status_exception;
15166 ops->print_it = print_it_exception;
15167 ops->print_one = print_one_exception;
15168 ops->print_mention = print_mention_exception;
15169 ops->print_recreate = print_recreate_exception;
15170 }
15171
15172 /* This module's 'new_objfile' observer. */
15173
15174 static void
15175 ada_new_objfile_observer (struct objfile *objfile)
15176 {
15177 ada_clear_symbol_cache ();
15178 }
15179
15180 /* This module's 'free_objfile' observer. */
15181
15182 static void
15183 ada_free_objfile_observer (struct objfile *objfile)
15184 {
15185 ada_clear_symbol_cache ();
15186 }
15187
15188 void _initialize_ada_language ();
15189 void
15190 _initialize_ada_language ()
15191 {
15192 initialize_ada_catchpoint_ops ();
15193
15194 add_basic_prefix_cmd ("ada", no_class,
15195 _("Prefix command for changing Ada-specific settings."),
15196 &set_ada_list, "set ada ", 0, &setlist);
15197
15198 add_show_prefix_cmd ("ada", no_class,
15199 _("Generic command for showing Ada-specific settings."),
15200 &show_ada_list, "show ada ", 0, &showlist);
15201
15202 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
15203 &trust_pad_over_xvs, _("\
15204 Enable or disable an optimization trusting PAD types over XVS types."), _("\
15205 Show whether an optimization trusting PAD types over XVS types is activated."),
15206 _("\
15207 This is related to the encoding used by the GNAT compiler. The debugger\n\
15208 should normally trust the contents of PAD types, but certain older versions\n\
15209 of GNAT have a bug that sometimes causes the information in the PAD type\n\
15210 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
15211 work around this bug. It is always safe to turn this option \"off\", but\n\
15212 this incurs a slight performance penalty, so it is recommended to NOT change\n\
15213 this option to \"off\" unless necessary."),
15214 NULL, NULL, &set_ada_list, &show_ada_list);
15215
15216 add_setshow_boolean_cmd ("print-signatures", class_vars,
15217 &print_signatures, _("\
15218 Enable or disable the output of formal and return types for functions in the \
15219 overloads selection menu."), _("\
15220 Show whether the output of formal and return types for functions in the \
15221 overloads selection menu is activated."),
15222 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
15223
15224 add_catch_command ("exception", _("\
15225 Catch Ada exceptions, when raised.\n\
15226 Usage: catch exception [ARG] [if CONDITION]\n\
15227 Without any argument, stop when any Ada exception is raised.\n\
15228 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
15229 being raised does not have a handler (and will therefore lead to the task's\n\
15230 termination).\n\
15231 Otherwise, the catchpoint only stops when the name of the exception being\n\
15232 raised is the same as ARG.\n\
15233 CONDITION is a boolean expression that is evaluated to see whether the\n\
15234 exception should cause a stop."),
15235 catch_ada_exception_command,
15236 catch_ada_completer,
15237 CATCH_PERMANENT,
15238 CATCH_TEMPORARY);
15239
15240 add_catch_command ("handlers", _("\
15241 Catch Ada exceptions, when handled.\n\
15242 Usage: catch handlers [ARG] [if CONDITION]\n\
15243 Without any argument, stop when any Ada exception is handled.\n\
15244 With an argument, catch only exceptions with the given name.\n\
15245 CONDITION is a boolean expression that is evaluated to see whether the\n\
15246 exception should cause a stop."),
15247 catch_ada_handlers_command,
15248 catch_ada_completer,
15249 CATCH_PERMANENT,
15250 CATCH_TEMPORARY);
15251 add_catch_command ("assert", _("\
15252 Catch failed Ada assertions, when raised.\n\
15253 Usage: catch assert [if CONDITION]\n\
15254 CONDITION is a boolean expression that is evaluated to see whether the\n\
15255 exception should cause a stop."),
15256 catch_assert_command,
15257 NULL,
15258 CATCH_PERMANENT,
15259 CATCH_TEMPORARY);
15260
15261 varsize_limit = 65536;
15262 add_setshow_uinteger_cmd ("varsize-limit", class_support,
15263 &varsize_limit, _("\
15264 Set the maximum number of bytes allowed in a variable-size object."), _("\
15265 Show the maximum number of bytes allowed in a variable-size object."), _("\
15266 Attempts to access an object whose size is not a compile-time constant\n\
15267 and exceeds this limit will cause an error."),
15268 NULL, NULL, &setlist, &showlist);
15269
15270 add_info ("exceptions", info_exceptions_command,
15271 _("\
15272 List all Ada exception names.\n\
15273 Usage: info exceptions [REGEXP]\n\
15274 If a regular expression is passed as an argument, only those matching\n\
15275 the regular expression are listed."));
15276
15277 add_basic_prefix_cmd ("ada", class_maintenance,
15278 _("Set Ada maintenance-related variables."),
15279 &maint_set_ada_cmdlist, "maintenance set ada ",
15280 0/*allow-unknown*/, &maintenance_set_cmdlist);
15281
15282 add_show_prefix_cmd ("ada", class_maintenance,
15283 _("Show Ada maintenance-related variables."),
15284 &maint_show_ada_cmdlist, "maintenance show ada ",
15285 0/*allow-unknown*/, &maintenance_show_cmdlist);
15286
15287 add_setshow_boolean_cmd
15288 ("ignore-descriptive-types", class_maintenance,
15289 &ada_ignore_descriptive_types_p,
15290 _("Set whether descriptive types generated by GNAT should be ignored."),
15291 _("Show whether descriptive types generated by GNAT should be ignored."),
15292 _("\
15293 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
15294 DWARF attribute."),
15295 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
15296
15297 decoded_names_store = htab_create_alloc (256, htab_hash_string, streq_hash,
15298 NULL, xcalloc, xfree);
15299
15300 /* The ada-lang observers. */
15301 gdb::observers::new_objfile.attach (ada_new_objfile_observer);
15302 gdb::observers::free_objfile.attach (ada_free_objfile_observer);
15303 gdb::observers::inferior_exit.attach (ada_inferior_exit);
15304 }