Convert ada-exp.y to use operations
[deliverable/binutils-gdb.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2021 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20
21 #include "defs.h"
22 #include <ctype.h>
23 #include "gdb_regex.h"
24 #include "frame.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "gdbcmd.h"
28 #include "expression.h"
29 #include "parser-defs.h"
30 #include "language.h"
31 #include "varobj.h"
32 #include "inferior.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "breakpoint.h"
36 #include "gdbcore.h"
37 #include "hashtab.h"
38 #include "gdb_obstack.h"
39 #include "ada-lang.h"
40 #include "completer.h"
41 #include "ui-out.h"
42 #include "block.h"
43 #include "infcall.h"
44 #include "annotate.h"
45 #include "valprint.h"
46 #include "source.h"
47 #include "observable.h"
48 #include "stack.h"
49 #include "typeprint.h"
50 #include "namespace.h"
51 #include "cli/cli-style.h"
52
53 #include "value.h"
54 #include "mi/mi-common.h"
55 #include "arch-utils.h"
56 #include "cli/cli-utils.h"
57 #include "gdbsupport/function-view.h"
58 #include "gdbsupport/byte-vector.h"
59 #include <algorithm>
60 #include "ada-exp.h"
61
62 /* Define whether or not the C operator '/' truncates towards zero for
63 differently signed operands (truncation direction is undefined in C).
64 Copied from valarith.c. */
65
66 #ifndef TRUNCATION_TOWARDS_ZERO
67 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
68 #endif
69
70 static struct type *desc_base_type (struct type *);
71
72 static struct type *desc_bounds_type (struct type *);
73
74 static struct value *desc_bounds (struct value *);
75
76 static int fat_pntr_bounds_bitpos (struct type *);
77
78 static int fat_pntr_bounds_bitsize (struct type *);
79
80 static struct type *desc_data_target_type (struct type *);
81
82 static struct value *desc_data (struct value *);
83
84 static int fat_pntr_data_bitpos (struct type *);
85
86 static int fat_pntr_data_bitsize (struct type *);
87
88 static struct value *desc_one_bound (struct value *, int, int);
89
90 static int desc_bound_bitpos (struct type *, int, int);
91
92 static int desc_bound_bitsize (struct type *, int, int);
93
94 static struct type *desc_index_type (struct type *, int);
95
96 static int desc_arity (struct type *);
97
98 static int ada_type_match (struct type *, struct type *, int);
99
100 static int ada_args_match (struct symbol *, struct value **, int);
101
102 static struct value *make_array_descriptor (struct type *, struct value *);
103
104 static void ada_add_block_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
106 const lookup_name_info &lookup_name,
107 domain_enum, struct objfile *);
108
109 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
110 const struct block *,
111 const lookup_name_info &lookup_name,
112 domain_enum, int, int *);
113
114 static int is_nonfunction (const std::vector<struct block_symbol> &);
115
116 static void add_defn_to_vec (std::vector<struct block_symbol> &,
117 struct symbol *,
118 const struct block *);
119
120 static struct value *resolve_subexp (expression_up *, int *, int,
121 struct type *, int,
122 innermost_block_tracker *);
123
124 static void replace_operator_with_call (expression_up *, int, int, int,
125 struct symbol *, const struct block *);
126
127 static int possible_user_operator_p (enum exp_opcode, struct value **);
128
129 static const char *ada_decoded_op_name (enum exp_opcode);
130
131 static int numeric_type_p (struct type *);
132
133 static int integer_type_p (struct type *);
134
135 static int scalar_type_p (struct type *);
136
137 static int discrete_type_p (struct type *);
138
139 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
140 int, int);
141
142 static struct value *evaluate_subexp_type (struct expression *, int *);
143
144 static struct type *ada_find_parallel_type_with_name (struct type *,
145 const char *);
146
147 static int is_dynamic_field (struct type *, int);
148
149 static struct type *to_fixed_variant_branch_type (struct type *,
150 const gdb_byte *,
151 CORE_ADDR, struct value *);
152
153 static struct type *to_fixed_array_type (struct type *, struct value *, int);
154
155 static struct type *to_fixed_range_type (struct type *, struct value *);
156
157 static struct type *to_static_fixed_type (struct type *);
158 static struct type *static_unwrap_type (struct type *type);
159
160 static struct value *unwrap_value (struct value *);
161
162 static struct type *constrained_packed_array_type (struct type *, long *);
163
164 static struct type *decode_constrained_packed_array_type (struct type *);
165
166 static long decode_packed_array_bitsize (struct type *);
167
168 static struct value *decode_constrained_packed_array (struct value *);
169
170 static int ada_is_unconstrained_packed_array_type (struct type *);
171
172 static struct value *value_subscript_packed (struct value *, int,
173 struct value **);
174
175 static struct value *coerce_unspec_val_to_type (struct value *,
176 struct type *);
177
178 static int lesseq_defined_than (struct symbol *, struct symbol *);
179
180 static int equiv_types (struct type *, struct type *);
181
182 static int is_name_suffix (const char *);
183
184 static int advance_wild_match (const char **, const char *, char);
185
186 static bool wild_match (const char *name, const char *patn);
187
188 static struct value *ada_coerce_ref (struct value *);
189
190 static LONGEST pos_atr (struct value *);
191
192 static struct value *val_atr (struct type *, LONGEST);
193
194 static struct symbol *standard_lookup (const char *, const struct block *,
195 domain_enum);
196
197 static struct value *ada_search_struct_field (const char *, struct value *, int,
198 struct type *);
199
200 static int find_struct_field (const char *, struct type *, int,
201 struct type **, int *, int *, int *, int *);
202
203 static int ada_resolve_function (std::vector<struct block_symbol> &,
204 struct value **, int, const char *,
205 struct type *, int);
206
207 static int ada_is_direct_array_type (struct type *);
208
209 static struct value *ada_index_struct_field (int, struct value *, int,
210 struct type *);
211
212 static struct value *assign_aggregate (struct value *, struct value *,
213 struct expression *,
214 int *, enum noside);
215
216 static void aggregate_assign_from_choices (struct value *, struct value *,
217 struct expression *,
218 int *, std::vector<LONGEST> &,
219 LONGEST, LONGEST);
220
221 static void aggregate_assign_positional (struct value *, struct value *,
222 struct expression *,
223 int *, std::vector<LONGEST> &,
224 LONGEST, LONGEST);
225
226
227 static void aggregate_assign_others (struct value *, struct value *,
228 struct expression *,
229 int *, std::vector<LONGEST> &,
230 LONGEST, LONGEST);
231
232
233 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
234
235
236 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
237 int *, enum noside);
238
239 static void ada_forward_operator_length (struct expression *, int, int *,
240 int *);
241
242 static struct type *ada_find_any_type (const char *name);
243
244 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
245 (const lookup_name_info &lookup_name);
246
247 \f
248
249 /* The result of a symbol lookup to be stored in our symbol cache. */
250
251 struct cache_entry
252 {
253 /* The name used to perform the lookup. */
254 const char *name;
255 /* The namespace used during the lookup. */
256 domain_enum domain;
257 /* The symbol returned by the lookup, or NULL if no matching symbol
258 was found. */
259 struct symbol *sym;
260 /* The block where the symbol was found, or NULL if no matching
261 symbol was found. */
262 const struct block *block;
263 /* A pointer to the next entry with the same hash. */
264 struct cache_entry *next;
265 };
266
267 /* The Ada symbol cache, used to store the result of Ada-mode symbol
268 lookups in the course of executing the user's commands.
269
270 The cache is implemented using a simple, fixed-sized hash.
271 The size is fixed on the grounds that there are not likely to be
272 all that many symbols looked up during any given session, regardless
273 of the size of the symbol table. If we decide to go to a resizable
274 table, let's just use the stuff from libiberty instead. */
275
276 #define HASH_SIZE 1009
277
278 struct ada_symbol_cache
279 {
280 /* An obstack used to store the entries in our cache. */
281 struct auto_obstack cache_space;
282
283 /* The root of the hash table used to implement our symbol cache. */
284 struct cache_entry *root[HASH_SIZE] {};
285 };
286
287 /* Maximum-sized dynamic type. */
288 static unsigned int varsize_limit;
289
290 static const char ada_completer_word_break_characters[] =
291 #ifdef VMS
292 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
293 #else
294 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
295 #endif
296
297 /* The name of the symbol to use to get the name of the main subprogram. */
298 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
299 = "__gnat_ada_main_program_name";
300
301 /* Limit on the number of warnings to raise per expression evaluation. */
302 static int warning_limit = 2;
303
304 /* Number of warning messages issued; reset to 0 by cleanups after
305 expression evaluation. */
306 static int warnings_issued = 0;
307
308 static const char * const known_runtime_file_name_patterns[] = {
309 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
310 };
311
312 static const char * const known_auxiliary_function_name_patterns[] = {
313 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
314 };
315
316 /* Maintenance-related settings for this module. */
317
318 static struct cmd_list_element *maint_set_ada_cmdlist;
319 static struct cmd_list_element *maint_show_ada_cmdlist;
320
321 /* The "maintenance ada set/show ignore-descriptive-type" value. */
322
323 static bool ada_ignore_descriptive_types_p = false;
324
325 /* Inferior-specific data. */
326
327 /* Per-inferior data for this module. */
328
329 struct ada_inferior_data
330 {
331 /* The ada__tags__type_specific_data type, which is used when decoding
332 tagged types. With older versions of GNAT, this type was directly
333 accessible through a component ("tsd") in the object tag. But this
334 is no longer the case, so we cache it for each inferior. */
335 struct type *tsd_type = nullptr;
336
337 /* The exception_support_info data. This data is used to determine
338 how to implement support for Ada exception catchpoints in a given
339 inferior. */
340 const struct exception_support_info *exception_info = nullptr;
341 };
342
343 /* Our key to this module's inferior data. */
344 static const struct inferior_key<ada_inferior_data> ada_inferior_data;
345
346 /* Return our inferior data for the given inferior (INF).
347
348 This function always returns a valid pointer to an allocated
349 ada_inferior_data structure. If INF's inferior data has not
350 been previously set, this functions creates a new one with all
351 fields set to zero, sets INF's inferior to it, and then returns
352 a pointer to that newly allocated ada_inferior_data. */
353
354 static struct ada_inferior_data *
355 get_ada_inferior_data (struct inferior *inf)
356 {
357 struct ada_inferior_data *data;
358
359 data = ada_inferior_data.get (inf);
360 if (data == NULL)
361 data = ada_inferior_data.emplace (inf);
362
363 return data;
364 }
365
366 /* Perform all necessary cleanups regarding our module's inferior data
367 that is required after the inferior INF just exited. */
368
369 static void
370 ada_inferior_exit (struct inferior *inf)
371 {
372 ada_inferior_data.clear (inf);
373 }
374
375
376 /* program-space-specific data. */
377
378 /* This module's per-program-space data. */
379 struct ada_pspace_data
380 {
381 /* The Ada symbol cache. */
382 std::unique_ptr<ada_symbol_cache> sym_cache;
383 };
384
385 /* Key to our per-program-space data. */
386 static const struct program_space_key<ada_pspace_data> ada_pspace_data_handle;
387
388 /* Return this module's data for the given program space (PSPACE).
389 If not is found, add a zero'ed one now.
390
391 This function always returns a valid object. */
392
393 static struct ada_pspace_data *
394 get_ada_pspace_data (struct program_space *pspace)
395 {
396 struct ada_pspace_data *data;
397
398 data = ada_pspace_data_handle.get (pspace);
399 if (data == NULL)
400 data = ada_pspace_data_handle.emplace (pspace);
401
402 return data;
403 }
404
405 /* Utilities */
406
407 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
408 all typedef layers have been peeled. Otherwise, return TYPE.
409
410 Normally, we really expect a typedef type to only have 1 typedef layer.
411 In other words, we really expect the target type of a typedef type to be
412 a non-typedef type. This is particularly true for Ada units, because
413 the language does not have a typedef vs not-typedef distinction.
414 In that respect, the Ada compiler has been trying to eliminate as many
415 typedef definitions in the debugging information, since they generally
416 do not bring any extra information (we still use typedef under certain
417 circumstances related mostly to the GNAT encoding).
418
419 Unfortunately, we have seen situations where the debugging information
420 generated by the compiler leads to such multiple typedef layers. For
421 instance, consider the following example with stabs:
422
423 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
424 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
425
426 This is an error in the debugging information which causes type
427 pck__float_array___XUP to be defined twice, and the second time,
428 it is defined as a typedef of a typedef.
429
430 This is on the fringe of legality as far as debugging information is
431 concerned, and certainly unexpected. But it is easy to handle these
432 situations correctly, so we can afford to be lenient in this case. */
433
434 static struct type *
435 ada_typedef_target_type (struct type *type)
436 {
437 while (type->code () == TYPE_CODE_TYPEDEF)
438 type = TYPE_TARGET_TYPE (type);
439 return type;
440 }
441
442 /* Given DECODED_NAME a string holding a symbol name in its
443 decoded form (ie using the Ada dotted notation), returns
444 its unqualified name. */
445
446 static const char *
447 ada_unqualified_name (const char *decoded_name)
448 {
449 const char *result;
450
451 /* If the decoded name starts with '<', it means that the encoded
452 name does not follow standard naming conventions, and thus that
453 it is not your typical Ada symbol name. Trying to unqualify it
454 is therefore pointless and possibly erroneous. */
455 if (decoded_name[0] == '<')
456 return decoded_name;
457
458 result = strrchr (decoded_name, '.');
459 if (result != NULL)
460 result++; /* Skip the dot... */
461 else
462 result = decoded_name;
463
464 return result;
465 }
466
467 /* Return a string starting with '<', followed by STR, and '>'. */
468
469 static std::string
470 add_angle_brackets (const char *str)
471 {
472 return string_printf ("<%s>", str);
473 }
474
475 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
476 suffix of FIELD_NAME beginning "___". */
477
478 static int
479 field_name_match (const char *field_name, const char *target)
480 {
481 int len = strlen (target);
482
483 return
484 (strncmp (field_name, target, len) == 0
485 && (field_name[len] == '\0'
486 || (startswith (field_name + len, "___")
487 && strcmp (field_name + strlen (field_name) - 6,
488 "___XVN") != 0)));
489 }
490
491
492 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
493 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
494 and return its index. This function also handles fields whose name
495 have ___ suffixes because the compiler sometimes alters their name
496 by adding such a suffix to represent fields with certain constraints.
497 If the field could not be found, return a negative number if
498 MAYBE_MISSING is set. Otherwise raise an error. */
499
500 int
501 ada_get_field_index (const struct type *type, const char *field_name,
502 int maybe_missing)
503 {
504 int fieldno;
505 struct type *struct_type = check_typedef ((struct type *) type);
506
507 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
508 if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
509 return fieldno;
510
511 if (!maybe_missing)
512 error (_("Unable to find field %s in struct %s. Aborting"),
513 field_name, struct_type->name ());
514
515 return -1;
516 }
517
518 /* The length of the prefix of NAME prior to any "___" suffix. */
519
520 int
521 ada_name_prefix_len (const char *name)
522 {
523 if (name == NULL)
524 return 0;
525 else
526 {
527 const char *p = strstr (name, "___");
528
529 if (p == NULL)
530 return strlen (name);
531 else
532 return p - name;
533 }
534 }
535
536 /* Return non-zero if SUFFIX is a suffix of STR.
537 Return zero if STR is null. */
538
539 static int
540 is_suffix (const char *str, const char *suffix)
541 {
542 int len1, len2;
543
544 if (str == NULL)
545 return 0;
546 len1 = strlen (str);
547 len2 = strlen (suffix);
548 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
549 }
550
551 /* The contents of value VAL, treated as a value of type TYPE. The
552 result is an lval in memory if VAL is. */
553
554 static struct value *
555 coerce_unspec_val_to_type (struct value *val, struct type *type)
556 {
557 type = ada_check_typedef (type);
558 if (value_type (val) == type)
559 return val;
560 else
561 {
562 struct value *result;
563
564 /* Make sure that the object size is not unreasonable before
565 trying to allocate some memory for it. */
566 ada_ensure_varsize_limit (type);
567
568 if (value_optimized_out (val))
569 result = allocate_optimized_out_value (type);
570 else if (value_lazy (val)
571 /* Be careful not to make a lazy not_lval value. */
572 || (VALUE_LVAL (val) != not_lval
573 && TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val))))
574 result = allocate_value_lazy (type);
575 else
576 {
577 result = allocate_value (type);
578 value_contents_copy (result, 0, val, 0, TYPE_LENGTH (type));
579 }
580 set_value_component_location (result, val);
581 set_value_bitsize (result, value_bitsize (val));
582 set_value_bitpos (result, value_bitpos (val));
583 if (VALUE_LVAL (result) == lval_memory)
584 set_value_address (result, value_address (val));
585 return result;
586 }
587 }
588
589 static const gdb_byte *
590 cond_offset_host (const gdb_byte *valaddr, long offset)
591 {
592 if (valaddr == NULL)
593 return NULL;
594 else
595 return valaddr + offset;
596 }
597
598 static CORE_ADDR
599 cond_offset_target (CORE_ADDR address, long offset)
600 {
601 if (address == 0)
602 return 0;
603 else
604 return address + offset;
605 }
606
607 /* Issue a warning (as for the definition of warning in utils.c, but
608 with exactly one argument rather than ...), unless the limit on the
609 number of warnings has passed during the evaluation of the current
610 expression. */
611
612 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
613 provided by "complaint". */
614 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
615
616 static void
617 lim_warning (const char *format, ...)
618 {
619 va_list args;
620
621 va_start (args, format);
622 warnings_issued += 1;
623 if (warnings_issued <= warning_limit)
624 vwarning (format, args);
625
626 va_end (args);
627 }
628
629 /* Issue an error if the size of an object of type T is unreasonable,
630 i.e. if it would be a bad idea to allocate a value of this type in
631 GDB. */
632
633 void
634 ada_ensure_varsize_limit (const struct type *type)
635 {
636 if (TYPE_LENGTH (type) > varsize_limit)
637 error (_("object size is larger than varsize-limit"));
638 }
639
640 /* Maximum value of a SIZE-byte signed integer type. */
641 static LONGEST
642 max_of_size (int size)
643 {
644 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
645
646 return top_bit | (top_bit - 1);
647 }
648
649 /* Minimum value of a SIZE-byte signed integer type. */
650 static LONGEST
651 min_of_size (int size)
652 {
653 return -max_of_size (size) - 1;
654 }
655
656 /* Maximum value of a SIZE-byte unsigned integer type. */
657 static ULONGEST
658 umax_of_size (int size)
659 {
660 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
661
662 return top_bit | (top_bit - 1);
663 }
664
665 /* Maximum value of integral type T, as a signed quantity. */
666 static LONGEST
667 max_of_type (struct type *t)
668 {
669 if (t->is_unsigned ())
670 return (LONGEST) umax_of_size (TYPE_LENGTH (t));
671 else
672 return max_of_size (TYPE_LENGTH (t));
673 }
674
675 /* Minimum value of integral type T, as a signed quantity. */
676 static LONGEST
677 min_of_type (struct type *t)
678 {
679 if (t->is_unsigned ())
680 return 0;
681 else
682 return min_of_size (TYPE_LENGTH (t));
683 }
684
685 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
686 LONGEST
687 ada_discrete_type_high_bound (struct type *type)
688 {
689 type = resolve_dynamic_type (type, {}, 0);
690 switch (type->code ())
691 {
692 case TYPE_CODE_RANGE:
693 {
694 const dynamic_prop &high = type->bounds ()->high;
695
696 if (high.kind () == PROP_CONST)
697 return high.const_val ();
698 else
699 {
700 gdb_assert (high.kind () == PROP_UNDEFINED);
701
702 /* This happens when trying to evaluate a type's dynamic bound
703 without a live target. There is nothing relevant for us to
704 return here, so return 0. */
705 return 0;
706 }
707 }
708 case TYPE_CODE_ENUM:
709 return TYPE_FIELD_ENUMVAL (type, type->num_fields () - 1);
710 case TYPE_CODE_BOOL:
711 return 1;
712 case TYPE_CODE_CHAR:
713 case TYPE_CODE_INT:
714 return max_of_type (type);
715 default:
716 error (_("Unexpected type in ada_discrete_type_high_bound."));
717 }
718 }
719
720 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
721 LONGEST
722 ada_discrete_type_low_bound (struct type *type)
723 {
724 type = resolve_dynamic_type (type, {}, 0);
725 switch (type->code ())
726 {
727 case TYPE_CODE_RANGE:
728 {
729 const dynamic_prop &low = type->bounds ()->low;
730
731 if (low.kind () == PROP_CONST)
732 return low.const_val ();
733 else
734 {
735 gdb_assert (low.kind () == PROP_UNDEFINED);
736
737 /* This happens when trying to evaluate a type's dynamic bound
738 without a live target. There is nothing relevant for us to
739 return here, so return 0. */
740 return 0;
741 }
742 }
743 case TYPE_CODE_ENUM:
744 return TYPE_FIELD_ENUMVAL (type, 0);
745 case TYPE_CODE_BOOL:
746 return 0;
747 case TYPE_CODE_CHAR:
748 case TYPE_CODE_INT:
749 return min_of_type (type);
750 default:
751 error (_("Unexpected type in ada_discrete_type_low_bound."));
752 }
753 }
754
755 /* The identity on non-range types. For range types, the underlying
756 non-range scalar type. */
757
758 static struct type *
759 get_base_type (struct type *type)
760 {
761 while (type != NULL && type->code () == TYPE_CODE_RANGE)
762 {
763 if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
764 return type;
765 type = TYPE_TARGET_TYPE (type);
766 }
767 return type;
768 }
769
770 /* Return a decoded version of the given VALUE. This means returning
771 a value whose type is obtained by applying all the GNAT-specific
772 encodings, making the resulting type a static but standard description
773 of the initial type. */
774
775 struct value *
776 ada_get_decoded_value (struct value *value)
777 {
778 struct type *type = ada_check_typedef (value_type (value));
779
780 if (ada_is_array_descriptor_type (type)
781 || (ada_is_constrained_packed_array_type (type)
782 && type->code () != TYPE_CODE_PTR))
783 {
784 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
785 value = ada_coerce_to_simple_array_ptr (value);
786 else
787 value = ada_coerce_to_simple_array (value);
788 }
789 else
790 value = ada_to_fixed_value (value);
791
792 return value;
793 }
794
795 /* Same as ada_get_decoded_value, but with the given TYPE.
796 Because there is no associated actual value for this type,
797 the resulting type might be a best-effort approximation in
798 the case of dynamic types. */
799
800 struct type *
801 ada_get_decoded_type (struct type *type)
802 {
803 type = to_static_fixed_type (type);
804 if (ada_is_constrained_packed_array_type (type))
805 type = ada_coerce_to_simple_array_type (type);
806 return type;
807 }
808
809 \f
810
811 /* Language Selection */
812
813 /* If the main program is in Ada, return language_ada, otherwise return LANG
814 (the main program is in Ada iif the adainit symbol is found). */
815
816 static enum language
817 ada_update_initial_language (enum language lang)
818 {
819 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
820 return language_ada;
821
822 return lang;
823 }
824
825 /* If the main procedure is written in Ada, then return its name.
826 The result is good until the next call. Return NULL if the main
827 procedure doesn't appear to be in Ada. */
828
829 char *
830 ada_main_name (void)
831 {
832 struct bound_minimal_symbol msym;
833 static gdb::unique_xmalloc_ptr<char> main_program_name;
834
835 /* For Ada, the name of the main procedure is stored in a specific
836 string constant, generated by the binder. Look for that symbol,
837 extract its address, and then read that string. If we didn't find
838 that string, then most probably the main procedure is not written
839 in Ada. */
840 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
841
842 if (msym.minsym != NULL)
843 {
844 CORE_ADDR main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
845 if (main_program_name_addr == 0)
846 error (_("Invalid address for Ada main program name."));
847
848 main_program_name = target_read_string (main_program_name_addr, 1024);
849 return main_program_name.get ();
850 }
851
852 /* The main procedure doesn't seem to be in Ada. */
853 return NULL;
854 }
855 \f
856 /* Symbols */
857
858 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
859 of NULLs. */
860
861 const struct ada_opname_map ada_opname_table[] = {
862 {"Oadd", "\"+\"", BINOP_ADD},
863 {"Osubtract", "\"-\"", BINOP_SUB},
864 {"Omultiply", "\"*\"", BINOP_MUL},
865 {"Odivide", "\"/\"", BINOP_DIV},
866 {"Omod", "\"mod\"", BINOP_MOD},
867 {"Orem", "\"rem\"", BINOP_REM},
868 {"Oexpon", "\"**\"", BINOP_EXP},
869 {"Olt", "\"<\"", BINOP_LESS},
870 {"Ole", "\"<=\"", BINOP_LEQ},
871 {"Ogt", "\">\"", BINOP_GTR},
872 {"Oge", "\">=\"", BINOP_GEQ},
873 {"Oeq", "\"=\"", BINOP_EQUAL},
874 {"One", "\"/=\"", BINOP_NOTEQUAL},
875 {"Oand", "\"and\"", BINOP_BITWISE_AND},
876 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
877 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
878 {"Oconcat", "\"&\"", BINOP_CONCAT},
879 {"Oabs", "\"abs\"", UNOP_ABS},
880 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
881 {"Oadd", "\"+\"", UNOP_PLUS},
882 {"Osubtract", "\"-\"", UNOP_NEG},
883 {NULL, NULL}
884 };
885
886 /* The "encoded" form of DECODED, according to GNAT conventions. If
887 THROW_ERRORS, throw an error if invalid operator name is found.
888 Otherwise, return the empty string in that case. */
889
890 static std::string
891 ada_encode_1 (const char *decoded, bool throw_errors)
892 {
893 if (decoded == NULL)
894 return {};
895
896 std::string encoding_buffer;
897 for (const char *p = decoded; *p != '\0'; p += 1)
898 {
899 if (*p == '.')
900 encoding_buffer.append ("__");
901 else if (*p == '"')
902 {
903 const struct ada_opname_map *mapping;
904
905 for (mapping = ada_opname_table;
906 mapping->encoded != NULL
907 && !startswith (p, mapping->decoded); mapping += 1)
908 ;
909 if (mapping->encoded == NULL)
910 {
911 if (throw_errors)
912 error (_("invalid Ada operator name: %s"), p);
913 else
914 return {};
915 }
916 encoding_buffer.append (mapping->encoded);
917 break;
918 }
919 else
920 encoding_buffer.push_back (*p);
921 }
922
923 return encoding_buffer;
924 }
925
926 /* The "encoded" form of DECODED, according to GNAT conventions. */
927
928 std::string
929 ada_encode (const char *decoded)
930 {
931 return ada_encode_1 (decoded, true);
932 }
933
934 /* Return NAME folded to lower case, or, if surrounded by single
935 quotes, unfolded, but with the quotes stripped away. Result good
936 to next call. */
937
938 static const char *
939 ada_fold_name (gdb::string_view name)
940 {
941 static std::string fold_storage;
942
943 if (!name.empty () && name[0] == '\'')
944 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
945 else
946 {
947 fold_storage = gdb::to_string (name);
948 for (int i = 0; i < name.size (); i += 1)
949 fold_storage[i] = tolower (fold_storage[i]);
950 }
951
952 return fold_storage.c_str ();
953 }
954
955 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
956
957 static int
958 is_lower_alphanum (const char c)
959 {
960 return (isdigit (c) || (isalpha (c) && islower (c)));
961 }
962
963 /* ENCODED is the linkage name of a symbol and LEN contains its length.
964 This function saves in LEN the length of that same symbol name but
965 without either of these suffixes:
966 . .{DIGIT}+
967 . ${DIGIT}+
968 . ___{DIGIT}+
969 . __{DIGIT}+.
970
971 These are suffixes introduced by the compiler for entities such as
972 nested subprogram for instance, in order to avoid name clashes.
973 They do not serve any purpose for the debugger. */
974
975 static void
976 ada_remove_trailing_digits (const char *encoded, int *len)
977 {
978 if (*len > 1 && isdigit (encoded[*len - 1]))
979 {
980 int i = *len - 2;
981
982 while (i > 0 && isdigit (encoded[i]))
983 i--;
984 if (i >= 0 && encoded[i] == '.')
985 *len = i;
986 else if (i >= 0 && encoded[i] == '$')
987 *len = i;
988 else if (i >= 2 && startswith (encoded + i - 2, "___"))
989 *len = i - 2;
990 else if (i >= 1 && startswith (encoded + i - 1, "__"))
991 *len = i - 1;
992 }
993 }
994
995 /* Remove the suffix introduced by the compiler for protected object
996 subprograms. */
997
998 static void
999 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1000 {
1001 /* Remove trailing N. */
1002
1003 /* Protected entry subprograms are broken into two
1004 separate subprograms: The first one is unprotected, and has
1005 a 'N' suffix; the second is the protected version, and has
1006 the 'P' suffix. The second calls the first one after handling
1007 the protection. Since the P subprograms are internally generated,
1008 we leave these names undecoded, giving the user a clue that this
1009 entity is internal. */
1010
1011 if (*len > 1
1012 && encoded[*len - 1] == 'N'
1013 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1014 *len = *len - 1;
1015 }
1016
1017 /* If ENCODED follows the GNAT entity encoding conventions, then return
1018 the decoded form of ENCODED. Otherwise, return "<%s>" where "%s" is
1019 replaced by ENCODED. */
1020
1021 std::string
1022 ada_decode (const char *encoded)
1023 {
1024 int i, j;
1025 int len0;
1026 const char *p;
1027 int at_start_name;
1028 std::string decoded;
1029
1030 /* With function descriptors on PPC64, the value of a symbol named
1031 ".FN", if it exists, is the entry point of the function "FN". */
1032 if (encoded[0] == '.')
1033 encoded += 1;
1034
1035 /* The name of the Ada main procedure starts with "_ada_".
1036 This prefix is not part of the decoded name, so skip this part
1037 if we see this prefix. */
1038 if (startswith (encoded, "_ada_"))
1039 encoded += 5;
1040
1041 /* If the name starts with '_', then it is not a properly encoded
1042 name, so do not attempt to decode it. Similarly, if the name
1043 starts with '<', the name should not be decoded. */
1044 if (encoded[0] == '_' || encoded[0] == '<')
1045 goto Suppress;
1046
1047 len0 = strlen (encoded);
1048
1049 ada_remove_trailing_digits (encoded, &len0);
1050 ada_remove_po_subprogram_suffix (encoded, &len0);
1051
1052 /* Remove the ___X.* suffix if present. Do not forget to verify that
1053 the suffix is located before the current "end" of ENCODED. We want
1054 to avoid re-matching parts of ENCODED that have previously been
1055 marked as discarded (by decrementing LEN0). */
1056 p = strstr (encoded, "___");
1057 if (p != NULL && p - encoded < len0 - 3)
1058 {
1059 if (p[3] == 'X')
1060 len0 = p - encoded;
1061 else
1062 goto Suppress;
1063 }
1064
1065 /* Remove any trailing TKB suffix. It tells us that this symbol
1066 is for the body of a task, but that information does not actually
1067 appear in the decoded name. */
1068
1069 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1070 len0 -= 3;
1071
1072 /* Remove any trailing TB suffix. The TB suffix is slightly different
1073 from the TKB suffix because it is used for non-anonymous task
1074 bodies. */
1075
1076 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1077 len0 -= 2;
1078
1079 /* Remove trailing "B" suffixes. */
1080 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1081
1082 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1083 len0 -= 1;
1084
1085 /* Make decoded big enough for possible expansion by operator name. */
1086
1087 decoded.resize (2 * len0 + 1, 'X');
1088
1089 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1090
1091 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1092 {
1093 i = len0 - 2;
1094 while ((i >= 0 && isdigit (encoded[i]))
1095 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1096 i -= 1;
1097 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1098 len0 = i - 1;
1099 else if (encoded[i] == '$')
1100 len0 = i;
1101 }
1102
1103 /* The first few characters that are not alphabetic are not part
1104 of any encoding we use, so we can copy them over verbatim. */
1105
1106 for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1107 decoded[j] = encoded[i];
1108
1109 at_start_name = 1;
1110 while (i < len0)
1111 {
1112 /* Is this a symbol function? */
1113 if (at_start_name && encoded[i] == 'O')
1114 {
1115 int k;
1116
1117 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1118 {
1119 int op_len = strlen (ada_opname_table[k].encoded);
1120 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1121 op_len - 1) == 0)
1122 && !isalnum (encoded[i + op_len]))
1123 {
1124 strcpy (&decoded.front() + j, ada_opname_table[k].decoded);
1125 at_start_name = 0;
1126 i += op_len;
1127 j += strlen (ada_opname_table[k].decoded);
1128 break;
1129 }
1130 }
1131 if (ada_opname_table[k].encoded != NULL)
1132 continue;
1133 }
1134 at_start_name = 0;
1135
1136 /* Replace "TK__" with "__", which will eventually be translated
1137 into "." (just below). */
1138
1139 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1140 i += 2;
1141
1142 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1143 be translated into "." (just below). These are internal names
1144 generated for anonymous blocks inside which our symbol is nested. */
1145
1146 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1147 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1148 && isdigit (encoded [i+4]))
1149 {
1150 int k = i + 5;
1151
1152 while (k < len0 && isdigit (encoded[k]))
1153 k++; /* Skip any extra digit. */
1154
1155 /* Double-check that the "__B_{DIGITS}+" sequence we found
1156 is indeed followed by "__". */
1157 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1158 i = k;
1159 }
1160
1161 /* Remove _E{DIGITS}+[sb] */
1162
1163 /* Just as for protected object subprograms, there are 2 categories
1164 of subprograms created by the compiler for each entry. The first
1165 one implements the actual entry code, and has a suffix following
1166 the convention above; the second one implements the barrier and
1167 uses the same convention as above, except that the 'E' is replaced
1168 by a 'B'.
1169
1170 Just as above, we do not decode the name of barrier functions
1171 to give the user a clue that the code he is debugging has been
1172 internally generated. */
1173
1174 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1175 && isdigit (encoded[i+2]))
1176 {
1177 int k = i + 3;
1178
1179 while (k < len0 && isdigit (encoded[k]))
1180 k++;
1181
1182 if (k < len0
1183 && (encoded[k] == 'b' || encoded[k] == 's'))
1184 {
1185 k++;
1186 /* Just as an extra precaution, make sure that if this
1187 suffix is followed by anything else, it is a '_'.
1188 Otherwise, we matched this sequence by accident. */
1189 if (k == len0
1190 || (k < len0 && encoded[k] == '_'))
1191 i = k;
1192 }
1193 }
1194
1195 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1196 the GNAT front-end in protected object subprograms. */
1197
1198 if (i < len0 + 3
1199 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1200 {
1201 /* Backtrack a bit up until we reach either the begining of
1202 the encoded name, or "__". Make sure that we only find
1203 digits or lowercase characters. */
1204 const char *ptr = encoded + i - 1;
1205
1206 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1207 ptr--;
1208 if (ptr < encoded
1209 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1210 i++;
1211 }
1212
1213 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1214 {
1215 /* This is a X[bn]* sequence not separated from the previous
1216 part of the name with a non-alpha-numeric character (in other
1217 words, immediately following an alpha-numeric character), then
1218 verify that it is placed at the end of the encoded name. If
1219 not, then the encoding is not valid and we should abort the
1220 decoding. Otherwise, just skip it, it is used in body-nested
1221 package names. */
1222 do
1223 i += 1;
1224 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1225 if (i < len0)
1226 goto Suppress;
1227 }
1228 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1229 {
1230 /* Replace '__' by '.'. */
1231 decoded[j] = '.';
1232 at_start_name = 1;
1233 i += 2;
1234 j += 1;
1235 }
1236 else
1237 {
1238 /* It's a character part of the decoded name, so just copy it
1239 over. */
1240 decoded[j] = encoded[i];
1241 i += 1;
1242 j += 1;
1243 }
1244 }
1245 decoded.resize (j);
1246
1247 /* Decoded names should never contain any uppercase character.
1248 Double-check this, and abort the decoding if we find one. */
1249
1250 for (i = 0; i < decoded.length(); ++i)
1251 if (isupper (decoded[i]) || decoded[i] == ' ')
1252 goto Suppress;
1253
1254 return decoded;
1255
1256 Suppress:
1257 if (encoded[0] == '<')
1258 decoded = encoded;
1259 else
1260 decoded = '<' + std::string(encoded) + '>';
1261 return decoded;
1262
1263 }
1264
1265 /* Table for keeping permanent unique copies of decoded names. Once
1266 allocated, names in this table are never released. While this is a
1267 storage leak, it should not be significant unless there are massive
1268 changes in the set of decoded names in successive versions of a
1269 symbol table loaded during a single session. */
1270 static struct htab *decoded_names_store;
1271
1272 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1273 in the language-specific part of GSYMBOL, if it has not been
1274 previously computed. Tries to save the decoded name in the same
1275 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1276 in any case, the decoded symbol has a lifetime at least that of
1277 GSYMBOL).
1278 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1279 const, but nevertheless modified to a semantically equivalent form
1280 when a decoded name is cached in it. */
1281
1282 const char *
1283 ada_decode_symbol (const struct general_symbol_info *arg)
1284 {
1285 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1286 const char **resultp =
1287 &gsymbol->language_specific.demangled_name;
1288
1289 if (!gsymbol->ada_mangled)
1290 {
1291 std::string decoded = ada_decode (gsymbol->linkage_name ());
1292 struct obstack *obstack = gsymbol->language_specific.obstack;
1293
1294 gsymbol->ada_mangled = 1;
1295
1296 if (obstack != NULL)
1297 *resultp = obstack_strdup (obstack, decoded.c_str ());
1298 else
1299 {
1300 /* Sometimes, we can't find a corresponding objfile, in
1301 which case, we put the result on the heap. Since we only
1302 decode when needed, we hope this usually does not cause a
1303 significant memory leak (FIXME). */
1304
1305 char **slot = (char **) htab_find_slot (decoded_names_store,
1306 decoded.c_str (), INSERT);
1307
1308 if (*slot == NULL)
1309 *slot = xstrdup (decoded.c_str ());
1310 *resultp = *slot;
1311 }
1312 }
1313
1314 return *resultp;
1315 }
1316
1317 static char *
1318 ada_la_decode (const char *encoded, int options)
1319 {
1320 return xstrdup (ada_decode (encoded).c_str ());
1321 }
1322
1323 \f
1324
1325 /* Arrays */
1326
1327 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1328 generated by the GNAT compiler to describe the index type used
1329 for each dimension of an array, check whether it follows the latest
1330 known encoding. If not, fix it up to conform to the latest encoding.
1331 Otherwise, do nothing. This function also does nothing if
1332 INDEX_DESC_TYPE is NULL.
1333
1334 The GNAT encoding used to describe the array index type evolved a bit.
1335 Initially, the information would be provided through the name of each
1336 field of the structure type only, while the type of these fields was
1337 described as unspecified and irrelevant. The debugger was then expected
1338 to perform a global type lookup using the name of that field in order
1339 to get access to the full index type description. Because these global
1340 lookups can be very expensive, the encoding was later enhanced to make
1341 the global lookup unnecessary by defining the field type as being
1342 the full index type description.
1343
1344 The purpose of this routine is to allow us to support older versions
1345 of the compiler by detecting the use of the older encoding, and by
1346 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1347 we essentially replace each field's meaningless type by the associated
1348 index subtype). */
1349
1350 void
1351 ada_fixup_array_indexes_type (struct type *index_desc_type)
1352 {
1353 int i;
1354
1355 if (index_desc_type == NULL)
1356 return;
1357 gdb_assert (index_desc_type->num_fields () > 0);
1358
1359 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1360 to check one field only, no need to check them all). If not, return
1361 now.
1362
1363 If our INDEX_DESC_TYPE was generated using the older encoding,
1364 the field type should be a meaningless integer type whose name
1365 is not equal to the field name. */
1366 if (index_desc_type->field (0).type ()->name () != NULL
1367 && strcmp (index_desc_type->field (0).type ()->name (),
1368 TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
1369 return;
1370
1371 /* Fixup each field of INDEX_DESC_TYPE. */
1372 for (i = 0; i < index_desc_type->num_fields (); i++)
1373 {
1374 const char *name = TYPE_FIELD_NAME (index_desc_type, i);
1375 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1376
1377 if (raw_type)
1378 index_desc_type->field (i).set_type (raw_type);
1379 }
1380 }
1381
1382 /* The desc_* routines return primitive portions of array descriptors
1383 (fat pointers). */
1384
1385 /* The descriptor or array type, if any, indicated by TYPE; removes
1386 level of indirection, if needed. */
1387
1388 static struct type *
1389 desc_base_type (struct type *type)
1390 {
1391 if (type == NULL)
1392 return NULL;
1393 type = ada_check_typedef (type);
1394 if (type->code () == TYPE_CODE_TYPEDEF)
1395 type = ada_typedef_target_type (type);
1396
1397 if (type != NULL
1398 && (type->code () == TYPE_CODE_PTR
1399 || type->code () == TYPE_CODE_REF))
1400 return ada_check_typedef (TYPE_TARGET_TYPE (type));
1401 else
1402 return type;
1403 }
1404
1405 /* True iff TYPE indicates a "thin" array pointer type. */
1406
1407 static int
1408 is_thin_pntr (struct type *type)
1409 {
1410 return
1411 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1412 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1413 }
1414
1415 /* The descriptor type for thin pointer type TYPE. */
1416
1417 static struct type *
1418 thin_descriptor_type (struct type *type)
1419 {
1420 struct type *base_type = desc_base_type (type);
1421
1422 if (base_type == NULL)
1423 return NULL;
1424 if (is_suffix (ada_type_name (base_type), "___XVE"))
1425 return base_type;
1426 else
1427 {
1428 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1429
1430 if (alt_type == NULL)
1431 return base_type;
1432 else
1433 return alt_type;
1434 }
1435 }
1436
1437 /* A pointer to the array data for thin-pointer value VAL. */
1438
1439 static struct value *
1440 thin_data_pntr (struct value *val)
1441 {
1442 struct type *type = ada_check_typedef (value_type (val));
1443 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1444
1445 data_type = lookup_pointer_type (data_type);
1446
1447 if (type->code () == TYPE_CODE_PTR)
1448 return value_cast (data_type, value_copy (val));
1449 else
1450 return value_from_longest (data_type, value_address (val));
1451 }
1452
1453 /* True iff TYPE indicates a "thick" array pointer type. */
1454
1455 static int
1456 is_thick_pntr (struct type *type)
1457 {
1458 type = desc_base_type (type);
1459 return (type != NULL && type->code () == TYPE_CODE_STRUCT
1460 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1461 }
1462
1463 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1464 pointer to one, the type of its bounds data; otherwise, NULL. */
1465
1466 static struct type *
1467 desc_bounds_type (struct type *type)
1468 {
1469 struct type *r;
1470
1471 type = desc_base_type (type);
1472
1473 if (type == NULL)
1474 return NULL;
1475 else if (is_thin_pntr (type))
1476 {
1477 type = thin_descriptor_type (type);
1478 if (type == NULL)
1479 return NULL;
1480 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1481 if (r != NULL)
1482 return ada_check_typedef (r);
1483 }
1484 else if (type->code () == TYPE_CODE_STRUCT)
1485 {
1486 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1487 if (r != NULL)
1488 return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1489 }
1490 return NULL;
1491 }
1492
1493 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1494 one, a pointer to its bounds data. Otherwise NULL. */
1495
1496 static struct value *
1497 desc_bounds (struct value *arr)
1498 {
1499 struct type *type = ada_check_typedef (value_type (arr));
1500
1501 if (is_thin_pntr (type))
1502 {
1503 struct type *bounds_type =
1504 desc_bounds_type (thin_descriptor_type (type));
1505 LONGEST addr;
1506
1507 if (bounds_type == NULL)
1508 error (_("Bad GNAT array descriptor"));
1509
1510 /* NOTE: The following calculation is not really kosher, but
1511 since desc_type is an XVE-encoded type (and shouldn't be),
1512 the correct calculation is a real pain. FIXME (and fix GCC). */
1513 if (type->code () == TYPE_CODE_PTR)
1514 addr = value_as_long (arr);
1515 else
1516 addr = value_address (arr);
1517
1518 return
1519 value_from_longest (lookup_pointer_type (bounds_type),
1520 addr - TYPE_LENGTH (bounds_type));
1521 }
1522
1523 else if (is_thick_pntr (type))
1524 {
1525 struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1526 _("Bad GNAT array descriptor"));
1527 struct type *p_bounds_type = value_type (p_bounds);
1528
1529 if (p_bounds_type
1530 && p_bounds_type->code () == TYPE_CODE_PTR)
1531 {
1532 struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1533
1534 if (target_type->is_stub ())
1535 p_bounds = value_cast (lookup_pointer_type
1536 (ada_check_typedef (target_type)),
1537 p_bounds);
1538 }
1539 else
1540 error (_("Bad GNAT array descriptor"));
1541
1542 return p_bounds;
1543 }
1544 else
1545 return NULL;
1546 }
1547
1548 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1549 position of the field containing the address of the bounds data. */
1550
1551 static int
1552 fat_pntr_bounds_bitpos (struct type *type)
1553 {
1554 return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1555 }
1556
1557 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1558 size of the field containing the address of the bounds data. */
1559
1560 static int
1561 fat_pntr_bounds_bitsize (struct type *type)
1562 {
1563 type = desc_base_type (type);
1564
1565 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1566 return TYPE_FIELD_BITSIZE (type, 1);
1567 else
1568 return 8 * TYPE_LENGTH (ada_check_typedef (type->field (1).type ()));
1569 }
1570
1571 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1572 pointer to one, the type of its array data (a array-with-no-bounds type);
1573 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1574 data. */
1575
1576 static struct type *
1577 desc_data_target_type (struct type *type)
1578 {
1579 type = desc_base_type (type);
1580
1581 /* NOTE: The following is bogus; see comment in desc_bounds. */
1582 if (is_thin_pntr (type))
1583 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1584 else if (is_thick_pntr (type))
1585 {
1586 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1587
1588 if (data_type
1589 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1590 return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1591 }
1592
1593 return NULL;
1594 }
1595
1596 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1597 its array data. */
1598
1599 static struct value *
1600 desc_data (struct value *arr)
1601 {
1602 struct type *type = value_type (arr);
1603
1604 if (is_thin_pntr (type))
1605 return thin_data_pntr (arr);
1606 else if (is_thick_pntr (type))
1607 return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1608 _("Bad GNAT array descriptor"));
1609 else
1610 return NULL;
1611 }
1612
1613
1614 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1615 position of the field containing the address of the data. */
1616
1617 static int
1618 fat_pntr_data_bitpos (struct type *type)
1619 {
1620 return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1621 }
1622
1623 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1624 size of the field containing the address of the data. */
1625
1626 static int
1627 fat_pntr_data_bitsize (struct type *type)
1628 {
1629 type = desc_base_type (type);
1630
1631 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1632 return TYPE_FIELD_BITSIZE (type, 0);
1633 else
1634 return TARGET_CHAR_BIT * TYPE_LENGTH (type->field (0).type ());
1635 }
1636
1637 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1638 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1639 bound, if WHICH is 1. The first bound is I=1. */
1640
1641 static struct value *
1642 desc_one_bound (struct value *bounds, int i, int which)
1643 {
1644 char bound_name[20];
1645 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1646 which ? 'U' : 'L', i - 1);
1647 return value_struct_elt (&bounds, NULL, bound_name, NULL,
1648 _("Bad GNAT array descriptor bounds"));
1649 }
1650
1651 /* If BOUNDS is an array-bounds structure type, return the bit position
1652 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1653 bound, if WHICH is 1. The first bound is I=1. */
1654
1655 static int
1656 desc_bound_bitpos (struct type *type, int i, int which)
1657 {
1658 return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1659 }
1660
1661 /* If BOUNDS is an array-bounds structure type, return the bit field size
1662 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1663 bound, if WHICH is 1. The first bound is I=1. */
1664
1665 static int
1666 desc_bound_bitsize (struct type *type, int i, int which)
1667 {
1668 type = desc_base_type (type);
1669
1670 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1671 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1672 else
1673 return 8 * TYPE_LENGTH (type->field (2 * i + which - 2).type ());
1674 }
1675
1676 /* If TYPE is the type of an array-bounds structure, the type of its
1677 Ith bound (numbering from 1). Otherwise, NULL. */
1678
1679 static struct type *
1680 desc_index_type (struct type *type, int i)
1681 {
1682 type = desc_base_type (type);
1683
1684 if (type->code () == TYPE_CODE_STRUCT)
1685 {
1686 char bound_name[20];
1687 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
1688 return lookup_struct_elt_type (type, bound_name, 1);
1689 }
1690 else
1691 return NULL;
1692 }
1693
1694 /* The number of index positions in the array-bounds type TYPE.
1695 Return 0 if TYPE is NULL. */
1696
1697 static int
1698 desc_arity (struct type *type)
1699 {
1700 type = desc_base_type (type);
1701
1702 if (type != NULL)
1703 return type->num_fields () / 2;
1704 return 0;
1705 }
1706
1707 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
1708 an array descriptor type (representing an unconstrained array
1709 type). */
1710
1711 static int
1712 ada_is_direct_array_type (struct type *type)
1713 {
1714 if (type == NULL)
1715 return 0;
1716 type = ada_check_typedef (type);
1717 return (type->code () == TYPE_CODE_ARRAY
1718 || ada_is_array_descriptor_type (type));
1719 }
1720
1721 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1722 * to one. */
1723
1724 static int
1725 ada_is_array_type (struct type *type)
1726 {
1727 while (type != NULL
1728 && (type->code () == TYPE_CODE_PTR
1729 || type->code () == TYPE_CODE_REF))
1730 type = TYPE_TARGET_TYPE (type);
1731 return ada_is_direct_array_type (type);
1732 }
1733
1734 /* Non-zero iff TYPE is a simple array type or pointer to one. */
1735
1736 int
1737 ada_is_simple_array_type (struct type *type)
1738 {
1739 if (type == NULL)
1740 return 0;
1741 type = ada_check_typedef (type);
1742 return (type->code () == TYPE_CODE_ARRAY
1743 || (type->code () == TYPE_CODE_PTR
1744 && (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ()
1745 == TYPE_CODE_ARRAY)));
1746 }
1747
1748 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
1749
1750 int
1751 ada_is_array_descriptor_type (struct type *type)
1752 {
1753 struct type *data_type = desc_data_target_type (type);
1754
1755 if (type == NULL)
1756 return 0;
1757 type = ada_check_typedef (type);
1758 return (data_type != NULL
1759 && data_type->code () == TYPE_CODE_ARRAY
1760 && desc_arity (desc_bounds_type (type)) > 0);
1761 }
1762
1763 /* Non-zero iff type is a partially mal-formed GNAT array
1764 descriptor. FIXME: This is to compensate for some problems with
1765 debugging output from GNAT. Re-examine periodically to see if it
1766 is still needed. */
1767
1768 int
1769 ada_is_bogus_array_descriptor (struct type *type)
1770 {
1771 return
1772 type != NULL
1773 && type->code () == TYPE_CODE_STRUCT
1774 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1775 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1776 && !ada_is_array_descriptor_type (type);
1777 }
1778
1779
1780 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1781 (fat pointer) returns the type of the array data described---specifically,
1782 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
1783 in from the descriptor; otherwise, they are left unspecified. If
1784 the ARR denotes a null array descriptor and BOUNDS is non-zero,
1785 returns NULL. The result is simply the type of ARR if ARR is not
1786 a descriptor. */
1787
1788 static struct type *
1789 ada_type_of_array (struct value *arr, int bounds)
1790 {
1791 if (ada_is_constrained_packed_array_type (value_type (arr)))
1792 return decode_constrained_packed_array_type (value_type (arr));
1793
1794 if (!ada_is_array_descriptor_type (value_type (arr)))
1795 return value_type (arr);
1796
1797 if (!bounds)
1798 {
1799 struct type *array_type =
1800 ada_check_typedef (desc_data_target_type (value_type (arr)));
1801
1802 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1803 TYPE_FIELD_BITSIZE (array_type, 0) =
1804 decode_packed_array_bitsize (value_type (arr));
1805
1806 return array_type;
1807 }
1808 else
1809 {
1810 struct type *elt_type;
1811 int arity;
1812 struct value *descriptor;
1813
1814 elt_type = ada_array_element_type (value_type (arr), -1);
1815 arity = ada_array_arity (value_type (arr));
1816
1817 if (elt_type == NULL || arity == 0)
1818 return ada_check_typedef (value_type (arr));
1819
1820 descriptor = desc_bounds (arr);
1821 if (value_as_long (descriptor) == 0)
1822 return NULL;
1823 while (arity > 0)
1824 {
1825 struct type *range_type = alloc_type_copy (value_type (arr));
1826 struct type *array_type = alloc_type_copy (value_type (arr));
1827 struct value *low = desc_one_bound (descriptor, arity, 0);
1828 struct value *high = desc_one_bound (descriptor, arity, 1);
1829
1830 arity -= 1;
1831 create_static_range_type (range_type, value_type (low),
1832 longest_to_int (value_as_long (low)),
1833 longest_to_int (value_as_long (high)));
1834 elt_type = create_array_type (array_type, elt_type, range_type);
1835
1836 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1837 {
1838 /* We need to store the element packed bitsize, as well as
1839 recompute the array size, because it was previously
1840 computed based on the unpacked element size. */
1841 LONGEST lo = value_as_long (low);
1842 LONGEST hi = value_as_long (high);
1843
1844 TYPE_FIELD_BITSIZE (elt_type, 0) =
1845 decode_packed_array_bitsize (value_type (arr));
1846 /* If the array has no element, then the size is already
1847 zero, and does not need to be recomputed. */
1848 if (lo < hi)
1849 {
1850 int array_bitsize =
1851 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
1852
1853 TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
1854 }
1855 }
1856 }
1857
1858 return lookup_pointer_type (elt_type);
1859 }
1860 }
1861
1862 /* If ARR does not represent an array, returns ARR unchanged.
1863 Otherwise, returns either a standard GDB array with bounds set
1864 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1865 GDB array. Returns NULL if ARR is a null fat pointer. */
1866
1867 struct value *
1868 ada_coerce_to_simple_array_ptr (struct value *arr)
1869 {
1870 if (ada_is_array_descriptor_type (value_type (arr)))
1871 {
1872 struct type *arrType = ada_type_of_array (arr, 1);
1873
1874 if (arrType == NULL)
1875 return NULL;
1876 return value_cast (arrType, value_copy (desc_data (arr)));
1877 }
1878 else if (ada_is_constrained_packed_array_type (value_type (arr)))
1879 return decode_constrained_packed_array (arr);
1880 else
1881 return arr;
1882 }
1883
1884 /* If ARR does not represent an array, returns ARR unchanged.
1885 Otherwise, returns a standard GDB array describing ARR (which may
1886 be ARR itself if it already is in the proper form). */
1887
1888 struct value *
1889 ada_coerce_to_simple_array (struct value *arr)
1890 {
1891 if (ada_is_array_descriptor_type (value_type (arr)))
1892 {
1893 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1894
1895 if (arrVal == NULL)
1896 error (_("Bounds unavailable for null array pointer."));
1897 ada_ensure_varsize_limit (TYPE_TARGET_TYPE (value_type (arrVal)));
1898 return value_ind (arrVal);
1899 }
1900 else if (ada_is_constrained_packed_array_type (value_type (arr)))
1901 return decode_constrained_packed_array (arr);
1902 else
1903 return arr;
1904 }
1905
1906 /* If TYPE represents a GNAT array type, return it translated to an
1907 ordinary GDB array type (possibly with BITSIZE fields indicating
1908 packing). For other types, is the identity. */
1909
1910 struct type *
1911 ada_coerce_to_simple_array_type (struct type *type)
1912 {
1913 if (ada_is_constrained_packed_array_type (type))
1914 return decode_constrained_packed_array_type (type);
1915
1916 if (ada_is_array_descriptor_type (type))
1917 return ada_check_typedef (desc_data_target_type (type));
1918
1919 return type;
1920 }
1921
1922 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
1923
1924 static int
1925 ada_is_gnat_encoded_packed_array_type (struct type *type)
1926 {
1927 if (type == NULL)
1928 return 0;
1929 type = desc_base_type (type);
1930 type = ada_check_typedef (type);
1931 return
1932 ada_type_name (type) != NULL
1933 && strstr (ada_type_name (type), "___XP") != NULL;
1934 }
1935
1936 /* Non-zero iff TYPE represents a standard GNAT constrained
1937 packed-array type. */
1938
1939 int
1940 ada_is_constrained_packed_array_type (struct type *type)
1941 {
1942 return ada_is_gnat_encoded_packed_array_type (type)
1943 && !ada_is_array_descriptor_type (type);
1944 }
1945
1946 /* Non-zero iff TYPE represents an array descriptor for a
1947 unconstrained packed-array type. */
1948
1949 static int
1950 ada_is_unconstrained_packed_array_type (struct type *type)
1951 {
1952 if (!ada_is_array_descriptor_type (type))
1953 return 0;
1954
1955 if (ada_is_gnat_encoded_packed_array_type (type))
1956 return 1;
1957
1958 /* If we saw GNAT encodings, then the above code is sufficient.
1959 However, with minimal encodings, we will just have a thick
1960 pointer instead. */
1961 if (is_thick_pntr (type))
1962 {
1963 type = desc_base_type (type);
1964 /* The structure's first field is a pointer to an array, so this
1965 fetches the array type. */
1966 type = TYPE_TARGET_TYPE (type->field (0).type ());
1967 /* Now we can see if the array elements are packed. */
1968 return TYPE_FIELD_BITSIZE (type, 0) > 0;
1969 }
1970
1971 return 0;
1972 }
1973
1974 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
1975 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
1976
1977 static bool
1978 ada_is_any_packed_array_type (struct type *type)
1979 {
1980 return (ada_is_constrained_packed_array_type (type)
1981 || (type->code () == TYPE_CODE_ARRAY
1982 && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
1983 }
1984
1985 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
1986 return the size of its elements in bits. */
1987
1988 static long
1989 decode_packed_array_bitsize (struct type *type)
1990 {
1991 const char *raw_name;
1992 const char *tail;
1993 long bits;
1994
1995 /* Access to arrays implemented as fat pointers are encoded as a typedef
1996 of the fat pointer type. We need the name of the fat pointer type
1997 to do the decoding, so strip the typedef layer. */
1998 if (type->code () == TYPE_CODE_TYPEDEF)
1999 type = ada_typedef_target_type (type);
2000
2001 raw_name = ada_type_name (ada_check_typedef (type));
2002 if (!raw_name)
2003 raw_name = ada_type_name (desc_base_type (type));
2004
2005 if (!raw_name)
2006 return 0;
2007
2008 tail = strstr (raw_name, "___XP");
2009 if (tail == nullptr)
2010 {
2011 gdb_assert (is_thick_pntr (type));
2012 /* The structure's first field is a pointer to an array, so this
2013 fetches the array type. */
2014 type = TYPE_TARGET_TYPE (type->field (0).type ());
2015 /* Now we can see if the array elements are packed. */
2016 return TYPE_FIELD_BITSIZE (type, 0);
2017 }
2018
2019 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2020 {
2021 lim_warning
2022 (_("could not understand bit size information on packed array"));
2023 return 0;
2024 }
2025
2026 return bits;
2027 }
2028
2029 /* Given that TYPE is a standard GDB array type with all bounds filled
2030 in, and that the element size of its ultimate scalar constituents
2031 (that is, either its elements, or, if it is an array of arrays, its
2032 elements' elements, etc.) is *ELT_BITS, return an identical type,
2033 but with the bit sizes of its elements (and those of any
2034 constituent arrays) recorded in the BITSIZE components of its
2035 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2036 in bits.
2037
2038 Note that, for arrays whose index type has an XA encoding where
2039 a bound references a record discriminant, getting that discriminant,
2040 and therefore the actual value of that bound, is not possible
2041 because none of the given parameters gives us access to the record.
2042 This function assumes that it is OK in the context where it is being
2043 used to return an array whose bounds are still dynamic and where
2044 the length is arbitrary. */
2045
2046 static struct type *
2047 constrained_packed_array_type (struct type *type, long *elt_bits)
2048 {
2049 struct type *new_elt_type;
2050 struct type *new_type;
2051 struct type *index_type_desc;
2052 struct type *index_type;
2053 LONGEST low_bound, high_bound;
2054
2055 type = ada_check_typedef (type);
2056 if (type->code () != TYPE_CODE_ARRAY)
2057 return type;
2058
2059 index_type_desc = ada_find_parallel_type (type, "___XA");
2060 if (index_type_desc)
2061 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2062 NULL);
2063 else
2064 index_type = type->index_type ();
2065
2066 new_type = alloc_type_copy (type);
2067 new_elt_type =
2068 constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2069 elt_bits);
2070 create_array_type (new_type, new_elt_type, index_type);
2071 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2072 new_type->set_name (ada_type_name (type));
2073
2074 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2075 && is_dynamic_type (check_typedef (index_type)))
2076 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2077 low_bound = high_bound = 0;
2078 if (high_bound < low_bound)
2079 *elt_bits = TYPE_LENGTH (new_type) = 0;
2080 else
2081 {
2082 *elt_bits *= (high_bound - low_bound + 1);
2083 TYPE_LENGTH (new_type) =
2084 (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2085 }
2086
2087 new_type->set_is_fixed_instance (true);
2088 return new_type;
2089 }
2090
2091 /* The array type encoded by TYPE, where
2092 ada_is_constrained_packed_array_type (TYPE). */
2093
2094 static struct type *
2095 decode_constrained_packed_array_type (struct type *type)
2096 {
2097 const char *raw_name = ada_type_name (ada_check_typedef (type));
2098 char *name;
2099 const char *tail;
2100 struct type *shadow_type;
2101 long bits;
2102
2103 if (!raw_name)
2104 raw_name = ada_type_name (desc_base_type (type));
2105
2106 if (!raw_name)
2107 return NULL;
2108
2109 name = (char *) alloca (strlen (raw_name) + 1);
2110 tail = strstr (raw_name, "___XP");
2111 type = desc_base_type (type);
2112
2113 memcpy (name, raw_name, tail - raw_name);
2114 name[tail - raw_name] = '\000';
2115
2116 shadow_type = ada_find_parallel_type_with_name (type, name);
2117
2118 if (shadow_type == NULL)
2119 {
2120 lim_warning (_("could not find bounds information on packed array"));
2121 return NULL;
2122 }
2123 shadow_type = check_typedef (shadow_type);
2124
2125 if (shadow_type->code () != TYPE_CODE_ARRAY)
2126 {
2127 lim_warning (_("could not understand bounds "
2128 "information on packed array"));
2129 return NULL;
2130 }
2131
2132 bits = decode_packed_array_bitsize (type);
2133 return constrained_packed_array_type (shadow_type, &bits);
2134 }
2135
2136 /* Helper function for decode_constrained_packed_array. Set the field
2137 bitsize on a series of packed arrays. Returns the number of
2138 elements in TYPE. */
2139
2140 static LONGEST
2141 recursively_update_array_bitsize (struct type *type)
2142 {
2143 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2144
2145 LONGEST low, high;
2146 if (!get_discrete_bounds (type->index_type (), &low, &high)
2147 || low > high)
2148 return 0;
2149 LONGEST our_len = high - low + 1;
2150
2151 struct type *elt_type = TYPE_TARGET_TYPE (type);
2152 if (elt_type->code () == TYPE_CODE_ARRAY)
2153 {
2154 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2155 LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2156 TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2157
2158 TYPE_LENGTH (type) = ((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2159 / HOST_CHAR_BIT);
2160 }
2161
2162 return our_len;
2163 }
2164
2165 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2166 array, returns a simple array that denotes that array. Its type is a
2167 standard GDB array type except that the BITSIZEs of the array
2168 target types are set to the number of bits in each element, and the
2169 type length is set appropriately. */
2170
2171 static struct value *
2172 decode_constrained_packed_array (struct value *arr)
2173 {
2174 struct type *type;
2175
2176 /* If our value is a pointer, then dereference it. Likewise if
2177 the value is a reference. Make sure that this operation does not
2178 cause the target type to be fixed, as this would indirectly cause
2179 this array to be decoded. The rest of the routine assumes that
2180 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2181 and "value_ind" routines to perform the dereferencing, as opposed
2182 to using "ada_coerce_ref" or "ada_value_ind". */
2183 arr = coerce_ref (arr);
2184 if (ada_check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2185 arr = value_ind (arr);
2186
2187 type = decode_constrained_packed_array_type (value_type (arr));
2188 if (type == NULL)
2189 {
2190 error (_("can't unpack array"));
2191 return NULL;
2192 }
2193
2194 /* Decoding the packed array type could not correctly set the field
2195 bitsizes for any dimension except the innermost, because the
2196 bounds may be variable and were not passed to that function. So,
2197 we further resolve the array bounds here and then update the
2198 sizes. */
2199 const gdb_byte *valaddr = value_contents_for_printing (arr);
2200 CORE_ADDR address = value_address (arr);
2201 gdb::array_view<const gdb_byte> view
2202 = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
2203 type = resolve_dynamic_type (type, view, address);
2204 recursively_update_array_bitsize (type);
2205
2206 if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2207 && ada_is_modular_type (value_type (arr)))
2208 {
2209 /* This is a (right-justified) modular type representing a packed
2210 array with no wrapper. In order to interpret the value through
2211 the (left-justified) packed array type we just built, we must
2212 first left-justify it. */
2213 int bit_size, bit_pos;
2214 ULONGEST mod;
2215
2216 mod = ada_modulus (value_type (arr)) - 1;
2217 bit_size = 0;
2218 while (mod > 0)
2219 {
2220 bit_size += 1;
2221 mod >>= 1;
2222 }
2223 bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2224 arr = ada_value_primitive_packed_val (arr, NULL,
2225 bit_pos / HOST_CHAR_BIT,
2226 bit_pos % HOST_CHAR_BIT,
2227 bit_size,
2228 type);
2229 }
2230
2231 return coerce_unspec_val_to_type (arr, type);
2232 }
2233
2234
2235 /* The value of the element of packed array ARR at the ARITY indices
2236 given in IND. ARR must be a simple array. */
2237
2238 static struct value *
2239 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2240 {
2241 int i;
2242 int bits, elt_off, bit_off;
2243 long elt_total_bit_offset;
2244 struct type *elt_type;
2245 struct value *v;
2246
2247 bits = 0;
2248 elt_total_bit_offset = 0;
2249 elt_type = ada_check_typedef (value_type (arr));
2250 for (i = 0; i < arity; i += 1)
2251 {
2252 if (elt_type->code () != TYPE_CODE_ARRAY
2253 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2254 error
2255 (_("attempt to do packed indexing of "
2256 "something other than a packed array"));
2257 else
2258 {
2259 struct type *range_type = elt_type->index_type ();
2260 LONGEST lowerbound, upperbound;
2261 LONGEST idx;
2262
2263 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2264 {
2265 lim_warning (_("don't know bounds of array"));
2266 lowerbound = upperbound = 0;
2267 }
2268
2269 idx = pos_atr (ind[i]);
2270 if (idx < lowerbound || idx > upperbound)
2271 lim_warning (_("packed array index %ld out of bounds"),
2272 (long) idx);
2273 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2274 elt_total_bit_offset += (idx - lowerbound) * bits;
2275 elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2276 }
2277 }
2278 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2279 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2280
2281 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2282 bits, elt_type);
2283 return v;
2284 }
2285
2286 /* Non-zero iff TYPE includes negative integer values. */
2287
2288 static int
2289 has_negatives (struct type *type)
2290 {
2291 switch (type->code ())
2292 {
2293 default:
2294 return 0;
2295 case TYPE_CODE_INT:
2296 return !type->is_unsigned ();
2297 case TYPE_CODE_RANGE:
2298 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2299 }
2300 }
2301
2302 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2303 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2304 the unpacked buffer.
2305
2306 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2307 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2308
2309 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2310 zero otherwise.
2311
2312 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2313
2314 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2315
2316 static void
2317 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2318 gdb_byte *unpacked, int unpacked_len,
2319 int is_big_endian, int is_signed_type,
2320 int is_scalar)
2321 {
2322 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2323 int src_idx; /* Index into the source area */
2324 int src_bytes_left; /* Number of source bytes left to process. */
2325 int srcBitsLeft; /* Number of source bits left to move */
2326 int unusedLS; /* Number of bits in next significant
2327 byte of source that are unused */
2328
2329 int unpacked_idx; /* Index into the unpacked buffer */
2330 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2331
2332 unsigned long accum; /* Staging area for bits being transferred */
2333 int accumSize; /* Number of meaningful bits in accum */
2334 unsigned char sign;
2335
2336 /* Transmit bytes from least to most significant; delta is the direction
2337 the indices move. */
2338 int delta = is_big_endian ? -1 : 1;
2339
2340 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2341 bits from SRC. .*/
2342 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2343 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2344 bit_size, unpacked_len);
2345
2346 srcBitsLeft = bit_size;
2347 src_bytes_left = src_len;
2348 unpacked_bytes_left = unpacked_len;
2349 sign = 0;
2350
2351 if (is_big_endian)
2352 {
2353 src_idx = src_len - 1;
2354 if (is_signed_type
2355 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2356 sign = ~0;
2357
2358 unusedLS =
2359 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2360 % HOST_CHAR_BIT;
2361
2362 if (is_scalar)
2363 {
2364 accumSize = 0;
2365 unpacked_idx = unpacked_len - 1;
2366 }
2367 else
2368 {
2369 /* Non-scalar values must be aligned at a byte boundary... */
2370 accumSize =
2371 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2372 /* ... And are placed at the beginning (most-significant) bytes
2373 of the target. */
2374 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2375 unpacked_bytes_left = unpacked_idx + 1;
2376 }
2377 }
2378 else
2379 {
2380 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2381
2382 src_idx = unpacked_idx = 0;
2383 unusedLS = bit_offset;
2384 accumSize = 0;
2385
2386 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2387 sign = ~0;
2388 }
2389
2390 accum = 0;
2391 while (src_bytes_left > 0)
2392 {
2393 /* Mask for removing bits of the next source byte that are not
2394 part of the value. */
2395 unsigned int unusedMSMask =
2396 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2397 1;
2398 /* Sign-extend bits for this byte. */
2399 unsigned int signMask = sign & ~unusedMSMask;
2400
2401 accum |=
2402 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2403 accumSize += HOST_CHAR_BIT - unusedLS;
2404 if (accumSize >= HOST_CHAR_BIT)
2405 {
2406 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2407 accumSize -= HOST_CHAR_BIT;
2408 accum >>= HOST_CHAR_BIT;
2409 unpacked_bytes_left -= 1;
2410 unpacked_idx += delta;
2411 }
2412 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2413 unusedLS = 0;
2414 src_bytes_left -= 1;
2415 src_idx += delta;
2416 }
2417 while (unpacked_bytes_left > 0)
2418 {
2419 accum |= sign << accumSize;
2420 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2421 accumSize -= HOST_CHAR_BIT;
2422 if (accumSize < 0)
2423 accumSize = 0;
2424 accum >>= HOST_CHAR_BIT;
2425 unpacked_bytes_left -= 1;
2426 unpacked_idx += delta;
2427 }
2428 }
2429
2430 /* Create a new value of type TYPE from the contents of OBJ starting
2431 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2432 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2433 assigning through the result will set the field fetched from.
2434 VALADDR is ignored unless OBJ is NULL, in which case,
2435 VALADDR+OFFSET must address the start of storage containing the
2436 packed value. The value returned in this case is never an lval.
2437 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2438
2439 struct value *
2440 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2441 long offset, int bit_offset, int bit_size,
2442 struct type *type)
2443 {
2444 struct value *v;
2445 const gdb_byte *src; /* First byte containing data to unpack */
2446 gdb_byte *unpacked;
2447 const int is_scalar = is_scalar_type (type);
2448 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2449 gdb::byte_vector staging;
2450
2451 type = ada_check_typedef (type);
2452
2453 if (obj == NULL)
2454 src = valaddr + offset;
2455 else
2456 src = value_contents (obj) + offset;
2457
2458 if (is_dynamic_type (type))
2459 {
2460 /* The length of TYPE might by dynamic, so we need to resolve
2461 TYPE in order to know its actual size, which we then use
2462 to create the contents buffer of the value we return.
2463 The difficulty is that the data containing our object is
2464 packed, and therefore maybe not at a byte boundary. So, what
2465 we do, is unpack the data into a byte-aligned buffer, and then
2466 use that buffer as our object's value for resolving the type. */
2467 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2468 staging.resize (staging_len);
2469
2470 ada_unpack_from_contents (src, bit_offset, bit_size,
2471 staging.data (), staging.size (),
2472 is_big_endian, has_negatives (type),
2473 is_scalar);
2474 type = resolve_dynamic_type (type, staging, 0);
2475 if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2476 {
2477 /* This happens when the length of the object is dynamic,
2478 and is actually smaller than the space reserved for it.
2479 For instance, in an array of variant records, the bit_size
2480 we're given is the array stride, which is constant and
2481 normally equal to the maximum size of its element.
2482 But, in reality, each element only actually spans a portion
2483 of that stride. */
2484 bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2485 }
2486 }
2487
2488 if (obj == NULL)
2489 {
2490 v = allocate_value (type);
2491 src = valaddr + offset;
2492 }
2493 else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2494 {
2495 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2496 gdb_byte *buf;
2497
2498 v = value_at (type, value_address (obj) + offset);
2499 buf = (gdb_byte *) alloca (src_len);
2500 read_memory (value_address (v), buf, src_len);
2501 src = buf;
2502 }
2503 else
2504 {
2505 v = allocate_value (type);
2506 src = value_contents (obj) + offset;
2507 }
2508
2509 if (obj != NULL)
2510 {
2511 long new_offset = offset;
2512
2513 set_value_component_location (v, obj);
2514 set_value_bitpos (v, bit_offset + value_bitpos (obj));
2515 set_value_bitsize (v, bit_size);
2516 if (value_bitpos (v) >= HOST_CHAR_BIT)
2517 {
2518 ++new_offset;
2519 set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2520 }
2521 set_value_offset (v, new_offset);
2522
2523 /* Also set the parent value. This is needed when trying to
2524 assign a new value (in inferior memory). */
2525 set_value_parent (v, obj);
2526 }
2527 else
2528 set_value_bitsize (v, bit_size);
2529 unpacked = value_contents_writeable (v);
2530
2531 if (bit_size == 0)
2532 {
2533 memset (unpacked, 0, TYPE_LENGTH (type));
2534 return v;
2535 }
2536
2537 if (staging.size () == TYPE_LENGTH (type))
2538 {
2539 /* Small short-cut: If we've unpacked the data into a buffer
2540 of the same size as TYPE's length, then we can reuse that,
2541 instead of doing the unpacking again. */
2542 memcpy (unpacked, staging.data (), staging.size ());
2543 }
2544 else
2545 ada_unpack_from_contents (src, bit_offset, bit_size,
2546 unpacked, TYPE_LENGTH (type),
2547 is_big_endian, has_negatives (type), is_scalar);
2548
2549 return v;
2550 }
2551
2552 /* Store the contents of FROMVAL into the location of TOVAL.
2553 Return a new value with the location of TOVAL and contents of
2554 FROMVAL. Handles assignment into packed fields that have
2555 floating-point or non-scalar types. */
2556
2557 static struct value *
2558 ada_value_assign (struct value *toval, struct value *fromval)
2559 {
2560 struct type *type = value_type (toval);
2561 int bits = value_bitsize (toval);
2562
2563 toval = ada_coerce_ref (toval);
2564 fromval = ada_coerce_ref (fromval);
2565
2566 if (ada_is_direct_array_type (value_type (toval)))
2567 toval = ada_coerce_to_simple_array (toval);
2568 if (ada_is_direct_array_type (value_type (fromval)))
2569 fromval = ada_coerce_to_simple_array (fromval);
2570
2571 if (!deprecated_value_modifiable (toval))
2572 error (_("Left operand of assignment is not a modifiable lvalue."));
2573
2574 if (VALUE_LVAL (toval) == lval_memory
2575 && bits > 0
2576 && (type->code () == TYPE_CODE_FLT
2577 || type->code () == TYPE_CODE_STRUCT))
2578 {
2579 int len = (value_bitpos (toval)
2580 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2581 int from_size;
2582 gdb_byte *buffer = (gdb_byte *) alloca (len);
2583 struct value *val;
2584 CORE_ADDR to_addr = value_address (toval);
2585
2586 if (type->code () == TYPE_CODE_FLT)
2587 fromval = value_cast (type, fromval);
2588
2589 read_memory (to_addr, buffer, len);
2590 from_size = value_bitsize (fromval);
2591 if (from_size == 0)
2592 from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2593
2594 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2595 ULONGEST from_offset = 0;
2596 if (is_big_endian && is_scalar_type (value_type (fromval)))
2597 from_offset = from_size - bits;
2598 copy_bitwise (buffer, value_bitpos (toval),
2599 value_contents (fromval), from_offset,
2600 bits, is_big_endian);
2601 write_memory_with_notification (to_addr, buffer, len);
2602
2603 val = value_copy (toval);
2604 memcpy (value_contents_raw (val), value_contents (fromval),
2605 TYPE_LENGTH (type));
2606 deprecated_set_value_type (val, type);
2607
2608 return val;
2609 }
2610
2611 return value_assign (toval, fromval);
2612 }
2613
2614
2615 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2616 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2617 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2618 COMPONENT, and not the inferior's memory. The current contents
2619 of COMPONENT are ignored.
2620
2621 Although not part of the initial design, this function also works
2622 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2623 had a null address, and COMPONENT had an address which is equal to
2624 its offset inside CONTAINER. */
2625
2626 static void
2627 value_assign_to_component (struct value *container, struct value *component,
2628 struct value *val)
2629 {
2630 LONGEST offset_in_container =
2631 (LONGEST) (value_address (component) - value_address (container));
2632 int bit_offset_in_container =
2633 value_bitpos (component) - value_bitpos (container);
2634 int bits;
2635
2636 val = value_cast (value_type (component), val);
2637
2638 if (value_bitsize (component) == 0)
2639 bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2640 else
2641 bits = value_bitsize (component);
2642
2643 if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2644 {
2645 int src_offset;
2646
2647 if (is_scalar_type (check_typedef (value_type (component))))
2648 src_offset
2649 = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2650 else
2651 src_offset = 0;
2652 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2653 value_bitpos (container) + bit_offset_in_container,
2654 value_contents (val), src_offset, bits, 1);
2655 }
2656 else
2657 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2658 value_bitpos (container) + bit_offset_in_container,
2659 value_contents (val), 0, bits, 0);
2660 }
2661
2662 /* Determine if TYPE is an access to an unconstrained array. */
2663
2664 bool
2665 ada_is_access_to_unconstrained_array (struct type *type)
2666 {
2667 return (type->code () == TYPE_CODE_TYPEDEF
2668 && is_thick_pntr (ada_typedef_target_type (type)));
2669 }
2670
2671 /* The value of the element of array ARR at the ARITY indices given in IND.
2672 ARR may be either a simple array, GNAT array descriptor, or pointer
2673 thereto. */
2674
2675 struct value *
2676 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2677 {
2678 int k;
2679 struct value *elt;
2680 struct type *elt_type;
2681
2682 elt = ada_coerce_to_simple_array (arr);
2683
2684 elt_type = ada_check_typedef (value_type (elt));
2685 if (elt_type->code () == TYPE_CODE_ARRAY
2686 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2687 return value_subscript_packed (elt, arity, ind);
2688
2689 for (k = 0; k < arity; k += 1)
2690 {
2691 struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
2692
2693 if (elt_type->code () != TYPE_CODE_ARRAY)
2694 error (_("too many subscripts (%d expected)"), k);
2695
2696 elt = value_subscript (elt, pos_atr (ind[k]));
2697
2698 if (ada_is_access_to_unconstrained_array (saved_elt_type)
2699 && value_type (elt)->code () != TYPE_CODE_TYPEDEF)
2700 {
2701 /* The element is a typedef to an unconstrained array,
2702 except that the value_subscript call stripped the
2703 typedef layer. The typedef layer is GNAT's way to
2704 specify that the element is, at the source level, an
2705 access to the unconstrained array, rather than the
2706 unconstrained array. So, we need to restore that
2707 typedef layer, which we can do by forcing the element's
2708 type back to its original type. Otherwise, the returned
2709 value is going to be printed as the array, rather
2710 than as an access. Another symptom of the same issue
2711 would be that an expression trying to dereference the
2712 element would also be improperly rejected. */
2713 deprecated_set_value_type (elt, saved_elt_type);
2714 }
2715
2716 elt_type = ada_check_typedef (value_type (elt));
2717 }
2718
2719 return elt;
2720 }
2721
2722 /* Assuming ARR is a pointer to a GDB array, the value of the element
2723 of *ARR at the ARITY indices given in IND.
2724 Does not read the entire array into memory.
2725
2726 Note: Unlike what one would expect, this function is used instead of
2727 ada_value_subscript for basically all non-packed array types. The reason
2728 for this is that a side effect of doing our own pointer arithmetics instead
2729 of relying on value_subscript is that there is no implicit typedef peeling.
2730 This is important for arrays of array accesses, where it allows us to
2731 preserve the fact that the array's element is an array access, where the
2732 access part os encoded in a typedef layer. */
2733
2734 static struct value *
2735 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
2736 {
2737 int k;
2738 struct value *array_ind = ada_value_ind (arr);
2739 struct type *type
2740 = check_typedef (value_enclosing_type (array_ind));
2741
2742 if (type->code () == TYPE_CODE_ARRAY
2743 && TYPE_FIELD_BITSIZE (type, 0) > 0)
2744 return value_subscript_packed (array_ind, arity, ind);
2745
2746 for (k = 0; k < arity; k += 1)
2747 {
2748 LONGEST lwb, upb;
2749
2750 if (type->code () != TYPE_CODE_ARRAY)
2751 error (_("too many subscripts (%d expected)"), k);
2752 arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2753 value_copy (arr));
2754 get_discrete_bounds (type->index_type (), &lwb, &upb);
2755 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
2756 type = TYPE_TARGET_TYPE (type);
2757 }
2758
2759 return value_ind (arr);
2760 }
2761
2762 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2763 actual type of ARRAY_PTR is ignored), returns the Ada slice of
2764 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
2765 this array is LOW, as per Ada rules. */
2766 static struct value *
2767 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2768 int low, int high)
2769 {
2770 struct type *type0 = ada_check_typedef (type);
2771 struct type *base_index_type = TYPE_TARGET_TYPE (type0->index_type ());
2772 struct type *index_type
2773 = create_static_range_type (NULL, base_index_type, low, high);
2774 struct type *slice_type = create_array_type_with_stride
2775 (NULL, TYPE_TARGET_TYPE (type0), index_type,
2776 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
2777 TYPE_FIELD_BITSIZE (type0, 0));
2778 int base_low = ada_discrete_type_low_bound (type0->index_type ());
2779 gdb::optional<LONGEST> base_low_pos, low_pos;
2780 CORE_ADDR base;
2781
2782 low_pos = discrete_position (base_index_type, low);
2783 base_low_pos = discrete_position (base_index_type, base_low);
2784
2785 if (!low_pos.has_value () || !base_low_pos.has_value ())
2786 {
2787 warning (_("unable to get positions in slice, use bounds instead"));
2788 low_pos = low;
2789 base_low_pos = base_low;
2790 }
2791
2792 ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
2793 if (stride == 0)
2794 stride = TYPE_LENGTH (TYPE_TARGET_TYPE (type0));
2795
2796 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
2797 return value_at_lazy (slice_type, base);
2798 }
2799
2800
2801 static struct value *
2802 ada_value_slice (struct value *array, int low, int high)
2803 {
2804 struct type *type = ada_check_typedef (value_type (array));
2805 struct type *base_index_type = TYPE_TARGET_TYPE (type->index_type ());
2806 struct type *index_type
2807 = create_static_range_type (NULL, type->index_type (), low, high);
2808 struct type *slice_type = create_array_type_with_stride
2809 (NULL, TYPE_TARGET_TYPE (type), index_type,
2810 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
2811 TYPE_FIELD_BITSIZE (type, 0));
2812 gdb::optional<LONGEST> low_pos, high_pos;
2813
2814
2815 low_pos = discrete_position (base_index_type, low);
2816 high_pos = discrete_position (base_index_type, high);
2817
2818 if (!low_pos.has_value () || !high_pos.has_value ())
2819 {
2820 warning (_("unable to get positions in slice, use bounds instead"));
2821 low_pos = low;
2822 high_pos = high;
2823 }
2824
2825 return value_cast (slice_type,
2826 value_slice (array, low, *high_pos - *low_pos + 1));
2827 }
2828
2829 /* If type is a record type in the form of a standard GNAT array
2830 descriptor, returns the number of dimensions for type. If arr is a
2831 simple array, returns the number of "array of"s that prefix its
2832 type designation. Otherwise, returns 0. */
2833
2834 int
2835 ada_array_arity (struct type *type)
2836 {
2837 int arity;
2838
2839 if (type == NULL)
2840 return 0;
2841
2842 type = desc_base_type (type);
2843
2844 arity = 0;
2845 if (type->code () == TYPE_CODE_STRUCT)
2846 return desc_arity (desc_bounds_type (type));
2847 else
2848 while (type->code () == TYPE_CODE_ARRAY)
2849 {
2850 arity += 1;
2851 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2852 }
2853
2854 return arity;
2855 }
2856
2857 /* If TYPE is a record type in the form of a standard GNAT array
2858 descriptor or a simple array type, returns the element type for
2859 TYPE after indexing by NINDICES indices, or by all indices if
2860 NINDICES is -1. Otherwise, returns NULL. */
2861
2862 struct type *
2863 ada_array_element_type (struct type *type, int nindices)
2864 {
2865 type = desc_base_type (type);
2866
2867 if (type->code () == TYPE_CODE_STRUCT)
2868 {
2869 int k;
2870 struct type *p_array_type;
2871
2872 p_array_type = desc_data_target_type (type);
2873
2874 k = ada_array_arity (type);
2875 if (k == 0)
2876 return NULL;
2877
2878 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
2879 if (nindices >= 0 && k > nindices)
2880 k = nindices;
2881 while (k > 0 && p_array_type != NULL)
2882 {
2883 p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2884 k -= 1;
2885 }
2886 return p_array_type;
2887 }
2888 else if (type->code () == TYPE_CODE_ARRAY)
2889 {
2890 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
2891 {
2892 type = TYPE_TARGET_TYPE (type);
2893 nindices -= 1;
2894 }
2895 return type;
2896 }
2897
2898 return NULL;
2899 }
2900
2901 /* See ada-lang.h. */
2902
2903 struct type *
2904 ada_index_type (struct type *type, int n, const char *name)
2905 {
2906 struct type *result_type;
2907
2908 type = desc_base_type (type);
2909
2910 if (n < 0 || n > ada_array_arity (type))
2911 error (_("invalid dimension number to '%s"), name);
2912
2913 if (ada_is_simple_array_type (type))
2914 {
2915 int i;
2916
2917 for (i = 1; i < n; i += 1)
2918 type = TYPE_TARGET_TYPE (type);
2919 result_type = TYPE_TARGET_TYPE (type->index_type ());
2920 /* FIXME: The stabs type r(0,0);bound;bound in an array type
2921 has a target type of TYPE_CODE_UNDEF. We compensate here, but
2922 perhaps stabsread.c would make more sense. */
2923 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
2924 result_type = NULL;
2925 }
2926 else
2927 {
2928 result_type = desc_index_type (desc_bounds_type (type), n);
2929 if (result_type == NULL)
2930 error (_("attempt to take bound of something that is not an array"));
2931 }
2932
2933 return result_type;
2934 }
2935
2936 /* Given that arr is an array type, returns the lower bound of the
2937 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2938 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
2939 array-descriptor type. It works for other arrays with bounds supplied
2940 by run-time quantities other than discriminants. */
2941
2942 static LONGEST
2943 ada_array_bound_from_type (struct type *arr_type, int n, int which)
2944 {
2945 struct type *type, *index_type_desc, *index_type;
2946 int i;
2947
2948 gdb_assert (which == 0 || which == 1);
2949
2950 if (ada_is_constrained_packed_array_type (arr_type))
2951 arr_type = decode_constrained_packed_array_type (arr_type);
2952
2953 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2954 return (LONGEST) - which;
2955
2956 if (arr_type->code () == TYPE_CODE_PTR)
2957 type = TYPE_TARGET_TYPE (arr_type);
2958 else
2959 type = arr_type;
2960
2961 if (type->is_fixed_instance ())
2962 {
2963 /* The array has already been fixed, so we do not need to
2964 check the parallel ___XA type again. That encoding has
2965 already been applied, so ignore it now. */
2966 index_type_desc = NULL;
2967 }
2968 else
2969 {
2970 index_type_desc = ada_find_parallel_type (type, "___XA");
2971 ada_fixup_array_indexes_type (index_type_desc);
2972 }
2973
2974 if (index_type_desc != NULL)
2975 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
2976 NULL);
2977 else
2978 {
2979 struct type *elt_type = check_typedef (type);
2980
2981 for (i = 1; i < n; i++)
2982 elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
2983
2984 index_type = elt_type->index_type ();
2985 }
2986
2987 return
2988 (LONGEST) (which == 0
2989 ? ada_discrete_type_low_bound (index_type)
2990 : ada_discrete_type_high_bound (index_type));
2991 }
2992
2993 /* Given that arr is an array value, returns the lower bound of the
2994 nth index (numbering from 1) if WHICH is 0, and the upper bound if
2995 WHICH is 1. This routine will also work for arrays with bounds
2996 supplied by run-time quantities other than discriminants. */
2997
2998 static LONGEST
2999 ada_array_bound (struct value *arr, int n, int which)
3000 {
3001 struct type *arr_type;
3002
3003 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3004 arr = value_ind (arr);
3005 arr_type = value_enclosing_type (arr);
3006
3007 if (ada_is_constrained_packed_array_type (arr_type))
3008 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3009 else if (ada_is_simple_array_type (arr_type))
3010 return ada_array_bound_from_type (arr_type, n, which);
3011 else
3012 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3013 }
3014
3015 /* Given that arr is an array value, returns the length of the
3016 nth index. This routine will also work for arrays with bounds
3017 supplied by run-time quantities other than discriminants.
3018 Does not work for arrays indexed by enumeration types with representation
3019 clauses at the moment. */
3020
3021 static LONGEST
3022 ada_array_length (struct value *arr, int n)
3023 {
3024 struct type *arr_type, *index_type;
3025 int low, high;
3026
3027 if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3028 arr = value_ind (arr);
3029 arr_type = value_enclosing_type (arr);
3030
3031 if (ada_is_constrained_packed_array_type (arr_type))
3032 return ada_array_length (decode_constrained_packed_array (arr), n);
3033
3034 if (ada_is_simple_array_type (arr_type))
3035 {
3036 low = ada_array_bound_from_type (arr_type, n, 0);
3037 high = ada_array_bound_from_type (arr_type, n, 1);
3038 }
3039 else
3040 {
3041 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3042 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3043 }
3044
3045 arr_type = check_typedef (arr_type);
3046 index_type = ada_index_type (arr_type, n, "length");
3047 if (index_type != NULL)
3048 {
3049 struct type *base_type;
3050 if (index_type->code () == TYPE_CODE_RANGE)
3051 base_type = TYPE_TARGET_TYPE (index_type);
3052 else
3053 base_type = index_type;
3054
3055 low = pos_atr (value_from_longest (base_type, low));
3056 high = pos_atr (value_from_longest (base_type, high));
3057 }
3058 return high - low + 1;
3059 }
3060
3061 /* An array whose type is that of ARR_TYPE (an array type), with
3062 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3063 less than LOW, then LOW-1 is used. */
3064
3065 static struct value *
3066 empty_array (struct type *arr_type, int low, int high)
3067 {
3068 struct type *arr_type0 = ada_check_typedef (arr_type);
3069 struct type *index_type
3070 = create_static_range_type
3071 (NULL, TYPE_TARGET_TYPE (arr_type0->index_type ()), low,
3072 high < low ? low - 1 : high);
3073 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3074
3075 return allocate_value (create_array_type (NULL, elt_type, index_type));
3076 }
3077 \f
3078
3079 /* Name resolution */
3080
3081 /* The "decoded" name for the user-definable Ada operator corresponding
3082 to OP. */
3083
3084 static const char *
3085 ada_decoded_op_name (enum exp_opcode op)
3086 {
3087 int i;
3088
3089 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3090 {
3091 if (ada_opname_table[i].op == op)
3092 return ada_opname_table[i].decoded;
3093 }
3094 error (_("Could not find operator name for opcode"));
3095 }
3096
3097 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3098 in a listing of choices during disambiguation (see sort_choices, below).
3099 The idea is that overloadings of a subprogram name from the
3100 same package should sort in their source order. We settle for ordering
3101 such symbols by their trailing number (__N or $N). */
3102
3103 static int
3104 encoded_ordered_before (const char *N0, const char *N1)
3105 {
3106 if (N1 == NULL)
3107 return 0;
3108 else if (N0 == NULL)
3109 return 1;
3110 else
3111 {
3112 int k0, k1;
3113
3114 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3115 ;
3116 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3117 ;
3118 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3119 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3120 {
3121 int n0, n1;
3122
3123 n0 = k0;
3124 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3125 n0 -= 1;
3126 n1 = k1;
3127 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3128 n1 -= 1;
3129 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3130 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3131 }
3132 return (strcmp (N0, N1) < 0);
3133 }
3134 }
3135
3136 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3137 encoded names. */
3138
3139 static void
3140 sort_choices (struct block_symbol syms[], int nsyms)
3141 {
3142 int i;
3143
3144 for (i = 1; i < nsyms; i += 1)
3145 {
3146 struct block_symbol sym = syms[i];
3147 int j;
3148
3149 for (j = i - 1; j >= 0; j -= 1)
3150 {
3151 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3152 sym.symbol->linkage_name ()))
3153 break;
3154 syms[j + 1] = syms[j];
3155 }
3156 syms[j + 1] = sym;
3157 }
3158 }
3159
3160 /* Whether GDB should display formals and return types for functions in the
3161 overloads selection menu. */
3162 static bool print_signatures = true;
3163
3164 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3165 all but functions, the signature is just the name of the symbol. For
3166 functions, this is the name of the function, the list of types for formals
3167 and the return type (if any). */
3168
3169 static void
3170 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3171 const struct type_print_options *flags)
3172 {
3173 struct type *type = SYMBOL_TYPE (sym);
3174
3175 fprintf_filtered (stream, "%s", sym->print_name ());
3176 if (!print_signatures
3177 || type == NULL
3178 || type->code () != TYPE_CODE_FUNC)
3179 return;
3180
3181 if (type->num_fields () > 0)
3182 {
3183 int i;
3184
3185 fprintf_filtered (stream, " (");
3186 for (i = 0; i < type->num_fields (); ++i)
3187 {
3188 if (i > 0)
3189 fprintf_filtered (stream, "; ");
3190 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3191 flags);
3192 }
3193 fprintf_filtered (stream, ")");
3194 }
3195 if (TYPE_TARGET_TYPE (type) != NULL
3196 && TYPE_TARGET_TYPE (type)->code () != TYPE_CODE_VOID)
3197 {
3198 fprintf_filtered (stream, " return ");
3199 ada_print_type (TYPE_TARGET_TYPE (type), NULL, stream, -1, 0, flags);
3200 }
3201 }
3202
3203 /* Read and validate a set of numeric choices from the user in the
3204 range 0 .. N_CHOICES-1. Place the results in increasing
3205 order in CHOICES[0 .. N-1], and return N.
3206
3207 The user types choices as a sequence of numbers on one line
3208 separated by blanks, encoding them as follows:
3209
3210 + A choice of 0 means to cancel the selection, throwing an error.
3211 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3212 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3213
3214 The user is not allowed to choose more than MAX_RESULTS values.
3215
3216 ANNOTATION_SUFFIX, if present, is used to annotate the input
3217 prompts (for use with the -f switch). */
3218
3219 static int
3220 get_selections (int *choices, int n_choices, int max_results,
3221 int is_all_choice, const char *annotation_suffix)
3222 {
3223 const char *args;
3224 const char *prompt;
3225 int n_chosen;
3226 int first_choice = is_all_choice ? 2 : 1;
3227
3228 prompt = getenv ("PS2");
3229 if (prompt == NULL)
3230 prompt = "> ";
3231
3232 args = command_line_input (prompt, annotation_suffix);
3233
3234 if (args == NULL)
3235 error_no_arg (_("one or more choice numbers"));
3236
3237 n_chosen = 0;
3238
3239 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3240 order, as given in args. Choices are validated. */
3241 while (1)
3242 {
3243 char *args2;
3244 int choice, j;
3245
3246 args = skip_spaces (args);
3247 if (*args == '\0' && n_chosen == 0)
3248 error_no_arg (_("one or more choice numbers"));
3249 else if (*args == '\0')
3250 break;
3251
3252 choice = strtol (args, &args2, 10);
3253 if (args == args2 || choice < 0
3254 || choice > n_choices + first_choice - 1)
3255 error (_("Argument must be choice number"));
3256 args = args2;
3257
3258 if (choice == 0)
3259 error (_("cancelled"));
3260
3261 if (choice < first_choice)
3262 {
3263 n_chosen = n_choices;
3264 for (j = 0; j < n_choices; j += 1)
3265 choices[j] = j;
3266 break;
3267 }
3268 choice -= first_choice;
3269
3270 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3271 {
3272 }
3273
3274 if (j < 0 || choice != choices[j])
3275 {
3276 int k;
3277
3278 for (k = n_chosen - 1; k > j; k -= 1)
3279 choices[k + 1] = choices[k];
3280 choices[j + 1] = choice;
3281 n_chosen += 1;
3282 }
3283 }
3284
3285 if (n_chosen > max_results)
3286 error (_("Select no more than %d of the above"), max_results);
3287
3288 return n_chosen;
3289 }
3290
3291 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3292 by asking the user (if necessary), returning the number selected,
3293 and setting the first elements of SYMS items. Error if no symbols
3294 selected. */
3295
3296 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3297 to be re-integrated one of these days. */
3298
3299 static int
3300 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3301 {
3302 int i;
3303 int *chosen = XALLOCAVEC (int , nsyms);
3304 int n_chosen;
3305 int first_choice = (max_results == 1) ? 1 : 2;
3306 const char *select_mode = multiple_symbols_select_mode ();
3307
3308 if (max_results < 1)
3309 error (_("Request to select 0 symbols!"));
3310 if (nsyms <= 1)
3311 return nsyms;
3312
3313 if (select_mode == multiple_symbols_cancel)
3314 error (_("\
3315 canceled because the command is ambiguous\n\
3316 See set/show multiple-symbol."));
3317
3318 /* If select_mode is "all", then return all possible symbols.
3319 Only do that if more than one symbol can be selected, of course.
3320 Otherwise, display the menu as usual. */
3321 if (select_mode == multiple_symbols_all && max_results > 1)
3322 return nsyms;
3323
3324 printf_filtered (_("[0] cancel\n"));
3325 if (max_results > 1)
3326 printf_filtered (_("[1] all\n"));
3327
3328 sort_choices (syms, nsyms);
3329
3330 for (i = 0; i < nsyms; i += 1)
3331 {
3332 if (syms[i].symbol == NULL)
3333 continue;
3334
3335 if (SYMBOL_CLASS (syms[i].symbol) == LOC_BLOCK)
3336 {
3337 struct symtab_and_line sal =
3338 find_function_start_sal (syms[i].symbol, 1);
3339
3340 printf_filtered ("[%d] ", i + first_choice);
3341 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3342 &type_print_raw_options);
3343 if (sal.symtab == NULL)
3344 printf_filtered (_(" at %p[<no source file available>%p]:%d\n"),
3345 metadata_style.style ().ptr (), nullptr, sal.line);
3346 else
3347 printf_filtered
3348 (_(" at %ps:%d\n"),
3349 styled_string (file_name_style.style (),
3350 symtab_to_filename_for_display (sal.symtab)),
3351 sal.line);
3352 continue;
3353 }
3354 else
3355 {
3356 int is_enumeral =
3357 (SYMBOL_CLASS (syms[i].symbol) == LOC_CONST
3358 && SYMBOL_TYPE (syms[i].symbol) != NULL
3359 && SYMBOL_TYPE (syms[i].symbol)->code () == TYPE_CODE_ENUM);
3360 struct symtab *symtab = NULL;
3361
3362 if (SYMBOL_OBJFILE_OWNED (syms[i].symbol))
3363 symtab = symbol_symtab (syms[i].symbol);
3364
3365 if (SYMBOL_LINE (syms[i].symbol) != 0 && symtab != NULL)
3366 {
3367 printf_filtered ("[%d] ", i + first_choice);
3368 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3369 &type_print_raw_options);
3370 printf_filtered (_(" at %s:%d\n"),
3371 symtab_to_filename_for_display (symtab),
3372 SYMBOL_LINE (syms[i].symbol));
3373 }
3374 else if (is_enumeral
3375 && SYMBOL_TYPE (syms[i].symbol)->name () != NULL)
3376 {
3377 printf_filtered (("[%d] "), i + first_choice);
3378 ada_print_type (SYMBOL_TYPE (syms[i].symbol), NULL,
3379 gdb_stdout, -1, 0, &type_print_raw_options);
3380 printf_filtered (_("'(%s) (enumeral)\n"),
3381 syms[i].symbol->print_name ());
3382 }
3383 else
3384 {
3385 printf_filtered ("[%d] ", i + first_choice);
3386 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3387 &type_print_raw_options);
3388
3389 if (symtab != NULL)
3390 printf_filtered (is_enumeral
3391 ? _(" in %s (enumeral)\n")
3392 : _(" at %s:?\n"),
3393 symtab_to_filename_for_display (symtab));
3394 else
3395 printf_filtered (is_enumeral
3396 ? _(" (enumeral)\n")
3397 : _(" at ?\n"));
3398 }
3399 }
3400 }
3401
3402 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3403 "overload-choice");
3404
3405 for (i = 0; i < n_chosen; i += 1)
3406 syms[i] = syms[chosen[i]];
3407
3408 return n_chosen;
3409 }
3410
3411 /* See ada-lang.h. */
3412
3413 block_symbol
3414 ada_find_operator_symbol (enum exp_opcode op, int parse_completion,
3415 int nargs, value *argvec[])
3416 {
3417 if (possible_user_operator_p (op, argvec))
3418 {
3419 std::vector<struct block_symbol> candidates
3420 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3421 NULL, VAR_DOMAIN);
3422
3423 int i = ada_resolve_function (candidates, argvec,
3424 nargs, ada_decoded_op_name (op), NULL,
3425 parse_completion);
3426 if (i >= 0)
3427 return candidates[i];
3428 }
3429 return {};
3430 }
3431
3432 /* See ada-lang.h. */
3433
3434 block_symbol
3435 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3436 struct type *context_type,
3437 int parse_completion,
3438 int nargs, value *argvec[],
3439 innermost_block_tracker *tracker)
3440 {
3441 std::vector<struct block_symbol> candidates
3442 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3443
3444 int i;
3445 if (candidates.size () == 1)
3446 i = 0;
3447 else
3448 {
3449 i = ada_resolve_function
3450 (candidates,
3451 argvec, nargs,
3452 sym->linkage_name (),
3453 context_type, parse_completion);
3454 if (i < 0)
3455 error (_("Could not find a match for %s"), sym->print_name ());
3456 }
3457
3458 tracker->update (candidates[i]);
3459 return candidates[i];
3460 }
3461
3462 /* See ada-lang.h. */
3463
3464 block_symbol
3465 ada_resolve_variable (struct symbol *sym, const struct block *block,
3466 struct type *context_type,
3467 int parse_completion,
3468 int deprocedure_p,
3469 innermost_block_tracker *tracker)
3470 {
3471 std::vector<struct block_symbol> candidates
3472 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3473
3474 if (std::any_of (candidates.begin (),
3475 candidates.end (),
3476 [] (block_symbol &bsym)
3477 {
3478 switch (SYMBOL_CLASS (bsym.symbol))
3479 {
3480 case LOC_REGISTER:
3481 case LOC_ARG:
3482 case LOC_REF_ARG:
3483 case LOC_REGPARM_ADDR:
3484 case LOC_LOCAL:
3485 case LOC_COMPUTED:
3486 return true;
3487 default:
3488 return false;
3489 }
3490 }))
3491 {
3492 /* Types tend to get re-introduced locally, so if there
3493 are any local symbols that are not types, first filter
3494 out all types. */
3495 candidates.erase
3496 (std::remove_if
3497 (candidates.begin (),
3498 candidates.end (),
3499 [] (block_symbol &bsym)
3500 {
3501 return SYMBOL_CLASS (bsym.symbol) == LOC_TYPEDEF;
3502 }),
3503 candidates.end ());
3504 }
3505
3506 int i;
3507 if (candidates.empty ())
3508 error (_("No definition found for %s"), sym->print_name ());
3509 else if (candidates.size () == 1)
3510 i = 0;
3511 else if (deprocedure_p && !is_nonfunction (candidates))
3512 {
3513 i = ada_resolve_function
3514 (candidates, NULL, 0,
3515 sym->linkage_name (),
3516 context_type, parse_completion);
3517 if (i < 0)
3518 error (_("Could not find a match for %s"), sym->print_name ());
3519 }
3520 else
3521 {
3522 printf_filtered (_("Multiple matches for %s\n"), sym->print_name ());
3523 user_select_syms (candidates.data (), candidates.size (), 1);
3524 i = 0;
3525 }
3526
3527 tracker->update (candidates[i]);
3528 return candidates[i];
3529 }
3530
3531 /* Resolve the operator of the subexpression beginning at
3532 position *POS of *EXPP. "Resolving" consists of replacing
3533 the symbols that have undefined namespaces in OP_VAR_VALUE nodes
3534 with their resolutions, replacing built-in operators with
3535 function calls to user-defined operators, where appropriate, and,
3536 when DEPROCEDURE_P is non-zero, converting function-valued variables
3537 into parameterless calls. May expand *EXPP. The CONTEXT_TYPE functions
3538 are as in ada_resolve, above. */
3539
3540 static struct value *
3541 resolve_subexp (expression_up *expp, int *pos, int deprocedure_p,
3542 struct type *context_type, int parse_completion,
3543 innermost_block_tracker *tracker)
3544 {
3545 int pc = *pos;
3546 int i;
3547 struct expression *exp; /* Convenience: == *expp. */
3548 enum exp_opcode op = (*expp)->elts[pc].opcode;
3549 struct value **argvec; /* Vector of operand types (alloca'ed). */
3550 int nargs; /* Number of operands. */
3551 int oplen;
3552 /* If we're resolving an expression like ARRAY(ARG...), then we set
3553 this to the type of the array, so we can use the index types as
3554 the expected types for resolution. */
3555 struct type *array_type = nullptr;
3556 /* The arity of ARRAY_TYPE. */
3557 int array_arity = 0;
3558
3559 argvec = NULL;
3560 nargs = 0;
3561 exp = expp->get ();
3562
3563 /* Pass one: resolve operands, saving their types and updating *pos,
3564 if needed. */
3565 switch (op)
3566 {
3567 case OP_FUNCALL:
3568 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3569 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3570 *pos += 7;
3571 else
3572 {
3573 *pos += 3;
3574 struct value *lhs = resolve_subexp (expp, pos, 0, NULL,
3575 parse_completion, tracker);
3576 struct type *lhstype = ada_check_typedef (value_type (lhs));
3577 array_arity = ada_array_arity (lhstype);
3578 if (array_arity > 0)
3579 array_type = lhstype;
3580 }
3581 nargs = longest_to_int (exp->elts[pc + 1].longconst);
3582 break;
3583
3584 case UNOP_ADDR:
3585 *pos += 1;
3586 resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3587 break;
3588
3589 case UNOP_QUAL:
3590 *pos += 3;
3591 resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type),
3592 parse_completion, tracker);
3593 break;
3594
3595 case OP_ATR_MODULUS:
3596 case OP_ATR_SIZE:
3597 case OP_ATR_TAG:
3598 case OP_ATR_FIRST:
3599 case OP_ATR_LAST:
3600 case OP_ATR_LENGTH:
3601 case OP_ATR_POS:
3602 case OP_ATR_VAL:
3603 case OP_ATR_MIN:
3604 case OP_ATR_MAX:
3605 case TERNOP_IN_RANGE:
3606 case BINOP_IN_BOUNDS:
3607 case UNOP_IN_RANGE:
3608 case OP_AGGREGATE:
3609 case OP_OTHERS:
3610 case OP_CHOICES:
3611 case OP_POSITIONAL:
3612 case OP_DISCRETE_RANGE:
3613 case OP_NAME:
3614 ada_forward_operator_length (exp, pc, &oplen, &nargs);
3615 *pos += oplen;
3616 break;
3617
3618 case BINOP_ASSIGN:
3619 {
3620 struct value *arg1;
3621
3622 *pos += 1;
3623 arg1 = resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3624 if (arg1 == NULL)
3625 resolve_subexp (expp, pos, 1, NULL, parse_completion, tracker);
3626 else
3627 resolve_subexp (expp, pos, 1, value_type (arg1), parse_completion,
3628 tracker);
3629 break;
3630 }
3631
3632 case UNOP_CAST:
3633 *pos += 3;
3634 nargs = 1;
3635 break;
3636
3637 case BINOP_ADD:
3638 case BINOP_SUB:
3639 case BINOP_MUL:
3640 case BINOP_DIV:
3641 case BINOP_REM:
3642 case BINOP_MOD:
3643 case BINOP_EXP:
3644 case BINOP_CONCAT:
3645 case BINOP_LOGICAL_AND:
3646 case BINOP_LOGICAL_OR:
3647 case BINOP_BITWISE_AND:
3648 case BINOP_BITWISE_IOR:
3649 case BINOP_BITWISE_XOR:
3650
3651 case BINOP_EQUAL:
3652 case BINOP_NOTEQUAL:
3653 case BINOP_LESS:
3654 case BINOP_GTR:
3655 case BINOP_LEQ:
3656 case BINOP_GEQ:
3657
3658 case BINOP_REPEAT:
3659 case BINOP_SUBSCRIPT:
3660 case BINOP_COMMA:
3661 *pos += 1;
3662 nargs = 2;
3663 break;
3664
3665 case UNOP_NEG:
3666 case UNOP_PLUS:
3667 case UNOP_LOGICAL_NOT:
3668 case UNOP_ABS:
3669 case UNOP_IND:
3670 *pos += 1;
3671 nargs = 1;
3672 break;
3673
3674 case OP_LONG:
3675 case OP_FLOAT:
3676 case OP_VAR_VALUE:
3677 case OP_VAR_MSYM_VALUE:
3678 *pos += 4;
3679 break;
3680
3681 case OP_TYPE:
3682 case OP_BOOL:
3683 case OP_LAST:
3684 case OP_INTERNALVAR:
3685 *pos += 3;
3686 break;
3687
3688 case UNOP_MEMVAL:
3689 *pos += 3;
3690 nargs = 1;
3691 break;
3692
3693 case OP_REGISTER:
3694 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3695 break;
3696
3697 case STRUCTOP_STRUCT:
3698 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3699 nargs = 1;
3700 break;
3701
3702 case TERNOP_SLICE:
3703 *pos += 1;
3704 nargs = 3;
3705 break;
3706
3707 case OP_STRING:
3708 break;
3709
3710 default:
3711 error (_("Unexpected operator during name resolution"));
3712 }
3713
3714 argvec = XALLOCAVEC (struct value *, nargs + 1);
3715 for (i = 0; i < nargs; i += 1)
3716 {
3717 struct type *subtype = nullptr;
3718 if (i < array_arity)
3719 subtype = ada_index_type (array_type, i + 1, "array type");
3720 argvec[i] = resolve_subexp (expp, pos, 1, subtype, parse_completion,
3721 tracker);
3722 }
3723 argvec[i] = NULL;
3724 exp = expp->get ();
3725
3726 /* Pass two: perform any resolution on principal operator. */
3727 switch (op)
3728 {
3729 default:
3730 break;
3731
3732 case OP_VAR_VALUE:
3733 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
3734 {
3735 block_symbol resolved
3736 = ada_resolve_variable (exp->elts[pc + 2].symbol,
3737 exp->elts[pc + 1].block,
3738 context_type, parse_completion,
3739 deprocedure_p, tracker);
3740 exp->elts[pc + 1].block = resolved.block;
3741 exp->elts[pc + 2].symbol = resolved.symbol;
3742 }
3743
3744 if (deprocedure_p
3745 && (SYMBOL_TYPE (exp->elts[pc + 2].symbol)->code ()
3746 == TYPE_CODE_FUNC))
3747 {
3748 replace_operator_with_call (expp, pc, 0, 4,
3749 exp->elts[pc + 2].symbol,
3750 exp->elts[pc + 1].block);
3751 exp = expp->get ();
3752 }
3753 break;
3754
3755 case OP_FUNCALL:
3756 {
3757 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3758 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3759 {
3760 block_symbol resolved
3761 = ada_resolve_funcall (exp->elts[pc + 5].symbol,
3762 exp->elts[pc + 4].block,
3763 context_type, parse_completion,
3764 nargs, argvec,
3765 tracker);
3766 exp->elts[pc + 4].block = resolved.block;
3767 exp->elts[pc + 5].symbol = resolved.symbol;
3768 }
3769 }
3770 break;
3771 case BINOP_ADD:
3772 case BINOP_SUB:
3773 case BINOP_MUL:
3774 case BINOP_DIV:
3775 case BINOP_REM:
3776 case BINOP_MOD:
3777 case BINOP_CONCAT:
3778 case BINOP_BITWISE_AND:
3779 case BINOP_BITWISE_IOR:
3780 case BINOP_BITWISE_XOR:
3781 case BINOP_EQUAL:
3782 case BINOP_NOTEQUAL:
3783 case BINOP_LESS:
3784 case BINOP_GTR:
3785 case BINOP_LEQ:
3786 case BINOP_GEQ:
3787 case BINOP_EXP:
3788 case UNOP_NEG:
3789 case UNOP_PLUS:
3790 case UNOP_LOGICAL_NOT:
3791 case UNOP_ABS:
3792 {
3793 block_symbol found = ada_find_operator_symbol (op, parse_completion,
3794 nargs, argvec);
3795 if (found.symbol == nullptr)
3796 break;
3797
3798 replace_operator_with_call (expp, pc, nargs, 1,
3799 found.symbol, found.block);
3800 exp = expp->get ();
3801 }
3802 break;
3803
3804 case OP_TYPE:
3805 case OP_REGISTER:
3806 return NULL;
3807 }
3808
3809 *pos = pc;
3810 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
3811 return evaluate_var_msym_value (EVAL_AVOID_SIDE_EFFECTS,
3812 exp->elts[pc + 1].objfile,
3813 exp->elts[pc + 2].msymbol);
3814 else
3815 return evaluate_subexp_type (exp, pos);
3816 }
3817
3818 /* Return non-zero if formal type FTYPE matches actual type ATYPE. If
3819 MAY_DEREF is non-zero, the formal may be a pointer and the actual
3820 a non-pointer. */
3821 /* The term "match" here is rather loose. The match is heuristic and
3822 liberal. */
3823
3824 static int
3825 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
3826 {
3827 ftype = ada_check_typedef (ftype);
3828 atype = ada_check_typedef (atype);
3829
3830 if (ftype->code () == TYPE_CODE_REF)
3831 ftype = TYPE_TARGET_TYPE (ftype);
3832 if (atype->code () == TYPE_CODE_REF)
3833 atype = TYPE_TARGET_TYPE (atype);
3834
3835 switch (ftype->code ())
3836 {
3837 default:
3838 return ftype->code () == atype->code ();
3839 case TYPE_CODE_PTR:
3840 if (atype->code () == TYPE_CODE_PTR)
3841 return ada_type_match (TYPE_TARGET_TYPE (ftype),
3842 TYPE_TARGET_TYPE (atype), 0);
3843 else
3844 return (may_deref
3845 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
3846 case TYPE_CODE_INT:
3847 case TYPE_CODE_ENUM:
3848 case TYPE_CODE_RANGE:
3849 switch (atype->code ())
3850 {
3851 case TYPE_CODE_INT:
3852 case TYPE_CODE_ENUM:
3853 case TYPE_CODE_RANGE:
3854 return 1;
3855 default:
3856 return 0;
3857 }
3858
3859 case TYPE_CODE_ARRAY:
3860 return (atype->code () == TYPE_CODE_ARRAY
3861 || ada_is_array_descriptor_type (atype));
3862
3863 case TYPE_CODE_STRUCT:
3864 if (ada_is_array_descriptor_type (ftype))
3865 return (atype->code () == TYPE_CODE_ARRAY
3866 || ada_is_array_descriptor_type (atype));
3867 else
3868 return (atype->code () == TYPE_CODE_STRUCT
3869 && !ada_is_array_descriptor_type (atype));
3870
3871 case TYPE_CODE_UNION:
3872 case TYPE_CODE_FLT:
3873 return (atype->code () == ftype->code ());
3874 }
3875 }
3876
3877 /* Return non-zero if the formals of FUNC "sufficiently match" the
3878 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3879 may also be an enumeral, in which case it is treated as a 0-
3880 argument function. */
3881
3882 static int
3883 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3884 {
3885 int i;
3886 struct type *func_type = SYMBOL_TYPE (func);
3887
3888 if (SYMBOL_CLASS (func) == LOC_CONST
3889 && func_type->code () == TYPE_CODE_ENUM)
3890 return (n_actuals == 0);
3891 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3892 return 0;
3893
3894 if (func_type->num_fields () != n_actuals)
3895 return 0;
3896
3897 for (i = 0; i < n_actuals; i += 1)
3898 {
3899 if (actuals[i] == NULL)
3900 return 0;
3901 else
3902 {
3903 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3904 struct type *atype = ada_check_typedef (value_type (actuals[i]));
3905
3906 if (!ada_type_match (ftype, atype, 1))
3907 return 0;
3908 }
3909 }
3910 return 1;
3911 }
3912
3913 /* False iff function type FUNC_TYPE definitely does not produce a value
3914 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
3915 FUNC_TYPE is not a valid function type with a non-null return type
3916 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
3917
3918 static int
3919 return_match (struct type *func_type, struct type *context_type)
3920 {
3921 struct type *return_type;
3922
3923 if (func_type == NULL)
3924 return 1;
3925
3926 if (func_type->code () == TYPE_CODE_FUNC)
3927 return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3928 else
3929 return_type = get_base_type (func_type);
3930 if (return_type == NULL)
3931 return 1;
3932
3933 context_type = get_base_type (context_type);
3934
3935 if (return_type->code () == TYPE_CODE_ENUM)
3936 return context_type == NULL || return_type == context_type;
3937 else if (context_type == NULL)
3938 return return_type->code () != TYPE_CODE_VOID;
3939 else
3940 return return_type->code () == context_type->code ();
3941 }
3942
3943
3944 /* Returns the index in SYMS that contains the symbol for the
3945 function (if any) that matches the types of the NARGS arguments in
3946 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
3947 that returns that type, then eliminate matches that don't. If
3948 CONTEXT_TYPE is void and there is at least one match that does not
3949 return void, eliminate all matches that do.
3950
3951 Asks the user if there is more than one match remaining. Returns -1
3952 if there is no such symbol or none is selected. NAME is used
3953 solely for messages. May re-arrange and modify SYMS in
3954 the process; the index returned is for the modified vector. */
3955
3956 static int
3957 ada_resolve_function (std::vector<struct block_symbol> &syms,
3958 struct value **args, int nargs,
3959 const char *name, struct type *context_type,
3960 int parse_completion)
3961 {
3962 int fallback;
3963 int k;
3964 int m; /* Number of hits */
3965
3966 m = 0;
3967 /* In the first pass of the loop, we only accept functions matching
3968 context_type. If none are found, we add a second pass of the loop
3969 where every function is accepted. */
3970 for (fallback = 0; m == 0 && fallback < 2; fallback++)
3971 {
3972 for (k = 0; k < syms.size (); k += 1)
3973 {
3974 struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].symbol));
3975
3976 if (ada_args_match (syms[k].symbol, args, nargs)
3977 && (fallback || return_match (type, context_type)))
3978 {
3979 syms[m] = syms[k];
3980 m += 1;
3981 }
3982 }
3983 }
3984
3985 /* If we got multiple matches, ask the user which one to use. Don't do this
3986 interactive thing during completion, though, as the purpose of the
3987 completion is providing a list of all possible matches. Prompting the
3988 user to filter it down would be completely unexpected in this case. */
3989 if (m == 0)
3990 return -1;
3991 else if (m > 1 && !parse_completion)
3992 {
3993 printf_filtered (_("Multiple matches for %s\n"), name);
3994 user_select_syms (syms.data (), m, 1);
3995 return 0;
3996 }
3997 return 0;
3998 }
3999
4000 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
4001 on the function identified by SYM and BLOCK, and taking NARGS
4002 arguments. Update *EXPP as needed to hold more space. */
4003
4004 static void
4005 replace_operator_with_call (expression_up *expp, int pc, int nargs,
4006 int oplen, struct symbol *sym,
4007 const struct block *block)
4008 {
4009 /* We want to add 6 more elements (3 for funcall, 4 for function
4010 symbol, -OPLEN for operator being replaced) to the
4011 expression. */
4012 struct expression *exp = expp->get ();
4013 int save_nelts = exp->nelts;
4014 int extra_elts = 7 - oplen;
4015 exp->nelts += extra_elts;
4016
4017 if (extra_elts > 0)
4018 exp->resize (exp->nelts);
4019 memmove (exp->elts + pc + 7, exp->elts + pc + oplen,
4020 EXP_ELEM_TO_BYTES (save_nelts - pc - oplen));
4021 if (extra_elts < 0)
4022 exp->resize (exp->nelts);
4023
4024 exp->elts[pc].opcode = exp->elts[pc + 2].opcode = OP_FUNCALL;
4025 exp->elts[pc + 1].longconst = (LONGEST) nargs;
4026
4027 exp->elts[pc + 3].opcode = exp->elts[pc + 6].opcode = OP_VAR_VALUE;
4028 exp->elts[pc + 4].block = block;
4029 exp->elts[pc + 5].symbol = sym;
4030 }
4031
4032 /* Type-class predicates */
4033
4034 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4035 or FLOAT). */
4036
4037 static int
4038 numeric_type_p (struct type *type)
4039 {
4040 if (type == NULL)
4041 return 0;
4042 else
4043 {
4044 switch (type->code ())
4045 {
4046 case TYPE_CODE_INT:
4047 case TYPE_CODE_FLT:
4048 return 1;
4049 case TYPE_CODE_RANGE:
4050 return (type == TYPE_TARGET_TYPE (type)
4051 || numeric_type_p (TYPE_TARGET_TYPE (type)));
4052 default:
4053 return 0;
4054 }
4055 }
4056 }
4057
4058 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4059
4060 static int
4061 integer_type_p (struct type *type)
4062 {
4063 if (type == NULL)
4064 return 0;
4065 else
4066 {
4067 switch (type->code ())
4068 {
4069 case TYPE_CODE_INT:
4070 return 1;
4071 case TYPE_CODE_RANGE:
4072 return (type == TYPE_TARGET_TYPE (type)
4073 || integer_type_p (TYPE_TARGET_TYPE (type)));
4074 default:
4075 return 0;
4076 }
4077 }
4078 }
4079
4080 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4081
4082 static int
4083 scalar_type_p (struct type *type)
4084 {
4085 if (type == NULL)
4086 return 0;
4087 else
4088 {
4089 switch (type->code ())
4090 {
4091 case TYPE_CODE_INT:
4092 case TYPE_CODE_RANGE:
4093 case TYPE_CODE_ENUM:
4094 case TYPE_CODE_FLT:
4095 return 1;
4096 default:
4097 return 0;
4098 }
4099 }
4100 }
4101
4102 /* True iff TYPE is discrete (INT, RANGE, ENUM). */
4103
4104 static int
4105 discrete_type_p (struct type *type)
4106 {
4107 if (type == NULL)
4108 return 0;
4109 else
4110 {
4111 switch (type->code ())
4112 {
4113 case TYPE_CODE_INT:
4114 case TYPE_CODE_RANGE:
4115 case TYPE_CODE_ENUM:
4116 case TYPE_CODE_BOOL:
4117 return 1;
4118 default:
4119 return 0;
4120 }
4121 }
4122 }
4123
4124 /* Returns non-zero if OP with operands in the vector ARGS could be
4125 a user-defined function. Errs on the side of pre-defined operators
4126 (i.e., result 0). */
4127
4128 static int
4129 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4130 {
4131 struct type *type0 =
4132 (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
4133 struct type *type1 =
4134 (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
4135
4136 if (type0 == NULL)
4137 return 0;
4138
4139 switch (op)
4140 {
4141 default:
4142 return 0;
4143
4144 case BINOP_ADD:
4145 case BINOP_SUB:
4146 case BINOP_MUL:
4147 case BINOP_DIV:
4148 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4149
4150 case BINOP_REM:
4151 case BINOP_MOD:
4152 case BINOP_BITWISE_AND:
4153 case BINOP_BITWISE_IOR:
4154 case BINOP_BITWISE_XOR:
4155 return (!(integer_type_p (type0) && integer_type_p (type1)));
4156
4157 case BINOP_EQUAL:
4158 case BINOP_NOTEQUAL:
4159 case BINOP_LESS:
4160 case BINOP_GTR:
4161 case BINOP_LEQ:
4162 case BINOP_GEQ:
4163 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4164
4165 case BINOP_CONCAT:
4166 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4167
4168 case BINOP_EXP:
4169 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4170
4171 case UNOP_NEG:
4172 case UNOP_PLUS:
4173 case UNOP_LOGICAL_NOT:
4174 case UNOP_ABS:
4175 return (!numeric_type_p (type0));
4176
4177 }
4178 }
4179 \f
4180 /* Renaming */
4181
4182 /* NOTES:
4183
4184 1. In the following, we assume that a renaming type's name may
4185 have an ___XD suffix. It would be nice if this went away at some
4186 point.
4187 2. We handle both the (old) purely type-based representation of
4188 renamings and the (new) variable-based encoding. At some point,
4189 it is devoutly to be hoped that the former goes away
4190 (FIXME: hilfinger-2007-07-09).
4191 3. Subprogram renamings are not implemented, although the XRS
4192 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4193
4194 /* If SYM encodes a renaming,
4195
4196 <renaming> renames <renamed entity>,
4197
4198 sets *LEN to the length of the renamed entity's name,
4199 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4200 the string describing the subcomponent selected from the renamed
4201 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4202 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4203 are undefined). Otherwise, returns a value indicating the category
4204 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4205 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4206 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4207 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4208 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4209 may be NULL, in which case they are not assigned.
4210
4211 [Currently, however, GCC does not generate subprogram renamings.] */
4212
4213 enum ada_renaming_category
4214 ada_parse_renaming (struct symbol *sym,
4215 const char **renamed_entity, int *len,
4216 const char **renaming_expr)
4217 {
4218 enum ada_renaming_category kind;
4219 const char *info;
4220 const char *suffix;
4221
4222 if (sym == NULL)
4223 return ADA_NOT_RENAMING;
4224 switch (SYMBOL_CLASS (sym))
4225 {
4226 default:
4227 return ADA_NOT_RENAMING;
4228 case LOC_LOCAL:
4229 case LOC_STATIC:
4230 case LOC_COMPUTED:
4231 case LOC_OPTIMIZED_OUT:
4232 info = strstr (sym->linkage_name (), "___XR");
4233 if (info == NULL)
4234 return ADA_NOT_RENAMING;
4235 switch (info[5])
4236 {
4237 case '_':
4238 kind = ADA_OBJECT_RENAMING;
4239 info += 6;
4240 break;
4241 case 'E':
4242 kind = ADA_EXCEPTION_RENAMING;
4243 info += 7;
4244 break;
4245 case 'P':
4246 kind = ADA_PACKAGE_RENAMING;
4247 info += 7;
4248 break;
4249 case 'S':
4250 kind = ADA_SUBPROGRAM_RENAMING;
4251 info += 7;
4252 break;
4253 default:
4254 return ADA_NOT_RENAMING;
4255 }
4256 }
4257
4258 if (renamed_entity != NULL)
4259 *renamed_entity = info;
4260 suffix = strstr (info, "___XE");
4261 if (suffix == NULL || suffix == info)
4262 return ADA_NOT_RENAMING;
4263 if (len != NULL)
4264 *len = strlen (info) - strlen (suffix);
4265 suffix += 5;
4266 if (renaming_expr != NULL)
4267 *renaming_expr = suffix;
4268 return kind;
4269 }
4270
4271 /* Compute the value of the given RENAMING_SYM, which is expected to
4272 be a symbol encoding a renaming expression. BLOCK is the block
4273 used to evaluate the renaming. */
4274
4275 static struct value *
4276 ada_read_renaming_var_value (struct symbol *renaming_sym,
4277 const struct block *block)
4278 {
4279 const char *sym_name;
4280
4281 sym_name = renaming_sym->linkage_name ();
4282 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4283 return evaluate_expression (expr.get ());
4284 }
4285 \f
4286
4287 /* Evaluation: Function Calls */
4288
4289 /* Return an lvalue containing the value VAL. This is the identity on
4290 lvalues, and otherwise has the side-effect of allocating memory
4291 in the inferior where a copy of the value contents is copied. */
4292
4293 static struct value *
4294 ensure_lval (struct value *val)
4295 {
4296 if (VALUE_LVAL (val) == not_lval
4297 || VALUE_LVAL (val) == lval_internalvar)
4298 {
4299 int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4300 const CORE_ADDR addr =
4301 value_as_long (value_allocate_space_in_inferior (len));
4302
4303 VALUE_LVAL (val) = lval_memory;
4304 set_value_address (val, addr);
4305 write_memory (addr, value_contents (val), len);
4306 }
4307
4308 return val;
4309 }
4310
4311 /* Given ARG, a value of type (pointer or reference to a)*
4312 structure/union, extract the component named NAME from the ultimate
4313 target structure/union and return it as a value with its
4314 appropriate type.
4315
4316 The routine searches for NAME among all members of the structure itself
4317 and (recursively) among all members of any wrapper members
4318 (e.g., '_parent').
4319
4320 If NO_ERR, then simply return NULL in case of error, rather than
4321 calling error. */
4322
4323 static struct value *
4324 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4325 {
4326 struct type *t, *t1;
4327 struct value *v;
4328 int check_tag;
4329
4330 v = NULL;
4331 t1 = t = ada_check_typedef (value_type (arg));
4332 if (t->code () == TYPE_CODE_REF)
4333 {
4334 t1 = TYPE_TARGET_TYPE (t);
4335 if (t1 == NULL)
4336 goto BadValue;
4337 t1 = ada_check_typedef (t1);
4338 if (t1->code () == TYPE_CODE_PTR)
4339 {
4340 arg = coerce_ref (arg);
4341 t = t1;
4342 }
4343 }
4344
4345 while (t->code () == TYPE_CODE_PTR)
4346 {
4347 t1 = TYPE_TARGET_TYPE (t);
4348 if (t1 == NULL)
4349 goto BadValue;
4350 t1 = ada_check_typedef (t1);
4351 if (t1->code () == TYPE_CODE_PTR)
4352 {
4353 arg = value_ind (arg);
4354 t = t1;
4355 }
4356 else
4357 break;
4358 }
4359
4360 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4361 goto BadValue;
4362
4363 if (t1 == t)
4364 v = ada_search_struct_field (name, arg, 0, t);
4365 else
4366 {
4367 int bit_offset, bit_size, byte_offset;
4368 struct type *field_type;
4369 CORE_ADDR address;
4370
4371 if (t->code () == TYPE_CODE_PTR)
4372 address = value_address (ada_value_ind (arg));
4373 else
4374 address = value_address (ada_coerce_ref (arg));
4375
4376 /* Check to see if this is a tagged type. We also need to handle
4377 the case where the type is a reference to a tagged type, but
4378 we have to be careful to exclude pointers to tagged types.
4379 The latter should be shown as usual (as a pointer), whereas
4380 a reference should mostly be transparent to the user. */
4381
4382 if (ada_is_tagged_type (t1, 0)
4383 || (t1->code () == TYPE_CODE_REF
4384 && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
4385 {
4386 /* We first try to find the searched field in the current type.
4387 If not found then let's look in the fixed type. */
4388
4389 if (!find_struct_field (name, t1, 0,
4390 &field_type, &byte_offset, &bit_offset,
4391 &bit_size, NULL))
4392 check_tag = 1;
4393 else
4394 check_tag = 0;
4395 }
4396 else
4397 check_tag = 0;
4398
4399 /* Convert to fixed type in all cases, so that we have proper
4400 offsets to each field in unconstrained record types. */
4401 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4402 address, NULL, check_tag);
4403
4404 /* Resolve the dynamic type as well. */
4405 arg = value_from_contents_and_address (t1, nullptr, address);
4406 t1 = value_type (arg);
4407
4408 if (find_struct_field (name, t1, 0,
4409 &field_type, &byte_offset, &bit_offset,
4410 &bit_size, NULL))
4411 {
4412 if (bit_size != 0)
4413 {
4414 if (t->code () == TYPE_CODE_REF)
4415 arg = ada_coerce_ref (arg);
4416 else
4417 arg = ada_value_ind (arg);
4418 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4419 bit_offset, bit_size,
4420 field_type);
4421 }
4422 else
4423 v = value_at_lazy (field_type, address + byte_offset);
4424 }
4425 }
4426
4427 if (v != NULL || no_err)
4428 return v;
4429 else
4430 error (_("There is no member named %s."), name);
4431
4432 BadValue:
4433 if (no_err)
4434 return NULL;
4435 else
4436 error (_("Attempt to extract a component of "
4437 "a value that is not a record."));
4438 }
4439
4440 /* Return the value ACTUAL, converted to be an appropriate value for a
4441 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4442 allocating any necessary descriptors (fat pointers), or copies of
4443 values not residing in memory, updating it as needed. */
4444
4445 struct value *
4446 ada_convert_actual (struct value *actual, struct type *formal_type0)
4447 {
4448 struct type *actual_type = ada_check_typedef (value_type (actual));
4449 struct type *formal_type = ada_check_typedef (formal_type0);
4450 struct type *formal_target =
4451 formal_type->code () == TYPE_CODE_PTR
4452 ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4453 struct type *actual_target =
4454 actual_type->code () == TYPE_CODE_PTR
4455 ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4456
4457 if (ada_is_array_descriptor_type (formal_target)
4458 && actual_target->code () == TYPE_CODE_ARRAY)
4459 return make_array_descriptor (formal_type, actual);
4460 else if (formal_type->code () == TYPE_CODE_PTR
4461 || formal_type->code () == TYPE_CODE_REF)
4462 {
4463 struct value *result;
4464
4465 if (formal_target->code () == TYPE_CODE_ARRAY
4466 && ada_is_array_descriptor_type (actual_target))
4467 result = desc_data (actual);
4468 else if (formal_type->code () != TYPE_CODE_PTR)
4469 {
4470 if (VALUE_LVAL (actual) != lval_memory)
4471 {
4472 struct value *val;
4473
4474 actual_type = ada_check_typedef (value_type (actual));
4475 val = allocate_value (actual_type);
4476 memcpy ((char *) value_contents_raw (val),
4477 (char *) value_contents (actual),
4478 TYPE_LENGTH (actual_type));
4479 actual = ensure_lval (val);
4480 }
4481 result = value_addr (actual);
4482 }
4483 else
4484 return actual;
4485 return value_cast_pointers (formal_type, result, 0);
4486 }
4487 else if (actual_type->code () == TYPE_CODE_PTR)
4488 return ada_value_ind (actual);
4489 else if (ada_is_aligner_type (formal_type))
4490 {
4491 /* We need to turn this parameter into an aligner type
4492 as well. */
4493 struct value *aligner = allocate_value (formal_type);
4494 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4495
4496 value_assign_to_component (aligner, component, actual);
4497 return aligner;
4498 }
4499
4500 return actual;
4501 }
4502
4503 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4504 type TYPE. This is usually an inefficient no-op except on some targets
4505 (such as AVR) where the representation of a pointer and an address
4506 differs. */
4507
4508 static CORE_ADDR
4509 value_pointer (struct value *value, struct type *type)
4510 {
4511 unsigned len = TYPE_LENGTH (type);
4512 gdb_byte *buf = (gdb_byte *) alloca (len);
4513 CORE_ADDR addr;
4514
4515 addr = value_address (value);
4516 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4517 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4518 return addr;
4519 }
4520
4521
4522 /* Push a descriptor of type TYPE for array value ARR on the stack at
4523 *SP, updating *SP to reflect the new descriptor. Return either
4524 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4525 to-descriptor type rather than a descriptor type), a struct value *
4526 representing a pointer to this descriptor. */
4527
4528 static struct value *
4529 make_array_descriptor (struct type *type, struct value *arr)
4530 {
4531 struct type *bounds_type = desc_bounds_type (type);
4532 struct type *desc_type = desc_base_type (type);
4533 struct value *descriptor = allocate_value (desc_type);
4534 struct value *bounds = allocate_value (bounds_type);
4535 int i;
4536
4537 for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4538 i > 0; i -= 1)
4539 {
4540 modify_field (value_type (bounds), value_contents_writeable (bounds),
4541 ada_array_bound (arr, i, 0),
4542 desc_bound_bitpos (bounds_type, i, 0),
4543 desc_bound_bitsize (bounds_type, i, 0));
4544 modify_field (value_type (bounds), value_contents_writeable (bounds),
4545 ada_array_bound (arr, i, 1),
4546 desc_bound_bitpos (bounds_type, i, 1),
4547 desc_bound_bitsize (bounds_type, i, 1));
4548 }
4549
4550 bounds = ensure_lval (bounds);
4551
4552 modify_field (value_type (descriptor),
4553 value_contents_writeable (descriptor),
4554 value_pointer (ensure_lval (arr),
4555 desc_type->field (0).type ()),
4556 fat_pntr_data_bitpos (desc_type),
4557 fat_pntr_data_bitsize (desc_type));
4558
4559 modify_field (value_type (descriptor),
4560 value_contents_writeable (descriptor),
4561 value_pointer (bounds,
4562 desc_type->field (1).type ()),
4563 fat_pntr_bounds_bitpos (desc_type),
4564 fat_pntr_bounds_bitsize (desc_type));
4565
4566 descriptor = ensure_lval (descriptor);
4567
4568 if (type->code () == TYPE_CODE_PTR)
4569 return value_addr (descriptor);
4570 else
4571 return descriptor;
4572 }
4573 \f
4574 /* Symbol Cache Module */
4575
4576 /* Performance measurements made as of 2010-01-15 indicate that
4577 this cache does bring some noticeable improvements. Depending
4578 on the type of entity being printed, the cache can make it as much
4579 as an order of magnitude faster than without it.
4580
4581 The descriptive type DWARF extension has significantly reduced
4582 the need for this cache, at least when DWARF is being used. However,
4583 even in this case, some expensive name-based symbol searches are still
4584 sometimes necessary - to find an XVZ variable, mostly. */
4585
4586 /* Return the symbol cache associated to the given program space PSPACE.
4587 If not allocated for this PSPACE yet, allocate and initialize one. */
4588
4589 static struct ada_symbol_cache *
4590 ada_get_symbol_cache (struct program_space *pspace)
4591 {
4592 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4593
4594 if (pspace_data->sym_cache == nullptr)
4595 pspace_data->sym_cache.reset (new ada_symbol_cache);
4596
4597 return pspace_data->sym_cache.get ();
4598 }
4599
4600 /* Clear all entries from the symbol cache. */
4601
4602 static void
4603 ada_clear_symbol_cache ()
4604 {
4605 struct ada_pspace_data *pspace_data
4606 = get_ada_pspace_data (current_program_space);
4607
4608 if (pspace_data->sym_cache != nullptr)
4609 pspace_data->sym_cache.reset ();
4610 }
4611
4612 /* Search our cache for an entry matching NAME and DOMAIN.
4613 Return it if found, or NULL otherwise. */
4614
4615 static struct cache_entry **
4616 find_entry (const char *name, domain_enum domain)
4617 {
4618 struct ada_symbol_cache *sym_cache
4619 = ada_get_symbol_cache (current_program_space);
4620 int h = msymbol_hash (name) % HASH_SIZE;
4621 struct cache_entry **e;
4622
4623 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4624 {
4625 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4626 return e;
4627 }
4628 return NULL;
4629 }
4630
4631 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4632 Return 1 if found, 0 otherwise.
4633
4634 If an entry was found and SYM is not NULL, set *SYM to the entry's
4635 SYM. Same principle for BLOCK if not NULL. */
4636
4637 static int
4638 lookup_cached_symbol (const char *name, domain_enum domain,
4639 struct symbol **sym, const struct block **block)
4640 {
4641 struct cache_entry **e = find_entry (name, domain);
4642
4643 if (e == NULL)
4644 return 0;
4645 if (sym != NULL)
4646 *sym = (*e)->sym;
4647 if (block != NULL)
4648 *block = (*e)->block;
4649 return 1;
4650 }
4651
4652 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4653 in domain DOMAIN, save this result in our symbol cache. */
4654
4655 static void
4656 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4657 const struct block *block)
4658 {
4659 struct ada_symbol_cache *sym_cache
4660 = ada_get_symbol_cache (current_program_space);
4661 int h;
4662 struct cache_entry *e;
4663
4664 /* Symbols for builtin types don't have a block.
4665 For now don't cache such symbols. */
4666 if (sym != NULL && !SYMBOL_OBJFILE_OWNED (sym))
4667 return;
4668
4669 /* If the symbol is a local symbol, then do not cache it, as a search
4670 for that symbol depends on the context. To determine whether
4671 the symbol is local or not, we check the block where we found it
4672 against the global and static blocks of its associated symtab. */
4673 if (sym
4674 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4675 GLOBAL_BLOCK) != block
4676 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4677 STATIC_BLOCK) != block)
4678 return;
4679
4680 h = msymbol_hash (name) % HASH_SIZE;
4681 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4682 e->next = sym_cache->root[h];
4683 sym_cache->root[h] = e;
4684 e->name = obstack_strdup (&sym_cache->cache_space, name);
4685 e->sym = sym;
4686 e->domain = domain;
4687 e->block = block;
4688 }
4689 \f
4690 /* Symbol Lookup */
4691
4692 /* Return the symbol name match type that should be used used when
4693 searching for all symbols matching LOOKUP_NAME.
4694
4695 LOOKUP_NAME is expected to be a symbol name after transformation
4696 for Ada lookups. */
4697
4698 static symbol_name_match_type
4699 name_match_type_from_name (const char *lookup_name)
4700 {
4701 return (strstr (lookup_name, "__") == NULL
4702 ? symbol_name_match_type::WILD
4703 : symbol_name_match_type::FULL);
4704 }
4705
4706 /* Return the result of a standard (literal, C-like) lookup of NAME in
4707 given DOMAIN, visible from lexical block BLOCK. */
4708
4709 static struct symbol *
4710 standard_lookup (const char *name, const struct block *block,
4711 domain_enum domain)
4712 {
4713 /* Initialize it just to avoid a GCC false warning. */
4714 struct block_symbol sym = {};
4715
4716 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4717 return sym.symbol;
4718 ada_lookup_encoded_symbol (name, block, domain, &sym);
4719 cache_symbol (name, domain, sym.symbol, sym.block);
4720 return sym.symbol;
4721 }
4722
4723
4724 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4725 in the symbol fields of SYMS. We treat enumerals as functions,
4726 since they contend in overloading in the same way. */
4727 static int
4728 is_nonfunction (const std::vector<struct block_symbol> &syms)
4729 {
4730 for (const block_symbol &sym : syms)
4731 if (SYMBOL_TYPE (sym.symbol)->code () != TYPE_CODE_FUNC
4732 && (SYMBOL_TYPE (sym.symbol)->code () != TYPE_CODE_ENUM
4733 || SYMBOL_CLASS (sym.symbol) != LOC_CONST))
4734 return 1;
4735
4736 return 0;
4737 }
4738
4739 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4740 struct types. Otherwise, they may not. */
4741
4742 static int
4743 equiv_types (struct type *type0, struct type *type1)
4744 {
4745 if (type0 == type1)
4746 return 1;
4747 if (type0 == NULL || type1 == NULL
4748 || type0->code () != type1->code ())
4749 return 0;
4750 if ((type0->code () == TYPE_CODE_STRUCT
4751 || type0->code () == TYPE_CODE_ENUM)
4752 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4753 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4754 return 1;
4755
4756 return 0;
4757 }
4758
4759 /* True iff SYM0 represents the same entity as SYM1, or one that is
4760 no more defined than that of SYM1. */
4761
4762 static int
4763 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4764 {
4765 if (sym0 == sym1)
4766 return 1;
4767 if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
4768 || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
4769 return 0;
4770
4771 switch (SYMBOL_CLASS (sym0))
4772 {
4773 case LOC_UNDEF:
4774 return 1;
4775 case LOC_TYPEDEF:
4776 {
4777 struct type *type0 = SYMBOL_TYPE (sym0);
4778 struct type *type1 = SYMBOL_TYPE (sym1);
4779 const char *name0 = sym0->linkage_name ();
4780 const char *name1 = sym1->linkage_name ();
4781 int len0 = strlen (name0);
4782
4783 return
4784 type0->code () == type1->code ()
4785 && (equiv_types (type0, type1)
4786 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4787 && startswith (name1 + len0, "___XV")));
4788 }
4789 case LOC_CONST:
4790 return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4791 && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
4792
4793 case LOC_STATIC:
4794 {
4795 const char *name0 = sym0->linkage_name ();
4796 const char *name1 = sym1->linkage_name ();
4797 return (strcmp (name0, name1) == 0
4798 && SYMBOL_VALUE_ADDRESS (sym0) == SYMBOL_VALUE_ADDRESS (sym1));
4799 }
4800
4801 default:
4802 return 0;
4803 }
4804 }
4805
4806 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4807 records in RESULT. Do nothing if SYM is a duplicate. */
4808
4809 static void
4810 add_defn_to_vec (std::vector<struct block_symbol> &result,
4811 struct symbol *sym,
4812 const struct block *block)
4813 {
4814 /* Do not try to complete stub types, as the debugger is probably
4815 already scanning all symbols matching a certain name at the
4816 time when this function is called. Trying to replace the stub
4817 type by its associated full type will cause us to restart a scan
4818 which may lead to an infinite recursion. Instead, the client
4819 collecting the matching symbols will end up collecting several
4820 matches, with at least one of them complete. It can then filter
4821 out the stub ones if needed. */
4822
4823 for (int i = result.size () - 1; i >= 0; i -= 1)
4824 {
4825 if (lesseq_defined_than (sym, result[i].symbol))
4826 return;
4827 else if (lesseq_defined_than (result[i].symbol, sym))
4828 {
4829 result[i].symbol = sym;
4830 result[i].block = block;
4831 return;
4832 }
4833 }
4834
4835 struct block_symbol info;
4836 info.symbol = sym;
4837 info.block = block;
4838 result.push_back (info);
4839 }
4840
4841 /* Return a bound minimal symbol matching NAME according to Ada
4842 decoding rules. Returns an invalid symbol if there is no such
4843 minimal symbol. Names prefixed with "standard__" are handled
4844 specially: "standard__" is first stripped off, and only static and
4845 global symbols are searched. */
4846
4847 struct bound_minimal_symbol
4848 ada_lookup_simple_minsym (const char *name)
4849 {
4850 struct bound_minimal_symbol result;
4851
4852 memset (&result, 0, sizeof (result));
4853
4854 symbol_name_match_type match_type = name_match_type_from_name (name);
4855 lookup_name_info lookup_name (name, match_type);
4856
4857 symbol_name_matcher_ftype *match_name
4858 = ada_get_symbol_name_matcher (lookup_name);
4859
4860 for (objfile *objfile : current_program_space->objfiles ())
4861 {
4862 for (minimal_symbol *msymbol : objfile->msymbols ())
4863 {
4864 if (match_name (msymbol->linkage_name (), lookup_name, NULL)
4865 && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4866 {
4867 result.minsym = msymbol;
4868 result.objfile = objfile;
4869 break;
4870 }
4871 }
4872 }
4873
4874 return result;
4875 }
4876
4877 /* For all subprograms that statically enclose the subprogram of the
4878 selected frame, add symbols matching identifier NAME in DOMAIN
4879 and their blocks to the list of data in RESULT, as for
4880 ada_add_block_symbols (q.v.). If WILD_MATCH_P, treat as NAME
4881 with a wildcard prefix. */
4882
4883 static void
4884 add_symbols_from_enclosing_procs (std::vector<struct block_symbol> &result,
4885 const lookup_name_info &lookup_name,
4886 domain_enum domain)
4887 {
4888 }
4889
4890 /* True if TYPE is definitely an artificial type supplied to a symbol
4891 for which no debugging information was given in the symbol file. */
4892
4893 static int
4894 is_nondebugging_type (struct type *type)
4895 {
4896 const char *name = ada_type_name (type);
4897
4898 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4899 }
4900
4901 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4902 that are deemed "identical" for practical purposes.
4903
4904 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4905 types and that their number of enumerals is identical (in other
4906 words, type1->num_fields () == type2->num_fields ()). */
4907
4908 static int
4909 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4910 {
4911 int i;
4912
4913 /* The heuristic we use here is fairly conservative. We consider
4914 that 2 enumerate types are identical if they have the same
4915 number of enumerals and that all enumerals have the same
4916 underlying value and name. */
4917
4918 /* All enums in the type should have an identical underlying value. */
4919 for (i = 0; i < type1->num_fields (); i++)
4920 if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
4921 return 0;
4922
4923 /* All enumerals should also have the same name (modulo any numerical
4924 suffix). */
4925 for (i = 0; i < type1->num_fields (); i++)
4926 {
4927 const char *name_1 = TYPE_FIELD_NAME (type1, i);
4928 const char *name_2 = TYPE_FIELD_NAME (type2, i);
4929 int len_1 = strlen (name_1);
4930 int len_2 = strlen (name_2);
4931
4932 ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
4933 ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
4934 if (len_1 != len_2
4935 || strncmp (TYPE_FIELD_NAME (type1, i),
4936 TYPE_FIELD_NAME (type2, i),
4937 len_1) != 0)
4938 return 0;
4939 }
4940
4941 return 1;
4942 }
4943
4944 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4945 that are deemed "identical" for practical purposes. Sometimes,
4946 enumerals are not strictly identical, but their types are so similar
4947 that they can be considered identical.
4948
4949 For instance, consider the following code:
4950
4951 type Color is (Black, Red, Green, Blue, White);
4952 type RGB_Color is new Color range Red .. Blue;
4953
4954 Type RGB_Color is a subrange of an implicit type which is a copy
4955 of type Color. If we call that implicit type RGB_ColorB ("B" is
4956 for "Base Type"), then type RGB_ColorB is a copy of type Color.
4957 As a result, when an expression references any of the enumeral
4958 by name (Eg. "print green"), the expression is technically
4959 ambiguous and the user should be asked to disambiguate. But
4960 doing so would only hinder the user, since it wouldn't matter
4961 what choice he makes, the outcome would always be the same.
4962 So, for practical purposes, we consider them as the same. */
4963
4964 static int
4965 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
4966 {
4967 int i;
4968
4969 /* Before performing a thorough comparison check of each type,
4970 we perform a series of inexpensive checks. We expect that these
4971 checks will quickly fail in the vast majority of cases, and thus
4972 help prevent the unnecessary use of a more expensive comparison.
4973 Said comparison also expects us to make some of these checks
4974 (see ada_identical_enum_types_p). */
4975
4976 /* Quick check: All symbols should have an enum type. */
4977 for (i = 0; i < syms.size (); i++)
4978 if (SYMBOL_TYPE (syms[i].symbol)->code () != TYPE_CODE_ENUM)
4979 return 0;
4980
4981 /* Quick check: They should all have the same value. */
4982 for (i = 1; i < syms.size (); i++)
4983 if (SYMBOL_VALUE (syms[i].symbol) != SYMBOL_VALUE (syms[0].symbol))
4984 return 0;
4985
4986 /* Quick check: They should all have the same number of enumerals. */
4987 for (i = 1; i < syms.size (); i++)
4988 if (SYMBOL_TYPE (syms[i].symbol)->num_fields ()
4989 != SYMBOL_TYPE (syms[0].symbol)->num_fields ())
4990 return 0;
4991
4992 /* All the sanity checks passed, so we might have a set of
4993 identical enumeration types. Perform a more complete
4994 comparison of the type of each symbol. */
4995 for (i = 1; i < syms.size (); i++)
4996 if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].symbol),
4997 SYMBOL_TYPE (syms[0].symbol)))
4998 return 0;
4999
5000 return 1;
5001 }
5002
5003 /* Remove any non-debugging symbols in SYMS that definitely
5004 duplicate other symbols in the list (The only case I know of where
5005 this happens is when object files containing stabs-in-ecoff are
5006 linked with files containing ordinary ecoff debugging symbols (or no
5007 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
5008
5009 static void
5010 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5011 {
5012 int i, j;
5013
5014 /* We should never be called with less than 2 symbols, as there
5015 cannot be any extra symbol in that case. But it's easy to
5016 handle, since we have nothing to do in that case. */
5017 if (syms->size () < 2)
5018 return;
5019
5020 i = 0;
5021 while (i < syms->size ())
5022 {
5023 int remove_p = 0;
5024
5025 /* If two symbols have the same name and one of them is a stub type,
5026 the get rid of the stub. */
5027
5028 if (SYMBOL_TYPE ((*syms)[i].symbol)->is_stub ()
5029 && (*syms)[i].symbol->linkage_name () != NULL)
5030 {
5031 for (j = 0; j < syms->size (); j++)
5032 {
5033 if (j != i
5034 && !SYMBOL_TYPE ((*syms)[j].symbol)->is_stub ()
5035 && (*syms)[j].symbol->linkage_name () != NULL
5036 && strcmp ((*syms)[i].symbol->linkage_name (),
5037 (*syms)[j].symbol->linkage_name ()) == 0)
5038 remove_p = 1;
5039 }
5040 }
5041
5042 /* Two symbols with the same name, same class and same address
5043 should be identical. */
5044
5045 else if ((*syms)[i].symbol->linkage_name () != NULL
5046 && SYMBOL_CLASS ((*syms)[i].symbol) == LOC_STATIC
5047 && is_nondebugging_type (SYMBOL_TYPE ((*syms)[i].symbol)))
5048 {
5049 for (j = 0; j < syms->size (); j += 1)
5050 {
5051 if (i != j
5052 && (*syms)[j].symbol->linkage_name () != NULL
5053 && strcmp ((*syms)[i].symbol->linkage_name (),
5054 (*syms)[j].symbol->linkage_name ()) == 0
5055 && SYMBOL_CLASS ((*syms)[i].symbol)
5056 == SYMBOL_CLASS ((*syms)[j].symbol)
5057 && SYMBOL_VALUE_ADDRESS ((*syms)[i].symbol)
5058 == SYMBOL_VALUE_ADDRESS ((*syms)[j].symbol))
5059 remove_p = 1;
5060 }
5061 }
5062
5063 if (remove_p)
5064 syms->erase (syms->begin () + i);
5065 else
5066 i += 1;
5067 }
5068
5069 /* If all the remaining symbols are identical enumerals, then
5070 just keep the first one and discard the rest.
5071
5072 Unlike what we did previously, we do not discard any entry
5073 unless they are ALL identical. This is because the symbol
5074 comparison is not a strict comparison, but rather a practical
5075 comparison. If all symbols are considered identical, then
5076 we can just go ahead and use the first one and discard the rest.
5077 But if we cannot reduce the list to a single element, we have
5078 to ask the user to disambiguate anyways. And if we have to
5079 present a multiple-choice menu, it's less confusing if the list
5080 isn't missing some choices that were identical and yet distinct. */
5081 if (symbols_are_identical_enums (*syms))
5082 syms->resize (1);
5083 }
5084
5085 /* Given a type that corresponds to a renaming entity, use the type name
5086 to extract the scope (package name or function name, fully qualified,
5087 and following the GNAT encoding convention) where this renaming has been
5088 defined. */
5089
5090 static std::string
5091 xget_renaming_scope (struct type *renaming_type)
5092 {
5093 /* The renaming types adhere to the following convention:
5094 <scope>__<rename>___<XR extension>.
5095 So, to extract the scope, we search for the "___XR" extension,
5096 and then backtrack until we find the first "__". */
5097
5098 const char *name = renaming_type->name ();
5099 const char *suffix = strstr (name, "___XR");
5100 const char *last;
5101
5102 /* Now, backtrack a bit until we find the first "__". Start looking
5103 at suffix - 3, as the <rename> part is at least one character long. */
5104
5105 for (last = suffix - 3; last > name; last--)
5106 if (last[0] == '_' && last[1] == '_')
5107 break;
5108
5109 /* Make a copy of scope and return it. */
5110 return std::string (name, last);
5111 }
5112
5113 /* Return nonzero if NAME corresponds to a package name. */
5114
5115 static int
5116 is_package_name (const char *name)
5117 {
5118 /* Here, We take advantage of the fact that no symbols are generated
5119 for packages, while symbols are generated for each function.
5120 So the condition for NAME represent a package becomes equivalent
5121 to NAME not existing in our list of symbols. There is only one
5122 small complication with library-level functions (see below). */
5123
5124 /* If it is a function that has not been defined at library level,
5125 then we should be able to look it up in the symbols. */
5126 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5127 return 0;
5128
5129 /* Library-level function names start with "_ada_". See if function
5130 "_ada_" followed by NAME can be found. */
5131
5132 /* Do a quick check that NAME does not contain "__", since library-level
5133 functions names cannot contain "__" in them. */
5134 if (strstr (name, "__") != NULL)
5135 return 0;
5136
5137 std::string fun_name = string_printf ("_ada_%s", name);
5138
5139 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5140 }
5141
5142 /* Return nonzero if SYM corresponds to a renaming entity that is
5143 not visible from FUNCTION_NAME. */
5144
5145 static int
5146 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5147 {
5148 if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
5149 return 0;
5150
5151 std::string scope = xget_renaming_scope (SYMBOL_TYPE (sym));
5152
5153 /* If the rename has been defined in a package, then it is visible. */
5154 if (is_package_name (scope.c_str ()))
5155 return 0;
5156
5157 /* Check that the rename is in the current function scope by checking
5158 that its name starts with SCOPE. */
5159
5160 /* If the function name starts with "_ada_", it means that it is
5161 a library-level function. Strip this prefix before doing the
5162 comparison, as the encoding for the renaming does not contain
5163 this prefix. */
5164 if (startswith (function_name, "_ada_"))
5165 function_name += 5;
5166
5167 return !startswith (function_name, scope.c_str ());
5168 }
5169
5170 /* Remove entries from SYMS that corresponds to a renaming entity that
5171 is not visible from the function associated with CURRENT_BLOCK or
5172 that is superfluous due to the presence of more specific renaming
5173 information. Places surviving symbols in the initial entries of
5174 SYMS.
5175
5176 Rationale:
5177 First, in cases where an object renaming is implemented as a
5178 reference variable, GNAT may produce both the actual reference
5179 variable and the renaming encoding. In this case, we discard the
5180 latter.
5181
5182 Second, GNAT emits a type following a specified encoding for each renaming
5183 entity. Unfortunately, STABS currently does not support the definition
5184 of types that are local to a given lexical block, so all renamings types
5185 are emitted at library level. As a consequence, if an application
5186 contains two renaming entities using the same name, and a user tries to
5187 print the value of one of these entities, the result of the ada symbol
5188 lookup will also contain the wrong renaming type.
5189
5190 This function partially covers for this limitation by attempting to
5191 remove from the SYMS list renaming symbols that should be visible
5192 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5193 method with the current information available. The implementation
5194 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5195
5196 - When the user tries to print a rename in a function while there
5197 is another rename entity defined in a package: Normally, the
5198 rename in the function has precedence over the rename in the
5199 package, so the latter should be removed from the list. This is
5200 currently not the case.
5201
5202 - This function will incorrectly remove valid renames if
5203 the CURRENT_BLOCK corresponds to a function which symbol name
5204 has been changed by an "Export" pragma. As a consequence,
5205 the user will be unable to print such rename entities. */
5206
5207 static void
5208 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5209 const struct block *current_block)
5210 {
5211 struct symbol *current_function;
5212 const char *current_function_name;
5213 int i;
5214 int is_new_style_renaming;
5215
5216 /* If there is both a renaming foo___XR... encoded as a variable and
5217 a simple variable foo in the same block, discard the latter.
5218 First, zero out such symbols, then compress. */
5219 is_new_style_renaming = 0;
5220 for (i = 0; i < syms->size (); i += 1)
5221 {
5222 struct symbol *sym = (*syms)[i].symbol;
5223 const struct block *block = (*syms)[i].block;
5224 const char *name;
5225 const char *suffix;
5226
5227 if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
5228 continue;
5229 name = sym->linkage_name ();
5230 suffix = strstr (name, "___XR");
5231
5232 if (suffix != NULL)
5233 {
5234 int name_len = suffix - name;
5235 int j;
5236
5237 is_new_style_renaming = 1;
5238 for (j = 0; j < syms->size (); j += 1)
5239 if (i != j && (*syms)[j].symbol != NULL
5240 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5241 name_len) == 0
5242 && block == (*syms)[j].block)
5243 (*syms)[j].symbol = NULL;
5244 }
5245 }
5246 if (is_new_style_renaming)
5247 {
5248 int j, k;
5249
5250 for (j = k = 0; j < syms->size (); j += 1)
5251 if ((*syms)[j].symbol != NULL)
5252 {
5253 (*syms)[k] = (*syms)[j];
5254 k += 1;
5255 }
5256 syms->resize (k);
5257 return;
5258 }
5259
5260 /* Extract the function name associated to CURRENT_BLOCK.
5261 Abort if unable to do so. */
5262
5263 if (current_block == NULL)
5264 return;
5265
5266 current_function = block_linkage_function (current_block);
5267 if (current_function == NULL)
5268 return;
5269
5270 current_function_name = current_function->linkage_name ();
5271 if (current_function_name == NULL)
5272 return;
5273
5274 /* Check each of the symbols, and remove it from the list if it is
5275 a type corresponding to a renaming that is out of the scope of
5276 the current block. */
5277
5278 i = 0;
5279 while (i < syms->size ())
5280 {
5281 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5282 == ADA_OBJECT_RENAMING
5283 && old_renaming_is_invisible ((*syms)[i].symbol,
5284 current_function_name))
5285 syms->erase (syms->begin () + i);
5286 else
5287 i += 1;
5288 }
5289 }
5290
5291 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
5292 whose name and domain match NAME and DOMAIN respectively.
5293 If no match was found, then extend the search to "enclosing"
5294 routines (in other words, if we're inside a nested function,
5295 search the symbols defined inside the enclosing functions).
5296 If WILD_MATCH_P is nonzero, perform the naming matching in
5297 "wild" mode (see function "wild_match" for more info).
5298
5299 Note: This function assumes that RESULT has 0 (zero) element in it. */
5300
5301 static void
5302 ada_add_local_symbols (std::vector<struct block_symbol> &result,
5303 const lookup_name_info &lookup_name,
5304 const struct block *block, domain_enum domain)
5305 {
5306 int block_depth = 0;
5307
5308 while (block != NULL)
5309 {
5310 block_depth += 1;
5311 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5312
5313 /* If we found a non-function match, assume that's the one. */
5314 if (is_nonfunction (result))
5315 return;
5316
5317 block = BLOCK_SUPERBLOCK (block);
5318 }
5319
5320 /* If no luck so far, try to find NAME as a local symbol in some lexically
5321 enclosing subprogram. */
5322 if (result.empty () && block_depth > 2)
5323 add_symbols_from_enclosing_procs (result, lookup_name, domain);
5324 }
5325
5326 /* An object of this type is used as the user_data argument when
5327 calling the map_matching_symbols method. */
5328
5329 struct match_data
5330 {
5331 explicit match_data (std::vector<struct block_symbol> *rp)
5332 : resultp (rp)
5333 {
5334 }
5335 DISABLE_COPY_AND_ASSIGN (match_data);
5336
5337 struct objfile *objfile = nullptr;
5338 std::vector<struct block_symbol> *resultp;
5339 struct symbol *arg_sym = nullptr;
5340 bool found_sym = false;
5341 };
5342
5343 /* A callback for add_nonlocal_symbols that adds symbol, found in BSYM,
5344 to a list of symbols. DATA is a pointer to a struct match_data *
5345 containing the vector that collects the symbol list, the file that SYM
5346 must come from, a flag indicating whether a non-argument symbol has
5347 been found in the current block, and the last argument symbol
5348 passed in SYM within the current block (if any). When SYM is null,
5349 marking the end of a block, the argument symbol is added if no
5350 other has been found. */
5351
5352 static bool
5353 aux_add_nonlocal_symbols (struct block_symbol *bsym,
5354 struct match_data *data)
5355 {
5356 const struct block *block = bsym->block;
5357 struct symbol *sym = bsym->symbol;
5358
5359 if (sym == NULL)
5360 {
5361 if (!data->found_sym && data->arg_sym != NULL)
5362 add_defn_to_vec (*data->resultp,
5363 fixup_symbol_section (data->arg_sym, data->objfile),
5364 block);
5365 data->found_sym = false;
5366 data->arg_sym = NULL;
5367 }
5368 else
5369 {
5370 if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5371 return true;
5372 else if (SYMBOL_IS_ARGUMENT (sym))
5373 data->arg_sym = sym;
5374 else
5375 {
5376 data->found_sym = true;
5377 add_defn_to_vec (*data->resultp,
5378 fixup_symbol_section (sym, data->objfile),
5379 block);
5380 }
5381 }
5382 return true;
5383 }
5384
5385 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5386 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5387 symbols to RESULT. Return whether we found such symbols. */
5388
5389 static int
5390 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5391 const struct block *block,
5392 const lookup_name_info &lookup_name,
5393 domain_enum domain)
5394 {
5395 struct using_direct *renaming;
5396 int defns_mark = result.size ();
5397
5398 symbol_name_matcher_ftype *name_match
5399 = ada_get_symbol_name_matcher (lookup_name);
5400
5401 for (renaming = block_using (block);
5402 renaming != NULL;
5403 renaming = renaming->next)
5404 {
5405 const char *r_name;
5406
5407 /* Avoid infinite recursions: skip this renaming if we are actually
5408 already traversing it.
5409
5410 Currently, symbol lookup in Ada don't use the namespace machinery from
5411 C++/Fortran support: skip namespace imports that use them. */
5412 if (renaming->searched
5413 || (renaming->import_src != NULL
5414 && renaming->import_src[0] != '\0')
5415 || (renaming->import_dest != NULL
5416 && renaming->import_dest[0] != '\0'))
5417 continue;
5418 renaming->searched = 1;
5419
5420 /* TODO: here, we perform another name-based symbol lookup, which can
5421 pull its own multiple overloads. In theory, we should be able to do
5422 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5423 not a simple name. But in order to do this, we would need to enhance
5424 the DWARF reader to associate a symbol to this renaming, instead of a
5425 name. So, for now, we do something simpler: re-use the C++/Fortran
5426 namespace machinery. */
5427 r_name = (renaming->alias != NULL
5428 ? renaming->alias
5429 : renaming->declaration);
5430 if (name_match (r_name, lookup_name, NULL))
5431 {
5432 lookup_name_info decl_lookup_name (renaming->declaration,
5433 lookup_name.match_type ());
5434 ada_add_all_symbols (result, block, decl_lookup_name, domain,
5435 1, NULL);
5436 }
5437 renaming->searched = 0;
5438 }
5439 return result.size () != defns_mark;
5440 }
5441
5442 /* Implements compare_names, but only applying the comparision using
5443 the given CASING. */
5444
5445 static int
5446 compare_names_with_case (const char *string1, const char *string2,
5447 enum case_sensitivity casing)
5448 {
5449 while (*string1 != '\0' && *string2 != '\0')
5450 {
5451 char c1, c2;
5452
5453 if (isspace (*string1) || isspace (*string2))
5454 return strcmp_iw_ordered (string1, string2);
5455
5456 if (casing == case_sensitive_off)
5457 {
5458 c1 = tolower (*string1);
5459 c2 = tolower (*string2);
5460 }
5461 else
5462 {
5463 c1 = *string1;
5464 c2 = *string2;
5465 }
5466 if (c1 != c2)
5467 break;
5468
5469 string1 += 1;
5470 string2 += 1;
5471 }
5472
5473 switch (*string1)
5474 {
5475 case '(':
5476 return strcmp_iw_ordered (string1, string2);
5477 case '_':
5478 if (*string2 == '\0')
5479 {
5480 if (is_name_suffix (string1))
5481 return 0;
5482 else
5483 return 1;
5484 }
5485 /* FALLTHROUGH */
5486 default:
5487 if (*string2 == '(')
5488 return strcmp_iw_ordered (string1, string2);
5489 else
5490 {
5491 if (casing == case_sensitive_off)
5492 return tolower (*string1) - tolower (*string2);
5493 else
5494 return *string1 - *string2;
5495 }
5496 }
5497 }
5498
5499 /* Compare STRING1 to STRING2, with results as for strcmp.
5500 Compatible with strcmp_iw_ordered in that...
5501
5502 strcmp_iw_ordered (STRING1, STRING2) <= 0
5503
5504 ... implies...
5505
5506 compare_names (STRING1, STRING2) <= 0
5507
5508 (they may differ as to what symbols compare equal). */
5509
5510 static int
5511 compare_names (const char *string1, const char *string2)
5512 {
5513 int result;
5514
5515 /* Similar to what strcmp_iw_ordered does, we need to perform
5516 a case-insensitive comparison first, and only resort to
5517 a second, case-sensitive, comparison if the first one was
5518 not sufficient to differentiate the two strings. */
5519
5520 result = compare_names_with_case (string1, string2, case_sensitive_off);
5521 if (result == 0)
5522 result = compare_names_with_case (string1, string2, case_sensitive_on);
5523
5524 return result;
5525 }
5526
5527 /* Convenience function to get at the Ada encoded lookup name for
5528 LOOKUP_NAME, as a C string. */
5529
5530 static const char *
5531 ada_lookup_name (const lookup_name_info &lookup_name)
5532 {
5533 return lookup_name.ada ().lookup_name ().c_str ();
5534 }
5535
5536 /* Add to RESULT all non-local symbols whose name and domain match
5537 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5538 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5539 symbols otherwise. */
5540
5541 static void
5542 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5543 const lookup_name_info &lookup_name,
5544 domain_enum domain, int global)
5545 {
5546 struct match_data data (&result);
5547
5548 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5549
5550 auto callback = [&] (struct block_symbol *bsym)
5551 {
5552 return aux_add_nonlocal_symbols (bsym, &data);
5553 };
5554
5555 for (objfile *objfile : current_program_space->objfiles ())
5556 {
5557 data.objfile = objfile;
5558
5559 if (objfile->sf != nullptr)
5560 objfile->sf->qf->map_matching_symbols (objfile, lookup_name,
5561 domain, global, callback,
5562 (is_wild_match
5563 ? NULL : compare_names));
5564
5565 for (compunit_symtab *cu : objfile->compunits ())
5566 {
5567 const struct block *global_block
5568 = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cu), GLOBAL_BLOCK);
5569
5570 if (ada_add_block_renamings (result, global_block, lookup_name,
5571 domain))
5572 data.found_sym = true;
5573 }
5574 }
5575
5576 if (result.empty () && global && !is_wild_match)
5577 {
5578 const char *name = ada_lookup_name (lookup_name);
5579 std::string bracket_name = std::string ("<_ada_") + name + '>';
5580 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5581
5582 for (objfile *objfile : current_program_space->objfiles ())
5583 {
5584 data.objfile = objfile;
5585 if (objfile->sf != nullptr)
5586 objfile->sf->qf->map_matching_symbols (objfile, name1,
5587 domain, global, callback,
5588 compare_names);
5589 }
5590 }
5591 }
5592
5593 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5594 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5595 returning the number of matches. Add these to RESULT.
5596
5597 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5598 symbol match within the nest of blocks whose innermost member is BLOCK,
5599 is the one match returned (no other matches in that or
5600 enclosing blocks is returned). If there are any matches in or
5601 surrounding BLOCK, then these alone are returned.
5602
5603 Names prefixed with "standard__" are handled specially:
5604 "standard__" is first stripped off (by the lookup_name
5605 constructor), and only static and global symbols are searched.
5606
5607 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5608 to lookup global symbols. */
5609
5610 static void
5611 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5612 const struct block *block,
5613 const lookup_name_info &lookup_name,
5614 domain_enum domain,
5615 int full_search,
5616 int *made_global_lookup_p)
5617 {
5618 struct symbol *sym;
5619
5620 if (made_global_lookup_p)
5621 *made_global_lookup_p = 0;
5622
5623 /* Special case: If the user specifies a symbol name inside package
5624 Standard, do a non-wild matching of the symbol name without
5625 the "standard__" prefix. This was primarily introduced in order
5626 to allow the user to specifically access the standard exceptions
5627 using, for instance, Standard.Constraint_Error when Constraint_Error
5628 is ambiguous (due to the user defining its own Constraint_Error
5629 entity inside its program). */
5630 if (lookup_name.ada ().standard_p ())
5631 block = NULL;
5632
5633 /* Check the non-global symbols. If we have ANY match, then we're done. */
5634
5635 if (block != NULL)
5636 {
5637 if (full_search)
5638 ada_add_local_symbols (result, lookup_name, block, domain);
5639 else
5640 {
5641 /* In the !full_search case we're are being called by
5642 iterate_over_symbols, and we don't want to search
5643 superblocks. */
5644 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5645 }
5646 if (!result.empty () || !full_search)
5647 return;
5648 }
5649
5650 /* No non-global symbols found. Check our cache to see if we have
5651 already performed this search before. If we have, then return
5652 the same result. */
5653
5654 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5655 domain, &sym, &block))
5656 {
5657 if (sym != NULL)
5658 add_defn_to_vec (result, sym, block);
5659 return;
5660 }
5661
5662 if (made_global_lookup_p)
5663 *made_global_lookup_p = 1;
5664
5665 /* Search symbols from all global blocks. */
5666
5667 add_nonlocal_symbols (result, lookup_name, domain, 1);
5668
5669 /* Now add symbols from all per-file blocks if we've gotten no hits
5670 (not strictly correct, but perhaps better than an error). */
5671
5672 if (result.empty ())
5673 add_nonlocal_symbols (result, lookup_name, domain, 0);
5674 }
5675
5676 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5677 is non-zero, enclosing scope and in global scopes.
5678
5679 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5680 blocks and symbol tables (if any) in which they were found.
5681
5682 When full_search is non-zero, any non-function/non-enumeral
5683 symbol match within the nest of blocks whose innermost member is BLOCK,
5684 is the one match returned (no other matches in that or
5685 enclosing blocks is returned). If there are any matches in or
5686 surrounding BLOCK, then these alone are returned.
5687
5688 Names prefixed with "standard__" are handled specially: "standard__"
5689 is first stripped off, and only static and global symbols are searched. */
5690
5691 static std::vector<struct block_symbol>
5692 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5693 const struct block *block,
5694 domain_enum domain,
5695 int full_search)
5696 {
5697 int syms_from_global_search;
5698 std::vector<struct block_symbol> results;
5699
5700 ada_add_all_symbols (results, block, lookup_name,
5701 domain, full_search, &syms_from_global_search);
5702
5703 remove_extra_symbols (&results);
5704
5705 if (results.empty () && full_search && syms_from_global_search)
5706 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5707
5708 if (results.size () == 1 && full_search && syms_from_global_search)
5709 cache_symbol (ada_lookup_name (lookup_name), domain,
5710 results[0].symbol, results[0].block);
5711
5712 remove_irrelevant_renamings (&results, block);
5713 return results;
5714 }
5715
5716 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5717 in global scopes, returning (SYM,BLOCK) tuples.
5718
5719 See ada_lookup_symbol_list_worker for further details. */
5720
5721 std::vector<struct block_symbol>
5722 ada_lookup_symbol_list (const char *name, const struct block *block,
5723 domain_enum domain)
5724 {
5725 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5726 lookup_name_info lookup_name (name, name_match_type);
5727
5728 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5729 }
5730
5731 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5732 to 1, but choosing the first symbol found if there are multiple
5733 choices.
5734
5735 The result is stored in *INFO, which must be non-NULL.
5736 If no match is found, INFO->SYM is set to NULL. */
5737
5738 void
5739 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5740 domain_enum domain,
5741 struct block_symbol *info)
5742 {
5743 /* Since we already have an encoded name, wrap it in '<>' to force a
5744 verbatim match. Otherwise, if the name happens to not look like
5745 an encoded name (because it doesn't include a "__"),
5746 ada_lookup_name_info would re-encode/fold it again, and that
5747 would e.g., incorrectly lowercase object renaming names like
5748 "R28b" -> "r28b". */
5749 std::string verbatim = add_angle_brackets (name);
5750
5751 gdb_assert (info != NULL);
5752 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5753 }
5754
5755 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5756 scope and in global scopes, or NULL if none. NAME is folded and
5757 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5758 choosing the first symbol if there are multiple choices. */
5759
5760 struct block_symbol
5761 ada_lookup_symbol (const char *name, const struct block *block0,
5762 domain_enum domain)
5763 {
5764 std::vector<struct block_symbol> candidates
5765 = ada_lookup_symbol_list (name, block0, domain);
5766
5767 if (candidates.empty ())
5768 return {};
5769
5770 block_symbol info = candidates[0];
5771 info.symbol = fixup_symbol_section (info.symbol, NULL);
5772 return info;
5773 }
5774
5775
5776 /* True iff STR is a possible encoded suffix of a normal Ada name
5777 that is to be ignored for matching purposes. Suffixes of parallel
5778 names (e.g., XVE) are not included here. Currently, the possible suffixes
5779 are given by any of the regular expressions:
5780
5781 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5782 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5783 TKB [subprogram suffix for task bodies]
5784 _E[0-9]+[bs]$ [protected object entry suffixes]
5785 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5786
5787 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5788 match is performed. This sequence is used to differentiate homonyms,
5789 is an optional part of a valid name suffix. */
5790
5791 static int
5792 is_name_suffix (const char *str)
5793 {
5794 int k;
5795 const char *matching;
5796 const int len = strlen (str);
5797
5798 /* Skip optional leading __[0-9]+. */
5799
5800 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5801 {
5802 str += 3;
5803 while (isdigit (str[0]))
5804 str += 1;
5805 }
5806
5807 /* [.$][0-9]+ */
5808
5809 if (str[0] == '.' || str[0] == '$')
5810 {
5811 matching = str + 1;
5812 while (isdigit (matching[0]))
5813 matching += 1;
5814 if (matching[0] == '\0')
5815 return 1;
5816 }
5817
5818 /* ___[0-9]+ */
5819
5820 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5821 {
5822 matching = str + 3;
5823 while (isdigit (matching[0]))
5824 matching += 1;
5825 if (matching[0] == '\0')
5826 return 1;
5827 }
5828
5829 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5830
5831 if (strcmp (str, "TKB") == 0)
5832 return 1;
5833
5834 #if 0
5835 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5836 with a N at the end. Unfortunately, the compiler uses the same
5837 convention for other internal types it creates. So treating
5838 all entity names that end with an "N" as a name suffix causes
5839 some regressions. For instance, consider the case of an enumerated
5840 type. To support the 'Image attribute, it creates an array whose
5841 name ends with N.
5842 Having a single character like this as a suffix carrying some
5843 information is a bit risky. Perhaps we should change the encoding
5844 to be something like "_N" instead. In the meantime, do not do
5845 the following check. */
5846 /* Protected Object Subprograms */
5847 if (len == 1 && str [0] == 'N')
5848 return 1;
5849 #endif
5850
5851 /* _E[0-9]+[bs]$ */
5852 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5853 {
5854 matching = str + 3;
5855 while (isdigit (matching[0]))
5856 matching += 1;
5857 if ((matching[0] == 'b' || matching[0] == 's')
5858 && matching [1] == '\0')
5859 return 1;
5860 }
5861
5862 /* ??? We should not modify STR directly, as we are doing below. This
5863 is fine in this case, but may become problematic later if we find
5864 that this alternative did not work, and want to try matching
5865 another one from the begining of STR. Since we modified it, we
5866 won't be able to find the begining of the string anymore! */
5867 if (str[0] == 'X')
5868 {
5869 str += 1;
5870 while (str[0] != '_' && str[0] != '\0')
5871 {
5872 if (str[0] != 'n' && str[0] != 'b')
5873 return 0;
5874 str += 1;
5875 }
5876 }
5877
5878 if (str[0] == '\000')
5879 return 1;
5880
5881 if (str[0] == '_')
5882 {
5883 if (str[1] != '_' || str[2] == '\000')
5884 return 0;
5885 if (str[2] == '_')
5886 {
5887 if (strcmp (str + 3, "JM") == 0)
5888 return 1;
5889 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5890 the LJM suffix in favor of the JM one. But we will
5891 still accept LJM as a valid suffix for a reasonable
5892 amount of time, just to allow ourselves to debug programs
5893 compiled using an older version of GNAT. */
5894 if (strcmp (str + 3, "LJM") == 0)
5895 return 1;
5896 if (str[3] != 'X')
5897 return 0;
5898 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5899 || str[4] == 'U' || str[4] == 'P')
5900 return 1;
5901 if (str[4] == 'R' && str[5] != 'T')
5902 return 1;
5903 return 0;
5904 }
5905 if (!isdigit (str[2]))
5906 return 0;
5907 for (k = 3; str[k] != '\0'; k += 1)
5908 if (!isdigit (str[k]) && str[k] != '_')
5909 return 0;
5910 return 1;
5911 }
5912 if (str[0] == '$' && isdigit (str[1]))
5913 {
5914 for (k = 2; str[k] != '\0'; k += 1)
5915 if (!isdigit (str[k]) && str[k] != '_')
5916 return 0;
5917 return 1;
5918 }
5919 return 0;
5920 }
5921
5922 /* Return non-zero if the string starting at NAME and ending before
5923 NAME_END contains no capital letters. */
5924
5925 static int
5926 is_valid_name_for_wild_match (const char *name0)
5927 {
5928 std::string decoded_name = ada_decode (name0);
5929 int i;
5930
5931 /* If the decoded name starts with an angle bracket, it means that
5932 NAME0 does not follow the GNAT encoding format. It should then
5933 not be allowed as a possible wild match. */
5934 if (decoded_name[0] == '<')
5935 return 0;
5936
5937 for (i=0; decoded_name[i] != '\0'; i++)
5938 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5939 return 0;
5940
5941 return 1;
5942 }
5943
5944 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5945 character which could start a simple name. Assumes that *NAMEP points
5946 somewhere inside the string beginning at NAME0. */
5947
5948 static int
5949 advance_wild_match (const char **namep, const char *name0, char target0)
5950 {
5951 const char *name = *namep;
5952
5953 while (1)
5954 {
5955 char t0, t1;
5956
5957 t0 = *name;
5958 if (t0 == '_')
5959 {
5960 t1 = name[1];
5961 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5962 {
5963 name += 1;
5964 if (name == name0 + 5 && startswith (name0, "_ada"))
5965 break;
5966 else
5967 name += 1;
5968 }
5969 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5970 || name[2] == target0))
5971 {
5972 name += 2;
5973 break;
5974 }
5975 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5976 {
5977 /* Names like "pkg__B_N__name", where N is a number, are
5978 block-local. We can handle these by simply skipping
5979 the "B_" here. */
5980 name += 4;
5981 }
5982 else
5983 return 0;
5984 }
5985 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5986 name += 1;
5987 else
5988 return 0;
5989 }
5990
5991 *namep = name;
5992 return 1;
5993 }
5994
5995 /* Return true iff NAME encodes a name of the form prefix.PATN.
5996 Ignores any informational suffixes of NAME (i.e., for which
5997 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5998 simple name. */
5999
6000 static bool
6001 wild_match (const char *name, const char *patn)
6002 {
6003 const char *p;
6004 const char *name0 = name;
6005
6006 while (1)
6007 {
6008 const char *match = name;
6009
6010 if (*name == *patn)
6011 {
6012 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6013 if (*p != *name)
6014 break;
6015 if (*p == '\0' && is_name_suffix (name))
6016 return match == name0 || is_valid_name_for_wild_match (name0);
6017
6018 if (name[-1] == '_')
6019 name -= 1;
6020 }
6021 if (!advance_wild_match (&name, name0, *patn))
6022 return false;
6023 }
6024 }
6025
6026 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
6027 necessary). OBJFILE is the section containing BLOCK. */
6028
6029 static void
6030 ada_add_block_symbols (std::vector<struct block_symbol> &result,
6031 const struct block *block,
6032 const lookup_name_info &lookup_name,
6033 domain_enum domain, struct objfile *objfile)
6034 {
6035 struct block_iterator iter;
6036 /* A matching argument symbol, if any. */
6037 struct symbol *arg_sym;
6038 /* Set true when we find a matching non-argument symbol. */
6039 bool found_sym;
6040 struct symbol *sym;
6041
6042 arg_sym = NULL;
6043 found_sym = false;
6044 for (sym = block_iter_match_first (block, lookup_name, &iter);
6045 sym != NULL;
6046 sym = block_iter_match_next (lookup_name, &iter))
6047 {
6048 if (symbol_matches_domain (sym->language (), SYMBOL_DOMAIN (sym), domain))
6049 {
6050 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6051 {
6052 if (SYMBOL_IS_ARGUMENT (sym))
6053 arg_sym = sym;
6054 else
6055 {
6056 found_sym = true;
6057 add_defn_to_vec (result,
6058 fixup_symbol_section (sym, objfile),
6059 block);
6060 }
6061 }
6062 }
6063 }
6064
6065 /* Handle renamings. */
6066
6067 if (ada_add_block_renamings (result, block, lookup_name, domain))
6068 found_sym = true;
6069
6070 if (!found_sym && arg_sym != NULL)
6071 {
6072 add_defn_to_vec (result,
6073 fixup_symbol_section (arg_sym, objfile),
6074 block);
6075 }
6076
6077 if (!lookup_name.ada ().wild_match_p ())
6078 {
6079 arg_sym = NULL;
6080 found_sym = false;
6081 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6082 const char *name = ada_lookup_name.c_str ();
6083 size_t name_len = ada_lookup_name.size ();
6084
6085 ALL_BLOCK_SYMBOLS (block, iter, sym)
6086 {
6087 if (symbol_matches_domain (sym->language (),
6088 SYMBOL_DOMAIN (sym), domain))
6089 {
6090 int cmp;
6091
6092 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6093 if (cmp == 0)
6094 {
6095 cmp = !startswith (sym->linkage_name (), "_ada_");
6096 if (cmp == 0)
6097 cmp = strncmp (name, sym->linkage_name () + 5,
6098 name_len);
6099 }
6100
6101 if (cmp == 0
6102 && is_name_suffix (sym->linkage_name () + name_len + 5))
6103 {
6104 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6105 {
6106 if (SYMBOL_IS_ARGUMENT (sym))
6107 arg_sym = sym;
6108 else
6109 {
6110 found_sym = true;
6111 add_defn_to_vec (result,
6112 fixup_symbol_section (sym, objfile),
6113 block);
6114 }
6115 }
6116 }
6117 }
6118 }
6119
6120 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6121 They aren't parameters, right? */
6122 if (!found_sym && arg_sym != NULL)
6123 {
6124 add_defn_to_vec (result,
6125 fixup_symbol_section (arg_sym, objfile),
6126 block);
6127 }
6128 }
6129 }
6130 \f
6131
6132 /* Symbol Completion */
6133
6134 /* See symtab.h. */
6135
6136 bool
6137 ada_lookup_name_info::matches
6138 (const char *sym_name,
6139 symbol_name_match_type match_type,
6140 completion_match_result *comp_match_res) const
6141 {
6142 bool match = false;
6143 const char *text = m_encoded_name.c_str ();
6144 size_t text_len = m_encoded_name.size ();
6145
6146 /* First, test against the fully qualified name of the symbol. */
6147
6148 if (strncmp (sym_name, text, text_len) == 0)
6149 match = true;
6150
6151 std::string decoded_name = ada_decode (sym_name);
6152 if (match && !m_encoded_p)
6153 {
6154 /* One needed check before declaring a positive match is to verify
6155 that iff we are doing a verbatim match, the decoded version
6156 of the symbol name starts with '<'. Otherwise, this symbol name
6157 is not a suitable completion. */
6158
6159 bool has_angle_bracket = (decoded_name[0] == '<');
6160 match = (has_angle_bracket == m_verbatim_p);
6161 }
6162
6163 if (match && !m_verbatim_p)
6164 {
6165 /* When doing non-verbatim match, another check that needs to
6166 be done is to verify that the potentially matching symbol name
6167 does not include capital letters, because the ada-mode would
6168 not be able to understand these symbol names without the
6169 angle bracket notation. */
6170 const char *tmp;
6171
6172 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6173 if (*tmp != '\0')
6174 match = false;
6175 }
6176
6177 /* Second: Try wild matching... */
6178
6179 if (!match && m_wild_match_p)
6180 {
6181 /* Since we are doing wild matching, this means that TEXT
6182 may represent an unqualified symbol name. We therefore must
6183 also compare TEXT against the unqualified name of the symbol. */
6184 sym_name = ada_unqualified_name (decoded_name.c_str ());
6185
6186 if (strncmp (sym_name, text, text_len) == 0)
6187 match = true;
6188 }
6189
6190 /* Finally: If we found a match, prepare the result to return. */
6191
6192 if (!match)
6193 return false;
6194
6195 if (comp_match_res != NULL)
6196 {
6197 std::string &match_str = comp_match_res->match.storage ();
6198
6199 if (!m_encoded_p)
6200 match_str = ada_decode (sym_name);
6201 else
6202 {
6203 if (m_verbatim_p)
6204 match_str = add_angle_brackets (sym_name);
6205 else
6206 match_str = sym_name;
6207
6208 }
6209
6210 comp_match_res->set_match (match_str.c_str ());
6211 }
6212
6213 return true;
6214 }
6215
6216 /* Field Access */
6217
6218 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6219 for tagged types. */
6220
6221 static int
6222 ada_is_dispatch_table_ptr_type (struct type *type)
6223 {
6224 const char *name;
6225
6226 if (type->code () != TYPE_CODE_PTR)
6227 return 0;
6228
6229 name = TYPE_TARGET_TYPE (type)->name ();
6230 if (name == NULL)
6231 return 0;
6232
6233 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6234 }
6235
6236 /* Return non-zero if TYPE is an interface tag. */
6237
6238 static int
6239 ada_is_interface_tag (struct type *type)
6240 {
6241 const char *name = type->name ();
6242
6243 if (name == NULL)
6244 return 0;
6245
6246 return (strcmp (name, "ada__tags__interface_tag") == 0);
6247 }
6248
6249 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6250 to be invisible to users. */
6251
6252 int
6253 ada_is_ignored_field (struct type *type, int field_num)
6254 {
6255 if (field_num < 0 || field_num > type->num_fields ())
6256 return 1;
6257
6258 /* Check the name of that field. */
6259 {
6260 const char *name = TYPE_FIELD_NAME (type, field_num);
6261
6262 /* Anonymous field names should not be printed.
6263 brobecker/2007-02-20: I don't think this can actually happen
6264 but we don't want to print the value of anonymous fields anyway. */
6265 if (name == NULL)
6266 return 1;
6267
6268 /* Normally, fields whose name start with an underscore ("_")
6269 are fields that have been internally generated by the compiler,
6270 and thus should not be printed. The "_parent" field is special,
6271 however: This is a field internally generated by the compiler
6272 for tagged types, and it contains the components inherited from
6273 the parent type. This field should not be printed as is, but
6274 should not be ignored either. */
6275 if (name[0] == '_' && !startswith (name, "_parent"))
6276 return 1;
6277 }
6278
6279 /* If this is the dispatch table of a tagged type or an interface tag,
6280 then ignore. */
6281 if (ada_is_tagged_type (type, 1)
6282 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6283 || ada_is_interface_tag (type->field (field_num).type ())))
6284 return 1;
6285
6286 /* Not a special field, so it should not be ignored. */
6287 return 0;
6288 }
6289
6290 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6291 pointer or reference type whose ultimate target has a tag field. */
6292
6293 int
6294 ada_is_tagged_type (struct type *type, int refok)
6295 {
6296 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6297 }
6298
6299 /* True iff TYPE represents the type of X'Tag */
6300
6301 int
6302 ada_is_tag_type (struct type *type)
6303 {
6304 type = ada_check_typedef (type);
6305
6306 if (type == NULL || type->code () != TYPE_CODE_PTR)
6307 return 0;
6308 else
6309 {
6310 const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
6311
6312 return (name != NULL
6313 && strcmp (name, "ada__tags__dispatch_table") == 0);
6314 }
6315 }
6316
6317 /* The type of the tag on VAL. */
6318
6319 static struct type *
6320 ada_tag_type (struct value *val)
6321 {
6322 return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6323 }
6324
6325 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6326 retired at Ada 05). */
6327
6328 static int
6329 is_ada95_tag (struct value *tag)
6330 {
6331 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6332 }
6333
6334 /* The value of the tag on VAL. */
6335
6336 static struct value *
6337 ada_value_tag (struct value *val)
6338 {
6339 return ada_value_struct_elt (val, "_tag", 0);
6340 }
6341
6342 /* The value of the tag on the object of type TYPE whose contents are
6343 saved at VALADDR, if it is non-null, or is at memory address
6344 ADDRESS. */
6345
6346 static struct value *
6347 value_tag_from_contents_and_address (struct type *type,
6348 const gdb_byte *valaddr,
6349 CORE_ADDR address)
6350 {
6351 int tag_byte_offset;
6352 struct type *tag_type;
6353
6354 if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
6355 NULL, NULL, NULL))
6356 {
6357 const gdb_byte *valaddr1 = ((valaddr == NULL)
6358 ? NULL
6359 : valaddr + tag_byte_offset);
6360 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6361
6362 return value_from_contents_and_address (tag_type, valaddr1, address1);
6363 }
6364 return NULL;
6365 }
6366
6367 static struct type *
6368 type_from_tag (struct value *tag)
6369 {
6370 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6371
6372 if (type_name != NULL)
6373 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6374 return NULL;
6375 }
6376
6377 /* Given a value OBJ of a tagged type, return a value of this
6378 type at the base address of the object. The base address, as
6379 defined in Ada.Tags, it is the address of the primary tag of
6380 the object, and therefore where the field values of its full
6381 view can be fetched. */
6382
6383 struct value *
6384 ada_tag_value_at_base_address (struct value *obj)
6385 {
6386 struct value *val;
6387 LONGEST offset_to_top = 0;
6388 struct type *ptr_type, *obj_type;
6389 struct value *tag;
6390 CORE_ADDR base_address;
6391
6392 obj_type = value_type (obj);
6393
6394 /* It is the responsability of the caller to deref pointers. */
6395
6396 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6397 return obj;
6398
6399 tag = ada_value_tag (obj);
6400 if (!tag)
6401 return obj;
6402
6403 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6404
6405 if (is_ada95_tag (tag))
6406 return obj;
6407
6408 ptr_type = language_lookup_primitive_type
6409 (language_def (language_ada), target_gdbarch(), "storage_offset");
6410 ptr_type = lookup_pointer_type (ptr_type);
6411 val = value_cast (ptr_type, tag);
6412 if (!val)
6413 return obj;
6414
6415 /* It is perfectly possible that an exception be raised while
6416 trying to determine the base address, just like for the tag;
6417 see ada_tag_name for more details. We do not print the error
6418 message for the same reason. */
6419
6420 try
6421 {
6422 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6423 }
6424
6425 catch (const gdb_exception_error &e)
6426 {
6427 return obj;
6428 }
6429
6430 /* If offset is null, nothing to do. */
6431
6432 if (offset_to_top == 0)
6433 return obj;
6434
6435 /* -1 is a special case in Ada.Tags; however, what should be done
6436 is not quite clear from the documentation. So do nothing for
6437 now. */
6438
6439 if (offset_to_top == -1)
6440 return obj;
6441
6442 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6443 from the base address. This was however incompatible with
6444 C++ dispatch table: C++ uses a *negative* value to *add*
6445 to the base address. Ada's convention has therefore been
6446 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6447 use the same convention. Here, we support both cases by
6448 checking the sign of OFFSET_TO_TOP. */
6449
6450 if (offset_to_top > 0)
6451 offset_to_top = -offset_to_top;
6452
6453 base_address = value_address (obj) + offset_to_top;
6454 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6455
6456 /* Make sure that we have a proper tag at the new address.
6457 Otherwise, offset_to_top is bogus (which can happen when
6458 the object is not initialized yet). */
6459
6460 if (!tag)
6461 return obj;
6462
6463 obj_type = type_from_tag (tag);
6464
6465 if (!obj_type)
6466 return obj;
6467
6468 return value_from_contents_and_address (obj_type, NULL, base_address);
6469 }
6470
6471 /* Return the "ada__tags__type_specific_data" type. */
6472
6473 static struct type *
6474 ada_get_tsd_type (struct inferior *inf)
6475 {
6476 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6477
6478 if (data->tsd_type == 0)
6479 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6480 return data->tsd_type;
6481 }
6482
6483 /* Return the TSD (type-specific data) associated to the given TAG.
6484 TAG is assumed to be the tag of a tagged-type entity.
6485
6486 May return NULL if we are unable to get the TSD. */
6487
6488 static struct value *
6489 ada_get_tsd_from_tag (struct value *tag)
6490 {
6491 struct value *val;
6492 struct type *type;
6493
6494 /* First option: The TSD is simply stored as a field of our TAG.
6495 Only older versions of GNAT would use this format, but we have
6496 to test it first, because there are no visible markers for
6497 the current approach except the absence of that field. */
6498
6499 val = ada_value_struct_elt (tag, "tsd", 1);
6500 if (val)
6501 return val;
6502
6503 /* Try the second representation for the dispatch table (in which
6504 there is no explicit 'tsd' field in the referent of the tag pointer,
6505 and instead the tsd pointer is stored just before the dispatch
6506 table. */
6507
6508 type = ada_get_tsd_type (current_inferior());
6509 if (type == NULL)
6510 return NULL;
6511 type = lookup_pointer_type (lookup_pointer_type (type));
6512 val = value_cast (type, tag);
6513 if (val == NULL)
6514 return NULL;
6515 return value_ind (value_ptradd (val, -1));
6516 }
6517
6518 /* Given the TSD of a tag (type-specific data), return a string
6519 containing the name of the associated type.
6520
6521 May return NULL if we are unable to determine the tag name. */
6522
6523 static gdb::unique_xmalloc_ptr<char>
6524 ada_tag_name_from_tsd (struct value *tsd)
6525 {
6526 char *p;
6527 struct value *val;
6528
6529 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6530 if (val == NULL)
6531 return NULL;
6532 gdb::unique_xmalloc_ptr<char> buffer
6533 = target_read_string (value_as_address (val), INT_MAX);
6534 if (buffer == nullptr)
6535 return nullptr;
6536
6537 for (p = buffer.get (); *p != '\0'; ++p)
6538 {
6539 if (isalpha (*p))
6540 *p = tolower (*p);
6541 }
6542
6543 return buffer;
6544 }
6545
6546 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6547 a C string.
6548
6549 Return NULL if the TAG is not an Ada tag, or if we were unable to
6550 determine the name of that tag. */
6551
6552 gdb::unique_xmalloc_ptr<char>
6553 ada_tag_name (struct value *tag)
6554 {
6555 gdb::unique_xmalloc_ptr<char> name;
6556
6557 if (!ada_is_tag_type (value_type (tag)))
6558 return NULL;
6559
6560 /* It is perfectly possible that an exception be raised while trying
6561 to determine the TAG's name, even under normal circumstances:
6562 The associated variable may be uninitialized or corrupted, for
6563 instance. We do not let any exception propagate past this point.
6564 instead we return NULL.
6565
6566 We also do not print the error message either (which often is very
6567 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6568 the caller print a more meaningful message if necessary. */
6569 try
6570 {
6571 struct value *tsd = ada_get_tsd_from_tag (tag);
6572
6573 if (tsd != NULL)
6574 name = ada_tag_name_from_tsd (tsd);
6575 }
6576 catch (const gdb_exception_error &e)
6577 {
6578 }
6579
6580 return name;
6581 }
6582
6583 /* The parent type of TYPE, or NULL if none. */
6584
6585 struct type *
6586 ada_parent_type (struct type *type)
6587 {
6588 int i;
6589
6590 type = ada_check_typedef (type);
6591
6592 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6593 return NULL;
6594
6595 for (i = 0; i < type->num_fields (); i += 1)
6596 if (ada_is_parent_field (type, i))
6597 {
6598 struct type *parent_type = type->field (i).type ();
6599
6600 /* If the _parent field is a pointer, then dereference it. */
6601 if (parent_type->code () == TYPE_CODE_PTR)
6602 parent_type = TYPE_TARGET_TYPE (parent_type);
6603 /* If there is a parallel XVS type, get the actual base type. */
6604 parent_type = ada_get_base_type (parent_type);
6605
6606 return ada_check_typedef (parent_type);
6607 }
6608
6609 return NULL;
6610 }
6611
6612 /* True iff field number FIELD_NUM of structure type TYPE contains the
6613 parent-type (inherited) fields of a derived type. Assumes TYPE is
6614 a structure type with at least FIELD_NUM+1 fields. */
6615
6616 int
6617 ada_is_parent_field (struct type *type, int field_num)
6618 {
6619 const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
6620
6621 return (name != NULL
6622 && (startswith (name, "PARENT")
6623 || startswith (name, "_parent")));
6624 }
6625
6626 /* True iff field number FIELD_NUM of structure type TYPE is a
6627 transparent wrapper field (which should be silently traversed when doing
6628 field selection and flattened when printing). Assumes TYPE is a
6629 structure type with at least FIELD_NUM+1 fields. Such fields are always
6630 structures. */
6631
6632 int
6633 ada_is_wrapper_field (struct type *type, int field_num)
6634 {
6635 const char *name = TYPE_FIELD_NAME (type, field_num);
6636
6637 if (name != NULL && strcmp (name, "RETVAL") == 0)
6638 {
6639 /* This happens in functions with "out" or "in out" parameters
6640 which are passed by copy. For such functions, GNAT describes
6641 the function's return type as being a struct where the return
6642 value is in a field called RETVAL, and where the other "out"
6643 or "in out" parameters are fields of that struct. This is not
6644 a wrapper. */
6645 return 0;
6646 }
6647
6648 return (name != NULL
6649 && (startswith (name, "PARENT")
6650 || strcmp (name, "REP") == 0
6651 || startswith (name, "_parent")
6652 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6653 }
6654
6655 /* True iff field number FIELD_NUM of structure or union type TYPE
6656 is a variant wrapper. Assumes TYPE is a structure type with at least
6657 FIELD_NUM+1 fields. */
6658
6659 int
6660 ada_is_variant_part (struct type *type, int field_num)
6661 {
6662 /* Only Ada types are eligible. */
6663 if (!ADA_TYPE_P (type))
6664 return 0;
6665
6666 struct type *field_type = type->field (field_num).type ();
6667
6668 return (field_type->code () == TYPE_CODE_UNION
6669 || (is_dynamic_field (type, field_num)
6670 && (TYPE_TARGET_TYPE (field_type)->code ()
6671 == TYPE_CODE_UNION)));
6672 }
6673
6674 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6675 whose discriminants are contained in the record type OUTER_TYPE,
6676 returns the type of the controlling discriminant for the variant.
6677 May return NULL if the type could not be found. */
6678
6679 struct type *
6680 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6681 {
6682 const char *name = ada_variant_discrim_name (var_type);
6683
6684 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6685 }
6686
6687 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6688 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6689 represents a 'when others' clause; otherwise 0. */
6690
6691 static int
6692 ada_is_others_clause (struct type *type, int field_num)
6693 {
6694 const char *name = TYPE_FIELD_NAME (type, field_num);
6695
6696 return (name != NULL && name[0] == 'O');
6697 }
6698
6699 /* Assuming that TYPE0 is the type of the variant part of a record,
6700 returns the name of the discriminant controlling the variant.
6701 The value is valid until the next call to ada_variant_discrim_name. */
6702
6703 const char *
6704 ada_variant_discrim_name (struct type *type0)
6705 {
6706 static std::string result;
6707 struct type *type;
6708 const char *name;
6709 const char *discrim_end;
6710 const char *discrim_start;
6711
6712 if (type0->code () == TYPE_CODE_PTR)
6713 type = TYPE_TARGET_TYPE (type0);
6714 else
6715 type = type0;
6716
6717 name = ada_type_name (type);
6718
6719 if (name == NULL || name[0] == '\000')
6720 return "";
6721
6722 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6723 discrim_end -= 1)
6724 {
6725 if (startswith (discrim_end, "___XVN"))
6726 break;
6727 }
6728 if (discrim_end == name)
6729 return "";
6730
6731 for (discrim_start = discrim_end; discrim_start != name + 3;
6732 discrim_start -= 1)
6733 {
6734 if (discrim_start == name + 1)
6735 return "";
6736 if ((discrim_start > name + 3
6737 && startswith (discrim_start - 3, "___"))
6738 || discrim_start[-1] == '.')
6739 break;
6740 }
6741
6742 result = std::string (discrim_start, discrim_end - discrim_start);
6743 return result.c_str ();
6744 }
6745
6746 /* Scan STR for a subtype-encoded number, beginning at position K.
6747 Put the position of the character just past the number scanned in
6748 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6749 Return 1 if there was a valid number at the given position, and 0
6750 otherwise. A "subtype-encoded" number consists of the absolute value
6751 in decimal, followed by the letter 'm' to indicate a negative number.
6752 Assumes 0m does not occur. */
6753
6754 int
6755 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6756 {
6757 ULONGEST RU;
6758
6759 if (!isdigit (str[k]))
6760 return 0;
6761
6762 /* Do it the hard way so as not to make any assumption about
6763 the relationship of unsigned long (%lu scan format code) and
6764 LONGEST. */
6765 RU = 0;
6766 while (isdigit (str[k]))
6767 {
6768 RU = RU * 10 + (str[k] - '0');
6769 k += 1;
6770 }
6771
6772 if (str[k] == 'm')
6773 {
6774 if (R != NULL)
6775 *R = (-(LONGEST) (RU - 1)) - 1;
6776 k += 1;
6777 }
6778 else if (R != NULL)
6779 *R = (LONGEST) RU;
6780
6781 /* NOTE on the above: Technically, C does not say what the results of
6782 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6783 number representable as a LONGEST (although either would probably work
6784 in most implementations). When RU>0, the locution in the then branch
6785 above is always equivalent to the negative of RU. */
6786
6787 if (new_k != NULL)
6788 *new_k = k;
6789 return 1;
6790 }
6791
6792 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6793 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6794 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
6795
6796 static int
6797 ada_in_variant (LONGEST val, struct type *type, int field_num)
6798 {
6799 const char *name = TYPE_FIELD_NAME (type, field_num);
6800 int p;
6801
6802 p = 0;
6803 while (1)
6804 {
6805 switch (name[p])
6806 {
6807 case '\0':
6808 return 0;
6809 case 'S':
6810 {
6811 LONGEST W;
6812
6813 if (!ada_scan_number (name, p + 1, &W, &p))
6814 return 0;
6815 if (val == W)
6816 return 1;
6817 break;
6818 }
6819 case 'R':
6820 {
6821 LONGEST L, U;
6822
6823 if (!ada_scan_number (name, p + 1, &L, &p)
6824 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6825 return 0;
6826 if (val >= L && val <= U)
6827 return 1;
6828 break;
6829 }
6830 case 'O':
6831 return 1;
6832 default:
6833 return 0;
6834 }
6835 }
6836 }
6837
6838 /* FIXME: Lots of redundancy below. Try to consolidate. */
6839
6840 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6841 ARG_TYPE, extract and return the value of one of its (non-static)
6842 fields. FIELDNO says which field. Differs from value_primitive_field
6843 only in that it can handle packed values of arbitrary type. */
6844
6845 struct value *
6846 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6847 struct type *arg_type)
6848 {
6849 struct type *type;
6850
6851 arg_type = ada_check_typedef (arg_type);
6852 type = arg_type->field (fieldno).type ();
6853
6854 /* Handle packed fields. It might be that the field is not packed
6855 relative to its containing structure, but the structure itself is
6856 packed; in this case we must take the bit-field path. */
6857 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
6858 {
6859 int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
6860 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6861
6862 return ada_value_primitive_packed_val (arg1, value_contents (arg1),
6863 offset + bit_pos / 8,
6864 bit_pos % 8, bit_size, type);
6865 }
6866 else
6867 return value_primitive_field (arg1, offset, fieldno, arg_type);
6868 }
6869
6870 /* Find field with name NAME in object of type TYPE. If found,
6871 set the following for each argument that is non-null:
6872 - *FIELD_TYPE_P to the field's type;
6873 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6874 an object of that type;
6875 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6876 - *BIT_SIZE_P to its size in bits if the field is packed, and
6877 0 otherwise;
6878 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6879 fields up to but not including the desired field, or by the total
6880 number of fields if not found. A NULL value of NAME never
6881 matches; the function just counts visible fields in this case.
6882
6883 Notice that we need to handle when a tagged record hierarchy
6884 has some components with the same name, like in this scenario:
6885
6886 type Top_T is tagged record
6887 N : Integer := 1;
6888 U : Integer := 974;
6889 A : Integer := 48;
6890 end record;
6891
6892 type Middle_T is new Top.Top_T with record
6893 N : Character := 'a';
6894 C : Integer := 3;
6895 end record;
6896
6897 type Bottom_T is new Middle.Middle_T with record
6898 N : Float := 4.0;
6899 C : Character := '5';
6900 X : Integer := 6;
6901 A : Character := 'J';
6902 end record;
6903
6904 Let's say we now have a variable declared and initialized as follow:
6905
6906 TC : Top_A := new Bottom_T;
6907
6908 And then we use this variable to call this function
6909
6910 procedure Assign (Obj: in out Top_T; TV : Integer);
6911
6912 as follow:
6913
6914 Assign (Top_T (B), 12);
6915
6916 Now, we're in the debugger, and we're inside that procedure
6917 then and we want to print the value of obj.c:
6918
6919 Usually, the tagged record or one of the parent type owns the
6920 component to print and there's no issue but in this particular
6921 case, what does it mean to ask for Obj.C? Since the actual
6922 type for object is type Bottom_T, it could mean two things: type
6923 component C from the Middle_T view, but also component C from
6924 Bottom_T. So in that "undefined" case, when the component is
6925 not found in the non-resolved type (which includes all the
6926 components of the parent type), then resolve it and see if we
6927 get better luck once expanded.
6928
6929 In the case of homonyms in the derived tagged type, we don't
6930 guaranty anything, and pick the one that's easiest for us
6931 to program.
6932
6933 Returns 1 if found, 0 otherwise. */
6934
6935 static int
6936 find_struct_field (const char *name, struct type *type, int offset,
6937 struct type **field_type_p,
6938 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6939 int *index_p)
6940 {
6941 int i;
6942 int parent_offset = -1;
6943
6944 type = ada_check_typedef (type);
6945
6946 if (field_type_p != NULL)
6947 *field_type_p = NULL;
6948 if (byte_offset_p != NULL)
6949 *byte_offset_p = 0;
6950 if (bit_offset_p != NULL)
6951 *bit_offset_p = 0;
6952 if (bit_size_p != NULL)
6953 *bit_size_p = 0;
6954
6955 for (i = 0; i < type->num_fields (); i += 1)
6956 {
6957 int bit_pos = TYPE_FIELD_BITPOS (type, i);
6958 int fld_offset = offset + bit_pos / 8;
6959 const char *t_field_name = TYPE_FIELD_NAME (type, i);
6960
6961 if (t_field_name == NULL)
6962 continue;
6963
6964 else if (ada_is_parent_field (type, i))
6965 {
6966 /* This is a field pointing us to the parent type of a tagged
6967 type. As hinted in this function's documentation, we give
6968 preference to fields in the current record first, so what
6969 we do here is just record the index of this field before
6970 we skip it. If it turns out we couldn't find our field
6971 in the current record, then we'll get back to it and search
6972 inside it whether the field might exist in the parent. */
6973
6974 parent_offset = i;
6975 continue;
6976 }
6977
6978 else if (name != NULL && field_name_match (t_field_name, name))
6979 {
6980 int bit_size = TYPE_FIELD_BITSIZE (type, i);
6981
6982 if (field_type_p != NULL)
6983 *field_type_p = type->field (i).type ();
6984 if (byte_offset_p != NULL)
6985 *byte_offset_p = fld_offset;
6986 if (bit_offset_p != NULL)
6987 *bit_offset_p = bit_pos % 8;
6988 if (bit_size_p != NULL)
6989 *bit_size_p = bit_size;
6990 return 1;
6991 }
6992 else if (ada_is_wrapper_field (type, i))
6993 {
6994 if (find_struct_field (name, type->field (i).type (), fld_offset,
6995 field_type_p, byte_offset_p, bit_offset_p,
6996 bit_size_p, index_p))
6997 return 1;
6998 }
6999 else if (ada_is_variant_part (type, i))
7000 {
7001 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7002 fixed type?? */
7003 int j;
7004 struct type *field_type
7005 = ada_check_typedef (type->field (i).type ());
7006
7007 for (j = 0; j < field_type->num_fields (); j += 1)
7008 {
7009 if (find_struct_field (name, field_type->field (j).type (),
7010 fld_offset
7011 + TYPE_FIELD_BITPOS (field_type, j) / 8,
7012 field_type_p, byte_offset_p,
7013 bit_offset_p, bit_size_p, index_p))
7014 return 1;
7015 }
7016 }
7017 else if (index_p != NULL)
7018 *index_p += 1;
7019 }
7020
7021 /* Field not found so far. If this is a tagged type which
7022 has a parent, try finding that field in the parent now. */
7023
7024 if (parent_offset != -1)
7025 {
7026 int bit_pos = TYPE_FIELD_BITPOS (type, parent_offset);
7027 int fld_offset = offset + bit_pos / 8;
7028
7029 if (find_struct_field (name, type->field (parent_offset).type (),
7030 fld_offset, field_type_p, byte_offset_p,
7031 bit_offset_p, bit_size_p, index_p))
7032 return 1;
7033 }
7034
7035 return 0;
7036 }
7037
7038 /* Number of user-visible fields in record type TYPE. */
7039
7040 static int
7041 num_visible_fields (struct type *type)
7042 {
7043 int n;
7044
7045 n = 0;
7046 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7047 return n;
7048 }
7049
7050 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7051 and search in it assuming it has (class) type TYPE.
7052 If found, return value, else return NULL.
7053
7054 Searches recursively through wrapper fields (e.g., '_parent').
7055
7056 In the case of homonyms in the tagged types, please refer to the
7057 long explanation in find_struct_field's function documentation. */
7058
7059 static struct value *
7060 ada_search_struct_field (const char *name, struct value *arg, int offset,
7061 struct type *type)
7062 {
7063 int i;
7064 int parent_offset = -1;
7065
7066 type = ada_check_typedef (type);
7067 for (i = 0; i < type->num_fields (); i += 1)
7068 {
7069 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7070
7071 if (t_field_name == NULL)
7072 continue;
7073
7074 else if (ada_is_parent_field (type, i))
7075 {
7076 /* This is a field pointing us to the parent type of a tagged
7077 type. As hinted in this function's documentation, we give
7078 preference to fields in the current record first, so what
7079 we do here is just record the index of this field before
7080 we skip it. If it turns out we couldn't find our field
7081 in the current record, then we'll get back to it and search
7082 inside it whether the field might exist in the parent. */
7083
7084 parent_offset = i;
7085 continue;
7086 }
7087
7088 else if (field_name_match (t_field_name, name))
7089 return ada_value_primitive_field (arg, offset, i, type);
7090
7091 else if (ada_is_wrapper_field (type, i))
7092 {
7093 struct value *v = /* Do not let indent join lines here. */
7094 ada_search_struct_field (name, arg,
7095 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7096 type->field (i).type ());
7097
7098 if (v != NULL)
7099 return v;
7100 }
7101
7102 else if (ada_is_variant_part (type, i))
7103 {
7104 /* PNH: Do we ever get here? See find_struct_field. */
7105 int j;
7106 struct type *field_type = ada_check_typedef (type->field (i).type ());
7107 int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
7108
7109 for (j = 0; j < field_type->num_fields (); j += 1)
7110 {
7111 struct value *v = ada_search_struct_field /* Force line
7112 break. */
7113 (name, arg,
7114 var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
7115 field_type->field (j).type ());
7116
7117 if (v != NULL)
7118 return v;
7119 }
7120 }
7121 }
7122
7123 /* Field not found so far. If this is a tagged type which
7124 has a parent, try finding that field in the parent now. */
7125
7126 if (parent_offset != -1)
7127 {
7128 struct value *v = ada_search_struct_field (
7129 name, arg, offset + TYPE_FIELD_BITPOS (type, parent_offset) / 8,
7130 type->field (parent_offset).type ());
7131
7132 if (v != NULL)
7133 return v;
7134 }
7135
7136 return NULL;
7137 }
7138
7139 static struct value *ada_index_struct_field_1 (int *, struct value *,
7140 int, struct type *);
7141
7142
7143 /* Return field #INDEX in ARG, where the index is that returned by
7144 * find_struct_field through its INDEX_P argument. Adjust the address
7145 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7146 * If found, return value, else return NULL. */
7147
7148 static struct value *
7149 ada_index_struct_field (int index, struct value *arg, int offset,
7150 struct type *type)
7151 {
7152 return ada_index_struct_field_1 (&index, arg, offset, type);
7153 }
7154
7155
7156 /* Auxiliary function for ada_index_struct_field. Like
7157 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7158 * *INDEX_P. */
7159
7160 static struct value *
7161 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7162 struct type *type)
7163 {
7164 int i;
7165 type = ada_check_typedef (type);
7166
7167 for (i = 0; i < type->num_fields (); i += 1)
7168 {
7169 if (TYPE_FIELD_NAME (type, i) == NULL)
7170 continue;
7171 else if (ada_is_wrapper_field (type, i))
7172 {
7173 struct value *v = /* Do not let indent join lines here. */
7174 ada_index_struct_field_1 (index_p, arg,
7175 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7176 type->field (i).type ());
7177
7178 if (v != NULL)
7179 return v;
7180 }
7181
7182 else if (ada_is_variant_part (type, i))
7183 {
7184 /* PNH: Do we ever get here? See ada_search_struct_field,
7185 find_struct_field. */
7186 error (_("Cannot assign this kind of variant record"));
7187 }
7188 else if (*index_p == 0)
7189 return ada_value_primitive_field (arg, offset, i, type);
7190 else
7191 *index_p -= 1;
7192 }
7193 return NULL;
7194 }
7195
7196 /* Return a string representation of type TYPE. */
7197
7198 static std::string
7199 type_as_string (struct type *type)
7200 {
7201 string_file tmp_stream;
7202
7203 type_print (type, "", &tmp_stream, -1);
7204
7205 return std::move (tmp_stream.string ());
7206 }
7207
7208 /* Given a type TYPE, look up the type of the component of type named NAME.
7209 If DISPP is non-null, add its byte displacement from the beginning of a
7210 structure (pointed to by a value) of type TYPE to *DISPP (does not
7211 work for packed fields).
7212
7213 Matches any field whose name has NAME as a prefix, possibly
7214 followed by "___".
7215
7216 TYPE can be either a struct or union. If REFOK, TYPE may also
7217 be a (pointer or reference)+ to a struct or union, and the
7218 ultimate target type will be searched.
7219
7220 Looks recursively into variant clauses and parent types.
7221
7222 In the case of homonyms in the tagged types, please refer to the
7223 long explanation in find_struct_field's function documentation.
7224
7225 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7226 TYPE is not a type of the right kind. */
7227
7228 static struct type *
7229 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7230 int noerr)
7231 {
7232 int i;
7233 int parent_offset = -1;
7234
7235 if (name == NULL)
7236 goto BadName;
7237
7238 if (refok && type != NULL)
7239 while (1)
7240 {
7241 type = ada_check_typedef (type);
7242 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7243 break;
7244 type = TYPE_TARGET_TYPE (type);
7245 }
7246
7247 if (type == NULL
7248 || (type->code () != TYPE_CODE_STRUCT
7249 && type->code () != TYPE_CODE_UNION))
7250 {
7251 if (noerr)
7252 return NULL;
7253
7254 error (_("Type %s is not a structure or union type"),
7255 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7256 }
7257
7258 type = to_static_fixed_type (type);
7259
7260 for (i = 0; i < type->num_fields (); i += 1)
7261 {
7262 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7263 struct type *t;
7264
7265 if (t_field_name == NULL)
7266 continue;
7267
7268 else if (ada_is_parent_field (type, i))
7269 {
7270 /* This is a field pointing us to the parent type of a tagged
7271 type. As hinted in this function's documentation, we give
7272 preference to fields in the current record first, so what
7273 we do here is just record the index of this field before
7274 we skip it. If it turns out we couldn't find our field
7275 in the current record, then we'll get back to it and search
7276 inside it whether the field might exist in the parent. */
7277
7278 parent_offset = i;
7279 continue;
7280 }
7281
7282 else if (field_name_match (t_field_name, name))
7283 return type->field (i).type ();
7284
7285 else if (ada_is_wrapper_field (type, i))
7286 {
7287 t = ada_lookup_struct_elt_type (type->field (i).type (), name,
7288 0, 1);
7289 if (t != NULL)
7290 return t;
7291 }
7292
7293 else if (ada_is_variant_part (type, i))
7294 {
7295 int j;
7296 struct type *field_type = ada_check_typedef (type->field (i).type ());
7297
7298 for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7299 {
7300 /* FIXME pnh 2008/01/26: We check for a field that is
7301 NOT wrapped in a struct, since the compiler sometimes
7302 generates these for unchecked variant types. Revisit
7303 if the compiler changes this practice. */
7304 const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
7305
7306 if (v_field_name != NULL
7307 && field_name_match (v_field_name, name))
7308 t = field_type->field (j).type ();
7309 else
7310 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
7311 name, 0, 1);
7312
7313 if (t != NULL)
7314 return t;
7315 }
7316 }
7317
7318 }
7319
7320 /* Field not found so far. If this is a tagged type which
7321 has a parent, try finding that field in the parent now. */
7322
7323 if (parent_offset != -1)
7324 {
7325 struct type *t;
7326
7327 t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7328 name, 0, 1);
7329 if (t != NULL)
7330 return t;
7331 }
7332
7333 BadName:
7334 if (!noerr)
7335 {
7336 const char *name_str = name != NULL ? name : _("<null>");
7337
7338 error (_("Type %s has no component named %s"),
7339 type_as_string (type).c_str (), name_str);
7340 }
7341
7342 return NULL;
7343 }
7344
7345 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7346 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7347 represents an unchecked union (that is, the variant part of a
7348 record that is named in an Unchecked_Union pragma). */
7349
7350 static int
7351 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7352 {
7353 const char *discrim_name = ada_variant_discrim_name (var_type);
7354
7355 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7356 }
7357
7358
7359 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7360 within OUTER, determine which variant clause (field number in VAR_TYPE,
7361 numbering from 0) is applicable. Returns -1 if none are. */
7362
7363 int
7364 ada_which_variant_applies (struct type *var_type, struct value *outer)
7365 {
7366 int others_clause;
7367 int i;
7368 const char *discrim_name = ada_variant_discrim_name (var_type);
7369 struct value *discrim;
7370 LONGEST discrim_val;
7371
7372 /* Using plain value_from_contents_and_address here causes problems
7373 because we will end up trying to resolve a type that is currently
7374 being constructed. */
7375 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7376 if (discrim == NULL)
7377 return -1;
7378 discrim_val = value_as_long (discrim);
7379
7380 others_clause = -1;
7381 for (i = 0; i < var_type->num_fields (); i += 1)
7382 {
7383 if (ada_is_others_clause (var_type, i))
7384 others_clause = i;
7385 else if (ada_in_variant (discrim_val, var_type, i))
7386 return i;
7387 }
7388
7389 return others_clause;
7390 }
7391 \f
7392
7393
7394 /* Dynamic-Sized Records */
7395
7396 /* Strategy: The type ostensibly attached to a value with dynamic size
7397 (i.e., a size that is not statically recorded in the debugging
7398 data) does not accurately reflect the size or layout of the value.
7399 Our strategy is to convert these values to values with accurate,
7400 conventional types that are constructed on the fly. */
7401
7402 /* There is a subtle and tricky problem here. In general, we cannot
7403 determine the size of dynamic records without its data. However,
7404 the 'struct value' data structure, which GDB uses to represent
7405 quantities in the inferior process (the target), requires the size
7406 of the type at the time of its allocation in order to reserve space
7407 for GDB's internal copy of the data. That's why the
7408 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7409 rather than struct value*s.
7410
7411 However, GDB's internal history variables ($1, $2, etc.) are
7412 struct value*s containing internal copies of the data that are not, in
7413 general, the same as the data at their corresponding addresses in
7414 the target. Fortunately, the types we give to these values are all
7415 conventional, fixed-size types (as per the strategy described
7416 above), so that we don't usually have to perform the
7417 'to_fixed_xxx_type' conversions to look at their values.
7418 Unfortunately, there is one exception: if one of the internal
7419 history variables is an array whose elements are unconstrained
7420 records, then we will need to create distinct fixed types for each
7421 element selected. */
7422
7423 /* The upshot of all of this is that many routines take a (type, host
7424 address, target address) triple as arguments to represent a value.
7425 The host address, if non-null, is supposed to contain an internal
7426 copy of the relevant data; otherwise, the program is to consult the
7427 target at the target address. */
7428
7429 /* Assuming that VAL0 represents a pointer value, the result of
7430 dereferencing it. Differs from value_ind in its treatment of
7431 dynamic-sized types. */
7432
7433 struct value *
7434 ada_value_ind (struct value *val0)
7435 {
7436 struct value *val = value_ind (val0);
7437
7438 if (ada_is_tagged_type (value_type (val), 0))
7439 val = ada_tag_value_at_base_address (val);
7440
7441 return ada_to_fixed_value (val);
7442 }
7443
7444 /* The value resulting from dereferencing any "reference to"
7445 qualifiers on VAL0. */
7446
7447 static struct value *
7448 ada_coerce_ref (struct value *val0)
7449 {
7450 if (value_type (val0)->code () == TYPE_CODE_REF)
7451 {
7452 struct value *val = val0;
7453
7454 val = coerce_ref (val);
7455
7456 if (ada_is_tagged_type (value_type (val), 0))
7457 val = ada_tag_value_at_base_address (val);
7458
7459 return ada_to_fixed_value (val);
7460 }
7461 else
7462 return val0;
7463 }
7464
7465 /* Return the bit alignment required for field #F of template type TYPE. */
7466
7467 static unsigned int
7468 field_alignment (struct type *type, int f)
7469 {
7470 const char *name = TYPE_FIELD_NAME (type, f);
7471 int len;
7472 int align_offset;
7473
7474 /* The field name should never be null, unless the debugging information
7475 is somehow malformed. In this case, we assume the field does not
7476 require any alignment. */
7477 if (name == NULL)
7478 return 1;
7479
7480 len = strlen (name);
7481
7482 if (!isdigit (name[len - 1]))
7483 return 1;
7484
7485 if (isdigit (name[len - 2]))
7486 align_offset = len - 2;
7487 else
7488 align_offset = len - 1;
7489
7490 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7491 return TARGET_CHAR_BIT;
7492
7493 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7494 }
7495
7496 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7497
7498 static struct symbol *
7499 ada_find_any_type_symbol (const char *name)
7500 {
7501 struct symbol *sym;
7502
7503 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7504 if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
7505 return sym;
7506
7507 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7508 return sym;
7509 }
7510
7511 /* Find a type named NAME. Ignores ambiguity. This routine will look
7512 solely for types defined by debug info, it will not search the GDB
7513 primitive types. */
7514
7515 static struct type *
7516 ada_find_any_type (const char *name)
7517 {
7518 struct symbol *sym = ada_find_any_type_symbol (name);
7519
7520 if (sym != NULL)
7521 return SYMBOL_TYPE (sym);
7522
7523 return NULL;
7524 }
7525
7526 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7527 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7528 symbol, in which case it is returned. Otherwise, this looks for
7529 symbols whose name is that of NAME_SYM suffixed with "___XR".
7530 Return symbol if found, and NULL otherwise. */
7531
7532 static bool
7533 ada_is_renaming_symbol (struct symbol *name_sym)
7534 {
7535 const char *name = name_sym->linkage_name ();
7536 return strstr (name, "___XR") != NULL;
7537 }
7538
7539 /* Because of GNAT encoding conventions, several GDB symbols may match a
7540 given type name. If the type denoted by TYPE0 is to be preferred to
7541 that of TYPE1 for purposes of type printing, return non-zero;
7542 otherwise return 0. */
7543
7544 int
7545 ada_prefer_type (struct type *type0, struct type *type1)
7546 {
7547 if (type1 == NULL)
7548 return 1;
7549 else if (type0 == NULL)
7550 return 0;
7551 else if (type1->code () == TYPE_CODE_VOID)
7552 return 1;
7553 else if (type0->code () == TYPE_CODE_VOID)
7554 return 0;
7555 else if (type1->name () == NULL && type0->name () != NULL)
7556 return 1;
7557 else if (ada_is_constrained_packed_array_type (type0))
7558 return 1;
7559 else if (ada_is_array_descriptor_type (type0)
7560 && !ada_is_array_descriptor_type (type1))
7561 return 1;
7562 else
7563 {
7564 const char *type0_name = type0->name ();
7565 const char *type1_name = type1->name ();
7566
7567 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7568 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7569 return 1;
7570 }
7571 return 0;
7572 }
7573
7574 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7575 null. */
7576
7577 const char *
7578 ada_type_name (struct type *type)
7579 {
7580 if (type == NULL)
7581 return NULL;
7582 return type->name ();
7583 }
7584
7585 /* Search the list of "descriptive" types associated to TYPE for a type
7586 whose name is NAME. */
7587
7588 static struct type *
7589 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7590 {
7591 struct type *result, *tmp;
7592
7593 if (ada_ignore_descriptive_types_p)
7594 return NULL;
7595
7596 /* If there no descriptive-type info, then there is no parallel type
7597 to be found. */
7598 if (!HAVE_GNAT_AUX_INFO (type))
7599 return NULL;
7600
7601 result = TYPE_DESCRIPTIVE_TYPE (type);
7602 while (result != NULL)
7603 {
7604 const char *result_name = ada_type_name (result);
7605
7606 if (result_name == NULL)
7607 {
7608 warning (_("unexpected null name on descriptive type"));
7609 return NULL;
7610 }
7611
7612 /* If the names match, stop. */
7613 if (strcmp (result_name, name) == 0)
7614 break;
7615
7616 /* Otherwise, look at the next item on the list, if any. */
7617 if (HAVE_GNAT_AUX_INFO (result))
7618 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7619 else
7620 tmp = NULL;
7621
7622 /* If not found either, try after having resolved the typedef. */
7623 if (tmp != NULL)
7624 result = tmp;
7625 else
7626 {
7627 result = check_typedef (result);
7628 if (HAVE_GNAT_AUX_INFO (result))
7629 result = TYPE_DESCRIPTIVE_TYPE (result);
7630 else
7631 result = NULL;
7632 }
7633 }
7634
7635 /* If we didn't find a match, see whether this is a packed array. With
7636 older compilers, the descriptive type information is either absent or
7637 irrelevant when it comes to packed arrays so the above lookup fails.
7638 Fall back to using a parallel lookup by name in this case. */
7639 if (result == NULL && ada_is_constrained_packed_array_type (type))
7640 return ada_find_any_type (name);
7641
7642 return result;
7643 }
7644
7645 /* Find a parallel type to TYPE with the specified NAME, using the
7646 descriptive type taken from the debugging information, if available,
7647 and otherwise using the (slower) name-based method. */
7648
7649 static struct type *
7650 ada_find_parallel_type_with_name (struct type *type, const char *name)
7651 {
7652 struct type *result = NULL;
7653
7654 if (HAVE_GNAT_AUX_INFO (type))
7655 result = find_parallel_type_by_descriptive_type (type, name);
7656 else
7657 result = ada_find_any_type (name);
7658
7659 return result;
7660 }
7661
7662 /* Same as above, but specify the name of the parallel type by appending
7663 SUFFIX to the name of TYPE. */
7664
7665 struct type *
7666 ada_find_parallel_type (struct type *type, const char *suffix)
7667 {
7668 char *name;
7669 const char *type_name = ada_type_name (type);
7670 int len;
7671
7672 if (type_name == NULL)
7673 return NULL;
7674
7675 len = strlen (type_name);
7676
7677 name = (char *) alloca (len + strlen (suffix) + 1);
7678
7679 strcpy (name, type_name);
7680 strcpy (name + len, suffix);
7681
7682 return ada_find_parallel_type_with_name (type, name);
7683 }
7684
7685 /* If TYPE is a variable-size record type, return the corresponding template
7686 type describing its fields. Otherwise, return NULL. */
7687
7688 static struct type *
7689 dynamic_template_type (struct type *type)
7690 {
7691 type = ada_check_typedef (type);
7692
7693 if (type == NULL || type->code () != TYPE_CODE_STRUCT
7694 || ada_type_name (type) == NULL)
7695 return NULL;
7696 else
7697 {
7698 int len = strlen (ada_type_name (type));
7699
7700 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7701 return type;
7702 else
7703 return ada_find_parallel_type (type, "___XVE");
7704 }
7705 }
7706
7707 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7708 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
7709
7710 static int
7711 is_dynamic_field (struct type *templ_type, int field_num)
7712 {
7713 const char *name = TYPE_FIELD_NAME (templ_type, field_num);
7714
7715 return name != NULL
7716 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7717 && strstr (name, "___XVL") != NULL;
7718 }
7719
7720 /* The index of the variant field of TYPE, or -1 if TYPE does not
7721 represent a variant record type. */
7722
7723 static int
7724 variant_field_index (struct type *type)
7725 {
7726 int f;
7727
7728 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7729 return -1;
7730
7731 for (f = 0; f < type->num_fields (); f += 1)
7732 {
7733 if (ada_is_variant_part (type, f))
7734 return f;
7735 }
7736 return -1;
7737 }
7738
7739 /* A record type with no fields. */
7740
7741 static struct type *
7742 empty_record (struct type *templ)
7743 {
7744 struct type *type = alloc_type_copy (templ);
7745
7746 type->set_code (TYPE_CODE_STRUCT);
7747 INIT_NONE_SPECIFIC (type);
7748 type->set_name ("<empty>");
7749 TYPE_LENGTH (type) = 0;
7750 return type;
7751 }
7752
7753 /* An ordinary record type (with fixed-length fields) that describes
7754 the value of type TYPE at VALADDR or ADDRESS (see comments at
7755 the beginning of this section) VAL according to GNAT conventions.
7756 DVAL0 should describe the (portion of a) record that contains any
7757 necessary discriminants. It should be NULL if value_type (VAL) is
7758 an outer-level type (i.e., as opposed to a branch of a variant.) A
7759 variant field (unless unchecked) is replaced by a particular branch
7760 of the variant.
7761
7762 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7763 length are not statically known are discarded. As a consequence,
7764 VALADDR, ADDRESS and DVAL0 are ignored.
7765
7766 NOTE: Limitations: For now, we assume that dynamic fields and
7767 variants occupy whole numbers of bytes. However, they need not be
7768 byte-aligned. */
7769
7770 struct type *
7771 ada_template_to_fixed_record_type_1 (struct type *type,
7772 const gdb_byte *valaddr,
7773 CORE_ADDR address, struct value *dval0,
7774 int keep_dynamic_fields)
7775 {
7776 struct value *mark = value_mark ();
7777 struct value *dval;
7778 struct type *rtype;
7779 int nfields, bit_len;
7780 int variant_field;
7781 long off;
7782 int fld_bit_len;
7783 int f;
7784
7785 /* Compute the number of fields in this record type that are going
7786 to be processed: unless keep_dynamic_fields, this includes only
7787 fields whose position and length are static will be processed. */
7788 if (keep_dynamic_fields)
7789 nfields = type->num_fields ();
7790 else
7791 {
7792 nfields = 0;
7793 while (nfields < type->num_fields ()
7794 && !ada_is_variant_part (type, nfields)
7795 && !is_dynamic_field (type, nfields))
7796 nfields++;
7797 }
7798
7799 rtype = alloc_type_copy (type);
7800 rtype->set_code (TYPE_CODE_STRUCT);
7801 INIT_NONE_SPECIFIC (rtype);
7802 rtype->set_num_fields (nfields);
7803 rtype->set_fields
7804 ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7805 rtype->set_name (ada_type_name (type));
7806 rtype->set_is_fixed_instance (true);
7807
7808 off = 0;
7809 bit_len = 0;
7810 variant_field = -1;
7811
7812 for (f = 0; f < nfields; f += 1)
7813 {
7814 off = align_up (off, field_alignment (type, f))
7815 + TYPE_FIELD_BITPOS (type, f);
7816 SET_FIELD_BITPOS (rtype->field (f), off);
7817 TYPE_FIELD_BITSIZE (rtype, f) = 0;
7818
7819 if (ada_is_variant_part (type, f))
7820 {
7821 variant_field = f;
7822 fld_bit_len = 0;
7823 }
7824 else if (is_dynamic_field (type, f))
7825 {
7826 const gdb_byte *field_valaddr = valaddr;
7827 CORE_ADDR field_address = address;
7828 struct type *field_type =
7829 TYPE_TARGET_TYPE (type->field (f).type ());
7830
7831 if (dval0 == NULL)
7832 {
7833 /* rtype's length is computed based on the run-time
7834 value of discriminants. If the discriminants are not
7835 initialized, the type size may be completely bogus and
7836 GDB may fail to allocate a value for it. So check the
7837 size first before creating the value. */
7838 ada_ensure_varsize_limit (rtype);
7839 /* Using plain value_from_contents_and_address here
7840 causes problems because we will end up trying to
7841 resolve a type that is currently being
7842 constructed. */
7843 dval = value_from_contents_and_address_unresolved (rtype,
7844 valaddr,
7845 address);
7846 rtype = value_type (dval);
7847 }
7848 else
7849 dval = dval0;
7850
7851 /* If the type referenced by this field is an aligner type, we need
7852 to unwrap that aligner type, because its size might not be set.
7853 Keeping the aligner type would cause us to compute the wrong
7854 size for this field, impacting the offset of the all the fields
7855 that follow this one. */
7856 if (ada_is_aligner_type (field_type))
7857 {
7858 long field_offset = TYPE_FIELD_BITPOS (field_type, f);
7859
7860 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7861 field_address = cond_offset_target (field_address, field_offset);
7862 field_type = ada_aligned_type (field_type);
7863 }
7864
7865 field_valaddr = cond_offset_host (field_valaddr,
7866 off / TARGET_CHAR_BIT);
7867 field_address = cond_offset_target (field_address,
7868 off / TARGET_CHAR_BIT);
7869
7870 /* Get the fixed type of the field. Note that, in this case,
7871 we do not want to get the real type out of the tag: if
7872 the current field is the parent part of a tagged record,
7873 we will get the tag of the object. Clearly wrong: the real
7874 type of the parent is not the real type of the child. We
7875 would end up in an infinite loop. */
7876 field_type = ada_get_base_type (field_type);
7877 field_type = ada_to_fixed_type (field_type, field_valaddr,
7878 field_address, dval, 0);
7879 /* If the field size is already larger than the maximum
7880 object size, then the record itself will necessarily
7881 be larger than the maximum object size. We need to make
7882 this check now, because the size might be so ridiculously
7883 large (due to an uninitialized variable in the inferior)
7884 that it would cause an overflow when adding it to the
7885 record size. */
7886 ada_ensure_varsize_limit (field_type);
7887
7888 rtype->field (f).set_type (field_type);
7889 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7890 /* The multiplication can potentially overflow. But because
7891 the field length has been size-checked just above, and
7892 assuming that the maximum size is a reasonable value,
7893 an overflow should not happen in practice. So rather than
7894 adding overflow recovery code to this already complex code,
7895 we just assume that it's not going to happen. */
7896 fld_bit_len =
7897 TYPE_LENGTH (rtype->field (f).type ()) * TARGET_CHAR_BIT;
7898 }
7899 else
7900 {
7901 /* Note: If this field's type is a typedef, it is important
7902 to preserve the typedef layer.
7903
7904 Otherwise, we might be transforming a typedef to a fat
7905 pointer (encoding a pointer to an unconstrained array),
7906 into a basic fat pointer (encoding an unconstrained
7907 array). As both types are implemented using the same
7908 structure, the typedef is the only clue which allows us
7909 to distinguish between the two options. Stripping it
7910 would prevent us from printing this field appropriately. */
7911 rtype->field (f).set_type (type->field (f).type ());
7912 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7913 if (TYPE_FIELD_BITSIZE (type, f) > 0)
7914 fld_bit_len =
7915 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7916 else
7917 {
7918 struct type *field_type = type->field (f).type ();
7919
7920 /* We need to be careful of typedefs when computing
7921 the length of our field. If this is a typedef,
7922 get the length of the target type, not the length
7923 of the typedef. */
7924 if (field_type->code () == TYPE_CODE_TYPEDEF)
7925 field_type = ada_typedef_target_type (field_type);
7926
7927 fld_bit_len =
7928 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
7929 }
7930 }
7931 if (off + fld_bit_len > bit_len)
7932 bit_len = off + fld_bit_len;
7933 off += fld_bit_len;
7934 TYPE_LENGTH (rtype) =
7935 align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7936 }
7937
7938 /* We handle the variant part, if any, at the end because of certain
7939 odd cases in which it is re-ordered so as NOT to be the last field of
7940 the record. This can happen in the presence of representation
7941 clauses. */
7942 if (variant_field >= 0)
7943 {
7944 struct type *branch_type;
7945
7946 off = TYPE_FIELD_BITPOS (rtype, variant_field);
7947
7948 if (dval0 == NULL)
7949 {
7950 /* Using plain value_from_contents_and_address here causes
7951 problems because we will end up trying to resolve a type
7952 that is currently being constructed. */
7953 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7954 address);
7955 rtype = value_type (dval);
7956 }
7957 else
7958 dval = dval0;
7959
7960 branch_type =
7961 to_fixed_variant_branch_type
7962 (type->field (variant_field).type (),
7963 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7964 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7965 if (branch_type == NULL)
7966 {
7967 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7968 rtype->field (f - 1) = rtype->field (f);
7969 rtype->set_num_fields (rtype->num_fields () - 1);
7970 }
7971 else
7972 {
7973 rtype->field (variant_field).set_type (branch_type);
7974 TYPE_FIELD_NAME (rtype, variant_field) = "S";
7975 fld_bit_len =
7976 TYPE_LENGTH (rtype->field (variant_field).type ()) *
7977 TARGET_CHAR_BIT;
7978 if (off + fld_bit_len > bit_len)
7979 bit_len = off + fld_bit_len;
7980 TYPE_LENGTH (rtype) =
7981 align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7982 }
7983 }
7984
7985 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7986 should contain the alignment of that record, which should be a strictly
7987 positive value. If null or negative, then something is wrong, most
7988 probably in the debug info. In that case, we don't round up the size
7989 of the resulting type. If this record is not part of another structure,
7990 the current RTYPE length might be good enough for our purposes. */
7991 if (TYPE_LENGTH (type) <= 0)
7992 {
7993 if (rtype->name ())
7994 warning (_("Invalid type size for `%s' detected: %s."),
7995 rtype->name (), pulongest (TYPE_LENGTH (type)));
7996 else
7997 warning (_("Invalid type size for <unnamed> detected: %s."),
7998 pulongest (TYPE_LENGTH (type)));
7999 }
8000 else
8001 {
8002 TYPE_LENGTH (rtype) = align_up (TYPE_LENGTH (rtype),
8003 TYPE_LENGTH (type));
8004 }
8005
8006 value_free_to_mark (mark);
8007 if (TYPE_LENGTH (rtype) > varsize_limit)
8008 error (_("record type with dynamic size is larger than varsize-limit"));
8009 return rtype;
8010 }
8011
8012 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8013 of 1. */
8014
8015 static struct type *
8016 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8017 CORE_ADDR address, struct value *dval0)
8018 {
8019 return ada_template_to_fixed_record_type_1 (type, valaddr,
8020 address, dval0, 1);
8021 }
8022
8023 /* An ordinary record type in which ___XVL-convention fields and
8024 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8025 static approximations, containing all possible fields. Uses
8026 no runtime values. Useless for use in values, but that's OK,
8027 since the results are used only for type determinations. Works on both
8028 structs and unions. Representation note: to save space, we memorize
8029 the result of this function in the TYPE_TARGET_TYPE of the
8030 template type. */
8031
8032 static struct type *
8033 template_to_static_fixed_type (struct type *type0)
8034 {
8035 struct type *type;
8036 int nfields;
8037 int f;
8038
8039 /* No need no do anything if the input type is already fixed. */
8040 if (type0->is_fixed_instance ())
8041 return type0;
8042
8043 /* Likewise if we already have computed the static approximation. */
8044 if (TYPE_TARGET_TYPE (type0) != NULL)
8045 return TYPE_TARGET_TYPE (type0);
8046
8047 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8048 type = type0;
8049 nfields = type0->num_fields ();
8050
8051 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8052 recompute all over next time. */
8053 TYPE_TARGET_TYPE (type0) = type;
8054
8055 for (f = 0; f < nfields; f += 1)
8056 {
8057 struct type *field_type = type0->field (f).type ();
8058 struct type *new_type;
8059
8060 if (is_dynamic_field (type0, f))
8061 {
8062 field_type = ada_check_typedef (field_type);
8063 new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
8064 }
8065 else
8066 new_type = static_unwrap_type (field_type);
8067
8068 if (new_type != field_type)
8069 {
8070 /* Clone TYPE0 only the first time we get a new field type. */
8071 if (type == type0)
8072 {
8073 TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
8074 type->set_code (type0->code ());
8075 INIT_NONE_SPECIFIC (type);
8076 type->set_num_fields (nfields);
8077
8078 field *fields =
8079 ((struct field *)
8080 TYPE_ALLOC (type, nfields * sizeof (struct field)));
8081 memcpy (fields, type0->fields (),
8082 sizeof (struct field) * nfields);
8083 type->set_fields (fields);
8084
8085 type->set_name (ada_type_name (type0));
8086 type->set_is_fixed_instance (true);
8087 TYPE_LENGTH (type) = 0;
8088 }
8089 type->field (f).set_type (new_type);
8090 TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
8091 }
8092 }
8093
8094 return type;
8095 }
8096
8097 /* Given an object of type TYPE whose contents are at VALADDR and
8098 whose address in memory is ADDRESS, returns a revision of TYPE,
8099 which should be a non-dynamic-sized record, in which the variant
8100 part, if any, is replaced with the appropriate branch. Looks
8101 for discriminant values in DVAL0, which can be NULL if the record
8102 contains the necessary discriminant values. */
8103
8104 static struct type *
8105 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8106 CORE_ADDR address, struct value *dval0)
8107 {
8108 struct value *mark = value_mark ();
8109 struct value *dval;
8110 struct type *rtype;
8111 struct type *branch_type;
8112 int nfields = type->num_fields ();
8113 int variant_field = variant_field_index (type);
8114
8115 if (variant_field == -1)
8116 return type;
8117
8118 if (dval0 == NULL)
8119 {
8120 dval = value_from_contents_and_address (type, valaddr, address);
8121 type = value_type (dval);
8122 }
8123 else
8124 dval = dval0;
8125
8126 rtype = alloc_type_copy (type);
8127 rtype->set_code (TYPE_CODE_STRUCT);
8128 INIT_NONE_SPECIFIC (rtype);
8129 rtype->set_num_fields (nfields);
8130
8131 field *fields =
8132 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8133 memcpy (fields, type->fields (), sizeof (struct field) * nfields);
8134 rtype->set_fields (fields);
8135
8136 rtype->set_name (ada_type_name (type));
8137 rtype->set_is_fixed_instance (true);
8138 TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
8139
8140 branch_type = to_fixed_variant_branch_type
8141 (type->field (variant_field).type (),
8142 cond_offset_host (valaddr,
8143 TYPE_FIELD_BITPOS (type, variant_field)
8144 / TARGET_CHAR_BIT),
8145 cond_offset_target (address,
8146 TYPE_FIELD_BITPOS (type, variant_field)
8147 / TARGET_CHAR_BIT), dval);
8148 if (branch_type == NULL)
8149 {
8150 int f;
8151
8152 for (f = variant_field + 1; f < nfields; f += 1)
8153 rtype->field (f - 1) = rtype->field (f);
8154 rtype->set_num_fields (rtype->num_fields () - 1);
8155 }
8156 else
8157 {
8158 rtype->field (variant_field).set_type (branch_type);
8159 TYPE_FIELD_NAME (rtype, variant_field) = "S";
8160 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8161 TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
8162 }
8163 TYPE_LENGTH (rtype) -= TYPE_LENGTH (type->field (variant_field).type ());
8164
8165 value_free_to_mark (mark);
8166 return rtype;
8167 }
8168
8169 /* An ordinary record type (with fixed-length fields) that describes
8170 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8171 beginning of this section]. Any necessary discriminants' values
8172 should be in DVAL, a record value; it may be NULL if the object
8173 at ADDR itself contains any necessary discriminant values.
8174 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8175 values from the record are needed. Except in the case that DVAL,
8176 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8177 unchecked) is replaced by a particular branch of the variant.
8178
8179 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8180 is questionable and may be removed. It can arise during the
8181 processing of an unconstrained-array-of-record type where all the
8182 variant branches have exactly the same size. This is because in
8183 such cases, the compiler does not bother to use the XVS convention
8184 when encoding the record. I am currently dubious of this
8185 shortcut and suspect the compiler should be altered. FIXME. */
8186
8187 static struct type *
8188 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8189 CORE_ADDR address, struct value *dval)
8190 {
8191 struct type *templ_type;
8192
8193 if (type0->is_fixed_instance ())
8194 return type0;
8195
8196 templ_type = dynamic_template_type (type0);
8197
8198 if (templ_type != NULL)
8199 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8200 else if (variant_field_index (type0) >= 0)
8201 {
8202 if (dval == NULL && valaddr == NULL && address == 0)
8203 return type0;
8204 return to_record_with_fixed_variant_part (type0, valaddr, address,
8205 dval);
8206 }
8207 else
8208 {
8209 type0->set_is_fixed_instance (true);
8210 return type0;
8211 }
8212
8213 }
8214
8215 /* An ordinary record type (with fixed-length fields) that describes
8216 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8217 union type. Any necessary discriminants' values should be in DVAL,
8218 a record value. That is, this routine selects the appropriate
8219 branch of the union at ADDR according to the discriminant value
8220 indicated in the union's type name. Returns VAR_TYPE0 itself if
8221 it represents a variant subject to a pragma Unchecked_Union. */
8222
8223 static struct type *
8224 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8225 CORE_ADDR address, struct value *dval)
8226 {
8227 int which;
8228 struct type *templ_type;
8229 struct type *var_type;
8230
8231 if (var_type0->code () == TYPE_CODE_PTR)
8232 var_type = TYPE_TARGET_TYPE (var_type0);
8233 else
8234 var_type = var_type0;
8235
8236 templ_type = ada_find_parallel_type (var_type, "___XVU");
8237
8238 if (templ_type != NULL)
8239 var_type = templ_type;
8240
8241 if (is_unchecked_variant (var_type, value_type (dval)))
8242 return var_type0;
8243 which = ada_which_variant_applies (var_type, dval);
8244
8245 if (which < 0)
8246 return empty_record (var_type);
8247 else if (is_dynamic_field (var_type, which))
8248 return to_fixed_record_type
8249 (TYPE_TARGET_TYPE (var_type->field (which).type ()),
8250 valaddr, address, dval);
8251 else if (variant_field_index (var_type->field (which).type ()) >= 0)
8252 return
8253 to_fixed_record_type
8254 (var_type->field (which).type (), valaddr, address, dval);
8255 else
8256 return var_type->field (which).type ();
8257 }
8258
8259 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8260 ENCODING_TYPE, a type following the GNAT conventions for discrete
8261 type encodings, only carries redundant information. */
8262
8263 static int
8264 ada_is_redundant_range_encoding (struct type *range_type,
8265 struct type *encoding_type)
8266 {
8267 const char *bounds_str;
8268 int n;
8269 LONGEST lo, hi;
8270
8271 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8272
8273 if (get_base_type (range_type)->code ()
8274 != get_base_type (encoding_type)->code ())
8275 {
8276 /* The compiler probably used a simple base type to describe
8277 the range type instead of the range's actual base type,
8278 expecting us to get the real base type from the encoding
8279 anyway. In this situation, the encoding cannot be ignored
8280 as redundant. */
8281 return 0;
8282 }
8283
8284 if (is_dynamic_type (range_type))
8285 return 0;
8286
8287 if (encoding_type->name () == NULL)
8288 return 0;
8289
8290 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8291 if (bounds_str == NULL)
8292 return 0;
8293
8294 n = 8; /* Skip "___XDLU_". */
8295 if (!ada_scan_number (bounds_str, n, &lo, &n))
8296 return 0;
8297 if (range_type->bounds ()->low.const_val () != lo)
8298 return 0;
8299
8300 n += 2; /* Skip the "__" separator between the two bounds. */
8301 if (!ada_scan_number (bounds_str, n, &hi, &n))
8302 return 0;
8303 if (range_type->bounds ()->high.const_val () != hi)
8304 return 0;
8305
8306 return 1;
8307 }
8308
8309 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8310 a type following the GNAT encoding for describing array type
8311 indices, only carries redundant information. */
8312
8313 static int
8314 ada_is_redundant_index_type_desc (struct type *array_type,
8315 struct type *desc_type)
8316 {
8317 struct type *this_layer = check_typedef (array_type);
8318 int i;
8319
8320 for (i = 0; i < desc_type->num_fields (); i++)
8321 {
8322 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8323 desc_type->field (i).type ()))
8324 return 0;
8325 this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
8326 }
8327
8328 return 1;
8329 }
8330
8331 /* Assuming that TYPE0 is an array type describing the type of a value
8332 at ADDR, and that DVAL describes a record containing any
8333 discriminants used in TYPE0, returns a type for the value that
8334 contains no dynamic components (that is, no components whose sizes
8335 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8336 true, gives an error message if the resulting type's size is over
8337 varsize_limit. */
8338
8339 static struct type *
8340 to_fixed_array_type (struct type *type0, struct value *dval,
8341 int ignore_too_big)
8342 {
8343 struct type *index_type_desc;
8344 struct type *result;
8345 int constrained_packed_array_p;
8346 static const char *xa_suffix = "___XA";
8347
8348 type0 = ada_check_typedef (type0);
8349 if (type0->is_fixed_instance ())
8350 return type0;
8351
8352 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8353 if (constrained_packed_array_p)
8354 {
8355 type0 = decode_constrained_packed_array_type (type0);
8356 if (type0 == nullptr)
8357 error (_("could not decode constrained packed array type"));
8358 }
8359
8360 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8361
8362 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8363 encoding suffixed with 'P' may still be generated. If so,
8364 it should be used to find the XA type. */
8365
8366 if (index_type_desc == NULL)
8367 {
8368 const char *type_name = ada_type_name (type0);
8369
8370 if (type_name != NULL)
8371 {
8372 const int len = strlen (type_name);
8373 char *name = (char *) alloca (len + strlen (xa_suffix));
8374
8375 if (type_name[len - 1] == 'P')
8376 {
8377 strcpy (name, type_name);
8378 strcpy (name + len - 1, xa_suffix);
8379 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8380 }
8381 }
8382 }
8383
8384 ada_fixup_array_indexes_type (index_type_desc);
8385 if (index_type_desc != NULL
8386 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8387 {
8388 /* Ignore this ___XA parallel type, as it does not bring any
8389 useful information. This allows us to avoid creating fixed
8390 versions of the array's index types, which would be identical
8391 to the original ones. This, in turn, can also help avoid
8392 the creation of fixed versions of the array itself. */
8393 index_type_desc = NULL;
8394 }
8395
8396 if (index_type_desc == NULL)
8397 {
8398 struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8399
8400 /* NOTE: elt_type---the fixed version of elt_type0---should never
8401 depend on the contents of the array in properly constructed
8402 debugging data. */
8403 /* Create a fixed version of the array element type.
8404 We're not providing the address of an element here,
8405 and thus the actual object value cannot be inspected to do
8406 the conversion. This should not be a problem, since arrays of
8407 unconstrained objects are not allowed. In particular, all
8408 the elements of an array of a tagged type should all be of
8409 the same type specified in the debugging info. No need to
8410 consult the object tag. */
8411 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8412
8413 /* Make sure we always create a new array type when dealing with
8414 packed array types, since we're going to fix-up the array
8415 type length and element bitsize a little further down. */
8416 if (elt_type0 == elt_type && !constrained_packed_array_p)
8417 result = type0;
8418 else
8419 result = create_array_type (alloc_type_copy (type0),
8420 elt_type, type0->index_type ());
8421 }
8422 else
8423 {
8424 int i;
8425 struct type *elt_type0;
8426
8427 elt_type0 = type0;
8428 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8429 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8430
8431 /* NOTE: result---the fixed version of elt_type0---should never
8432 depend on the contents of the array in properly constructed
8433 debugging data. */
8434 /* Create a fixed version of the array element type.
8435 We're not providing the address of an element here,
8436 and thus the actual object value cannot be inspected to do
8437 the conversion. This should not be a problem, since arrays of
8438 unconstrained objects are not allowed. In particular, all
8439 the elements of an array of a tagged type should all be of
8440 the same type specified in the debugging info. No need to
8441 consult the object tag. */
8442 result =
8443 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8444
8445 elt_type0 = type0;
8446 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8447 {
8448 struct type *range_type =
8449 to_fixed_range_type (index_type_desc->field (i).type (), dval);
8450
8451 result = create_array_type (alloc_type_copy (elt_type0),
8452 result, range_type);
8453 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8454 }
8455 if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
8456 error (_("array type with dynamic size is larger than varsize-limit"));
8457 }
8458
8459 /* We want to preserve the type name. This can be useful when
8460 trying to get the type name of a value that has already been
8461 printed (for instance, if the user did "print VAR; whatis $". */
8462 result->set_name (type0->name ());
8463
8464 if (constrained_packed_array_p)
8465 {
8466 /* So far, the resulting type has been created as if the original
8467 type was a regular (non-packed) array type. As a result, the
8468 bitsize of the array elements needs to be set again, and the array
8469 length needs to be recomputed based on that bitsize. */
8470 int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8471 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8472
8473 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8474 TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8475 if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8476 TYPE_LENGTH (result)++;
8477 }
8478
8479 result->set_is_fixed_instance (true);
8480 return result;
8481 }
8482
8483
8484 /* A standard type (containing no dynamically sized components)
8485 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8486 DVAL describes a record containing any discriminants used in TYPE0,
8487 and may be NULL if there are none, or if the object of type TYPE at
8488 ADDRESS or in VALADDR contains these discriminants.
8489
8490 If CHECK_TAG is not null, in the case of tagged types, this function
8491 attempts to locate the object's tag and use it to compute the actual
8492 type. However, when ADDRESS is null, we cannot use it to determine the
8493 location of the tag, and therefore compute the tagged type's actual type.
8494 So we return the tagged type without consulting the tag. */
8495
8496 static struct type *
8497 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8498 CORE_ADDR address, struct value *dval, int check_tag)
8499 {
8500 type = ada_check_typedef (type);
8501
8502 /* Only un-fixed types need to be handled here. */
8503 if (!HAVE_GNAT_AUX_INFO (type))
8504 return type;
8505
8506 switch (type->code ())
8507 {
8508 default:
8509 return type;
8510 case TYPE_CODE_STRUCT:
8511 {
8512 struct type *static_type = to_static_fixed_type (type);
8513 struct type *fixed_record_type =
8514 to_fixed_record_type (type, valaddr, address, NULL);
8515
8516 /* If STATIC_TYPE is a tagged type and we know the object's address,
8517 then we can determine its tag, and compute the object's actual
8518 type from there. Note that we have to use the fixed record
8519 type (the parent part of the record may have dynamic fields
8520 and the way the location of _tag is expressed may depend on
8521 them). */
8522
8523 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8524 {
8525 struct value *tag =
8526 value_tag_from_contents_and_address
8527 (fixed_record_type,
8528 valaddr,
8529 address);
8530 struct type *real_type = type_from_tag (tag);
8531 struct value *obj =
8532 value_from_contents_and_address (fixed_record_type,
8533 valaddr,
8534 address);
8535 fixed_record_type = value_type (obj);
8536 if (real_type != NULL)
8537 return to_fixed_record_type
8538 (real_type, NULL,
8539 value_address (ada_tag_value_at_base_address (obj)), NULL);
8540 }
8541
8542 /* Check to see if there is a parallel ___XVZ variable.
8543 If there is, then it provides the actual size of our type. */
8544 else if (ada_type_name (fixed_record_type) != NULL)
8545 {
8546 const char *name = ada_type_name (fixed_record_type);
8547 char *xvz_name
8548 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8549 bool xvz_found = false;
8550 LONGEST size;
8551
8552 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8553 try
8554 {
8555 xvz_found = get_int_var_value (xvz_name, size);
8556 }
8557 catch (const gdb_exception_error &except)
8558 {
8559 /* We found the variable, but somehow failed to read
8560 its value. Rethrow the same error, but with a little
8561 bit more information, to help the user understand
8562 what went wrong (Eg: the variable might have been
8563 optimized out). */
8564 throw_error (except.error,
8565 _("unable to read value of %s (%s)"),
8566 xvz_name, except.what ());
8567 }
8568
8569 if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
8570 {
8571 fixed_record_type = copy_type (fixed_record_type);
8572 TYPE_LENGTH (fixed_record_type) = size;
8573
8574 /* The FIXED_RECORD_TYPE may have be a stub. We have
8575 observed this when the debugging info is STABS, and
8576 apparently it is something that is hard to fix.
8577
8578 In practice, we don't need the actual type definition
8579 at all, because the presence of the XVZ variable allows us
8580 to assume that there must be a XVS type as well, which we
8581 should be able to use later, when we need the actual type
8582 definition.
8583
8584 In the meantime, pretend that the "fixed" type we are
8585 returning is NOT a stub, because this can cause trouble
8586 when using this type to create new types targeting it.
8587 Indeed, the associated creation routines often check
8588 whether the target type is a stub and will try to replace
8589 it, thus using a type with the wrong size. This, in turn,
8590 might cause the new type to have the wrong size too.
8591 Consider the case of an array, for instance, where the size
8592 of the array is computed from the number of elements in
8593 our array multiplied by the size of its element. */
8594 fixed_record_type->set_is_stub (false);
8595 }
8596 }
8597 return fixed_record_type;
8598 }
8599 case TYPE_CODE_ARRAY:
8600 return to_fixed_array_type (type, dval, 1);
8601 case TYPE_CODE_UNION:
8602 if (dval == NULL)
8603 return type;
8604 else
8605 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8606 }
8607 }
8608
8609 /* The same as ada_to_fixed_type_1, except that it preserves the type
8610 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8611
8612 The typedef layer needs be preserved in order to differentiate between
8613 arrays and array pointers when both types are implemented using the same
8614 fat pointer. In the array pointer case, the pointer is encoded as
8615 a typedef of the pointer type. For instance, considering:
8616
8617 type String_Access is access String;
8618 S1 : String_Access := null;
8619
8620 To the debugger, S1 is defined as a typedef of type String. But
8621 to the user, it is a pointer. So if the user tries to print S1,
8622 we should not dereference the array, but print the array address
8623 instead.
8624
8625 If we didn't preserve the typedef layer, we would lose the fact that
8626 the type is to be presented as a pointer (needs de-reference before
8627 being printed). And we would also use the source-level type name. */
8628
8629 struct type *
8630 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8631 CORE_ADDR address, struct value *dval, int check_tag)
8632
8633 {
8634 struct type *fixed_type =
8635 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8636
8637 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8638 then preserve the typedef layer.
8639
8640 Implementation note: We can only check the main-type portion of
8641 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8642 from TYPE now returns a type that has the same instance flags
8643 as TYPE. For instance, if TYPE is a "typedef const", and its
8644 target type is a "struct", then the typedef elimination will return
8645 a "const" version of the target type. See check_typedef for more
8646 details about how the typedef layer elimination is done.
8647
8648 brobecker/2010-11-19: It seems to me that the only case where it is
8649 useful to preserve the typedef layer is when dealing with fat pointers.
8650 Perhaps, we could add a check for that and preserve the typedef layer
8651 only in that situation. But this seems unnecessary so far, probably
8652 because we call check_typedef/ada_check_typedef pretty much everywhere.
8653 */
8654 if (type->code () == TYPE_CODE_TYPEDEF
8655 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8656 == TYPE_MAIN_TYPE (fixed_type)))
8657 return type;
8658
8659 return fixed_type;
8660 }
8661
8662 /* A standard (static-sized) type corresponding as well as possible to
8663 TYPE0, but based on no runtime data. */
8664
8665 static struct type *
8666 to_static_fixed_type (struct type *type0)
8667 {
8668 struct type *type;
8669
8670 if (type0 == NULL)
8671 return NULL;
8672
8673 if (type0->is_fixed_instance ())
8674 return type0;
8675
8676 type0 = ada_check_typedef (type0);
8677
8678 switch (type0->code ())
8679 {
8680 default:
8681 return type0;
8682 case TYPE_CODE_STRUCT:
8683 type = dynamic_template_type (type0);
8684 if (type != NULL)
8685 return template_to_static_fixed_type (type);
8686 else
8687 return template_to_static_fixed_type (type0);
8688 case TYPE_CODE_UNION:
8689 type = ada_find_parallel_type (type0, "___XVU");
8690 if (type != NULL)
8691 return template_to_static_fixed_type (type);
8692 else
8693 return template_to_static_fixed_type (type0);
8694 }
8695 }
8696
8697 /* A static approximation of TYPE with all type wrappers removed. */
8698
8699 static struct type *
8700 static_unwrap_type (struct type *type)
8701 {
8702 if (ada_is_aligner_type (type))
8703 {
8704 struct type *type1 = ada_check_typedef (type)->field (0).type ();
8705 if (ada_type_name (type1) == NULL)
8706 type1->set_name (ada_type_name (type));
8707
8708 return static_unwrap_type (type1);
8709 }
8710 else
8711 {
8712 struct type *raw_real_type = ada_get_base_type (type);
8713
8714 if (raw_real_type == type)
8715 return type;
8716 else
8717 return to_static_fixed_type (raw_real_type);
8718 }
8719 }
8720
8721 /* In some cases, incomplete and private types require
8722 cross-references that are not resolved as records (for example,
8723 type Foo;
8724 type FooP is access Foo;
8725 V: FooP;
8726 type Foo is array ...;
8727 ). In these cases, since there is no mechanism for producing
8728 cross-references to such types, we instead substitute for FooP a
8729 stub enumeration type that is nowhere resolved, and whose tag is
8730 the name of the actual type. Call these types "non-record stubs". */
8731
8732 /* A type equivalent to TYPE that is not a non-record stub, if one
8733 exists, otherwise TYPE. */
8734
8735 struct type *
8736 ada_check_typedef (struct type *type)
8737 {
8738 if (type == NULL)
8739 return NULL;
8740
8741 /* If our type is an access to an unconstrained array, which is encoded
8742 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8743 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8744 what allows us to distinguish between fat pointers that represent
8745 array types, and fat pointers that represent array access types
8746 (in both cases, the compiler implements them as fat pointers). */
8747 if (ada_is_access_to_unconstrained_array (type))
8748 return type;
8749
8750 type = check_typedef (type);
8751 if (type == NULL || type->code () != TYPE_CODE_ENUM
8752 || !type->is_stub ()
8753 || type->name () == NULL)
8754 return type;
8755 else
8756 {
8757 const char *name = type->name ();
8758 struct type *type1 = ada_find_any_type (name);
8759
8760 if (type1 == NULL)
8761 return type;
8762
8763 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8764 stubs pointing to arrays, as we don't create symbols for array
8765 types, only for the typedef-to-array types). If that's the case,
8766 strip the typedef layer. */
8767 if (type1->code () == TYPE_CODE_TYPEDEF)
8768 type1 = ada_check_typedef (type1);
8769
8770 return type1;
8771 }
8772 }
8773
8774 /* A value representing the data at VALADDR/ADDRESS as described by
8775 type TYPE0, but with a standard (static-sized) type that correctly
8776 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8777 type, then return VAL0 [this feature is simply to avoid redundant
8778 creation of struct values]. */
8779
8780 static struct value *
8781 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8782 struct value *val0)
8783 {
8784 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8785
8786 if (type == type0 && val0 != NULL)
8787 return val0;
8788
8789 if (VALUE_LVAL (val0) != lval_memory)
8790 {
8791 /* Our value does not live in memory; it could be a convenience
8792 variable, for instance. Create a not_lval value using val0's
8793 contents. */
8794 return value_from_contents (type, value_contents (val0));
8795 }
8796
8797 return value_from_contents_and_address (type, 0, address);
8798 }
8799
8800 /* A value representing VAL, but with a standard (static-sized) type
8801 that correctly describes it. Does not necessarily create a new
8802 value. */
8803
8804 struct value *
8805 ada_to_fixed_value (struct value *val)
8806 {
8807 val = unwrap_value (val);
8808 val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
8809 return val;
8810 }
8811 \f
8812
8813 /* Attributes */
8814
8815 /* Table mapping attribute numbers to names.
8816 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
8817
8818 static const char * const attribute_names[] = {
8819 "<?>",
8820
8821 "first",
8822 "last",
8823 "length",
8824 "image",
8825 "max",
8826 "min",
8827 "modulus",
8828 "pos",
8829 "size",
8830 "tag",
8831 "val",
8832 0
8833 };
8834
8835 static const char *
8836 ada_attribute_name (enum exp_opcode n)
8837 {
8838 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8839 return attribute_names[n - OP_ATR_FIRST + 1];
8840 else
8841 return attribute_names[0];
8842 }
8843
8844 /* Evaluate the 'POS attribute applied to ARG. */
8845
8846 static LONGEST
8847 pos_atr (struct value *arg)
8848 {
8849 struct value *val = coerce_ref (arg);
8850 struct type *type = value_type (val);
8851
8852 if (!discrete_type_p (type))
8853 error (_("'POS only defined on discrete types"));
8854
8855 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8856 if (!result.has_value ())
8857 error (_("enumeration value is invalid: can't find 'POS"));
8858
8859 return *result;
8860 }
8861
8862 struct value *
8863 ada_pos_atr (struct type *expect_type,
8864 struct expression *exp,
8865 enum noside noside, enum exp_opcode op,
8866 struct value *arg)
8867 {
8868 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8869 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8870 return value_zero (type, not_lval);
8871 return value_from_longest (type, pos_atr (arg));
8872 }
8873
8874 /* Evaluate the TYPE'VAL attribute applied to ARG. */
8875
8876 static struct value *
8877 val_atr (struct type *type, LONGEST val)
8878 {
8879 gdb_assert (discrete_type_p (type));
8880 if (type->code () == TYPE_CODE_RANGE)
8881 type = TYPE_TARGET_TYPE (type);
8882 if (type->code () == TYPE_CODE_ENUM)
8883 {
8884 if (val < 0 || val >= type->num_fields ())
8885 error (_("argument to 'VAL out of range"));
8886 val = TYPE_FIELD_ENUMVAL (type, val);
8887 }
8888 return value_from_longest (type, val);
8889 }
8890
8891 struct value *
8892 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8893 {
8894 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8895 return value_zero (type, not_lval);
8896
8897 if (!discrete_type_p (type))
8898 error (_("'VAL only defined on discrete types"));
8899 if (!integer_type_p (value_type (arg)))
8900 error (_("'VAL requires integral argument"));
8901
8902 return val_atr (type, value_as_long (arg));
8903 }
8904 \f
8905
8906 /* Evaluation */
8907
8908 /* True if TYPE appears to be an Ada character type.
8909 [At the moment, this is true only for Character and Wide_Character;
8910 It is a heuristic test that could stand improvement]. */
8911
8912 bool
8913 ada_is_character_type (struct type *type)
8914 {
8915 const char *name;
8916
8917 /* If the type code says it's a character, then assume it really is,
8918 and don't check any further. */
8919 if (type->code () == TYPE_CODE_CHAR)
8920 return true;
8921
8922 /* Otherwise, assume it's a character type iff it is a discrete type
8923 with a known character type name. */
8924 name = ada_type_name (type);
8925 return (name != NULL
8926 && (type->code () == TYPE_CODE_INT
8927 || type->code () == TYPE_CODE_RANGE)
8928 && (strcmp (name, "character") == 0
8929 || strcmp (name, "wide_character") == 0
8930 || strcmp (name, "wide_wide_character") == 0
8931 || strcmp (name, "unsigned char") == 0));
8932 }
8933
8934 /* True if TYPE appears to be an Ada string type. */
8935
8936 bool
8937 ada_is_string_type (struct type *type)
8938 {
8939 type = ada_check_typedef (type);
8940 if (type != NULL
8941 && type->code () != TYPE_CODE_PTR
8942 && (ada_is_simple_array_type (type)
8943 || ada_is_array_descriptor_type (type))
8944 && ada_array_arity (type) == 1)
8945 {
8946 struct type *elttype = ada_array_element_type (type, 1);
8947
8948 return ada_is_character_type (elttype);
8949 }
8950 else
8951 return false;
8952 }
8953
8954 /* The compiler sometimes provides a parallel XVS type for a given
8955 PAD type. Normally, it is safe to follow the PAD type directly,
8956 but older versions of the compiler have a bug that causes the offset
8957 of its "F" field to be wrong. Following that field in that case
8958 would lead to incorrect results, but this can be worked around
8959 by ignoring the PAD type and using the associated XVS type instead.
8960
8961 Set to True if the debugger should trust the contents of PAD types.
8962 Otherwise, ignore the PAD type if there is a parallel XVS type. */
8963 static bool trust_pad_over_xvs = true;
8964
8965 /* True if TYPE is a struct type introduced by the compiler to force the
8966 alignment of a value. Such types have a single field with a
8967 distinctive name. */
8968
8969 int
8970 ada_is_aligner_type (struct type *type)
8971 {
8972 type = ada_check_typedef (type);
8973
8974 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8975 return 0;
8976
8977 return (type->code () == TYPE_CODE_STRUCT
8978 && type->num_fields () == 1
8979 && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
8980 }
8981
8982 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8983 the parallel type. */
8984
8985 struct type *
8986 ada_get_base_type (struct type *raw_type)
8987 {
8988 struct type *real_type_namer;
8989 struct type *raw_real_type;
8990
8991 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8992 return raw_type;
8993
8994 if (ada_is_aligner_type (raw_type))
8995 /* The encoding specifies that we should always use the aligner type.
8996 So, even if this aligner type has an associated XVS type, we should
8997 simply ignore it.
8998
8999 According to the compiler gurus, an XVS type parallel to an aligner
9000 type may exist because of a stabs limitation. In stabs, aligner
9001 types are empty because the field has a variable-sized type, and
9002 thus cannot actually be used as an aligner type. As a result,
9003 we need the associated parallel XVS type to decode the type.
9004 Since the policy in the compiler is to not change the internal
9005 representation based on the debugging info format, we sometimes
9006 end up having a redundant XVS type parallel to the aligner type. */
9007 return raw_type;
9008
9009 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9010 if (real_type_namer == NULL
9011 || real_type_namer->code () != TYPE_CODE_STRUCT
9012 || real_type_namer->num_fields () != 1)
9013 return raw_type;
9014
9015 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
9016 {
9017 /* This is an older encoding form where the base type needs to be
9018 looked up by name. We prefer the newer encoding because it is
9019 more efficient. */
9020 raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
9021 if (raw_real_type == NULL)
9022 return raw_type;
9023 else
9024 return raw_real_type;
9025 }
9026
9027 /* The field in our XVS type is a reference to the base type. */
9028 return TYPE_TARGET_TYPE (real_type_namer->field (0).type ());
9029 }
9030
9031 /* The type of value designated by TYPE, with all aligners removed. */
9032
9033 struct type *
9034 ada_aligned_type (struct type *type)
9035 {
9036 if (ada_is_aligner_type (type))
9037 return ada_aligned_type (type->field (0).type ());
9038 else
9039 return ada_get_base_type (type);
9040 }
9041
9042
9043 /* The address of the aligned value in an object at address VALADDR
9044 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9045
9046 const gdb_byte *
9047 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9048 {
9049 if (ada_is_aligner_type (type))
9050 return ada_aligned_value_addr (type->field (0).type (),
9051 valaddr +
9052 TYPE_FIELD_BITPOS (type,
9053 0) / TARGET_CHAR_BIT);
9054 else
9055 return valaddr;
9056 }
9057
9058
9059
9060 /* The printed representation of an enumeration literal with encoded
9061 name NAME. The value is good to the next call of ada_enum_name. */
9062 const char *
9063 ada_enum_name (const char *name)
9064 {
9065 static std::string storage;
9066 const char *tmp;
9067
9068 /* First, unqualify the enumeration name:
9069 1. Search for the last '.' character. If we find one, then skip
9070 all the preceding characters, the unqualified name starts
9071 right after that dot.
9072 2. Otherwise, we may be debugging on a target where the compiler
9073 translates dots into "__". Search forward for double underscores,
9074 but stop searching when we hit an overloading suffix, which is
9075 of the form "__" followed by digits. */
9076
9077 tmp = strrchr (name, '.');
9078 if (tmp != NULL)
9079 name = tmp + 1;
9080 else
9081 {
9082 while ((tmp = strstr (name, "__")) != NULL)
9083 {
9084 if (isdigit (tmp[2]))
9085 break;
9086 else
9087 name = tmp + 2;
9088 }
9089 }
9090
9091 if (name[0] == 'Q')
9092 {
9093 int v;
9094
9095 if (name[1] == 'U' || name[1] == 'W')
9096 {
9097 if (sscanf (name + 2, "%x", &v) != 1)
9098 return name;
9099 }
9100 else if (((name[1] >= '0' && name[1] <= '9')
9101 || (name[1] >= 'a' && name[1] <= 'z'))
9102 && name[2] == '\0')
9103 {
9104 storage = string_printf ("'%c'", name[1]);
9105 return storage.c_str ();
9106 }
9107 else
9108 return name;
9109
9110 if (isascii (v) && isprint (v))
9111 storage = string_printf ("'%c'", v);
9112 else if (name[1] == 'U')
9113 storage = string_printf ("[\"%02x\"]", v);
9114 else
9115 storage = string_printf ("[\"%04x\"]", v);
9116
9117 return storage.c_str ();
9118 }
9119 else
9120 {
9121 tmp = strstr (name, "__");
9122 if (tmp == NULL)
9123 tmp = strstr (name, "$");
9124 if (tmp != NULL)
9125 {
9126 storage = std::string (name, tmp - name);
9127 return storage.c_str ();
9128 }
9129
9130 return name;
9131 }
9132 }
9133
9134 /* Evaluate the subexpression of EXP starting at *POS as for
9135 evaluate_type, updating *POS to point just past the evaluated
9136 expression. */
9137
9138 static struct value *
9139 evaluate_subexp_type (struct expression *exp, int *pos)
9140 {
9141 return evaluate_subexp (nullptr, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
9142 }
9143
9144 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9145 value it wraps. */
9146
9147 static struct value *
9148 unwrap_value (struct value *val)
9149 {
9150 struct type *type = ada_check_typedef (value_type (val));
9151
9152 if (ada_is_aligner_type (type))
9153 {
9154 struct value *v = ada_value_struct_elt (val, "F", 0);
9155 struct type *val_type = ada_check_typedef (value_type (v));
9156
9157 if (ada_type_name (val_type) == NULL)
9158 val_type->set_name (ada_type_name (type));
9159
9160 return unwrap_value (v);
9161 }
9162 else
9163 {
9164 struct type *raw_real_type =
9165 ada_check_typedef (ada_get_base_type (type));
9166
9167 /* If there is no parallel XVS or XVE type, then the value is
9168 already unwrapped. Return it without further modification. */
9169 if ((type == raw_real_type)
9170 && ada_find_parallel_type (type, "___XVE") == NULL)
9171 return val;
9172
9173 return
9174 coerce_unspec_val_to_type
9175 (val, ada_to_fixed_type (raw_real_type, 0,
9176 value_address (val),
9177 NULL, 1));
9178 }
9179 }
9180
9181 /* Given two array types T1 and T2, return nonzero iff both arrays
9182 contain the same number of elements. */
9183
9184 static int
9185 ada_same_array_size_p (struct type *t1, struct type *t2)
9186 {
9187 LONGEST lo1, hi1, lo2, hi2;
9188
9189 /* Get the array bounds in order to verify that the size of
9190 the two arrays match. */
9191 if (!get_array_bounds (t1, &lo1, &hi1)
9192 || !get_array_bounds (t2, &lo2, &hi2))
9193 error (_("unable to determine array bounds"));
9194
9195 /* To make things easier for size comparison, normalize a bit
9196 the case of empty arrays by making sure that the difference
9197 between upper bound and lower bound is always -1. */
9198 if (lo1 > hi1)
9199 hi1 = lo1 - 1;
9200 if (lo2 > hi2)
9201 hi2 = lo2 - 1;
9202
9203 return (hi1 - lo1 == hi2 - lo2);
9204 }
9205
9206 /* Assuming that VAL is an array of integrals, and TYPE represents
9207 an array with the same number of elements, but with wider integral
9208 elements, return an array "casted" to TYPE. In practice, this
9209 means that the returned array is built by casting each element
9210 of the original array into TYPE's (wider) element type. */
9211
9212 static struct value *
9213 ada_promote_array_of_integrals (struct type *type, struct value *val)
9214 {
9215 struct type *elt_type = TYPE_TARGET_TYPE (type);
9216 LONGEST lo, hi;
9217 struct value *res;
9218 LONGEST i;
9219
9220 /* Verify that both val and type are arrays of scalars, and
9221 that the size of val's elements is smaller than the size
9222 of type's element. */
9223 gdb_assert (type->code () == TYPE_CODE_ARRAY);
9224 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
9225 gdb_assert (value_type (val)->code () == TYPE_CODE_ARRAY);
9226 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
9227 gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
9228 > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
9229
9230 if (!get_array_bounds (type, &lo, &hi))
9231 error (_("unable to determine array bounds"));
9232
9233 res = allocate_value (type);
9234
9235 /* Promote each array element. */
9236 for (i = 0; i < hi - lo + 1; i++)
9237 {
9238 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9239
9240 memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
9241 value_contents_all (elt), TYPE_LENGTH (elt_type));
9242 }
9243
9244 return res;
9245 }
9246
9247 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9248 return the converted value. */
9249
9250 static struct value *
9251 coerce_for_assign (struct type *type, struct value *val)
9252 {
9253 struct type *type2 = value_type (val);
9254
9255 if (type == type2)
9256 return val;
9257
9258 type2 = ada_check_typedef (type2);
9259 type = ada_check_typedef (type);
9260
9261 if (type2->code () == TYPE_CODE_PTR
9262 && type->code () == TYPE_CODE_ARRAY)
9263 {
9264 val = ada_value_ind (val);
9265 type2 = value_type (val);
9266 }
9267
9268 if (type2->code () == TYPE_CODE_ARRAY
9269 && type->code () == TYPE_CODE_ARRAY)
9270 {
9271 if (!ada_same_array_size_p (type, type2))
9272 error (_("cannot assign arrays of different length"));
9273
9274 if (is_integral_type (TYPE_TARGET_TYPE (type))
9275 && is_integral_type (TYPE_TARGET_TYPE (type2))
9276 && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9277 < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9278 {
9279 /* Allow implicit promotion of the array elements to
9280 a wider type. */
9281 return ada_promote_array_of_integrals (type, val);
9282 }
9283
9284 if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9285 != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9286 error (_("Incompatible types in assignment"));
9287 deprecated_set_value_type (val, type);
9288 }
9289 return val;
9290 }
9291
9292 static struct value *
9293 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9294 {
9295 struct value *val;
9296 struct type *type1, *type2;
9297 LONGEST v, v1, v2;
9298
9299 arg1 = coerce_ref (arg1);
9300 arg2 = coerce_ref (arg2);
9301 type1 = get_base_type (ada_check_typedef (value_type (arg1)));
9302 type2 = get_base_type (ada_check_typedef (value_type (arg2)));
9303
9304 if (type1->code () != TYPE_CODE_INT
9305 || type2->code () != TYPE_CODE_INT)
9306 return value_binop (arg1, arg2, op);
9307
9308 switch (op)
9309 {
9310 case BINOP_MOD:
9311 case BINOP_DIV:
9312 case BINOP_REM:
9313 break;
9314 default:
9315 return value_binop (arg1, arg2, op);
9316 }
9317
9318 v2 = value_as_long (arg2);
9319 if (v2 == 0)
9320 {
9321 const char *name;
9322 if (op == BINOP_MOD)
9323 name = "mod";
9324 else if (op == BINOP_DIV)
9325 name = "/";
9326 else
9327 {
9328 gdb_assert (op == BINOP_REM);
9329 name = "rem";
9330 }
9331
9332 error (_("second operand of %s must not be zero."), name);
9333 }
9334
9335 if (type1->is_unsigned () || op == BINOP_MOD)
9336 return value_binop (arg1, arg2, op);
9337
9338 v1 = value_as_long (arg1);
9339 switch (op)
9340 {
9341 case BINOP_DIV:
9342 v = v1 / v2;
9343 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9344 v += v > 0 ? -1 : 1;
9345 break;
9346 case BINOP_REM:
9347 v = v1 % v2;
9348 if (v * v1 < 0)
9349 v -= v2;
9350 break;
9351 default:
9352 /* Should not reach this point. */
9353 v = 0;
9354 }
9355
9356 val = allocate_value (type1);
9357 store_unsigned_integer (value_contents_raw (val),
9358 TYPE_LENGTH (value_type (val)),
9359 type_byte_order (type1), v);
9360 return val;
9361 }
9362
9363 static int
9364 ada_value_equal (struct value *arg1, struct value *arg2)
9365 {
9366 if (ada_is_direct_array_type (value_type (arg1))
9367 || ada_is_direct_array_type (value_type (arg2)))
9368 {
9369 struct type *arg1_type, *arg2_type;
9370
9371 /* Automatically dereference any array reference before
9372 we attempt to perform the comparison. */
9373 arg1 = ada_coerce_ref (arg1);
9374 arg2 = ada_coerce_ref (arg2);
9375
9376 arg1 = ada_coerce_to_simple_array (arg1);
9377 arg2 = ada_coerce_to_simple_array (arg2);
9378
9379 arg1_type = ada_check_typedef (value_type (arg1));
9380 arg2_type = ada_check_typedef (value_type (arg2));
9381
9382 if (arg1_type->code () != TYPE_CODE_ARRAY
9383 || arg2_type->code () != TYPE_CODE_ARRAY)
9384 error (_("Attempt to compare array with non-array"));
9385 /* FIXME: The following works only for types whose
9386 representations use all bits (no padding or undefined bits)
9387 and do not have user-defined equality. */
9388 return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9389 && memcmp (value_contents (arg1), value_contents (arg2),
9390 TYPE_LENGTH (arg1_type)) == 0);
9391 }
9392 return value_equal (arg1, arg2);
9393 }
9394
9395 /* Assign the result of evaluating EXP starting at *POS to the INDEXth
9396 component of LHS (a simple array or a record), updating *POS past
9397 the expression, assuming that LHS is contained in CONTAINER. Does
9398 not modify the inferior's memory, nor does it modify LHS (unless
9399 LHS == CONTAINER). */
9400
9401 static void
9402 assign_component (struct value *container, struct value *lhs, LONGEST index,
9403 struct expression *exp, int *pos)
9404 {
9405 struct value *mark = value_mark ();
9406 struct value *elt;
9407 struct type *lhs_type = check_typedef (value_type (lhs));
9408
9409 if (lhs_type->code () == TYPE_CODE_ARRAY)
9410 {
9411 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9412 struct value *index_val = value_from_longest (index_type, index);
9413
9414 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9415 }
9416 else
9417 {
9418 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9419 elt = ada_to_fixed_value (elt);
9420 }
9421
9422 if (exp->elts[*pos].opcode == OP_AGGREGATE)
9423 assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
9424 else
9425 value_assign_to_component (container, elt,
9426 ada_evaluate_subexp (NULL, exp, pos,
9427 EVAL_NORMAL));
9428
9429 value_free_to_mark (mark);
9430 }
9431
9432 /* Assuming that LHS represents an lvalue having a record or array
9433 type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
9434 of that aggregate's value to LHS, advancing *POS past the
9435 aggregate. NOSIDE is as for evaluate_subexp. CONTAINER is an
9436 lvalue containing LHS (possibly LHS itself). Does not modify
9437 the inferior's memory, nor does it modify the contents of
9438 LHS (unless == CONTAINER). Returns the modified CONTAINER. */
9439
9440 static struct value *
9441 assign_aggregate (struct value *container,
9442 struct value *lhs, struct expression *exp,
9443 int *pos, enum noside noside)
9444 {
9445 struct type *lhs_type;
9446 int n = exp->elts[*pos+1].longconst;
9447 LONGEST low_index, high_index;
9448 int i;
9449
9450 *pos += 3;
9451 if (noside != EVAL_NORMAL)
9452 {
9453 for (i = 0; i < n; i += 1)
9454 ada_evaluate_subexp (NULL, exp, pos, noside);
9455 return container;
9456 }
9457
9458 container = ada_coerce_ref (container);
9459 if (ada_is_direct_array_type (value_type (container)))
9460 container = ada_coerce_to_simple_array (container);
9461 lhs = ada_coerce_ref (lhs);
9462 if (!deprecated_value_modifiable (lhs))
9463 error (_("Left operand of assignment is not a modifiable lvalue."));
9464
9465 lhs_type = check_typedef (value_type (lhs));
9466 if (ada_is_direct_array_type (lhs_type))
9467 {
9468 lhs = ada_coerce_to_simple_array (lhs);
9469 lhs_type = check_typedef (value_type (lhs));
9470 low_index = lhs_type->bounds ()->low.const_val ();
9471 high_index = lhs_type->bounds ()->high.const_val ();
9472 }
9473 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9474 {
9475 low_index = 0;
9476 high_index = num_visible_fields (lhs_type) - 1;
9477 }
9478 else
9479 error (_("Left-hand side must be array or record."));
9480
9481 std::vector<LONGEST> indices (4);
9482 indices[0] = indices[1] = low_index - 1;
9483 indices[2] = indices[3] = high_index + 1;
9484
9485 for (i = 0; i < n; i += 1)
9486 {
9487 switch (exp->elts[*pos].opcode)
9488 {
9489 case OP_CHOICES:
9490 aggregate_assign_from_choices (container, lhs, exp, pos, indices,
9491 low_index, high_index);
9492 break;
9493 case OP_POSITIONAL:
9494 aggregate_assign_positional (container, lhs, exp, pos, indices,
9495 low_index, high_index);
9496 break;
9497 case OP_OTHERS:
9498 if (i != n-1)
9499 error (_("Misplaced 'others' clause"));
9500 aggregate_assign_others (container, lhs, exp, pos, indices,
9501 low_index, high_index);
9502 break;
9503 default:
9504 error (_("Internal error: bad aggregate clause"));
9505 }
9506 }
9507
9508 return container;
9509 }
9510
9511 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9512 construct at *POS, updating *POS past the construct, given that
9513 the positions are relative to lower bound LOW, where HIGH is the
9514 upper bound. Record the position in INDICES. CONTAINER is as for
9515 assign_aggregate. */
9516 static void
9517 aggregate_assign_positional (struct value *container,
9518 struct value *lhs, struct expression *exp,
9519 int *pos, std::vector<LONGEST> &indices,
9520 LONGEST low, LONGEST high)
9521 {
9522 LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
9523
9524 if (ind - 1 == high)
9525 warning (_("Extra components in aggregate ignored."));
9526 if (ind <= high)
9527 {
9528 add_component_interval (ind, ind, indices);
9529 *pos += 3;
9530 assign_component (container, lhs, ind, exp, pos);
9531 }
9532 else
9533 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9534 }
9535
9536 /* Assign into the components of LHS indexed by the OP_CHOICES
9537 construct at *POS, updating *POS past the construct, given that
9538 the allowable indices are LOW..HIGH. Record the indices assigned
9539 to in INDICES. CONTAINER is as for assign_aggregate. */
9540 static void
9541 aggregate_assign_from_choices (struct value *container,
9542 struct value *lhs, struct expression *exp,
9543 int *pos, std::vector<LONGEST> &indices,
9544 LONGEST low, LONGEST high)
9545 {
9546 int j;
9547 int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
9548 int choice_pos, expr_pc;
9549 int is_array = ada_is_direct_array_type (value_type (lhs));
9550
9551 choice_pos = *pos += 3;
9552
9553 for (j = 0; j < n_choices; j += 1)
9554 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9555 expr_pc = *pos;
9556 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9557
9558 for (j = 0; j < n_choices; j += 1)
9559 {
9560 LONGEST lower, upper;
9561 enum exp_opcode op = exp->elts[choice_pos].opcode;
9562
9563 if (op == OP_DISCRETE_RANGE)
9564 {
9565 choice_pos += 1;
9566 lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
9567 EVAL_NORMAL));
9568 upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
9569 EVAL_NORMAL));
9570 }
9571 else if (is_array)
9572 {
9573 lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos,
9574 EVAL_NORMAL));
9575 upper = lower;
9576 }
9577 else
9578 {
9579 int ind;
9580 const char *name;
9581
9582 switch (op)
9583 {
9584 case OP_NAME:
9585 name = &exp->elts[choice_pos + 2].string;
9586 break;
9587 case OP_VAR_VALUE:
9588 name = exp->elts[choice_pos + 2].symbol->natural_name ();
9589 break;
9590 default:
9591 error (_("Invalid record component association."));
9592 }
9593 ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
9594 ind = 0;
9595 if (! find_struct_field (name, value_type (lhs), 0,
9596 NULL, NULL, NULL, NULL, &ind))
9597 error (_("Unknown component name: %s."), name);
9598 lower = upper = ind;
9599 }
9600
9601 if (lower <= upper && (lower < low || upper > high))
9602 error (_("Index in component association out of bounds."));
9603
9604 add_component_interval (lower, upper, indices);
9605 while (lower <= upper)
9606 {
9607 int pos1;
9608
9609 pos1 = expr_pc;
9610 assign_component (container, lhs, lower, exp, &pos1);
9611 lower += 1;
9612 }
9613 }
9614 }
9615
9616 /* Assign the value of the expression in the OP_OTHERS construct in
9617 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9618 have not been previously assigned. The index intervals already assigned
9619 are in INDICES. Updates *POS to after the OP_OTHERS clause.
9620 CONTAINER is as for assign_aggregate. */
9621 static void
9622 aggregate_assign_others (struct value *container,
9623 struct value *lhs, struct expression *exp,
9624 int *pos, std::vector<LONGEST> &indices,
9625 LONGEST low, LONGEST high)
9626 {
9627 int i;
9628 int expr_pc = *pos + 1;
9629
9630 int num_indices = indices.size ();
9631 for (i = 0; i < num_indices - 2; i += 2)
9632 {
9633 LONGEST ind;
9634
9635 for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9636 {
9637 int localpos;
9638
9639 localpos = expr_pc;
9640 assign_component (container, lhs, ind, exp, &localpos);
9641 }
9642 }
9643 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9644 }
9645
9646 namespace expr
9647 {
9648
9649 bool
9650 check_objfile (const std::unique_ptr<ada_component> &comp,
9651 struct objfile *objfile)
9652 {
9653 return comp->uses_objfile (objfile);
9654 }
9655
9656 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9657 component of LHS (a simple array or a record). Does not modify the
9658 inferior's memory, nor does it modify LHS (unless LHS ==
9659 CONTAINER). */
9660
9661 static void
9662 assign_component (struct value *container, struct value *lhs, LONGEST index,
9663 struct expression *exp, operation_up &arg)
9664 {
9665 scoped_value_mark mark;
9666
9667 struct value *elt;
9668 struct type *lhs_type = check_typedef (value_type (lhs));
9669
9670 if (lhs_type->code () == TYPE_CODE_ARRAY)
9671 {
9672 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9673 struct value *index_val = value_from_longest (index_type, index);
9674
9675 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9676 }
9677 else
9678 {
9679 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9680 elt = ada_to_fixed_value (elt);
9681 }
9682
9683 ada_aggregate_operation *ag_op
9684 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9685 if (ag_op != nullptr)
9686 ag_op->assign_aggregate (container, elt, exp);
9687 else
9688 value_assign_to_component (container, elt,
9689 arg->evaluate (nullptr, exp,
9690 EVAL_NORMAL));
9691 }
9692
9693 bool
9694 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9695 {
9696 for (const auto &item : m_components)
9697 if (item->uses_objfile (objfile))
9698 return true;
9699 return false;
9700 }
9701
9702 void
9703 ada_aggregate_component::dump (ui_file *stream, int depth)
9704 {
9705 fprintf_filtered (stream, _("%*sAggregate\n"), depth, "");
9706 for (const auto &item : m_components)
9707 item->dump (stream, depth + 1);
9708 }
9709
9710 void
9711 ada_aggregate_component::assign (struct value *container,
9712 struct value *lhs, struct expression *exp,
9713 std::vector<LONGEST> &indices,
9714 LONGEST low, LONGEST high)
9715 {
9716 for (auto &item : m_components)
9717 item->assign (container, lhs, exp, indices, low, high);
9718 }
9719
9720 void
9721 ada_aggregate_operation::assign_aggregate (struct value *container,
9722 struct value *lhs,
9723 struct expression *exp)
9724 {
9725 struct type *lhs_type;
9726 LONGEST low_index, high_index;
9727
9728 container = ada_coerce_ref (container);
9729 if (ada_is_direct_array_type (value_type (container)))
9730 container = ada_coerce_to_simple_array (container);
9731 lhs = ada_coerce_ref (lhs);
9732 if (!deprecated_value_modifiable (lhs))
9733 error (_("Left operand of assignment is not a modifiable lvalue."));
9734
9735 lhs_type = check_typedef (value_type (lhs));
9736 if (ada_is_direct_array_type (lhs_type))
9737 {
9738 lhs = ada_coerce_to_simple_array (lhs);
9739 lhs_type = check_typedef (value_type (lhs));
9740 low_index = lhs_type->bounds ()->low.const_val ();
9741 high_index = lhs_type->bounds ()->high.const_val ();
9742 }
9743 else if (lhs_type->code () == TYPE_CODE_STRUCT)
9744 {
9745 low_index = 0;
9746 high_index = num_visible_fields (lhs_type) - 1;
9747 }
9748 else
9749 error (_("Left-hand side must be array or record."));
9750
9751 std::vector<LONGEST> indices (4);
9752 indices[0] = indices[1] = low_index - 1;
9753 indices[2] = indices[3] = high_index + 1;
9754
9755 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9756 low_index, high_index);
9757 }
9758
9759 bool
9760 ada_positional_component::uses_objfile (struct objfile *objfile)
9761 {
9762 return m_op->uses_objfile (objfile);
9763 }
9764
9765 void
9766 ada_positional_component::dump (ui_file *stream, int depth)
9767 {
9768 fprintf_filtered (stream, _("%*sPositional, index = %d\n"),
9769 depth, "", m_index);
9770 m_op->dump (stream, depth + 1);
9771 }
9772
9773 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9774 construct, given that the positions are relative to lower bound
9775 LOW, where HIGH is the upper bound. Record the position in
9776 INDICES. CONTAINER is as for assign_aggregate. */
9777 void
9778 ada_positional_component::assign (struct value *container,
9779 struct value *lhs, struct expression *exp,
9780 std::vector<LONGEST> &indices,
9781 LONGEST low, LONGEST high)
9782 {
9783 LONGEST ind = m_index + low;
9784
9785 if (ind - 1 == high)
9786 warning (_("Extra components in aggregate ignored."));
9787 if (ind <= high)
9788 {
9789 add_component_interval (ind, ind, indices);
9790 assign_component (container, lhs, ind, exp, m_op);
9791 }
9792 }
9793
9794 bool
9795 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9796 {
9797 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9798 }
9799
9800 void
9801 ada_discrete_range_association::dump (ui_file *stream, int depth)
9802 {
9803 fprintf_filtered (stream, _("%*sDiscrete range:\n"), depth, "");
9804 m_low->dump (stream, depth + 1);
9805 m_high->dump (stream, depth + 1);
9806 }
9807
9808 void
9809 ada_discrete_range_association::assign (struct value *container,
9810 struct value *lhs,
9811 struct expression *exp,
9812 std::vector<LONGEST> &indices,
9813 LONGEST low, LONGEST high,
9814 operation_up &op)
9815 {
9816 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9817 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9818
9819 if (lower <= upper && (lower < low || upper > high))
9820 error (_("Index in component association out of bounds."));
9821
9822 add_component_interval (lower, upper, indices);
9823 while (lower <= upper)
9824 {
9825 assign_component (container, lhs, lower, exp, op);
9826 lower += 1;
9827 }
9828 }
9829
9830 bool
9831 ada_name_association::uses_objfile (struct objfile *objfile)
9832 {
9833 return m_val->uses_objfile (objfile);
9834 }
9835
9836 void
9837 ada_name_association::dump (ui_file *stream, int depth)
9838 {
9839 fprintf_filtered (stream, _("%*sName:\n"), depth, "");
9840 m_val->dump (stream, depth + 1);
9841 }
9842
9843 void
9844 ada_name_association::assign (struct value *container,
9845 struct value *lhs,
9846 struct expression *exp,
9847 std::vector<LONGEST> &indices,
9848 LONGEST low, LONGEST high,
9849 operation_up &op)
9850 {
9851 int index;
9852
9853 if (ada_is_direct_array_type (value_type (lhs)))
9854 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9855 EVAL_NORMAL)));
9856 else
9857 {
9858 ada_string_operation *strop
9859 = dynamic_cast<ada_string_operation *> (m_val.get ());
9860
9861 const char *name;
9862 if (strop != nullptr)
9863 name = strop->get_name ();
9864 else
9865 {
9866 ada_var_value_operation *vvo
9867 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9868 if (vvo != nullptr)
9869 error (_("Invalid record component association."));
9870 name = vvo->get_symbol ()->natural_name ();
9871 }
9872
9873 index = 0;
9874 if (! find_struct_field (name, value_type (lhs), 0,
9875 NULL, NULL, NULL, NULL, &index))
9876 error (_("Unknown component name: %s."), name);
9877 }
9878
9879 add_component_interval (index, index, indices);
9880 assign_component (container, lhs, index, exp, op);
9881 }
9882
9883 bool
9884 ada_choices_component::uses_objfile (struct objfile *objfile)
9885 {
9886 if (m_op->uses_objfile (objfile))
9887 return true;
9888 for (const auto &item : m_assocs)
9889 if (item->uses_objfile (objfile))
9890 return true;
9891 return false;
9892 }
9893
9894 void
9895 ada_choices_component::dump (ui_file *stream, int depth)
9896 {
9897 fprintf_filtered (stream, _("%*sChoices:\n"), depth, "");
9898 m_op->dump (stream, depth + 1);
9899 for (const auto &item : m_assocs)
9900 item->dump (stream, depth + 1);
9901 }
9902
9903 /* Assign into the components of LHS indexed by the OP_CHOICES
9904 construct at *POS, updating *POS past the construct, given that
9905 the allowable indices are LOW..HIGH. Record the indices assigned
9906 to in INDICES. CONTAINER is as for assign_aggregate. */
9907 void
9908 ada_choices_component::assign (struct value *container,
9909 struct value *lhs, struct expression *exp,
9910 std::vector<LONGEST> &indices,
9911 LONGEST low, LONGEST high)
9912 {
9913 for (auto &item : m_assocs)
9914 item->assign (container, lhs, exp, indices, low, high, m_op);
9915 }
9916
9917 bool
9918 ada_others_component::uses_objfile (struct objfile *objfile)
9919 {
9920 return m_op->uses_objfile (objfile);
9921 }
9922
9923 void
9924 ada_others_component::dump (ui_file *stream, int depth)
9925 {
9926 fprintf_filtered (stream, _("%*sOthers:\n"), depth, "");
9927 m_op->dump (stream, depth + 1);
9928 }
9929
9930 /* Assign the value of the expression in the OP_OTHERS construct in
9931 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9932 have not been previously assigned. The index intervals already assigned
9933 are in INDICES. CONTAINER is as for assign_aggregate. */
9934 void
9935 ada_others_component::assign (struct value *container,
9936 struct value *lhs, struct expression *exp,
9937 std::vector<LONGEST> &indices,
9938 LONGEST low, LONGEST high)
9939 {
9940 int num_indices = indices.size ();
9941 for (int i = 0; i < num_indices - 2; i += 2)
9942 {
9943 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9944 assign_component (container, lhs, ind, exp, m_op);
9945 }
9946 }
9947
9948 struct value *
9949 ada_assign_operation::evaluate (struct type *expect_type,
9950 struct expression *exp,
9951 enum noside noside)
9952 {
9953 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9954
9955 ada_aggregate_operation *ag_op
9956 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9957 if (ag_op != nullptr)
9958 {
9959 if (noside != EVAL_NORMAL)
9960 return arg1;
9961
9962 ag_op->assign_aggregate (arg1, arg1, exp);
9963 return ada_value_assign (arg1, arg1);
9964 }
9965 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9966 except if the lhs of our assignment is a convenience variable.
9967 In the case of assigning to a convenience variable, the lhs
9968 should be exactly the result of the evaluation of the rhs. */
9969 struct type *type = value_type (arg1);
9970 if (VALUE_LVAL (arg1) == lval_internalvar)
9971 type = NULL;
9972 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9973 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
9974 return arg1;
9975 if (VALUE_LVAL (arg1) == lval_internalvar)
9976 {
9977 /* Nothing. */
9978 }
9979 else
9980 arg2 = coerce_for_assign (value_type (arg1), arg2);
9981 return ada_value_assign (arg1, arg2);
9982 }
9983
9984 } /* namespace expr */
9985
9986 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9987 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9988 overlap. */
9989 static void
9990 add_component_interval (LONGEST low, LONGEST high,
9991 std::vector<LONGEST> &indices)
9992 {
9993 int i, j;
9994
9995 int size = indices.size ();
9996 for (i = 0; i < size; i += 2) {
9997 if (high >= indices[i] && low <= indices[i + 1])
9998 {
9999 int kh;
10000
10001 for (kh = i + 2; kh < size; kh += 2)
10002 if (high < indices[kh])
10003 break;
10004 if (low < indices[i])
10005 indices[i] = low;
10006 indices[i + 1] = indices[kh - 1];
10007 if (high > indices[i + 1])
10008 indices[i + 1] = high;
10009 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
10010 indices.resize (kh - i - 2);
10011 return;
10012 }
10013 else if (high < indices[i])
10014 break;
10015 }
10016
10017 indices.resize (indices.size () + 2);
10018 for (j = indices.size () - 1; j >= i + 2; j -= 1)
10019 indices[j] = indices[j - 2];
10020 indices[i] = low;
10021 indices[i + 1] = high;
10022 }
10023
10024 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
10025 is different. */
10026
10027 static struct value *
10028 ada_value_cast (struct type *type, struct value *arg2)
10029 {
10030 if (type == ada_check_typedef (value_type (arg2)))
10031 return arg2;
10032
10033 return value_cast (type, arg2);
10034 }
10035
10036 /* Evaluating Ada expressions, and printing their result.
10037 ------------------------------------------------------
10038
10039 1. Introduction:
10040 ----------------
10041
10042 We usually evaluate an Ada expression in order to print its value.
10043 We also evaluate an expression in order to print its type, which
10044 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
10045 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
10046 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
10047 the evaluation compared to the EVAL_NORMAL, but is otherwise very
10048 similar.
10049
10050 Evaluating expressions is a little more complicated for Ada entities
10051 than it is for entities in languages such as C. The main reason for
10052 this is that Ada provides types whose definition might be dynamic.
10053 One example of such types is variant records. Or another example
10054 would be an array whose bounds can only be known at run time.
10055
10056 The following description is a general guide as to what should be
10057 done (and what should NOT be done) in order to evaluate an expression
10058 involving such types, and when. This does not cover how the semantic
10059 information is encoded by GNAT as this is covered separatly. For the
10060 document used as the reference for the GNAT encoding, see exp_dbug.ads
10061 in the GNAT sources.
10062
10063 Ideally, we should embed each part of this description next to its
10064 associated code. Unfortunately, the amount of code is so vast right
10065 now that it's hard to see whether the code handling a particular
10066 situation might be duplicated or not. One day, when the code is
10067 cleaned up, this guide might become redundant with the comments
10068 inserted in the code, and we might want to remove it.
10069
10070 2. ``Fixing'' an Entity, the Simple Case:
10071 -----------------------------------------
10072
10073 When evaluating Ada expressions, the tricky issue is that they may
10074 reference entities whose type contents and size are not statically
10075 known. Consider for instance a variant record:
10076
10077 type Rec (Empty : Boolean := True) is record
10078 case Empty is
10079 when True => null;
10080 when False => Value : Integer;
10081 end case;
10082 end record;
10083 Yes : Rec := (Empty => False, Value => 1);
10084 No : Rec := (empty => True);
10085
10086 The size and contents of that record depends on the value of the
10087 descriminant (Rec.Empty). At this point, neither the debugging
10088 information nor the associated type structure in GDB are able to
10089 express such dynamic types. So what the debugger does is to create
10090 "fixed" versions of the type that applies to the specific object.
10091 We also informally refer to this operation as "fixing" an object,
10092 which means creating its associated fixed type.
10093
10094 Example: when printing the value of variable "Yes" above, its fixed
10095 type would look like this:
10096
10097 type Rec is record
10098 Empty : Boolean;
10099 Value : Integer;
10100 end record;
10101
10102 On the other hand, if we printed the value of "No", its fixed type
10103 would become:
10104
10105 type Rec is record
10106 Empty : Boolean;
10107 end record;
10108
10109 Things become a little more complicated when trying to fix an entity
10110 with a dynamic type that directly contains another dynamic type,
10111 such as an array of variant records, for instance. There are
10112 two possible cases: Arrays, and records.
10113
10114 3. ``Fixing'' Arrays:
10115 ---------------------
10116
10117 The type structure in GDB describes an array in terms of its bounds,
10118 and the type of its elements. By design, all elements in the array
10119 have the same type and we cannot represent an array of variant elements
10120 using the current type structure in GDB. When fixing an array,
10121 we cannot fix the array element, as we would potentially need one
10122 fixed type per element of the array. As a result, the best we can do
10123 when fixing an array is to produce an array whose bounds and size
10124 are correct (allowing us to read it from memory), but without having
10125 touched its element type. Fixing each element will be done later,
10126 when (if) necessary.
10127
10128 Arrays are a little simpler to handle than records, because the same
10129 amount of memory is allocated for each element of the array, even if
10130 the amount of space actually used by each element differs from element
10131 to element. Consider for instance the following array of type Rec:
10132
10133 type Rec_Array is array (1 .. 2) of Rec;
10134
10135 The actual amount of memory occupied by each element might be different
10136 from element to element, depending on the value of their discriminant.
10137 But the amount of space reserved for each element in the array remains
10138 fixed regardless. So we simply need to compute that size using
10139 the debugging information available, from which we can then determine
10140 the array size (we multiply the number of elements of the array by
10141 the size of each element).
10142
10143 The simplest case is when we have an array of a constrained element
10144 type. For instance, consider the following type declarations:
10145
10146 type Bounded_String (Max_Size : Integer) is
10147 Length : Integer;
10148 Buffer : String (1 .. Max_Size);
10149 end record;
10150 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
10151
10152 In this case, the compiler describes the array as an array of
10153 variable-size elements (identified by its XVS suffix) for which
10154 the size can be read in the parallel XVZ variable.
10155
10156 In the case of an array of an unconstrained element type, the compiler
10157 wraps the array element inside a private PAD type. This type should not
10158 be shown to the user, and must be "unwrap"'ed before printing. Note
10159 that we also use the adjective "aligner" in our code to designate
10160 these wrapper types.
10161
10162 In some cases, the size allocated for each element is statically
10163 known. In that case, the PAD type already has the correct size,
10164 and the array element should remain unfixed.
10165
10166 But there are cases when this size is not statically known.
10167 For instance, assuming that "Five" is an integer variable:
10168
10169 type Dynamic is array (1 .. Five) of Integer;
10170 type Wrapper (Has_Length : Boolean := False) is record
10171 Data : Dynamic;
10172 case Has_Length is
10173 when True => Length : Integer;
10174 when False => null;
10175 end case;
10176 end record;
10177 type Wrapper_Array is array (1 .. 2) of Wrapper;
10178
10179 Hello : Wrapper_Array := (others => (Has_Length => True,
10180 Data => (others => 17),
10181 Length => 1));
10182
10183
10184 The debugging info would describe variable Hello as being an
10185 array of a PAD type. The size of that PAD type is not statically
10186 known, but can be determined using a parallel XVZ variable.
10187 In that case, a copy of the PAD type with the correct size should
10188 be used for the fixed array.
10189
10190 3. ``Fixing'' record type objects:
10191 ----------------------------------
10192
10193 Things are slightly different from arrays in the case of dynamic
10194 record types. In this case, in order to compute the associated
10195 fixed type, we need to determine the size and offset of each of
10196 its components. This, in turn, requires us to compute the fixed
10197 type of each of these components.
10198
10199 Consider for instance the example:
10200
10201 type Bounded_String (Max_Size : Natural) is record
10202 Str : String (1 .. Max_Size);
10203 Length : Natural;
10204 end record;
10205 My_String : Bounded_String (Max_Size => 10);
10206
10207 In that case, the position of field "Length" depends on the size
10208 of field Str, which itself depends on the value of the Max_Size
10209 discriminant. In order to fix the type of variable My_String,
10210 we need to fix the type of field Str. Therefore, fixing a variant
10211 record requires us to fix each of its components.
10212
10213 However, if a component does not have a dynamic size, the component
10214 should not be fixed. In particular, fields that use a PAD type
10215 should not fixed. Here is an example where this might happen
10216 (assuming type Rec above):
10217
10218 type Container (Big : Boolean) is record
10219 First : Rec;
10220 After : Integer;
10221 case Big is
10222 when True => Another : Integer;
10223 when False => null;
10224 end case;
10225 end record;
10226 My_Container : Container := (Big => False,
10227 First => (Empty => True),
10228 After => 42);
10229
10230 In that example, the compiler creates a PAD type for component First,
10231 whose size is constant, and then positions the component After just
10232 right after it. The offset of component After is therefore constant
10233 in this case.
10234
10235 The debugger computes the position of each field based on an algorithm
10236 that uses, among other things, the actual position and size of the field
10237 preceding it. Let's now imagine that the user is trying to print
10238 the value of My_Container. If the type fixing was recursive, we would
10239 end up computing the offset of field After based on the size of the
10240 fixed version of field First. And since in our example First has
10241 only one actual field, the size of the fixed type is actually smaller
10242 than the amount of space allocated to that field, and thus we would
10243 compute the wrong offset of field After.
10244
10245 To make things more complicated, we need to watch out for dynamic
10246 components of variant records (identified by the ___XVL suffix in
10247 the component name). Even if the target type is a PAD type, the size
10248 of that type might not be statically known. So the PAD type needs
10249 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10250 we might end up with the wrong size for our component. This can be
10251 observed with the following type declarations:
10252
10253 type Octal is new Integer range 0 .. 7;
10254 type Octal_Array is array (Positive range <>) of Octal;
10255 pragma Pack (Octal_Array);
10256
10257 type Octal_Buffer (Size : Positive) is record
10258 Buffer : Octal_Array (1 .. Size);
10259 Length : Integer;
10260 end record;
10261
10262 In that case, Buffer is a PAD type whose size is unset and needs
10263 to be computed by fixing the unwrapped type.
10264
10265 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10266 ----------------------------------------------------------
10267
10268 Lastly, when should the sub-elements of an entity that remained unfixed
10269 thus far, be actually fixed?
10270
10271 The answer is: Only when referencing that element. For instance
10272 when selecting one component of a record, this specific component
10273 should be fixed at that point in time. Or when printing the value
10274 of a record, each component should be fixed before its value gets
10275 printed. Similarly for arrays, the element of the array should be
10276 fixed when printing each element of the array, or when extracting
10277 one element out of that array. On the other hand, fixing should
10278 not be performed on the elements when taking a slice of an array!
10279
10280 Note that one of the side effects of miscomputing the offset and
10281 size of each field is that we end up also miscomputing the size
10282 of the containing type. This can have adverse results when computing
10283 the value of an entity. GDB fetches the value of an entity based
10284 on the size of its type, and thus a wrong size causes GDB to fetch
10285 the wrong amount of memory. In the case where the computed size is
10286 too small, GDB fetches too little data to print the value of our
10287 entity. Results in this case are unpredictable, as we usually read
10288 past the buffer containing the data =:-o. */
10289
10290 /* Evaluate a subexpression of EXP, at index *POS, and return a value
10291 for that subexpression cast to TO_TYPE. Advance *POS over the
10292 subexpression. */
10293
10294 static value *
10295 ada_evaluate_subexp_for_cast (expression *exp, int *pos,
10296 enum noside noside, struct type *to_type)
10297 {
10298 int pc = *pos;
10299
10300 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE
10301 || exp->elts[pc].opcode == OP_VAR_VALUE)
10302 {
10303 (*pos) += 4;
10304
10305 value *val;
10306 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
10307 {
10308 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10309 return value_zero (to_type, not_lval);
10310
10311 val = evaluate_var_msym_value (noside,
10312 exp->elts[pc + 1].objfile,
10313 exp->elts[pc + 2].msymbol);
10314 }
10315 else
10316 val = evaluate_var_value (noside,
10317 exp->elts[pc + 1].block,
10318 exp->elts[pc + 2].symbol);
10319
10320 if (noside == EVAL_SKIP)
10321 return eval_skip_value (exp);
10322
10323 val = ada_value_cast (to_type, val);
10324
10325 /* Follow the Ada language semantics that do not allow taking
10326 an address of the result of a cast (view conversion in Ada). */
10327 if (VALUE_LVAL (val) == lval_memory)
10328 {
10329 if (value_lazy (val))
10330 value_fetch_lazy (val);
10331 VALUE_LVAL (val) = not_lval;
10332 }
10333 return val;
10334 }
10335
10336 value *val = evaluate_subexp (to_type, exp, pos, noside);
10337 if (noside == EVAL_SKIP)
10338 return eval_skip_value (exp);
10339 return ada_value_cast (to_type, val);
10340 }
10341
10342 /* A helper function for TERNOP_IN_RANGE. */
10343
10344 static value *
10345 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10346 enum noside noside,
10347 value *arg1, value *arg2, value *arg3)
10348 {
10349 if (noside == EVAL_SKIP)
10350 return eval_skip_value (exp);
10351
10352 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10353 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10354 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10355 return
10356 value_from_longest (type,
10357 (value_less (arg1, arg3)
10358 || value_equal (arg1, arg3))
10359 && (value_less (arg2, arg1)
10360 || value_equal (arg2, arg1)));
10361 }
10362
10363 /* A helper function for UNOP_NEG. */
10364
10365 value *
10366 ada_unop_neg (struct type *expect_type,
10367 struct expression *exp,
10368 enum noside noside, enum exp_opcode op,
10369 struct value *arg1)
10370 {
10371 if (noside == EVAL_SKIP)
10372 return eval_skip_value (exp);
10373 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10374 return value_neg (arg1);
10375 }
10376
10377 /* A helper function for UNOP_IN_RANGE. */
10378
10379 value *
10380 ada_unop_in_range (struct type *expect_type,
10381 struct expression *exp,
10382 enum noside noside, enum exp_opcode op,
10383 struct value *arg1, struct type *type)
10384 {
10385 if (noside == EVAL_SKIP)
10386 return eval_skip_value (exp);
10387
10388 struct value *arg2, *arg3;
10389 switch (type->code ())
10390 {
10391 default:
10392 lim_warning (_("Membership test incompletely implemented; "
10393 "always returns true"));
10394 type = language_bool_type (exp->language_defn, exp->gdbarch);
10395 return value_from_longest (type, (LONGEST) 1);
10396
10397 case TYPE_CODE_RANGE:
10398 arg2 = value_from_longest (type,
10399 type->bounds ()->low.const_val ());
10400 arg3 = value_from_longest (type,
10401 type->bounds ()->high.const_val ());
10402 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10403 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10404 type = language_bool_type (exp->language_defn, exp->gdbarch);
10405 return
10406 value_from_longest (type,
10407 (value_less (arg1, arg3)
10408 || value_equal (arg1, arg3))
10409 && (value_less (arg2, arg1)
10410 || value_equal (arg2, arg1)));
10411 }
10412 }
10413
10414 /* A helper function for OP_ATR_TAG. */
10415
10416 value *
10417 ada_atr_tag (struct type *expect_type,
10418 struct expression *exp,
10419 enum noside noside, enum exp_opcode op,
10420 struct value *arg1)
10421 {
10422 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10423 return value_zero (ada_tag_type (arg1), not_lval);
10424
10425 return ada_value_tag (arg1);
10426 }
10427
10428 /* A helper function for OP_ATR_SIZE. */
10429
10430 value *
10431 ada_atr_size (struct type *expect_type,
10432 struct expression *exp,
10433 enum noside noside, enum exp_opcode op,
10434 struct value *arg1)
10435 {
10436 struct type *type = value_type (arg1);
10437
10438 /* If the argument is a reference, then dereference its type, since
10439 the user is really asking for the size of the actual object,
10440 not the size of the pointer. */
10441 if (type->code () == TYPE_CODE_REF)
10442 type = TYPE_TARGET_TYPE (type);
10443
10444 if (noside == EVAL_SKIP)
10445 return eval_skip_value (exp);
10446 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10447 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10448 else
10449 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10450 TARGET_CHAR_BIT * TYPE_LENGTH (type));
10451 }
10452
10453 /* A helper function for UNOP_ABS. */
10454
10455 value *
10456 ada_abs (struct type *expect_type,
10457 struct expression *exp,
10458 enum noside noside, enum exp_opcode op,
10459 struct value *arg1)
10460 {
10461 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10462 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10463 return value_neg (arg1);
10464 else
10465 return arg1;
10466 }
10467
10468 /* A helper function for BINOP_MUL. */
10469
10470 value *
10471 ada_mult_binop (struct type *expect_type,
10472 struct expression *exp,
10473 enum noside noside, enum exp_opcode op,
10474 struct value *arg1, struct value *arg2)
10475 {
10476 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10477 {
10478 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10479 return value_zero (value_type (arg1), not_lval);
10480 }
10481 else
10482 {
10483 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10484 return ada_value_binop (arg1, arg2, op);
10485 }
10486 }
10487
10488 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10489
10490 value *
10491 ada_equal_binop (struct type *expect_type,
10492 struct expression *exp,
10493 enum noside noside, enum exp_opcode op,
10494 struct value *arg1, struct value *arg2)
10495 {
10496 int tem;
10497 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10498 tem = 0;
10499 else
10500 {
10501 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10502 tem = ada_value_equal (arg1, arg2);
10503 }
10504 if (op == BINOP_NOTEQUAL)
10505 tem = !tem;
10506 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10507 return value_from_longest (type, (LONGEST) tem);
10508 }
10509
10510 /* A helper function for TERNOP_SLICE. */
10511
10512 value *
10513 ada_ternop_slice (struct expression *exp,
10514 enum noside noside,
10515 struct value *array, struct value *low_bound_val,
10516 struct value *high_bound_val)
10517 {
10518 LONGEST low_bound;
10519 LONGEST high_bound;
10520
10521 low_bound_val = coerce_ref (low_bound_val);
10522 high_bound_val = coerce_ref (high_bound_val);
10523 low_bound = value_as_long (low_bound_val);
10524 high_bound = value_as_long (high_bound_val);
10525
10526 /* If this is a reference to an aligner type, then remove all
10527 the aligners. */
10528 if (value_type (array)->code () == TYPE_CODE_REF
10529 && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
10530 TYPE_TARGET_TYPE (value_type (array)) =
10531 ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
10532
10533 if (ada_is_any_packed_array_type (value_type (array)))
10534 error (_("cannot slice a packed array"));
10535
10536 /* If this is a reference to an array or an array lvalue,
10537 convert to a pointer. */
10538 if (value_type (array)->code () == TYPE_CODE_REF
10539 || (value_type (array)->code () == TYPE_CODE_ARRAY
10540 && VALUE_LVAL (array) == lval_memory))
10541 array = value_addr (array);
10542
10543 if (noside == EVAL_AVOID_SIDE_EFFECTS
10544 && ada_is_array_descriptor_type (ada_check_typedef
10545 (value_type (array))))
10546 return empty_array (ada_type_of_array (array, 0), low_bound,
10547 high_bound);
10548
10549 array = ada_coerce_to_simple_array_ptr (array);
10550
10551 /* If we have more than one level of pointer indirection,
10552 dereference the value until we get only one level. */
10553 while (value_type (array)->code () == TYPE_CODE_PTR
10554 && (TYPE_TARGET_TYPE (value_type (array))->code ()
10555 == TYPE_CODE_PTR))
10556 array = value_ind (array);
10557
10558 /* Make sure we really do have an array type before going further,
10559 to avoid a SEGV when trying to get the index type or the target
10560 type later down the road if the debug info generated by
10561 the compiler is incorrect or incomplete. */
10562 if (!ada_is_simple_array_type (value_type (array)))
10563 error (_("cannot take slice of non-array"));
10564
10565 if (ada_check_typedef (value_type (array))->code ()
10566 == TYPE_CODE_PTR)
10567 {
10568 struct type *type0 = ada_check_typedef (value_type (array));
10569
10570 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10571 return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
10572 else
10573 {
10574 struct type *arr_type0 =
10575 to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
10576
10577 return ada_value_slice_from_ptr (array, arr_type0,
10578 longest_to_int (low_bound),
10579 longest_to_int (high_bound));
10580 }
10581 }
10582 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10583 return array;
10584 else if (high_bound < low_bound)
10585 return empty_array (value_type (array), low_bound, high_bound);
10586 else
10587 return ada_value_slice (array, longest_to_int (low_bound),
10588 longest_to_int (high_bound));
10589 }
10590
10591 /* A helper function for BINOP_IN_BOUNDS. */
10592
10593 value *
10594 ada_binop_in_bounds (struct expression *exp, enum noside noside,
10595 struct value *arg1, struct value *arg2, int n)
10596 {
10597 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10598 {
10599 struct type *type = language_bool_type (exp->language_defn,
10600 exp->gdbarch);
10601 return value_zero (type, not_lval);
10602 }
10603
10604 struct type *type = ada_index_type (value_type (arg2), n, "range");
10605 if (!type)
10606 type = value_type (arg1);
10607
10608 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10609 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10610
10611 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10612 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10613 type = language_bool_type (exp->language_defn, exp->gdbarch);
10614 return value_from_longest (type,
10615 (value_less (arg1, arg3)
10616 || value_equal (arg1, arg3))
10617 && (value_less (arg2, arg1)
10618 || value_equal (arg2, arg1)));
10619 }
10620
10621 /* A helper function for some attribute operations. */
10622
10623 static value *
10624 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10625 struct value *arg1, struct type *type_arg, int tem)
10626 {
10627 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10628 {
10629 if (type_arg == NULL)
10630 type_arg = value_type (arg1);
10631
10632 if (ada_is_constrained_packed_array_type (type_arg))
10633 type_arg = decode_constrained_packed_array_type (type_arg);
10634
10635 if (!discrete_type_p (type_arg))
10636 {
10637 switch (op)
10638 {
10639 default: /* Should never happen. */
10640 error (_("unexpected attribute encountered"));
10641 case OP_ATR_FIRST:
10642 case OP_ATR_LAST:
10643 type_arg = ada_index_type (type_arg, tem,
10644 ada_attribute_name (op));
10645 break;
10646 case OP_ATR_LENGTH:
10647 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10648 break;
10649 }
10650 }
10651
10652 return value_zero (type_arg, not_lval);
10653 }
10654 else if (type_arg == NULL)
10655 {
10656 arg1 = ada_coerce_ref (arg1);
10657
10658 if (ada_is_constrained_packed_array_type (value_type (arg1)))
10659 arg1 = ada_coerce_to_simple_array (arg1);
10660
10661 struct type *type;
10662 if (op == OP_ATR_LENGTH)
10663 type = builtin_type (exp->gdbarch)->builtin_int;
10664 else
10665 {
10666 type = ada_index_type (value_type (arg1), tem,
10667 ada_attribute_name (op));
10668 if (type == NULL)
10669 type = builtin_type (exp->gdbarch)->builtin_int;
10670 }
10671
10672 switch (op)
10673 {
10674 default: /* Should never happen. */
10675 error (_("unexpected attribute encountered"));
10676 case OP_ATR_FIRST:
10677 return value_from_longest
10678 (type, ada_array_bound (arg1, tem, 0));
10679 case OP_ATR_LAST:
10680 return value_from_longest
10681 (type, ada_array_bound (arg1, tem, 1));
10682 case OP_ATR_LENGTH:
10683 return value_from_longest
10684 (type, ada_array_length (arg1, tem));
10685 }
10686 }
10687 else if (discrete_type_p (type_arg))
10688 {
10689 struct type *range_type;
10690 const char *name = ada_type_name (type_arg);
10691
10692 range_type = NULL;
10693 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10694 range_type = to_fixed_range_type (type_arg, NULL);
10695 if (range_type == NULL)
10696 range_type = type_arg;
10697 switch (op)
10698 {
10699 default:
10700 error (_("unexpected attribute encountered"));
10701 case OP_ATR_FIRST:
10702 return value_from_longest
10703 (range_type, ada_discrete_type_low_bound (range_type));
10704 case OP_ATR_LAST:
10705 return value_from_longest
10706 (range_type, ada_discrete_type_high_bound (range_type));
10707 case OP_ATR_LENGTH:
10708 error (_("the 'length attribute applies only to array types"));
10709 }
10710 }
10711 else if (type_arg->code () == TYPE_CODE_FLT)
10712 error (_("unimplemented type attribute"));
10713 else
10714 {
10715 LONGEST low, high;
10716
10717 if (ada_is_constrained_packed_array_type (type_arg))
10718 type_arg = decode_constrained_packed_array_type (type_arg);
10719
10720 struct type *type;
10721 if (op == OP_ATR_LENGTH)
10722 type = builtin_type (exp->gdbarch)->builtin_int;
10723 else
10724 {
10725 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10726 if (type == NULL)
10727 type = builtin_type (exp->gdbarch)->builtin_int;
10728 }
10729
10730 switch (op)
10731 {
10732 default:
10733 error (_("unexpected attribute encountered"));
10734 case OP_ATR_FIRST:
10735 low = ada_array_bound_from_type (type_arg, tem, 0);
10736 return value_from_longest (type, low);
10737 case OP_ATR_LAST:
10738 high = ada_array_bound_from_type (type_arg, tem, 1);
10739 return value_from_longest (type, high);
10740 case OP_ATR_LENGTH:
10741 low = ada_array_bound_from_type (type_arg, tem, 0);
10742 high = ada_array_bound_from_type (type_arg, tem, 1);
10743 return value_from_longest (type, high - low + 1);
10744 }
10745 }
10746 }
10747
10748 /* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10749
10750 struct value *
10751 ada_binop_minmax (struct type *expect_type,
10752 struct expression *exp,
10753 enum noside noside, enum exp_opcode op,
10754 struct value *arg1, struct value *arg2)
10755 {
10756 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10757 return value_zero (value_type (arg1), not_lval);
10758 else
10759 {
10760 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10761 return value_binop (arg1, arg2,
10762 op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
10763 }
10764 }
10765
10766 /* A helper function for BINOP_EXP. */
10767
10768 struct value *
10769 ada_binop_exp (struct type *expect_type,
10770 struct expression *exp,
10771 enum noside noside, enum exp_opcode op,
10772 struct value *arg1, struct value *arg2)
10773 {
10774 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10775 return value_zero (value_type (arg1), not_lval);
10776 else
10777 {
10778 /* For integer exponentiation operations,
10779 only promote the first argument. */
10780 if (is_integral_type (value_type (arg2)))
10781 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10782 else
10783 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10784
10785 return value_binop (arg1, arg2, op);
10786 }
10787 }
10788
10789 namespace expr
10790 {
10791
10792 value *
10793 ada_wrapped_operation::evaluate (struct type *expect_type,
10794 struct expression *exp,
10795 enum noside noside)
10796 {
10797 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10798 if (noside == EVAL_NORMAL)
10799 result = unwrap_value (result);
10800
10801 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10802 then we need to perform the conversion manually, because
10803 evaluate_subexp_standard doesn't do it. This conversion is
10804 necessary in Ada because the different kinds of float/fixed
10805 types in Ada have different representations.
10806
10807 Similarly, we need to perform the conversion from OP_LONG
10808 ourselves. */
10809 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10810 result = ada_value_cast (expect_type, result);
10811
10812 return result;
10813 }
10814
10815 value *
10816 ada_string_operation::evaluate (struct type *expect_type,
10817 struct expression *exp,
10818 enum noside noside)
10819 {
10820 value *result = string_operation::evaluate (expect_type, exp, noside);
10821 /* The result type will have code OP_STRING, bashed there from
10822 OP_ARRAY. Bash it back. */
10823 if (value_type (result)->code () == TYPE_CODE_STRING)
10824 value_type (result)->set_code (TYPE_CODE_ARRAY);
10825 return result;
10826 }
10827
10828 value *
10829 ada_qual_operation::evaluate (struct type *expect_type,
10830 struct expression *exp,
10831 enum noside noside)
10832 {
10833 struct type *type = std::get<1> (m_storage);
10834 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10835 }
10836
10837 value *
10838 ada_ternop_range_operation::evaluate (struct type *expect_type,
10839 struct expression *exp,
10840 enum noside noside)
10841 {
10842 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10843 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10844 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10845 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10846 }
10847
10848 value *
10849 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10850 struct expression *exp,
10851 enum noside noside)
10852 {
10853 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10854 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10855
10856 auto do_op = [=] (LONGEST x, LONGEST y)
10857 {
10858 if (std::get<0> (m_storage) == BINOP_ADD)
10859 return x + y;
10860 return x - y;
10861 };
10862
10863 if (value_type (arg1)->code () == TYPE_CODE_PTR)
10864 return (value_from_longest
10865 (value_type (arg1),
10866 do_op (value_as_long (arg1), value_as_long (arg2))));
10867 if (value_type (arg2)->code () == TYPE_CODE_PTR)
10868 return (value_from_longest
10869 (value_type (arg2),
10870 do_op (value_as_long (arg1), value_as_long (arg2))));
10871 /* Preserve the original type for use by the range case below.
10872 We cannot cast the result to a reference type, so if ARG1 is
10873 a reference type, find its underlying type. */
10874 struct type *type = value_type (arg1);
10875 while (type->code () == TYPE_CODE_REF)
10876 type = TYPE_TARGET_TYPE (type);
10877 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10878 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10879 /* We need to special-case the result with a range.
10880 This is done for the benefit of "ptype". gdb's Ada support
10881 historically used the LHS to set the result type here, so
10882 preserve this behavior. */
10883 if (type->code () == TYPE_CODE_RANGE)
10884 arg1 = value_cast (type, arg1);
10885 return arg1;
10886 }
10887
10888 value *
10889 ada_unop_atr_operation::evaluate (struct type *expect_type,
10890 struct expression *exp,
10891 enum noside noside)
10892 {
10893 struct type *type_arg = nullptr;
10894 value *val = nullptr;
10895
10896 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10897 {
10898 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10899 EVAL_AVOID_SIDE_EFFECTS);
10900 type_arg = value_type (tem);
10901 }
10902 else
10903 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10904
10905 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10906 val, type_arg, std::get<2> (m_storage));
10907 }
10908
10909 value *
10910 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10911 struct expression *exp,
10912 enum noside noside)
10913 {
10914 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10915 return value_zero (expect_type, not_lval);
10916
10917 value *val = evaluate_var_msym_value (noside,
10918 std::get<1> (m_storage),
10919 std::get<0> (m_storage));
10920
10921 val = ada_value_cast (expect_type, val);
10922
10923 /* Follow the Ada language semantics that do not allow taking
10924 an address of the result of a cast (view conversion in Ada). */
10925 if (VALUE_LVAL (val) == lval_memory)
10926 {
10927 if (value_lazy (val))
10928 value_fetch_lazy (val);
10929 VALUE_LVAL (val) = not_lval;
10930 }
10931 return val;
10932 }
10933
10934 value *
10935 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10936 struct expression *exp,
10937 enum noside noside)
10938 {
10939 value *val = evaluate_var_value (noside,
10940 std::get<1> (m_storage),
10941 std::get<0> (m_storage));
10942
10943 val = ada_value_cast (expect_type, val);
10944
10945 /* Follow the Ada language semantics that do not allow taking
10946 an address of the result of a cast (view conversion in Ada). */
10947 if (VALUE_LVAL (val) == lval_memory)
10948 {
10949 if (value_lazy (val))
10950 value_fetch_lazy (val);
10951 VALUE_LVAL (val) = not_lval;
10952 }
10953 return val;
10954 }
10955
10956 value *
10957 ada_var_value_operation::evaluate (struct type *expect_type,
10958 struct expression *exp,
10959 enum noside noside)
10960 {
10961 symbol *sym = std::get<0> (m_storage);
10962
10963 if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
10964 /* Only encountered when an unresolved symbol occurs in a
10965 context other than a function call, in which case, it is
10966 invalid. */
10967 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10968 sym->print_name ());
10969
10970 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10971 {
10972 struct type *type = static_unwrap_type (SYMBOL_TYPE (sym));
10973 /* Check to see if this is a tagged type. We also need to handle
10974 the case where the type is a reference to a tagged type, but
10975 we have to be careful to exclude pointers to tagged types.
10976 The latter should be shown as usual (as a pointer), whereas
10977 a reference should mostly be transparent to the user. */
10978 if (ada_is_tagged_type (type, 0)
10979 || (type->code () == TYPE_CODE_REF
10980 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10981 {
10982 /* Tagged types are a little special in the fact that the real
10983 type is dynamic and can only be determined by inspecting the
10984 object's tag. This means that we need to get the object's
10985 value first (EVAL_NORMAL) and then extract the actual object
10986 type from its tag.
10987
10988 Note that we cannot skip the final step where we extract
10989 the object type from its tag, because the EVAL_NORMAL phase
10990 results in dynamic components being resolved into fixed ones.
10991 This can cause problems when trying to print the type
10992 description of tagged types whose parent has a dynamic size:
10993 We use the type name of the "_parent" component in order
10994 to print the name of the ancestor type in the type description.
10995 If that component had a dynamic size, the resolution into
10996 a fixed type would result in the loss of that type name,
10997 thus preventing us from printing the name of the ancestor
10998 type in the type description. */
10999 value *arg1 = var_value_operation::evaluate (nullptr, exp,
11000 EVAL_NORMAL);
11001
11002 if (type->code () != TYPE_CODE_REF)
11003 {
11004 struct type *actual_type;
11005
11006 actual_type = type_from_tag (ada_value_tag (arg1));
11007 if (actual_type == NULL)
11008 /* If, for some reason, we were unable to determine
11009 the actual type from the tag, then use the static
11010 approximation that we just computed as a fallback.
11011 This can happen if the debugging information is
11012 incomplete, for instance. */
11013 actual_type = type;
11014 return value_zero (actual_type, not_lval);
11015 }
11016 else
11017 {
11018 /* In the case of a ref, ada_coerce_ref takes care
11019 of determining the actual type. But the evaluation
11020 should return a ref as it should be valid to ask
11021 for its address; so rebuild a ref after coerce. */
11022 arg1 = ada_coerce_ref (arg1);
11023 return value_ref (arg1, TYPE_CODE_REF);
11024 }
11025 }
11026
11027 /* Records and unions for which GNAT encodings have been
11028 generated need to be statically fixed as well.
11029 Otherwise, non-static fixing produces a type where
11030 all dynamic properties are removed, which prevents "ptype"
11031 from being able to completely describe the type.
11032 For instance, a case statement in a variant record would be
11033 replaced by the relevant components based on the actual
11034 value of the discriminants. */
11035 if ((type->code () == TYPE_CODE_STRUCT
11036 && dynamic_template_type (type) != NULL)
11037 || (type->code () == TYPE_CODE_UNION
11038 && ada_find_parallel_type (type, "___XVU") != NULL))
11039 return value_zero (to_static_fixed_type (type), not_lval);
11040 }
11041
11042 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
11043 return ada_to_fixed_value (arg1);
11044 }
11045
11046 bool
11047 ada_var_value_operation::resolve (struct expression *exp,
11048 bool deprocedure_p,
11049 bool parse_completion,
11050 innermost_block_tracker *tracker,
11051 struct type *context_type)
11052 {
11053 symbol *sym = std::get<0> (m_storage);
11054 if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
11055 {
11056 block_symbol resolved
11057 = ada_resolve_variable (sym, std::get<1> (m_storage),
11058 context_type, parse_completion,
11059 deprocedure_p, tracker);
11060 std::get<0> (m_storage) = resolved.symbol;
11061 std::get<1> (m_storage) = resolved.block;
11062 }
11063
11064 if (deprocedure_p
11065 && SYMBOL_TYPE (std::get<0> (m_storage))->code () == TYPE_CODE_FUNC)
11066 return true;
11067
11068 return false;
11069 }
11070
11071 value *
11072 ada_atr_val_operation::evaluate (struct type *expect_type,
11073 struct expression *exp,
11074 enum noside noside)
11075 {
11076 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
11077 return ada_val_atr (noside, std::get<0> (m_storage), arg);
11078 }
11079
11080 value *
11081 ada_unop_ind_operation::evaluate (struct type *expect_type,
11082 struct expression *exp,
11083 enum noside noside)
11084 {
11085 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11086
11087 struct type *type = ada_check_typedef (value_type (arg1));
11088 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11089 {
11090 if (ada_is_array_descriptor_type (type))
11091 /* GDB allows dereferencing GNAT array descriptors. */
11092 {
11093 struct type *arrType = ada_type_of_array (arg1, 0);
11094
11095 if (arrType == NULL)
11096 error (_("Attempt to dereference null array pointer."));
11097 return value_at_lazy (arrType, 0);
11098 }
11099 else if (type->code () == TYPE_CODE_PTR
11100 || type->code () == TYPE_CODE_REF
11101 /* In C you can dereference an array to get the 1st elt. */
11102 || type->code () == TYPE_CODE_ARRAY)
11103 {
11104 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11105 only be determined by inspecting the object's tag.
11106 This means that we need to evaluate completely the
11107 expression in order to get its type. */
11108
11109 if ((type->code () == TYPE_CODE_REF
11110 || type->code () == TYPE_CODE_PTR)
11111 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11112 {
11113 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11114 EVAL_NORMAL);
11115 type = value_type (ada_value_ind (arg1));
11116 }
11117 else
11118 {
11119 type = to_static_fixed_type
11120 (ada_aligned_type
11121 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
11122 }
11123 ada_ensure_varsize_limit (type);
11124 return value_zero (type, lval_memory);
11125 }
11126 else if (type->code () == TYPE_CODE_INT)
11127 {
11128 /* GDB allows dereferencing an int. */
11129 if (expect_type == NULL)
11130 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11131 lval_memory);
11132 else
11133 {
11134 expect_type =
11135 to_static_fixed_type (ada_aligned_type (expect_type));
11136 return value_zero (expect_type, lval_memory);
11137 }
11138 }
11139 else
11140 error (_("Attempt to take contents of a non-pointer value."));
11141 }
11142 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11143 type = ada_check_typedef (value_type (arg1));
11144
11145 if (type->code () == TYPE_CODE_INT)
11146 /* GDB allows dereferencing an int. If we were given
11147 the expect_type, then use that as the target type.
11148 Otherwise, assume that the target type is an int. */
11149 {
11150 if (expect_type != NULL)
11151 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11152 arg1));
11153 else
11154 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11155 (CORE_ADDR) value_as_address (arg1));
11156 }
11157
11158 if (ada_is_array_descriptor_type (type))
11159 /* GDB allows dereferencing GNAT array descriptors. */
11160 return ada_coerce_to_simple_array (arg1);
11161 else
11162 return ada_value_ind (arg1);
11163 }
11164
11165 value *
11166 ada_structop_operation::evaluate (struct type *expect_type,
11167 struct expression *exp,
11168 enum noside noside)
11169 {
11170 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11171 const char *str = std::get<1> (m_storage).c_str ();
11172 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11173 {
11174 struct type *type;
11175 struct type *type1 = value_type (arg1);
11176
11177 if (ada_is_tagged_type (type1, 1))
11178 {
11179 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11180
11181 /* If the field is not found, check if it exists in the
11182 extension of this object's type. This means that we
11183 need to evaluate completely the expression. */
11184
11185 if (type == NULL)
11186 {
11187 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11188 EVAL_NORMAL);
11189 arg1 = ada_value_struct_elt (arg1, str, 0);
11190 arg1 = unwrap_value (arg1);
11191 type = value_type (ada_to_fixed_value (arg1));
11192 }
11193 }
11194 else
11195 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11196
11197 return value_zero (ada_aligned_type (type), lval_memory);
11198 }
11199 else
11200 {
11201 arg1 = ada_value_struct_elt (arg1, str, 0);
11202 arg1 = unwrap_value (arg1);
11203 return ada_to_fixed_value (arg1);
11204 }
11205 }
11206
11207 value *
11208 ada_funcall_operation::evaluate (struct type *expect_type,
11209 struct expression *exp,
11210 enum noside noside)
11211 {
11212 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11213 int nargs = args_up.size ();
11214 std::vector<value *> argvec (nargs);
11215 operation_up &callee_op = std::get<0> (m_storage);
11216
11217 ada_var_value_operation *avv
11218 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11219 if (avv != nullptr
11220 && SYMBOL_DOMAIN (avv->get_symbol ()) == UNDEF_DOMAIN)
11221 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11222 avv->get_symbol ()->print_name ());
11223
11224 value *callee = callee_op->evaluate (nullptr, exp, noside);
11225 for (int i = 0; i < args_up.size (); ++i)
11226 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11227
11228 if (ada_is_constrained_packed_array_type
11229 (desc_base_type (value_type (callee))))
11230 callee = ada_coerce_to_simple_array (callee);
11231 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11232 && TYPE_FIELD_BITSIZE (value_type (callee), 0) != 0)
11233 /* This is a packed array that has already been fixed, and
11234 therefore already coerced to a simple array. Nothing further
11235 to do. */
11236 ;
11237 else if (value_type (callee)->code () == TYPE_CODE_REF)
11238 {
11239 /* Make sure we dereference references so that all the code below
11240 feels like it's really handling the referenced value. Wrapping
11241 types (for alignment) may be there, so make sure we strip them as
11242 well. */
11243 callee = ada_to_fixed_value (coerce_ref (callee));
11244 }
11245 else if (value_type (callee)->code () == TYPE_CODE_ARRAY
11246 && VALUE_LVAL (callee) == lval_memory)
11247 callee = value_addr (callee);
11248
11249 struct type *type = ada_check_typedef (value_type (callee));
11250
11251 /* Ada allows us to implicitly dereference arrays when subscripting
11252 them. So, if this is an array typedef (encoding use for array
11253 access types encoded as fat pointers), strip it now. */
11254 if (type->code () == TYPE_CODE_TYPEDEF)
11255 type = ada_typedef_target_type (type);
11256
11257 if (type->code () == TYPE_CODE_PTR)
11258 {
11259 switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
11260 {
11261 case TYPE_CODE_FUNC:
11262 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11263 break;
11264 case TYPE_CODE_ARRAY:
11265 break;
11266 case TYPE_CODE_STRUCT:
11267 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11268 callee = ada_value_ind (callee);
11269 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11270 break;
11271 default:
11272 error (_("cannot subscript or call something of type `%s'"),
11273 ada_type_name (value_type (callee)));
11274 break;
11275 }
11276 }
11277
11278 switch (type->code ())
11279 {
11280 case TYPE_CODE_FUNC:
11281 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11282 {
11283 if (TYPE_TARGET_TYPE (type) == NULL)
11284 error_call_unknown_return_type (NULL);
11285 return allocate_value (TYPE_TARGET_TYPE (type));
11286 }
11287 return call_function_by_hand (callee, NULL, argvec);
11288 case TYPE_CODE_INTERNAL_FUNCTION:
11289 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11290 /* We don't know anything about what the internal
11291 function might return, but we have to return
11292 something. */
11293 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11294 not_lval);
11295 else
11296 return call_internal_function (exp->gdbarch, exp->language_defn,
11297 callee, nargs,
11298 argvec.data ());
11299
11300 case TYPE_CODE_STRUCT:
11301 {
11302 int arity;
11303
11304 arity = ada_array_arity (type);
11305 type = ada_array_element_type (type, nargs);
11306 if (type == NULL)
11307 error (_("cannot subscript or call a record"));
11308 if (arity != nargs)
11309 error (_("wrong number of subscripts; expecting %d"), arity);
11310 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11311 return value_zero (ada_aligned_type (type), lval_memory);
11312 return
11313 unwrap_value (ada_value_subscript
11314 (callee, nargs, argvec.data ()));
11315 }
11316 case TYPE_CODE_ARRAY:
11317 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11318 {
11319 type = ada_array_element_type (type, nargs);
11320 if (type == NULL)
11321 error (_("element type of array unknown"));
11322 else
11323 return value_zero (ada_aligned_type (type), lval_memory);
11324 }
11325 return
11326 unwrap_value (ada_value_subscript
11327 (ada_coerce_to_simple_array (callee),
11328 nargs, argvec.data ()));
11329 case TYPE_CODE_PTR: /* Pointer to array */
11330 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11331 {
11332 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
11333 type = ada_array_element_type (type, nargs);
11334 if (type == NULL)
11335 error (_("element type of array unknown"));
11336 else
11337 return value_zero (ada_aligned_type (type), lval_memory);
11338 }
11339 return
11340 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11341 argvec.data ()));
11342
11343 default:
11344 error (_("Attempt to index or call something other than an "
11345 "array or function"));
11346 }
11347 }
11348
11349 bool
11350 ada_funcall_operation::resolve (struct expression *exp,
11351 bool deprocedure_p,
11352 bool parse_completion,
11353 innermost_block_tracker *tracker,
11354 struct type *context_type)
11355 {
11356 operation_up &callee_op = std::get<0> (m_storage);
11357
11358 ada_var_value_operation *avv
11359 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11360 if (avv == nullptr)
11361 return false;
11362
11363 symbol *sym = avv->get_symbol ();
11364 if (SYMBOL_DOMAIN (sym) != UNDEF_DOMAIN)
11365 return false;
11366
11367 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11368 int nargs = args_up.size ();
11369 std::vector<value *> argvec (nargs);
11370
11371 for (int i = 0; i < args_up.size (); ++i)
11372 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
11373
11374 const block *block = avv->get_block ();
11375 block_symbol resolved
11376 = ada_resolve_funcall (sym, block,
11377 context_type, parse_completion,
11378 nargs, argvec.data (),
11379 tracker);
11380
11381 std::get<0> (m_storage)
11382 = make_operation<ada_var_value_operation> (resolved.symbol,
11383 resolved.block);
11384 return false;
11385 }
11386
11387 bool
11388 ada_ternop_slice_operation::resolve (struct expression *exp,
11389 bool deprocedure_p,
11390 bool parse_completion,
11391 innermost_block_tracker *tracker,
11392 struct type *context_type)
11393 {
11394 /* Historically this check was done during resolution, so we
11395 continue that here. */
11396 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11397 EVAL_AVOID_SIDE_EFFECTS);
11398 if (ada_is_any_packed_array_type (value_type (v)))
11399 error (_("cannot slice a packed array"));
11400 return false;
11401 }
11402
11403 }
11404
11405 /* Implement the evaluate_exp routine in the exp_descriptor structure
11406 for the Ada language. */
11407
11408 static struct value *
11409 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
11410 int *pos, enum noside noside)
11411 {
11412 enum exp_opcode op;
11413 int tem;
11414 int pc;
11415 int preeval_pos;
11416 struct value *arg1 = NULL, *arg2 = NULL, *arg3;
11417 struct type *type;
11418 int nargs, oplen;
11419 struct value **argvec;
11420
11421 pc = *pos;
11422 *pos += 1;
11423 op = exp->elts[pc].opcode;
11424
11425 switch (op)
11426 {
11427 default:
11428 *pos -= 1;
11429 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
11430
11431 if (noside == EVAL_NORMAL)
11432 arg1 = unwrap_value (arg1);
11433
11434 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
11435 then we need to perform the conversion manually, because
11436 evaluate_subexp_standard doesn't do it. This conversion is
11437 necessary in Ada because the different kinds of float/fixed
11438 types in Ada have different representations.
11439
11440 Similarly, we need to perform the conversion from OP_LONG
11441 ourselves. */
11442 if ((op == OP_FLOAT || op == OP_LONG) && expect_type != NULL)
11443 arg1 = ada_value_cast (expect_type, arg1);
11444
11445 return arg1;
11446
11447 case OP_STRING:
11448 {
11449 struct value *result;
11450
11451 *pos -= 1;
11452 result = evaluate_subexp_standard (expect_type, exp, pos, noside);
11453 /* The result type will have code OP_STRING, bashed there from
11454 OP_ARRAY. Bash it back. */
11455 if (value_type (result)->code () == TYPE_CODE_STRING)
11456 value_type (result)->set_code (TYPE_CODE_ARRAY);
11457 return result;
11458 }
11459
11460 case UNOP_CAST:
11461 (*pos) += 2;
11462 type = exp->elts[pc + 1].type;
11463 return ada_evaluate_subexp_for_cast (exp, pos, noside, type);
11464
11465 case UNOP_QUAL:
11466 (*pos) += 2;
11467 type = exp->elts[pc + 1].type;
11468 return ada_evaluate_subexp (type, exp, pos, noside);
11469
11470 case BINOP_ASSIGN:
11471 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11472 if (exp->elts[*pos].opcode == OP_AGGREGATE)
11473 {
11474 arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
11475 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
11476 return arg1;
11477 return ada_value_assign (arg1, arg1);
11478 }
11479 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
11480 except if the lhs of our assignment is a convenience variable.
11481 In the case of assigning to a convenience variable, the lhs
11482 should be exactly the result of the evaluation of the rhs. */
11483 type = value_type (arg1);
11484 if (VALUE_LVAL (arg1) == lval_internalvar)
11485 type = NULL;
11486 arg2 = evaluate_subexp (type, exp, pos, noside);
11487 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
11488 return arg1;
11489 if (VALUE_LVAL (arg1) == lval_internalvar)
11490 {
11491 /* Nothing. */
11492 }
11493 else
11494 arg2 = coerce_for_assign (value_type (arg1), arg2);
11495 return ada_value_assign (arg1, arg2);
11496
11497 case BINOP_ADD:
11498 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
11499 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
11500 if (noside == EVAL_SKIP)
11501 goto nosideret;
11502 if (value_type (arg1)->code () == TYPE_CODE_PTR)
11503 return (value_from_longest
11504 (value_type (arg1),
11505 value_as_long (arg1) + value_as_long (arg2)));
11506 if (value_type (arg2)->code () == TYPE_CODE_PTR)
11507 return (value_from_longest
11508 (value_type (arg2),
11509 value_as_long (arg1) + value_as_long (arg2)));
11510 /* Preserve the original type for use by the range case below.
11511 We cannot cast the result to a reference type, so if ARG1 is
11512 a reference type, find its underlying type. */
11513 type = value_type (arg1);
11514 while (type->code () == TYPE_CODE_REF)
11515 type = TYPE_TARGET_TYPE (type);
11516 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11517 arg1 = value_binop (arg1, arg2, BINOP_ADD);
11518 /* We need to special-case the result of adding to a range.
11519 This is done for the benefit of "ptype". gdb's Ada support
11520 historically used the LHS to set the result type here, so
11521 preserve this behavior. */
11522 if (type->code () == TYPE_CODE_RANGE)
11523 arg1 = value_cast (type, arg1);
11524 return arg1;
11525
11526 case BINOP_SUB:
11527 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
11528 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
11529 if (noside == EVAL_SKIP)
11530 goto nosideret;
11531 if (value_type (arg1)->code () == TYPE_CODE_PTR)
11532 return (value_from_longest
11533 (value_type (arg1),
11534 value_as_long (arg1) - value_as_long (arg2)));
11535 if (value_type (arg2)->code () == TYPE_CODE_PTR)
11536 return (value_from_longest
11537 (value_type (arg2),
11538 value_as_long (arg1) - value_as_long (arg2)));
11539 /* Preserve the original type for use by the range case below.
11540 We cannot cast the result to a reference type, so if ARG1 is
11541 a reference type, find its underlying type. */
11542 type = value_type (arg1);
11543 while (type->code () == TYPE_CODE_REF)
11544 type = TYPE_TARGET_TYPE (type);
11545 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11546 arg1 = value_binop (arg1, arg2, BINOP_SUB);
11547 /* We need to special-case the result of adding to a range.
11548 This is done for the benefit of "ptype". gdb's Ada support
11549 historically used the LHS to set the result type here, so
11550 preserve this behavior. */
11551 if (type->code () == TYPE_CODE_RANGE)
11552 arg1 = value_cast (type, arg1);
11553 return arg1;
11554
11555 case BINOP_MUL:
11556 case BINOP_DIV:
11557 case BINOP_REM:
11558 case BINOP_MOD:
11559 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11560 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11561 if (noside == EVAL_SKIP)
11562 goto nosideret;
11563 return ada_mult_binop (expect_type, exp, noside, op,
11564 arg1, arg2);
11565
11566 case BINOP_EQUAL:
11567 case BINOP_NOTEQUAL:
11568 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11569 arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
11570 if (noside == EVAL_SKIP)
11571 goto nosideret;
11572 return ada_equal_binop (expect_type, exp, noside, op, arg1, arg2);
11573
11574 case UNOP_NEG:
11575 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11576 return ada_unop_neg (expect_type, exp, noside, op, arg1);
11577
11578 case BINOP_LOGICAL_AND:
11579 case BINOP_LOGICAL_OR:
11580 case UNOP_LOGICAL_NOT:
11581 {
11582 struct value *val;
11583
11584 *pos -= 1;
11585 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
11586 type = language_bool_type (exp->language_defn, exp->gdbarch);
11587 return value_cast (type, val);
11588 }
11589
11590 case BINOP_BITWISE_AND:
11591 case BINOP_BITWISE_IOR:
11592 case BINOP_BITWISE_XOR:
11593 {
11594 struct value *val;
11595
11596 arg1 = evaluate_subexp (nullptr, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
11597 *pos = pc;
11598 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
11599
11600 return value_cast (value_type (arg1), val);
11601 }
11602
11603 case OP_VAR_VALUE:
11604 *pos -= 1;
11605
11606 if (noside == EVAL_SKIP)
11607 {
11608 *pos += 4;
11609 goto nosideret;
11610 }
11611
11612 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
11613 /* Only encountered when an unresolved symbol occurs in a
11614 context other than a function call, in which case, it is
11615 invalid. */
11616 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11617 exp->elts[pc + 2].symbol->print_name ());
11618
11619 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11620 {
11621 type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
11622 /* Check to see if this is a tagged type. We also need to handle
11623 the case where the type is a reference to a tagged type, but
11624 we have to be careful to exclude pointers to tagged types.
11625 The latter should be shown as usual (as a pointer), whereas
11626 a reference should mostly be transparent to the user. */
11627 if (ada_is_tagged_type (type, 0)
11628 || (type->code () == TYPE_CODE_REF
11629 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
11630 {
11631 /* Tagged types are a little special in the fact that the real
11632 type is dynamic and can only be determined by inspecting the
11633 object's tag. This means that we need to get the object's
11634 value first (EVAL_NORMAL) and then extract the actual object
11635 type from its tag.
11636
11637 Note that we cannot skip the final step where we extract
11638 the object type from its tag, because the EVAL_NORMAL phase
11639 results in dynamic components being resolved into fixed ones.
11640 This can cause problems when trying to print the type
11641 description of tagged types whose parent has a dynamic size:
11642 We use the type name of the "_parent" component in order
11643 to print the name of the ancestor type in the type description.
11644 If that component had a dynamic size, the resolution into
11645 a fixed type would result in the loss of that type name,
11646 thus preventing us from printing the name of the ancestor
11647 type in the type description. */
11648 arg1 = evaluate_subexp (nullptr, exp, pos, EVAL_NORMAL);
11649
11650 if (type->code () != TYPE_CODE_REF)
11651 {
11652 struct type *actual_type;
11653
11654 actual_type = type_from_tag (ada_value_tag (arg1));
11655 if (actual_type == NULL)
11656 /* If, for some reason, we were unable to determine
11657 the actual type from the tag, then use the static
11658 approximation that we just computed as a fallback.
11659 This can happen if the debugging information is
11660 incomplete, for instance. */
11661 actual_type = type;
11662 return value_zero (actual_type, not_lval);
11663 }
11664 else
11665 {
11666 /* In the case of a ref, ada_coerce_ref takes care
11667 of determining the actual type. But the evaluation
11668 should return a ref as it should be valid to ask
11669 for its address; so rebuild a ref after coerce. */
11670 arg1 = ada_coerce_ref (arg1);
11671 return value_ref (arg1, TYPE_CODE_REF);
11672 }
11673 }
11674
11675 /* Records and unions for which GNAT encodings have been
11676 generated need to be statically fixed as well.
11677 Otherwise, non-static fixing produces a type where
11678 all dynamic properties are removed, which prevents "ptype"
11679 from being able to completely describe the type.
11680 For instance, a case statement in a variant record would be
11681 replaced by the relevant components based on the actual
11682 value of the discriminants. */
11683 if ((type->code () == TYPE_CODE_STRUCT
11684 && dynamic_template_type (type) != NULL)
11685 || (type->code () == TYPE_CODE_UNION
11686 && ada_find_parallel_type (type, "___XVU") != NULL))
11687 {
11688 *pos += 4;
11689 return value_zero (to_static_fixed_type (type), not_lval);
11690 }
11691 }
11692
11693 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
11694 return ada_to_fixed_value (arg1);
11695
11696 case OP_FUNCALL:
11697 (*pos) += 2;
11698
11699 /* Allocate arg vector, including space for the function to be
11700 called in argvec[0] and a terminating NULL. */
11701 nargs = longest_to_int (exp->elts[pc + 1].longconst);
11702 argvec = XALLOCAVEC (struct value *, nargs + 2);
11703
11704 if (exp->elts[*pos].opcode == OP_VAR_VALUE
11705 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
11706 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11707 exp->elts[pc + 5].symbol->print_name ());
11708 else
11709 {
11710 for (tem = 0; tem <= nargs; tem += 1)
11711 argvec[tem] = evaluate_subexp (nullptr, exp, pos, noside);
11712 argvec[tem] = 0;
11713
11714 if (noside == EVAL_SKIP)
11715 goto nosideret;
11716 }
11717
11718 if (ada_is_constrained_packed_array_type
11719 (desc_base_type (value_type (argvec[0]))))
11720 argvec[0] = ada_coerce_to_simple_array (argvec[0]);
11721 else if (value_type (argvec[0])->code () == TYPE_CODE_ARRAY
11722 && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
11723 /* This is a packed array that has already been fixed, and
11724 therefore already coerced to a simple array. Nothing further
11725 to do. */
11726 ;
11727 else if (value_type (argvec[0])->code () == TYPE_CODE_REF)
11728 {
11729 /* Make sure we dereference references so that all the code below
11730 feels like it's really handling the referenced value. Wrapping
11731 types (for alignment) may be there, so make sure we strip them as
11732 well. */
11733 argvec[0] = ada_to_fixed_value (coerce_ref (argvec[0]));
11734 }
11735 else if (value_type (argvec[0])->code () == TYPE_CODE_ARRAY
11736 && VALUE_LVAL (argvec[0]) == lval_memory)
11737 argvec[0] = value_addr (argvec[0]);
11738
11739 type = ada_check_typedef (value_type (argvec[0]));
11740
11741 /* Ada allows us to implicitly dereference arrays when subscripting
11742 them. So, if this is an array typedef (encoding use for array
11743 access types encoded as fat pointers), strip it now. */
11744 if (type->code () == TYPE_CODE_TYPEDEF)
11745 type = ada_typedef_target_type (type);
11746
11747 if (type->code () == TYPE_CODE_PTR)
11748 {
11749 switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
11750 {
11751 case TYPE_CODE_FUNC:
11752 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11753 break;
11754 case TYPE_CODE_ARRAY:
11755 break;
11756 case TYPE_CODE_STRUCT:
11757 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11758 argvec[0] = ada_value_ind (argvec[0]);
11759 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
11760 break;
11761 default:
11762 error (_("cannot subscript or call something of type `%s'"),
11763 ada_type_name (value_type (argvec[0])));
11764 break;
11765 }
11766 }
11767
11768 switch (type->code ())
11769 {
11770 case TYPE_CODE_FUNC:
11771 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11772 {
11773 if (TYPE_TARGET_TYPE (type) == NULL)
11774 error_call_unknown_return_type (NULL);
11775 return allocate_value (TYPE_TARGET_TYPE (type));
11776 }
11777 return call_function_by_hand (argvec[0], NULL,
11778 gdb::make_array_view (argvec + 1,
11779 nargs));
11780 case TYPE_CODE_INTERNAL_FUNCTION:
11781 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11782 /* We don't know anything about what the internal
11783 function might return, but we have to return
11784 something. */
11785 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11786 not_lval);
11787 else
11788 return call_internal_function (exp->gdbarch, exp->language_defn,
11789 argvec[0], nargs, argvec + 1);
11790
11791 case TYPE_CODE_STRUCT:
11792 {
11793 int arity;
11794
11795 arity = ada_array_arity (type);
11796 type = ada_array_element_type (type, nargs);
11797 if (type == NULL)
11798 error (_("cannot subscript or call a record"));
11799 if (arity != nargs)
11800 error (_("wrong number of subscripts; expecting %d"), arity);
11801 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11802 return value_zero (ada_aligned_type (type), lval_memory);
11803 return
11804 unwrap_value (ada_value_subscript
11805 (argvec[0], nargs, argvec + 1));
11806 }
11807 case TYPE_CODE_ARRAY:
11808 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11809 {
11810 type = ada_array_element_type (type, nargs);
11811 if (type == NULL)
11812 error (_("element type of array unknown"));
11813 else
11814 return value_zero (ada_aligned_type (type), lval_memory);
11815 }
11816 return
11817 unwrap_value (ada_value_subscript
11818 (ada_coerce_to_simple_array (argvec[0]),
11819 nargs, argvec + 1));
11820 case TYPE_CODE_PTR: /* Pointer to array */
11821 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11822 {
11823 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
11824 type = ada_array_element_type (type, nargs);
11825 if (type == NULL)
11826 error (_("element type of array unknown"));
11827 else
11828 return value_zero (ada_aligned_type (type), lval_memory);
11829 }
11830 return
11831 unwrap_value (ada_value_ptr_subscript (argvec[0],
11832 nargs, argvec + 1));
11833
11834 default:
11835 error (_("Attempt to index or call something other than an "
11836 "array or function"));
11837 }
11838
11839 case TERNOP_SLICE:
11840 {
11841 struct value *array = evaluate_subexp (nullptr, exp, pos, noside);
11842 struct value *low_bound_val
11843 = evaluate_subexp (nullptr, exp, pos, noside);
11844 struct value *high_bound_val
11845 = evaluate_subexp (nullptr, exp, pos, noside);
11846
11847 if (noside == EVAL_SKIP)
11848 goto nosideret;
11849
11850 return ada_ternop_slice (exp, noside, array, low_bound_val,
11851 high_bound_val);
11852 }
11853
11854 case UNOP_IN_RANGE:
11855 (*pos) += 2;
11856 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11857 type = check_typedef (exp->elts[pc + 1].type);
11858 return ada_unop_in_range (expect_type, exp, noside, op, arg1, type);
11859
11860 case BINOP_IN_BOUNDS:
11861 (*pos) += 2;
11862 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11863 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11864
11865 if (noside == EVAL_SKIP)
11866 goto nosideret;
11867
11868 tem = longest_to_int (exp->elts[pc + 1].longconst);
11869
11870 return ada_binop_in_bounds (exp, noside, arg1, arg2, tem);
11871
11872 case TERNOP_IN_RANGE:
11873 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11874 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11875 arg3 = evaluate_subexp (nullptr, exp, pos, noside);
11876
11877 return eval_ternop_in_range (expect_type, exp, noside, arg1, arg2, arg3);
11878
11879 case OP_ATR_FIRST:
11880 case OP_ATR_LAST:
11881 case OP_ATR_LENGTH:
11882 {
11883 struct type *type_arg;
11884
11885 if (exp->elts[*pos].opcode == OP_TYPE)
11886 {
11887 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11888 arg1 = NULL;
11889 type_arg = check_typedef (exp->elts[pc + 2].type);
11890 }
11891 else
11892 {
11893 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11894 type_arg = NULL;
11895 }
11896
11897 if (exp->elts[*pos].opcode != OP_LONG)
11898 error (_("Invalid operand to '%s"), ada_attribute_name (op));
11899 tem = longest_to_int (exp->elts[*pos + 2].longconst);
11900 *pos += 4;
11901
11902 if (noside == EVAL_SKIP)
11903 goto nosideret;
11904
11905 return ada_unop_atr (exp, noside, op, arg1, type_arg, tem);
11906 }
11907
11908 case OP_ATR_TAG:
11909 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11910 if (noside == EVAL_SKIP)
11911 goto nosideret;
11912 return ada_atr_tag (expect_type, exp, noside, op, arg1);
11913
11914 case OP_ATR_MIN:
11915 case OP_ATR_MAX:
11916 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11917 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11918 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11919 if (noside == EVAL_SKIP)
11920 goto nosideret;
11921 return ada_binop_minmax (expect_type, exp, noside, op, arg1, arg2);
11922
11923 case OP_ATR_MODULUS:
11924 {
11925 struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
11926
11927 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11928 if (noside == EVAL_SKIP)
11929 goto nosideret;
11930
11931 if (!ada_is_modular_type (type_arg))
11932 error (_("'modulus must be applied to modular type"));
11933
11934 return value_from_longest (TYPE_TARGET_TYPE (type_arg),
11935 ada_modulus (type_arg));
11936 }
11937
11938
11939 case OP_ATR_POS:
11940 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11941 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11942 if (noside == EVAL_SKIP)
11943 goto nosideret;
11944 return ada_pos_atr (expect_type, exp, noside, op, arg1);
11945
11946 case OP_ATR_SIZE:
11947 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11948 return ada_atr_size (expect_type, exp, noside, op, arg1);
11949
11950 case OP_ATR_VAL:
11951 evaluate_subexp (nullptr, exp, pos, EVAL_SKIP);
11952 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11953 type = exp->elts[pc + 2].type;
11954 if (noside == EVAL_SKIP)
11955 goto nosideret;
11956 return ada_val_atr (noside, type, arg1);
11957
11958 case BINOP_EXP:
11959 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11960 arg2 = evaluate_subexp (nullptr, exp, pos, noside);
11961 if (noside == EVAL_SKIP)
11962 goto nosideret;
11963 return ada_binop_exp (expect_type, exp, noside, op, arg1, arg2);
11964
11965 case UNOP_PLUS:
11966 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11967 if (noside == EVAL_SKIP)
11968 goto nosideret;
11969 else
11970 return arg1;
11971
11972 case UNOP_ABS:
11973 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11974 if (noside == EVAL_SKIP)
11975 goto nosideret;
11976 return ada_abs (expect_type, exp, noside, op, arg1);
11977
11978 case UNOP_IND:
11979 preeval_pos = *pos;
11980 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
11981 if (noside == EVAL_SKIP)
11982 goto nosideret;
11983 type = ada_check_typedef (value_type (arg1));
11984 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11985 {
11986 if (ada_is_array_descriptor_type (type))
11987 /* GDB allows dereferencing GNAT array descriptors. */
11988 {
11989 struct type *arrType = ada_type_of_array (arg1, 0);
11990
11991 if (arrType == NULL)
11992 error (_("Attempt to dereference null array pointer."));
11993 return value_at_lazy (arrType, 0);
11994 }
11995 else if (type->code () == TYPE_CODE_PTR
11996 || type->code () == TYPE_CODE_REF
11997 /* In C you can dereference an array to get the 1st elt. */
11998 || type->code () == TYPE_CODE_ARRAY)
11999 {
12000 /* As mentioned in the OP_VAR_VALUE case, tagged types can
12001 only be determined by inspecting the object's tag.
12002 This means that we need to evaluate completely the
12003 expression in order to get its type. */
12004
12005 if ((type->code () == TYPE_CODE_REF
12006 || type->code () == TYPE_CODE_PTR)
12007 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
12008 {
12009 arg1
12010 = evaluate_subexp (nullptr, exp, &preeval_pos, EVAL_NORMAL);
12011 type = value_type (ada_value_ind (arg1));
12012 }
12013 else
12014 {
12015 type = to_static_fixed_type
12016 (ada_aligned_type
12017 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
12018 }
12019 ada_ensure_varsize_limit (type);
12020 return value_zero (type, lval_memory);
12021 }
12022 else if (type->code () == TYPE_CODE_INT)
12023 {
12024 /* GDB allows dereferencing an int. */
12025 if (expect_type == NULL)
12026 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
12027 lval_memory);
12028 else
12029 {
12030 expect_type =
12031 to_static_fixed_type (ada_aligned_type (expect_type));
12032 return value_zero (expect_type, lval_memory);
12033 }
12034 }
12035 else
12036 error (_("Attempt to take contents of a non-pointer value."));
12037 }
12038 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
12039 type = ada_check_typedef (value_type (arg1));
12040
12041 if (type->code () == TYPE_CODE_INT)
12042 /* GDB allows dereferencing an int. If we were given
12043 the expect_type, then use that as the target type.
12044 Otherwise, assume that the target type is an int. */
12045 {
12046 if (expect_type != NULL)
12047 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
12048 arg1));
12049 else
12050 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
12051 (CORE_ADDR) value_as_address (arg1));
12052 }
12053
12054 if (ada_is_array_descriptor_type (type))
12055 /* GDB allows dereferencing GNAT array descriptors. */
12056 return ada_coerce_to_simple_array (arg1);
12057 else
12058 return ada_value_ind (arg1);
12059
12060 case STRUCTOP_STRUCT:
12061 tem = longest_to_int (exp->elts[pc + 1].longconst);
12062 (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
12063 preeval_pos = *pos;
12064 arg1 = evaluate_subexp (nullptr, exp, pos, noside);
12065 if (noside == EVAL_SKIP)
12066 goto nosideret;
12067 if (noside == EVAL_AVOID_SIDE_EFFECTS)
12068 {
12069 struct type *type1 = value_type (arg1);
12070
12071 if (ada_is_tagged_type (type1, 1))
12072 {
12073 type = ada_lookup_struct_elt_type (type1,
12074 &exp->elts[pc + 2].string,
12075 1, 1);
12076
12077 /* If the field is not found, check if it exists in the
12078 extension of this object's type. This means that we
12079 need to evaluate completely the expression. */
12080
12081 if (type == NULL)
12082 {
12083 arg1
12084 = evaluate_subexp (nullptr, exp, &preeval_pos, EVAL_NORMAL);
12085 arg1 = ada_value_struct_elt (arg1,
12086 &exp->elts[pc + 2].string,
12087 0);
12088 arg1 = unwrap_value (arg1);
12089 type = value_type (ada_to_fixed_value (arg1));
12090 }
12091 }
12092 else
12093 type =
12094 ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
12095 0);
12096
12097 return value_zero (ada_aligned_type (type), lval_memory);
12098 }
12099 else
12100 {
12101 arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
12102 arg1 = unwrap_value (arg1);
12103 return ada_to_fixed_value (arg1);
12104 }
12105
12106 case OP_TYPE:
12107 /* The value is not supposed to be used. This is here to make it
12108 easier to accommodate expressions that contain types. */
12109 (*pos) += 2;
12110 if (noside == EVAL_SKIP)
12111 goto nosideret;
12112 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
12113 return allocate_value (exp->elts[pc + 1].type);
12114 else
12115 error (_("Attempt to use a type name as an expression"));
12116
12117 case OP_AGGREGATE:
12118 case OP_CHOICES:
12119 case OP_OTHERS:
12120 case OP_DISCRETE_RANGE:
12121 case OP_POSITIONAL:
12122 case OP_NAME:
12123 if (noside == EVAL_NORMAL)
12124 switch (op)
12125 {
12126 case OP_NAME:
12127 error (_("Undefined name, ambiguous name, or renaming used in "
12128 "component association: %s."), &exp->elts[pc+2].string);
12129 case OP_AGGREGATE:
12130 error (_("Aggregates only allowed on the right of an assignment"));
12131 default:
12132 internal_error (__FILE__, __LINE__,
12133 _("aggregate apparently mangled"));
12134 }
12135
12136 ada_forward_operator_length (exp, pc, &oplen, &nargs);
12137 *pos += oplen - 1;
12138 for (tem = 0; tem < nargs; tem += 1)
12139 ada_evaluate_subexp (NULL, exp, pos, noside);
12140 goto nosideret;
12141 }
12142
12143 nosideret:
12144 return eval_skip_value (exp);
12145 }
12146 \f
12147
12148 /* Return non-zero iff TYPE represents a System.Address type. */
12149
12150 int
12151 ada_is_system_address_type (struct type *type)
12152 {
12153 return (type->name () && strcmp (type->name (), "system__address") == 0);
12154 }
12155
12156 \f
12157
12158 /* Range types */
12159
12160 /* Scan STR beginning at position K for a discriminant name, and
12161 return the value of that discriminant field of DVAL in *PX. If
12162 PNEW_K is not null, put the position of the character beyond the
12163 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
12164 not alter *PX and *PNEW_K if unsuccessful. */
12165
12166 static int
12167 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
12168 int *pnew_k)
12169 {
12170 static std::string storage;
12171 const char *pstart, *pend, *bound;
12172 struct value *bound_val;
12173
12174 if (dval == NULL || str == NULL || str[k] == '\0')
12175 return 0;
12176
12177 pstart = str + k;
12178 pend = strstr (pstart, "__");
12179 if (pend == NULL)
12180 {
12181 bound = pstart;
12182 k += strlen (bound);
12183 }
12184 else
12185 {
12186 int len = pend - pstart;
12187
12188 /* Strip __ and beyond. */
12189 storage = std::string (pstart, len);
12190 bound = storage.c_str ();
12191 k = pend - str;
12192 }
12193
12194 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
12195 if (bound_val == NULL)
12196 return 0;
12197
12198 *px = value_as_long (bound_val);
12199 if (pnew_k != NULL)
12200 *pnew_k = k;
12201 return 1;
12202 }
12203
12204 /* Value of variable named NAME. Only exact matches are considered.
12205 If no such variable found, then if ERR_MSG is null, returns 0, and
12206 otherwise causes an error with message ERR_MSG. */
12207
12208 static struct value *
12209 get_var_value (const char *name, const char *err_msg)
12210 {
12211 std::string quoted_name = add_angle_brackets (name);
12212
12213 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
12214
12215 std::vector<struct block_symbol> syms
12216 = ada_lookup_symbol_list_worker (lookup_name,
12217 get_selected_block (0),
12218 VAR_DOMAIN, 1);
12219
12220 if (syms.size () != 1)
12221 {
12222 if (err_msg == NULL)
12223 return 0;
12224 else
12225 error (("%s"), err_msg);
12226 }
12227
12228 return value_of_variable (syms[0].symbol, syms[0].block);
12229 }
12230
12231 /* Value of integer variable named NAME in the current environment.
12232 If no such variable is found, returns false. Otherwise, sets VALUE
12233 to the variable's value and returns true. */
12234
12235 bool
12236 get_int_var_value (const char *name, LONGEST &value)
12237 {
12238 struct value *var_val = get_var_value (name, 0);
12239
12240 if (var_val == 0)
12241 return false;
12242
12243 value = value_as_long (var_val);
12244 return true;
12245 }
12246
12247
12248 /* Return a range type whose base type is that of the range type named
12249 NAME in the current environment, and whose bounds are calculated
12250 from NAME according to the GNAT range encoding conventions.
12251 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
12252 corresponding range type from debug information; fall back to using it
12253 if symbol lookup fails. If a new type must be created, allocate it
12254 like ORIG_TYPE was. The bounds information, in general, is encoded
12255 in NAME, the base type given in the named range type. */
12256
12257 static struct type *
12258 to_fixed_range_type (struct type *raw_type, struct value *dval)
12259 {
12260 const char *name;
12261 struct type *base_type;
12262 const char *subtype_info;
12263
12264 gdb_assert (raw_type != NULL);
12265 gdb_assert (raw_type->name () != NULL);
12266
12267 if (raw_type->code () == TYPE_CODE_RANGE)
12268 base_type = TYPE_TARGET_TYPE (raw_type);
12269 else
12270 base_type = raw_type;
12271
12272 name = raw_type->name ();
12273 subtype_info = strstr (name, "___XD");
12274 if (subtype_info == NULL)
12275 {
12276 LONGEST L = ada_discrete_type_low_bound (raw_type);
12277 LONGEST U = ada_discrete_type_high_bound (raw_type);
12278
12279 if (L < INT_MIN || U > INT_MAX)
12280 return raw_type;
12281 else
12282 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
12283 L, U);
12284 }
12285 else
12286 {
12287 int prefix_len = subtype_info - name;
12288 LONGEST L, U;
12289 struct type *type;
12290 const char *bounds_str;
12291 int n;
12292
12293 subtype_info += 5;
12294 bounds_str = strchr (subtype_info, '_');
12295 n = 1;
12296
12297 if (*subtype_info == 'L')
12298 {
12299 if (!ada_scan_number (bounds_str, n, &L, &n)
12300 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
12301 return raw_type;
12302 if (bounds_str[n] == '_')
12303 n += 2;
12304 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
12305 n += 1;
12306 subtype_info += 1;
12307 }
12308 else
12309 {
12310 std::string name_buf = std::string (name, prefix_len) + "___L";
12311 if (!get_int_var_value (name_buf.c_str (), L))
12312 {
12313 lim_warning (_("Unknown lower bound, using 1."));
12314 L = 1;
12315 }
12316 }
12317
12318 if (*subtype_info == 'U')
12319 {
12320 if (!ada_scan_number (bounds_str, n, &U, &n)
12321 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
12322 return raw_type;
12323 }
12324 else
12325 {
12326 std::string name_buf = std::string (name, prefix_len) + "___U";
12327 if (!get_int_var_value (name_buf.c_str (), U))
12328 {
12329 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
12330 U = L;
12331 }
12332 }
12333
12334 type = create_static_range_type (alloc_type_copy (raw_type),
12335 base_type, L, U);
12336 /* create_static_range_type alters the resulting type's length
12337 to match the size of the base_type, which is not what we want.
12338 Set it back to the original range type's length. */
12339 TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
12340 type->set_name (name);
12341 return type;
12342 }
12343 }
12344
12345 /* True iff NAME is the name of a range type. */
12346
12347 int
12348 ada_is_range_type_name (const char *name)
12349 {
12350 return (name != NULL && strstr (name, "___XD"));
12351 }
12352 \f
12353
12354 /* Modular types */
12355
12356 /* True iff TYPE is an Ada modular type. */
12357
12358 int
12359 ada_is_modular_type (struct type *type)
12360 {
12361 struct type *subranged_type = get_base_type (type);
12362
12363 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
12364 && subranged_type->code () == TYPE_CODE_INT
12365 && subranged_type->is_unsigned ());
12366 }
12367
12368 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
12369
12370 ULONGEST
12371 ada_modulus (struct type *type)
12372 {
12373 const dynamic_prop &high = type->bounds ()->high;
12374
12375 if (high.kind () == PROP_CONST)
12376 return (ULONGEST) high.const_val () + 1;
12377
12378 /* If TYPE is unresolved, the high bound might be a location list. Return
12379 0, for lack of a better value to return. */
12380 return 0;
12381 }
12382 \f
12383
12384 /* Ada exception catchpoint support:
12385 ---------------------------------
12386
12387 We support 3 kinds of exception catchpoints:
12388 . catchpoints on Ada exceptions
12389 . catchpoints on unhandled Ada exceptions
12390 . catchpoints on failed assertions
12391
12392 Exceptions raised during failed assertions, or unhandled exceptions
12393 could perfectly be caught with the general catchpoint on Ada exceptions.
12394 However, we can easily differentiate these two special cases, and having
12395 the option to distinguish these two cases from the rest can be useful
12396 to zero-in on certain situations.
12397
12398 Exception catchpoints are a specialized form of breakpoint,
12399 since they rely on inserting breakpoints inside known routines
12400 of the GNAT runtime. The implementation therefore uses a standard
12401 breakpoint structure of the BP_BREAKPOINT type, but with its own set
12402 of breakpoint_ops.
12403
12404 Support in the runtime for exception catchpoints have been changed
12405 a few times already, and these changes affect the implementation
12406 of these catchpoints. In order to be able to support several
12407 variants of the runtime, we use a sniffer that will determine
12408 the runtime variant used by the program being debugged. */
12409
12410 /* Ada's standard exceptions.
12411
12412 The Ada 83 standard also defined Numeric_Error. But there so many
12413 situations where it was unclear from the Ada 83 Reference Manual
12414 (RM) whether Constraint_Error or Numeric_Error should be raised,
12415 that the ARG (Ada Rapporteur Group) eventually issued a Binding
12416 Interpretation saying that anytime the RM says that Numeric_Error
12417 should be raised, the implementation may raise Constraint_Error.
12418 Ada 95 went one step further and pretty much removed Numeric_Error
12419 from the list of standard exceptions (it made it a renaming of
12420 Constraint_Error, to help preserve compatibility when compiling
12421 an Ada83 compiler). As such, we do not include Numeric_Error from
12422 this list of standard exceptions. */
12423
12424 static const char * const standard_exc[] = {
12425 "constraint_error",
12426 "program_error",
12427 "storage_error",
12428 "tasking_error"
12429 };
12430
12431 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
12432
12433 /* A structure that describes how to support exception catchpoints
12434 for a given executable. */
12435
12436 struct exception_support_info
12437 {
12438 /* The name of the symbol to break on in order to insert
12439 a catchpoint on exceptions. */
12440 const char *catch_exception_sym;
12441
12442 /* The name of the symbol to break on in order to insert
12443 a catchpoint on unhandled exceptions. */
12444 const char *catch_exception_unhandled_sym;
12445
12446 /* The name of the symbol to break on in order to insert
12447 a catchpoint on failed assertions. */
12448 const char *catch_assert_sym;
12449
12450 /* The name of the symbol to break on in order to insert
12451 a catchpoint on exception handling. */
12452 const char *catch_handlers_sym;
12453
12454 /* Assuming that the inferior just triggered an unhandled exception
12455 catchpoint, this function is responsible for returning the address
12456 in inferior memory where the name of that exception is stored.
12457 Return zero if the address could not be computed. */
12458 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
12459 };
12460
12461 static CORE_ADDR ada_unhandled_exception_name_addr (void);
12462 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
12463
12464 /* The following exception support info structure describes how to
12465 implement exception catchpoints with the latest version of the
12466 Ada runtime (as of 2019-08-??). */
12467
12468 static const struct exception_support_info default_exception_support_info =
12469 {
12470 "__gnat_debug_raise_exception", /* catch_exception_sym */
12471 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12472 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
12473 "__gnat_begin_handler_v1", /* catch_handlers_sym */
12474 ada_unhandled_exception_name_addr
12475 };
12476
12477 /* The following exception support info structure describes how to
12478 implement exception catchpoints with an earlier version of the
12479 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
12480
12481 static const struct exception_support_info exception_support_info_v0 =
12482 {
12483 "__gnat_debug_raise_exception", /* catch_exception_sym */
12484 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12485 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
12486 "__gnat_begin_handler", /* catch_handlers_sym */
12487 ada_unhandled_exception_name_addr
12488 };
12489
12490 /* The following exception support info structure describes how to
12491 implement exception catchpoints with a slightly older version
12492 of the Ada runtime. */
12493
12494 static const struct exception_support_info exception_support_info_fallback =
12495 {
12496 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
12497 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12498 "system__assertions__raise_assert_failure", /* catch_assert_sym */
12499 "__gnat_begin_handler", /* catch_handlers_sym */
12500 ada_unhandled_exception_name_addr_from_raise
12501 };
12502
12503 /* Return nonzero if we can detect the exception support routines
12504 described in EINFO.
12505
12506 This function errors out if an abnormal situation is detected
12507 (for instance, if we find the exception support routines, but
12508 that support is found to be incomplete). */
12509
12510 static int
12511 ada_has_this_exception_support (const struct exception_support_info *einfo)
12512 {
12513 struct symbol *sym;
12514
12515 /* The symbol we're looking up is provided by a unit in the GNAT runtime
12516 that should be compiled with debugging information. As a result, we
12517 expect to find that symbol in the symtabs. */
12518
12519 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
12520 if (sym == NULL)
12521 {
12522 /* Perhaps we did not find our symbol because the Ada runtime was
12523 compiled without debugging info, or simply stripped of it.
12524 It happens on some GNU/Linux distributions for instance, where
12525 users have to install a separate debug package in order to get
12526 the runtime's debugging info. In that situation, let the user
12527 know why we cannot insert an Ada exception catchpoint.
12528
12529 Note: Just for the purpose of inserting our Ada exception
12530 catchpoint, we could rely purely on the associated minimal symbol.
12531 But we would be operating in degraded mode anyway, since we are
12532 still lacking the debugging info needed later on to extract
12533 the name of the exception being raised (this name is printed in
12534 the catchpoint message, and is also used when trying to catch
12535 a specific exception). We do not handle this case for now. */
12536 struct bound_minimal_symbol msym
12537 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
12538
12539 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
12540 error (_("Your Ada runtime appears to be missing some debugging "
12541 "information.\nCannot insert Ada exception catchpoint "
12542 "in this configuration."));
12543
12544 return 0;
12545 }
12546
12547 /* Make sure that the symbol we found corresponds to a function. */
12548
12549 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12550 {
12551 error (_("Symbol \"%s\" is not a function (class = %d)"),
12552 sym->linkage_name (), SYMBOL_CLASS (sym));
12553 return 0;
12554 }
12555
12556 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
12557 if (sym == NULL)
12558 {
12559 struct bound_minimal_symbol msym
12560 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
12561
12562 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
12563 error (_("Your Ada runtime appears to be missing some debugging "
12564 "information.\nCannot insert Ada exception catchpoint "
12565 "in this configuration."));
12566
12567 return 0;
12568 }
12569
12570 /* Make sure that the symbol we found corresponds to a function. */
12571
12572 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12573 {
12574 error (_("Symbol \"%s\" is not a function (class = %d)"),
12575 sym->linkage_name (), SYMBOL_CLASS (sym));
12576 return 0;
12577 }
12578
12579 return 1;
12580 }
12581
12582 /* Inspect the Ada runtime and determine which exception info structure
12583 should be used to provide support for exception catchpoints.
12584
12585 This function will always set the per-inferior exception_info,
12586 or raise an error. */
12587
12588 static void
12589 ada_exception_support_info_sniffer (void)
12590 {
12591 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12592
12593 /* If the exception info is already known, then no need to recompute it. */
12594 if (data->exception_info != NULL)
12595 return;
12596
12597 /* Check the latest (default) exception support info. */
12598 if (ada_has_this_exception_support (&default_exception_support_info))
12599 {
12600 data->exception_info = &default_exception_support_info;
12601 return;
12602 }
12603
12604 /* Try the v0 exception suport info. */
12605 if (ada_has_this_exception_support (&exception_support_info_v0))
12606 {
12607 data->exception_info = &exception_support_info_v0;
12608 return;
12609 }
12610
12611 /* Try our fallback exception suport info. */
12612 if (ada_has_this_exception_support (&exception_support_info_fallback))
12613 {
12614 data->exception_info = &exception_support_info_fallback;
12615 return;
12616 }
12617
12618 /* Sometimes, it is normal for us to not be able to find the routine
12619 we are looking for. This happens when the program is linked with
12620 the shared version of the GNAT runtime, and the program has not been
12621 started yet. Inform the user of these two possible causes if
12622 applicable. */
12623
12624 if (ada_update_initial_language (language_unknown) != language_ada)
12625 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
12626
12627 /* If the symbol does not exist, then check that the program is
12628 already started, to make sure that shared libraries have been
12629 loaded. If it is not started, this may mean that the symbol is
12630 in a shared library. */
12631
12632 if (inferior_ptid.pid () == 0)
12633 error (_("Unable to insert catchpoint. Try to start the program first."));
12634
12635 /* At this point, we know that we are debugging an Ada program and
12636 that the inferior has been started, but we still are not able to
12637 find the run-time symbols. That can mean that we are in
12638 configurable run time mode, or that a-except as been optimized
12639 out by the linker... In any case, at this point it is not worth
12640 supporting this feature. */
12641
12642 error (_("Cannot insert Ada exception catchpoints in this configuration."));
12643 }
12644
12645 /* True iff FRAME is very likely to be that of a function that is
12646 part of the runtime system. This is all very heuristic, but is
12647 intended to be used as advice as to what frames are uninteresting
12648 to most users. */
12649
12650 static int
12651 is_known_support_routine (struct frame_info *frame)
12652 {
12653 enum language func_lang;
12654 int i;
12655 const char *fullname;
12656
12657 /* If this code does not have any debugging information (no symtab),
12658 This cannot be any user code. */
12659
12660 symtab_and_line sal = find_frame_sal (frame);
12661 if (sal.symtab == NULL)
12662 return 1;
12663
12664 /* If there is a symtab, but the associated source file cannot be
12665 located, then assume this is not user code: Selecting a frame
12666 for which we cannot display the code would not be very helpful
12667 for the user. This should also take care of case such as VxWorks
12668 where the kernel has some debugging info provided for a few units. */
12669
12670 fullname = symtab_to_fullname (sal.symtab);
12671 if (access (fullname, R_OK) != 0)
12672 return 1;
12673
12674 /* Check the unit filename against the Ada runtime file naming.
12675 We also check the name of the objfile against the name of some
12676 known system libraries that sometimes come with debugging info
12677 too. */
12678
12679 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
12680 {
12681 re_comp (known_runtime_file_name_patterns[i]);
12682 if (re_exec (lbasename (sal.symtab->filename)))
12683 return 1;
12684 if (SYMTAB_OBJFILE (sal.symtab) != NULL
12685 && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
12686 return 1;
12687 }
12688
12689 /* Check whether the function is a GNAT-generated entity. */
12690
12691 gdb::unique_xmalloc_ptr<char> func_name
12692 = find_frame_funname (frame, &func_lang, NULL);
12693 if (func_name == NULL)
12694 return 1;
12695
12696 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
12697 {
12698 re_comp (known_auxiliary_function_name_patterns[i]);
12699 if (re_exec (func_name.get ()))
12700 return 1;
12701 }
12702
12703 return 0;
12704 }
12705
12706 /* Find the first frame that contains debugging information and that is not
12707 part of the Ada run-time, starting from FI and moving upward. */
12708
12709 void
12710 ada_find_printable_frame (struct frame_info *fi)
12711 {
12712 for (; fi != NULL; fi = get_prev_frame (fi))
12713 {
12714 if (!is_known_support_routine (fi))
12715 {
12716 select_frame (fi);
12717 break;
12718 }
12719 }
12720
12721 }
12722
12723 /* Assuming that the inferior just triggered an unhandled exception
12724 catchpoint, return the address in inferior memory where the name
12725 of the exception is stored.
12726
12727 Return zero if the address could not be computed. */
12728
12729 static CORE_ADDR
12730 ada_unhandled_exception_name_addr (void)
12731 {
12732 return parse_and_eval_address ("e.full_name");
12733 }
12734
12735 /* Same as ada_unhandled_exception_name_addr, except that this function
12736 should be used when the inferior uses an older version of the runtime,
12737 where the exception name needs to be extracted from a specific frame
12738 several frames up in the callstack. */
12739
12740 static CORE_ADDR
12741 ada_unhandled_exception_name_addr_from_raise (void)
12742 {
12743 int frame_level;
12744 struct frame_info *fi;
12745 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12746
12747 /* To determine the name of this exception, we need to select
12748 the frame corresponding to RAISE_SYM_NAME. This frame is
12749 at least 3 levels up, so we simply skip the first 3 frames
12750 without checking the name of their associated function. */
12751 fi = get_current_frame ();
12752 for (frame_level = 0; frame_level < 3; frame_level += 1)
12753 if (fi != NULL)
12754 fi = get_prev_frame (fi);
12755
12756 while (fi != NULL)
12757 {
12758 enum language func_lang;
12759
12760 gdb::unique_xmalloc_ptr<char> func_name
12761 = find_frame_funname (fi, &func_lang, NULL);
12762 if (func_name != NULL)
12763 {
12764 if (strcmp (func_name.get (),
12765 data->exception_info->catch_exception_sym) == 0)
12766 break; /* We found the frame we were looking for... */
12767 }
12768 fi = get_prev_frame (fi);
12769 }
12770
12771 if (fi == NULL)
12772 return 0;
12773
12774 select_frame (fi);
12775 return parse_and_eval_address ("id.full_name");
12776 }
12777
12778 /* Assuming the inferior just triggered an Ada exception catchpoint
12779 (of any type), return the address in inferior memory where the name
12780 of the exception is stored, if applicable.
12781
12782 Assumes the selected frame is the current frame.
12783
12784 Return zero if the address could not be computed, or if not relevant. */
12785
12786 static CORE_ADDR
12787 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
12788 struct breakpoint *b)
12789 {
12790 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12791
12792 switch (ex)
12793 {
12794 case ada_catch_exception:
12795 return (parse_and_eval_address ("e.full_name"));
12796 break;
12797
12798 case ada_catch_exception_unhandled:
12799 return data->exception_info->unhandled_exception_name_addr ();
12800 break;
12801
12802 case ada_catch_handlers:
12803 return 0; /* The runtimes does not provide access to the exception
12804 name. */
12805 break;
12806
12807 case ada_catch_assert:
12808 return 0; /* Exception name is not relevant in this case. */
12809 break;
12810
12811 default:
12812 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12813 break;
12814 }
12815
12816 return 0; /* Should never be reached. */
12817 }
12818
12819 /* Assuming the inferior is stopped at an exception catchpoint,
12820 return the message which was associated to the exception, if
12821 available. Return NULL if the message could not be retrieved.
12822
12823 Note: The exception message can be associated to an exception
12824 either through the use of the Raise_Exception function, or
12825 more simply (Ada 2005 and later), via:
12826
12827 raise Exception_Name with "exception message";
12828
12829 */
12830
12831 static gdb::unique_xmalloc_ptr<char>
12832 ada_exception_message_1 (void)
12833 {
12834 struct value *e_msg_val;
12835 int e_msg_len;
12836
12837 /* For runtimes that support this feature, the exception message
12838 is passed as an unbounded string argument called "message". */
12839 e_msg_val = parse_and_eval ("message");
12840 if (e_msg_val == NULL)
12841 return NULL; /* Exception message not supported. */
12842
12843 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12844 gdb_assert (e_msg_val != NULL);
12845 e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
12846
12847 /* If the message string is empty, then treat it as if there was
12848 no exception message. */
12849 if (e_msg_len <= 0)
12850 return NULL;
12851
12852 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12853 read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
12854 e_msg_len);
12855 e_msg.get ()[e_msg_len] = '\0';
12856
12857 return e_msg;
12858 }
12859
12860 /* Same as ada_exception_message_1, except that all exceptions are
12861 contained here (returning NULL instead). */
12862
12863 static gdb::unique_xmalloc_ptr<char>
12864 ada_exception_message (void)
12865 {
12866 gdb::unique_xmalloc_ptr<char> e_msg;
12867
12868 try
12869 {
12870 e_msg = ada_exception_message_1 ();
12871 }
12872 catch (const gdb_exception_error &e)
12873 {
12874 e_msg.reset (nullptr);
12875 }
12876
12877 return e_msg;
12878 }
12879
12880 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12881 any error that ada_exception_name_addr_1 might cause to be thrown.
12882 When an error is intercepted, a warning with the error message is printed,
12883 and zero is returned. */
12884
12885 static CORE_ADDR
12886 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
12887 struct breakpoint *b)
12888 {
12889 CORE_ADDR result = 0;
12890
12891 try
12892 {
12893 result = ada_exception_name_addr_1 (ex, b);
12894 }
12895
12896 catch (const gdb_exception_error &e)
12897 {
12898 warning (_("failed to get exception name: %s"), e.what ());
12899 return 0;
12900 }
12901
12902 return result;
12903 }
12904
12905 static std::string ada_exception_catchpoint_cond_string
12906 (const char *excep_string,
12907 enum ada_exception_catchpoint_kind ex);
12908
12909 /* Ada catchpoints.
12910
12911 In the case of catchpoints on Ada exceptions, the catchpoint will
12912 stop the target on every exception the program throws. When a user
12913 specifies the name of a specific exception, we translate this
12914 request into a condition expression (in text form), and then parse
12915 it into an expression stored in each of the catchpoint's locations.
12916 We then use this condition to check whether the exception that was
12917 raised is the one the user is interested in. If not, then the
12918 target is resumed again. We store the name of the requested
12919 exception, in order to be able to re-set the condition expression
12920 when symbols change. */
12921
12922 /* An instance of this type is used to represent an Ada catchpoint
12923 breakpoint location. */
12924
12925 class ada_catchpoint_location : public bp_location
12926 {
12927 public:
12928 ada_catchpoint_location (breakpoint *owner)
12929 : bp_location (owner, bp_loc_software_breakpoint)
12930 {}
12931
12932 /* The condition that checks whether the exception that was raised
12933 is the specific exception the user specified on catchpoint
12934 creation. */
12935 expression_up excep_cond_expr;
12936 };
12937
12938 /* An instance of this type is used to represent an Ada catchpoint. */
12939
12940 struct ada_catchpoint : public breakpoint
12941 {
12942 explicit ada_catchpoint (enum ada_exception_catchpoint_kind kind)
12943 : m_kind (kind)
12944 {
12945 }
12946
12947 /* The name of the specific exception the user specified. */
12948 std::string excep_string;
12949
12950 /* What kind of catchpoint this is. */
12951 enum ada_exception_catchpoint_kind m_kind;
12952 };
12953
12954 /* Parse the exception condition string in the context of each of the
12955 catchpoint's locations, and store them for later evaluation. */
12956
12957 static void
12958 create_excep_cond_exprs (struct ada_catchpoint *c,
12959 enum ada_exception_catchpoint_kind ex)
12960 {
12961 struct bp_location *bl;
12962
12963 /* Nothing to do if there's no specific exception to catch. */
12964 if (c->excep_string.empty ())
12965 return;
12966
12967 /* Same if there are no locations... */
12968 if (c->loc == NULL)
12969 return;
12970
12971 /* Compute the condition expression in text form, from the specific
12972 expection we want to catch. */
12973 std::string cond_string
12974 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12975
12976 /* Iterate over all the catchpoint's locations, and parse an
12977 expression for each. */
12978 for (bl = c->loc; bl != NULL; bl = bl->next)
12979 {
12980 struct ada_catchpoint_location *ada_loc
12981 = (struct ada_catchpoint_location *) bl;
12982 expression_up exp;
12983
12984 if (!bl->shlib_disabled)
12985 {
12986 const char *s;
12987
12988 s = cond_string.c_str ();
12989 try
12990 {
12991 exp = parse_exp_1 (&s, bl->address,
12992 block_for_pc (bl->address),
12993 0);
12994 }
12995 catch (const gdb_exception_error &e)
12996 {
12997 warning (_("failed to reevaluate internal exception condition "
12998 "for catchpoint %d: %s"),
12999 c->number, e.what ());
13000 }
13001 }
13002
13003 ada_loc->excep_cond_expr = std::move (exp);
13004 }
13005 }
13006
13007 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
13008 structure for all exception catchpoint kinds. */
13009
13010 static struct bp_location *
13011 allocate_location_exception (struct breakpoint *self)
13012 {
13013 return new ada_catchpoint_location (self);
13014 }
13015
13016 /* Implement the RE_SET method in the breakpoint_ops structure for all
13017 exception catchpoint kinds. */
13018
13019 static void
13020 re_set_exception (struct breakpoint *b)
13021 {
13022 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13023
13024 /* Call the base class's method. This updates the catchpoint's
13025 locations. */
13026 bkpt_breakpoint_ops.re_set (b);
13027
13028 /* Reparse the exception conditional expressions. One for each
13029 location. */
13030 create_excep_cond_exprs (c, c->m_kind);
13031 }
13032
13033 /* Returns true if we should stop for this breakpoint hit. If the
13034 user specified a specific exception, we only want to cause a stop
13035 if the program thrown that exception. */
13036
13037 static int
13038 should_stop_exception (const struct bp_location *bl)
13039 {
13040 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
13041 const struct ada_catchpoint_location *ada_loc
13042 = (const struct ada_catchpoint_location *) bl;
13043 int stop;
13044
13045 struct internalvar *var = lookup_internalvar ("_ada_exception");
13046 if (c->m_kind == ada_catch_assert)
13047 clear_internalvar (var);
13048 else
13049 {
13050 try
13051 {
13052 const char *expr;
13053
13054 if (c->m_kind == ada_catch_handlers)
13055 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
13056 ".all.occurrence.id");
13057 else
13058 expr = "e";
13059
13060 struct value *exc = parse_and_eval (expr);
13061 set_internalvar (var, exc);
13062 }
13063 catch (const gdb_exception_error &ex)
13064 {
13065 clear_internalvar (var);
13066 }
13067 }
13068
13069 /* With no specific exception, should always stop. */
13070 if (c->excep_string.empty ())
13071 return 1;
13072
13073 if (ada_loc->excep_cond_expr == NULL)
13074 {
13075 /* We will have a NULL expression if back when we were creating
13076 the expressions, this location's had failed to parse. */
13077 return 1;
13078 }
13079
13080 stop = 1;
13081 try
13082 {
13083 struct value *mark;
13084
13085 mark = value_mark ();
13086 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
13087 value_free_to_mark (mark);
13088 }
13089 catch (const gdb_exception &ex)
13090 {
13091 exception_fprintf (gdb_stderr, ex,
13092 _("Error in testing exception condition:\n"));
13093 }
13094
13095 return stop;
13096 }
13097
13098 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
13099 for all exception catchpoint kinds. */
13100
13101 static void
13102 check_status_exception (bpstat bs)
13103 {
13104 bs->stop = should_stop_exception (bs->bp_location_at.get ());
13105 }
13106
13107 /* Implement the PRINT_IT method in the breakpoint_ops structure
13108 for all exception catchpoint kinds. */
13109
13110 static enum print_stop_action
13111 print_it_exception (bpstat bs)
13112 {
13113 struct ui_out *uiout = current_uiout;
13114 struct breakpoint *b = bs->breakpoint_at;
13115
13116 annotate_catchpoint (b->number);
13117
13118 if (uiout->is_mi_like_p ())
13119 {
13120 uiout->field_string ("reason",
13121 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13122 uiout->field_string ("disp", bpdisp_text (b->disposition));
13123 }
13124
13125 uiout->text (b->disposition == disp_del
13126 ? "\nTemporary catchpoint " : "\nCatchpoint ");
13127 uiout->field_signed ("bkptno", b->number);
13128 uiout->text (", ");
13129
13130 /* ada_exception_name_addr relies on the selected frame being the
13131 current frame. Need to do this here because this function may be
13132 called more than once when printing a stop, and below, we'll
13133 select the first frame past the Ada run-time (see
13134 ada_find_printable_frame). */
13135 select_frame (get_current_frame ());
13136
13137 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13138 switch (c->m_kind)
13139 {
13140 case ada_catch_exception:
13141 case ada_catch_exception_unhandled:
13142 case ada_catch_handlers:
13143 {
13144 const CORE_ADDR addr = ada_exception_name_addr (c->m_kind, b);
13145 char exception_name[256];
13146
13147 if (addr != 0)
13148 {
13149 read_memory (addr, (gdb_byte *) exception_name,
13150 sizeof (exception_name) - 1);
13151 exception_name [sizeof (exception_name) - 1] = '\0';
13152 }
13153 else
13154 {
13155 /* For some reason, we were unable to read the exception
13156 name. This could happen if the Runtime was compiled
13157 without debugging info, for instance. In that case,
13158 just replace the exception name by the generic string
13159 "exception" - it will read as "an exception" in the
13160 notification we are about to print. */
13161 memcpy (exception_name, "exception", sizeof ("exception"));
13162 }
13163 /* In the case of unhandled exception breakpoints, we print
13164 the exception name as "unhandled EXCEPTION_NAME", to make
13165 it clearer to the user which kind of catchpoint just got
13166 hit. We used ui_out_text to make sure that this extra
13167 info does not pollute the exception name in the MI case. */
13168 if (c->m_kind == ada_catch_exception_unhandled)
13169 uiout->text ("unhandled ");
13170 uiout->field_string ("exception-name", exception_name);
13171 }
13172 break;
13173 case ada_catch_assert:
13174 /* In this case, the name of the exception is not really
13175 important. Just print "failed assertion" to make it clearer
13176 that his program just hit an assertion-failure catchpoint.
13177 We used ui_out_text because this info does not belong in
13178 the MI output. */
13179 uiout->text ("failed assertion");
13180 break;
13181 }
13182
13183 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
13184 if (exception_message != NULL)
13185 {
13186 uiout->text (" (");
13187 uiout->field_string ("exception-message", exception_message.get ());
13188 uiout->text (")");
13189 }
13190
13191 uiout->text (" at ");
13192 ada_find_printable_frame (get_current_frame ());
13193
13194 return PRINT_SRC_AND_LOC;
13195 }
13196
13197 /* Implement the PRINT_ONE method in the breakpoint_ops structure
13198 for all exception catchpoint kinds. */
13199
13200 static void
13201 print_one_exception (struct breakpoint *b, struct bp_location **last_loc)
13202 {
13203 struct ui_out *uiout = current_uiout;
13204 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13205 struct value_print_options opts;
13206
13207 get_user_print_options (&opts);
13208
13209 if (opts.addressprint)
13210 uiout->field_skip ("addr");
13211
13212 annotate_field (5);
13213 switch (c->m_kind)
13214 {
13215 case ada_catch_exception:
13216 if (!c->excep_string.empty ())
13217 {
13218 std::string msg = string_printf (_("`%s' Ada exception"),
13219 c->excep_string.c_str ());
13220
13221 uiout->field_string ("what", msg);
13222 }
13223 else
13224 uiout->field_string ("what", "all Ada exceptions");
13225
13226 break;
13227
13228 case ada_catch_exception_unhandled:
13229 uiout->field_string ("what", "unhandled Ada exceptions");
13230 break;
13231
13232 case ada_catch_handlers:
13233 if (!c->excep_string.empty ())
13234 {
13235 uiout->field_fmt ("what",
13236 _("`%s' Ada exception handlers"),
13237 c->excep_string.c_str ());
13238 }
13239 else
13240 uiout->field_string ("what", "all Ada exceptions handlers");
13241 break;
13242
13243 case ada_catch_assert:
13244 uiout->field_string ("what", "failed Ada assertions");
13245 break;
13246
13247 default:
13248 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
13249 break;
13250 }
13251 }
13252
13253 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
13254 for all exception catchpoint kinds. */
13255
13256 static void
13257 print_mention_exception (struct breakpoint *b)
13258 {
13259 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13260 struct ui_out *uiout = current_uiout;
13261
13262 uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
13263 : _("Catchpoint "));
13264 uiout->field_signed ("bkptno", b->number);
13265 uiout->text (": ");
13266
13267 switch (c->m_kind)
13268 {
13269 case ada_catch_exception:
13270 if (!c->excep_string.empty ())
13271 {
13272 std::string info = string_printf (_("`%s' Ada exception"),
13273 c->excep_string.c_str ());
13274 uiout->text (info.c_str ());
13275 }
13276 else
13277 uiout->text (_("all Ada exceptions"));
13278 break;
13279
13280 case ada_catch_exception_unhandled:
13281 uiout->text (_("unhandled Ada exceptions"));
13282 break;
13283
13284 case ada_catch_handlers:
13285 if (!c->excep_string.empty ())
13286 {
13287 std::string info
13288 = string_printf (_("`%s' Ada exception handlers"),
13289 c->excep_string.c_str ());
13290 uiout->text (info.c_str ());
13291 }
13292 else
13293 uiout->text (_("all Ada exceptions handlers"));
13294 break;
13295
13296 case ada_catch_assert:
13297 uiout->text (_("failed Ada assertions"));
13298 break;
13299
13300 default:
13301 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
13302 break;
13303 }
13304 }
13305
13306 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
13307 for all exception catchpoint kinds. */
13308
13309 static void
13310 print_recreate_exception (struct breakpoint *b, struct ui_file *fp)
13311 {
13312 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
13313
13314 switch (c->m_kind)
13315 {
13316 case ada_catch_exception:
13317 fprintf_filtered (fp, "catch exception");
13318 if (!c->excep_string.empty ())
13319 fprintf_filtered (fp, " %s", c->excep_string.c_str ());
13320 break;
13321
13322 case ada_catch_exception_unhandled:
13323 fprintf_filtered (fp, "catch exception unhandled");
13324 break;
13325
13326 case ada_catch_handlers:
13327 fprintf_filtered (fp, "catch handlers");
13328 break;
13329
13330 case ada_catch_assert:
13331 fprintf_filtered (fp, "catch assert");
13332 break;
13333
13334 default:
13335 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
13336 }
13337 print_recreate_thread (b, fp);
13338 }
13339
13340 /* Virtual tables for various breakpoint types. */
13341 static struct breakpoint_ops catch_exception_breakpoint_ops;
13342 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
13343 static struct breakpoint_ops catch_assert_breakpoint_ops;
13344 static struct breakpoint_ops catch_handlers_breakpoint_ops;
13345
13346 /* See ada-lang.h. */
13347
13348 bool
13349 is_ada_exception_catchpoint (breakpoint *bp)
13350 {
13351 return (bp->ops == &catch_exception_breakpoint_ops
13352 || bp->ops == &catch_exception_unhandled_breakpoint_ops
13353 || bp->ops == &catch_assert_breakpoint_ops
13354 || bp->ops == &catch_handlers_breakpoint_ops);
13355 }
13356
13357 /* Split the arguments specified in a "catch exception" command.
13358 Set EX to the appropriate catchpoint type.
13359 Set EXCEP_STRING to the name of the specific exception if
13360 specified by the user.
13361 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
13362 "catch handlers" command. False otherwise.
13363 If a condition is found at the end of the arguments, the condition
13364 expression is stored in COND_STRING (memory must be deallocated
13365 after use). Otherwise COND_STRING is set to NULL. */
13366
13367 static void
13368 catch_ada_exception_command_split (const char *args,
13369 bool is_catch_handlers_cmd,
13370 enum ada_exception_catchpoint_kind *ex,
13371 std::string *excep_string,
13372 std::string *cond_string)
13373 {
13374 std::string exception_name;
13375
13376 exception_name = extract_arg (&args);
13377 if (exception_name == "if")
13378 {
13379 /* This is not an exception name; this is the start of a condition
13380 expression for a catchpoint on all exceptions. So, "un-get"
13381 this token, and set exception_name to NULL. */
13382 exception_name.clear ();
13383 args -= 2;
13384 }
13385
13386 /* Check to see if we have a condition. */
13387
13388 args = skip_spaces (args);
13389 if (startswith (args, "if")
13390 && (isspace (args[2]) || args[2] == '\0'))
13391 {
13392 args += 2;
13393 args = skip_spaces (args);
13394
13395 if (args[0] == '\0')
13396 error (_("Condition missing after `if' keyword"));
13397 *cond_string = args;
13398
13399 args += strlen (args);
13400 }
13401
13402 /* Check that we do not have any more arguments. Anything else
13403 is unexpected. */
13404
13405 if (args[0] != '\0')
13406 error (_("Junk at end of expression"));
13407
13408 if (is_catch_handlers_cmd)
13409 {
13410 /* Catch handling of exceptions. */
13411 *ex = ada_catch_handlers;
13412 *excep_string = exception_name;
13413 }
13414 else if (exception_name.empty ())
13415 {
13416 /* Catch all exceptions. */
13417 *ex = ada_catch_exception;
13418 excep_string->clear ();
13419 }
13420 else if (exception_name == "unhandled")
13421 {
13422 /* Catch unhandled exceptions. */
13423 *ex = ada_catch_exception_unhandled;
13424 excep_string->clear ();
13425 }
13426 else
13427 {
13428 /* Catch a specific exception. */
13429 *ex = ada_catch_exception;
13430 *excep_string = exception_name;
13431 }
13432 }
13433
13434 /* Return the name of the symbol on which we should break in order to
13435 implement a catchpoint of the EX kind. */
13436
13437 static const char *
13438 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
13439 {
13440 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
13441
13442 gdb_assert (data->exception_info != NULL);
13443
13444 switch (ex)
13445 {
13446 case ada_catch_exception:
13447 return (data->exception_info->catch_exception_sym);
13448 break;
13449 case ada_catch_exception_unhandled:
13450 return (data->exception_info->catch_exception_unhandled_sym);
13451 break;
13452 case ada_catch_assert:
13453 return (data->exception_info->catch_assert_sym);
13454 break;
13455 case ada_catch_handlers:
13456 return (data->exception_info->catch_handlers_sym);
13457 break;
13458 default:
13459 internal_error (__FILE__, __LINE__,
13460 _("unexpected catchpoint kind (%d)"), ex);
13461 }
13462 }
13463
13464 /* Return the breakpoint ops "virtual table" used for catchpoints
13465 of the EX kind. */
13466
13467 static const struct breakpoint_ops *
13468 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
13469 {
13470 switch (ex)
13471 {
13472 case ada_catch_exception:
13473 return (&catch_exception_breakpoint_ops);
13474 break;
13475 case ada_catch_exception_unhandled:
13476 return (&catch_exception_unhandled_breakpoint_ops);
13477 break;
13478 case ada_catch_assert:
13479 return (&catch_assert_breakpoint_ops);
13480 break;
13481 case ada_catch_handlers:
13482 return (&catch_handlers_breakpoint_ops);
13483 break;
13484 default:
13485 internal_error (__FILE__, __LINE__,
13486 _("unexpected catchpoint kind (%d)"), ex);
13487 }
13488 }
13489
13490 /* Return the condition that will be used to match the current exception
13491 being raised with the exception that the user wants to catch. This
13492 assumes that this condition is used when the inferior just triggered
13493 an exception catchpoint.
13494 EX: the type of catchpoints used for catching Ada exceptions. */
13495
13496 static std::string
13497 ada_exception_catchpoint_cond_string (const char *excep_string,
13498 enum ada_exception_catchpoint_kind ex)
13499 {
13500 int i;
13501 bool is_standard_exc = false;
13502 std::string result;
13503
13504 if (ex == ada_catch_handlers)
13505 {
13506 /* For exception handlers catchpoints, the condition string does
13507 not use the same parameter as for the other exceptions. */
13508 result = ("long_integer (GNAT_GCC_exception_Access"
13509 "(gcc_exception).all.occurrence.id)");
13510 }
13511 else
13512 result = "long_integer (e)";
13513
13514 /* The standard exceptions are a special case. They are defined in
13515 runtime units that have been compiled without debugging info; if
13516 EXCEP_STRING is the not-fully-qualified name of a standard
13517 exception (e.g. "constraint_error") then, during the evaluation
13518 of the condition expression, the symbol lookup on this name would
13519 *not* return this standard exception. The catchpoint condition
13520 may then be set only on user-defined exceptions which have the
13521 same not-fully-qualified name (e.g. my_package.constraint_error).
13522
13523 To avoid this unexcepted behavior, these standard exceptions are
13524 systematically prefixed by "standard". This means that "catch
13525 exception constraint_error" is rewritten into "catch exception
13526 standard.constraint_error".
13527
13528 If an exception named constraint_error is defined in another package of
13529 the inferior program, then the only way to specify this exception as a
13530 breakpoint condition is to use its fully-qualified named:
13531 e.g. my_package.constraint_error. */
13532
13533 for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
13534 {
13535 if (strcmp (standard_exc [i], excep_string) == 0)
13536 {
13537 is_standard_exc = true;
13538 break;
13539 }
13540 }
13541
13542 result += " = ";
13543
13544 if (is_standard_exc)
13545 string_appendf (result, "long_integer (&standard.%s)", excep_string);
13546 else
13547 string_appendf (result, "long_integer (&%s)", excep_string);
13548
13549 return result;
13550 }
13551
13552 /* Return the symtab_and_line that should be used to insert an exception
13553 catchpoint of the TYPE kind.
13554
13555 ADDR_STRING returns the name of the function where the real
13556 breakpoint that implements the catchpoints is set, depending on the
13557 type of catchpoint we need to create. */
13558
13559 static struct symtab_and_line
13560 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
13561 std::string *addr_string, const struct breakpoint_ops **ops)
13562 {
13563 const char *sym_name;
13564 struct symbol *sym;
13565
13566 /* First, find out which exception support info to use. */
13567 ada_exception_support_info_sniffer ();
13568
13569 /* Then lookup the function on which we will break in order to catch
13570 the Ada exceptions requested by the user. */
13571 sym_name = ada_exception_sym_name (ex);
13572 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
13573
13574 if (sym == NULL)
13575 error (_("Catchpoint symbol not found: %s"), sym_name);
13576
13577 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
13578 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
13579
13580 /* Set ADDR_STRING. */
13581 *addr_string = sym_name;
13582
13583 /* Set OPS. */
13584 *ops = ada_exception_breakpoint_ops (ex);
13585
13586 return find_function_start_sal (sym, 1);
13587 }
13588
13589 /* Create an Ada exception catchpoint.
13590
13591 EX_KIND is the kind of exception catchpoint to be created.
13592
13593 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
13594 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
13595 of the exception to which this catchpoint applies.
13596
13597 COND_STRING, if not empty, is the catchpoint condition.
13598
13599 TEMPFLAG, if nonzero, means that the underlying breakpoint
13600 should be temporary.
13601
13602 FROM_TTY is the usual argument passed to all commands implementations. */
13603
13604 void
13605 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
13606 enum ada_exception_catchpoint_kind ex_kind,
13607 const std::string &excep_string,
13608 const std::string &cond_string,
13609 int tempflag,
13610 int disabled,
13611 int from_tty)
13612 {
13613 std::string addr_string;
13614 const struct breakpoint_ops *ops = NULL;
13615 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
13616
13617 std::unique_ptr<ada_catchpoint> c (new ada_catchpoint (ex_kind));
13618 init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
13619 ops, tempflag, disabled, from_tty);
13620 c->excep_string = excep_string;
13621 create_excep_cond_exprs (c.get (), ex_kind);
13622 if (!cond_string.empty ())
13623 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
13624 install_breakpoint (0, std::move (c), 1);
13625 }
13626
13627 /* Implement the "catch exception" command. */
13628
13629 static void
13630 catch_ada_exception_command (const char *arg_entry, int from_tty,
13631 struct cmd_list_element *command)
13632 {
13633 const char *arg = arg_entry;
13634 struct gdbarch *gdbarch = get_current_arch ();
13635 int tempflag;
13636 enum ada_exception_catchpoint_kind ex_kind;
13637 std::string excep_string;
13638 std::string cond_string;
13639
13640 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13641
13642 if (!arg)
13643 arg = "";
13644 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
13645 &cond_string);
13646 create_ada_exception_catchpoint (gdbarch, ex_kind,
13647 excep_string, cond_string,
13648 tempflag, 1 /* enabled */,
13649 from_tty);
13650 }
13651
13652 /* Implement the "catch handlers" command. */
13653
13654 static void
13655 catch_ada_handlers_command (const char *arg_entry, int from_tty,
13656 struct cmd_list_element *command)
13657 {
13658 const char *arg = arg_entry;
13659 struct gdbarch *gdbarch = get_current_arch ();
13660 int tempflag;
13661 enum ada_exception_catchpoint_kind ex_kind;
13662 std::string excep_string;
13663 std::string cond_string;
13664
13665 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13666
13667 if (!arg)
13668 arg = "";
13669 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
13670 &cond_string);
13671 create_ada_exception_catchpoint (gdbarch, ex_kind,
13672 excep_string, cond_string,
13673 tempflag, 1 /* enabled */,
13674 from_tty);
13675 }
13676
13677 /* Completion function for the Ada "catch" commands. */
13678
13679 static void
13680 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
13681 const char *text, const char *word)
13682 {
13683 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
13684
13685 for (const ada_exc_info &info : exceptions)
13686 {
13687 if (startswith (info.name, word))
13688 tracker.add_completion (make_unique_xstrdup (info.name));
13689 }
13690 }
13691
13692 /* Split the arguments specified in a "catch assert" command.
13693
13694 ARGS contains the command's arguments (or the empty string if
13695 no arguments were passed).
13696
13697 If ARGS contains a condition, set COND_STRING to that condition
13698 (the memory needs to be deallocated after use). */
13699
13700 static void
13701 catch_ada_assert_command_split (const char *args, std::string &cond_string)
13702 {
13703 args = skip_spaces (args);
13704
13705 /* Check whether a condition was provided. */
13706 if (startswith (args, "if")
13707 && (isspace (args[2]) || args[2] == '\0'))
13708 {
13709 args += 2;
13710 args = skip_spaces (args);
13711 if (args[0] == '\0')
13712 error (_("condition missing after `if' keyword"));
13713 cond_string.assign (args);
13714 }
13715
13716 /* Otherwise, there should be no other argument at the end of
13717 the command. */
13718 else if (args[0] != '\0')
13719 error (_("Junk at end of arguments."));
13720 }
13721
13722 /* Implement the "catch assert" command. */
13723
13724 static void
13725 catch_assert_command (const char *arg_entry, int from_tty,
13726 struct cmd_list_element *command)
13727 {
13728 const char *arg = arg_entry;
13729 struct gdbarch *gdbarch = get_current_arch ();
13730 int tempflag;
13731 std::string cond_string;
13732
13733 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13734
13735 if (!arg)
13736 arg = "";
13737 catch_ada_assert_command_split (arg, cond_string);
13738 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
13739 "", cond_string,
13740 tempflag, 1 /* enabled */,
13741 from_tty);
13742 }
13743
13744 /* Return non-zero if the symbol SYM is an Ada exception object. */
13745
13746 static int
13747 ada_is_exception_sym (struct symbol *sym)
13748 {
13749 const char *type_name = SYMBOL_TYPE (sym)->name ();
13750
13751 return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
13752 && SYMBOL_CLASS (sym) != LOC_BLOCK
13753 && SYMBOL_CLASS (sym) != LOC_CONST
13754 && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
13755 && type_name != NULL && strcmp (type_name, "exception") == 0);
13756 }
13757
13758 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
13759 Ada exception object. This matches all exceptions except the ones
13760 defined by the Ada language. */
13761
13762 static int
13763 ada_is_non_standard_exception_sym (struct symbol *sym)
13764 {
13765 int i;
13766
13767 if (!ada_is_exception_sym (sym))
13768 return 0;
13769
13770 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13771 if (strcmp (sym->linkage_name (), standard_exc[i]) == 0)
13772 return 0; /* A standard exception. */
13773
13774 /* Numeric_Error is also a standard exception, so exclude it.
13775 See the STANDARD_EXC description for more details as to why
13776 this exception is not listed in that array. */
13777 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
13778 return 0;
13779
13780 return 1;
13781 }
13782
13783 /* A helper function for std::sort, comparing two struct ada_exc_info
13784 objects.
13785
13786 The comparison is determined first by exception name, and then
13787 by exception address. */
13788
13789 bool
13790 ada_exc_info::operator< (const ada_exc_info &other) const
13791 {
13792 int result;
13793
13794 result = strcmp (name, other.name);
13795 if (result < 0)
13796 return true;
13797 if (result == 0 && addr < other.addr)
13798 return true;
13799 return false;
13800 }
13801
13802 bool
13803 ada_exc_info::operator== (const ada_exc_info &other) const
13804 {
13805 return addr == other.addr && strcmp (name, other.name) == 0;
13806 }
13807
13808 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13809 routine, but keeping the first SKIP elements untouched.
13810
13811 All duplicates are also removed. */
13812
13813 static void
13814 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13815 int skip)
13816 {
13817 std::sort (exceptions->begin () + skip, exceptions->end ());
13818 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13819 exceptions->end ());
13820 }
13821
13822 /* Add all exceptions defined by the Ada standard whose name match
13823 a regular expression.
13824
13825 If PREG is not NULL, then this regexp_t object is used to
13826 perform the symbol name matching. Otherwise, no name-based
13827 filtering is performed.
13828
13829 EXCEPTIONS is a vector of exceptions to which matching exceptions
13830 gets pushed. */
13831
13832 static void
13833 ada_add_standard_exceptions (compiled_regex *preg,
13834 std::vector<ada_exc_info> *exceptions)
13835 {
13836 int i;
13837
13838 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13839 {
13840 if (preg == NULL
13841 || preg->exec (standard_exc[i], 0, NULL, 0) == 0)
13842 {
13843 struct bound_minimal_symbol msymbol
13844 = ada_lookup_simple_minsym (standard_exc[i]);
13845
13846 if (msymbol.minsym != NULL)
13847 {
13848 struct ada_exc_info info
13849 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};
13850
13851 exceptions->push_back (info);
13852 }
13853 }
13854 }
13855 }
13856
13857 /* Add all Ada exceptions defined locally and accessible from the given
13858 FRAME.
13859
13860 If PREG is not NULL, then this regexp_t object is used to
13861 perform the symbol name matching. Otherwise, no name-based
13862 filtering is performed.
13863
13864 EXCEPTIONS is a vector of exceptions to which matching exceptions
13865 gets pushed. */
13866
13867 static void
13868 ada_add_exceptions_from_frame (compiled_regex *preg,
13869 struct frame_info *frame,
13870 std::vector<ada_exc_info> *exceptions)
13871 {
13872 const struct block *block = get_frame_block (frame, 0);
13873
13874 while (block != 0)
13875 {
13876 struct block_iterator iter;
13877 struct symbol *sym;
13878
13879 ALL_BLOCK_SYMBOLS (block, iter, sym)
13880 {
13881 switch (SYMBOL_CLASS (sym))
13882 {
13883 case LOC_TYPEDEF:
13884 case LOC_BLOCK:
13885 case LOC_CONST:
13886 break;
13887 default:
13888 if (ada_is_exception_sym (sym))
13889 {
13890 struct ada_exc_info info = {sym->print_name (),
13891 SYMBOL_VALUE_ADDRESS (sym)};
13892
13893 exceptions->push_back (info);
13894 }
13895 }
13896 }
13897 if (BLOCK_FUNCTION (block) != NULL)
13898 break;
13899 block = BLOCK_SUPERBLOCK (block);
13900 }
13901 }
13902
13903 /* Return true if NAME matches PREG or if PREG is NULL. */
13904
13905 static bool
13906 name_matches_regex (const char *name, compiled_regex *preg)
13907 {
13908 return (preg == NULL
13909 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13910 }
13911
13912 /* Add all exceptions defined globally whose name name match
13913 a regular expression, excluding standard exceptions.
13914
13915 The reason we exclude standard exceptions is that they need
13916 to be handled separately: Standard exceptions are defined inside
13917 a runtime unit which is normally not compiled with debugging info,
13918 and thus usually do not show up in our symbol search. However,
13919 if the unit was in fact built with debugging info, we need to
13920 exclude them because they would duplicate the entry we found
13921 during the special loop that specifically searches for those
13922 standard exceptions.
13923
13924 If PREG is not NULL, then this regexp_t object is used to
13925 perform the symbol name matching. Otherwise, no name-based
13926 filtering is performed.
13927
13928 EXCEPTIONS is a vector of exceptions to which matching exceptions
13929 gets pushed. */
13930
13931 static void
13932 ada_add_global_exceptions (compiled_regex *preg,
13933 std::vector<ada_exc_info> *exceptions)
13934 {
13935 /* In Ada, the symbol "search name" is a linkage name, whereas the
13936 regular expression used to do the matching refers to the natural
13937 name. So match against the decoded name. */
13938 expand_symtabs_matching (NULL,
13939 lookup_name_info::match_any (),
13940 [&] (const char *search_name)
13941 {
13942 std::string decoded = ada_decode (search_name);
13943 return name_matches_regex (decoded.c_str (), preg);
13944 },
13945 NULL,
13946 VARIABLES_DOMAIN);
13947
13948 for (objfile *objfile : current_program_space->objfiles ())
13949 {
13950 for (compunit_symtab *s : objfile->compunits ())
13951 {
13952 const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
13953 int i;
13954
13955 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13956 {
13957 const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
13958 struct block_iterator iter;
13959 struct symbol *sym;
13960
13961 ALL_BLOCK_SYMBOLS (b, iter, sym)
13962 if (ada_is_non_standard_exception_sym (sym)
13963 && name_matches_regex (sym->natural_name (), preg))
13964 {
13965 struct ada_exc_info info
13966 = {sym->print_name (), SYMBOL_VALUE_ADDRESS (sym)};
13967
13968 exceptions->push_back (info);
13969 }
13970 }
13971 }
13972 }
13973 }
13974
13975 /* Implements ada_exceptions_list with the regular expression passed
13976 as a regex_t, rather than a string.
13977
13978 If not NULL, PREG is used to filter out exceptions whose names
13979 do not match. Otherwise, all exceptions are listed. */
13980
13981 static std::vector<ada_exc_info>
13982 ada_exceptions_list_1 (compiled_regex *preg)
13983 {
13984 std::vector<ada_exc_info> result;
13985 int prev_len;
13986
13987 /* First, list the known standard exceptions. These exceptions
13988 need to be handled separately, as they are usually defined in
13989 runtime units that have been compiled without debugging info. */
13990
13991 ada_add_standard_exceptions (preg, &result);
13992
13993 /* Next, find all exceptions whose scope is local and accessible
13994 from the currently selected frame. */
13995
13996 if (has_stack_frames ())
13997 {
13998 prev_len = result.size ();
13999 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
14000 &result);
14001 if (result.size () > prev_len)
14002 sort_remove_dups_ada_exceptions_list (&result, prev_len);
14003 }
14004
14005 /* Add all exceptions whose scope is global. */
14006
14007 prev_len = result.size ();
14008 ada_add_global_exceptions (preg, &result);
14009 if (result.size () > prev_len)
14010 sort_remove_dups_ada_exceptions_list (&result, prev_len);
14011
14012 return result;
14013 }
14014
14015 /* Return a vector of ada_exc_info.
14016
14017 If REGEXP is NULL, all exceptions are included in the result.
14018 Otherwise, it should contain a valid regular expression,
14019 and only the exceptions whose names match that regular expression
14020 are included in the result.
14021
14022 The exceptions are sorted in the following order:
14023 - Standard exceptions (defined by the Ada language), in
14024 alphabetical order;
14025 - Exceptions only visible from the current frame, in
14026 alphabetical order;
14027 - Exceptions whose scope is global, in alphabetical order. */
14028
14029 std::vector<ada_exc_info>
14030 ada_exceptions_list (const char *regexp)
14031 {
14032 if (regexp == NULL)
14033 return ada_exceptions_list_1 (NULL);
14034
14035 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
14036 return ada_exceptions_list_1 (&reg);
14037 }
14038
14039 /* Implement the "info exceptions" command. */
14040
14041 static void
14042 info_exceptions_command (const char *regexp, int from_tty)
14043 {
14044 struct gdbarch *gdbarch = get_current_arch ();
14045
14046 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
14047
14048 if (regexp != NULL)
14049 printf_filtered
14050 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
14051 else
14052 printf_filtered (_("All defined Ada exceptions:\n"));
14053
14054 for (const ada_exc_info &info : exceptions)
14055 printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
14056 }
14057
14058 /* Operators */
14059 /* Information about operators given special treatment in functions
14060 below. */
14061 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>). */
14062
14063 #define ADA_OPERATORS \
14064 OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
14065 OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
14066 OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
14067 OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
14068 OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
14069 OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
14070 OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
14071 OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
14072 OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
14073 OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
14074 OP_DEFN (OP_ATR_POS, 1, 2, 0) \
14075 OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
14076 OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
14077 OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
14078 OP_DEFN (UNOP_QUAL, 3, 1, 0) \
14079 OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
14080 OP_DEFN (OP_OTHERS, 1, 1, 0) \
14081 OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
14082 OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
14083
14084 static void
14085 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
14086 int *argsp)
14087 {
14088 switch (exp->elts[pc - 1].opcode)
14089 {
14090 default:
14091 operator_length_standard (exp, pc, oplenp, argsp);
14092 break;
14093
14094 #define OP_DEFN(op, len, args, binop) \
14095 case op: *oplenp = len; *argsp = args; break;
14096 ADA_OPERATORS;
14097 #undef OP_DEFN
14098
14099 case OP_AGGREGATE:
14100 *oplenp = 3;
14101 *argsp = longest_to_int (exp->elts[pc - 2].longconst);
14102 break;
14103
14104 case OP_CHOICES:
14105 *oplenp = 3;
14106 *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
14107 break;
14108 }
14109 }
14110
14111 /* Implementation of the exp_descriptor method operator_check. */
14112
14113 static int
14114 ada_operator_check (struct expression *exp, int pos,
14115 int (*objfile_func) (struct objfile *objfile, void *data),
14116 void *data)
14117 {
14118 const union exp_element *const elts = exp->elts;
14119 struct type *type = NULL;
14120
14121 switch (elts[pos].opcode)
14122 {
14123 case UNOP_IN_RANGE:
14124 case UNOP_QUAL:
14125 type = elts[pos + 1].type;
14126 break;
14127
14128 default:
14129 return operator_check_standard (exp, pos, objfile_func, data);
14130 }
14131
14132 /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL. */
14133
14134 if (type != nullptr && type->objfile_owner () != nullptr
14135 && objfile_func (type->objfile_owner (), data))
14136 return 1;
14137
14138 return 0;
14139 }
14140
14141 /* As for operator_length, but assumes PC is pointing at the first
14142 element of the operator, and gives meaningful results only for the
14143 Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise. */
14144
14145 static void
14146 ada_forward_operator_length (struct expression *exp, int pc,
14147 int *oplenp, int *argsp)
14148 {
14149 switch (exp->elts[pc].opcode)
14150 {
14151 default:
14152 *oplenp = *argsp = 0;
14153 break;
14154
14155 #define OP_DEFN(op, len, args, binop) \
14156 case op: *oplenp = len; *argsp = args; break;
14157 ADA_OPERATORS;
14158 #undef OP_DEFN
14159
14160 case OP_AGGREGATE:
14161 *oplenp = 3;
14162 *argsp = longest_to_int (exp->elts[pc + 1].longconst);
14163 break;
14164
14165 case OP_CHOICES:
14166 *oplenp = 3;
14167 *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
14168 break;
14169
14170 case OP_STRING:
14171 case OP_NAME:
14172 {
14173 int len = longest_to_int (exp->elts[pc + 1].longconst);
14174
14175 *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
14176 *argsp = 0;
14177 break;
14178 }
14179 }
14180 }
14181
14182 static int
14183 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
14184 {
14185 enum exp_opcode op = exp->elts[elt].opcode;
14186 int oplen, nargs;
14187 int pc = elt;
14188 int i;
14189
14190 ada_forward_operator_length (exp, elt, &oplen, &nargs);
14191
14192 switch (op)
14193 {
14194 /* Ada attributes ('Foo). */
14195 case OP_ATR_FIRST:
14196 case OP_ATR_LAST:
14197 case OP_ATR_LENGTH:
14198 case OP_ATR_IMAGE:
14199 case OP_ATR_MAX:
14200 case OP_ATR_MIN:
14201 case OP_ATR_MODULUS:
14202 case OP_ATR_POS:
14203 case OP_ATR_SIZE:
14204 case OP_ATR_TAG:
14205 case OP_ATR_VAL:
14206 break;
14207
14208 case UNOP_IN_RANGE:
14209 case UNOP_QUAL:
14210 /* XXX: gdb_sprint_host_address, type_sprint */
14211 fprintf_filtered (stream, _("Type @"));
14212 gdb_print_host_address (exp->elts[pc + 1].type, stream);
14213 fprintf_filtered (stream, " (");
14214 type_print (exp->elts[pc + 1].type, NULL, stream, 0);
14215 fprintf_filtered (stream, ")");
14216 break;
14217 case BINOP_IN_BOUNDS:
14218 fprintf_filtered (stream, " (%d)",
14219 longest_to_int (exp->elts[pc + 2].longconst));
14220 break;
14221 case TERNOP_IN_RANGE:
14222 break;
14223
14224 case OP_AGGREGATE:
14225 case OP_OTHERS:
14226 case OP_DISCRETE_RANGE:
14227 case OP_POSITIONAL:
14228 case OP_CHOICES:
14229 break;
14230
14231 case OP_NAME:
14232 case OP_STRING:
14233 {
14234 char *name = &exp->elts[elt + 2].string;
14235 int len = longest_to_int (exp->elts[elt + 1].longconst);
14236
14237 fprintf_filtered (stream, "Text: `%.*s'", len, name);
14238 break;
14239 }
14240
14241 default:
14242 return dump_subexp_body_standard (exp, stream, elt);
14243 }
14244
14245 elt += oplen;
14246 for (i = 0; i < nargs; i += 1)
14247 elt = dump_subexp (exp, stream, elt);
14248
14249 return elt;
14250 }
14251
14252 /* The Ada extension of print_subexp (q.v.). */
14253
14254 static void
14255 ada_print_subexp (struct expression *exp, int *pos,
14256 struct ui_file *stream, enum precedence prec)
14257 {
14258 int oplen, nargs, i;
14259 int pc = *pos;
14260 enum exp_opcode op = exp->elts[pc].opcode;
14261
14262 ada_forward_operator_length (exp, pc, &oplen, &nargs);
14263
14264 *pos += oplen;
14265 switch (op)
14266 {
14267 default:
14268 *pos -= oplen;
14269 print_subexp_standard (exp, pos, stream, prec);
14270 return;
14271
14272 case OP_VAR_VALUE:
14273 fputs_filtered (exp->elts[pc + 2].symbol->natural_name (), stream);
14274 return;
14275
14276 case BINOP_IN_BOUNDS:
14277 /* XXX: sprint_subexp */
14278 print_subexp (exp, pos, stream, PREC_SUFFIX);
14279 fputs_filtered (" in ", stream);
14280 print_subexp (exp, pos, stream, PREC_SUFFIX);
14281 fputs_filtered ("'range", stream);
14282 if (exp->elts[pc + 1].longconst > 1)
14283 fprintf_filtered (stream, "(%ld)",
14284 (long) exp->elts[pc + 1].longconst);
14285 return;
14286
14287 case TERNOP_IN_RANGE:
14288 if (prec >= PREC_EQUAL)
14289 fputs_filtered ("(", stream);
14290 /* XXX: sprint_subexp */
14291 print_subexp (exp, pos, stream, PREC_SUFFIX);
14292 fputs_filtered (" in ", stream);
14293 print_subexp (exp, pos, stream, PREC_EQUAL);
14294 fputs_filtered (" .. ", stream);
14295 print_subexp (exp, pos, stream, PREC_EQUAL);
14296 if (prec >= PREC_EQUAL)
14297 fputs_filtered (")", stream);
14298 return;
14299
14300 case OP_ATR_FIRST:
14301 case OP_ATR_LAST:
14302 case OP_ATR_LENGTH:
14303 case OP_ATR_IMAGE:
14304 case OP_ATR_MAX:
14305 case OP_ATR_MIN:
14306 case OP_ATR_MODULUS:
14307 case OP_ATR_POS:
14308 case OP_ATR_SIZE:
14309 case OP_ATR_TAG:
14310 case OP_ATR_VAL:
14311 if (exp->elts[*pos].opcode == OP_TYPE)
14312 {
14313 if (exp->elts[*pos + 1].type->code () != TYPE_CODE_VOID)
14314 LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
14315 &type_print_raw_options);
14316 *pos += 3;
14317 }
14318 else
14319 print_subexp (exp, pos, stream, PREC_SUFFIX);
14320 fprintf_filtered (stream, "'%s", ada_attribute_name (op));
14321 if (nargs > 1)
14322 {
14323 int tem;
14324
14325 for (tem = 1; tem < nargs; tem += 1)
14326 {
14327 fputs_filtered ((tem == 1) ? " (" : ", ", stream);
14328 print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
14329 }
14330 fputs_filtered (")", stream);
14331 }
14332 return;
14333
14334 case UNOP_QUAL:
14335 type_print (exp->elts[pc + 1].type, "", stream, 0);
14336 fputs_filtered ("'(", stream);
14337 print_subexp (exp, pos, stream, PREC_PREFIX);
14338 fputs_filtered (")", stream);
14339 return;
14340
14341 case UNOP_IN_RANGE:
14342 /* XXX: sprint_subexp */
14343 print_subexp (exp, pos, stream, PREC_SUFFIX);
14344 fputs_filtered (" in ", stream);
14345 LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
14346 &type_print_raw_options);
14347 return;
14348
14349 case OP_DISCRETE_RANGE:
14350 print_subexp (exp, pos, stream, PREC_SUFFIX);
14351 fputs_filtered ("..", stream);
14352 print_subexp (exp, pos, stream, PREC_SUFFIX);
14353 return;
14354
14355 case OP_OTHERS:
14356 fputs_filtered ("others => ", stream);
14357 print_subexp (exp, pos, stream, PREC_SUFFIX);
14358 return;
14359
14360 case OP_CHOICES:
14361 for (i = 0; i < nargs-1; i += 1)
14362 {
14363 if (i > 0)
14364 fputs_filtered ("|", stream);
14365 print_subexp (exp, pos, stream, PREC_SUFFIX);
14366 }
14367 fputs_filtered (" => ", stream);
14368 print_subexp (exp, pos, stream, PREC_SUFFIX);
14369 return;
14370
14371 case OP_POSITIONAL:
14372 print_subexp (exp, pos, stream, PREC_SUFFIX);
14373 return;
14374
14375 case OP_AGGREGATE:
14376 fputs_filtered ("(", stream);
14377 for (i = 0; i < nargs; i += 1)
14378 {
14379 if (i > 0)
14380 fputs_filtered (", ", stream);
14381 print_subexp (exp, pos, stream, PREC_SUFFIX);
14382 }
14383 fputs_filtered (")", stream);
14384 return;
14385 }
14386 }
14387
14388 /* Table mapping opcodes into strings for printing operators
14389 and precedences of the operators. */
14390
14391 static const struct op_print ada_op_print_tab[] = {
14392 {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
14393 {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
14394 {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
14395 {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
14396 {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
14397 {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
14398 {"=", BINOP_EQUAL, PREC_EQUAL, 0},
14399 {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
14400 {"<=", BINOP_LEQ, PREC_ORDER, 0},
14401 {">=", BINOP_GEQ, PREC_ORDER, 0},
14402 {">", BINOP_GTR, PREC_ORDER, 0},
14403 {"<", BINOP_LESS, PREC_ORDER, 0},
14404 {">>", BINOP_RSH, PREC_SHIFT, 0},
14405 {"<<", BINOP_LSH, PREC_SHIFT, 0},
14406 {"+", BINOP_ADD, PREC_ADD, 0},
14407 {"-", BINOP_SUB, PREC_ADD, 0},
14408 {"&", BINOP_CONCAT, PREC_ADD, 0},
14409 {"*", BINOP_MUL, PREC_MUL, 0},
14410 {"/", BINOP_DIV, PREC_MUL, 0},
14411 {"rem", BINOP_REM, PREC_MUL, 0},
14412 {"mod", BINOP_MOD, PREC_MUL, 0},
14413 {"**", BINOP_EXP, PREC_REPEAT, 0},
14414 {"@", BINOP_REPEAT, PREC_REPEAT, 0},
14415 {"-", UNOP_NEG, PREC_PREFIX, 0},
14416 {"+", UNOP_PLUS, PREC_PREFIX, 0},
14417 {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
14418 {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
14419 {"abs ", UNOP_ABS, PREC_PREFIX, 0},
14420 {".all", UNOP_IND, PREC_SUFFIX, 1},
14421 {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
14422 {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
14423 {NULL, OP_NULL, PREC_SUFFIX, 0}
14424 };
14425 \f
14426 /* Language vector */
14427
14428 static const struct exp_descriptor ada_exp_descriptor = {
14429 ada_print_subexp,
14430 ada_operator_length,
14431 ada_operator_check,
14432 ada_dump_subexp_body,
14433 ada_evaluate_subexp
14434 };
14435
14436 /* symbol_name_matcher_ftype adapter for wild_match. */
14437
14438 static bool
14439 do_wild_match (const char *symbol_search_name,
14440 const lookup_name_info &lookup_name,
14441 completion_match_result *comp_match_res)
14442 {
14443 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
14444 }
14445
14446 /* symbol_name_matcher_ftype adapter for full_match. */
14447
14448 static bool
14449 do_full_match (const char *symbol_search_name,
14450 const lookup_name_info &lookup_name,
14451 completion_match_result *comp_match_res)
14452 {
14453 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
14454
14455 /* If both symbols start with "_ada_", just let the loop below
14456 handle the comparison. However, if only the symbol name starts
14457 with "_ada_", skip the prefix and let the match proceed as
14458 usual. */
14459 if (startswith (symbol_search_name, "_ada_")
14460 && !startswith (lname, "_ada"))
14461 symbol_search_name += 5;
14462
14463 int uscore_count = 0;
14464 while (*lname != '\0')
14465 {
14466 if (*symbol_search_name != *lname)
14467 {
14468 if (*symbol_search_name == 'B' && uscore_count == 2
14469 && symbol_search_name[1] == '_')
14470 {
14471 symbol_search_name += 2;
14472 while (isdigit (*symbol_search_name))
14473 ++symbol_search_name;
14474 if (symbol_search_name[0] == '_'
14475 && symbol_search_name[1] == '_')
14476 {
14477 symbol_search_name += 2;
14478 continue;
14479 }
14480 }
14481 return false;
14482 }
14483
14484 if (*symbol_search_name == '_')
14485 ++uscore_count;
14486 else
14487 uscore_count = 0;
14488
14489 ++symbol_search_name;
14490 ++lname;
14491 }
14492
14493 return is_name_suffix (symbol_search_name);
14494 }
14495
14496 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
14497
14498 static bool
14499 do_exact_match (const char *symbol_search_name,
14500 const lookup_name_info &lookup_name,
14501 completion_match_result *comp_match_res)
14502 {
14503 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
14504 }
14505
14506 /* Build the Ada lookup name for LOOKUP_NAME. */
14507
14508 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
14509 {
14510 gdb::string_view user_name = lookup_name.name ();
14511
14512 if (!user_name.empty () && user_name[0] == '<')
14513 {
14514 if (user_name.back () == '>')
14515 m_encoded_name
14516 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
14517 else
14518 m_encoded_name
14519 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
14520 m_encoded_p = true;
14521 m_verbatim_p = true;
14522 m_wild_match_p = false;
14523 m_standard_p = false;
14524 }
14525 else
14526 {
14527 m_verbatim_p = false;
14528
14529 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
14530
14531 if (!m_encoded_p)
14532 {
14533 const char *folded = ada_fold_name (user_name);
14534 m_encoded_name = ada_encode_1 (folded, false);
14535 if (m_encoded_name.empty ())
14536 m_encoded_name = gdb::to_string (user_name);
14537 }
14538 else
14539 m_encoded_name = gdb::to_string (user_name);
14540
14541 /* Handle the 'package Standard' special case. See description
14542 of m_standard_p. */
14543 if (startswith (m_encoded_name.c_str (), "standard__"))
14544 {
14545 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
14546 m_standard_p = true;
14547 }
14548 else
14549 m_standard_p = false;
14550
14551 /* If the name contains a ".", then the user is entering a fully
14552 qualified entity name, and the match must not be done in wild
14553 mode. Similarly, if the user wants to complete what looks
14554 like an encoded name, the match must not be done in wild
14555 mode. Also, in the standard__ special case always do
14556 non-wild matching. */
14557 m_wild_match_p
14558 = (lookup_name.match_type () != symbol_name_match_type::FULL
14559 && !m_encoded_p
14560 && !m_standard_p
14561 && user_name.find ('.') == std::string::npos);
14562 }
14563 }
14564
14565 /* symbol_name_matcher_ftype method for Ada. This only handles
14566 completion mode. */
14567
14568 static bool
14569 ada_symbol_name_matches (const char *symbol_search_name,
14570 const lookup_name_info &lookup_name,
14571 completion_match_result *comp_match_res)
14572 {
14573 return lookup_name.ada ().matches (symbol_search_name,
14574 lookup_name.match_type (),
14575 comp_match_res);
14576 }
14577
14578 /* A name matcher that matches the symbol name exactly, with
14579 strcmp. */
14580
14581 static bool
14582 literal_symbol_name_matcher (const char *symbol_search_name,
14583 const lookup_name_info &lookup_name,
14584 completion_match_result *comp_match_res)
14585 {
14586 gdb::string_view name_view = lookup_name.name ();
14587
14588 if (lookup_name.completion_mode ()
14589 ? (strncmp (symbol_search_name, name_view.data (),
14590 name_view.size ()) == 0)
14591 : symbol_search_name == name_view)
14592 {
14593 if (comp_match_res != NULL)
14594 comp_match_res->set_match (symbol_search_name);
14595 return true;
14596 }
14597 else
14598 return false;
14599 }
14600
14601 /* Implement the "get_symbol_name_matcher" language_defn method for
14602 Ada. */
14603
14604 static symbol_name_matcher_ftype *
14605 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
14606 {
14607 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
14608 return literal_symbol_name_matcher;
14609
14610 if (lookup_name.completion_mode ())
14611 return ada_symbol_name_matches;
14612 else
14613 {
14614 if (lookup_name.ada ().wild_match_p ())
14615 return do_wild_match;
14616 else if (lookup_name.ada ().verbatim_p ())
14617 return do_exact_match;
14618 else
14619 return do_full_match;
14620 }
14621 }
14622
14623 /* Class representing the Ada language. */
14624
14625 class ada_language : public language_defn
14626 {
14627 public:
14628 ada_language ()
14629 : language_defn (language_ada)
14630 { /* Nothing. */ }
14631
14632 /* See language.h. */
14633
14634 const char *name () const override
14635 { return "ada"; }
14636
14637 /* See language.h. */
14638
14639 const char *natural_name () const override
14640 { return "Ada"; }
14641
14642 /* See language.h. */
14643
14644 const std::vector<const char *> &filename_extensions () const override
14645 {
14646 static const std::vector<const char *> extensions
14647 = { ".adb", ".ads", ".a", ".ada", ".dg" };
14648 return extensions;
14649 }
14650
14651 /* Print an array element index using the Ada syntax. */
14652
14653 void print_array_index (struct type *index_type,
14654 LONGEST index,
14655 struct ui_file *stream,
14656 const value_print_options *options) const override
14657 {
14658 struct value *index_value = val_atr (index_type, index);
14659
14660 value_print (index_value, stream, options);
14661 fprintf_filtered (stream, " => ");
14662 }
14663
14664 /* Implement the "read_var_value" language_defn method for Ada. */
14665
14666 struct value *read_var_value (struct symbol *var,
14667 const struct block *var_block,
14668 struct frame_info *frame) const override
14669 {
14670 /* The only case where default_read_var_value is not sufficient
14671 is when VAR is a renaming... */
14672 if (frame != nullptr)
14673 {
14674 const struct block *frame_block = get_frame_block (frame, NULL);
14675 if (frame_block != nullptr && ada_is_renaming_symbol (var))
14676 return ada_read_renaming_var_value (var, frame_block);
14677 }
14678
14679 /* This is a typical case where we expect the default_read_var_value
14680 function to work. */
14681 return language_defn::read_var_value (var, var_block, frame);
14682 }
14683
14684 /* See language.h. */
14685 void language_arch_info (struct gdbarch *gdbarch,
14686 struct language_arch_info *lai) const override
14687 {
14688 const struct builtin_type *builtin = builtin_type (gdbarch);
14689
14690 /* Helper function to allow shorter lines below. */
14691 auto add = [&] (struct type *t)
14692 {
14693 lai->add_primitive_type (t);
14694 };
14695
14696 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14697 0, "integer"));
14698 add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
14699 0, "long_integer"));
14700 add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
14701 0, "short_integer"));
14702 struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
14703 0, "character");
14704 lai->set_string_char_type (char_type);
14705 add (char_type);
14706 add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
14707 "float", gdbarch_float_format (gdbarch)));
14708 add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
14709 "long_float", gdbarch_double_format (gdbarch)));
14710 add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
14711 0, "long_long_integer"));
14712 add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
14713 "long_long_float",
14714 gdbarch_long_double_format (gdbarch)));
14715 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14716 0, "natural"));
14717 add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14718 0, "positive"));
14719 add (builtin->builtin_void);
14720
14721 struct type *system_addr_ptr
14722 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
14723 "void"));
14724 system_addr_ptr->set_name ("system__address");
14725 add (system_addr_ptr);
14726
14727 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
14728 type. This is a signed integral type whose size is the same as
14729 the size of addresses. */
14730 unsigned int addr_length = TYPE_LENGTH (system_addr_ptr);
14731 add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
14732 "storage_offset"));
14733
14734 lai->set_bool_type (builtin->builtin_bool);
14735 }
14736
14737 /* See language.h. */
14738
14739 bool iterate_over_symbols
14740 (const struct block *block, const lookup_name_info &name,
14741 domain_enum domain,
14742 gdb::function_view<symbol_found_callback_ftype> callback) const override
14743 {
14744 std::vector<struct block_symbol> results
14745 = ada_lookup_symbol_list_worker (name, block, domain, 0);
14746 for (block_symbol &sym : results)
14747 {
14748 if (!callback (&sym))
14749 return false;
14750 }
14751
14752 return true;
14753 }
14754
14755 /* See language.h. */
14756 bool sniff_from_mangled_name (const char *mangled,
14757 char **out) const override
14758 {
14759 std::string demangled = ada_decode (mangled);
14760
14761 *out = NULL;
14762
14763 if (demangled != mangled && demangled[0] != '<')
14764 {
14765 /* Set the gsymbol language to Ada, but still return 0.
14766 Two reasons for that:
14767
14768 1. For Ada, we prefer computing the symbol's decoded name
14769 on the fly rather than pre-compute it, in order to save
14770 memory (Ada projects are typically very large).
14771
14772 2. There are some areas in the definition of the GNAT
14773 encoding where, with a bit of bad luck, we might be able
14774 to decode a non-Ada symbol, generating an incorrect
14775 demangled name (Eg: names ending with "TB" for instance
14776 are identified as task bodies and so stripped from
14777 the decoded name returned).
14778
14779 Returning true, here, but not setting *DEMANGLED, helps us get
14780 a little bit of the best of both worlds. Because we're last,
14781 we should not affect any of the other languages that were
14782 able to demangle the symbol before us; we get to correctly
14783 tag Ada symbols as such; and even if we incorrectly tagged a
14784 non-Ada symbol, which should be rare, any routing through the
14785 Ada language should be transparent (Ada tries to behave much
14786 like C/C++ with non-Ada symbols). */
14787 return true;
14788 }
14789
14790 return false;
14791 }
14792
14793 /* See language.h. */
14794
14795 char *demangle_symbol (const char *mangled, int options) const override
14796 {
14797 return ada_la_decode (mangled, options);
14798 }
14799
14800 /* See language.h. */
14801
14802 void print_type (struct type *type, const char *varstring,
14803 struct ui_file *stream, int show, int level,
14804 const struct type_print_options *flags) const override
14805 {
14806 ada_print_type (type, varstring, stream, show, level, flags);
14807 }
14808
14809 /* See language.h. */
14810
14811 const char *word_break_characters (void) const override
14812 {
14813 return ada_completer_word_break_characters;
14814 }
14815
14816 /* See language.h. */
14817
14818 void collect_symbol_completion_matches (completion_tracker &tracker,
14819 complete_symbol_mode mode,
14820 symbol_name_match_type name_match_type,
14821 const char *text, const char *word,
14822 enum type_code code) const override
14823 {
14824 struct symbol *sym;
14825 const struct block *b, *surrounding_static_block = 0;
14826 struct block_iterator iter;
14827
14828 gdb_assert (code == TYPE_CODE_UNDEF);
14829
14830 lookup_name_info lookup_name (text, name_match_type, true);
14831
14832 /* First, look at the partial symtab symbols. */
14833 expand_symtabs_matching (NULL,
14834 lookup_name,
14835 NULL,
14836 NULL,
14837 ALL_DOMAIN);
14838
14839 /* At this point scan through the misc symbol vectors and add each
14840 symbol you find to the list. Eventually we want to ignore
14841 anything that isn't a text symbol (everything else will be
14842 handled by the psymtab code above). */
14843
14844 for (objfile *objfile : current_program_space->objfiles ())
14845 {
14846 for (minimal_symbol *msymbol : objfile->msymbols ())
14847 {
14848 QUIT;
14849
14850 if (completion_skip_symbol (mode, msymbol))
14851 continue;
14852
14853 language symbol_language = msymbol->language ();
14854
14855 /* Ada minimal symbols won't have their language set to Ada. If
14856 we let completion_list_add_name compare using the
14857 default/C-like matcher, then when completing e.g., symbols in a
14858 package named "pck", we'd match internal Ada symbols like
14859 "pckS", which are invalid in an Ada expression, unless you wrap
14860 them in '<' '>' to request a verbatim match.
14861
14862 Unfortunately, some Ada encoded names successfully demangle as
14863 C++ symbols (using an old mangling scheme), such as "name__2Xn"
14864 -> "Xn::name(void)" and thus some Ada minimal symbols end up
14865 with the wrong language set. Paper over that issue here. */
14866 if (symbol_language == language_auto
14867 || symbol_language == language_cplus)
14868 symbol_language = language_ada;
14869
14870 completion_list_add_name (tracker,
14871 symbol_language,
14872 msymbol->linkage_name (),
14873 lookup_name, text, word);
14874 }
14875 }
14876
14877 /* Search upwards from currently selected frame (so that we can
14878 complete on local vars. */
14879
14880 for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
14881 {
14882 if (!BLOCK_SUPERBLOCK (b))
14883 surrounding_static_block = b; /* For elmin of dups */
14884
14885 ALL_BLOCK_SYMBOLS (b, iter, sym)
14886 {
14887 if (completion_skip_symbol (mode, sym))
14888 continue;
14889
14890 completion_list_add_name (tracker,
14891 sym->language (),
14892 sym->linkage_name (),
14893 lookup_name, text, word);
14894 }
14895 }
14896
14897 /* Go through the symtabs and check the externs and statics for
14898 symbols which match. */
14899
14900 for (objfile *objfile : current_program_space->objfiles ())
14901 {
14902 for (compunit_symtab *s : objfile->compunits ())
14903 {
14904 QUIT;
14905 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
14906 ALL_BLOCK_SYMBOLS (b, iter, sym)
14907 {
14908 if (completion_skip_symbol (mode, sym))
14909 continue;
14910
14911 completion_list_add_name (tracker,
14912 sym->language (),
14913 sym->linkage_name (),
14914 lookup_name, text, word);
14915 }
14916 }
14917 }
14918
14919 for (objfile *objfile : current_program_space->objfiles ())
14920 {
14921 for (compunit_symtab *s : objfile->compunits ())
14922 {
14923 QUIT;
14924 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
14925 /* Don't do this block twice. */
14926 if (b == surrounding_static_block)
14927 continue;
14928 ALL_BLOCK_SYMBOLS (b, iter, sym)
14929 {
14930 if (completion_skip_symbol (mode, sym))
14931 continue;
14932
14933 completion_list_add_name (tracker,
14934 sym->language (),
14935 sym->linkage_name (),
14936 lookup_name, text, word);
14937 }
14938 }
14939 }
14940 }
14941
14942 /* See language.h. */
14943
14944 gdb::unique_xmalloc_ptr<char> watch_location_expression
14945 (struct type *type, CORE_ADDR addr) const override
14946 {
14947 type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
14948 std::string name = type_to_string (type);
14949 return gdb::unique_xmalloc_ptr<char>
14950 (xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr)));
14951 }
14952
14953 /* See language.h. */
14954
14955 void value_print (struct value *val, struct ui_file *stream,
14956 const struct value_print_options *options) const override
14957 {
14958 return ada_value_print (val, stream, options);
14959 }
14960
14961 /* See language.h. */
14962
14963 void value_print_inner
14964 (struct value *val, struct ui_file *stream, int recurse,
14965 const struct value_print_options *options) const override
14966 {
14967 return ada_value_print_inner (val, stream, recurse, options);
14968 }
14969
14970 /* See language.h. */
14971
14972 struct block_symbol lookup_symbol_nonlocal
14973 (const char *name, const struct block *block,
14974 const domain_enum domain) const override
14975 {
14976 struct block_symbol sym;
14977
14978 sym = ada_lookup_symbol (name, block_static_block (block), domain);
14979 if (sym.symbol != NULL)
14980 return sym;
14981
14982 /* If we haven't found a match at this point, try the primitive
14983 types. In other languages, this search is performed before
14984 searching for global symbols in order to short-circuit that
14985 global-symbol search if it happens that the name corresponds
14986 to a primitive type. But we cannot do the same in Ada, because
14987 it is perfectly legitimate for a program to declare a type which
14988 has the same name as a standard type. If looking up a type in
14989 that situation, we have traditionally ignored the primitive type
14990 in favor of user-defined types. This is why, unlike most other
14991 languages, we search the primitive types this late and only after
14992 having searched the global symbols without success. */
14993
14994 if (domain == VAR_DOMAIN)
14995 {
14996 struct gdbarch *gdbarch;
14997
14998 if (block == NULL)
14999 gdbarch = target_gdbarch ();
15000 else
15001 gdbarch = block_gdbarch (block);
15002 sym.symbol
15003 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
15004 if (sym.symbol != NULL)
15005 return sym;
15006 }
15007
15008 return {};
15009 }
15010
15011 /* See language.h. */
15012
15013 int parser (struct parser_state *ps) const override
15014 {
15015 warnings_issued = 0;
15016 return ada_parse (ps);
15017 }
15018
15019 /* See language.h.
15020
15021 Same as evaluate_type (*EXP), but resolves ambiguous symbol references
15022 (marked by OP_VAR_VALUE nodes in which the symbol has an undefined
15023 namespace) and converts operators that are user-defined into
15024 appropriate function calls. If CONTEXT_TYPE is non-null, it provides
15025 a preferred result type [at the moment, only type void has any
15026 effect---causing procedures to be preferred over functions in calls].
15027 A null CONTEXT_TYPE indicates that a non-void return type is
15028 preferred. May change (expand) *EXP. */
15029
15030 void post_parser (expression_up *expp, struct parser_state *ps)
15031 const override
15032 {
15033 struct type *context_type = NULL;
15034 int pc = 0;
15035
15036 if (ps->void_context_p)
15037 context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
15038
15039 resolve_subexp (expp, &pc, 1, context_type, ps->parse_completion,
15040 ps->block_tracker);
15041 }
15042
15043 /* See language.h. */
15044
15045 void emitchar (int ch, struct type *chtype,
15046 struct ui_file *stream, int quoter) const override
15047 {
15048 ada_emit_char (ch, chtype, stream, quoter, 1);
15049 }
15050
15051 /* See language.h. */
15052
15053 void printchar (int ch, struct type *chtype,
15054 struct ui_file *stream) const override
15055 {
15056 ada_printchar (ch, chtype, stream);
15057 }
15058
15059 /* See language.h. */
15060
15061 void printstr (struct ui_file *stream, struct type *elttype,
15062 const gdb_byte *string, unsigned int length,
15063 const char *encoding, int force_ellipses,
15064 const struct value_print_options *options) const override
15065 {
15066 ada_printstr (stream, elttype, string, length, encoding,
15067 force_ellipses, options);
15068 }
15069
15070 /* See language.h. */
15071
15072 void print_typedef (struct type *type, struct symbol *new_symbol,
15073 struct ui_file *stream) const override
15074 {
15075 ada_print_typedef (type, new_symbol, stream);
15076 }
15077
15078 /* See language.h. */
15079
15080 bool is_string_type_p (struct type *type) const override
15081 {
15082 return ada_is_string_type (type);
15083 }
15084
15085 /* See language.h. */
15086
15087 const char *struct_too_deep_ellipsis () const override
15088 { return "(...)"; }
15089
15090 /* See language.h. */
15091
15092 bool c_style_arrays_p () const override
15093 { return false; }
15094
15095 /* See language.h. */
15096
15097 bool store_sym_names_in_linkage_form_p () const override
15098 { return true; }
15099
15100 /* See language.h. */
15101
15102 const struct lang_varobj_ops *varobj_ops () const override
15103 { return &ada_varobj_ops; }
15104
15105 /* See language.h. */
15106
15107 const struct exp_descriptor *expression_ops () const override
15108 { return &ada_exp_descriptor; }
15109
15110 /* See language.h. */
15111
15112 const struct op_print *opcode_print_table () const override
15113 { return ada_op_print_tab; }
15114
15115 protected:
15116 /* See language.h. */
15117
15118 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
15119 (const lookup_name_info &lookup_name) const override
15120 {
15121 return ada_get_symbol_name_matcher (lookup_name);
15122 }
15123 };
15124
15125 /* Single instance of the Ada language class. */
15126
15127 static ada_language ada_language_defn;
15128
15129 /* Command-list for the "set/show ada" prefix command. */
15130 static struct cmd_list_element *set_ada_list;
15131 static struct cmd_list_element *show_ada_list;
15132
15133 static void
15134 initialize_ada_catchpoint_ops (void)
15135 {
15136 struct breakpoint_ops *ops;
15137
15138 initialize_breakpoint_ops ();
15139
15140 ops = &catch_exception_breakpoint_ops;
15141 *ops = bkpt_breakpoint_ops;
15142 ops->allocate_location = allocate_location_exception;
15143 ops->re_set = re_set_exception;
15144 ops->check_status = check_status_exception;
15145 ops->print_it = print_it_exception;
15146 ops->print_one = print_one_exception;
15147 ops->print_mention = print_mention_exception;
15148 ops->print_recreate = print_recreate_exception;
15149
15150 ops = &catch_exception_unhandled_breakpoint_ops;
15151 *ops = bkpt_breakpoint_ops;
15152 ops->allocate_location = allocate_location_exception;
15153 ops->re_set = re_set_exception;
15154 ops->check_status = check_status_exception;
15155 ops->print_it = print_it_exception;
15156 ops->print_one = print_one_exception;
15157 ops->print_mention = print_mention_exception;
15158 ops->print_recreate = print_recreate_exception;
15159
15160 ops = &catch_assert_breakpoint_ops;
15161 *ops = bkpt_breakpoint_ops;
15162 ops->allocate_location = allocate_location_exception;
15163 ops->re_set = re_set_exception;
15164 ops->check_status = check_status_exception;
15165 ops->print_it = print_it_exception;
15166 ops->print_one = print_one_exception;
15167 ops->print_mention = print_mention_exception;
15168 ops->print_recreate = print_recreate_exception;
15169
15170 ops = &catch_handlers_breakpoint_ops;
15171 *ops = bkpt_breakpoint_ops;
15172 ops->allocate_location = allocate_location_exception;
15173 ops->re_set = re_set_exception;
15174 ops->check_status = check_status_exception;
15175 ops->print_it = print_it_exception;
15176 ops->print_one = print_one_exception;
15177 ops->print_mention = print_mention_exception;
15178 ops->print_recreate = print_recreate_exception;
15179 }
15180
15181 /* This module's 'new_objfile' observer. */
15182
15183 static void
15184 ada_new_objfile_observer (struct objfile *objfile)
15185 {
15186 ada_clear_symbol_cache ();
15187 }
15188
15189 /* This module's 'free_objfile' observer. */
15190
15191 static void
15192 ada_free_objfile_observer (struct objfile *objfile)
15193 {
15194 ada_clear_symbol_cache ();
15195 }
15196
15197 void _initialize_ada_language ();
15198 void
15199 _initialize_ada_language ()
15200 {
15201 initialize_ada_catchpoint_ops ();
15202
15203 add_basic_prefix_cmd ("ada", no_class,
15204 _("Prefix command for changing Ada-specific settings."),
15205 &set_ada_list, "set ada ", 0, &setlist);
15206
15207 add_show_prefix_cmd ("ada", no_class,
15208 _("Generic command for showing Ada-specific settings."),
15209 &show_ada_list, "show ada ", 0, &showlist);
15210
15211 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
15212 &trust_pad_over_xvs, _("\
15213 Enable or disable an optimization trusting PAD types over XVS types."), _("\
15214 Show whether an optimization trusting PAD types over XVS types is activated."),
15215 _("\
15216 This is related to the encoding used by the GNAT compiler. The debugger\n\
15217 should normally trust the contents of PAD types, but certain older versions\n\
15218 of GNAT have a bug that sometimes causes the information in the PAD type\n\
15219 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
15220 work around this bug. It is always safe to turn this option \"off\", but\n\
15221 this incurs a slight performance penalty, so it is recommended to NOT change\n\
15222 this option to \"off\" unless necessary."),
15223 NULL, NULL, &set_ada_list, &show_ada_list);
15224
15225 add_setshow_boolean_cmd ("print-signatures", class_vars,
15226 &print_signatures, _("\
15227 Enable or disable the output of formal and return types for functions in the \
15228 overloads selection menu."), _("\
15229 Show whether the output of formal and return types for functions in the \
15230 overloads selection menu is activated."),
15231 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
15232
15233 add_catch_command ("exception", _("\
15234 Catch Ada exceptions, when raised.\n\
15235 Usage: catch exception [ARG] [if CONDITION]\n\
15236 Without any argument, stop when any Ada exception is raised.\n\
15237 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
15238 being raised does not have a handler (and will therefore lead to the task's\n\
15239 termination).\n\
15240 Otherwise, the catchpoint only stops when the name of the exception being\n\
15241 raised is the same as ARG.\n\
15242 CONDITION is a boolean expression that is evaluated to see whether the\n\
15243 exception should cause a stop."),
15244 catch_ada_exception_command,
15245 catch_ada_completer,
15246 CATCH_PERMANENT,
15247 CATCH_TEMPORARY);
15248
15249 add_catch_command ("handlers", _("\
15250 Catch Ada exceptions, when handled.\n\
15251 Usage: catch handlers [ARG] [if CONDITION]\n\
15252 Without any argument, stop when any Ada exception is handled.\n\
15253 With an argument, catch only exceptions with the given name.\n\
15254 CONDITION is a boolean expression that is evaluated to see whether the\n\
15255 exception should cause a stop."),
15256 catch_ada_handlers_command,
15257 catch_ada_completer,
15258 CATCH_PERMANENT,
15259 CATCH_TEMPORARY);
15260 add_catch_command ("assert", _("\
15261 Catch failed Ada assertions, when raised.\n\
15262 Usage: catch assert [if CONDITION]\n\
15263 CONDITION is a boolean expression that is evaluated to see whether the\n\
15264 exception should cause a stop."),
15265 catch_assert_command,
15266 NULL,
15267 CATCH_PERMANENT,
15268 CATCH_TEMPORARY);
15269
15270 varsize_limit = 65536;
15271 add_setshow_uinteger_cmd ("varsize-limit", class_support,
15272 &varsize_limit, _("\
15273 Set the maximum number of bytes allowed in a variable-size object."), _("\
15274 Show the maximum number of bytes allowed in a variable-size object."), _("\
15275 Attempts to access an object whose size is not a compile-time constant\n\
15276 and exceeds this limit will cause an error."),
15277 NULL, NULL, &setlist, &showlist);
15278
15279 add_info ("exceptions", info_exceptions_command,
15280 _("\
15281 List all Ada exception names.\n\
15282 Usage: info exceptions [REGEXP]\n\
15283 If a regular expression is passed as an argument, only those matching\n\
15284 the regular expression are listed."));
15285
15286 add_basic_prefix_cmd ("ada", class_maintenance,
15287 _("Set Ada maintenance-related variables."),
15288 &maint_set_ada_cmdlist, "maintenance set ada ",
15289 0/*allow-unknown*/, &maintenance_set_cmdlist);
15290
15291 add_show_prefix_cmd ("ada", class_maintenance,
15292 _("Show Ada maintenance-related variables."),
15293 &maint_show_ada_cmdlist, "maintenance show ada ",
15294 0/*allow-unknown*/, &maintenance_show_cmdlist);
15295
15296 add_setshow_boolean_cmd
15297 ("ignore-descriptive-types", class_maintenance,
15298 &ada_ignore_descriptive_types_p,
15299 _("Set whether descriptive types generated by GNAT should be ignored."),
15300 _("Show whether descriptive types generated by GNAT should be ignored."),
15301 _("\
15302 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
15303 DWARF attribute."),
15304 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
15305
15306 decoded_names_store = htab_create_alloc (256, htab_hash_string, streq_hash,
15307 NULL, xcalloc, xfree);
15308
15309 /* The ada-lang observers. */
15310 gdb::observers::new_objfile.attach (ada_new_objfile_observer);
15311 gdb::observers::free_objfile.attach (ada_free_objfile_observer);
15312 gdb::observers::inferior_exit.attach (ada_inferior_exit);
15313 }
This page took 0.364864 seconds and 5 git commands to generate.