gdb: make get_dyn_prop a method of struct type
[deliverable/binutils-gdb.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2020 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
61 /* Define whether or not the C operator '/' truncates towards zero for
62 differently signed operands (truncation direction is undefined in C).
63 Copied from valarith.c. */
64
65 #ifndef TRUNCATION_TOWARDS_ZERO
66 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
67 #endif
68
69 static struct type *desc_base_type (struct type *);
70
71 static struct type *desc_bounds_type (struct type *);
72
73 static struct value *desc_bounds (struct value *);
74
75 static int fat_pntr_bounds_bitpos (struct type *);
76
77 static int fat_pntr_bounds_bitsize (struct type *);
78
79 static struct type *desc_data_target_type (struct type *);
80
81 static struct value *desc_data (struct value *);
82
83 static int fat_pntr_data_bitpos (struct type *);
84
85 static int fat_pntr_data_bitsize (struct type *);
86
87 static struct value *desc_one_bound (struct value *, int, int);
88
89 static int desc_bound_bitpos (struct type *, int, int);
90
91 static int desc_bound_bitsize (struct type *, int, int);
92
93 static struct type *desc_index_type (struct type *, int);
94
95 static int desc_arity (struct type *);
96
97 static int ada_type_match (struct type *, struct type *, int);
98
99 static int ada_args_match (struct symbol *, struct value **, int);
100
101 static struct value *make_array_descriptor (struct type *, struct value *);
102
103 static void ada_add_block_symbols (struct obstack *,
104 const struct block *,
105 const lookup_name_info &lookup_name,
106 domain_enum, struct objfile *);
107
108 static void ada_add_all_symbols (struct obstack *, const struct block *,
109 const lookup_name_info &lookup_name,
110 domain_enum, int, int *);
111
112 static int is_nonfunction (struct block_symbol *, int);
113
114 static void add_defn_to_vec (struct obstack *, struct symbol *,
115 const struct block *);
116
117 static int num_defns_collected (struct obstack *);
118
119 static struct block_symbol *defns_collected (struct obstack *, int);
120
121 static struct value *resolve_subexp (expression_up *, int *, int,
122 struct type *, int,
123 innermost_block_tracker *);
124
125 static void replace_operator_with_call (expression_up *, int, int, int,
126 struct symbol *, const struct block *);
127
128 static int possible_user_operator_p (enum exp_opcode, struct value **);
129
130 static const char *ada_op_name (enum exp_opcode);
131
132 static const char *ada_decoded_op_name (enum exp_opcode);
133
134 static int numeric_type_p (struct type *);
135
136 static int integer_type_p (struct type *);
137
138 static int scalar_type_p (struct type *);
139
140 static int discrete_type_p (struct type *);
141
142 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
143 int, int);
144
145 static struct value *evaluate_subexp_type (struct expression *, int *);
146
147 static struct type *ada_find_parallel_type_with_name (struct type *,
148 const char *);
149
150 static int is_dynamic_field (struct type *, int);
151
152 static struct type *to_fixed_variant_branch_type (struct type *,
153 const gdb_byte *,
154 CORE_ADDR, struct value *);
155
156 static struct type *to_fixed_array_type (struct type *, struct value *, int);
157
158 static struct type *to_fixed_range_type (struct type *, struct value *);
159
160 static struct type *to_static_fixed_type (struct type *);
161 static struct type *static_unwrap_type (struct type *type);
162
163 static struct value *unwrap_value (struct value *);
164
165 static struct type *constrained_packed_array_type (struct type *, long *);
166
167 static struct type *decode_constrained_packed_array_type (struct type *);
168
169 static long decode_packed_array_bitsize (struct type *);
170
171 static struct value *decode_constrained_packed_array (struct value *);
172
173 static int ada_is_packed_array_type (struct type *);
174
175 static int ada_is_unconstrained_packed_array_type (struct type *);
176
177 static struct value *value_subscript_packed (struct value *, int,
178 struct value **);
179
180 static struct value *coerce_unspec_val_to_type (struct value *,
181 struct type *);
182
183 static int lesseq_defined_than (struct symbol *, struct symbol *);
184
185 static int equiv_types (struct type *, struct type *);
186
187 static int is_name_suffix (const char *);
188
189 static int advance_wild_match (const char **, const char *, int);
190
191 static bool wild_match (const char *name, const char *patn);
192
193 static struct value *ada_coerce_ref (struct value *);
194
195 static LONGEST pos_atr (struct value *);
196
197 static struct value *value_pos_atr (struct type *, struct value *);
198
199 static struct value *value_val_atr (struct type *, struct value *);
200
201 static struct symbol *standard_lookup (const char *, const struct block *,
202 domain_enum);
203
204 static struct value *ada_search_struct_field (const char *, struct value *, int,
205 struct type *);
206
207 static struct value *ada_value_primitive_field (struct value *, int, int,
208 struct type *);
209
210 static int find_struct_field (const char *, struct type *, int,
211 struct type **, int *, int *, int *, int *);
212
213 static int ada_resolve_function (struct block_symbol *, int,
214 struct value **, int, const char *,
215 struct type *, int);
216
217 static int ada_is_direct_array_type (struct type *);
218
219 static void ada_language_arch_info (struct gdbarch *,
220 struct language_arch_info *);
221
222 static struct value *ada_index_struct_field (int, struct value *, int,
223 struct type *);
224
225 static struct value *assign_aggregate (struct value *, struct value *,
226 struct expression *,
227 int *, enum noside);
228
229 static void aggregate_assign_from_choices (struct value *, struct value *,
230 struct expression *,
231 int *, LONGEST *, int *,
232 int, LONGEST, LONGEST);
233
234 static void aggregate_assign_positional (struct value *, struct value *,
235 struct expression *,
236 int *, LONGEST *, int *, int,
237 LONGEST, LONGEST);
238
239
240 static void aggregate_assign_others (struct value *, struct value *,
241 struct expression *,
242 int *, LONGEST *, int, LONGEST, LONGEST);
243
244
245 static void add_component_interval (LONGEST, LONGEST, LONGEST *, int *, int);
246
247
248 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
249 int *, enum noside);
250
251 static void ada_forward_operator_length (struct expression *, int, int *,
252 int *);
253
254 static struct type *ada_find_any_type (const char *name);
255
256 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
257 (const lookup_name_info &lookup_name);
258
259 \f
260
261 /* The result of a symbol lookup to be stored in our symbol cache. */
262
263 struct cache_entry
264 {
265 /* The name used to perform the lookup. */
266 const char *name;
267 /* The namespace used during the lookup. */
268 domain_enum domain;
269 /* The symbol returned by the lookup, or NULL if no matching symbol
270 was found. */
271 struct symbol *sym;
272 /* The block where the symbol was found, or NULL if no matching
273 symbol was found. */
274 const struct block *block;
275 /* A pointer to the next entry with the same hash. */
276 struct cache_entry *next;
277 };
278
279 /* The Ada symbol cache, used to store the result of Ada-mode symbol
280 lookups in the course of executing the user's commands.
281
282 The cache is implemented using a simple, fixed-sized hash.
283 The size is fixed on the grounds that there are not likely to be
284 all that many symbols looked up during any given session, regardless
285 of the size of the symbol table. If we decide to go to a resizable
286 table, let's just use the stuff from libiberty instead. */
287
288 #define HASH_SIZE 1009
289
290 struct ada_symbol_cache
291 {
292 /* An obstack used to store the entries in our cache. */
293 struct obstack cache_space;
294
295 /* The root of the hash table used to implement our symbol cache. */
296 struct cache_entry *root[HASH_SIZE];
297 };
298
299 static void ada_free_symbol_cache (struct ada_symbol_cache *sym_cache);
300
301 /* Maximum-sized dynamic type. */
302 static unsigned int varsize_limit;
303
304 static const char ada_completer_word_break_characters[] =
305 #ifdef VMS
306 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
307 #else
308 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
309 #endif
310
311 /* The name of the symbol to use to get the name of the main subprogram. */
312 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
313 = "__gnat_ada_main_program_name";
314
315 /* Limit on the number of warnings to raise per expression evaluation. */
316 static int warning_limit = 2;
317
318 /* Number of warning messages issued; reset to 0 by cleanups after
319 expression evaluation. */
320 static int warnings_issued = 0;
321
322 static const char *known_runtime_file_name_patterns[] = {
323 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
324 };
325
326 static const char *known_auxiliary_function_name_patterns[] = {
327 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
328 };
329
330 /* Maintenance-related settings for this module. */
331
332 static struct cmd_list_element *maint_set_ada_cmdlist;
333 static struct cmd_list_element *maint_show_ada_cmdlist;
334
335 /* The "maintenance ada set/show ignore-descriptive-type" value. */
336
337 static bool ada_ignore_descriptive_types_p = false;
338
339 /* Inferior-specific data. */
340
341 /* Per-inferior data for this module. */
342
343 struct ada_inferior_data
344 {
345 /* The ada__tags__type_specific_data type, which is used when decoding
346 tagged types. With older versions of GNAT, this type was directly
347 accessible through a component ("tsd") in the object tag. But this
348 is no longer the case, so we cache it for each inferior. */
349 struct type *tsd_type = nullptr;
350
351 /* The exception_support_info data. This data is used to determine
352 how to implement support for Ada exception catchpoints in a given
353 inferior. */
354 const struct exception_support_info *exception_info = nullptr;
355 };
356
357 /* Our key to this module's inferior data. */
358 static const struct inferior_key<ada_inferior_data> ada_inferior_data;
359
360 /* Return our inferior data for the given inferior (INF).
361
362 This function always returns a valid pointer to an allocated
363 ada_inferior_data structure. If INF's inferior data has not
364 been previously set, this functions creates a new one with all
365 fields set to zero, sets INF's inferior to it, and then returns
366 a pointer to that newly allocated ada_inferior_data. */
367
368 static struct ada_inferior_data *
369 get_ada_inferior_data (struct inferior *inf)
370 {
371 struct ada_inferior_data *data;
372
373 data = ada_inferior_data.get (inf);
374 if (data == NULL)
375 data = ada_inferior_data.emplace (inf);
376
377 return data;
378 }
379
380 /* Perform all necessary cleanups regarding our module's inferior data
381 that is required after the inferior INF just exited. */
382
383 static void
384 ada_inferior_exit (struct inferior *inf)
385 {
386 ada_inferior_data.clear (inf);
387 }
388
389
390 /* program-space-specific data. */
391
392 /* This module's per-program-space data. */
393 struct ada_pspace_data
394 {
395 ~ada_pspace_data ()
396 {
397 if (sym_cache != NULL)
398 ada_free_symbol_cache (sym_cache);
399 }
400
401 /* The Ada symbol cache. */
402 struct ada_symbol_cache *sym_cache = nullptr;
403 };
404
405 /* Key to our per-program-space data. */
406 static const struct program_space_key<ada_pspace_data> ada_pspace_data_handle;
407
408 /* Return this module's data for the given program space (PSPACE).
409 If not is found, add a zero'ed one now.
410
411 This function always returns a valid object. */
412
413 static struct ada_pspace_data *
414 get_ada_pspace_data (struct program_space *pspace)
415 {
416 struct ada_pspace_data *data;
417
418 data = ada_pspace_data_handle.get (pspace);
419 if (data == NULL)
420 data = ada_pspace_data_handle.emplace (pspace);
421
422 return data;
423 }
424
425 /* Utilities */
426
427 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
428 all typedef layers have been peeled. Otherwise, return TYPE.
429
430 Normally, we really expect a typedef type to only have 1 typedef layer.
431 In other words, we really expect the target type of a typedef type to be
432 a non-typedef type. This is particularly true for Ada units, because
433 the language does not have a typedef vs not-typedef distinction.
434 In that respect, the Ada compiler has been trying to eliminate as many
435 typedef definitions in the debugging information, since they generally
436 do not bring any extra information (we still use typedef under certain
437 circumstances related mostly to the GNAT encoding).
438
439 Unfortunately, we have seen situations where the debugging information
440 generated by the compiler leads to such multiple typedef layers. For
441 instance, consider the following example with stabs:
442
443 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
444 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
445
446 This is an error in the debugging information which causes type
447 pck__float_array___XUP to be defined twice, and the second time,
448 it is defined as a typedef of a typedef.
449
450 This is on the fringe of legality as far as debugging information is
451 concerned, and certainly unexpected. But it is easy to handle these
452 situations correctly, so we can afford to be lenient in this case. */
453
454 static struct type *
455 ada_typedef_target_type (struct type *type)
456 {
457 while (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
458 type = TYPE_TARGET_TYPE (type);
459 return type;
460 }
461
462 /* Given DECODED_NAME a string holding a symbol name in its
463 decoded form (ie using the Ada dotted notation), returns
464 its unqualified name. */
465
466 static const char *
467 ada_unqualified_name (const char *decoded_name)
468 {
469 const char *result;
470
471 /* If the decoded name starts with '<', it means that the encoded
472 name does not follow standard naming conventions, and thus that
473 it is not your typical Ada symbol name. Trying to unqualify it
474 is therefore pointless and possibly erroneous. */
475 if (decoded_name[0] == '<')
476 return decoded_name;
477
478 result = strrchr (decoded_name, '.');
479 if (result != NULL)
480 result++; /* Skip the dot... */
481 else
482 result = decoded_name;
483
484 return result;
485 }
486
487 /* Return a string starting with '<', followed by STR, and '>'. */
488
489 static std::string
490 add_angle_brackets (const char *str)
491 {
492 return string_printf ("<%s>", str);
493 }
494
495 static const char *
496 ada_get_gdb_completer_word_break_characters (void)
497 {
498 return ada_completer_word_break_characters;
499 }
500
501 /* Print an array element index using the Ada syntax. */
502
503 static void
504 ada_print_array_index (struct value *index_value, struct ui_file *stream,
505 const struct value_print_options *options)
506 {
507 LA_VALUE_PRINT (index_value, stream, options);
508 fprintf_filtered (stream, " => ");
509 }
510
511 /* la_watch_location_expression for Ada. */
512
513 static gdb::unique_xmalloc_ptr<char>
514 ada_watch_location_expression (struct type *type, CORE_ADDR addr)
515 {
516 type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
517 std::string name = type_to_string (type);
518 return gdb::unique_xmalloc_ptr<char>
519 (xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr)));
520 }
521
522 /* Assuming V points to an array of S objects, make sure that it contains at
523 least M objects, updating V and S as necessary. */
524
525 #define GROW_VECT(v, s, m) \
526 if ((s) < (m)) (v) = (char *) grow_vect (v, &(s), m, sizeof *(v));
527
528 /* Assuming VECT points to an array of *SIZE objects of size
529 ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
530 updating *SIZE as necessary and returning the (new) array. */
531
532 static void *
533 grow_vect (void *vect, size_t *size, size_t min_size, int element_size)
534 {
535 if (*size < min_size)
536 {
537 *size *= 2;
538 if (*size < min_size)
539 *size = min_size;
540 vect = xrealloc (vect, *size * element_size);
541 }
542 return vect;
543 }
544
545 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
546 suffix of FIELD_NAME beginning "___". */
547
548 static int
549 field_name_match (const char *field_name, const char *target)
550 {
551 int len = strlen (target);
552
553 return
554 (strncmp (field_name, target, len) == 0
555 && (field_name[len] == '\0'
556 || (startswith (field_name + len, "___")
557 && strcmp (field_name + strlen (field_name) - 6,
558 "___XVN") != 0)));
559 }
560
561
562 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
563 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
564 and return its index. This function also handles fields whose name
565 have ___ suffixes because the compiler sometimes alters their name
566 by adding such a suffix to represent fields with certain constraints.
567 If the field could not be found, return a negative number if
568 MAYBE_MISSING is set. Otherwise raise an error. */
569
570 int
571 ada_get_field_index (const struct type *type, const char *field_name,
572 int maybe_missing)
573 {
574 int fieldno;
575 struct type *struct_type = check_typedef ((struct type *) type);
576
577 for (fieldno = 0; fieldno < TYPE_NFIELDS (struct_type); fieldno++)
578 if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
579 return fieldno;
580
581 if (!maybe_missing)
582 error (_("Unable to find field %s in struct %s. Aborting"),
583 field_name, TYPE_NAME (struct_type));
584
585 return -1;
586 }
587
588 /* The length of the prefix of NAME prior to any "___" suffix. */
589
590 int
591 ada_name_prefix_len (const char *name)
592 {
593 if (name == NULL)
594 return 0;
595 else
596 {
597 const char *p = strstr (name, "___");
598
599 if (p == NULL)
600 return strlen (name);
601 else
602 return p - name;
603 }
604 }
605
606 /* Return non-zero if SUFFIX is a suffix of STR.
607 Return zero if STR is null. */
608
609 static int
610 is_suffix (const char *str, const char *suffix)
611 {
612 int len1, len2;
613
614 if (str == NULL)
615 return 0;
616 len1 = strlen (str);
617 len2 = strlen (suffix);
618 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
619 }
620
621 /* The contents of value VAL, treated as a value of type TYPE. The
622 result is an lval in memory if VAL is. */
623
624 static struct value *
625 coerce_unspec_val_to_type (struct value *val, struct type *type)
626 {
627 type = ada_check_typedef (type);
628 if (value_type (val) == type)
629 return val;
630 else
631 {
632 struct value *result;
633
634 /* Make sure that the object size is not unreasonable before
635 trying to allocate some memory for it. */
636 ada_ensure_varsize_limit (type);
637
638 if (value_lazy (val)
639 || TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val)))
640 result = allocate_value_lazy (type);
641 else
642 {
643 result = allocate_value (type);
644 value_contents_copy_raw (result, 0, val, 0, TYPE_LENGTH (type));
645 }
646 set_value_component_location (result, val);
647 set_value_bitsize (result, value_bitsize (val));
648 set_value_bitpos (result, value_bitpos (val));
649 if (VALUE_LVAL (result) == lval_memory)
650 set_value_address (result, value_address (val));
651 return result;
652 }
653 }
654
655 static const gdb_byte *
656 cond_offset_host (const gdb_byte *valaddr, long offset)
657 {
658 if (valaddr == NULL)
659 return NULL;
660 else
661 return valaddr + offset;
662 }
663
664 static CORE_ADDR
665 cond_offset_target (CORE_ADDR address, long offset)
666 {
667 if (address == 0)
668 return 0;
669 else
670 return address + offset;
671 }
672
673 /* Issue a warning (as for the definition of warning in utils.c, but
674 with exactly one argument rather than ...), unless the limit on the
675 number of warnings has passed during the evaluation of the current
676 expression. */
677
678 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
679 provided by "complaint". */
680 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
681
682 static void
683 lim_warning (const char *format, ...)
684 {
685 va_list args;
686
687 va_start (args, format);
688 warnings_issued += 1;
689 if (warnings_issued <= warning_limit)
690 vwarning (format, args);
691
692 va_end (args);
693 }
694
695 /* Issue an error if the size of an object of type T is unreasonable,
696 i.e. if it would be a bad idea to allocate a value of this type in
697 GDB. */
698
699 void
700 ada_ensure_varsize_limit (const struct type *type)
701 {
702 if (TYPE_LENGTH (type) > varsize_limit)
703 error (_("object size is larger than varsize-limit"));
704 }
705
706 /* Maximum value of a SIZE-byte signed integer type. */
707 static LONGEST
708 max_of_size (int size)
709 {
710 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
711
712 return top_bit | (top_bit - 1);
713 }
714
715 /* Minimum value of a SIZE-byte signed integer type. */
716 static LONGEST
717 min_of_size (int size)
718 {
719 return -max_of_size (size) - 1;
720 }
721
722 /* Maximum value of a SIZE-byte unsigned integer type. */
723 static ULONGEST
724 umax_of_size (int size)
725 {
726 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
727
728 return top_bit | (top_bit - 1);
729 }
730
731 /* Maximum value of integral type T, as a signed quantity. */
732 static LONGEST
733 max_of_type (struct type *t)
734 {
735 if (TYPE_UNSIGNED (t))
736 return (LONGEST) umax_of_size (TYPE_LENGTH (t));
737 else
738 return max_of_size (TYPE_LENGTH (t));
739 }
740
741 /* Minimum value of integral type T, as a signed quantity. */
742 static LONGEST
743 min_of_type (struct type *t)
744 {
745 if (TYPE_UNSIGNED (t))
746 return 0;
747 else
748 return min_of_size (TYPE_LENGTH (t));
749 }
750
751 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
752 LONGEST
753 ada_discrete_type_high_bound (struct type *type)
754 {
755 type = resolve_dynamic_type (type, {}, 0);
756 switch (TYPE_CODE (type))
757 {
758 case TYPE_CODE_RANGE:
759 return TYPE_HIGH_BOUND (type);
760 case TYPE_CODE_ENUM:
761 return TYPE_FIELD_ENUMVAL (type, TYPE_NFIELDS (type) - 1);
762 case TYPE_CODE_BOOL:
763 return 1;
764 case TYPE_CODE_CHAR:
765 case TYPE_CODE_INT:
766 return max_of_type (type);
767 default:
768 error (_("Unexpected type in ada_discrete_type_high_bound."));
769 }
770 }
771
772 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
773 LONGEST
774 ada_discrete_type_low_bound (struct type *type)
775 {
776 type = resolve_dynamic_type (type, {}, 0);
777 switch (TYPE_CODE (type))
778 {
779 case TYPE_CODE_RANGE:
780 return TYPE_LOW_BOUND (type);
781 case TYPE_CODE_ENUM:
782 return TYPE_FIELD_ENUMVAL (type, 0);
783 case TYPE_CODE_BOOL:
784 return 0;
785 case TYPE_CODE_CHAR:
786 case TYPE_CODE_INT:
787 return min_of_type (type);
788 default:
789 error (_("Unexpected type in ada_discrete_type_low_bound."));
790 }
791 }
792
793 /* The identity on non-range types. For range types, the underlying
794 non-range scalar type. */
795
796 static struct type *
797 get_base_type (struct type *type)
798 {
799 while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
800 {
801 if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
802 return type;
803 type = TYPE_TARGET_TYPE (type);
804 }
805 return type;
806 }
807
808 /* Return a decoded version of the given VALUE. This means returning
809 a value whose type is obtained by applying all the GNAT-specific
810 encodings, making the resulting type a static but standard description
811 of the initial type. */
812
813 struct value *
814 ada_get_decoded_value (struct value *value)
815 {
816 struct type *type = ada_check_typedef (value_type (value));
817
818 if (ada_is_array_descriptor_type (type)
819 || (ada_is_constrained_packed_array_type (type)
820 && TYPE_CODE (type) != TYPE_CODE_PTR))
821 {
822 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF) /* array access type. */
823 value = ada_coerce_to_simple_array_ptr (value);
824 else
825 value = ada_coerce_to_simple_array (value);
826 }
827 else
828 value = ada_to_fixed_value (value);
829
830 return value;
831 }
832
833 /* Same as ada_get_decoded_value, but with the given TYPE.
834 Because there is no associated actual value for this type,
835 the resulting type might be a best-effort approximation in
836 the case of dynamic types. */
837
838 struct type *
839 ada_get_decoded_type (struct type *type)
840 {
841 type = to_static_fixed_type (type);
842 if (ada_is_constrained_packed_array_type (type))
843 type = ada_coerce_to_simple_array_type (type);
844 return type;
845 }
846
847 \f
848
849 /* Language Selection */
850
851 /* If the main program is in Ada, return language_ada, otherwise return LANG
852 (the main program is in Ada iif the adainit symbol is found). */
853
854 static enum language
855 ada_update_initial_language (enum language lang)
856 {
857 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
858 return language_ada;
859
860 return lang;
861 }
862
863 /* If the main procedure is written in Ada, then return its name.
864 The result is good until the next call. Return NULL if the main
865 procedure doesn't appear to be in Ada. */
866
867 char *
868 ada_main_name (void)
869 {
870 struct bound_minimal_symbol msym;
871 static gdb::unique_xmalloc_ptr<char> main_program_name;
872
873 /* For Ada, the name of the main procedure is stored in a specific
874 string constant, generated by the binder. Look for that symbol,
875 extract its address, and then read that string. If we didn't find
876 that string, then most probably the main procedure is not written
877 in Ada. */
878 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
879
880 if (msym.minsym != NULL)
881 {
882 CORE_ADDR main_program_name_addr;
883 int err_code;
884
885 main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
886 if (main_program_name_addr == 0)
887 error (_("Invalid address for Ada main program name."));
888
889 target_read_string (main_program_name_addr, &main_program_name,
890 1024, &err_code);
891
892 if (err_code != 0)
893 return NULL;
894 return main_program_name.get ();
895 }
896
897 /* The main procedure doesn't seem to be in Ada. */
898 return NULL;
899 }
900 \f
901 /* Symbols */
902
903 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
904 of NULLs. */
905
906 const struct ada_opname_map ada_opname_table[] = {
907 {"Oadd", "\"+\"", BINOP_ADD},
908 {"Osubtract", "\"-\"", BINOP_SUB},
909 {"Omultiply", "\"*\"", BINOP_MUL},
910 {"Odivide", "\"/\"", BINOP_DIV},
911 {"Omod", "\"mod\"", BINOP_MOD},
912 {"Orem", "\"rem\"", BINOP_REM},
913 {"Oexpon", "\"**\"", BINOP_EXP},
914 {"Olt", "\"<\"", BINOP_LESS},
915 {"Ole", "\"<=\"", BINOP_LEQ},
916 {"Ogt", "\">\"", BINOP_GTR},
917 {"Oge", "\">=\"", BINOP_GEQ},
918 {"Oeq", "\"=\"", BINOP_EQUAL},
919 {"One", "\"/=\"", BINOP_NOTEQUAL},
920 {"Oand", "\"and\"", BINOP_BITWISE_AND},
921 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
922 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
923 {"Oconcat", "\"&\"", BINOP_CONCAT},
924 {"Oabs", "\"abs\"", UNOP_ABS},
925 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
926 {"Oadd", "\"+\"", UNOP_PLUS},
927 {"Osubtract", "\"-\"", UNOP_NEG},
928 {NULL, NULL}
929 };
930
931 /* The "encoded" form of DECODED, according to GNAT conventions. The
932 result is valid until the next call to ada_encode. If
933 THROW_ERRORS, throw an error if invalid operator name is found.
934 Otherwise, return NULL in that case. */
935
936 static char *
937 ada_encode_1 (const char *decoded, bool throw_errors)
938 {
939 static char *encoding_buffer = NULL;
940 static size_t encoding_buffer_size = 0;
941 const char *p;
942 int k;
943
944 if (decoded == NULL)
945 return NULL;
946
947 GROW_VECT (encoding_buffer, encoding_buffer_size,
948 2 * strlen (decoded) + 10);
949
950 k = 0;
951 for (p = decoded; *p != '\0'; p += 1)
952 {
953 if (*p == '.')
954 {
955 encoding_buffer[k] = encoding_buffer[k + 1] = '_';
956 k += 2;
957 }
958 else if (*p == '"')
959 {
960 const struct ada_opname_map *mapping;
961
962 for (mapping = ada_opname_table;
963 mapping->encoded != NULL
964 && !startswith (p, mapping->decoded); mapping += 1)
965 ;
966 if (mapping->encoded == NULL)
967 {
968 if (throw_errors)
969 error (_("invalid Ada operator name: %s"), p);
970 else
971 return NULL;
972 }
973 strcpy (encoding_buffer + k, mapping->encoded);
974 k += strlen (mapping->encoded);
975 break;
976 }
977 else
978 {
979 encoding_buffer[k] = *p;
980 k += 1;
981 }
982 }
983
984 encoding_buffer[k] = '\0';
985 return encoding_buffer;
986 }
987
988 /* The "encoded" form of DECODED, according to GNAT conventions.
989 The result is valid until the next call to ada_encode. */
990
991 char *
992 ada_encode (const char *decoded)
993 {
994 return ada_encode_1 (decoded, true);
995 }
996
997 /* Return NAME folded to lower case, or, if surrounded by single
998 quotes, unfolded, but with the quotes stripped away. Result good
999 to next call. */
1000
1001 static char *
1002 ada_fold_name (gdb::string_view name)
1003 {
1004 static char *fold_buffer = NULL;
1005 static size_t fold_buffer_size = 0;
1006
1007 int len = name.size ();
1008 GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
1009
1010 if (name[0] == '\'')
1011 {
1012 strncpy (fold_buffer, name.data () + 1, len - 2);
1013 fold_buffer[len - 2] = '\000';
1014 }
1015 else
1016 {
1017 int i;
1018
1019 for (i = 0; i <= len; i += 1)
1020 fold_buffer[i] = tolower (name[i]);
1021 }
1022
1023 return fold_buffer;
1024 }
1025
1026 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1027
1028 static int
1029 is_lower_alphanum (const char c)
1030 {
1031 return (isdigit (c) || (isalpha (c) && islower (c)));
1032 }
1033
1034 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1035 This function saves in LEN the length of that same symbol name but
1036 without either of these suffixes:
1037 . .{DIGIT}+
1038 . ${DIGIT}+
1039 . ___{DIGIT}+
1040 . __{DIGIT}+.
1041
1042 These are suffixes introduced by the compiler for entities such as
1043 nested subprogram for instance, in order to avoid name clashes.
1044 They do not serve any purpose for the debugger. */
1045
1046 static void
1047 ada_remove_trailing_digits (const char *encoded, int *len)
1048 {
1049 if (*len > 1 && isdigit (encoded[*len - 1]))
1050 {
1051 int i = *len - 2;
1052
1053 while (i > 0 && isdigit (encoded[i]))
1054 i--;
1055 if (i >= 0 && encoded[i] == '.')
1056 *len = i;
1057 else if (i >= 0 && encoded[i] == '$')
1058 *len = i;
1059 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1060 *len = i - 2;
1061 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1062 *len = i - 1;
1063 }
1064 }
1065
1066 /* Remove the suffix introduced by the compiler for protected object
1067 subprograms. */
1068
1069 static void
1070 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1071 {
1072 /* Remove trailing N. */
1073
1074 /* Protected entry subprograms are broken into two
1075 separate subprograms: The first one is unprotected, and has
1076 a 'N' suffix; the second is the protected version, and has
1077 the 'P' suffix. The second calls the first one after handling
1078 the protection. Since the P subprograms are internally generated,
1079 we leave these names undecoded, giving the user a clue that this
1080 entity is internal. */
1081
1082 if (*len > 1
1083 && encoded[*len - 1] == 'N'
1084 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1085 *len = *len - 1;
1086 }
1087
1088 /* If ENCODED follows the GNAT entity encoding conventions, then return
1089 the decoded form of ENCODED. Otherwise, return "<%s>" where "%s" is
1090 replaced by ENCODED. */
1091
1092 std::string
1093 ada_decode (const char *encoded)
1094 {
1095 int i, j;
1096 int len0;
1097 const char *p;
1098 int at_start_name;
1099 std::string decoded;
1100
1101 /* With function descriptors on PPC64, the value of a symbol named
1102 ".FN", if it exists, is the entry point of the function "FN". */
1103 if (encoded[0] == '.')
1104 encoded += 1;
1105
1106 /* The name of the Ada main procedure starts with "_ada_".
1107 This prefix is not part of the decoded name, so skip this part
1108 if we see this prefix. */
1109 if (startswith (encoded, "_ada_"))
1110 encoded += 5;
1111
1112 /* If the name starts with '_', then it is not a properly encoded
1113 name, so do not attempt to decode it. Similarly, if the name
1114 starts with '<', the name should not be decoded. */
1115 if (encoded[0] == '_' || encoded[0] == '<')
1116 goto Suppress;
1117
1118 len0 = strlen (encoded);
1119
1120 ada_remove_trailing_digits (encoded, &len0);
1121 ada_remove_po_subprogram_suffix (encoded, &len0);
1122
1123 /* Remove the ___X.* suffix if present. Do not forget to verify that
1124 the suffix is located before the current "end" of ENCODED. We want
1125 to avoid re-matching parts of ENCODED that have previously been
1126 marked as discarded (by decrementing LEN0). */
1127 p = strstr (encoded, "___");
1128 if (p != NULL && p - encoded < len0 - 3)
1129 {
1130 if (p[3] == 'X')
1131 len0 = p - encoded;
1132 else
1133 goto Suppress;
1134 }
1135
1136 /* Remove any trailing TKB suffix. It tells us that this symbol
1137 is for the body of a task, but that information does not actually
1138 appear in the decoded name. */
1139
1140 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1141 len0 -= 3;
1142
1143 /* Remove any trailing TB suffix. The TB suffix is slightly different
1144 from the TKB suffix because it is used for non-anonymous task
1145 bodies. */
1146
1147 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1148 len0 -= 2;
1149
1150 /* Remove trailing "B" suffixes. */
1151 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1152
1153 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1154 len0 -= 1;
1155
1156 /* Make decoded big enough for possible expansion by operator name. */
1157
1158 decoded.resize (2 * len0 + 1, 'X');
1159
1160 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1161
1162 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1163 {
1164 i = len0 - 2;
1165 while ((i >= 0 && isdigit (encoded[i]))
1166 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1167 i -= 1;
1168 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1169 len0 = i - 1;
1170 else if (encoded[i] == '$')
1171 len0 = i;
1172 }
1173
1174 /* The first few characters that are not alphabetic are not part
1175 of any encoding we use, so we can copy them over verbatim. */
1176
1177 for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1178 decoded[j] = encoded[i];
1179
1180 at_start_name = 1;
1181 while (i < len0)
1182 {
1183 /* Is this a symbol function? */
1184 if (at_start_name && encoded[i] == 'O')
1185 {
1186 int k;
1187
1188 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1189 {
1190 int op_len = strlen (ada_opname_table[k].encoded);
1191 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1192 op_len - 1) == 0)
1193 && !isalnum (encoded[i + op_len]))
1194 {
1195 strcpy (&decoded.front() + j, ada_opname_table[k].decoded);
1196 at_start_name = 0;
1197 i += op_len;
1198 j += strlen (ada_opname_table[k].decoded);
1199 break;
1200 }
1201 }
1202 if (ada_opname_table[k].encoded != NULL)
1203 continue;
1204 }
1205 at_start_name = 0;
1206
1207 /* Replace "TK__" with "__", which will eventually be translated
1208 into "." (just below). */
1209
1210 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1211 i += 2;
1212
1213 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1214 be translated into "." (just below). These are internal names
1215 generated for anonymous blocks inside which our symbol is nested. */
1216
1217 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1218 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1219 && isdigit (encoded [i+4]))
1220 {
1221 int k = i + 5;
1222
1223 while (k < len0 && isdigit (encoded[k]))
1224 k++; /* Skip any extra digit. */
1225
1226 /* Double-check that the "__B_{DIGITS}+" sequence we found
1227 is indeed followed by "__". */
1228 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1229 i = k;
1230 }
1231
1232 /* Remove _E{DIGITS}+[sb] */
1233
1234 /* Just as for protected object subprograms, there are 2 categories
1235 of subprograms created by the compiler for each entry. The first
1236 one implements the actual entry code, and has a suffix following
1237 the convention above; the second one implements the barrier and
1238 uses the same convention as above, except that the 'E' is replaced
1239 by a 'B'.
1240
1241 Just as above, we do not decode the name of barrier functions
1242 to give the user a clue that the code he is debugging has been
1243 internally generated. */
1244
1245 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1246 && isdigit (encoded[i+2]))
1247 {
1248 int k = i + 3;
1249
1250 while (k < len0 && isdigit (encoded[k]))
1251 k++;
1252
1253 if (k < len0
1254 && (encoded[k] == 'b' || encoded[k] == 's'))
1255 {
1256 k++;
1257 /* Just as an extra precaution, make sure that if this
1258 suffix is followed by anything else, it is a '_'.
1259 Otherwise, we matched this sequence by accident. */
1260 if (k == len0
1261 || (k < len0 && encoded[k] == '_'))
1262 i = k;
1263 }
1264 }
1265
1266 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1267 the GNAT front-end in protected object subprograms. */
1268
1269 if (i < len0 + 3
1270 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1271 {
1272 /* Backtrack a bit up until we reach either the begining of
1273 the encoded name, or "__". Make sure that we only find
1274 digits or lowercase characters. */
1275 const char *ptr = encoded + i - 1;
1276
1277 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1278 ptr--;
1279 if (ptr < encoded
1280 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1281 i++;
1282 }
1283
1284 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1285 {
1286 /* This is a X[bn]* sequence not separated from the previous
1287 part of the name with a non-alpha-numeric character (in other
1288 words, immediately following an alpha-numeric character), then
1289 verify that it is placed at the end of the encoded name. If
1290 not, then the encoding is not valid and we should abort the
1291 decoding. Otherwise, just skip it, it is used in body-nested
1292 package names. */
1293 do
1294 i += 1;
1295 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1296 if (i < len0)
1297 goto Suppress;
1298 }
1299 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1300 {
1301 /* Replace '__' by '.'. */
1302 decoded[j] = '.';
1303 at_start_name = 1;
1304 i += 2;
1305 j += 1;
1306 }
1307 else
1308 {
1309 /* It's a character part of the decoded name, so just copy it
1310 over. */
1311 decoded[j] = encoded[i];
1312 i += 1;
1313 j += 1;
1314 }
1315 }
1316 decoded.resize (j);
1317
1318 /* Decoded names should never contain any uppercase character.
1319 Double-check this, and abort the decoding if we find one. */
1320
1321 for (i = 0; i < decoded.length(); ++i)
1322 if (isupper (decoded[i]) || decoded[i] == ' ')
1323 goto Suppress;
1324
1325 return decoded;
1326
1327 Suppress:
1328 if (encoded[0] == '<')
1329 decoded = encoded;
1330 else
1331 decoded = '<' + std::string(encoded) + '>';
1332 return decoded;
1333
1334 }
1335
1336 /* Table for keeping permanent unique copies of decoded names. Once
1337 allocated, names in this table are never released. While this is a
1338 storage leak, it should not be significant unless there are massive
1339 changes in the set of decoded names in successive versions of a
1340 symbol table loaded during a single session. */
1341 static struct htab *decoded_names_store;
1342
1343 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1344 in the language-specific part of GSYMBOL, if it has not been
1345 previously computed. Tries to save the decoded name in the same
1346 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1347 in any case, the decoded symbol has a lifetime at least that of
1348 GSYMBOL).
1349 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1350 const, but nevertheless modified to a semantically equivalent form
1351 when a decoded name is cached in it. */
1352
1353 const char *
1354 ada_decode_symbol (const struct general_symbol_info *arg)
1355 {
1356 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1357 const char **resultp =
1358 &gsymbol->language_specific.demangled_name;
1359
1360 if (!gsymbol->ada_mangled)
1361 {
1362 std::string decoded = ada_decode (gsymbol->linkage_name ());
1363 struct obstack *obstack = gsymbol->language_specific.obstack;
1364
1365 gsymbol->ada_mangled = 1;
1366
1367 if (obstack != NULL)
1368 *resultp = obstack_strdup (obstack, decoded.c_str ());
1369 else
1370 {
1371 /* Sometimes, we can't find a corresponding objfile, in
1372 which case, we put the result on the heap. Since we only
1373 decode when needed, we hope this usually does not cause a
1374 significant memory leak (FIXME). */
1375
1376 char **slot = (char **) htab_find_slot (decoded_names_store,
1377 decoded.c_str (), INSERT);
1378
1379 if (*slot == NULL)
1380 *slot = xstrdup (decoded.c_str ());
1381 *resultp = *slot;
1382 }
1383 }
1384
1385 return *resultp;
1386 }
1387
1388 static char *
1389 ada_la_decode (const char *encoded, int options)
1390 {
1391 return xstrdup (ada_decode (encoded).c_str ());
1392 }
1393
1394 /* Implement la_sniff_from_mangled_name for Ada. */
1395
1396 static int
1397 ada_sniff_from_mangled_name (const char *mangled, char **out)
1398 {
1399 std::string demangled = ada_decode (mangled);
1400
1401 *out = NULL;
1402
1403 if (demangled != mangled && demangled[0] != '<')
1404 {
1405 /* Set the gsymbol language to Ada, but still return 0.
1406 Two reasons for that:
1407
1408 1. For Ada, we prefer computing the symbol's decoded name
1409 on the fly rather than pre-compute it, in order to save
1410 memory (Ada projects are typically very large).
1411
1412 2. There are some areas in the definition of the GNAT
1413 encoding where, with a bit of bad luck, we might be able
1414 to decode a non-Ada symbol, generating an incorrect
1415 demangled name (Eg: names ending with "TB" for instance
1416 are identified as task bodies and so stripped from
1417 the decoded name returned).
1418
1419 Returning 1, here, but not setting *DEMANGLED, helps us get a
1420 little bit of the best of both worlds. Because we're last,
1421 we should not affect any of the other languages that were
1422 able to demangle the symbol before us; we get to correctly
1423 tag Ada symbols as such; and even if we incorrectly tagged a
1424 non-Ada symbol, which should be rare, any routing through the
1425 Ada language should be transparent (Ada tries to behave much
1426 like C/C++ with non-Ada symbols). */
1427 return 1;
1428 }
1429
1430 return 0;
1431 }
1432
1433 \f
1434
1435 /* Arrays */
1436
1437 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1438 generated by the GNAT compiler to describe the index type used
1439 for each dimension of an array, check whether it follows the latest
1440 known encoding. If not, fix it up to conform to the latest encoding.
1441 Otherwise, do nothing. This function also does nothing if
1442 INDEX_DESC_TYPE is NULL.
1443
1444 The GNAT encoding used to describe the array index type evolved a bit.
1445 Initially, the information would be provided through the name of each
1446 field of the structure type only, while the type of these fields was
1447 described as unspecified and irrelevant. The debugger was then expected
1448 to perform a global type lookup using the name of that field in order
1449 to get access to the full index type description. Because these global
1450 lookups can be very expensive, the encoding was later enhanced to make
1451 the global lookup unnecessary by defining the field type as being
1452 the full index type description.
1453
1454 The purpose of this routine is to allow us to support older versions
1455 of the compiler by detecting the use of the older encoding, and by
1456 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1457 we essentially replace each field's meaningless type by the associated
1458 index subtype). */
1459
1460 void
1461 ada_fixup_array_indexes_type (struct type *index_desc_type)
1462 {
1463 int i;
1464
1465 if (index_desc_type == NULL)
1466 return;
1467 gdb_assert (TYPE_NFIELDS (index_desc_type) > 0);
1468
1469 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1470 to check one field only, no need to check them all). If not, return
1471 now.
1472
1473 If our INDEX_DESC_TYPE was generated using the older encoding,
1474 the field type should be a meaningless integer type whose name
1475 is not equal to the field name. */
1476 if (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)) != NULL
1477 && strcmp (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)),
1478 TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
1479 return;
1480
1481 /* Fixup each field of INDEX_DESC_TYPE. */
1482 for (i = 0; i < TYPE_NFIELDS (index_desc_type); i++)
1483 {
1484 const char *name = TYPE_FIELD_NAME (index_desc_type, i);
1485 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1486
1487 if (raw_type)
1488 TYPE_FIELD_TYPE (index_desc_type, i) = raw_type;
1489 }
1490 }
1491
1492 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors. */
1493
1494 static const char *bound_name[] = {
1495 "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
1496 "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
1497 };
1498
1499 /* Maximum number of array dimensions we are prepared to handle. */
1500
1501 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))
1502
1503
1504 /* The desc_* routines return primitive portions of array descriptors
1505 (fat pointers). */
1506
1507 /* The descriptor or array type, if any, indicated by TYPE; removes
1508 level of indirection, if needed. */
1509
1510 static struct type *
1511 desc_base_type (struct type *type)
1512 {
1513 if (type == NULL)
1514 return NULL;
1515 type = ada_check_typedef (type);
1516 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
1517 type = ada_typedef_target_type (type);
1518
1519 if (type != NULL
1520 && (TYPE_CODE (type) == TYPE_CODE_PTR
1521 || TYPE_CODE (type) == TYPE_CODE_REF))
1522 return ada_check_typedef (TYPE_TARGET_TYPE (type));
1523 else
1524 return type;
1525 }
1526
1527 /* True iff TYPE indicates a "thin" array pointer type. */
1528
1529 static int
1530 is_thin_pntr (struct type *type)
1531 {
1532 return
1533 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1534 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1535 }
1536
1537 /* The descriptor type for thin pointer type TYPE. */
1538
1539 static struct type *
1540 thin_descriptor_type (struct type *type)
1541 {
1542 struct type *base_type = desc_base_type (type);
1543
1544 if (base_type == NULL)
1545 return NULL;
1546 if (is_suffix (ada_type_name (base_type), "___XVE"))
1547 return base_type;
1548 else
1549 {
1550 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1551
1552 if (alt_type == NULL)
1553 return base_type;
1554 else
1555 return alt_type;
1556 }
1557 }
1558
1559 /* A pointer to the array data for thin-pointer value VAL. */
1560
1561 static struct value *
1562 thin_data_pntr (struct value *val)
1563 {
1564 struct type *type = ada_check_typedef (value_type (val));
1565 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1566
1567 data_type = lookup_pointer_type (data_type);
1568
1569 if (TYPE_CODE (type) == TYPE_CODE_PTR)
1570 return value_cast (data_type, value_copy (val));
1571 else
1572 return value_from_longest (data_type, value_address (val));
1573 }
1574
1575 /* True iff TYPE indicates a "thick" array pointer type. */
1576
1577 static int
1578 is_thick_pntr (struct type *type)
1579 {
1580 type = desc_base_type (type);
1581 return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
1582 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1583 }
1584
1585 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1586 pointer to one, the type of its bounds data; otherwise, NULL. */
1587
1588 static struct type *
1589 desc_bounds_type (struct type *type)
1590 {
1591 struct type *r;
1592
1593 type = desc_base_type (type);
1594
1595 if (type == NULL)
1596 return NULL;
1597 else if (is_thin_pntr (type))
1598 {
1599 type = thin_descriptor_type (type);
1600 if (type == NULL)
1601 return NULL;
1602 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1603 if (r != NULL)
1604 return ada_check_typedef (r);
1605 }
1606 else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1607 {
1608 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1609 if (r != NULL)
1610 return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1611 }
1612 return NULL;
1613 }
1614
1615 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1616 one, a pointer to its bounds data. Otherwise NULL. */
1617
1618 static struct value *
1619 desc_bounds (struct value *arr)
1620 {
1621 struct type *type = ada_check_typedef (value_type (arr));
1622
1623 if (is_thin_pntr (type))
1624 {
1625 struct type *bounds_type =
1626 desc_bounds_type (thin_descriptor_type (type));
1627 LONGEST addr;
1628
1629 if (bounds_type == NULL)
1630 error (_("Bad GNAT array descriptor"));
1631
1632 /* NOTE: The following calculation is not really kosher, but
1633 since desc_type is an XVE-encoded type (and shouldn't be),
1634 the correct calculation is a real pain. FIXME (and fix GCC). */
1635 if (TYPE_CODE (type) == TYPE_CODE_PTR)
1636 addr = value_as_long (arr);
1637 else
1638 addr = value_address (arr);
1639
1640 return
1641 value_from_longest (lookup_pointer_type (bounds_type),
1642 addr - TYPE_LENGTH (bounds_type));
1643 }
1644
1645 else if (is_thick_pntr (type))
1646 {
1647 struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1648 _("Bad GNAT array descriptor"));
1649 struct type *p_bounds_type = value_type (p_bounds);
1650
1651 if (p_bounds_type
1652 && TYPE_CODE (p_bounds_type) == TYPE_CODE_PTR)
1653 {
1654 struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1655
1656 if (TYPE_STUB (target_type))
1657 p_bounds = value_cast (lookup_pointer_type
1658 (ada_check_typedef (target_type)),
1659 p_bounds);
1660 }
1661 else
1662 error (_("Bad GNAT array descriptor"));
1663
1664 return p_bounds;
1665 }
1666 else
1667 return NULL;
1668 }
1669
1670 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1671 position of the field containing the address of the bounds data. */
1672
1673 static int
1674 fat_pntr_bounds_bitpos (struct type *type)
1675 {
1676 return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1677 }
1678
1679 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1680 size of the field containing the address of the bounds data. */
1681
1682 static int
1683 fat_pntr_bounds_bitsize (struct type *type)
1684 {
1685 type = desc_base_type (type);
1686
1687 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1688 return TYPE_FIELD_BITSIZE (type, 1);
1689 else
1690 return 8 * TYPE_LENGTH (ada_check_typedef (TYPE_FIELD_TYPE (type, 1)));
1691 }
1692
1693 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1694 pointer to one, the type of its array data (a array-with-no-bounds type);
1695 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1696 data. */
1697
1698 static struct type *
1699 desc_data_target_type (struct type *type)
1700 {
1701 type = desc_base_type (type);
1702
1703 /* NOTE: The following is bogus; see comment in desc_bounds. */
1704 if (is_thin_pntr (type))
1705 return desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1));
1706 else if (is_thick_pntr (type))
1707 {
1708 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1709
1710 if (data_type
1711 && TYPE_CODE (ada_check_typedef (data_type)) == TYPE_CODE_PTR)
1712 return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1713 }
1714
1715 return NULL;
1716 }
1717
1718 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1719 its array data. */
1720
1721 static struct value *
1722 desc_data (struct value *arr)
1723 {
1724 struct type *type = value_type (arr);
1725
1726 if (is_thin_pntr (type))
1727 return thin_data_pntr (arr);
1728 else if (is_thick_pntr (type))
1729 return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1730 _("Bad GNAT array descriptor"));
1731 else
1732 return NULL;
1733 }
1734
1735
1736 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1737 position of the field containing the address of the data. */
1738
1739 static int
1740 fat_pntr_data_bitpos (struct type *type)
1741 {
1742 return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1743 }
1744
1745 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1746 size of the field containing the address of the data. */
1747
1748 static int
1749 fat_pntr_data_bitsize (struct type *type)
1750 {
1751 type = desc_base_type (type);
1752
1753 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1754 return TYPE_FIELD_BITSIZE (type, 0);
1755 else
1756 return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
1757 }
1758
1759 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1760 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1761 bound, if WHICH is 1. The first bound is I=1. */
1762
1763 static struct value *
1764 desc_one_bound (struct value *bounds, int i, int which)
1765 {
1766 return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
1767 _("Bad GNAT array descriptor bounds"));
1768 }
1769
1770 /* If BOUNDS is an array-bounds structure type, return the bit position
1771 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1772 bound, if WHICH is 1. The first bound is I=1. */
1773
1774 static int
1775 desc_bound_bitpos (struct type *type, int i, int which)
1776 {
1777 return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1778 }
1779
1780 /* If BOUNDS is an array-bounds structure type, return the bit field size
1781 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1782 bound, if WHICH is 1. The first bound is I=1. */
1783
1784 static int
1785 desc_bound_bitsize (struct type *type, int i, int which)
1786 {
1787 type = desc_base_type (type);
1788
1789 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1790 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1791 else
1792 return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
1793 }
1794
1795 /* If TYPE is the type of an array-bounds structure, the type of its
1796 Ith bound (numbering from 1). Otherwise, NULL. */
1797
1798 static struct type *
1799 desc_index_type (struct type *type, int i)
1800 {
1801 type = desc_base_type (type);
1802
1803 if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1804 return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
1805 else
1806 return NULL;
1807 }
1808
1809 /* The number of index positions in the array-bounds type TYPE.
1810 Return 0 if TYPE is NULL. */
1811
1812 static int
1813 desc_arity (struct type *type)
1814 {
1815 type = desc_base_type (type);
1816
1817 if (type != NULL)
1818 return TYPE_NFIELDS (type) / 2;
1819 return 0;
1820 }
1821
1822 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
1823 an array descriptor type (representing an unconstrained array
1824 type). */
1825
1826 static int
1827 ada_is_direct_array_type (struct type *type)
1828 {
1829 if (type == NULL)
1830 return 0;
1831 type = ada_check_typedef (type);
1832 return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1833 || ada_is_array_descriptor_type (type));
1834 }
1835
1836 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1837 * to one. */
1838
1839 static int
1840 ada_is_array_type (struct type *type)
1841 {
1842 while (type != NULL
1843 && (TYPE_CODE (type) == TYPE_CODE_PTR
1844 || TYPE_CODE (type) == TYPE_CODE_REF))
1845 type = TYPE_TARGET_TYPE (type);
1846 return ada_is_direct_array_type (type);
1847 }
1848
1849 /* Non-zero iff TYPE is a simple array type or pointer to one. */
1850
1851 int
1852 ada_is_simple_array_type (struct type *type)
1853 {
1854 if (type == NULL)
1855 return 0;
1856 type = ada_check_typedef (type);
1857 return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1858 || (TYPE_CODE (type) == TYPE_CODE_PTR
1859 && TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type)))
1860 == TYPE_CODE_ARRAY));
1861 }
1862
1863 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
1864
1865 int
1866 ada_is_array_descriptor_type (struct type *type)
1867 {
1868 struct type *data_type = desc_data_target_type (type);
1869
1870 if (type == NULL)
1871 return 0;
1872 type = ada_check_typedef (type);
1873 return (data_type != NULL
1874 && TYPE_CODE (data_type) == TYPE_CODE_ARRAY
1875 && desc_arity (desc_bounds_type (type)) > 0);
1876 }
1877
1878 /* Non-zero iff type is a partially mal-formed GNAT array
1879 descriptor. FIXME: This is to compensate for some problems with
1880 debugging output from GNAT. Re-examine periodically to see if it
1881 is still needed. */
1882
1883 int
1884 ada_is_bogus_array_descriptor (struct type *type)
1885 {
1886 return
1887 type != NULL
1888 && TYPE_CODE (type) == TYPE_CODE_STRUCT
1889 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1890 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1891 && !ada_is_array_descriptor_type (type);
1892 }
1893
1894
1895 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1896 (fat pointer) returns the type of the array data described---specifically,
1897 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
1898 in from the descriptor; otherwise, they are left unspecified. If
1899 the ARR denotes a null array descriptor and BOUNDS is non-zero,
1900 returns NULL. The result is simply the type of ARR if ARR is not
1901 a descriptor. */
1902
1903 static struct type *
1904 ada_type_of_array (struct value *arr, int bounds)
1905 {
1906 if (ada_is_constrained_packed_array_type (value_type (arr)))
1907 return decode_constrained_packed_array_type (value_type (arr));
1908
1909 if (!ada_is_array_descriptor_type (value_type (arr)))
1910 return value_type (arr);
1911
1912 if (!bounds)
1913 {
1914 struct type *array_type =
1915 ada_check_typedef (desc_data_target_type (value_type (arr)));
1916
1917 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1918 TYPE_FIELD_BITSIZE (array_type, 0) =
1919 decode_packed_array_bitsize (value_type (arr));
1920
1921 return array_type;
1922 }
1923 else
1924 {
1925 struct type *elt_type;
1926 int arity;
1927 struct value *descriptor;
1928
1929 elt_type = ada_array_element_type (value_type (arr), -1);
1930 arity = ada_array_arity (value_type (arr));
1931
1932 if (elt_type == NULL || arity == 0)
1933 return ada_check_typedef (value_type (arr));
1934
1935 descriptor = desc_bounds (arr);
1936 if (value_as_long (descriptor) == 0)
1937 return NULL;
1938 while (arity > 0)
1939 {
1940 struct type *range_type = alloc_type_copy (value_type (arr));
1941 struct type *array_type = alloc_type_copy (value_type (arr));
1942 struct value *low = desc_one_bound (descriptor, arity, 0);
1943 struct value *high = desc_one_bound (descriptor, arity, 1);
1944
1945 arity -= 1;
1946 create_static_range_type (range_type, value_type (low),
1947 longest_to_int (value_as_long (low)),
1948 longest_to_int (value_as_long (high)));
1949 elt_type = create_array_type (array_type, elt_type, range_type);
1950
1951 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1952 {
1953 /* We need to store the element packed bitsize, as well as
1954 recompute the array size, because it was previously
1955 computed based on the unpacked element size. */
1956 LONGEST lo = value_as_long (low);
1957 LONGEST hi = value_as_long (high);
1958
1959 TYPE_FIELD_BITSIZE (elt_type, 0) =
1960 decode_packed_array_bitsize (value_type (arr));
1961 /* If the array has no element, then the size is already
1962 zero, and does not need to be recomputed. */
1963 if (lo < hi)
1964 {
1965 int array_bitsize =
1966 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
1967
1968 TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
1969 }
1970 }
1971 }
1972
1973 return lookup_pointer_type (elt_type);
1974 }
1975 }
1976
1977 /* If ARR does not represent an array, returns ARR unchanged.
1978 Otherwise, returns either a standard GDB array with bounds set
1979 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1980 GDB array. Returns NULL if ARR is a null fat pointer. */
1981
1982 struct value *
1983 ada_coerce_to_simple_array_ptr (struct value *arr)
1984 {
1985 if (ada_is_array_descriptor_type (value_type (arr)))
1986 {
1987 struct type *arrType = ada_type_of_array (arr, 1);
1988
1989 if (arrType == NULL)
1990 return NULL;
1991 return value_cast (arrType, value_copy (desc_data (arr)));
1992 }
1993 else if (ada_is_constrained_packed_array_type (value_type (arr)))
1994 return decode_constrained_packed_array (arr);
1995 else
1996 return arr;
1997 }
1998
1999 /* If ARR does not represent an array, returns ARR unchanged.
2000 Otherwise, returns a standard GDB array describing ARR (which may
2001 be ARR itself if it already is in the proper form). */
2002
2003 struct value *
2004 ada_coerce_to_simple_array (struct value *arr)
2005 {
2006 if (ada_is_array_descriptor_type (value_type (arr)))
2007 {
2008 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2009
2010 if (arrVal == NULL)
2011 error (_("Bounds unavailable for null array pointer."));
2012 ada_ensure_varsize_limit (TYPE_TARGET_TYPE (value_type (arrVal)));
2013 return value_ind (arrVal);
2014 }
2015 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2016 return decode_constrained_packed_array (arr);
2017 else
2018 return arr;
2019 }
2020
2021 /* If TYPE represents a GNAT array type, return it translated to an
2022 ordinary GDB array type (possibly with BITSIZE fields indicating
2023 packing). For other types, is the identity. */
2024
2025 struct type *
2026 ada_coerce_to_simple_array_type (struct type *type)
2027 {
2028 if (ada_is_constrained_packed_array_type (type))
2029 return decode_constrained_packed_array_type (type);
2030
2031 if (ada_is_array_descriptor_type (type))
2032 return ada_check_typedef (desc_data_target_type (type));
2033
2034 return type;
2035 }
2036
2037 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2038
2039 static int
2040 ada_is_packed_array_type (struct type *type)
2041 {
2042 if (type == NULL)
2043 return 0;
2044 type = desc_base_type (type);
2045 type = ada_check_typedef (type);
2046 return
2047 ada_type_name (type) != NULL
2048 && strstr (ada_type_name (type), "___XP") != NULL;
2049 }
2050
2051 /* Non-zero iff TYPE represents a standard GNAT constrained
2052 packed-array type. */
2053
2054 int
2055 ada_is_constrained_packed_array_type (struct type *type)
2056 {
2057 return ada_is_packed_array_type (type)
2058 && !ada_is_array_descriptor_type (type);
2059 }
2060
2061 /* Non-zero iff TYPE represents an array descriptor for a
2062 unconstrained packed-array type. */
2063
2064 static int
2065 ada_is_unconstrained_packed_array_type (struct type *type)
2066 {
2067 return ada_is_packed_array_type (type)
2068 && ada_is_array_descriptor_type (type);
2069 }
2070
2071 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2072 return the size of its elements in bits. */
2073
2074 static long
2075 decode_packed_array_bitsize (struct type *type)
2076 {
2077 const char *raw_name;
2078 const char *tail;
2079 long bits;
2080
2081 /* Access to arrays implemented as fat pointers are encoded as a typedef
2082 of the fat pointer type. We need the name of the fat pointer type
2083 to do the decoding, so strip the typedef layer. */
2084 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
2085 type = ada_typedef_target_type (type);
2086
2087 raw_name = ada_type_name (ada_check_typedef (type));
2088 if (!raw_name)
2089 raw_name = ada_type_name (desc_base_type (type));
2090
2091 if (!raw_name)
2092 return 0;
2093
2094 tail = strstr (raw_name, "___XP");
2095 gdb_assert (tail != NULL);
2096
2097 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2098 {
2099 lim_warning
2100 (_("could not understand bit size information on packed array"));
2101 return 0;
2102 }
2103
2104 return bits;
2105 }
2106
2107 /* Given that TYPE is a standard GDB array type with all bounds filled
2108 in, and that the element size of its ultimate scalar constituents
2109 (that is, either its elements, or, if it is an array of arrays, its
2110 elements' elements, etc.) is *ELT_BITS, return an identical type,
2111 but with the bit sizes of its elements (and those of any
2112 constituent arrays) recorded in the BITSIZE components of its
2113 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2114 in bits.
2115
2116 Note that, for arrays whose index type has an XA encoding where
2117 a bound references a record discriminant, getting that discriminant,
2118 and therefore the actual value of that bound, is not possible
2119 because none of the given parameters gives us access to the record.
2120 This function assumes that it is OK in the context where it is being
2121 used to return an array whose bounds are still dynamic and where
2122 the length is arbitrary. */
2123
2124 static struct type *
2125 constrained_packed_array_type (struct type *type, long *elt_bits)
2126 {
2127 struct type *new_elt_type;
2128 struct type *new_type;
2129 struct type *index_type_desc;
2130 struct type *index_type;
2131 LONGEST low_bound, high_bound;
2132
2133 type = ada_check_typedef (type);
2134 if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2135 return type;
2136
2137 index_type_desc = ada_find_parallel_type (type, "___XA");
2138 if (index_type_desc)
2139 index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, 0),
2140 NULL);
2141 else
2142 index_type = TYPE_INDEX_TYPE (type);
2143
2144 new_type = alloc_type_copy (type);
2145 new_elt_type =
2146 constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2147 elt_bits);
2148 create_array_type (new_type, new_elt_type, index_type);
2149 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2150 TYPE_NAME (new_type) = ada_type_name (type);
2151
2152 if ((TYPE_CODE (check_typedef (index_type)) == TYPE_CODE_RANGE
2153 && is_dynamic_type (check_typedef (index_type)))
2154 || get_discrete_bounds (index_type, &low_bound, &high_bound) < 0)
2155 low_bound = high_bound = 0;
2156 if (high_bound < low_bound)
2157 *elt_bits = TYPE_LENGTH (new_type) = 0;
2158 else
2159 {
2160 *elt_bits *= (high_bound - low_bound + 1);
2161 TYPE_LENGTH (new_type) =
2162 (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2163 }
2164
2165 TYPE_FIXED_INSTANCE (new_type) = 1;
2166 return new_type;
2167 }
2168
2169 /* The array type encoded by TYPE, where
2170 ada_is_constrained_packed_array_type (TYPE). */
2171
2172 static struct type *
2173 decode_constrained_packed_array_type (struct type *type)
2174 {
2175 const char *raw_name = ada_type_name (ada_check_typedef (type));
2176 char *name;
2177 const char *tail;
2178 struct type *shadow_type;
2179 long bits;
2180
2181 if (!raw_name)
2182 raw_name = ada_type_name (desc_base_type (type));
2183
2184 if (!raw_name)
2185 return NULL;
2186
2187 name = (char *) alloca (strlen (raw_name) + 1);
2188 tail = strstr (raw_name, "___XP");
2189 type = desc_base_type (type);
2190
2191 memcpy (name, raw_name, tail - raw_name);
2192 name[tail - raw_name] = '\000';
2193
2194 shadow_type = ada_find_parallel_type_with_name (type, name);
2195
2196 if (shadow_type == NULL)
2197 {
2198 lim_warning (_("could not find bounds information on packed array"));
2199 return NULL;
2200 }
2201 shadow_type = check_typedef (shadow_type);
2202
2203 if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
2204 {
2205 lim_warning (_("could not understand bounds "
2206 "information on packed array"));
2207 return NULL;
2208 }
2209
2210 bits = decode_packed_array_bitsize (type);
2211 return constrained_packed_array_type (shadow_type, &bits);
2212 }
2213
2214 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2215 array, returns a simple array that denotes that array. Its type is a
2216 standard GDB array type except that the BITSIZEs of the array
2217 target types are set to the number of bits in each element, and the
2218 type length is set appropriately. */
2219
2220 static struct value *
2221 decode_constrained_packed_array (struct value *arr)
2222 {
2223 struct type *type;
2224
2225 /* If our value is a pointer, then dereference it. Likewise if
2226 the value is a reference. Make sure that this operation does not
2227 cause the target type to be fixed, as this would indirectly cause
2228 this array to be decoded. The rest of the routine assumes that
2229 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2230 and "value_ind" routines to perform the dereferencing, as opposed
2231 to using "ada_coerce_ref" or "ada_value_ind". */
2232 arr = coerce_ref (arr);
2233 if (TYPE_CODE (ada_check_typedef (value_type (arr))) == TYPE_CODE_PTR)
2234 arr = value_ind (arr);
2235
2236 type = decode_constrained_packed_array_type (value_type (arr));
2237 if (type == NULL)
2238 {
2239 error (_("can't unpack array"));
2240 return NULL;
2241 }
2242
2243 if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2244 && ada_is_modular_type (value_type (arr)))
2245 {
2246 /* This is a (right-justified) modular type representing a packed
2247 array with no wrapper. In order to interpret the value through
2248 the (left-justified) packed array type we just built, we must
2249 first left-justify it. */
2250 int bit_size, bit_pos;
2251 ULONGEST mod;
2252
2253 mod = ada_modulus (value_type (arr)) - 1;
2254 bit_size = 0;
2255 while (mod > 0)
2256 {
2257 bit_size += 1;
2258 mod >>= 1;
2259 }
2260 bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2261 arr = ada_value_primitive_packed_val (arr, NULL,
2262 bit_pos / HOST_CHAR_BIT,
2263 bit_pos % HOST_CHAR_BIT,
2264 bit_size,
2265 type);
2266 }
2267
2268 return coerce_unspec_val_to_type (arr, type);
2269 }
2270
2271
2272 /* The value of the element of packed array ARR at the ARITY indices
2273 given in IND. ARR must be a simple array. */
2274
2275 static struct value *
2276 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2277 {
2278 int i;
2279 int bits, elt_off, bit_off;
2280 long elt_total_bit_offset;
2281 struct type *elt_type;
2282 struct value *v;
2283
2284 bits = 0;
2285 elt_total_bit_offset = 0;
2286 elt_type = ada_check_typedef (value_type (arr));
2287 for (i = 0; i < arity; i += 1)
2288 {
2289 if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
2290 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2291 error
2292 (_("attempt to do packed indexing of "
2293 "something other than a packed array"));
2294 else
2295 {
2296 struct type *range_type = TYPE_INDEX_TYPE (elt_type);
2297 LONGEST lowerbound, upperbound;
2298 LONGEST idx;
2299
2300 if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
2301 {
2302 lim_warning (_("don't know bounds of array"));
2303 lowerbound = upperbound = 0;
2304 }
2305
2306 idx = pos_atr (ind[i]);
2307 if (idx < lowerbound || idx > upperbound)
2308 lim_warning (_("packed array index %ld out of bounds"),
2309 (long) idx);
2310 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2311 elt_total_bit_offset += (idx - lowerbound) * bits;
2312 elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2313 }
2314 }
2315 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2316 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2317
2318 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2319 bits, elt_type);
2320 return v;
2321 }
2322
2323 /* Non-zero iff TYPE includes negative integer values. */
2324
2325 static int
2326 has_negatives (struct type *type)
2327 {
2328 switch (TYPE_CODE (type))
2329 {
2330 default:
2331 return 0;
2332 case TYPE_CODE_INT:
2333 return !TYPE_UNSIGNED (type);
2334 case TYPE_CODE_RANGE:
2335 return TYPE_LOW_BOUND (type) - TYPE_RANGE_DATA (type)->bias < 0;
2336 }
2337 }
2338
2339 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2340 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2341 the unpacked buffer.
2342
2343 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2344 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2345
2346 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2347 zero otherwise.
2348
2349 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2350
2351 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2352
2353 static void
2354 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2355 gdb_byte *unpacked, int unpacked_len,
2356 int is_big_endian, int is_signed_type,
2357 int is_scalar)
2358 {
2359 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2360 int src_idx; /* Index into the source area */
2361 int src_bytes_left; /* Number of source bytes left to process. */
2362 int srcBitsLeft; /* Number of source bits left to move */
2363 int unusedLS; /* Number of bits in next significant
2364 byte of source that are unused */
2365
2366 int unpacked_idx; /* Index into the unpacked buffer */
2367 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2368
2369 unsigned long accum; /* Staging area for bits being transferred */
2370 int accumSize; /* Number of meaningful bits in accum */
2371 unsigned char sign;
2372
2373 /* Transmit bytes from least to most significant; delta is the direction
2374 the indices move. */
2375 int delta = is_big_endian ? -1 : 1;
2376
2377 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2378 bits from SRC. .*/
2379 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2380 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2381 bit_size, unpacked_len);
2382
2383 srcBitsLeft = bit_size;
2384 src_bytes_left = src_len;
2385 unpacked_bytes_left = unpacked_len;
2386 sign = 0;
2387
2388 if (is_big_endian)
2389 {
2390 src_idx = src_len - 1;
2391 if (is_signed_type
2392 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2393 sign = ~0;
2394
2395 unusedLS =
2396 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2397 % HOST_CHAR_BIT;
2398
2399 if (is_scalar)
2400 {
2401 accumSize = 0;
2402 unpacked_idx = unpacked_len - 1;
2403 }
2404 else
2405 {
2406 /* Non-scalar values must be aligned at a byte boundary... */
2407 accumSize =
2408 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2409 /* ... And are placed at the beginning (most-significant) bytes
2410 of the target. */
2411 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2412 unpacked_bytes_left = unpacked_idx + 1;
2413 }
2414 }
2415 else
2416 {
2417 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2418
2419 src_idx = unpacked_idx = 0;
2420 unusedLS = bit_offset;
2421 accumSize = 0;
2422
2423 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2424 sign = ~0;
2425 }
2426
2427 accum = 0;
2428 while (src_bytes_left > 0)
2429 {
2430 /* Mask for removing bits of the next source byte that are not
2431 part of the value. */
2432 unsigned int unusedMSMask =
2433 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2434 1;
2435 /* Sign-extend bits for this byte. */
2436 unsigned int signMask = sign & ~unusedMSMask;
2437
2438 accum |=
2439 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2440 accumSize += HOST_CHAR_BIT - unusedLS;
2441 if (accumSize >= HOST_CHAR_BIT)
2442 {
2443 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2444 accumSize -= HOST_CHAR_BIT;
2445 accum >>= HOST_CHAR_BIT;
2446 unpacked_bytes_left -= 1;
2447 unpacked_idx += delta;
2448 }
2449 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2450 unusedLS = 0;
2451 src_bytes_left -= 1;
2452 src_idx += delta;
2453 }
2454 while (unpacked_bytes_left > 0)
2455 {
2456 accum |= sign << accumSize;
2457 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2458 accumSize -= HOST_CHAR_BIT;
2459 if (accumSize < 0)
2460 accumSize = 0;
2461 accum >>= HOST_CHAR_BIT;
2462 unpacked_bytes_left -= 1;
2463 unpacked_idx += delta;
2464 }
2465 }
2466
2467 /* Create a new value of type TYPE from the contents of OBJ starting
2468 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2469 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2470 assigning through the result will set the field fetched from.
2471 VALADDR is ignored unless OBJ is NULL, in which case,
2472 VALADDR+OFFSET must address the start of storage containing the
2473 packed value. The value returned in this case is never an lval.
2474 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2475
2476 struct value *
2477 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2478 long offset, int bit_offset, int bit_size,
2479 struct type *type)
2480 {
2481 struct value *v;
2482 const gdb_byte *src; /* First byte containing data to unpack */
2483 gdb_byte *unpacked;
2484 const int is_scalar = is_scalar_type (type);
2485 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2486 gdb::byte_vector staging;
2487
2488 type = ada_check_typedef (type);
2489
2490 if (obj == NULL)
2491 src = valaddr + offset;
2492 else
2493 src = value_contents (obj) + offset;
2494
2495 if (is_dynamic_type (type))
2496 {
2497 /* The length of TYPE might by dynamic, so we need to resolve
2498 TYPE in order to know its actual size, which we then use
2499 to create the contents buffer of the value we return.
2500 The difficulty is that the data containing our object is
2501 packed, and therefore maybe not at a byte boundary. So, what
2502 we do, is unpack the data into a byte-aligned buffer, and then
2503 use that buffer as our object's value for resolving the type. */
2504 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2505 staging.resize (staging_len);
2506
2507 ada_unpack_from_contents (src, bit_offset, bit_size,
2508 staging.data (), staging.size (),
2509 is_big_endian, has_negatives (type),
2510 is_scalar);
2511 type = resolve_dynamic_type (type, staging, 0);
2512 if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2513 {
2514 /* This happens when the length of the object is dynamic,
2515 and is actually smaller than the space reserved for it.
2516 For instance, in an array of variant records, the bit_size
2517 we're given is the array stride, which is constant and
2518 normally equal to the maximum size of its element.
2519 But, in reality, each element only actually spans a portion
2520 of that stride. */
2521 bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2522 }
2523 }
2524
2525 if (obj == NULL)
2526 {
2527 v = allocate_value (type);
2528 src = valaddr + offset;
2529 }
2530 else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2531 {
2532 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2533 gdb_byte *buf;
2534
2535 v = value_at (type, value_address (obj) + offset);
2536 buf = (gdb_byte *) alloca (src_len);
2537 read_memory (value_address (v), buf, src_len);
2538 src = buf;
2539 }
2540 else
2541 {
2542 v = allocate_value (type);
2543 src = value_contents (obj) + offset;
2544 }
2545
2546 if (obj != NULL)
2547 {
2548 long new_offset = offset;
2549
2550 set_value_component_location (v, obj);
2551 set_value_bitpos (v, bit_offset + value_bitpos (obj));
2552 set_value_bitsize (v, bit_size);
2553 if (value_bitpos (v) >= HOST_CHAR_BIT)
2554 {
2555 ++new_offset;
2556 set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2557 }
2558 set_value_offset (v, new_offset);
2559
2560 /* Also set the parent value. This is needed when trying to
2561 assign a new value (in inferior memory). */
2562 set_value_parent (v, obj);
2563 }
2564 else
2565 set_value_bitsize (v, bit_size);
2566 unpacked = value_contents_writeable (v);
2567
2568 if (bit_size == 0)
2569 {
2570 memset (unpacked, 0, TYPE_LENGTH (type));
2571 return v;
2572 }
2573
2574 if (staging.size () == TYPE_LENGTH (type))
2575 {
2576 /* Small short-cut: If we've unpacked the data into a buffer
2577 of the same size as TYPE's length, then we can reuse that,
2578 instead of doing the unpacking again. */
2579 memcpy (unpacked, staging.data (), staging.size ());
2580 }
2581 else
2582 ada_unpack_from_contents (src, bit_offset, bit_size,
2583 unpacked, TYPE_LENGTH (type),
2584 is_big_endian, has_negatives (type), is_scalar);
2585
2586 return v;
2587 }
2588
2589 /* Store the contents of FROMVAL into the location of TOVAL.
2590 Return a new value with the location of TOVAL and contents of
2591 FROMVAL. Handles assignment into packed fields that have
2592 floating-point or non-scalar types. */
2593
2594 static struct value *
2595 ada_value_assign (struct value *toval, struct value *fromval)
2596 {
2597 struct type *type = value_type (toval);
2598 int bits = value_bitsize (toval);
2599
2600 toval = ada_coerce_ref (toval);
2601 fromval = ada_coerce_ref (fromval);
2602
2603 if (ada_is_direct_array_type (value_type (toval)))
2604 toval = ada_coerce_to_simple_array (toval);
2605 if (ada_is_direct_array_type (value_type (fromval)))
2606 fromval = ada_coerce_to_simple_array (fromval);
2607
2608 if (!deprecated_value_modifiable (toval))
2609 error (_("Left operand of assignment is not a modifiable lvalue."));
2610
2611 if (VALUE_LVAL (toval) == lval_memory
2612 && bits > 0
2613 && (TYPE_CODE (type) == TYPE_CODE_FLT
2614 || TYPE_CODE (type) == TYPE_CODE_STRUCT))
2615 {
2616 int len = (value_bitpos (toval)
2617 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2618 int from_size;
2619 gdb_byte *buffer = (gdb_byte *) alloca (len);
2620 struct value *val;
2621 CORE_ADDR to_addr = value_address (toval);
2622
2623 if (TYPE_CODE (type) == TYPE_CODE_FLT)
2624 fromval = value_cast (type, fromval);
2625
2626 read_memory (to_addr, buffer, len);
2627 from_size = value_bitsize (fromval);
2628 if (from_size == 0)
2629 from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2630
2631 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2632 ULONGEST from_offset = 0;
2633 if (is_big_endian && is_scalar_type (value_type (fromval)))
2634 from_offset = from_size - bits;
2635 copy_bitwise (buffer, value_bitpos (toval),
2636 value_contents (fromval), from_offset,
2637 bits, is_big_endian);
2638 write_memory_with_notification (to_addr, buffer, len);
2639
2640 val = value_copy (toval);
2641 memcpy (value_contents_raw (val), value_contents (fromval),
2642 TYPE_LENGTH (type));
2643 deprecated_set_value_type (val, type);
2644
2645 return val;
2646 }
2647
2648 return value_assign (toval, fromval);
2649 }
2650
2651
2652 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2653 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2654 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2655 COMPONENT, and not the inferior's memory. The current contents
2656 of COMPONENT are ignored.
2657
2658 Although not part of the initial design, this function also works
2659 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2660 had a null address, and COMPONENT had an address which is equal to
2661 its offset inside CONTAINER. */
2662
2663 static void
2664 value_assign_to_component (struct value *container, struct value *component,
2665 struct value *val)
2666 {
2667 LONGEST offset_in_container =
2668 (LONGEST) (value_address (component) - value_address (container));
2669 int bit_offset_in_container =
2670 value_bitpos (component) - value_bitpos (container);
2671 int bits;
2672
2673 val = value_cast (value_type (component), val);
2674
2675 if (value_bitsize (component) == 0)
2676 bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2677 else
2678 bits = value_bitsize (component);
2679
2680 if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2681 {
2682 int src_offset;
2683
2684 if (is_scalar_type (check_typedef (value_type (component))))
2685 src_offset
2686 = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2687 else
2688 src_offset = 0;
2689 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2690 value_bitpos (container) + bit_offset_in_container,
2691 value_contents (val), src_offset, bits, 1);
2692 }
2693 else
2694 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2695 value_bitpos (container) + bit_offset_in_container,
2696 value_contents (val), 0, bits, 0);
2697 }
2698
2699 /* Determine if TYPE is an access to an unconstrained array. */
2700
2701 bool
2702 ada_is_access_to_unconstrained_array (struct type *type)
2703 {
2704 return (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
2705 && is_thick_pntr (ada_typedef_target_type (type)));
2706 }
2707
2708 /* The value of the element of array ARR at the ARITY indices given in IND.
2709 ARR may be either a simple array, GNAT array descriptor, or pointer
2710 thereto. */
2711
2712 struct value *
2713 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2714 {
2715 int k;
2716 struct value *elt;
2717 struct type *elt_type;
2718
2719 elt = ada_coerce_to_simple_array (arr);
2720
2721 elt_type = ada_check_typedef (value_type (elt));
2722 if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
2723 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2724 return value_subscript_packed (elt, arity, ind);
2725
2726 for (k = 0; k < arity; k += 1)
2727 {
2728 struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
2729
2730 if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
2731 error (_("too many subscripts (%d expected)"), k);
2732
2733 elt = value_subscript (elt, pos_atr (ind[k]));
2734
2735 if (ada_is_access_to_unconstrained_array (saved_elt_type)
2736 && TYPE_CODE (value_type (elt)) != TYPE_CODE_TYPEDEF)
2737 {
2738 /* The element is a typedef to an unconstrained array,
2739 except that the value_subscript call stripped the
2740 typedef layer. The typedef layer is GNAT's way to
2741 specify that the element is, at the source level, an
2742 access to the unconstrained array, rather than the
2743 unconstrained array. So, we need to restore that
2744 typedef layer, which we can do by forcing the element's
2745 type back to its original type. Otherwise, the returned
2746 value is going to be printed as the array, rather
2747 than as an access. Another symptom of the same issue
2748 would be that an expression trying to dereference the
2749 element would also be improperly rejected. */
2750 deprecated_set_value_type (elt, saved_elt_type);
2751 }
2752
2753 elt_type = ada_check_typedef (value_type (elt));
2754 }
2755
2756 return elt;
2757 }
2758
2759 /* Assuming ARR is a pointer to a GDB array, the value of the element
2760 of *ARR at the ARITY indices given in IND.
2761 Does not read the entire array into memory.
2762
2763 Note: Unlike what one would expect, this function is used instead of
2764 ada_value_subscript for basically all non-packed array types. The reason
2765 for this is that a side effect of doing our own pointer arithmetics instead
2766 of relying on value_subscript is that there is no implicit typedef peeling.
2767 This is important for arrays of array accesses, where it allows us to
2768 preserve the fact that the array's element is an array access, where the
2769 access part os encoded in a typedef layer. */
2770
2771 static struct value *
2772 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
2773 {
2774 int k;
2775 struct value *array_ind = ada_value_ind (arr);
2776 struct type *type
2777 = check_typedef (value_enclosing_type (array_ind));
2778
2779 if (TYPE_CODE (type) == TYPE_CODE_ARRAY
2780 && TYPE_FIELD_BITSIZE (type, 0) > 0)
2781 return value_subscript_packed (array_ind, arity, ind);
2782
2783 for (k = 0; k < arity; k += 1)
2784 {
2785 LONGEST lwb, upb;
2786 struct value *lwb_value;
2787
2788 if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2789 error (_("too many subscripts (%d expected)"), k);
2790 arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2791 value_copy (arr));
2792 get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
2793 lwb_value = value_from_longest (value_type(ind[k]), lwb);
2794 arr = value_ptradd (arr, pos_atr (ind[k]) - pos_atr (lwb_value));
2795 type = TYPE_TARGET_TYPE (type);
2796 }
2797
2798 return value_ind (arr);
2799 }
2800
2801 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2802 actual type of ARRAY_PTR is ignored), returns the Ada slice of
2803 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
2804 this array is LOW, as per Ada rules. */
2805 static struct value *
2806 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2807 int low, int high)
2808 {
2809 struct type *type0 = ada_check_typedef (type);
2810 struct type *base_index_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type0));
2811 struct type *index_type
2812 = create_static_range_type (NULL, base_index_type, low, high);
2813 struct type *slice_type = create_array_type_with_stride
2814 (NULL, TYPE_TARGET_TYPE (type0), index_type,
2815 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
2816 TYPE_FIELD_BITSIZE (type0, 0));
2817 int base_low = ada_discrete_type_low_bound (TYPE_INDEX_TYPE (type0));
2818 LONGEST base_low_pos, low_pos;
2819 CORE_ADDR base;
2820
2821 if (!discrete_position (base_index_type, low, &low_pos)
2822 || !discrete_position (base_index_type, base_low, &base_low_pos))
2823 {
2824 warning (_("unable to get positions in slice, use bounds instead"));
2825 low_pos = low;
2826 base_low_pos = base_low;
2827 }
2828
2829 base = value_as_address (array_ptr)
2830 + ((low_pos - base_low_pos)
2831 * TYPE_LENGTH (TYPE_TARGET_TYPE (type0)));
2832 return value_at_lazy (slice_type, base);
2833 }
2834
2835
2836 static struct value *
2837 ada_value_slice (struct value *array, int low, int high)
2838 {
2839 struct type *type = ada_check_typedef (value_type (array));
2840 struct type *base_index_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
2841 struct type *index_type
2842 = create_static_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
2843 struct type *slice_type = create_array_type_with_stride
2844 (NULL, TYPE_TARGET_TYPE (type), index_type,
2845 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
2846 TYPE_FIELD_BITSIZE (type, 0));
2847 LONGEST low_pos, high_pos;
2848
2849 if (!discrete_position (base_index_type, low, &low_pos)
2850 || !discrete_position (base_index_type, high, &high_pos))
2851 {
2852 warning (_("unable to get positions in slice, use bounds instead"));
2853 low_pos = low;
2854 high_pos = high;
2855 }
2856
2857 return value_cast (slice_type,
2858 value_slice (array, low, high_pos - low_pos + 1));
2859 }
2860
2861 /* If type is a record type in the form of a standard GNAT array
2862 descriptor, returns the number of dimensions for type. If arr is a
2863 simple array, returns the number of "array of"s that prefix its
2864 type designation. Otherwise, returns 0. */
2865
2866 int
2867 ada_array_arity (struct type *type)
2868 {
2869 int arity;
2870
2871 if (type == NULL)
2872 return 0;
2873
2874 type = desc_base_type (type);
2875
2876 arity = 0;
2877 if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2878 return desc_arity (desc_bounds_type (type));
2879 else
2880 while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2881 {
2882 arity += 1;
2883 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2884 }
2885
2886 return arity;
2887 }
2888
2889 /* If TYPE is a record type in the form of a standard GNAT array
2890 descriptor or a simple array type, returns the element type for
2891 TYPE after indexing by NINDICES indices, or by all indices if
2892 NINDICES is -1. Otherwise, returns NULL. */
2893
2894 struct type *
2895 ada_array_element_type (struct type *type, int nindices)
2896 {
2897 type = desc_base_type (type);
2898
2899 if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2900 {
2901 int k;
2902 struct type *p_array_type;
2903
2904 p_array_type = desc_data_target_type (type);
2905
2906 k = ada_array_arity (type);
2907 if (k == 0)
2908 return NULL;
2909
2910 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
2911 if (nindices >= 0 && k > nindices)
2912 k = nindices;
2913 while (k > 0 && p_array_type != NULL)
2914 {
2915 p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2916 k -= 1;
2917 }
2918 return p_array_type;
2919 }
2920 else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2921 {
2922 while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
2923 {
2924 type = TYPE_TARGET_TYPE (type);
2925 nindices -= 1;
2926 }
2927 return type;
2928 }
2929
2930 return NULL;
2931 }
2932
2933 /* The type of nth index in arrays of given type (n numbering from 1).
2934 Does not examine memory. Throws an error if N is invalid or TYPE
2935 is not an array type. NAME is the name of the Ada attribute being
2936 evaluated ('range, 'first, 'last, or 'length); it is used in building
2937 the error message. */
2938
2939 static struct type *
2940 ada_index_type (struct type *type, int n, const char *name)
2941 {
2942 struct type *result_type;
2943
2944 type = desc_base_type (type);
2945
2946 if (n < 0 || n > ada_array_arity (type))
2947 error (_("invalid dimension number to '%s"), name);
2948
2949 if (ada_is_simple_array_type (type))
2950 {
2951 int i;
2952
2953 for (i = 1; i < n; i += 1)
2954 type = TYPE_TARGET_TYPE (type);
2955 result_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
2956 /* FIXME: The stabs type r(0,0);bound;bound in an array type
2957 has a target type of TYPE_CODE_UNDEF. We compensate here, but
2958 perhaps stabsread.c would make more sense. */
2959 if (result_type && TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
2960 result_type = NULL;
2961 }
2962 else
2963 {
2964 result_type = desc_index_type (desc_bounds_type (type), n);
2965 if (result_type == NULL)
2966 error (_("attempt to take bound of something that is not an array"));
2967 }
2968
2969 return result_type;
2970 }
2971
2972 /* Given that arr is an array type, returns the lower bound of the
2973 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2974 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
2975 array-descriptor type. It works for other arrays with bounds supplied
2976 by run-time quantities other than discriminants. */
2977
2978 static LONGEST
2979 ada_array_bound_from_type (struct type *arr_type, int n, int which)
2980 {
2981 struct type *type, *index_type_desc, *index_type;
2982 int i;
2983
2984 gdb_assert (which == 0 || which == 1);
2985
2986 if (ada_is_constrained_packed_array_type (arr_type))
2987 arr_type = decode_constrained_packed_array_type (arr_type);
2988
2989 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2990 return (LONGEST) - which;
2991
2992 if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
2993 type = TYPE_TARGET_TYPE (arr_type);
2994 else
2995 type = arr_type;
2996
2997 if (TYPE_FIXED_INSTANCE (type))
2998 {
2999 /* The array has already been fixed, so we do not need to
3000 check the parallel ___XA type again. That encoding has
3001 already been applied, so ignore it now. */
3002 index_type_desc = NULL;
3003 }
3004 else
3005 {
3006 index_type_desc = ada_find_parallel_type (type, "___XA");
3007 ada_fixup_array_indexes_type (index_type_desc);
3008 }
3009
3010 if (index_type_desc != NULL)
3011 index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, n - 1),
3012 NULL);
3013 else
3014 {
3015 struct type *elt_type = check_typedef (type);
3016
3017 for (i = 1; i < n; i++)
3018 elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
3019
3020 index_type = TYPE_INDEX_TYPE (elt_type);
3021 }
3022
3023 return
3024 (LONGEST) (which == 0
3025 ? ada_discrete_type_low_bound (index_type)
3026 : ada_discrete_type_high_bound (index_type));
3027 }
3028
3029 /* Given that arr is an array value, returns the lower bound of the
3030 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3031 WHICH is 1. This routine will also work for arrays with bounds
3032 supplied by run-time quantities other than discriminants. */
3033
3034 static LONGEST
3035 ada_array_bound (struct value *arr, int n, int which)
3036 {
3037 struct type *arr_type;
3038
3039 if (TYPE_CODE (check_typedef (value_type (arr))) == TYPE_CODE_PTR)
3040 arr = value_ind (arr);
3041 arr_type = value_enclosing_type (arr);
3042
3043 if (ada_is_constrained_packed_array_type (arr_type))
3044 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3045 else if (ada_is_simple_array_type (arr_type))
3046 return ada_array_bound_from_type (arr_type, n, which);
3047 else
3048 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3049 }
3050
3051 /* Given that arr is an array value, returns the length of the
3052 nth index. This routine will also work for arrays with bounds
3053 supplied by run-time quantities other than discriminants.
3054 Does not work for arrays indexed by enumeration types with representation
3055 clauses at the moment. */
3056
3057 static LONGEST
3058 ada_array_length (struct value *arr, int n)
3059 {
3060 struct type *arr_type, *index_type;
3061 int low, high;
3062
3063 if (TYPE_CODE (check_typedef (value_type (arr))) == TYPE_CODE_PTR)
3064 arr = value_ind (arr);
3065 arr_type = value_enclosing_type (arr);
3066
3067 if (ada_is_constrained_packed_array_type (arr_type))
3068 return ada_array_length (decode_constrained_packed_array (arr), n);
3069
3070 if (ada_is_simple_array_type (arr_type))
3071 {
3072 low = ada_array_bound_from_type (arr_type, n, 0);
3073 high = ada_array_bound_from_type (arr_type, n, 1);
3074 }
3075 else
3076 {
3077 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3078 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3079 }
3080
3081 arr_type = check_typedef (arr_type);
3082 index_type = ada_index_type (arr_type, n, "length");
3083 if (index_type != NULL)
3084 {
3085 struct type *base_type;
3086 if (TYPE_CODE (index_type) == TYPE_CODE_RANGE)
3087 base_type = TYPE_TARGET_TYPE (index_type);
3088 else
3089 base_type = index_type;
3090
3091 low = pos_atr (value_from_longest (base_type, low));
3092 high = pos_atr (value_from_longest (base_type, high));
3093 }
3094 return high - low + 1;
3095 }
3096
3097 /* An array whose type is that of ARR_TYPE (an array type), with
3098 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3099 less than LOW, then LOW-1 is used. */
3100
3101 static struct value *
3102 empty_array (struct type *arr_type, int low, int high)
3103 {
3104 struct type *arr_type0 = ada_check_typedef (arr_type);
3105 struct type *index_type
3106 = create_static_range_type
3107 (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type0)), low,
3108 high < low ? low - 1 : high);
3109 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3110
3111 return allocate_value (create_array_type (NULL, elt_type, index_type));
3112 }
3113 \f
3114
3115 /* Name resolution */
3116
3117 /* The "decoded" name for the user-definable Ada operator corresponding
3118 to OP. */
3119
3120 static const char *
3121 ada_decoded_op_name (enum exp_opcode op)
3122 {
3123 int i;
3124
3125 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3126 {
3127 if (ada_opname_table[i].op == op)
3128 return ada_opname_table[i].decoded;
3129 }
3130 error (_("Could not find operator name for opcode"));
3131 }
3132
3133 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3134 in a listing of choices during disambiguation (see sort_choices, below).
3135 The idea is that overloadings of a subprogram name from the
3136 same package should sort in their source order. We settle for ordering
3137 such symbols by their trailing number (__N or $N). */
3138
3139 static int
3140 encoded_ordered_before (const char *N0, const char *N1)
3141 {
3142 if (N1 == NULL)
3143 return 0;
3144 else if (N0 == NULL)
3145 return 1;
3146 else
3147 {
3148 int k0, k1;
3149
3150 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3151 ;
3152 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3153 ;
3154 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3155 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3156 {
3157 int n0, n1;
3158
3159 n0 = k0;
3160 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3161 n0 -= 1;
3162 n1 = k1;
3163 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3164 n1 -= 1;
3165 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3166 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3167 }
3168 return (strcmp (N0, N1) < 0);
3169 }
3170 }
3171
3172 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3173 encoded names. */
3174
3175 static void
3176 sort_choices (struct block_symbol syms[], int nsyms)
3177 {
3178 int i;
3179
3180 for (i = 1; i < nsyms; i += 1)
3181 {
3182 struct block_symbol sym = syms[i];
3183 int j;
3184
3185 for (j = i - 1; j >= 0; j -= 1)
3186 {
3187 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3188 sym.symbol->linkage_name ()))
3189 break;
3190 syms[j + 1] = syms[j];
3191 }
3192 syms[j + 1] = sym;
3193 }
3194 }
3195
3196 /* Whether GDB should display formals and return types for functions in the
3197 overloads selection menu. */
3198 static bool print_signatures = true;
3199
3200 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3201 all but functions, the signature is just the name of the symbol. For
3202 functions, this is the name of the function, the list of types for formals
3203 and the return type (if any). */
3204
3205 static void
3206 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3207 const struct type_print_options *flags)
3208 {
3209 struct type *type = SYMBOL_TYPE (sym);
3210
3211 fprintf_filtered (stream, "%s", sym->print_name ());
3212 if (!print_signatures
3213 || type == NULL
3214 || TYPE_CODE (type) != TYPE_CODE_FUNC)
3215 return;
3216
3217 if (TYPE_NFIELDS (type) > 0)
3218 {
3219 int i;
3220
3221 fprintf_filtered (stream, " (");
3222 for (i = 0; i < TYPE_NFIELDS (type); ++i)
3223 {
3224 if (i > 0)
3225 fprintf_filtered (stream, "; ");
3226 ada_print_type (TYPE_FIELD_TYPE (type, i), NULL, stream, -1, 0,
3227 flags);
3228 }
3229 fprintf_filtered (stream, ")");
3230 }
3231 if (TYPE_TARGET_TYPE (type) != NULL
3232 && TYPE_CODE (TYPE_TARGET_TYPE (type)) != TYPE_CODE_VOID)
3233 {
3234 fprintf_filtered (stream, " return ");
3235 ada_print_type (TYPE_TARGET_TYPE (type), NULL, stream, -1, 0, flags);
3236 }
3237 }
3238
3239 /* Read and validate a set of numeric choices from the user in the
3240 range 0 .. N_CHOICES-1. Place the results in increasing
3241 order in CHOICES[0 .. N-1], and return N.
3242
3243 The user types choices as a sequence of numbers on one line
3244 separated by blanks, encoding them as follows:
3245
3246 + A choice of 0 means to cancel the selection, throwing an error.
3247 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3248 + The user chooses k by typing k+IS_ALL_CHOICE+1.
3249
3250 The user is not allowed to choose more than MAX_RESULTS values.
3251
3252 ANNOTATION_SUFFIX, if present, is used to annotate the input
3253 prompts (for use with the -f switch). */
3254
3255 static int
3256 get_selections (int *choices, int n_choices, int max_results,
3257 int is_all_choice, const char *annotation_suffix)
3258 {
3259 const char *args;
3260 const char *prompt;
3261 int n_chosen;
3262 int first_choice = is_all_choice ? 2 : 1;
3263
3264 prompt = getenv ("PS2");
3265 if (prompt == NULL)
3266 prompt = "> ";
3267
3268 args = command_line_input (prompt, annotation_suffix);
3269
3270 if (args == NULL)
3271 error_no_arg (_("one or more choice numbers"));
3272
3273 n_chosen = 0;
3274
3275 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3276 order, as given in args. Choices are validated. */
3277 while (1)
3278 {
3279 char *args2;
3280 int choice, j;
3281
3282 args = skip_spaces (args);
3283 if (*args == '\0' && n_chosen == 0)
3284 error_no_arg (_("one or more choice numbers"));
3285 else if (*args == '\0')
3286 break;
3287
3288 choice = strtol (args, &args2, 10);
3289 if (args == args2 || choice < 0
3290 || choice > n_choices + first_choice - 1)
3291 error (_("Argument must be choice number"));
3292 args = args2;
3293
3294 if (choice == 0)
3295 error (_("cancelled"));
3296
3297 if (choice < first_choice)
3298 {
3299 n_chosen = n_choices;
3300 for (j = 0; j < n_choices; j += 1)
3301 choices[j] = j;
3302 break;
3303 }
3304 choice -= first_choice;
3305
3306 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3307 {
3308 }
3309
3310 if (j < 0 || choice != choices[j])
3311 {
3312 int k;
3313
3314 for (k = n_chosen - 1; k > j; k -= 1)
3315 choices[k + 1] = choices[k];
3316 choices[j + 1] = choice;
3317 n_chosen += 1;
3318 }
3319 }
3320
3321 if (n_chosen > max_results)
3322 error (_("Select no more than %d of the above"), max_results);
3323
3324 return n_chosen;
3325 }
3326
3327 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3328 by asking the user (if necessary), returning the number selected,
3329 and setting the first elements of SYMS items. Error if no symbols
3330 selected. */
3331
3332 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3333 to be re-integrated one of these days. */
3334
3335 static int
3336 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3337 {
3338 int i;
3339 int *chosen = XALLOCAVEC (int , nsyms);
3340 int n_chosen;
3341 int first_choice = (max_results == 1) ? 1 : 2;
3342 const char *select_mode = multiple_symbols_select_mode ();
3343
3344 if (max_results < 1)
3345 error (_("Request to select 0 symbols!"));
3346 if (nsyms <= 1)
3347 return nsyms;
3348
3349 if (select_mode == multiple_symbols_cancel)
3350 error (_("\
3351 canceled because the command is ambiguous\n\
3352 See set/show multiple-symbol."));
3353
3354 /* If select_mode is "all", then return all possible symbols.
3355 Only do that if more than one symbol can be selected, of course.
3356 Otherwise, display the menu as usual. */
3357 if (select_mode == multiple_symbols_all && max_results > 1)
3358 return nsyms;
3359
3360 printf_filtered (_("[0] cancel\n"));
3361 if (max_results > 1)
3362 printf_filtered (_("[1] all\n"));
3363
3364 sort_choices (syms, nsyms);
3365
3366 for (i = 0; i < nsyms; i += 1)
3367 {
3368 if (syms[i].symbol == NULL)
3369 continue;
3370
3371 if (SYMBOL_CLASS (syms[i].symbol) == LOC_BLOCK)
3372 {
3373 struct symtab_and_line sal =
3374 find_function_start_sal (syms[i].symbol, 1);
3375
3376 printf_filtered ("[%d] ", i + first_choice);
3377 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3378 &type_print_raw_options);
3379 if (sal.symtab == NULL)
3380 printf_filtered (_(" at %p[<no source file available>%p]:%d\n"),
3381 metadata_style.style ().ptr (), nullptr, sal.line);
3382 else
3383 printf_filtered
3384 (_(" at %ps:%d\n"),
3385 styled_string (file_name_style.style (),
3386 symtab_to_filename_for_display (sal.symtab)),
3387 sal.line);
3388 continue;
3389 }
3390 else
3391 {
3392 int is_enumeral =
3393 (SYMBOL_CLASS (syms[i].symbol) == LOC_CONST
3394 && SYMBOL_TYPE (syms[i].symbol) != NULL
3395 && TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) == TYPE_CODE_ENUM);
3396 struct symtab *symtab = NULL;
3397
3398 if (SYMBOL_OBJFILE_OWNED (syms[i].symbol))
3399 symtab = symbol_symtab (syms[i].symbol);
3400
3401 if (SYMBOL_LINE (syms[i].symbol) != 0 && symtab != NULL)
3402 {
3403 printf_filtered ("[%d] ", i + first_choice);
3404 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3405 &type_print_raw_options);
3406 printf_filtered (_(" at %s:%d\n"),
3407 symtab_to_filename_for_display (symtab),
3408 SYMBOL_LINE (syms[i].symbol));
3409 }
3410 else if (is_enumeral
3411 && TYPE_NAME (SYMBOL_TYPE (syms[i].symbol)) != NULL)
3412 {
3413 printf_filtered (("[%d] "), i + first_choice);
3414 ada_print_type (SYMBOL_TYPE (syms[i].symbol), NULL,
3415 gdb_stdout, -1, 0, &type_print_raw_options);
3416 printf_filtered (_("'(%s) (enumeral)\n"),
3417 syms[i].symbol->print_name ());
3418 }
3419 else
3420 {
3421 printf_filtered ("[%d] ", i + first_choice);
3422 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3423 &type_print_raw_options);
3424
3425 if (symtab != NULL)
3426 printf_filtered (is_enumeral
3427 ? _(" in %s (enumeral)\n")
3428 : _(" at %s:?\n"),
3429 symtab_to_filename_for_display (symtab));
3430 else
3431 printf_filtered (is_enumeral
3432 ? _(" (enumeral)\n")
3433 : _(" at ?\n"));
3434 }
3435 }
3436 }
3437
3438 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3439 "overload-choice");
3440
3441 for (i = 0; i < n_chosen; i += 1)
3442 syms[i] = syms[chosen[i]];
3443
3444 return n_chosen;
3445 }
3446
3447 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
3448 references (marked by OP_VAR_VALUE nodes in which the symbol has an
3449 undefined namespace) and converts operators that are
3450 user-defined into appropriate function calls. If CONTEXT_TYPE is
3451 non-null, it provides a preferred result type [at the moment, only
3452 type void has any effect---causing procedures to be preferred over
3453 functions in calls]. A null CONTEXT_TYPE indicates that a non-void
3454 return type is preferred. May change (expand) *EXP. */
3455
3456 static void
3457 resolve (expression_up *expp, int void_context_p, int parse_completion,
3458 innermost_block_tracker *tracker)
3459 {
3460 struct type *context_type = NULL;
3461 int pc = 0;
3462
3463 if (void_context_p)
3464 context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
3465
3466 resolve_subexp (expp, &pc, 1, context_type, parse_completion, tracker);
3467 }
3468
3469 /* Resolve the operator of the subexpression beginning at
3470 position *POS of *EXPP. "Resolving" consists of replacing
3471 the symbols that have undefined namespaces in OP_VAR_VALUE nodes
3472 with their resolutions, replacing built-in operators with
3473 function calls to user-defined operators, where appropriate, and,
3474 when DEPROCEDURE_P is non-zero, converting function-valued variables
3475 into parameterless calls. May expand *EXPP. The CONTEXT_TYPE functions
3476 are as in ada_resolve, above. */
3477
3478 static struct value *
3479 resolve_subexp (expression_up *expp, int *pos, int deprocedure_p,
3480 struct type *context_type, int parse_completion,
3481 innermost_block_tracker *tracker)
3482 {
3483 int pc = *pos;
3484 int i;
3485 struct expression *exp; /* Convenience: == *expp. */
3486 enum exp_opcode op = (*expp)->elts[pc].opcode;
3487 struct value **argvec; /* Vector of operand types (alloca'ed). */
3488 int nargs; /* Number of operands. */
3489 int oplen;
3490
3491 argvec = NULL;
3492 nargs = 0;
3493 exp = expp->get ();
3494
3495 /* Pass one: resolve operands, saving their types and updating *pos,
3496 if needed. */
3497 switch (op)
3498 {
3499 case OP_FUNCALL:
3500 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3501 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3502 *pos += 7;
3503 else
3504 {
3505 *pos += 3;
3506 resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3507 }
3508 nargs = longest_to_int (exp->elts[pc + 1].longconst);
3509 break;
3510
3511 case UNOP_ADDR:
3512 *pos += 1;
3513 resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3514 break;
3515
3516 case UNOP_QUAL:
3517 *pos += 3;
3518 resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type),
3519 parse_completion, tracker);
3520 break;
3521
3522 case OP_ATR_MODULUS:
3523 case OP_ATR_SIZE:
3524 case OP_ATR_TAG:
3525 case OP_ATR_FIRST:
3526 case OP_ATR_LAST:
3527 case OP_ATR_LENGTH:
3528 case OP_ATR_POS:
3529 case OP_ATR_VAL:
3530 case OP_ATR_MIN:
3531 case OP_ATR_MAX:
3532 case TERNOP_IN_RANGE:
3533 case BINOP_IN_BOUNDS:
3534 case UNOP_IN_RANGE:
3535 case OP_AGGREGATE:
3536 case OP_OTHERS:
3537 case OP_CHOICES:
3538 case OP_POSITIONAL:
3539 case OP_DISCRETE_RANGE:
3540 case OP_NAME:
3541 ada_forward_operator_length (exp, pc, &oplen, &nargs);
3542 *pos += oplen;
3543 break;
3544
3545 case BINOP_ASSIGN:
3546 {
3547 struct value *arg1;
3548
3549 *pos += 1;
3550 arg1 = resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3551 if (arg1 == NULL)
3552 resolve_subexp (expp, pos, 1, NULL, parse_completion, tracker);
3553 else
3554 resolve_subexp (expp, pos, 1, value_type (arg1), parse_completion,
3555 tracker);
3556 break;
3557 }
3558
3559 case UNOP_CAST:
3560 *pos += 3;
3561 nargs = 1;
3562 break;
3563
3564 case BINOP_ADD:
3565 case BINOP_SUB:
3566 case BINOP_MUL:
3567 case BINOP_DIV:
3568 case BINOP_REM:
3569 case BINOP_MOD:
3570 case BINOP_EXP:
3571 case BINOP_CONCAT:
3572 case BINOP_LOGICAL_AND:
3573 case BINOP_LOGICAL_OR:
3574 case BINOP_BITWISE_AND:
3575 case BINOP_BITWISE_IOR:
3576 case BINOP_BITWISE_XOR:
3577
3578 case BINOP_EQUAL:
3579 case BINOP_NOTEQUAL:
3580 case BINOP_LESS:
3581 case BINOP_GTR:
3582 case BINOP_LEQ:
3583 case BINOP_GEQ:
3584
3585 case BINOP_REPEAT:
3586 case BINOP_SUBSCRIPT:
3587 case BINOP_COMMA:
3588 *pos += 1;
3589 nargs = 2;
3590 break;
3591
3592 case UNOP_NEG:
3593 case UNOP_PLUS:
3594 case UNOP_LOGICAL_NOT:
3595 case UNOP_ABS:
3596 case UNOP_IND:
3597 *pos += 1;
3598 nargs = 1;
3599 break;
3600
3601 case OP_LONG:
3602 case OP_FLOAT:
3603 case OP_VAR_VALUE:
3604 case OP_VAR_MSYM_VALUE:
3605 *pos += 4;
3606 break;
3607
3608 case OP_TYPE:
3609 case OP_BOOL:
3610 case OP_LAST:
3611 case OP_INTERNALVAR:
3612 *pos += 3;
3613 break;
3614
3615 case UNOP_MEMVAL:
3616 *pos += 3;
3617 nargs = 1;
3618 break;
3619
3620 case OP_REGISTER:
3621 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3622 break;
3623
3624 case STRUCTOP_STRUCT:
3625 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3626 nargs = 1;
3627 break;
3628
3629 case TERNOP_SLICE:
3630 *pos += 1;
3631 nargs = 3;
3632 break;
3633
3634 case OP_STRING:
3635 break;
3636
3637 default:
3638 error (_("Unexpected operator during name resolution"));
3639 }
3640
3641 argvec = XALLOCAVEC (struct value *, nargs + 1);
3642 for (i = 0; i < nargs; i += 1)
3643 argvec[i] = resolve_subexp (expp, pos, 1, NULL, parse_completion,
3644 tracker);
3645 argvec[i] = NULL;
3646 exp = expp->get ();
3647
3648 /* Pass two: perform any resolution on principal operator. */
3649 switch (op)
3650 {
3651 default:
3652 break;
3653
3654 case OP_VAR_VALUE:
3655 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
3656 {
3657 std::vector<struct block_symbol> candidates;
3658 int n_candidates;
3659
3660 n_candidates =
3661 ada_lookup_symbol_list (exp->elts[pc + 2].symbol->linkage_name (),
3662 exp->elts[pc + 1].block, VAR_DOMAIN,
3663 &candidates);
3664
3665 if (n_candidates > 1)
3666 {
3667 /* Types tend to get re-introduced locally, so if there
3668 are any local symbols that are not types, first filter
3669 out all types. */
3670 int j;
3671 for (j = 0; j < n_candidates; j += 1)
3672 switch (SYMBOL_CLASS (candidates[j].symbol))
3673 {
3674 case LOC_REGISTER:
3675 case LOC_ARG:
3676 case LOC_REF_ARG:
3677 case LOC_REGPARM_ADDR:
3678 case LOC_LOCAL:
3679 case LOC_COMPUTED:
3680 goto FoundNonType;
3681 default:
3682 break;
3683 }
3684 FoundNonType:
3685 if (j < n_candidates)
3686 {
3687 j = 0;
3688 while (j < n_candidates)
3689 {
3690 if (SYMBOL_CLASS (candidates[j].symbol) == LOC_TYPEDEF)
3691 {
3692 candidates[j] = candidates[n_candidates - 1];
3693 n_candidates -= 1;
3694 }
3695 else
3696 j += 1;
3697 }
3698 }
3699 }
3700
3701 if (n_candidates == 0)
3702 error (_("No definition found for %s"),
3703 exp->elts[pc + 2].symbol->print_name ());
3704 else if (n_candidates == 1)
3705 i = 0;
3706 else if (deprocedure_p
3707 && !is_nonfunction (candidates.data (), n_candidates))
3708 {
3709 i = ada_resolve_function
3710 (candidates.data (), n_candidates, NULL, 0,
3711 exp->elts[pc + 2].symbol->linkage_name (),
3712 context_type, parse_completion);
3713 if (i < 0)
3714 error (_("Could not find a match for %s"),
3715 exp->elts[pc + 2].symbol->print_name ());
3716 }
3717 else
3718 {
3719 printf_filtered (_("Multiple matches for %s\n"),
3720 exp->elts[pc + 2].symbol->print_name ());
3721 user_select_syms (candidates.data (), n_candidates, 1);
3722 i = 0;
3723 }
3724
3725 exp->elts[pc + 1].block = candidates[i].block;
3726 exp->elts[pc + 2].symbol = candidates[i].symbol;
3727 tracker->update (candidates[i]);
3728 }
3729
3730 if (deprocedure_p
3731 && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
3732 == TYPE_CODE_FUNC))
3733 {
3734 replace_operator_with_call (expp, pc, 0, 4,
3735 exp->elts[pc + 2].symbol,
3736 exp->elts[pc + 1].block);
3737 exp = expp->get ();
3738 }
3739 break;
3740
3741 case OP_FUNCALL:
3742 {
3743 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3744 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3745 {
3746 std::vector<struct block_symbol> candidates;
3747 int n_candidates;
3748
3749 n_candidates =
3750 ada_lookup_symbol_list (exp->elts[pc + 5].symbol->linkage_name (),
3751 exp->elts[pc + 4].block, VAR_DOMAIN,
3752 &candidates);
3753
3754 if (n_candidates == 1)
3755 i = 0;
3756 else
3757 {
3758 i = ada_resolve_function
3759 (candidates.data (), n_candidates,
3760 argvec, nargs,
3761 exp->elts[pc + 5].symbol->linkage_name (),
3762 context_type, parse_completion);
3763 if (i < 0)
3764 error (_("Could not find a match for %s"),
3765 exp->elts[pc + 5].symbol->print_name ());
3766 }
3767
3768 exp->elts[pc + 4].block = candidates[i].block;
3769 exp->elts[pc + 5].symbol = candidates[i].symbol;
3770 tracker->update (candidates[i]);
3771 }
3772 }
3773 break;
3774 case BINOP_ADD:
3775 case BINOP_SUB:
3776 case BINOP_MUL:
3777 case BINOP_DIV:
3778 case BINOP_REM:
3779 case BINOP_MOD:
3780 case BINOP_CONCAT:
3781 case BINOP_BITWISE_AND:
3782 case BINOP_BITWISE_IOR:
3783 case BINOP_BITWISE_XOR:
3784 case BINOP_EQUAL:
3785 case BINOP_NOTEQUAL:
3786 case BINOP_LESS:
3787 case BINOP_GTR:
3788 case BINOP_LEQ:
3789 case BINOP_GEQ:
3790 case BINOP_EXP:
3791 case UNOP_NEG:
3792 case UNOP_PLUS:
3793 case UNOP_LOGICAL_NOT:
3794 case UNOP_ABS:
3795 if (possible_user_operator_p (op, argvec))
3796 {
3797 std::vector<struct block_symbol> candidates;
3798 int n_candidates;
3799
3800 n_candidates =
3801 ada_lookup_symbol_list (ada_decoded_op_name (op),
3802 NULL, VAR_DOMAIN,
3803 &candidates);
3804
3805 i = ada_resolve_function (candidates.data (), n_candidates, argvec,
3806 nargs, ada_decoded_op_name (op), NULL,
3807 parse_completion);
3808 if (i < 0)
3809 break;
3810
3811 replace_operator_with_call (expp, pc, nargs, 1,
3812 candidates[i].symbol,
3813 candidates[i].block);
3814 exp = expp->get ();
3815 }
3816 break;
3817
3818 case OP_TYPE:
3819 case OP_REGISTER:
3820 return NULL;
3821 }
3822
3823 *pos = pc;
3824 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
3825 return evaluate_var_msym_value (EVAL_AVOID_SIDE_EFFECTS,
3826 exp->elts[pc + 1].objfile,
3827 exp->elts[pc + 2].msymbol);
3828 else
3829 return evaluate_subexp_type (exp, pos);
3830 }
3831
3832 /* Return non-zero if formal type FTYPE matches actual type ATYPE. If
3833 MAY_DEREF is non-zero, the formal may be a pointer and the actual
3834 a non-pointer. */
3835 /* The term "match" here is rather loose. The match is heuristic and
3836 liberal. */
3837
3838 static int
3839 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
3840 {
3841 ftype = ada_check_typedef (ftype);
3842 atype = ada_check_typedef (atype);
3843
3844 if (TYPE_CODE (ftype) == TYPE_CODE_REF)
3845 ftype = TYPE_TARGET_TYPE (ftype);
3846 if (TYPE_CODE (atype) == TYPE_CODE_REF)
3847 atype = TYPE_TARGET_TYPE (atype);
3848
3849 switch (TYPE_CODE (ftype))
3850 {
3851 default:
3852 return TYPE_CODE (ftype) == TYPE_CODE (atype);
3853 case TYPE_CODE_PTR:
3854 if (TYPE_CODE (atype) == TYPE_CODE_PTR)
3855 return ada_type_match (TYPE_TARGET_TYPE (ftype),
3856 TYPE_TARGET_TYPE (atype), 0);
3857 else
3858 return (may_deref
3859 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
3860 case TYPE_CODE_INT:
3861 case TYPE_CODE_ENUM:
3862 case TYPE_CODE_RANGE:
3863 switch (TYPE_CODE (atype))
3864 {
3865 case TYPE_CODE_INT:
3866 case TYPE_CODE_ENUM:
3867 case TYPE_CODE_RANGE:
3868 return 1;
3869 default:
3870 return 0;
3871 }
3872
3873 case TYPE_CODE_ARRAY:
3874 return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3875 || ada_is_array_descriptor_type (atype));
3876
3877 case TYPE_CODE_STRUCT:
3878 if (ada_is_array_descriptor_type (ftype))
3879 return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3880 || ada_is_array_descriptor_type (atype));
3881 else
3882 return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
3883 && !ada_is_array_descriptor_type (atype));
3884
3885 case TYPE_CODE_UNION:
3886 case TYPE_CODE_FLT:
3887 return (TYPE_CODE (atype) == TYPE_CODE (ftype));
3888 }
3889 }
3890
3891 /* Return non-zero if the formals of FUNC "sufficiently match" the
3892 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3893 may also be an enumeral, in which case it is treated as a 0-
3894 argument function. */
3895
3896 static int
3897 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3898 {
3899 int i;
3900 struct type *func_type = SYMBOL_TYPE (func);
3901
3902 if (SYMBOL_CLASS (func) == LOC_CONST
3903 && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
3904 return (n_actuals == 0);
3905 else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
3906 return 0;
3907
3908 if (TYPE_NFIELDS (func_type) != n_actuals)
3909 return 0;
3910
3911 for (i = 0; i < n_actuals; i += 1)
3912 {
3913 if (actuals[i] == NULL)
3914 return 0;
3915 else
3916 {
3917 struct type *ftype = ada_check_typedef (TYPE_FIELD_TYPE (func_type,
3918 i));
3919 struct type *atype = ada_check_typedef (value_type (actuals[i]));
3920
3921 if (!ada_type_match (ftype, atype, 1))
3922 return 0;
3923 }
3924 }
3925 return 1;
3926 }
3927
3928 /* False iff function type FUNC_TYPE definitely does not produce a value
3929 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
3930 FUNC_TYPE is not a valid function type with a non-null return type
3931 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
3932
3933 static int
3934 return_match (struct type *func_type, struct type *context_type)
3935 {
3936 struct type *return_type;
3937
3938 if (func_type == NULL)
3939 return 1;
3940
3941 if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
3942 return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3943 else
3944 return_type = get_base_type (func_type);
3945 if (return_type == NULL)
3946 return 1;
3947
3948 context_type = get_base_type (context_type);
3949
3950 if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
3951 return context_type == NULL || return_type == context_type;
3952 else if (context_type == NULL)
3953 return TYPE_CODE (return_type) != TYPE_CODE_VOID;
3954 else
3955 return TYPE_CODE (return_type) == TYPE_CODE (context_type);
3956 }
3957
3958
3959 /* Returns the index in SYMS[0..NSYMS-1] that contains the symbol for the
3960 function (if any) that matches the types of the NARGS arguments in
3961 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
3962 that returns that type, then eliminate matches that don't. If
3963 CONTEXT_TYPE is void and there is at least one match that does not
3964 return void, eliminate all matches that do.
3965
3966 Asks the user if there is more than one match remaining. Returns -1
3967 if there is no such symbol or none is selected. NAME is used
3968 solely for messages. May re-arrange and modify SYMS in
3969 the process; the index returned is for the modified vector. */
3970
3971 static int
3972 ada_resolve_function (struct block_symbol syms[],
3973 int nsyms, struct value **args, int nargs,
3974 const char *name, struct type *context_type,
3975 int parse_completion)
3976 {
3977 int fallback;
3978 int k;
3979 int m; /* Number of hits */
3980
3981 m = 0;
3982 /* In the first pass of the loop, we only accept functions matching
3983 context_type. If none are found, we add a second pass of the loop
3984 where every function is accepted. */
3985 for (fallback = 0; m == 0 && fallback < 2; fallback++)
3986 {
3987 for (k = 0; k < nsyms; k += 1)
3988 {
3989 struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].symbol));
3990
3991 if (ada_args_match (syms[k].symbol, args, nargs)
3992 && (fallback || return_match (type, context_type)))
3993 {
3994 syms[m] = syms[k];
3995 m += 1;
3996 }
3997 }
3998 }
3999
4000 /* If we got multiple matches, ask the user which one to use. Don't do this
4001 interactive thing during completion, though, as the purpose of the
4002 completion is providing a list of all possible matches. Prompting the
4003 user to filter it down would be completely unexpected in this case. */
4004 if (m == 0)
4005 return -1;
4006 else if (m > 1 && !parse_completion)
4007 {
4008 printf_filtered (_("Multiple matches for %s\n"), name);
4009 user_select_syms (syms, m, 1);
4010 return 0;
4011 }
4012 return 0;
4013 }
4014
4015 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
4016 on the function identified by SYM and BLOCK, and taking NARGS
4017 arguments. Update *EXPP as needed to hold more space. */
4018
4019 static void
4020 replace_operator_with_call (expression_up *expp, int pc, int nargs,
4021 int oplen, struct symbol *sym,
4022 const struct block *block)
4023 {
4024 /* A new expression, with 6 more elements (3 for funcall, 4 for function
4025 symbol, -oplen for operator being replaced). */
4026 struct expression *newexp = (struct expression *)
4027 xzalloc (sizeof (struct expression)
4028 + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
4029 struct expression *exp = expp->get ();
4030
4031 newexp->nelts = exp->nelts + 7 - oplen;
4032 newexp->language_defn = exp->language_defn;
4033 newexp->gdbarch = exp->gdbarch;
4034 memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
4035 memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
4036 EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
4037
4038 newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
4039 newexp->elts[pc + 1].longconst = (LONGEST) nargs;
4040
4041 newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
4042 newexp->elts[pc + 4].block = block;
4043 newexp->elts[pc + 5].symbol = sym;
4044
4045 expp->reset (newexp);
4046 }
4047
4048 /* Type-class predicates */
4049
4050 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4051 or FLOAT). */
4052
4053 static int
4054 numeric_type_p (struct type *type)
4055 {
4056 if (type == NULL)
4057 return 0;
4058 else
4059 {
4060 switch (TYPE_CODE (type))
4061 {
4062 case TYPE_CODE_INT:
4063 case TYPE_CODE_FLT:
4064 return 1;
4065 case TYPE_CODE_RANGE:
4066 return (type == TYPE_TARGET_TYPE (type)
4067 || numeric_type_p (TYPE_TARGET_TYPE (type)));
4068 default:
4069 return 0;
4070 }
4071 }
4072 }
4073
4074 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4075
4076 static int
4077 integer_type_p (struct type *type)
4078 {
4079 if (type == NULL)
4080 return 0;
4081 else
4082 {
4083 switch (TYPE_CODE (type))
4084 {
4085 case TYPE_CODE_INT:
4086 return 1;
4087 case TYPE_CODE_RANGE:
4088 return (type == TYPE_TARGET_TYPE (type)
4089 || integer_type_p (TYPE_TARGET_TYPE (type)));
4090 default:
4091 return 0;
4092 }
4093 }
4094 }
4095
4096 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4097
4098 static int
4099 scalar_type_p (struct type *type)
4100 {
4101 if (type == NULL)
4102 return 0;
4103 else
4104 {
4105 switch (TYPE_CODE (type))
4106 {
4107 case TYPE_CODE_INT:
4108 case TYPE_CODE_RANGE:
4109 case TYPE_CODE_ENUM:
4110 case TYPE_CODE_FLT:
4111 return 1;
4112 default:
4113 return 0;
4114 }
4115 }
4116 }
4117
4118 /* True iff TYPE is discrete (INT, RANGE, ENUM). */
4119
4120 static int
4121 discrete_type_p (struct type *type)
4122 {
4123 if (type == NULL)
4124 return 0;
4125 else
4126 {
4127 switch (TYPE_CODE (type))
4128 {
4129 case TYPE_CODE_INT:
4130 case TYPE_CODE_RANGE:
4131 case TYPE_CODE_ENUM:
4132 case TYPE_CODE_BOOL:
4133 return 1;
4134 default:
4135 return 0;
4136 }
4137 }
4138 }
4139
4140 /* Returns non-zero if OP with operands in the vector ARGS could be
4141 a user-defined function. Errs on the side of pre-defined operators
4142 (i.e., result 0). */
4143
4144 static int
4145 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4146 {
4147 struct type *type0 =
4148 (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
4149 struct type *type1 =
4150 (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
4151
4152 if (type0 == NULL)
4153 return 0;
4154
4155 switch (op)
4156 {
4157 default:
4158 return 0;
4159
4160 case BINOP_ADD:
4161 case BINOP_SUB:
4162 case BINOP_MUL:
4163 case BINOP_DIV:
4164 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4165
4166 case BINOP_REM:
4167 case BINOP_MOD:
4168 case BINOP_BITWISE_AND:
4169 case BINOP_BITWISE_IOR:
4170 case BINOP_BITWISE_XOR:
4171 return (!(integer_type_p (type0) && integer_type_p (type1)));
4172
4173 case BINOP_EQUAL:
4174 case BINOP_NOTEQUAL:
4175 case BINOP_LESS:
4176 case BINOP_GTR:
4177 case BINOP_LEQ:
4178 case BINOP_GEQ:
4179 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4180
4181 case BINOP_CONCAT:
4182 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4183
4184 case BINOP_EXP:
4185 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4186
4187 case UNOP_NEG:
4188 case UNOP_PLUS:
4189 case UNOP_LOGICAL_NOT:
4190 case UNOP_ABS:
4191 return (!numeric_type_p (type0));
4192
4193 }
4194 }
4195 \f
4196 /* Renaming */
4197
4198 /* NOTES:
4199
4200 1. In the following, we assume that a renaming type's name may
4201 have an ___XD suffix. It would be nice if this went away at some
4202 point.
4203 2. We handle both the (old) purely type-based representation of
4204 renamings and the (new) variable-based encoding. At some point,
4205 it is devoutly to be hoped that the former goes away
4206 (FIXME: hilfinger-2007-07-09).
4207 3. Subprogram renamings are not implemented, although the XRS
4208 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4209
4210 /* If SYM encodes a renaming,
4211
4212 <renaming> renames <renamed entity>,
4213
4214 sets *LEN to the length of the renamed entity's name,
4215 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4216 the string describing the subcomponent selected from the renamed
4217 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4218 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4219 are undefined). Otherwise, returns a value indicating the category
4220 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4221 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4222 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4223 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4224 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4225 may be NULL, in which case they are not assigned.
4226
4227 [Currently, however, GCC does not generate subprogram renamings.] */
4228
4229 enum ada_renaming_category
4230 ada_parse_renaming (struct symbol *sym,
4231 const char **renamed_entity, int *len,
4232 const char **renaming_expr)
4233 {
4234 enum ada_renaming_category kind;
4235 const char *info;
4236 const char *suffix;
4237
4238 if (sym == NULL)
4239 return ADA_NOT_RENAMING;
4240 switch (SYMBOL_CLASS (sym))
4241 {
4242 default:
4243 return ADA_NOT_RENAMING;
4244 case LOC_LOCAL:
4245 case LOC_STATIC:
4246 case LOC_COMPUTED:
4247 case LOC_OPTIMIZED_OUT:
4248 info = strstr (sym->linkage_name (), "___XR");
4249 if (info == NULL)
4250 return ADA_NOT_RENAMING;
4251 switch (info[5])
4252 {
4253 case '_':
4254 kind = ADA_OBJECT_RENAMING;
4255 info += 6;
4256 break;
4257 case 'E':
4258 kind = ADA_EXCEPTION_RENAMING;
4259 info += 7;
4260 break;
4261 case 'P':
4262 kind = ADA_PACKAGE_RENAMING;
4263 info += 7;
4264 break;
4265 case 'S':
4266 kind = ADA_SUBPROGRAM_RENAMING;
4267 info += 7;
4268 break;
4269 default:
4270 return ADA_NOT_RENAMING;
4271 }
4272 }
4273
4274 if (renamed_entity != NULL)
4275 *renamed_entity = info;
4276 suffix = strstr (info, "___XE");
4277 if (suffix == NULL || suffix == info)
4278 return ADA_NOT_RENAMING;
4279 if (len != NULL)
4280 *len = strlen (info) - strlen (suffix);
4281 suffix += 5;
4282 if (renaming_expr != NULL)
4283 *renaming_expr = suffix;
4284 return kind;
4285 }
4286
4287 /* Compute the value of the given RENAMING_SYM, which is expected to
4288 be a symbol encoding a renaming expression. BLOCK is the block
4289 used to evaluate the renaming. */
4290
4291 static struct value *
4292 ada_read_renaming_var_value (struct symbol *renaming_sym,
4293 const struct block *block)
4294 {
4295 const char *sym_name;
4296
4297 sym_name = renaming_sym->linkage_name ();
4298 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4299 return evaluate_expression (expr.get ());
4300 }
4301 \f
4302
4303 /* Evaluation: Function Calls */
4304
4305 /* Return an lvalue containing the value VAL. This is the identity on
4306 lvalues, and otherwise has the side-effect of allocating memory
4307 in the inferior where a copy of the value contents is copied. */
4308
4309 static struct value *
4310 ensure_lval (struct value *val)
4311 {
4312 if (VALUE_LVAL (val) == not_lval
4313 || VALUE_LVAL (val) == lval_internalvar)
4314 {
4315 int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4316 const CORE_ADDR addr =
4317 value_as_long (value_allocate_space_in_inferior (len));
4318
4319 VALUE_LVAL (val) = lval_memory;
4320 set_value_address (val, addr);
4321 write_memory (addr, value_contents (val), len);
4322 }
4323
4324 return val;
4325 }
4326
4327 /* Given ARG, a value of type (pointer or reference to a)*
4328 structure/union, extract the component named NAME from the ultimate
4329 target structure/union and return it as a value with its
4330 appropriate type.
4331
4332 The routine searches for NAME among all members of the structure itself
4333 and (recursively) among all members of any wrapper members
4334 (e.g., '_parent').
4335
4336 If NO_ERR, then simply return NULL in case of error, rather than
4337 calling error. */
4338
4339 static struct value *
4340 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4341 {
4342 struct type *t, *t1;
4343 struct value *v;
4344 int check_tag;
4345
4346 v = NULL;
4347 t1 = t = ada_check_typedef (value_type (arg));
4348 if (TYPE_CODE (t) == TYPE_CODE_REF)
4349 {
4350 t1 = TYPE_TARGET_TYPE (t);
4351 if (t1 == NULL)
4352 goto BadValue;
4353 t1 = ada_check_typedef (t1);
4354 if (TYPE_CODE (t1) == TYPE_CODE_PTR)
4355 {
4356 arg = coerce_ref (arg);
4357 t = t1;
4358 }
4359 }
4360
4361 while (TYPE_CODE (t) == TYPE_CODE_PTR)
4362 {
4363 t1 = TYPE_TARGET_TYPE (t);
4364 if (t1 == NULL)
4365 goto BadValue;
4366 t1 = ada_check_typedef (t1);
4367 if (TYPE_CODE (t1) == TYPE_CODE_PTR)
4368 {
4369 arg = value_ind (arg);
4370 t = t1;
4371 }
4372 else
4373 break;
4374 }
4375
4376 if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
4377 goto BadValue;
4378
4379 if (t1 == t)
4380 v = ada_search_struct_field (name, arg, 0, t);
4381 else
4382 {
4383 int bit_offset, bit_size, byte_offset;
4384 struct type *field_type;
4385 CORE_ADDR address;
4386
4387 if (TYPE_CODE (t) == TYPE_CODE_PTR)
4388 address = value_address (ada_value_ind (arg));
4389 else
4390 address = value_address (ada_coerce_ref (arg));
4391
4392 /* Check to see if this is a tagged type. We also need to handle
4393 the case where the type is a reference to a tagged type, but
4394 we have to be careful to exclude pointers to tagged types.
4395 The latter should be shown as usual (as a pointer), whereas
4396 a reference should mostly be transparent to the user. */
4397
4398 if (ada_is_tagged_type (t1, 0)
4399 || (TYPE_CODE (t1) == TYPE_CODE_REF
4400 && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
4401 {
4402 /* We first try to find the searched field in the current type.
4403 If not found then let's look in the fixed type. */
4404
4405 if (!find_struct_field (name, t1, 0,
4406 &field_type, &byte_offset, &bit_offset,
4407 &bit_size, NULL))
4408 check_tag = 1;
4409 else
4410 check_tag = 0;
4411 }
4412 else
4413 check_tag = 0;
4414
4415 /* Convert to fixed type in all cases, so that we have proper
4416 offsets to each field in unconstrained record types. */
4417 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4418 address, NULL, check_tag);
4419
4420 if (find_struct_field (name, t1, 0,
4421 &field_type, &byte_offset, &bit_offset,
4422 &bit_size, NULL))
4423 {
4424 if (bit_size != 0)
4425 {
4426 if (TYPE_CODE (t) == TYPE_CODE_REF)
4427 arg = ada_coerce_ref (arg);
4428 else
4429 arg = ada_value_ind (arg);
4430 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4431 bit_offset, bit_size,
4432 field_type);
4433 }
4434 else
4435 v = value_at_lazy (field_type, address + byte_offset);
4436 }
4437 }
4438
4439 if (v != NULL || no_err)
4440 return v;
4441 else
4442 error (_("There is no member named %s."), name);
4443
4444 BadValue:
4445 if (no_err)
4446 return NULL;
4447 else
4448 error (_("Attempt to extract a component of "
4449 "a value that is not a record."));
4450 }
4451
4452 /* Return the value ACTUAL, converted to be an appropriate value for a
4453 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4454 allocating any necessary descriptors (fat pointers), or copies of
4455 values not residing in memory, updating it as needed. */
4456
4457 struct value *
4458 ada_convert_actual (struct value *actual, struct type *formal_type0)
4459 {
4460 struct type *actual_type = ada_check_typedef (value_type (actual));
4461 struct type *formal_type = ada_check_typedef (formal_type0);
4462 struct type *formal_target =
4463 TYPE_CODE (formal_type) == TYPE_CODE_PTR
4464 ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4465 struct type *actual_target =
4466 TYPE_CODE (actual_type) == TYPE_CODE_PTR
4467 ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4468
4469 if (ada_is_array_descriptor_type (formal_target)
4470 && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
4471 return make_array_descriptor (formal_type, actual);
4472 else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR
4473 || TYPE_CODE (formal_type) == TYPE_CODE_REF)
4474 {
4475 struct value *result;
4476
4477 if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
4478 && ada_is_array_descriptor_type (actual_target))
4479 result = desc_data (actual);
4480 else if (TYPE_CODE (formal_type) != TYPE_CODE_PTR)
4481 {
4482 if (VALUE_LVAL (actual) != lval_memory)
4483 {
4484 struct value *val;
4485
4486 actual_type = ada_check_typedef (value_type (actual));
4487 val = allocate_value (actual_type);
4488 memcpy ((char *) value_contents_raw (val),
4489 (char *) value_contents (actual),
4490 TYPE_LENGTH (actual_type));
4491 actual = ensure_lval (val);
4492 }
4493 result = value_addr (actual);
4494 }
4495 else
4496 return actual;
4497 return value_cast_pointers (formal_type, result, 0);
4498 }
4499 else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
4500 return ada_value_ind (actual);
4501 else if (ada_is_aligner_type (formal_type))
4502 {
4503 /* We need to turn this parameter into an aligner type
4504 as well. */
4505 struct value *aligner = allocate_value (formal_type);
4506 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4507
4508 value_assign_to_component (aligner, component, actual);
4509 return aligner;
4510 }
4511
4512 return actual;
4513 }
4514
4515 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4516 type TYPE. This is usually an inefficient no-op except on some targets
4517 (such as AVR) where the representation of a pointer and an address
4518 differs. */
4519
4520 static CORE_ADDR
4521 value_pointer (struct value *value, struct type *type)
4522 {
4523 struct gdbarch *gdbarch = get_type_arch (type);
4524 unsigned len = TYPE_LENGTH (type);
4525 gdb_byte *buf = (gdb_byte *) alloca (len);
4526 CORE_ADDR addr;
4527
4528 addr = value_address (value);
4529 gdbarch_address_to_pointer (gdbarch, type, buf, addr);
4530 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4531 return addr;
4532 }
4533
4534
4535 /* Push a descriptor of type TYPE for array value ARR on the stack at
4536 *SP, updating *SP to reflect the new descriptor. Return either
4537 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4538 to-descriptor type rather than a descriptor type), a struct value *
4539 representing a pointer to this descriptor. */
4540
4541 static struct value *
4542 make_array_descriptor (struct type *type, struct value *arr)
4543 {
4544 struct type *bounds_type = desc_bounds_type (type);
4545 struct type *desc_type = desc_base_type (type);
4546 struct value *descriptor = allocate_value (desc_type);
4547 struct value *bounds = allocate_value (bounds_type);
4548 int i;
4549
4550 for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4551 i > 0; i -= 1)
4552 {
4553 modify_field (value_type (bounds), value_contents_writeable (bounds),
4554 ada_array_bound (arr, i, 0),
4555 desc_bound_bitpos (bounds_type, i, 0),
4556 desc_bound_bitsize (bounds_type, i, 0));
4557 modify_field (value_type (bounds), value_contents_writeable (bounds),
4558 ada_array_bound (arr, i, 1),
4559 desc_bound_bitpos (bounds_type, i, 1),
4560 desc_bound_bitsize (bounds_type, i, 1));
4561 }
4562
4563 bounds = ensure_lval (bounds);
4564
4565 modify_field (value_type (descriptor),
4566 value_contents_writeable (descriptor),
4567 value_pointer (ensure_lval (arr),
4568 TYPE_FIELD_TYPE (desc_type, 0)),
4569 fat_pntr_data_bitpos (desc_type),
4570 fat_pntr_data_bitsize (desc_type));
4571
4572 modify_field (value_type (descriptor),
4573 value_contents_writeable (descriptor),
4574 value_pointer (bounds,
4575 TYPE_FIELD_TYPE (desc_type, 1)),
4576 fat_pntr_bounds_bitpos (desc_type),
4577 fat_pntr_bounds_bitsize (desc_type));
4578
4579 descriptor = ensure_lval (descriptor);
4580
4581 if (TYPE_CODE (type) == TYPE_CODE_PTR)
4582 return value_addr (descriptor);
4583 else
4584 return descriptor;
4585 }
4586 \f
4587 /* Symbol Cache Module */
4588
4589 /* Performance measurements made as of 2010-01-15 indicate that
4590 this cache does bring some noticeable improvements. Depending
4591 on the type of entity being printed, the cache can make it as much
4592 as an order of magnitude faster than without it.
4593
4594 The descriptive type DWARF extension has significantly reduced
4595 the need for this cache, at least when DWARF is being used. However,
4596 even in this case, some expensive name-based symbol searches are still
4597 sometimes necessary - to find an XVZ variable, mostly. */
4598
4599 /* Initialize the contents of SYM_CACHE. */
4600
4601 static void
4602 ada_init_symbol_cache (struct ada_symbol_cache *sym_cache)
4603 {
4604 obstack_init (&sym_cache->cache_space);
4605 memset (sym_cache->root, '\000', sizeof (sym_cache->root));
4606 }
4607
4608 /* Free the memory used by SYM_CACHE. */
4609
4610 static void
4611 ada_free_symbol_cache (struct ada_symbol_cache *sym_cache)
4612 {
4613 obstack_free (&sym_cache->cache_space, NULL);
4614 xfree (sym_cache);
4615 }
4616
4617 /* Return the symbol cache associated to the given program space PSPACE.
4618 If not allocated for this PSPACE yet, allocate and initialize one. */
4619
4620 static struct ada_symbol_cache *
4621 ada_get_symbol_cache (struct program_space *pspace)
4622 {
4623 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4624
4625 if (pspace_data->sym_cache == NULL)
4626 {
4627 pspace_data->sym_cache = XCNEW (struct ada_symbol_cache);
4628 ada_init_symbol_cache (pspace_data->sym_cache);
4629 }
4630
4631 return pspace_data->sym_cache;
4632 }
4633
4634 /* Clear all entries from the symbol cache. */
4635
4636 static void
4637 ada_clear_symbol_cache (void)
4638 {
4639 struct ada_symbol_cache *sym_cache
4640 = ada_get_symbol_cache (current_program_space);
4641
4642 obstack_free (&sym_cache->cache_space, NULL);
4643 ada_init_symbol_cache (sym_cache);
4644 }
4645
4646 /* Search our cache for an entry matching NAME and DOMAIN.
4647 Return it if found, or NULL otherwise. */
4648
4649 static struct cache_entry **
4650 find_entry (const char *name, domain_enum domain)
4651 {
4652 struct ada_symbol_cache *sym_cache
4653 = ada_get_symbol_cache (current_program_space);
4654 int h = msymbol_hash (name) % HASH_SIZE;
4655 struct cache_entry **e;
4656
4657 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4658 {
4659 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4660 return e;
4661 }
4662 return NULL;
4663 }
4664
4665 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4666 Return 1 if found, 0 otherwise.
4667
4668 If an entry was found and SYM is not NULL, set *SYM to the entry's
4669 SYM. Same principle for BLOCK if not NULL. */
4670
4671 static int
4672 lookup_cached_symbol (const char *name, domain_enum domain,
4673 struct symbol **sym, const struct block **block)
4674 {
4675 struct cache_entry **e = find_entry (name, domain);
4676
4677 if (e == NULL)
4678 return 0;
4679 if (sym != NULL)
4680 *sym = (*e)->sym;
4681 if (block != NULL)
4682 *block = (*e)->block;
4683 return 1;
4684 }
4685
4686 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4687 in domain DOMAIN, save this result in our symbol cache. */
4688
4689 static void
4690 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4691 const struct block *block)
4692 {
4693 struct ada_symbol_cache *sym_cache
4694 = ada_get_symbol_cache (current_program_space);
4695 int h;
4696 struct cache_entry *e;
4697
4698 /* Symbols for builtin types don't have a block.
4699 For now don't cache such symbols. */
4700 if (sym != NULL && !SYMBOL_OBJFILE_OWNED (sym))
4701 return;
4702
4703 /* If the symbol is a local symbol, then do not cache it, as a search
4704 for that symbol depends on the context. To determine whether
4705 the symbol is local or not, we check the block where we found it
4706 against the global and static blocks of its associated symtab. */
4707 if (sym
4708 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4709 GLOBAL_BLOCK) != block
4710 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4711 STATIC_BLOCK) != block)
4712 return;
4713
4714 h = msymbol_hash (name) % HASH_SIZE;
4715 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4716 e->next = sym_cache->root[h];
4717 sym_cache->root[h] = e;
4718 e->name = obstack_strdup (&sym_cache->cache_space, name);
4719 e->sym = sym;
4720 e->domain = domain;
4721 e->block = block;
4722 }
4723 \f
4724 /* Symbol Lookup */
4725
4726 /* Return the symbol name match type that should be used used when
4727 searching for all symbols matching LOOKUP_NAME.
4728
4729 LOOKUP_NAME is expected to be a symbol name after transformation
4730 for Ada lookups. */
4731
4732 static symbol_name_match_type
4733 name_match_type_from_name (const char *lookup_name)
4734 {
4735 return (strstr (lookup_name, "__") == NULL
4736 ? symbol_name_match_type::WILD
4737 : symbol_name_match_type::FULL);
4738 }
4739
4740 /* Return the result of a standard (literal, C-like) lookup of NAME in
4741 given DOMAIN, visible from lexical block BLOCK. */
4742
4743 static struct symbol *
4744 standard_lookup (const char *name, const struct block *block,
4745 domain_enum domain)
4746 {
4747 /* Initialize it just to avoid a GCC false warning. */
4748 struct block_symbol sym = {};
4749
4750 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4751 return sym.symbol;
4752 ada_lookup_encoded_symbol (name, block, domain, &sym);
4753 cache_symbol (name, domain, sym.symbol, sym.block);
4754 return sym.symbol;
4755 }
4756
4757
4758 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4759 in the symbol fields of SYMS[0..N-1]. We treat enumerals as functions,
4760 since they contend in overloading in the same way. */
4761 static int
4762 is_nonfunction (struct block_symbol syms[], int n)
4763 {
4764 int i;
4765
4766 for (i = 0; i < n; i += 1)
4767 if (TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) != TYPE_CODE_FUNC
4768 && (TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) != TYPE_CODE_ENUM
4769 || SYMBOL_CLASS (syms[i].symbol) != LOC_CONST))
4770 return 1;
4771
4772 return 0;
4773 }
4774
4775 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4776 struct types. Otherwise, they may not. */
4777
4778 static int
4779 equiv_types (struct type *type0, struct type *type1)
4780 {
4781 if (type0 == type1)
4782 return 1;
4783 if (type0 == NULL || type1 == NULL
4784 || TYPE_CODE (type0) != TYPE_CODE (type1))
4785 return 0;
4786 if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
4787 || TYPE_CODE (type0) == TYPE_CODE_ENUM)
4788 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4789 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4790 return 1;
4791
4792 return 0;
4793 }
4794
4795 /* True iff SYM0 represents the same entity as SYM1, or one that is
4796 no more defined than that of SYM1. */
4797
4798 static int
4799 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4800 {
4801 if (sym0 == sym1)
4802 return 1;
4803 if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
4804 || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
4805 return 0;
4806
4807 switch (SYMBOL_CLASS (sym0))
4808 {
4809 case LOC_UNDEF:
4810 return 1;
4811 case LOC_TYPEDEF:
4812 {
4813 struct type *type0 = SYMBOL_TYPE (sym0);
4814 struct type *type1 = SYMBOL_TYPE (sym1);
4815 const char *name0 = sym0->linkage_name ();
4816 const char *name1 = sym1->linkage_name ();
4817 int len0 = strlen (name0);
4818
4819 return
4820 TYPE_CODE (type0) == TYPE_CODE (type1)
4821 && (equiv_types (type0, type1)
4822 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4823 && startswith (name1 + len0, "___XV")));
4824 }
4825 case LOC_CONST:
4826 return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4827 && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
4828
4829 case LOC_STATIC:
4830 {
4831 const char *name0 = sym0->linkage_name ();
4832 const char *name1 = sym1->linkage_name ();
4833 return (strcmp (name0, name1) == 0
4834 && SYMBOL_VALUE_ADDRESS (sym0) == SYMBOL_VALUE_ADDRESS (sym1));
4835 }
4836
4837 default:
4838 return 0;
4839 }
4840 }
4841
4842 /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct block_symbol
4843 records in OBSTACKP. Do nothing if SYM is a duplicate. */
4844
4845 static void
4846 add_defn_to_vec (struct obstack *obstackp,
4847 struct symbol *sym,
4848 const struct block *block)
4849 {
4850 int i;
4851 struct block_symbol *prevDefns = defns_collected (obstackp, 0);
4852
4853 /* Do not try to complete stub types, as the debugger is probably
4854 already scanning all symbols matching a certain name at the
4855 time when this function is called. Trying to replace the stub
4856 type by its associated full type will cause us to restart a scan
4857 which may lead to an infinite recursion. Instead, the client
4858 collecting the matching symbols will end up collecting several
4859 matches, with at least one of them complete. It can then filter
4860 out the stub ones if needed. */
4861
4862 for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
4863 {
4864 if (lesseq_defined_than (sym, prevDefns[i].symbol))
4865 return;
4866 else if (lesseq_defined_than (prevDefns[i].symbol, sym))
4867 {
4868 prevDefns[i].symbol = sym;
4869 prevDefns[i].block = block;
4870 return;
4871 }
4872 }
4873
4874 {
4875 struct block_symbol info;
4876
4877 info.symbol = sym;
4878 info.block = block;
4879 obstack_grow (obstackp, &info, sizeof (struct block_symbol));
4880 }
4881 }
4882
4883 /* Number of block_symbol structures currently collected in current vector in
4884 OBSTACKP. */
4885
4886 static int
4887 num_defns_collected (struct obstack *obstackp)
4888 {
4889 return obstack_object_size (obstackp) / sizeof (struct block_symbol);
4890 }
4891
4892 /* Vector of block_symbol structures currently collected in current vector in
4893 OBSTACKP. If FINISH, close off the vector and return its final address. */
4894
4895 static struct block_symbol *
4896 defns_collected (struct obstack *obstackp, int finish)
4897 {
4898 if (finish)
4899 return (struct block_symbol *) obstack_finish (obstackp);
4900 else
4901 return (struct block_symbol *) obstack_base (obstackp);
4902 }
4903
4904 /* Return a bound minimal symbol matching NAME according to Ada
4905 decoding rules. Returns an invalid symbol if there is no such
4906 minimal symbol. Names prefixed with "standard__" are handled
4907 specially: "standard__" is first stripped off, and only static and
4908 global symbols are searched. */
4909
4910 struct bound_minimal_symbol
4911 ada_lookup_simple_minsym (const char *name)
4912 {
4913 struct bound_minimal_symbol result;
4914
4915 memset (&result, 0, sizeof (result));
4916
4917 symbol_name_match_type match_type = name_match_type_from_name (name);
4918 lookup_name_info lookup_name (name, match_type);
4919
4920 symbol_name_matcher_ftype *match_name
4921 = ada_get_symbol_name_matcher (lookup_name);
4922
4923 for (objfile *objfile : current_program_space->objfiles ())
4924 {
4925 for (minimal_symbol *msymbol : objfile->msymbols ())
4926 {
4927 if (match_name (msymbol->linkage_name (), lookup_name, NULL)
4928 && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4929 {
4930 result.minsym = msymbol;
4931 result.objfile = objfile;
4932 break;
4933 }
4934 }
4935 }
4936
4937 return result;
4938 }
4939
4940 /* For all subprograms that statically enclose the subprogram of the
4941 selected frame, add symbols matching identifier NAME in DOMAIN
4942 and their blocks to the list of data in OBSTACKP, as for
4943 ada_add_block_symbols (q.v.). If WILD_MATCH_P, treat as NAME
4944 with a wildcard prefix. */
4945
4946 static void
4947 add_symbols_from_enclosing_procs (struct obstack *obstackp,
4948 const lookup_name_info &lookup_name,
4949 domain_enum domain)
4950 {
4951 }
4952
4953 /* True if TYPE is definitely an artificial type supplied to a symbol
4954 for which no debugging information was given in the symbol file. */
4955
4956 static int
4957 is_nondebugging_type (struct type *type)
4958 {
4959 const char *name = ada_type_name (type);
4960
4961 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4962 }
4963
4964 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4965 that are deemed "identical" for practical purposes.
4966
4967 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4968 types and that their number of enumerals is identical (in other
4969 words, TYPE_NFIELDS (type1) == TYPE_NFIELDS (type2)). */
4970
4971 static int
4972 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4973 {
4974 int i;
4975
4976 /* The heuristic we use here is fairly conservative. We consider
4977 that 2 enumerate types are identical if they have the same
4978 number of enumerals and that all enumerals have the same
4979 underlying value and name. */
4980
4981 /* All enums in the type should have an identical underlying value. */
4982 for (i = 0; i < TYPE_NFIELDS (type1); i++)
4983 if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
4984 return 0;
4985
4986 /* All enumerals should also have the same name (modulo any numerical
4987 suffix). */
4988 for (i = 0; i < TYPE_NFIELDS (type1); i++)
4989 {
4990 const char *name_1 = TYPE_FIELD_NAME (type1, i);
4991 const char *name_2 = TYPE_FIELD_NAME (type2, i);
4992 int len_1 = strlen (name_1);
4993 int len_2 = strlen (name_2);
4994
4995 ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
4996 ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
4997 if (len_1 != len_2
4998 || strncmp (TYPE_FIELD_NAME (type1, i),
4999 TYPE_FIELD_NAME (type2, i),
5000 len_1) != 0)
5001 return 0;
5002 }
5003
5004 return 1;
5005 }
5006
5007 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
5008 that are deemed "identical" for practical purposes. Sometimes,
5009 enumerals are not strictly identical, but their types are so similar
5010 that they can be considered identical.
5011
5012 For instance, consider the following code:
5013
5014 type Color is (Black, Red, Green, Blue, White);
5015 type RGB_Color is new Color range Red .. Blue;
5016
5017 Type RGB_Color is a subrange of an implicit type which is a copy
5018 of type Color. If we call that implicit type RGB_ColorB ("B" is
5019 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5020 As a result, when an expression references any of the enumeral
5021 by name (Eg. "print green"), the expression is technically
5022 ambiguous and the user should be asked to disambiguate. But
5023 doing so would only hinder the user, since it wouldn't matter
5024 what choice he makes, the outcome would always be the same.
5025 So, for practical purposes, we consider them as the same. */
5026
5027 static int
5028 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5029 {
5030 int i;
5031
5032 /* Before performing a thorough comparison check of each type,
5033 we perform a series of inexpensive checks. We expect that these
5034 checks will quickly fail in the vast majority of cases, and thus
5035 help prevent the unnecessary use of a more expensive comparison.
5036 Said comparison also expects us to make some of these checks
5037 (see ada_identical_enum_types_p). */
5038
5039 /* Quick check: All symbols should have an enum type. */
5040 for (i = 0; i < syms.size (); i++)
5041 if (TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) != TYPE_CODE_ENUM)
5042 return 0;
5043
5044 /* Quick check: They should all have the same value. */
5045 for (i = 1; i < syms.size (); i++)
5046 if (SYMBOL_VALUE (syms[i].symbol) != SYMBOL_VALUE (syms[0].symbol))
5047 return 0;
5048
5049 /* Quick check: They should all have the same number of enumerals. */
5050 for (i = 1; i < syms.size (); i++)
5051 if (TYPE_NFIELDS (SYMBOL_TYPE (syms[i].symbol))
5052 != TYPE_NFIELDS (SYMBOL_TYPE (syms[0].symbol)))
5053 return 0;
5054
5055 /* All the sanity checks passed, so we might have a set of
5056 identical enumeration types. Perform a more complete
5057 comparison of the type of each symbol. */
5058 for (i = 1; i < syms.size (); i++)
5059 if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].symbol),
5060 SYMBOL_TYPE (syms[0].symbol)))
5061 return 0;
5062
5063 return 1;
5064 }
5065
5066 /* Remove any non-debugging symbols in SYMS that definitely
5067 duplicate other symbols in the list (The only case I know of where
5068 this happens is when object files containing stabs-in-ecoff are
5069 linked with files containing ordinary ecoff debugging symbols (or no
5070 debugging symbols)). Modifies SYMS to squeeze out deleted entries.
5071 Returns the number of items in the modified list. */
5072
5073 static int
5074 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5075 {
5076 int i, j;
5077
5078 /* We should never be called with less than 2 symbols, as there
5079 cannot be any extra symbol in that case. But it's easy to
5080 handle, since we have nothing to do in that case. */
5081 if (syms->size () < 2)
5082 return syms->size ();
5083
5084 i = 0;
5085 while (i < syms->size ())
5086 {
5087 int remove_p = 0;
5088
5089 /* If two symbols have the same name and one of them is a stub type,
5090 the get rid of the stub. */
5091
5092 if (TYPE_STUB (SYMBOL_TYPE ((*syms)[i].symbol))
5093 && (*syms)[i].symbol->linkage_name () != NULL)
5094 {
5095 for (j = 0; j < syms->size (); j++)
5096 {
5097 if (j != i
5098 && !TYPE_STUB (SYMBOL_TYPE ((*syms)[j].symbol))
5099 && (*syms)[j].symbol->linkage_name () != NULL
5100 && strcmp ((*syms)[i].symbol->linkage_name (),
5101 (*syms)[j].symbol->linkage_name ()) == 0)
5102 remove_p = 1;
5103 }
5104 }
5105
5106 /* Two symbols with the same name, same class and same address
5107 should be identical. */
5108
5109 else if ((*syms)[i].symbol->linkage_name () != NULL
5110 && SYMBOL_CLASS ((*syms)[i].symbol) == LOC_STATIC
5111 && is_nondebugging_type (SYMBOL_TYPE ((*syms)[i].symbol)))
5112 {
5113 for (j = 0; j < syms->size (); j += 1)
5114 {
5115 if (i != j
5116 && (*syms)[j].symbol->linkage_name () != NULL
5117 && strcmp ((*syms)[i].symbol->linkage_name (),
5118 (*syms)[j].symbol->linkage_name ()) == 0
5119 && SYMBOL_CLASS ((*syms)[i].symbol)
5120 == SYMBOL_CLASS ((*syms)[j].symbol)
5121 && SYMBOL_VALUE_ADDRESS ((*syms)[i].symbol)
5122 == SYMBOL_VALUE_ADDRESS ((*syms)[j].symbol))
5123 remove_p = 1;
5124 }
5125 }
5126
5127 if (remove_p)
5128 syms->erase (syms->begin () + i);
5129
5130 i += 1;
5131 }
5132
5133 /* If all the remaining symbols are identical enumerals, then
5134 just keep the first one and discard the rest.
5135
5136 Unlike what we did previously, we do not discard any entry
5137 unless they are ALL identical. This is because the symbol
5138 comparison is not a strict comparison, but rather a practical
5139 comparison. If all symbols are considered identical, then
5140 we can just go ahead and use the first one and discard the rest.
5141 But if we cannot reduce the list to a single element, we have
5142 to ask the user to disambiguate anyways. And if we have to
5143 present a multiple-choice menu, it's less confusing if the list
5144 isn't missing some choices that were identical and yet distinct. */
5145 if (symbols_are_identical_enums (*syms))
5146 syms->resize (1);
5147
5148 return syms->size ();
5149 }
5150
5151 /* Given a type that corresponds to a renaming entity, use the type name
5152 to extract the scope (package name or function name, fully qualified,
5153 and following the GNAT encoding convention) where this renaming has been
5154 defined. */
5155
5156 static std::string
5157 xget_renaming_scope (struct type *renaming_type)
5158 {
5159 /* The renaming types adhere to the following convention:
5160 <scope>__<rename>___<XR extension>.
5161 So, to extract the scope, we search for the "___XR" extension,
5162 and then backtrack until we find the first "__". */
5163
5164 const char *name = TYPE_NAME (renaming_type);
5165 const char *suffix = strstr (name, "___XR");
5166 const char *last;
5167
5168 /* Now, backtrack a bit until we find the first "__". Start looking
5169 at suffix - 3, as the <rename> part is at least one character long. */
5170
5171 for (last = suffix - 3; last > name; last--)
5172 if (last[0] == '_' && last[1] == '_')
5173 break;
5174
5175 /* Make a copy of scope and return it. */
5176 return std::string (name, last);
5177 }
5178
5179 /* Return nonzero if NAME corresponds to a package name. */
5180
5181 static int
5182 is_package_name (const char *name)
5183 {
5184 /* Here, We take advantage of the fact that no symbols are generated
5185 for packages, while symbols are generated for each function.
5186 So the condition for NAME represent a package becomes equivalent
5187 to NAME not existing in our list of symbols. There is only one
5188 small complication with library-level functions (see below). */
5189
5190 /* If it is a function that has not been defined at library level,
5191 then we should be able to look it up in the symbols. */
5192 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5193 return 0;
5194
5195 /* Library-level function names start with "_ada_". See if function
5196 "_ada_" followed by NAME can be found. */
5197
5198 /* Do a quick check that NAME does not contain "__", since library-level
5199 functions names cannot contain "__" in them. */
5200 if (strstr (name, "__") != NULL)
5201 return 0;
5202
5203 std::string fun_name = string_printf ("_ada_%s", name);
5204
5205 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5206 }
5207
5208 /* Return nonzero if SYM corresponds to a renaming entity that is
5209 not visible from FUNCTION_NAME. */
5210
5211 static int
5212 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5213 {
5214 if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
5215 return 0;
5216
5217 std::string scope = xget_renaming_scope (SYMBOL_TYPE (sym));
5218
5219 /* If the rename has been defined in a package, then it is visible. */
5220 if (is_package_name (scope.c_str ()))
5221 return 0;
5222
5223 /* Check that the rename is in the current function scope by checking
5224 that its name starts with SCOPE. */
5225
5226 /* If the function name starts with "_ada_", it means that it is
5227 a library-level function. Strip this prefix before doing the
5228 comparison, as the encoding for the renaming does not contain
5229 this prefix. */
5230 if (startswith (function_name, "_ada_"))
5231 function_name += 5;
5232
5233 return !startswith (function_name, scope.c_str ());
5234 }
5235
5236 /* Remove entries from SYMS that corresponds to a renaming entity that
5237 is not visible from the function associated with CURRENT_BLOCK or
5238 that is superfluous due to the presence of more specific renaming
5239 information. Places surviving symbols in the initial entries of
5240 SYMS and returns the number of surviving symbols.
5241
5242 Rationale:
5243 First, in cases where an object renaming is implemented as a
5244 reference variable, GNAT may produce both the actual reference
5245 variable and the renaming encoding. In this case, we discard the
5246 latter.
5247
5248 Second, GNAT emits a type following a specified encoding for each renaming
5249 entity. Unfortunately, STABS currently does not support the definition
5250 of types that are local to a given lexical block, so all renamings types
5251 are emitted at library level. As a consequence, if an application
5252 contains two renaming entities using the same name, and a user tries to
5253 print the value of one of these entities, the result of the ada symbol
5254 lookup will also contain the wrong renaming type.
5255
5256 This function partially covers for this limitation by attempting to
5257 remove from the SYMS list renaming symbols that should be visible
5258 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5259 method with the current information available. The implementation
5260 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5261
5262 - When the user tries to print a rename in a function while there
5263 is another rename entity defined in a package: Normally, the
5264 rename in the function has precedence over the rename in the
5265 package, so the latter should be removed from the list. This is
5266 currently not the case.
5267
5268 - This function will incorrectly remove valid renames if
5269 the CURRENT_BLOCK corresponds to a function which symbol name
5270 has been changed by an "Export" pragma. As a consequence,
5271 the user will be unable to print such rename entities. */
5272
5273 static int
5274 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5275 const struct block *current_block)
5276 {
5277 struct symbol *current_function;
5278 const char *current_function_name;
5279 int i;
5280 int is_new_style_renaming;
5281
5282 /* If there is both a renaming foo___XR... encoded as a variable and
5283 a simple variable foo in the same block, discard the latter.
5284 First, zero out such symbols, then compress. */
5285 is_new_style_renaming = 0;
5286 for (i = 0; i < syms->size (); i += 1)
5287 {
5288 struct symbol *sym = (*syms)[i].symbol;
5289 const struct block *block = (*syms)[i].block;
5290 const char *name;
5291 const char *suffix;
5292
5293 if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
5294 continue;
5295 name = sym->linkage_name ();
5296 suffix = strstr (name, "___XR");
5297
5298 if (suffix != NULL)
5299 {
5300 int name_len = suffix - name;
5301 int j;
5302
5303 is_new_style_renaming = 1;
5304 for (j = 0; j < syms->size (); j += 1)
5305 if (i != j && (*syms)[j].symbol != NULL
5306 && strncmp (name, (*syms)[j].symbol->linkage_name (),
5307 name_len) == 0
5308 && block == (*syms)[j].block)
5309 (*syms)[j].symbol = NULL;
5310 }
5311 }
5312 if (is_new_style_renaming)
5313 {
5314 int j, k;
5315
5316 for (j = k = 0; j < syms->size (); j += 1)
5317 if ((*syms)[j].symbol != NULL)
5318 {
5319 (*syms)[k] = (*syms)[j];
5320 k += 1;
5321 }
5322 return k;
5323 }
5324
5325 /* Extract the function name associated to CURRENT_BLOCK.
5326 Abort if unable to do so. */
5327
5328 if (current_block == NULL)
5329 return syms->size ();
5330
5331 current_function = block_linkage_function (current_block);
5332 if (current_function == NULL)
5333 return syms->size ();
5334
5335 current_function_name = current_function->linkage_name ();
5336 if (current_function_name == NULL)
5337 return syms->size ();
5338
5339 /* Check each of the symbols, and remove it from the list if it is
5340 a type corresponding to a renaming that is out of the scope of
5341 the current block. */
5342
5343 i = 0;
5344 while (i < syms->size ())
5345 {
5346 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5347 == ADA_OBJECT_RENAMING
5348 && old_renaming_is_invisible ((*syms)[i].symbol,
5349 current_function_name))
5350 syms->erase (syms->begin () + i);
5351 else
5352 i += 1;
5353 }
5354
5355 return syms->size ();
5356 }
5357
5358 /* Add to OBSTACKP all symbols from BLOCK (and its super-blocks)
5359 whose name and domain match NAME and DOMAIN respectively.
5360 If no match was found, then extend the search to "enclosing"
5361 routines (in other words, if we're inside a nested function,
5362 search the symbols defined inside the enclosing functions).
5363 If WILD_MATCH_P is nonzero, perform the naming matching in
5364 "wild" mode (see function "wild_match" for more info).
5365
5366 Note: This function assumes that OBSTACKP has 0 (zero) element in it. */
5367
5368 static void
5369 ada_add_local_symbols (struct obstack *obstackp,
5370 const lookup_name_info &lookup_name,
5371 const struct block *block, domain_enum domain)
5372 {
5373 int block_depth = 0;
5374
5375 while (block != NULL)
5376 {
5377 block_depth += 1;
5378 ada_add_block_symbols (obstackp, block, lookup_name, domain, NULL);
5379
5380 /* If we found a non-function match, assume that's the one. */
5381 if (is_nonfunction (defns_collected (obstackp, 0),
5382 num_defns_collected (obstackp)))
5383 return;
5384
5385 block = BLOCK_SUPERBLOCK (block);
5386 }
5387
5388 /* If no luck so far, try to find NAME as a local symbol in some lexically
5389 enclosing subprogram. */
5390 if (num_defns_collected (obstackp) == 0 && block_depth > 2)
5391 add_symbols_from_enclosing_procs (obstackp, lookup_name, domain);
5392 }
5393
5394 /* An object of this type is used as the user_data argument when
5395 calling the map_matching_symbols method. */
5396
5397 struct match_data
5398 {
5399 struct objfile *objfile;
5400 struct obstack *obstackp;
5401 struct symbol *arg_sym;
5402 int found_sym;
5403 };
5404
5405 /* A callback for add_nonlocal_symbols that adds symbol, found in BSYM,
5406 to a list of symbols. DATA is a pointer to a struct match_data *
5407 containing the obstack that collects the symbol list, the file that SYM
5408 must come from, a flag indicating whether a non-argument symbol has
5409 been found in the current block, and the last argument symbol
5410 passed in SYM within the current block (if any). When SYM is null,
5411 marking the end of a block, the argument symbol is added if no
5412 other has been found. */
5413
5414 static bool
5415 aux_add_nonlocal_symbols (struct block_symbol *bsym,
5416 struct match_data *data)
5417 {
5418 const struct block *block = bsym->block;
5419 struct symbol *sym = bsym->symbol;
5420
5421 if (sym == NULL)
5422 {
5423 if (!data->found_sym && data->arg_sym != NULL)
5424 add_defn_to_vec (data->obstackp,
5425 fixup_symbol_section (data->arg_sym, data->objfile),
5426 block);
5427 data->found_sym = 0;
5428 data->arg_sym = NULL;
5429 }
5430 else
5431 {
5432 if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5433 return true;
5434 else if (SYMBOL_IS_ARGUMENT (sym))
5435 data->arg_sym = sym;
5436 else
5437 {
5438 data->found_sym = 1;
5439 add_defn_to_vec (data->obstackp,
5440 fixup_symbol_section (sym, data->objfile),
5441 block);
5442 }
5443 }
5444 return true;
5445 }
5446
5447 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5448 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5449 symbols to OBSTACKP. Return whether we found such symbols. */
5450
5451 static int
5452 ada_add_block_renamings (struct obstack *obstackp,
5453 const struct block *block,
5454 const lookup_name_info &lookup_name,
5455 domain_enum domain)
5456 {
5457 struct using_direct *renaming;
5458 int defns_mark = num_defns_collected (obstackp);
5459
5460 symbol_name_matcher_ftype *name_match
5461 = ada_get_symbol_name_matcher (lookup_name);
5462
5463 for (renaming = block_using (block);
5464 renaming != NULL;
5465 renaming = renaming->next)
5466 {
5467 const char *r_name;
5468
5469 /* Avoid infinite recursions: skip this renaming if we are actually
5470 already traversing it.
5471
5472 Currently, symbol lookup in Ada don't use the namespace machinery from
5473 C++/Fortran support: skip namespace imports that use them. */
5474 if (renaming->searched
5475 || (renaming->import_src != NULL
5476 && renaming->import_src[0] != '\0')
5477 || (renaming->import_dest != NULL
5478 && renaming->import_dest[0] != '\0'))
5479 continue;
5480 renaming->searched = 1;
5481
5482 /* TODO: here, we perform another name-based symbol lookup, which can
5483 pull its own multiple overloads. In theory, we should be able to do
5484 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5485 not a simple name. But in order to do this, we would need to enhance
5486 the DWARF reader to associate a symbol to this renaming, instead of a
5487 name. So, for now, we do something simpler: re-use the C++/Fortran
5488 namespace machinery. */
5489 r_name = (renaming->alias != NULL
5490 ? renaming->alias
5491 : renaming->declaration);
5492 if (name_match (r_name, lookup_name, NULL))
5493 {
5494 lookup_name_info decl_lookup_name (renaming->declaration,
5495 lookup_name.match_type ());
5496 ada_add_all_symbols (obstackp, block, decl_lookup_name, domain,
5497 1, NULL);
5498 }
5499 renaming->searched = 0;
5500 }
5501 return num_defns_collected (obstackp) != defns_mark;
5502 }
5503
5504 /* Implements compare_names, but only applying the comparision using
5505 the given CASING. */
5506
5507 static int
5508 compare_names_with_case (const char *string1, const char *string2,
5509 enum case_sensitivity casing)
5510 {
5511 while (*string1 != '\0' && *string2 != '\0')
5512 {
5513 char c1, c2;
5514
5515 if (isspace (*string1) || isspace (*string2))
5516 return strcmp_iw_ordered (string1, string2);
5517
5518 if (casing == case_sensitive_off)
5519 {
5520 c1 = tolower (*string1);
5521 c2 = tolower (*string2);
5522 }
5523 else
5524 {
5525 c1 = *string1;
5526 c2 = *string2;
5527 }
5528 if (c1 != c2)
5529 break;
5530
5531 string1 += 1;
5532 string2 += 1;
5533 }
5534
5535 switch (*string1)
5536 {
5537 case '(':
5538 return strcmp_iw_ordered (string1, string2);
5539 case '_':
5540 if (*string2 == '\0')
5541 {
5542 if (is_name_suffix (string1))
5543 return 0;
5544 else
5545 return 1;
5546 }
5547 /* FALLTHROUGH */
5548 default:
5549 if (*string2 == '(')
5550 return strcmp_iw_ordered (string1, string2);
5551 else
5552 {
5553 if (casing == case_sensitive_off)
5554 return tolower (*string1) - tolower (*string2);
5555 else
5556 return *string1 - *string2;
5557 }
5558 }
5559 }
5560
5561 /* Compare STRING1 to STRING2, with results as for strcmp.
5562 Compatible with strcmp_iw_ordered in that...
5563
5564 strcmp_iw_ordered (STRING1, STRING2) <= 0
5565
5566 ... implies...
5567
5568 compare_names (STRING1, STRING2) <= 0
5569
5570 (they may differ as to what symbols compare equal). */
5571
5572 static int
5573 compare_names (const char *string1, const char *string2)
5574 {
5575 int result;
5576
5577 /* Similar to what strcmp_iw_ordered does, we need to perform
5578 a case-insensitive comparison first, and only resort to
5579 a second, case-sensitive, comparison if the first one was
5580 not sufficient to differentiate the two strings. */
5581
5582 result = compare_names_with_case (string1, string2, case_sensitive_off);
5583 if (result == 0)
5584 result = compare_names_with_case (string1, string2, case_sensitive_on);
5585
5586 return result;
5587 }
5588
5589 /* Convenience function to get at the Ada encoded lookup name for
5590 LOOKUP_NAME, as a C string. */
5591
5592 static const char *
5593 ada_lookup_name (const lookup_name_info &lookup_name)
5594 {
5595 return lookup_name.ada ().lookup_name ().c_str ();
5596 }
5597
5598 /* Add to OBSTACKP all non-local symbols whose name and domain match
5599 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5600 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5601 symbols otherwise. */
5602
5603 static void
5604 add_nonlocal_symbols (struct obstack *obstackp,
5605 const lookup_name_info &lookup_name,
5606 domain_enum domain, int global)
5607 {
5608 struct match_data data;
5609
5610 memset (&data, 0, sizeof data);
5611 data.obstackp = obstackp;
5612
5613 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5614
5615 auto callback = [&] (struct block_symbol *bsym)
5616 {
5617 return aux_add_nonlocal_symbols (bsym, &data);
5618 };
5619
5620 for (objfile *objfile : current_program_space->objfiles ())
5621 {
5622 data.objfile = objfile;
5623
5624 objfile->sf->qf->map_matching_symbols (objfile, lookup_name,
5625 domain, global, callback,
5626 (is_wild_match
5627 ? NULL : compare_names));
5628
5629 for (compunit_symtab *cu : objfile->compunits ())
5630 {
5631 const struct block *global_block
5632 = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cu), GLOBAL_BLOCK);
5633
5634 if (ada_add_block_renamings (obstackp, global_block, lookup_name,
5635 domain))
5636 data.found_sym = 1;
5637 }
5638 }
5639
5640 if (num_defns_collected (obstackp) == 0 && global && !is_wild_match)
5641 {
5642 const char *name = ada_lookup_name (lookup_name);
5643 std::string bracket_name = std::string ("<_ada_") + name + '>';
5644 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5645
5646 for (objfile *objfile : current_program_space->objfiles ())
5647 {
5648 data.objfile = objfile;
5649 objfile->sf->qf->map_matching_symbols (objfile, name1,
5650 domain, global, callback,
5651 compare_names);
5652 }
5653 }
5654 }
5655
5656 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5657 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5658 returning the number of matches. Add these to OBSTACKP.
5659
5660 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5661 symbol match within the nest of blocks whose innermost member is BLOCK,
5662 is the one match returned (no other matches in that or
5663 enclosing blocks is returned). If there are any matches in or
5664 surrounding BLOCK, then these alone are returned.
5665
5666 Names prefixed with "standard__" are handled specially:
5667 "standard__" is first stripped off (by the lookup_name
5668 constructor), and only static and global symbols are searched.
5669
5670 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5671 to lookup global symbols. */
5672
5673 static void
5674 ada_add_all_symbols (struct obstack *obstackp,
5675 const struct block *block,
5676 const lookup_name_info &lookup_name,
5677 domain_enum domain,
5678 int full_search,
5679 int *made_global_lookup_p)
5680 {
5681 struct symbol *sym;
5682
5683 if (made_global_lookup_p)
5684 *made_global_lookup_p = 0;
5685
5686 /* Special case: If the user specifies a symbol name inside package
5687 Standard, do a non-wild matching of the symbol name without
5688 the "standard__" prefix. This was primarily introduced in order
5689 to allow the user to specifically access the standard exceptions
5690 using, for instance, Standard.Constraint_Error when Constraint_Error
5691 is ambiguous (due to the user defining its own Constraint_Error
5692 entity inside its program). */
5693 if (lookup_name.ada ().standard_p ())
5694 block = NULL;
5695
5696 /* Check the non-global symbols. If we have ANY match, then we're done. */
5697
5698 if (block != NULL)
5699 {
5700 if (full_search)
5701 ada_add_local_symbols (obstackp, lookup_name, block, domain);
5702 else
5703 {
5704 /* In the !full_search case we're are being called by
5705 ada_iterate_over_symbols, and we don't want to search
5706 superblocks. */
5707 ada_add_block_symbols (obstackp, block, lookup_name, domain, NULL);
5708 }
5709 if (num_defns_collected (obstackp) > 0 || !full_search)
5710 return;
5711 }
5712
5713 /* No non-global symbols found. Check our cache to see if we have
5714 already performed this search before. If we have, then return
5715 the same result. */
5716
5717 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5718 domain, &sym, &block))
5719 {
5720 if (sym != NULL)
5721 add_defn_to_vec (obstackp, sym, block);
5722 return;
5723 }
5724
5725 if (made_global_lookup_p)
5726 *made_global_lookup_p = 1;
5727
5728 /* Search symbols from all global blocks. */
5729
5730 add_nonlocal_symbols (obstackp, lookup_name, domain, 1);
5731
5732 /* Now add symbols from all per-file blocks if we've gotten no hits
5733 (not strictly correct, but perhaps better than an error). */
5734
5735 if (num_defns_collected (obstackp) == 0)
5736 add_nonlocal_symbols (obstackp, lookup_name, domain, 0);
5737 }
5738
5739 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5740 is non-zero, enclosing scope and in global scopes, returning the number of
5741 matches.
5742 Fills *RESULTS with (SYM,BLOCK) tuples, indicating the symbols
5743 found and the blocks and symbol tables (if any) in which they were
5744 found.
5745
5746 When full_search is non-zero, any non-function/non-enumeral
5747 symbol match within the nest of blocks whose innermost member is BLOCK,
5748 is the one match returned (no other matches in that or
5749 enclosing blocks is returned). If there are any matches in or
5750 surrounding BLOCK, then these alone are returned.
5751
5752 Names prefixed with "standard__" are handled specially: "standard__"
5753 is first stripped off, and only static and global symbols are searched. */
5754
5755 static int
5756 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5757 const struct block *block,
5758 domain_enum domain,
5759 std::vector<struct block_symbol> *results,
5760 int full_search)
5761 {
5762 int syms_from_global_search;
5763 int ndefns;
5764 auto_obstack obstack;
5765
5766 ada_add_all_symbols (&obstack, block, lookup_name,
5767 domain, full_search, &syms_from_global_search);
5768
5769 ndefns = num_defns_collected (&obstack);
5770
5771 struct block_symbol *base = defns_collected (&obstack, 1);
5772 for (int i = 0; i < ndefns; ++i)
5773 results->push_back (base[i]);
5774
5775 ndefns = remove_extra_symbols (results);
5776
5777 if (ndefns == 0 && full_search && syms_from_global_search)
5778 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5779
5780 if (ndefns == 1 && full_search && syms_from_global_search)
5781 cache_symbol (ada_lookup_name (lookup_name), domain,
5782 (*results)[0].symbol, (*results)[0].block);
5783
5784 ndefns = remove_irrelevant_renamings (results, block);
5785
5786 return ndefns;
5787 }
5788
5789 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5790 in global scopes, returning the number of matches, and filling *RESULTS
5791 with (SYM,BLOCK) tuples.
5792
5793 See ada_lookup_symbol_list_worker for further details. */
5794
5795 int
5796 ada_lookup_symbol_list (const char *name, const struct block *block,
5797 domain_enum domain,
5798 std::vector<struct block_symbol> *results)
5799 {
5800 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5801 lookup_name_info lookup_name (name, name_match_type);
5802
5803 return ada_lookup_symbol_list_worker (lookup_name, block, domain, results, 1);
5804 }
5805
5806 /* Implementation of the la_iterate_over_symbols method. */
5807
5808 static bool
5809 ada_iterate_over_symbols
5810 (const struct block *block, const lookup_name_info &name,
5811 domain_enum domain,
5812 gdb::function_view<symbol_found_callback_ftype> callback)
5813 {
5814 int ndefs, i;
5815 std::vector<struct block_symbol> results;
5816
5817 ndefs = ada_lookup_symbol_list_worker (name, block, domain, &results, 0);
5818
5819 for (i = 0; i < ndefs; ++i)
5820 {
5821 if (!callback (&results[i]))
5822 return false;
5823 }
5824
5825 return true;
5826 }
5827
5828 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5829 to 1, but choosing the first symbol found if there are multiple
5830 choices.
5831
5832 The result is stored in *INFO, which must be non-NULL.
5833 If no match is found, INFO->SYM is set to NULL. */
5834
5835 void
5836 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5837 domain_enum domain,
5838 struct block_symbol *info)
5839 {
5840 /* Since we already have an encoded name, wrap it in '<>' to force a
5841 verbatim match. Otherwise, if the name happens to not look like
5842 an encoded name (because it doesn't include a "__"),
5843 ada_lookup_name_info would re-encode/fold it again, and that
5844 would e.g., incorrectly lowercase object renaming names like
5845 "R28b" -> "r28b". */
5846 std::string verbatim = std::string ("<") + name + '>';
5847
5848 gdb_assert (info != NULL);
5849 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5850 }
5851
5852 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5853 scope and in global scopes, or NULL if none. NAME is folded and
5854 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5855 choosing the first symbol if there are multiple choices. */
5856
5857 struct block_symbol
5858 ada_lookup_symbol (const char *name, const struct block *block0,
5859 domain_enum domain)
5860 {
5861 std::vector<struct block_symbol> candidates;
5862 int n_candidates;
5863
5864 n_candidates = ada_lookup_symbol_list (name, block0, domain, &candidates);
5865
5866 if (n_candidates == 0)
5867 return {};
5868
5869 block_symbol info = candidates[0];
5870 info.symbol = fixup_symbol_section (info.symbol, NULL);
5871 return info;
5872 }
5873
5874 static struct block_symbol
5875 ada_lookup_symbol_nonlocal (const struct language_defn *langdef,
5876 const char *name,
5877 const struct block *block,
5878 const domain_enum domain)
5879 {
5880 struct block_symbol sym;
5881
5882 sym = ada_lookup_symbol (name, block_static_block (block), domain);
5883 if (sym.symbol != NULL)
5884 return sym;
5885
5886 /* If we haven't found a match at this point, try the primitive
5887 types. In other languages, this search is performed before
5888 searching for global symbols in order to short-circuit that
5889 global-symbol search if it happens that the name corresponds
5890 to a primitive type. But we cannot do the same in Ada, because
5891 it is perfectly legitimate for a program to declare a type which
5892 has the same name as a standard type. If looking up a type in
5893 that situation, we have traditionally ignored the primitive type
5894 in favor of user-defined types. This is why, unlike most other
5895 languages, we search the primitive types this late and only after
5896 having searched the global symbols without success. */
5897
5898 if (domain == VAR_DOMAIN)
5899 {
5900 struct gdbarch *gdbarch;
5901
5902 if (block == NULL)
5903 gdbarch = target_gdbarch ();
5904 else
5905 gdbarch = block_gdbarch (block);
5906 sym.symbol = language_lookup_primitive_type_as_symbol (langdef, gdbarch, name);
5907 if (sym.symbol != NULL)
5908 return sym;
5909 }
5910
5911 return {};
5912 }
5913
5914
5915 /* True iff STR is a possible encoded suffix of a normal Ada name
5916 that is to be ignored for matching purposes. Suffixes of parallel
5917 names (e.g., XVE) are not included here. Currently, the possible suffixes
5918 are given by any of the regular expressions:
5919
5920 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5921 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5922 TKB [subprogram suffix for task bodies]
5923 _E[0-9]+[bs]$ [protected object entry suffixes]
5924 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5925
5926 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5927 match is performed. This sequence is used to differentiate homonyms,
5928 is an optional part of a valid name suffix. */
5929
5930 static int
5931 is_name_suffix (const char *str)
5932 {
5933 int k;
5934 const char *matching;
5935 const int len = strlen (str);
5936
5937 /* Skip optional leading __[0-9]+. */
5938
5939 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5940 {
5941 str += 3;
5942 while (isdigit (str[0]))
5943 str += 1;
5944 }
5945
5946 /* [.$][0-9]+ */
5947
5948 if (str[0] == '.' || str[0] == '$')
5949 {
5950 matching = str + 1;
5951 while (isdigit (matching[0]))
5952 matching += 1;
5953 if (matching[0] == '\0')
5954 return 1;
5955 }
5956
5957 /* ___[0-9]+ */
5958
5959 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5960 {
5961 matching = str + 3;
5962 while (isdigit (matching[0]))
5963 matching += 1;
5964 if (matching[0] == '\0')
5965 return 1;
5966 }
5967
5968 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5969
5970 if (strcmp (str, "TKB") == 0)
5971 return 1;
5972
5973 #if 0
5974 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5975 with a N at the end. Unfortunately, the compiler uses the same
5976 convention for other internal types it creates. So treating
5977 all entity names that end with an "N" as a name suffix causes
5978 some regressions. For instance, consider the case of an enumerated
5979 type. To support the 'Image attribute, it creates an array whose
5980 name ends with N.
5981 Having a single character like this as a suffix carrying some
5982 information is a bit risky. Perhaps we should change the encoding
5983 to be something like "_N" instead. In the meantime, do not do
5984 the following check. */
5985 /* Protected Object Subprograms */
5986 if (len == 1 && str [0] == 'N')
5987 return 1;
5988 #endif
5989
5990 /* _E[0-9]+[bs]$ */
5991 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5992 {
5993 matching = str + 3;
5994 while (isdigit (matching[0]))
5995 matching += 1;
5996 if ((matching[0] == 'b' || matching[0] == 's')
5997 && matching [1] == '\0')
5998 return 1;
5999 }
6000
6001 /* ??? We should not modify STR directly, as we are doing below. This
6002 is fine in this case, but may become problematic later if we find
6003 that this alternative did not work, and want to try matching
6004 another one from the begining of STR. Since we modified it, we
6005 won't be able to find the begining of the string anymore! */
6006 if (str[0] == 'X')
6007 {
6008 str += 1;
6009 while (str[0] != '_' && str[0] != '\0')
6010 {
6011 if (str[0] != 'n' && str[0] != 'b')
6012 return 0;
6013 str += 1;
6014 }
6015 }
6016
6017 if (str[0] == '\000')
6018 return 1;
6019
6020 if (str[0] == '_')
6021 {
6022 if (str[1] != '_' || str[2] == '\000')
6023 return 0;
6024 if (str[2] == '_')
6025 {
6026 if (strcmp (str + 3, "JM") == 0)
6027 return 1;
6028 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
6029 the LJM suffix in favor of the JM one. But we will
6030 still accept LJM as a valid suffix for a reasonable
6031 amount of time, just to allow ourselves to debug programs
6032 compiled using an older version of GNAT. */
6033 if (strcmp (str + 3, "LJM") == 0)
6034 return 1;
6035 if (str[3] != 'X')
6036 return 0;
6037 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
6038 || str[4] == 'U' || str[4] == 'P')
6039 return 1;
6040 if (str[4] == 'R' && str[5] != 'T')
6041 return 1;
6042 return 0;
6043 }
6044 if (!isdigit (str[2]))
6045 return 0;
6046 for (k = 3; str[k] != '\0'; k += 1)
6047 if (!isdigit (str[k]) && str[k] != '_')
6048 return 0;
6049 return 1;
6050 }
6051 if (str[0] == '$' && isdigit (str[1]))
6052 {
6053 for (k = 2; str[k] != '\0'; k += 1)
6054 if (!isdigit (str[k]) && str[k] != '_')
6055 return 0;
6056 return 1;
6057 }
6058 return 0;
6059 }
6060
6061 /* Return non-zero if the string starting at NAME and ending before
6062 NAME_END contains no capital letters. */
6063
6064 static int
6065 is_valid_name_for_wild_match (const char *name0)
6066 {
6067 std::string decoded_name = ada_decode (name0);
6068 int i;
6069
6070 /* If the decoded name starts with an angle bracket, it means that
6071 NAME0 does not follow the GNAT encoding format. It should then
6072 not be allowed as a possible wild match. */
6073 if (decoded_name[0] == '<')
6074 return 0;
6075
6076 for (i=0; decoded_name[i] != '\0'; i++)
6077 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
6078 return 0;
6079
6080 return 1;
6081 }
6082
6083 /* Advance *NAMEP to next occurrence of TARGET0 in the string NAME0
6084 that could start a simple name. Assumes that *NAMEP points into
6085 the string beginning at NAME0. */
6086
6087 static int
6088 advance_wild_match (const char **namep, const char *name0, int target0)
6089 {
6090 const char *name = *namep;
6091
6092 while (1)
6093 {
6094 int t0, t1;
6095
6096 t0 = *name;
6097 if (t0 == '_')
6098 {
6099 t1 = name[1];
6100 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
6101 {
6102 name += 1;
6103 if (name == name0 + 5 && startswith (name0, "_ada"))
6104 break;
6105 else
6106 name += 1;
6107 }
6108 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6109 || name[2] == target0))
6110 {
6111 name += 2;
6112 break;
6113 }
6114 else
6115 return 0;
6116 }
6117 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6118 name += 1;
6119 else
6120 return 0;
6121 }
6122
6123 *namep = name;
6124 return 1;
6125 }
6126
6127 /* Return true iff NAME encodes a name of the form prefix.PATN.
6128 Ignores any informational suffixes of NAME (i.e., for which
6129 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6130 simple name. */
6131
6132 static bool
6133 wild_match (const char *name, const char *patn)
6134 {
6135 const char *p;
6136 const char *name0 = name;
6137
6138 while (1)
6139 {
6140 const char *match = name;
6141
6142 if (*name == *patn)
6143 {
6144 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6145 if (*p != *name)
6146 break;
6147 if (*p == '\0' && is_name_suffix (name))
6148 return match == name0 || is_valid_name_for_wild_match (name0);
6149
6150 if (name[-1] == '_')
6151 name -= 1;
6152 }
6153 if (!advance_wild_match (&name, name0, *patn))
6154 return false;
6155 }
6156 }
6157
6158 /* Returns true iff symbol name SYM_NAME matches SEARCH_NAME, ignoring
6159 any trailing suffixes that encode debugging information or leading
6160 _ada_ on SYM_NAME (see is_name_suffix commentary for the debugging
6161 information that is ignored). */
6162
6163 static bool
6164 full_match (const char *sym_name, const char *search_name)
6165 {
6166 size_t search_name_len = strlen (search_name);
6167
6168 if (strncmp (sym_name, search_name, search_name_len) == 0
6169 && is_name_suffix (sym_name + search_name_len))
6170 return true;
6171
6172 if (startswith (sym_name, "_ada_")
6173 && strncmp (sym_name + 5, search_name, search_name_len) == 0
6174 && is_name_suffix (sym_name + search_name_len + 5))
6175 return true;
6176
6177 return false;
6178 }
6179
6180 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to vector
6181 *defn_symbols, updating the list of symbols in OBSTACKP (if
6182 necessary). OBJFILE is the section containing BLOCK. */
6183
6184 static void
6185 ada_add_block_symbols (struct obstack *obstackp,
6186 const struct block *block,
6187 const lookup_name_info &lookup_name,
6188 domain_enum domain, struct objfile *objfile)
6189 {
6190 struct block_iterator iter;
6191 /* A matching argument symbol, if any. */
6192 struct symbol *arg_sym;
6193 /* Set true when we find a matching non-argument symbol. */
6194 int found_sym;
6195 struct symbol *sym;
6196
6197 arg_sym = NULL;
6198 found_sym = 0;
6199 for (sym = block_iter_match_first (block, lookup_name, &iter);
6200 sym != NULL;
6201 sym = block_iter_match_next (lookup_name, &iter))
6202 {
6203 if (symbol_matches_domain (sym->language (), SYMBOL_DOMAIN (sym), domain))
6204 {
6205 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6206 {
6207 if (SYMBOL_IS_ARGUMENT (sym))
6208 arg_sym = sym;
6209 else
6210 {
6211 found_sym = 1;
6212 add_defn_to_vec (obstackp,
6213 fixup_symbol_section (sym, objfile),
6214 block);
6215 }
6216 }
6217 }
6218 }
6219
6220 /* Handle renamings. */
6221
6222 if (ada_add_block_renamings (obstackp, block, lookup_name, domain))
6223 found_sym = 1;
6224
6225 if (!found_sym && arg_sym != NULL)
6226 {
6227 add_defn_to_vec (obstackp,
6228 fixup_symbol_section (arg_sym, objfile),
6229 block);
6230 }
6231
6232 if (!lookup_name.ada ().wild_match_p ())
6233 {
6234 arg_sym = NULL;
6235 found_sym = 0;
6236 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6237 const char *name = ada_lookup_name.c_str ();
6238 size_t name_len = ada_lookup_name.size ();
6239
6240 ALL_BLOCK_SYMBOLS (block, iter, sym)
6241 {
6242 if (symbol_matches_domain (sym->language (),
6243 SYMBOL_DOMAIN (sym), domain))
6244 {
6245 int cmp;
6246
6247 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6248 if (cmp == 0)
6249 {
6250 cmp = !startswith (sym->linkage_name (), "_ada_");
6251 if (cmp == 0)
6252 cmp = strncmp (name, sym->linkage_name () + 5,
6253 name_len);
6254 }
6255
6256 if (cmp == 0
6257 && is_name_suffix (sym->linkage_name () + name_len + 5))
6258 {
6259 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6260 {
6261 if (SYMBOL_IS_ARGUMENT (sym))
6262 arg_sym = sym;
6263 else
6264 {
6265 found_sym = 1;
6266 add_defn_to_vec (obstackp,
6267 fixup_symbol_section (sym, objfile),
6268 block);
6269 }
6270 }
6271 }
6272 }
6273 }
6274
6275 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6276 They aren't parameters, right? */
6277 if (!found_sym && arg_sym != NULL)
6278 {
6279 add_defn_to_vec (obstackp,
6280 fixup_symbol_section (arg_sym, objfile),
6281 block);
6282 }
6283 }
6284 }
6285 \f
6286
6287 /* Symbol Completion */
6288
6289 /* See symtab.h. */
6290
6291 bool
6292 ada_lookup_name_info::matches
6293 (const char *sym_name,
6294 symbol_name_match_type match_type,
6295 completion_match_result *comp_match_res) const
6296 {
6297 bool match = false;
6298 const char *text = m_encoded_name.c_str ();
6299 size_t text_len = m_encoded_name.size ();
6300
6301 /* First, test against the fully qualified name of the symbol. */
6302
6303 if (strncmp (sym_name, text, text_len) == 0)
6304 match = true;
6305
6306 std::string decoded_name = ada_decode (sym_name);
6307 if (match && !m_encoded_p)
6308 {
6309 /* One needed check before declaring a positive match is to verify
6310 that iff we are doing a verbatim match, the decoded version
6311 of the symbol name starts with '<'. Otherwise, this symbol name
6312 is not a suitable completion. */
6313
6314 bool has_angle_bracket = (decoded_name[0] == '<');
6315 match = (has_angle_bracket == m_verbatim_p);
6316 }
6317
6318 if (match && !m_verbatim_p)
6319 {
6320 /* When doing non-verbatim match, another check that needs to
6321 be done is to verify that the potentially matching symbol name
6322 does not include capital letters, because the ada-mode would
6323 not be able to understand these symbol names without the
6324 angle bracket notation. */
6325 const char *tmp;
6326
6327 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6328 if (*tmp != '\0')
6329 match = false;
6330 }
6331
6332 /* Second: Try wild matching... */
6333
6334 if (!match && m_wild_match_p)
6335 {
6336 /* Since we are doing wild matching, this means that TEXT
6337 may represent an unqualified symbol name. We therefore must
6338 also compare TEXT against the unqualified name of the symbol. */
6339 sym_name = ada_unqualified_name (decoded_name.c_str ());
6340
6341 if (strncmp (sym_name, text, text_len) == 0)
6342 match = true;
6343 }
6344
6345 /* Finally: If we found a match, prepare the result to return. */
6346
6347 if (!match)
6348 return false;
6349
6350 if (comp_match_res != NULL)
6351 {
6352 std::string &match_str = comp_match_res->match.storage ();
6353
6354 if (!m_encoded_p)
6355 match_str = ada_decode (sym_name);
6356 else
6357 {
6358 if (m_verbatim_p)
6359 match_str = add_angle_brackets (sym_name);
6360 else
6361 match_str = sym_name;
6362
6363 }
6364
6365 comp_match_res->set_match (match_str.c_str ());
6366 }
6367
6368 return true;
6369 }
6370
6371 /* Add the list of possible symbol names completing TEXT to TRACKER.
6372 WORD is the entire command on which completion is made. */
6373
6374 static void
6375 ada_collect_symbol_completion_matches (completion_tracker &tracker,
6376 complete_symbol_mode mode,
6377 symbol_name_match_type name_match_type,
6378 const char *text, const char *word,
6379 enum type_code code)
6380 {
6381 struct symbol *sym;
6382 const struct block *b, *surrounding_static_block = 0;
6383 struct block_iterator iter;
6384
6385 gdb_assert (code == TYPE_CODE_UNDEF);
6386
6387 lookup_name_info lookup_name (text, name_match_type, true);
6388
6389 /* First, look at the partial symtab symbols. */
6390 expand_symtabs_matching (NULL,
6391 lookup_name,
6392 NULL,
6393 NULL,
6394 ALL_DOMAIN);
6395
6396 /* At this point scan through the misc symbol vectors and add each
6397 symbol you find to the list. Eventually we want to ignore
6398 anything that isn't a text symbol (everything else will be
6399 handled by the psymtab code above). */
6400
6401 for (objfile *objfile : current_program_space->objfiles ())
6402 {
6403 for (minimal_symbol *msymbol : objfile->msymbols ())
6404 {
6405 QUIT;
6406
6407 if (completion_skip_symbol (mode, msymbol))
6408 continue;
6409
6410 language symbol_language = msymbol->language ();
6411
6412 /* Ada minimal symbols won't have their language set to Ada. If
6413 we let completion_list_add_name compare using the
6414 default/C-like matcher, then when completing e.g., symbols in a
6415 package named "pck", we'd match internal Ada symbols like
6416 "pckS", which are invalid in an Ada expression, unless you wrap
6417 them in '<' '>' to request a verbatim match.
6418
6419 Unfortunately, some Ada encoded names successfully demangle as
6420 C++ symbols (using an old mangling scheme), such as "name__2Xn"
6421 -> "Xn::name(void)" and thus some Ada minimal symbols end up
6422 with the wrong language set. Paper over that issue here. */
6423 if (symbol_language == language_auto
6424 || symbol_language == language_cplus)
6425 symbol_language = language_ada;
6426
6427 completion_list_add_name (tracker,
6428 symbol_language,
6429 msymbol->linkage_name (),
6430 lookup_name, text, word);
6431 }
6432 }
6433
6434 /* Search upwards from currently selected frame (so that we can
6435 complete on local vars. */
6436
6437 for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
6438 {
6439 if (!BLOCK_SUPERBLOCK (b))
6440 surrounding_static_block = b; /* For elmin of dups */
6441
6442 ALL_BLOCK_SYMBOLS (b, iter, sym)
6443 {
6444 if (completion_skip_symbol (mode, sym))
6445 continue;
6446
6447 completion_list_add_name (tracker,
6448 sym->language (),
6449 sym->linkage_name (),
6450 lookup_name, text, word);
6451 }
6452 }
6453
6454 /* Go through the symtabs and check the externs and statics for
6455 symbols which match. */
6456
6457 for (objfile *objfile : current_program_space->objfiles ())
6458 {
6459 for (compunit_symtab *s : objfile->compunits ())
6460 {
6461 QUIT;
6462 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
6463 ALL_BLOCK_SYMBOLS (b, iter, sym)
6464 {
6465 if (completion_skip_symbol (mode, sym))
6466 continue;
6467
6468 completion_list_add_name (tracker,
6469 sym->language (),
6470 sym->linkage_name (),
6471 lookup_name, text, word);
6472 }
6473 }
6474 }
6475
6476 for (objfile *objfile : current_program_space->objfiles ())
6477 {
6478 for (compunit_symtab *s : objfile->compunits ())
6479 {
6480 QUIT;
6481 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
6482 /* Don't do this block twice. */
6483 if (b == surrounding_static_block)
6484 continue;
6485 ALL_BLOCK_SYMBOLS (b, iter, sym)
6486 {
6487 if (completion_skip_symbol (mode, sym))
6488 continue;
6489
6490 completion_list_add_name (tracker,
6491 sym->language (),
6492 sym->linkage_name (),
6493 lookup_name, text, word);
6494 }
6495 }
6496 }
6497 }
6498
6499 /* Field Access */
6500
6501 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6502 for tagged types. */
6503
6504 static int
6505 ada_is_dispatch_table_ptr_type (struct type *type)
6506 {
6507 const char *name;
6508
6509 if (TYPE_CODE (type) != TYPE_CODE_PTR)
6510 return 0;
6511
6512 name = TYPE_NAME (TYPE_TARGET_TYPE (type));
6513 if (name == NULL)
6514 return 0;
6515
6516 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6517 }
6518
6519 /* Return non-zero if TYPE is an interface tag. */
6520
6521 static int
6522 ada_is_interface_tag (struct type *type)
6523 {
6524 const char *name = TYPE_NAME (type);
6525
6526 if (name == NULL)
6527 return 0;
6528
6529 return (strcmp (name, "ada__tags__interface_tag") == 0);
6530 }
6531
6532 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6533 to be invisible to users. */
6534
6535 int
6536 ada_is_ignored_field (struct type *type, int field_num)
6537 {
6538 if (field_num < 0 || field_num > TYPE_NFIELDS (type))
6539 return 1;
6540
6541 /* Check the name of that field. */
6542 {
6543 const char *name = TYPE_FIELD_NAME (type, field_num);
6544
6545 /* Anonymous field names should not be printed.
6546 brobecker/2007-02-20: I don't think this can actually happen
6547 but we don't want to print the value of anonymous fields anyway. */
6548 if (name == NULL)
6549 return 1;
6550
6551 /* Normally, fields whose name start with an underscore ("_")
6552 are fields that have been internally generated by the compiler,
6553 and thus should not be printed. The "_parent" field is special,
6554 however: This is a field internally generated by the compiler
6555 for tagged types, and it contains the components inherited from
6556 the parent type. This field should not be printed as is, but
6557 should not be ignored either. */
6558 if (name[0] == '_' && !startswith (name, "_parent"))
6559 return 1;
6560 }
6561
6562 /* If this is the dispatch table of a tagged type or an interface tag,
6563 then ignore. */
6564 if (ada_is_tagged_type (type, 1)
6565 && (ada_is_dispatch_table_ptr_type (TYPE_FIELD_TYPE (type, field_num))
6566 || ada_is_interface_tag (TYPE_FIELD_TYPE (type, field_num))))
6567 return 1;
6568
6569 /* Not a special field, so it should not be ignored. */
6570 return 0;
6571 }
6572
6573 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6574 pointer or reference type whose ultimate target has a tag field. */
6575
6576 int
6577 ada_is_tagged_type (struct type *type, int refok)
6578 {
6579 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6580 }
6581
6582 /* True iff TYPE represents the type of X'Tag */
6583
6584 int
6585 ada_is_tag_type (struct type *type)
6586 {
6587 type = ada_check_typedef (type);
6588
6589 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
6590 return 0;
6591 else
6592 {
6593 const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
6594
6595 return (name != NULL
6596 && strcmp (name, "ada__tags__dispatch_table") == 0);
6597 }
6598 }
6599
6600 /* The type of the tag on VAL. */
6601
6602 static struct type *
6603 ada_tag_type (struct value *val)
6604 {
6605 return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6606 }
6607
6608 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6609 retired at Ada 05). */
6610
6611 static int
6612 is_ada95_tag (struct value *tag)
6613 {
6614 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6615 }
6616
6617 /* The value of the tag on VAL. */
6618
6619 static struct value *
6620 ada_value_tag (struct value *val)
6621 {
6622 return ada_value_struct_elt (val, "_tag", 0);
6623 }
6624
6625 /* The value of the tag on the object of type TYPE whose contents are
6626 saved at VALADDR, if it is non-null, or is at memory address
6627 ADDRESS. */
6628
6629 static struct value *
6630 value_tag_from_contents_and_address (struct type *type,
6631 const gdb_byte *valaddr,
6632 CORE_ADDR address)
6633 {
6634 int tag_byte_offset;
6635 struct type *tag_type;
6636
6637 if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
6638 NULL, NULL, NULL))
6639 {
6640 const gdb_byte *valaddr1 = ((valaddr == NULL)
6641 ? NULL
6642 : valaddr + tag_byte_offset);
6643 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6644
6645 return value_from_contents_and_address (tag_type, valaddr1, address1);
6646 }
6647 return NULL;
6648 }
6649
6650 static struct type *
6651 type_from_tag (struct value *tag)
6652 {
6653 const char *type_name = ada_tag_name (tag);
6654
6655 if (type_name != NULL)
6656 return ada_find_any_type (ada_encode (type_name));
6657 return NULL;
6658 }
6659
6660 /* Given a value OBJ of a tagged type, return a value of this
6661 type at the base address of the object. The base address, as
6662 defined in Ada.Tags, it is the address of the primary tag of
6663 the object, and therefore where the field values of its full
6664 view can be fetched. */
6665
6666 struct value *
6667 ada_tag_value_at_base_address (struct value *obj)
6668 {
6669 struct value *val;
6670 LONGEST offset_to_top = 0;
6671 struct type *ptr_type, *obj_type;
6672 struct value *tag;
6673 CORE_ADDR base_address;
6674
6675 obj_type = value_type (obj);
6676
6677 /* It is the responsability of the caller to deref pointers. */
6678
6679 if (TYPE_CODE (obj_type) == TYPE_CODE_PTR
6680 || TYPE_CODE (obj_type) == TYPE_CODE_REF)
6681 return obj;
6682
6683 tag = ada_value_tag (obj);
6684 if (!tag)
6685 return obj;
6686
6687 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6688
6689 if (is_ada95_tag (tag))
6690 return obj;
6691
6692 ptr_type = language_lookup_primitive_type
6693 (language_def (language_ada), target_gdbarch(), "storage_offset");
6694 ptr_type = lookup_pointer_type (ptr_type);
6695 val = value_cast (ptr_type, tag);
6696 if (!val)
6697 return obj;
6698
6699 /* It is perfectly possible that an exception be raised while
6700 trying to determine the base address, just like for the tag;
6701 see ada_tag_name for more details. We do not print the error
6702 message for the same reason. */
6703
6704 try
6705 {
6706 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6707 }
6708
6709 catch (const gdb_exception_error &e)
6710 {
6711 return obj;
6712 }
6713
6714 /* If offset is null, nothing to do. */
6715
6716 if (offset_to_top == 0)
6717 return obj;
6718
6719 /* -1 is a special case in Ada.Tags; however, what should be done
6720 is not quite clear from the documentation. So do nothing for
6721 now. */
6722
6723 if (offset_to_top == -1)
6724 return obj;
6725
6726 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6727 from the base address. This was however incompatible with
6728 C++ dispatch table: C++ uses a *negative* value to *add*
6729 to the base address. Ada's convention has therefore been
6730 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6731 use the same convention. Here, we support both cases by
6732 checking the sign of OFFSET_TO_TOP. */
6733
6734 if (offset_to_top > 0)
6735 offset_to_top = -offset_to_top;
6736
6737 base_address = value_address (obj) + offset_to_top;
6738 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6739
6740 /* Make sure that we have a proper tag at the new address.
6741 Otherwise, offset_to_top is bogus (which can happen when
6742 the object is not initialized yet). */
6743
6744 if (!tag)
6745 return obj;
6746
6747 obj_type = type_from_tag (tag);
6748
6749 if (!obj_type)
6750 return obj;
6751
6752 return value_from_contents_and_address (obj_type, NULL, base_address);
6753 }
6754
6755 /* Return the "ada__tags__type_specific_data" type. */
6756
6757 static struct type *
6758 ada_get_tsd_type (struct inferior *inf)
6759 {
6760 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6761
6762 if (data->tsd_type == 0)
6763 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6764 return data->tsd_type;
6765 }
6766
6767 /* Return the TSD (type-specific data) associated to the given TAG.
6768 TAG is assumed to be the tag of a tagged-type entity.
6769
6770 May return NULL if we are unable to get the TSD. */
6771
6772 static struct value *
6773 ada_get_tsd_from_tag (struct value *tag)
6774 {
6775 struct value *val;
6776 struct type *type;
6777
6778 /* First option: The TSD is simply stored as a field of our TAG.
6779 Only older versions of GNAT would use this format, but we have
6780 to test it first, because there are no visible markers for
6781 the current approach except the absence of that field. */
6782
6783 val = ada_value_struct_elt (tag, "tsd", 1);
6784 if (val)
6785 return val;
6786
6787 /* Try the second representation for the dispatch table (in which
6788 there is no explicit 'tsd' field in the referent of the tag pointer,
6789 and instead the tsd pointer is stored just before the dispatch
6790 table. */
6791
6792 type = ada_get_tsd_type (current_inferior());
6793 if (type == NULL)
6794 return NULL;
6795 type = lookup_pointer_type (lookup_pointer_type (type));
6796 val = value_cast (type, tag);
6797 if (val == NULL)
6798 return NULL;
6799 return value_ind (value_ptradd (val, -1));
6800 }
6801
6802 /* Given the TSD of a tag (type-specific data), return a string
6803 containing the name of the associated type.
6804
6805 The returned value is good until the next call. May return NULL
6806 if we are unable to determine the tag name. */
6807
6808 static char *
6809 ada_tag_name_from_tsd (struct value *tsd)
6810 {
6811 static char name[1024];
6812 char *p;
6813 struct value *val;
6814
6815 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6816 if (val == NULL)
6817 return NULL;
6818 read_memory_string (value_as_address (val), name, sizeof (name) - 1);
6819 for (p = name; *p != '\0'; p += 1)
6820 if (isalpha (*p))
6821 *p = tolower (*p);
6822 return name;
6823 }
6824
6825 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6826 a C string.
6827
6828 Return NULL if the TAG is not an Ada tag, or if we were unable to
6829 determine the name of that tag. The result is good until the next
6830 call. */
6831
6832 const char *
6833 ada_tag_name (struct value *tag)
6834 {
6835 char *name = NULL;
6836
6837 if (!ada_is_tag_type (value_type (tag)))
6838 return NULL;
6839
6840 /* It is perfectly possible that an exception be raised while trying
6841 to determine the TAG's name, even under normal circumstances:
6842 The associated variable may be uninitialized or corrupted, for
6843 instance. We do not let any exception propagate past this point.
6844 instead we return NULL.
6845
6846 We also do not print the error message either (which often is very
6847 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6848 the caller print a more meaningful message if necessary. */
6849 try
6850 {
6851 struct value *tsd = ada_get_tsd_from_tag (tag);
6852
6853 if (tsd != NULL)
6854 name = ada_tag_name_from_tsd (tsd);
6855 }
6856 catch (const gdb_exception_error &e)
6857 {
6858 }
6859
6860 return name;
6861 }
6862
6863 /* The parent type of TYPE, or NULL if none. */
6864
6865 struct type *
6866 ada_parent_type (struct type *type)
6867 {
6868 int i;
6869
6870 type = ada_check_typedef (type);
6871
6872 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
6873 return NULL;
6874
6875 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6876 if (ada_is_parent_field (type, i))
6877 {
6878 struct type *parent_type = TYPE_FIELD_TYPE (type, i);
6879
6880 /* If the _parent field is a pointer, then dereference it. */
6881 if (TYPE_CODE (parent_type) == TYPE_CODE_PTR)
6882 parent_type = TYPE_TARGET_TYPE (parent_type);
6883 /* If there is a parallel XVS type, get the actual base type. */
6884 parent_type = ada_get_base_type (parent_type);
6885
6886 return ada_check_typedef (parent_type);
6887 }
6888
6889 return NULL;
6890 }
6891
6892 /* True iff field number FIELD_NUM of structure type TYPE contains the
6893 parent-type (inherited) fields of a derived type. Assumes TYPE is
6894 a structure type with at least FIELD_NUM+1 fields. */
6895
6896 int
6897 ada_is_parent_field (struct type *type, int field_num)
6898 {
6899 const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
6900
6901 return (name != NULL
6902 && (startswith (name, "PARENT")
6903 || startswith (name, "_parent")));
6904 }
6905
6906 /* True iff field number FIELD_NUM of structure type TYPE is a
6907 transparent wrapper field (which should be silently traversed when doing
6908 field selection and flattened when printing). Assumes TYPE is a
6909 structure type with at least FIELD_NUM+1 fields. Such fields are always
6910 structures. */
6911
6912 int
6913 ada_is_wrapper_field (struct type *type, int field_num)
6914 {
6915 const char *name = TYPE_FIELD_NAME (type, field_num);
6916
6917 if (name != NULL && strcmp (name, "RETVAL") == 0)
6918 {
6919 /* This happens in functions with "out" or "in out" parameters
6920 which are passed by copy. For such functions, GNAT describes
6921 the function's return type as being a struct where the return
6922 value is in a field called RETVAL, and where the other "out"
6923 or "in out" parameters are fields of that struct. This is not
6924 a wrapper. */
6925 return 0;
6926 }
6927
6928 return (name != NULL
6929 && (startswith (name, "PARENT")
6930 || strcmp (name, "REP") == 0
6931 || startswith (name, "_parent")
6932 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6933 }
6934
6935 /* True iff field number FIELD_NUM of structure or union type TYPE
6936 is a variant wrapper. Assumes TYPE is a structure type with at least
6937 FIELD_NUM+1 fields. */
6938
6939 int
6940 ada_is_variant_part (struct type *type, int field_num)
6941 {
6942 /* Only Ada types are eligible. */
6943 if (!ADA_TYPE_P (type))
6944 return 0;
6945
6946 struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
6947
6948 return (TYPE_CODE (field_type) == TYPE_CODE_UNION
6949 || (is_dynamic_field (type, field_num)
6950 && (TYPE_CODE (TYPE_TARGET_TYPE (field_type))
6951 == TYPE_CODE_UNION)));
6952 }
6953
6954 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6955 whose discriminants are contained in the record type OUTER_TYPE,
6956 returns the type of the controlling discriminant for the variant.
6957 May return NULL if the type could not be found. */
6958
6959 struct type *
6960 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6961 {
6962 const char *name = ada_variant_discrim_name (var_type);
6963
6964 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6965 }
6966
6967 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6968 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6969 represents a 'when others' clause; otherwise 0. */
6970
6971 static int
6972 ada_is_others_clause (struct type *type, int field_num)
6973 {
6974 const char *name = TYPE_FIELD_NAME (type, field_num);
6975
6976 return (name != NULL && name[0] == 'O');
6977 }
6978
6979 /* Assuming that TYPE0 is the type of the variant part of a record,
6980 returns the name of the discriminant controlling the variant.
6981 The value is valid until the next call to ada_variant_discrim_name. */
6982
6983 const char *
6984 ada_variant_discrim_name (struct type *type0)
6985 {
6986 static char *result = NULL;
6987 static size_t result_len = 0;
6988 struct type *type;
6989 const char *name;
6990 const char *discrim_end;
6991 const char *discrim_start;
6992
6993 if (TYPE_CODE (type0) == TYPE_CODE_PTR)
6994 type = TYPE_TARGET_TYPE (type0);
6995 else
6996 type = type0;
6997
6998 name = ada_type_name (type);
6999
7000 if (name == NULL || name[0] == '\000')
7001 return "";
7002
7003 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
7004 discrim_end -= 1)
7005 {
7006 if (startswith (discrim_end, "___XVN"))
7007 break;
7008 }
7009 if (discrim_end == name)
7010 return "";
7011
7012 for (discrim_start = discrim_end; discrim_start != name + 3;
7013 discrim_start -= 1)
7014 {
7015 if (discrim_start == name + 1)
7016 return "";
7017 if ((discrim_start > name + 3
7018 && startswith (discrim_start - 3, "___"))
7019 || discrim_start[-1] == '.')
7020 break;
7021 }
7022
7023 GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
7024 strncpy (result, discrim_start, discrim_end - discrim_start);
7025 result[discrim_end - discrim_start] = '\0';
7026 return result;
7027 }
7028
7029 /* Scan STR for a subtype-encoded number, beginning at position K.
7030 Put the position of the character just past the number scanned in
7031 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
7032 Return 1 if there was a valid number at the given position, and 0
7033 otherwise. A "subtype-encoded" number consists of the absolute value
7034 in decimal, followed by the letter 'm' to indicate a negative number.
7035 Assumes 0m does not occur. */
7036
7037 int
7038 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
7039 {
7040 ULONGEST RU;
7041
7042 if (!isdigit (str[k]))
7043 return 0;
7044
7045 /* Do it the hard way so as not to make any assumption about
7046 the relationship of unsigned long (%lu scan format code) and
7047 LONGEST. */
7048 RU = 0;
7049 while (isdigit (str[k]))
7050 {
7051 RU = RU * 10 + (str[k] - '0');
7052 k += 1;
7053 }
7054
7055 if (str[k] == 'm')
7056 {
7057 if (R != NULL)
7058 *R = (-(LONGEST) (RU - 1)) - 1;
7059 k += 1;
7060 }
7061 else if (R != NULL)
7062 *R = (LONGEST) RU;
7063
7064 /* NOTE on the above: Technically, C does not say what the results of
7065 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
7066 number representable as a LONGEST (although either would probably work
7067 in most implementations). When RU>0, the locution in the then branch
7068 above is always equivalent to the negative of RU. */
7069
7070 if (new_k != NULL)
7071 *new_k = k;
7072 return 1;
7073 }
7074
7075 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
7076 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
7077 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
7078
7079 static int
7080 ada_in_variant (LONGEST val, struct type *type, int field_num)
7081 {
7082 const char *name = TYPE_FIELD_NAME (type, field_num);
7083 int p;
7084
7085 p = 0;
7086 while (1)
7087 {
7088 switch (name[p])
7089 {
7090 case '\0':
7091 return 0;
7092 case 'S':
7093 {
7094 LONGEST W;
7095
7096 if (!ada_scan_number (name, p + 1, &W, &p))
7097 return 0;
7098 if (val == W)
7099 return 1;
7100 break;
7101 }
7102 case 'R':
7103 {
7104 LONGEST L, U;
7105
7106 if (!ada_scan_number (name, p + 1, &L, &p)
7107 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
7108 return 0;
7109 if (val >= L && val <= U)
7110 return 1;
7111 break;
7112 }
7113 case 'O':
7114 return 1;
7115 default:
7116 return 0;
7117 }
7118 }
7119 }
7120
7121 /* FIXME: Lots of redundancy below. Try to consolidate. */
7122
7123 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
7124 ARG_TYPE, extract and return the value of one of its (non-static)
7125 fields. FIELDNO says which field. Differs from value_primitive_field
7126 only in that it can handle packed values of arbitrary type. */
7127
7128 static struct value *
7129 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
7130 struct type *arg_type)
7131 {
7132 struct type *type;
7133
7134 arg_type = ada_check_typedef (arg_type);
7135 type = TYPE_FIELD_TYPE (arg_type, fieldno);
7136
7137 /* Handle packed fields. It might be that the field is not packed
7138 relative to its containing structure, but the structure itself is
7139 packed; in this case we must take the bit-field path. */
7140 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
7141 {
7142 int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
7143 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
7144
7145 return ada_value_primitive_packed_val (arg1, value_contents (arg1),
7146 offset + bit_pos / 8,
7147 bit_pos % 8, bit_size, type);
7148 }
7149 else
7150 return value_primitive_field (arg1, offset, fieldno, arg_type);
7151 }
7152
7153 /* Find field with name NAME in object of type TYPE. If found,
7154 set the following for each argument that is non-null:
7155 - *FIELD_TYPE_P to the field's type;
7156 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
7157 an object of that type;
7158 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
7159 - *BIT_SIZE_P to its size in bits if the field is packed, and
7160 0 otherwise;
7161 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
7162 fields up to but not including the desired field, or by the total
7163 number of fields if not found. A NULL value of NAME never
7164 matches; the function just counts visible fields in this case.
7165
7166 Notice that we need to handle when a tagged record hierarchy
7167 has some components with the same name, like in this scenario:
7168
7169 type Top_T is tagged record
7170 N : Integer := 1;
7171 U : Integer := 974;
7172 A : Integer := 48;
7173 end record;
7174
7175 type Middle_T is new Top.Top_T with record
7176 N : Character := 'a';
7177 C : Integer := 3;
7178 end record;
7179
7180 type Bottom_T is new Middle.Middle_T with record
7181 N : Float := 4.0;
7182 C : Character := '5';
7183 X : Integer := 6;
7184 A : Character := 'J';
7185 end record;
7186
7187 Let's say we now have a variable declared and initialized as follow:
7188
7189 TC : Top_A := new Bottom_T;
7190
7191 And then we use this variable to call this function
7192
7193 procedure Assign (Obj: in out Top_T; TV : Integer);
7194
7195 as follow:
7196
7197 Assign (Top_T (B), 12);
7198
7199 Now, we're in the debugger, and we're inside that procedure
7200 then and we want to print the value of obj.c:
7201
7202 Usually, the tagged record or one of the parent type owns the
7203 component to print and there's no issue but in this particular
7204 case, what does it mean to ask for Obj.C? Since the actual
7205 type for object is type Bottom_T, it could mean two things: type
7206 component C from the Middle_T view, but also component C from
7207 Bottom_T. So in that "undefined" case, when the component is
7208 not found in the non-resolved type (which includes all the
7209 components of the parent type), then resolve it and see if we
7210 get better luck once expanded.
7211
7212 In the case of homonyms in the derived tagged type, we don't
7213 guaranty anything, and pick the one that's easiest for us
7214 to program.
7215
7216 Returns 1 if found, 0 otherwise. */
7217
7218 static int
7219 find_struct_field (const char *name, struct type *type, int offset,
7220 struct type **field_type_p,
7221 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
7222 int *index_p)
7223 {
7224 int i;
7225 int parent_offset = -1;
7226
7227 type = ada_check_typedef (type);
7228
7229 if (field_type_p != NULL)
7230 *field_type_p = NULL;
7231 if (byte_offset_p != NULL)
7232 *byte_offset_p = 0;
7233 if (bit_offset_p != NULL)
7234 *bit_offset_p = 0;
7235 if (bit_size_p != NULL)
7236 *bit_size_p = 0;
7237
7238 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7239 {
7240 int bit_pos = TYPE_FIELD_BITPOS (type, i);
7241 int fld_offset = offset + bit_pos / 8;
7242 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7243
7244 if (t_field_name == NULL)
7245 continue;
7246
7247 else if (ada_is_parent_field (type, i))
7248 {
7249 /* This is a field pointing us to the parent type of a tagged
7250 type. As hinted in this function's documentation, we give
7251 preference to fields in the current record first, so what
7252 we do here is just record the index of this field before
7253 we skip it. If it turns out we couldn't find our field
7254 in the current record, then we'll get back to it and search
7255 inside it whether the field might exist in the parent. */
7256
7257 parent_offset = i;
7258 continue;
7259 }
7260
7261 else if (name != NULL && field_name_match (t_field_name, name))
7262 {
7263 int bit_size = TYPE_FIELD_BITSIZE (type, i);
7264
7265 if (field_type_p != NULL)
7266 *field_type_p = TYPE_FIELD_TYPE (type, i);
7267 if (byte_offset_p != NULL)
7268 *byte_offset_p = fld_offset;
7269 if (bit_offset_p != NULL)
7270 *bit_offset_p = bit_pos % 8;
7271 if (bit_size_p != NULL)
7272 *bit_size_p = bit_size;
7273 return 1;
7274 }
7275 else if (ada_is_wrapper_field (type, i))
7276 {
7277 if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
7278 field_type_p, byte_offset_p, bit_offset_p,
7279 bit_size_p, index_p))
7280 return 1;
7281 }
7282 else if (ada_is_variant_part (type, i))
7283 {
7284 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7285 fixed type?? */
7286 int j;
7287 struct type *field_type
7288 = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
7289
7290 for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
7291 {
7292 if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
7293 fld_offset
7294 + TYPE_FIELD_BITPOS (field_type, j) / 8,
7295 field_type_p, byte_offset_p,
7296 bit_offset_p, bit_size_p, index_p))
7297 return 1;
7298 }
7299 }
7300 else if (index_p != NULL)
7301 *index_p += 1;
7302 }
7303
7304 /* Field not found so far. If this is a tagged type which
7305 has a parent, try finding that field in the parent now. */
7306
7307 if (parent_offset != -1)
7308 {
7309 int bit_pos = TYPE_FIELD_BITPOS (type, parent_offset);
7310 int fld_offset = offset + bit_pos / 8;
7311
7312 if (find_struct_field (name, TYPE_FIELD_TYPE (type, parent_offset),
7313 fld_offset, field_type_p, byte_offset_p,
7314 bit_offset_p, bit_size_p, index_p))
7315 return 1;
7316 }
7317
7318 return 0;
7319 }
7320
7321 /* Number of user-visible fields in record type TYPE. */
7322
7323 static int
7324 num_visible_fields (struct type *type)
7325 {
7326 int n;
7327
7328 n = 0;
7329 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7330 return n;
7331 }
7332
7333 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7334 and search in it assuming it has (class) type TYPE.
7335 If found, return value, else return NULL.
7336
7337 Searches recursively through wrapper fields (e.g., '_parent').
7338
7339 In the case of homonyms in the tagged types, please refer to the
7340 long explanation in find_struct_field's function documentation. */
7341
7342 static struct value *
7343 ada_search_struct_field (const char *name, struct value *arg, int offset,
7344 struct type *type)
7345 {
7346 int i;
7347 int parent_offset = -1;
7348
7349 type = ada_check_typedef (type);
7350 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7351 {
7352 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7353
7354 if (t_field_name == NULL)
7355 continue;
7356
7357 else if (ada_is_parent_field (type, i))
7358 {
7359 /* This is a field pointing us to the parent type of a tagged
7360 type. As hinted in this function's documentation, we give
7361 preference to fields in the current record first, so what
7362 we do here is just record the index of this field before
7363 we skip it. If it turns out we couldn't find our field
7364 in the current record, then we'll get back to it and search
7365 inside it whether the field might exist in the parent. */
7366
7367 parent_offset = i;
7368 continue;
7369 }
7370
7371 else if (field_name_match (t_field_name, name))
7372 return ada_value_primitive_field (arg, offset, i, type);
7373
7374 else if (ada_is_wrapper_field (type, i))
7375 {
7376 struct value *v = /* Do not let indent join lines here. */
7377 ada_search_struct_field (name, arg,
7378 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7379 TYPE_FIELD_TYPE (type, i));
7380
7381 if (v != NULL)
7382 return v;
7383 }
7384
7385 else if (ada_is_variant_part (type, i))
7386 {
7387 /* PNH: Do we ever get here? See find_struct_field. */
7388 int j;
7389 struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
7390 i));
7391 int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
7392
7393 for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
7394 {
7395 struct value *v = ada_search_struct_field /* Force line
7396 break. */
7397 (name, arg,
7398 var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
7399 TYPE_FIELD_TYPE (field_type, j));
7400
7401 if (v != NULL)
7402 return v;
7403 }
7404 }
7405 }
7406
7407 /* Field not found so far. If this is a tagged type which
7408 has a parent, try finding that field in the parent now. */
7409
7410 if (parent_offset != -1)
7411 {
7412 struct value *v = ada_search_struct_field (
7413 name, arg, offset + TYPE_FIELD_BITPOS (type, parent_offset) / 8,
7414 TYPE_FIELD_TYPE (type, parent_offset));
7415
7416 if (v != NULL)
7417 return v;
7418 }
7419
7420 return NULL;
7421 }
7422
7423 static struct value *ada_index_struct_field_1 (int *, struct value *,
7424 int, struct type *);
7425
7426
7427 /* Return field #INDEX in ARG, where the index is that returned by
7428 * find_struct_field through its INDEX_P argument. Adjust the address
7429 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7430 * If found, return value, else return NULL. */
7431
7432 static struct value *
7433 ada_index_struct_field (int index, struct value *arg, int offset,
7434 struct type *type)
7435 {
7436 return ada_index_struct_field_1 (&index, arg, offset, type);
7437 }
7438
7439
7440 /* Auxiliary function for ada_index_struct_field. Like
7441 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7442 * *INDEX_P. */
7443
7444 static struct value *
7445 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7446 struct type *type)
7447 {
7448 int i;
7449 type = ada_check_typedef (type);
7450
7451 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7452 {
7453 if (TYPE_FIELD_NAME (type, i) == NULL)
7454 continue;
7455 else if (ada_is_wrapper_field (type, i))
7456 {
7457 struct value *v = /* Do not let indent join lines here. */
7458 ada_index_struct_field_1 (index_p, arg,
7459 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7460 TYPE_FIELD_TYPE (type, i));
7461
7462 if (v != NULL)
7463 return v;
7464 }
7465
7466 else if (ada_is_variant_part (type, i))
7467 {
7468 /* PNH: Do we ever get here? See ada_search_struct_field,
7469 find_struct_field. */
7470 error (_("Cannot assign this kind of variant record"));
7471 }
7472 else if (*index_p == 0)
7473 return ada_value_primitive_field (arg, offset, i, type);
7474 else
7475 *index_p -= 1;
7476 }
7477 return NULL;
7478 }
7479
7480 /* Return a string representation of type TYPE. */
7481
7482 static std::string
7483 type_as_string (struct type *type)
7484 {
7485 string_file tmp_stream;
7486
7487 type_print (type, "", &tmp_stream, -1);
7488
7489 return std::move (tmp_stream.string ());
7490 }
7491
7492 /* Given a type TYPE, look up the type of the component of type named NAME.
7493 If DISPP is non-null, add its byte displacement from the beginning of a
7494 structure (pointed to by a value) of type TYPE to *DISPP (does not
7495 work for packed fields).
7496
7497 Matches any field whose name has NAME as a prefix, possibly
7498 followed by "___".
7499
7500 TYPE can be either a struct or union. If REFOK, TYPE may also
7501 be a (pointer or reference)+ to a struct or union, and the
7502 ultimate target type will be searched.
7503
7504 Looks recursively into variant clauses and parent types.
7505
7506 In the case of homonyms in the tagged types, please refer to the
7507 long explanation in find_struct_field's function documentation.
7508
7509 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7510 TYPE is not a type of the right kind. */
7511
7512 static struct type *
7513 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7514 int noerr)
7515 {
7516 int i;
7517 int parent_offset = -1;
7518
7519 if (name == NULL)
7520 goto BadName;
7521
7522 if (refok && type != NULL)
7523 while (1)
7524 {
7525 type = ada_check_typedef (type);
7526 if (TYPE_CODE (type) != TYPE_CODE_PTR
7527 && TYPE_CODE (type) != TYPE_CODE_REF)
7528 break;
7529 type = TYPE_TARGET_TYPE (type);
7530 }
7531
7532 if (type == NULL
7533 || (TYPE_CODE (type) != TYPE_CODE_STRUCT
7534 && TYPE_CODE (type) != TYPE_CODE_UNION))
7535 {
7536 if (noerr)
7537 return NULL;
7538
7539 error (_("Type %s is not a structure or union type"),
7540 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7541 }
7542
7543 type = to_static_fixed_type (type);
7544
7545 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7546 {
7547 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7548 struct type *t;
7549
7550 if (t_field_name == NULL)
7551 continue;
7552
7553 else if (ada_is_parent_field (type, i))
7554 {
7555 /* This is a field pointing us to the parent type of a tagged
7556 type. As hinted in this function's documentation, we give
7557 preference to fields in the current record first, so what
7558 we do here is just record the index of this field before
7559 we skip it. If it turns out we couldn't find our field
7560 in the current record, then we'll get back to it and search
7561 inside it whether the field might exist in the parent. */
7562
7563 parent_offset = i;
7564 continue;
7565 }
7566
7567 else if (field_name_match (t_field_name, name))
7568 return TYPE_FIELD_TYPE (type, i);
7569
7570 else if (ada_is_wrapper_field (type, i))
7571 {
7572 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
7573 0, 1);
7574 if (t != NULL)
7575 return t;
7576 }
7577
7578 else if (ada_is_variant_part (type, i))
7579 {
7580 int j;
7581 struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
7582 i));
7583
7584 for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
7585 {
7586 /* FIXME pnh 2008/01/26: We check for a field that is
7587 NOT wrapped in a struct, since the compiler sometimes
7588 generates these for unchecked variant types. Revisit
7589 if the compiler changes this practice. */
7590 const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
7591
7592 if (v_field_name != NULL
7593 && field_name_match (v_field_name, name))
7594 t = TYPE_FIELD_TYPE (field_type, j);
7595 else
7596 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type,
7597 j),
7598 name, 0, 1);
7599
7600 if (t != NULL)
7601 return t;
7602 }
7603 }
7604
7605 }
7606
7607 /* Field not found so far. If this is a tagged type which
7608 has a parent, try finding that field in the parent now. */
7609
7610 if (parent_offset != -1)
7611 {
7612 struct type *t;
7613
7614 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, parent_offset),
7615 name, 0, 1);
7616 if (t != NULL)
7617 return t;
7618 }
7619
7620 BadName:
7621 if (!noerr)
7622 {
7623 const char *name_str = name != NULL ? name : _("<null>");
7624
7625 error (_("Type %s has no component named %s"),
7626 type_as_string (type).c_str (), name_str);
7627 }
7628
7629 return NULL;
7630 }
7631
7632 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7633 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7634 represents an unchecked union (that is, the variant part of a
7635 record that is named in an Unchecked_Union pragma). */
7636
7637 static int
7638 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7639 {
7640 const char *discrim_name = ada_variant_discrim_name (var_type);
7641
7642 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7643 }
7644
7645
7646 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7647 within OUTER, determine which variant clause (field number in VAR_TYPE,
7648 numbering from 0) is applicable. Returns -1 if none are. */
7649
7650 int
7651 ada_which_variant_applies (struct type *var_type, struct value *outer)
7652 {
7653 int others_clause;
7654 int i;
7655 const char *discrim_name = ada_variant_discrim_name (var_type);
7656 struct value *discrim;
7657 LONGEST discrim_val;
7658
7659 /* Using plain value_from_contents_and_address here causes problems
7660 because we will end up trying to resolve a type that is currently
7661 being constructed. */
7662 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7663 if (discrim == NULL)
7664 return -1;
7665 discrim_val = value_as_long (discrim);
7666
7667 others_clause = -1;
7668 for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
7669 {
7670 if (ada_is_others_clause (var_type, i))
7671 others_clause = i;
7672 else if (ada_in_variant (discrim_val, var_type, i))
7673 return i;
7674 }
7675
7676 return others_clause;
7677 }
7678 \f
7679
7680
7681 /* Dynamic-Sized Records */
7682
7683 /* Strategy: The type ostensibly attached to a value with dynamic size
7684 (i.e., a size that is not statically recorded in the debugging
7685 data) does not accurately reflect the size or layout of the value.
7686 Our strategy is to convert these values to values with accurate,
7687 conventional types that are constructed on the fly. */
7688
7689 /* There is a subtle and tricky problem here. In general, we cannot
7690 determine the size of dynamic records without its data. However,
7691 the 'struct value' data structure, which GDB uses to represent
7692 quantities in the inferior process (the target), requires the size
7693 of the type at the time of its allocation in order to reserve space
7694 for GDB's internal copy of the data. That's why the
7695 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7696 rather than struct value*s.
7697
7698 However, GDB's internal history variables ($1, $2, etc.) are
7699 struct value*s containing internal copies of the data that are not, in
7700 general, the same as the data at their corresponding addresses in
7701 the target. Fortunately, the types we give to these values are all
7702 conventional, fixed-size types (as per the strategy described
7703 above), so that we don't usually have to perform the
7704 'to_fixed_xxx_type' conversions to look at their values.
7705 Unfortunately, there is one exception: if one of the internal
7706 history variables is an array whose elements are unconstrained
7707 records, then we will need to create distinct fixed types for each
7708 element selected. */
7709
7710 /* The upshot of all of this is that many routines take a (type, host
7711 address, target address) triple as arguments to represent a value.
7712 The host address, if non-null, is supposed to contain an internal
7713 copy of the relevant data; otherwise, the program is to consult the
7714 target at the target address. */
7715
7716 /* Assuming that VAL0 represents a pointer value, the result of
7717 dereferencing it. Differs from value_ind in its treatment of
7718 dynamic-sized types. */
7719
7720 struct value *
7721 ada_value_ind (struct value *val0)
7722 {
7723 struct value *val = value_ind (val0);
7724
7725 if (ada_is_tagged_type (value_type (val), 0))
7726 val = ada_tag_value_at_base_address (val);
7727
7728 return ada_to_fixed_value (val);
7729 }
7730
7731 /* The value resulting from dereferencing any "reference to"
7732 qualifiers on VAL0. */
7733
7734 static struct value *
7735 ada_coerce_ref (struct value *val0)
7736 {
7737 if (TYPE_CODE (value_type (val0)) == TYPE_CODE_REF)
7738 {
7739 struct value *val = val0;
7740
7741 val = coerce_ref (val);
7742
7743 if (ada_is_tagged_type (value_type (val), 0))
7744 val = ada_tag_value_at_base_address (val);
7745
7746 return ada_to_fixed_value (val);
7747 }
7748 else
7749 return val0;
7750 }
7751
7752 /* Return OFF rounded upward if necessary to a multiple of
7753 ALIGNMENT (a power of 2). */
7754
7755 static unsigned int
7756 align_value (unsigned int off, unsigned int alignment)
7757 {
7758 return (off + alignment - 1) & ~(alignment - 1);
7759 }
7760
7761 /* Return the bit alignment required for field #F of template type TYPE. */
7762
7763 static unsigned int
7764 field_alignment (struct type *type, int f)
7765 {
7766 const char *name = TYPE_FIELD_NAME (type, f);
7767 int len;
7768 int align_offset;
7769
7770 /* The field name should never be null, unless the debugging information
7771 is somehow malformed. In this case, we assume the field does not
7772 require any alignment. */
7773 if (name == NULL)
7774 return 1;
7775
7776 len = strlen (name);
7777
7778 if (!isdigit (name[len - 1]))
7779 return 1;
7780
7781 if (isdigit (name[len - 2]))
7782 align_offset = len - 2;
7783 else
7784 align_offset = len - 1;
7785
7786 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7787 return TARGET_CHAR_BIT;
7788
7789 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7790 }
7791
7792 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7793
7794 static struct symbol *
7795 ada_find_any_type_symbol (const char *name)
7796 {
7797 struct symbol *sym;
7798
7799 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7800 if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
7801 return sym;
7802
7803 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7804 return sym;
7805 }
7806
7807 /* Find a type named NAME. Ignores ambiguity. This routine will look
7808 solely for types defined by debug info, it will not search the GDB
7809 primitive types. */
7810
7811 static struct type *
7812 ada_find_any_type (const char *name)
7813 {
7814 struct symbol *sym = ada_find_any_type_symbol (name);
7815
7816 if (sym != NULL)
7817 return SYMBOL_TYPE (sym);
7818
7819 return NULL;
7820 }
7821
7822 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7823 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7824 symbol, in which case it is returned. Otherwise, this looks for
7825 symbols whose name is that of NAME_SYM suffixed with "___XR".
7826 Return symbol if found, and NULL otherwise. */
7827
7828 static bool
7829 ada_is_renaming_symbol (struct symbol *name_sym)
7830 {
7831 const char *name = name_sym->linkage_name ();
7832 return strstr (name, "___XR") != NULL;
7833 }
7834
7835 /* Because of GNAT encoding conventions, several GDB symbols may match a
7836 given type name. If the type denoted by TYPE0 is to be preferred to
7837 that of TYPE1 for purposes of type printing, return non-zero;
7838 otherwise return 0. */
7839
7840 int
7841 ada_prefer_type (struct type *type0, struct type *type1)
7842 {
7843 if (type1 == NULL)
7844 return 1;
7845 else if (type0 == NULL)
7846 return 0;
7847 else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
7848 return 1;
7849 else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
7850 return 0;
7851 else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
7852 return 1;
7853 else if (ada_is_constrained_packed_array_type (type0))
7854 return 1;
7855 else if (ada_is_array_descriptor_type (type0)
7856 && !ada_is_array_descriptor_type (type1))
7857 return 1;
7858 else
7859 {
7860 const char *type0_name = TYPE_NAME (type0);
7861 const char *type1_name = TYPE_NAME (type1);
7862
7863 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7864 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7865 return 1;
7866 }
7867 return 0;
7868 }
7869
7870 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7871 null. */
7872
7873 const char *
7874 ada_type_name (struct type *type)
7875 {
7876 if (type == NULL)
7877 return NULL;
7878 return TYPE_NAME (type);
7879 }
7880
7881 /* Search the list of "descriptive" types associated to TYPE for a type
7882 whose name is NAME. */
7883
7884 static struct type *
7885 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7886 {
7887 struct type *result, *tmp;
7888
7889 if (ada_ignore_descriptive_types_p)
7890 return NULL;
7891
7892 /* If there no descriptive-type info, then there is no parallel type
7893 to be found. */
7894 if (!HAVE_GNAT_AUX_INFO (type))
7895 return NULL;
7896
7897 result = TYPE_DESCRIPTIVE_TYPE (type);
7898 while (result != NULL)
7899 {
7900 const char *result_name = ada_type_name (result);
7901
7902 if (result_name == NULL)
7903 {
7904 warning (_("unexpected null name on descriptive type"));
7905 return NULL;
7906 }
7907
7908 /* If the names match, stop. */
7909 if (strcmp (result_name, name) == 0)
7910 break;
7911
7912 /* Otherwise, look at the next item on the list, if any. */
7913 if (HAVE_GNAT_AUX_INFO (result))
7914 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7915 else
7916 tmp = NULL;
7917
7918 /* If not found either, try after having resolved the typedef. */
7919 if (tmp != NULL)
7920 result = tmp;
7921 else
7922 {
7923 result = check_typedef (result);
7924 if (HAVE_GNAT_AUX_INFO (result))
7925 result = TYPE_DESCRIPTIVE_TYPE (result);
7926 else
7927 result = NULL;
7928 }
7929 }
7930
7931 /* If we didn't find a match, see whether this is a packed array. With
7932 older compilers, the descriptive type information is either absent or
7933 irrelevant when it comes to packed arrays so the above lookup fails.
7934 Fall back to using a parallel lookup by name in this case. */
7935 if (result == NULL && ada_is_constrained_packed_array_type (type))
7936 return ada_find_any_type (name);
7937
7938 return result;
7939 }
7940
7941 /* Find a parallel type to TYPE with the specified NAME, using the
7942 descriptive type taken from the debugging information, if available,
7943 and otherwise using the (slower) name-based method. */
7944
7945 static struct type *
7946 ada_find_parallel_type_with_name (struct type *type, const char *name)
7947 {
7948 struct type *result = NULL;
7949
7950 if (HAVE_GNAT_AUX_INFO (type))
7951 result = find_parallel_type_by_descriptive_type (type, name);
7952 else
7953 result = ada_find_any_type (name);
7954
7955 return result;
7956 }
7957
7958 /* Same as above, but specify the name of the parallel type by appending
7959 SUFFIX to the name of TYPE. */
7960
7961 struct type *
7962 ada_find_parallel_type (struct type *type, const char *suffix)
7963 {
7964 char *name;
7965 const char *type_name = ada_type_name (type);
7966 int len;
7967
7968 if (type_name == NULL)
7969 return NULL;
7970
7971 len = strlen (type_name);
7972
7973 name = (char *) alloca (len + strlen (suffix) + 1);
7974
7975 strcpy (name, type_name);
7976 strcpy (name + len, suffix);
7977
7978 return ada_find_parallel_type_with_name (type, name);
7979 }
7980
7981 /* If TYPE is a variable-size record type, return the corresponding template
7982 type describing its fields. Otherwise, return NULL. */
7983
7984 static struct type *
7985 dynamic_template_type (struct type *type)
7986 {
7987 type = ada_check_typedef (type);
7988
7989 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
7990 || ada_type_name (type) == NULL)
7991 return NULL;
7992 else
7993 {
7994 int len = strlen (ada_type_name (type));
7995
7996 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7997 return type;
7998 else
7999 return ada_find_parallel_type (type, "___XVE");
8000 }
8001 }
8002
8003 /* Assuming that TEMPL_TYPE is a union or struct type, returns
8004 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
8005
8006 static int
8007 is_dynamic_field (struct type *templ_type, int field_num)
8008 {
8009 const char *name = TYPE_FIELD_NAME (templ_type, field_num);
8010
8011 return name != NULL
8012 && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
8013 && strstr (name, "___XVL") != NULL;
8014 }
8015
8016 /* The index of the variant field of TYPE, or -1 if TYPE does not
8017 represent a variant record type. */
8018
8019 static int
8020 variant_field_index (struct type *type)
8021 {
8022 int f;
8023
8024 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
8025 return -1;
8026
8027 for (f = 0; f < TYPE_NFIELDS (type); f += 1)
8028 {
8029 if (ada_is_variant_part (type, f))
8030 return f;
8031 }
8032 return -1;
8033 }
8034
8035 /* A record type with no fields. */
8036
8037 static struct type *
8038 empty_record (struct type *templ)
8039 {
8040 struct type *type = alloc_type_copy (templ);
8041
8042 TYPE_CODE (type) = TYPE_CODE_STRUCT;
8043 TYPE_NFIELDS (type) = 0;
8044 TYPE_FIELDS (type) = NULL;
8045 INIT_NONE_SPECIFIC (type);
8046 TYPE_NAME (type) = "<empty>";
8047 TYPE_LENGTH (type) = 0;
8048 return type;
8049 }
8050
8051 /* An ordinary record type (with fixed-length fields) that describes
8052 the value of type TYPE at VALADDR or ADDRESS (see comments at
8053 the beginning of this section) VAL according to GNAT conventions.
8054 DVAL0 should describe the (portion of a) record that contains any
8055 necessary discriminants. It should be NULL if value_type (VAL) is
8056 an outer-level type (i.e., as opposed to a branch of a variant.) A
8057 variant field (unless unchecked) is replaced by a particular branch
8058 of the variant.
8059
8060 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
8061 length are not statically known are discarded. As a consequence,
8062 VALADDR, ADDRESS and DVAL0 are ignored.
8063
8064 NOTE: Limitations: For now, we assume that dynamic fields and
8065 variants occupy whole numbers of bytes. However, they need not be
8066 byte-aligned. */
8067
8068 struct type *
8069 ada_template_to_fixed_record_type_1 (struct type *type,
8070 const gdb_byte *valaddr,
8071 CORE_ADDR address, struct value *dval0,
8072 int keep_dynamic_fields)
8073 {
8074 struct value *mark = value_mark ();
8075 struct value *dval;
8076 struct type *rtype;
8077 int nfields, bit_len;
8078 int variant_field;
8079 long off;
8080 int fld_bit_len;
8081 int f;
8082
8083 /* Compute the number of fields in this record type that are going
8084 to be processed: unless keep_dynamic_fields, this includes only
8085 fields whose position and length are static will be processed. */
8086 if (keep_dynamic_fields)
8087 nfields = TYPE_NFIELDS (type);
8088 else
8089 {
8090 nfields = 0;
8091 while (nfields < TYPE_NFIELDS (type)
8092 && !ada_is_variant_part (type, nfields)
8093 && !is_dynamic_field (type, nfields))
8094 nfields++;
8095 }
8096
8097 rtype = alloc_type_copy (type);
8098 TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
8099 INIT_NONE_SPECIFIC (rtype);
8100 TYPE_NFIELDS (rtype) = nfields;
8101 TYPE_FIELDS (rtype) = (struct field *)
8102 TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8103 memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
8104 TYPE_NAME (rtype) = ada_type_name (type);
8105 TYPE_FIXED_INSTANCE (rtype) = 1;
8106
8107 off = 0;
8108 bit_len = 0;
8109 variant_field = -1;
8110
8111 for (f = 0; f < nfields; f += 1)
8112 {
8113 off = align_value (off, field_alignment (type, f))
8114 + TYPE_FIELD_BITPOS (type, f);
8115 SET_FIELD_BITPOS (TYPE_FIELD (rtype, f), off);
8116 TYPE_FIELD_BITSIZE (rtype, f) = 0;
8117
8118 if (ada_is_variant_part (type, f))
8119 {
8120 variant_field = f;
8121 fld_bit_len = 0;
8122 }
8123 else if (is_dynamic_field (type, f))
8124 {
8125 const gdb_byte *field_valaddr = valaddr;
8126 CORE_ADDR field_address = address;
8127 struct type *field_type =
8128 TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f));
8129
8130 if (dval0 == NULL)
8131 {
8132 /* rtype's length is computed based on the run-time
8133 value of discriminants. If the discriminants are not
8134 initialized, the type size may be completely bogus and
8135 GDB may fail to allocate a value for it. So check the
8136 size first before creating the value. */
8137 ada_ensure_varsize_limit (rtype);
8138 /* Using plain value_from_contents_and_address here
8139 causes problems because we will end up trying to
8140 resolve a type that is currently being
8141 constructed. */
8142 dval = value_from_contents_and_address_unresolved (rtype,
8143 valaddr,
8144 address);
8145 rtype = value_type (dval);
8146 }
8147 else
8148 dval = dval0;
8149
8150 /* If the type referenced by this field is an aligner type, we need
8151 to unwrap that aligner type, because its size might not be set.
8152 Keeping the aligner type would cause us to compute the wrong
8153 size for this field, impacting the offset of the all the fields
8154 that follow this one. */
8155 if (ada_is_aligner_type (field_type))
8156 {
8157 long field_offset = TYPE_FIELD_BITPOS (field_type, f);
8158
8159 field_valaddr = cond_offset_host (field_valaddr, field_offset);
8160 field_address = cond_offset_target (field_address, field_offset);
8161 field_type = ada_aligned_type (field_type);
8162 }
8163
8164 field_valaddr = cond_offset_host (field_valaddr,
8165 off / TARGET_CHAR_BIT);
8166 field_address = cond_offset_target (field_address,
8167 off / TARGET_CHAR_BIT);
8168
8169 /* Get the fixed type of the field. Note that, in this case,
8170 we do not want to get the real type out of the tag: if
8171 the current field is the parent part of a tagged record,
8172 we will get the tag of the object. Clearly wrong: the real
8173 type of the parent is not the real type of the child. We
8174 would end up in an infinite loop. */
8175 field_type = ada_get_base_type (field_type);
8176 field_type = ada_to_fixed_type (field_type, field_valaddr,
8177 field_address, dval, 0);
8178 /* If the field size is already larger than the maximum
8179 object size, then the record itself will necessarily
8180 be larger than the maximum object size. We need to make
8181 this check now, because the size might be so ridiculously
8182 large (due to an uninitialized variable in the inferior)
8183 that it would cause an overflow when adding it to the
8184 record size. */
8185 ada_ensure_varsize_limit (field_type);
8186
8187 TYPE_FIELD_TYPE (rtype, f) = field_type;
8188 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
8189 /* The multiplication can potentially overflow. But because
8190 the field length has been size-checked just above, and
8191 assuming that the maximum size is a reasonable value,
8192 an overflow should not happen in practice. So rather than
8193 adding overflow recovery code to this already complex code,
8194 we just assume that it's not going to happen. */
8195 fld_bit_len =
8196 TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
8197 }
8198 else
8199 {
8200 /* Note: If this field's type is a typedef, it is important
8201 to preserve the typedef layer.
8202
8203 Otherwise, we might be transforming a typedef to a fat
8204 pointer (encoding a pointer to an unconstrained array),
8205 into a basic fat pointer (encoding an unconstrained
8206 array). As both types are implemented using the same
8207 structure, the typedef is the only clue which allows us
8208 to distinguish between the two options. Stripping it
8209 would prevent us from printing this field appropriately. */
8210 TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
8211 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
8212 if (TYPE_FIELD_BITSIZE (type, f) > 0)
8213 fld_bit_len =
8214 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
8215 else
8216 {
8217 struct type *field_type = TYPE_FIELD_TYPE (type, f);
8218
8219 /* We need to be careful of typedefs when computing
8220 the length of our field. If this is a typedef,
8221 get the length of the target type, not the length
8222 of the typedef. */
8223 if (TYPE_CODE (field_type) == TYPE_CODE_TYPEDEF)
8224 field_type = ada_typedef_target_type (field_type);
8225
8226 fld_bit_len =
8227 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
8228 }
8229 }
8230 if (off + fld_bit_len > bit_len)
8231 bit_len = off + fld_bit_len;
8232 off += fld_bit_len;
8233 TYPE_LENGTH (rtype) =
8234 align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
8235 }
8236
8237 /* We handle the variant part, if any, at the end because of certain
8238 odd cases in which it is re-ordered so as NOT to be the last field of
8239 the record. This can happen in the presence of representation
8240 clauses. */
8241 if (variant_field >= 0)
8242 {
8243 struct type *branch_type;
8244
8245 off = TYPE_FIELD_BITPOS (rtype, variant_field);
8246
8247 if (dval0 == NULL)
8248 {
8249 /* Using plain value_from_contents_and_address here causes
8250 problems because we will end up trying to resolve a type
8251 that is currently being constructed. */
8252 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
8253 address);
8254 rtype = value_type (dval);
8255 }
8256 else
8257 dval = dval0;
8258
8259 branch_type =
8260 to_fixed_variant_branch_type
8261 (TYPE_FIELD_TYPE (type, variant_field),
8262 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
8263 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
8264 if (branch_type == NULL)
8265 {
8266 for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
8267 TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
8268 TYPE_NFIELDS (rtype) -= 1;
8269 }
8270 else
8271 {
8272 TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
8273 TYPE_FIELD_NAME (rtype, variant_field) = "S";
8274 fld_bit_len =
8275 TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
8276 TARGET_CHAR_BIT;
8277 if (off + fld_bit_len > bit_len)
8278 bit_len = off + fld_bit_len;
8279 TYPE_LENGTH (rtype) =
8280 align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
8281 }
8282 }
8283
8284 /* According to exp_dbug.ads, the size of TYPE for variable-size records
8285 should contain the alignment of that record, which should be a strictly
8286 positive value. If null or negative, then something is wrong, most
8287 probably in the debug info. In that case, we don't round up the size
8288 of the resulting type. If this record is not part of another structure,
8289 the current RTYPE length might be good enough for our purposes. */
8290 if (TYPE_LENGTH (type) <= 0)
8291 {
8292 if (TYPE_NAME (rtype))
8293 warning (_("Invalid type size for `%s' detected: %s."),
8294 TYPE_NAME (rtype), pulongest (TYPE_LENGTH (type)));
8295 else
8296 warning (_("Invalid type size for <unnamed> detected: %s."),
8297 pulongest (TYPE_LENGTH (type)));
8298 }
8299 else
8300 {
8301 TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype),
8302 TYPE_LENGTH (type));
8303 }
8304
8305 value_free_to_mark (mark);
8306 if (TYPE_LENGTH (rtype) > varsize_limit)
8307 error (_("record type with dynamic size is larger than varsize-limit"));
8308 return rtype;
8309 }
8310
8311 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8312 of 1. */
8313
8314 static struct type *
8315 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8316 CORE_ADDR address, struct value *dval0)
8317 {
8318 return ada_template_to_fixed_record_type_1 (type, valaddr,
8319 address, dval0, 1);
8320 }
8321
8322 /* An ordinary record type in which ___XVL-convention fields and
8323 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8324 static approximations, containing all possible fields. Uses
8325 no runtime values. Useless for use in values, but that's OK,
8326 since the results are used only for type determinations. Works on both
8327 structs and unions. Representation note: to save space, we memorize
8328 the result of this function in the TYPE_TARGET_TYPE of the
8329 template type. */
8330
8331 static struct type *
8332 template_to_static_fixed_type (struct type *type0)
8333 {
8334 struct type *type;
8335 int nfields;
8336 int f;
8337
8338 /* No need no do anything if the input type is already fixed. */
8339 if (TYPE_FIXED_INSTANCE (type0))
8340 return type0;
8341
8342 /* Likewise if we already have computed the static approximation. */
8343 if (TYPE_TARGET_TYPE (type0) != NULL)
8344 return TYPE_TARGET_TYPE (type0);
8345
8346 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8347 type = type0;
8348 nfields = TYPE_NFIELDS (type0);
8349
8350 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8351 recompute all over next time. */
8352 TYPE_TARGET_TYPE (type0) = type;
8353
8354 for (f = 0; f < nfields; f += 1)
8355 {
8356 struct type *field_type = TYPE_FIELD_TYPE (type0, f);
8357 struct type *new_type;
8358
8359 if (is_dynamic_field (type0, f))
8360 {
8361 field_type = ada_check_typedef (field_type);
8362 new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
8363 }
8364 else
8365 new_type = static_unwrap_type (field_type);
8366
8367 if (new_type != field_type)
8368 {
8369 /* Clone TYPE0 only the first time we get a new field type. */
8370 if (type == type0)
8371 {
8372 TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
8373 TYPE_CODE (type) = TYPE_CODE (type0);
8374 INIT_NONE_SPECIFIC (type);
8375 TYPE_NFIELDS (type) = nfields;
8376 TYPE_FIELDS (type) = (struct field *)
8377 TYPE_ALLOC (type, nfields * sizeof (struct field));
8378 memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
8379 sizeof (struct field) * nfields);
8380 TYPE_NAME (type) = ada_type_name (type0);
8381 TYPE_FIXED_INSTANCE (type) = 1;
8382 TYPE_LENGTH (type) = 0;
8383 }
8384 TYPE_FIELD_TYPE (type, f) = new_type;
8385 TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
8386 }
8387 }
8388
8389 return type;
8390 }
8391
8392 /* Given an object of type TYPE whose contents are at VALADDR and
8393 whose address in memory is ADDRESS, returns a revision of TYPE,
8394 which should be a non-dynamic-sized record, in which the variant
8395 part, if any, is replaced with the appropriate branch. Looks
8396 for discriminant values in DVAL0, which can be NULL if the record
8397 contains the necessary discriminant values. */
8398
8399 static struct type *
8400 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8401 CORE_ADDR address, struct value *dval0)
8402 {
8403 struct value *mark = value_mark ();
8404 struct value *dval;
8405 struct type *rtype;
8406 struct type *branch_type;
8407 int nfields = TYPE_NFIELDS (type);
8408 int variant_field = variant_field_index (type);
8409
8410 if (variant_field == -1)
8411 return type;
8412
8413 if (dval0 == NULL)
8414 {
8415 dval = value_from_contents_and_address (type, valaddr, address);
8416 type = value_type (dval);
8417 }
8418 else
8419 dval = dval0;
8420
8421 rtype = alloc_type_copy (type);
8422 TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
8423 INIT_NONE_SPECIFIC (rtype);
8424 TYPE_NFIELDS (rtype) = nfields;
8425 TYPE_FIELDS (rtype) =
8426 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8427 memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
8428 sizeof (struct field) * nfields);
8429 TYPE_NAME (rtype) = ada_type_name (type);
8430 TYPE_FIXED_INSTANCE (rtype) = 1;
8431 TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
8432
8433 branch_type = to_fixed_variant_branch_type
8434 (TYPE_FIELD_TYPE (type, variant_field),
8435 cond_offset_host (valaddr,
8436 TYPE_FIELD_BITPOS (type, variant_field)
8437 / TARGET_CHAR_BIT),
8438 cond_offset_target (address,
8439 TYPE_FIELD_BITPOS (type, variant_field)
8440 / TARGET_CHAR_BIT), dval);
8441 if (branch_type == NULL)
8442 {
8443 int f;
8444
8445 for (f = variant_field + 1; f < nfields; f += 1)
8446 TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
8447 TYPE_NFIELDS (rtype) -= 1;
8448 }
8449 else
8450 {
8451 TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
8452 TYPE_FIELD_NAME (rtype, variant_field) = "S";
8453 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8454 TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
8455 }
8456 TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));
8457
8458 value_free_to_mark (mark);
8459 return rtype;
8460 }
8461
8462 /* An ordinary record type (with fixed-length fields) that describes
8463 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8464 beginning of this section]. Any necessary discriminants' values
8465 should be in DVAL, a record value; it may be NULL if the object
8466 at ADDR itself contains any necessary discriminant values.
8467 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8468 values from the record are needed. Except in the case that DVAL,
8469 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8470 unchecked) is replaced by a particular branch of the variant.
8471
8472 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8473 is questionable and may be removed. It can arise during the
8474 processing of an unconstrained-array-of-record type where all the
8475 variant branches have exactly the same size. This is because in
8476 such cases, the compiler does not bother to use the XVS convention
8477 when encoding the record. I am currently dubious of this
8478 shortcut and suspect the compiler should be altered. FIXME. */
8479
8480 static struct type *
8481 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8482 CORE_ADDR address, struct value *dval)
8483 {
8484 struct type *templ_type;
8485
8486 if (TYPE_FIXED_INSTANCE (type0))
8487 return type0;
8488
8489 templ_type = dynamic_template_type (type0);
8490
8491 if (templ_type != NULL)
8492 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8493 else if (variant_field_index (type0) >= 0)
8494 {
8495 if (dval == NULL && valaddr == NULL && address == 0)
8496 return type0;
8497 return to_record_with_fixed_variant_part (type0, valaddr, address,
8498 dval);
8499 }
8500 else
8501 {
8502 TYPE_FIXED_INSTANCE (type0) = 1;
8503 return type0;
8504 }
8505
8506 }
8507
8508 /* An ordinary record type (with fixed-length fields) that describes
8509 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8510 union type. Any necessary discriminants' values should be in DVAL,
8511 a record value. That is, this routine selects the appropriate
8512 branch of the union at ADDR according to the discriminant value
8513 indicated in the union's type name. Returns VAR_TYPE0 itself if
8514 it represents a variant subject to a pragma Unchecked_Union. */
8515
8516 static struct type *
8517 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8518 CORE_ADDR address, struct value *dval)
8519 {
8520 int which;
8521 struct type *templ_type;
8522 struct type *var_type;
8523
8524 if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
8525 var_type = TYPE_TARGET_TYPE (var_type0);
8526 else
8527 var_type = var_type0;
8528
8529 templ_type = ada_find_parallel_type (var_type, "___XVU");
8530
8531 if (templ_type != NULL)
8532 var_type = templ_type;
8533
8534 if (is_unchecked_variant (var_type, value_type (dval)))
8535 return var_type0;
8536 which = ada_which_variant_applies (var_type, dval);
8537
8538 if (which < 0)
8539 return empty_record (var_type);
8540 else if (is_dynamic_field (var_type, which))
8541 return to_fixed_record_type
8542 (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
8543 valaddr, address, dval);
8544 else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
8545 return
8546 to_fixed_record_type
8547 (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
8548 else
8549 return TYPE_FIELD_TYPE (var_type, which);
8550 }
8551
8552 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8553 ENCODING_TYPE, a type following the GNAT conventions for discrete
8554 type encodings, only carries redundant information. */
8555
8556 static int
8557 ada_is_redundant_range_encoding (struct type *range_type,
8558 struct type *encoding_type)
8559 {
8560 const char *bounds_str;
8561 int n;
8562 LONGEST lo, hi;
8563
8564 gdb_assert (TYPE_CODE (range_type) == TYPE_CODE_RANGE);
8565
8566 if (TYPE_CODE (get_base_type (range_type))
8567 != TYPE_CODE (get_base_type (encoding_type)))
8568 {
8569 /* The compiler probably used a simple base type to describe
8570 the range type instead of the range's actual base type,
8571 expecting us to get the real base type from the encoding
8572 anyway. In this situation, the encoding cannot be ignored
8573 as redundant. */
8574 return 0;
8575 }
8576
8577 if (is_dynamic_type (range_type))
8578 return 0;
8579
8580 if (TYPE_NAME (encoding_type) == NULL)
8581 return 0;
8582
8583 bounds_str = strstr (TYPE_NAME (encoding_type), "___XDLU_");
8584 if (bounds_str == NULL)
8585 return 0;
8586
8587 n = 8; /* Skip "___XDLU_". */
8588 if (!ada_scan_number (bounds_str, n, &lo, &n))
8589 return 0;
8590 if (TYPE_LOW_BOUND (range_type) != lo)
8591 return 0;
8592
8593 n += 2; /* Skip the "__" separator between the two bounds. */
8594 if (!ada_scan_number (bounds_str, n, &hi, &n))
8595 return 0;
8596 if (TYPE_HIGH_BOUND (range_type) != hi)
8597 return 0;
8598
8599 return 1;
8600 }
8601
8602 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8603 a type following the GNAT encoding for describing array type
8604 indices, only carries redundant information. */
8605
8606 static int
8607 ada_is_redundant_index_type_desc (struct type *array_type,
8608 struct type *desc_type)
8609 {
8610 struct type *this_layer = check_typedef (array_type);
8611 int i;
8612
8613 for (i = 0; i < TYPE_NFIELDS (desc_type); i++)
8614 {
8615 if (!ada_is_redundant_range_encoding (TYPE_INDEX_TYPE (this_layer),
8616 TYPE_FIELD_TYPE (desc_type, i)))
8617 return 0;
8618 this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
8619 }
8620
8621 return 1;
8622 }
8623
8624 /* Assuming that TYPE0 is an array type describing the type of a value
8625 at ADDR, and that DVAL describes a record containing any
8626 discriminants used in TYPE0, returns a type for the value that
8627 contains no dynamic components (that is, no components whose sizes
8628 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8629 true, gives an error message if the resulting type's size is over
8630 varsize_limit. */
8631
8632 static struct type *
8633 to_fixed_array_type (struct type *type0, struct value *dval,
8634 int ignore_too_big)
8635 {
8636 struct type *index_type_desc;
8637 struct type *result;
8638 int constrained_packed_array_p;
8639 static const char *xa_suffix = "___XA";
8640
8641 type0 = ada_check_typedef (type0);
8642 if (TYPE_FIXED_INSTANCE (type0))
8643 return type0;
8644
8645 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8646 if (constrained_packed_array_p)
8647 type0 = decode_constrained_packed_array_type (type0);
8648
8649 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8650
8651 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8652 encoding suffixed with 'P' may still be generated. If so,
8653 it should be used to find the XA type. */
8654
8655 if (index_type_desc == NULL)
8656 {
8657 const char *type_name = ada_type_name (type0);
8658
8659 if (type_name != NULL)
8660 {
8661 const int len = strlen (type_name);
8662 char *name = (char *) alloca (len + strlen (xa_suffix));
8663
8664 if (type_name[len - 1] == 'P')
8665 {
8666 strcpy (name, type_name);
8667 strcpy (name + len - 1, xa_suffix);
8668 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8669 }
8670 }
8671 }
8672
8673 ada_fixup_array_indexes_type (index_type_desc);
8674 if (index_type_desc != NULL
8675 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8676 {
8677 /* Ignore this ___XA parallel type, as it does not bring any
8678 useful information. This allows us to avoid creating fixed
8679 versions of the array's index types, which would be identical
8680 to the original ones. This, in turn, can also help avoid
8681 the creation of fixed versions of the array itself. */
8682 index_type_desc = NULL;
8683 }
8684
8685 if (index_type_desc == NULL)
8686 {
8687 struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8688
8689 /* NOTE: elt_type---the fixed version of elt_type0---should never
8690 depend on the contents of the array in properly constructed
8691 debugging data. */
8692 /* Create a fixed version of the array element type.
8693 We're not providing the address of an element here,
8694 and thus the actual object value cannot be inspected to do
8695 the conversion. This should not be a problem, since arrays of
8696 unconstrained objects are not allowed. In particular, all
8697 the elements of an array of a tagged type should all be of
8698 the same type specified in the debugging info. No need to
8699 consult the object tag. */
8700 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8701
8702 /* Make sure we always create a new array type when dealing with
8703 packed array types, since we're going to fix-up the array
8704 type length and element bitsize a little further down. */
8705 if (elt_type0 == elt_type && !constrained_packed_array_p)
8706 result = type0;
8707 else
8708 result = create_array_type (alloc_type_copy (type0),
8709 elt_type, TYPE_INDEX_TYPE (type0));
8710 }
8711 else
8712 {
8713 int i;
8714 struct type *elt_type0;
8715
8716 elt_type0 = type0;
8717 for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
8718 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8719
8720 /* NOTE: result---the fixed version of elt_type0---should never
8721 depend on the contents of the array in properly constructed
8722 debugging data. */
8723 /* Create a fixed version of the array element type.
8724 We're not providing the address of an element here,
8725 and thus the actual object value cannot be inspected to do
8726 the conversion. This should not be a problem, since arrays of
8727 unconstrained objects are not allowed. In particular, all
8728 the elements of an array of a tagged type should all be of
8729 the same type specified in the debugging info. No need to
8730 consult the object tag. */
8731 result =
8732 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8733
8734 elt_type0 = type0;
8735 for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
8736 {
8737 struct type *range_type =
8738 to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, i), dval);
8739
8740 result = create_array_type (alloc_type_copy (elt_type0),
8741 result, range_type);
8742 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8743 }
8744 if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
8745 error (_("array type with dynamic size is larger than varsize-limit"));
8746 }
8747
8748 /* We want to preserve the type name. This can be useful when
8749 trying to get the type name of a value that has already been
8750 printed (for instance, if the user did "print VAR; whatis $". */
8751 TYPE_NAME (result) = TYPE_NAME (type0);
8752
8753 if (constrained_packed_array_p)
8754 {
8755 /* So far, the resulting type has been created as if the original
8756 type was a regular (non-packed) array type. As a result, the
8757 bitsize of the array elements needs to be set again, and the array
8758 length needs to be recomputed based on that bitsize. */
8759 int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8760 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8761
8762 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8763 TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8764 if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8765 TYPE_LENGTH (result)++;
8766 }
8767
8768 TYPE_FIXED_INSTANCE (result) = 1;
8769 return result;
8770 }
8771
8772
8773 /* A standard type (containing no dynamically sized components)
8774 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8775 DVAL describes a record containing any discriminants used in TYPE0,
8776 and may be NULL if there are none, or if the object of type TYPE at
8777 ADDRESS or in VALADDR contains these discriminants.
8778
8779 If CHECK_TAG is not null, in the case of tagged types, this function
8780 attempts to locate the object's tag and use it to compute the actual
8781 type. However, when ADDRESS is null, we cannot use it to determine the
8782 location of the tag, and therefore compute the tagged type's actual type.
8783 So we return the tagged type without consulting the tag. */
8784
8785 static struct type *
8786 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8787 CORE_ADDR address, struct value *dval, int check_tag)
8788 {
8789 type = ada_check_typedef (type);
8790
8791 /* Only un-fixed types need to be handled here. */
8792 if (!HAVE_GNAT_AUX_INFO (type))
8793 return type;
8794
8795 switch (TYPE_CODE (type))
8796 {
8797 default:
8798 return type;
8799 case TYPE_CODE_STRUCT:
8800 {
8801 struct type *static_type = to_static_fixed_type (type);
8802 struct type *fixed_record_type =
8803 to_fixed_record_type (type, valaddr, address, NULL);
8804
8805 /* If STATIC_TYPE is a tagged type and we know the object's address,
8806 then we can determine its tag, and compute the object's actual
8807 type from there. Note that we have to use the fixed record
8808 type (the parent part of the record may have dynamic fields
8809 and the way the location of _tag is expressed may depend on
8810 them). */
8811
8812 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8813 {
8814 struct value *tag =
8815 value_tag_from_contents_and_address
8816 (fixed_record_type,
8817 valaddr,
8818 address);
8819 struct type *real_type = type_from_tag (tag);
8820 struct value *obj =
8821 value_from_contents_and_address (fixed_record_type,
8822 valaddr,
8823 address);
8824 fixed_record_type = value_type (obj);
8825 if (real_type != NULL)
8826 return to_fixed_record_type
8827 (real_type, NULL,
8828 value_address (ada_tag_value_at_base_address (obj)), NULL);
8829 }
8830
8831 /* Check to see if there is a parallel ___XVZ variable.
8832 If there is, then it provides the actual size of our type. */
8833 else if (ada_type_name (fixed_record_type) != NULL)
8834 {
8835 const char *name = ada_type_name (fixed_record_type);
8836 char *xvz_name
8837 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8838 bool xvz_found = false;
8839 LONGEST size;
8840
8841 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8842 try
8843 {
8844 xvz_found = get_int_var_value (xvz_name, size);
8845 }
8846 catch (const gdb_exception_error &except)
8847 {
8848 /* We found the variable, but somehow failed to read
8849 its value. Rethrow the same error, but with a little
8850 bit more information, to help the user understand
8851 what went wrong (Eg: the variable might have been
8852 optimized out). */
8853 throw_error (except.error,
8854 _("unable to read value of %s (%s)"),
8855 xvz_name, except.what ());
8856 }
8857
8858 if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
8859 {
8860 fixed_record_type = copy_type (fixed_record_type);
8861 TYPE_LENGTH (fixed_record_type) = size;
8862
8863 /* The FIXED_RECORD_TYPE may have be a stub. We have
8864 observed this when the debugging info is STABS, and
8865 apparently it is something that is hard to fix.
8866
8867 In practice, we don't need the actual type definition
8868 at all, because the presence of the XVZ variable allows us
8869 to assume that there must be a XVS type as well, which we
8870 should be able to use later, when we need the actual type
8871 definition.
8872
8873 In the meantime, pretend that the "fixed" type we are
8874 returning is NOT a stub, because this can cause trouble
8875 when using this type to create new types targeting it.
8876 Indeed, the associated creation routines often check
8877 whether the target type is a stub and will try to replace
8878 it, thus using a type with the wrong size. This, in turn,
8879 might cause the new type to have the wrong size too.
8880 Consider the case of an array, for instance, where the size
8881 of the array is computed from the number of elements in
8882 our array multiplied by the size of its element. */
8883 TYPE_STUB (fixed_record_type) = 0;
8884 }
8885 }
8886 return fixed_record_type;
8887 }
8888 case TYPE_CODE_ARRAY:
8889 return to_fixed_array_type (type, dval, 1);
8890 case TYPE_CODE_UNION:
8891 if (dval == NULL)
8892 return type;
8893 else
8894 return to_fixed_variant_branch_type (type, valaddr, address, dval);
8895 }
8896 }
8897
8898 /* The same as ada_to_fixed_type_1, except that it preserves the type
8899 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8900
8901 The typedef layer needs be preserved in order to differentiate between
8902 arrays and array pointers when both types are implemented using the same
8903 fat pointer. In the array pointer case, the pointer is encoded as
8904 a typedef of the pointer type. For instance, considering:
8905
8906 type String_Access is access String;
8907 S1 : String_Access := null;
8908
8909 To the debugger, S1 is defined as a typedef of type String. But
8910 to the user, it is a pointer. So if the user tries to print S1,
8911 we should not dereference the array, but print the array address
8912 instead.
8913
8914 If we didn't preserve the typedef layer, we would lose the fact that
8915 the type is to be presented as a pointer (needs de-reference before
8916 being printed). And we would also use the source-level type name. */
8917
8918 struct type *
8919 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8920 CORE_ADDR address, struct value *dval, int check_tag)
8921
8922 {
8923 struct type *fixed_type =
8924 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8925
8926 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8927 then preserve the typedef layer.
8928
8929 Implementation note: We can only check the main-type portion of
8930 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8931 from TYPE now returns a type that has the same instance flags
8932 as TYPE. For instance, if TYPE is a "typedef const", and its
8933 target type is a "struct", then the typedef elimination will return
8934 a "const" version of the target type. See check_typedef for more
8935 details about how the typedef layer elimination is done.
8936
8937 brobecker/2010-11-19: It seems to me that the only case where it is
8938 useful to preserve the typedef layer is when dealing with fat pointers.
8939 Perhaps, we could add a check for that and preserve the typedef layer
8940 only in that situation. But this seems unnecessary so far, probably
8941 because we call check_typedef/ada_check_typedef pretty much everywhere.
8942 */
8943 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
8944 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8945 == TYPE_MAIN_TYPE (fixed_type)))
8946 return type;
8947
8948 return fixed_type;
8949 }
8950
8951 /* A standard (static-sized) type corresponding as well as possible to
8952 TYPE0, but based on no runtime data. */
8953
8954 static struct type *
8955 to_static_fixed_type (struct type *type0)
8956 {
8957 struct type *type;
8958
8959 if (type0 == NULL)
8960 return NULL;
8961
8962 if (TYPE_FIXED_INSTANCE (type0))
8963 return type0;
8964
8965 type0 = ada_check_typedef (type0);
8966
8967 switch (TYPE_CODE (type0))
8968 {
8969 default:
8970 return type0;
8971 case TYPE_CODE_STRUCT:
8972 type = dynamic_template_type (type0);
8973 if (type != NULL)
8974 return template_to_static_fixed_type (type);
8975 else
8976 return template_to_static_fixed_type (type0);
8977 case TYPE_CODE_UNION:
8978 type = ada_find_parallel_type (type0, "___XVU");
8979 if (type != NULL)
8980 return template_to_static_fixed_type (type);
8981 else
8982 return template_to_static_fixed_type (type0);
8983 }
8984 }
8985
8986 /* A static approximation of TYPE with all type wrappers removed. */
8987
8988 static struct type *
8989 static_unwrap_type (struct type *type)
8990 {
8991 if (ada_is_aligner_type (type))
8992 {
8993 struct type *type1 = TYPE_FIELD_TYPE (ada_check_typedef (type), 0);
8994 if (ada_type_name (type1) == NULL)
8995 TYPE_NAME (type1) = ada_type_name (type);
8996
8997 return static_unwrap_type (type1);
8998 }
8999 else
9000 {
9001 struct type *raw_real_type = ada_get_base_type (type);
9002
9003 if (raw_real_type == type)
9004 return type;
9005 else
9006 return to_static_fixed_type (raw_real_type);
9007 }
9008 }
9009
9010 /* In some cases, incomplete and private types require
9011 cross-references that are not resolved as records (for example,
9012 type Foo;
9013 type FooP is access Foo;
9014 V: FooP;
9015 type Foo is array ...;
9016 ). In these cases, since there is no mechanism for producing
9017 cross-references to such types, we instead substitute for FooP a
9018 stub enumeration type that is nowhere resolved, and whose tag is
9019 the name of the actual type. Call these types "non-record stubs". */
9020
9021 /* A type equivalent to TYPE that is not a non-record stub, if one
9022 exists, otherwise TYPE. */
9023
9024 struct type *
9025 ada_check_typedef (struct type *type)
9026 {
9027 if (type == NULL)
9028 return NULL;
9029
9030 /* If our type is an access to an unconstrained array, which is encoded
9031 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
9032 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
9033 what allows us to distinguish between fat pointers that represent
9034 array types, and fat pointers that represent array access types
9035 (in both cases, the compiler implements them as fat pointers). */
9036 if (ada_is_access_to_unconstrained_array (type))
9037 return type;
9038
9039 type = check_typedef (type);
9040 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
9041 || !TYPE_STUB (type)
9042 || TYPE_NAME (type) == NULL)
9043 return type;
9044 else
9045 {
9046 const char *name = TYPE_NAME (type);
9047 struct type *type1 = ada_find_any_type (name);
9048
9049 if (type1 == NULL)
9050 return type;
9051
9052 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
9053 stubs pointing to arrays, as we don't create symbols for array
9054 types, only for the typedef-to-array types). If that's the case,
9055 strip the typedef layer. */
9056 if (TYPE_CODE (type1) == TYPE_CODE_TYPEDEF)
9057 type1 = ada_check_typedef (type1);
9058
9059 return type1;
9060 }
9061 }
9062
9063 /* A value representing the data at VALADDR/ADDRESS as described by
9064 type TYPE0, but with a standard (static-sized) type that correctly
9065 describes it. If VAL0 is not NULL and TYPE0 already is a standard
9066 type, then return VAL0 [this feature is simply to avoid redundant
9067 creation of struct values]. */
9068
9069 static struct value *
9070 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
9071 struct value *val0)
9072 {
9073 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
9074
9075 if (type == type0 && val0 != NULL)
9076 return val0;
9077
9078 if (VALUE_LVAL (val0) != lval_memory)
9079 {
9080 /* Our value does not live in memory; it could be a convenience
9081 variable, for instance. Create a not_lval value using val0's
9082 contents. */
9083 return value_from_contents (type, value_contents (val0));
9084 }
9085
9086 return value_from_contents_and_address (type, 0, address);
9087 }
9088
9089 /* A value representing VAL, but with a standard (static-sized) type
9090 that correctly describes it. Does not necessarily create a new
9091 value. */
9092
9093 struct value *
9094 ada_to_fixed_value (struct value *val)
9095 {
9096 val = unwrap_value (val);
9097 val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
9098 return val;
9099 }
9100 \f
9101
9102 /* Attributes */
9103
9104 /* Table mapping attribute numbers to names.
9105 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
9106
9107 static const char *attribute_names[] = {
9108 "<?>",
9109
9110 "first",
9111 "last",
9112 "length",
9113 "image",
9114 "max",
9115 "min",
9116 "modulus",
9117 "pos",
9118 "size",
9119 "tag",
9120 "val",
9121 0
9122 };
9123
9124 static const char *
9125 ada_attribute_name (enum exp_opcode n)
9126 {
9127 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
9128 return attribute_names[n - OP_ATR_FIRST + 1];
9129 else
9130 return attribute_names[0];
9131 }
9132
9133 /* Evaluate the 'POS attribute applied to ARG. */
9134
9135 static LONGEST
9136 pos_atr (struct value *arg)
9137 {
9138 struct value *val = coerce_ref (arg);
9139 struct type *type = value_type (val);
9140 LONGEST result;
9141
9142 if (!discrete_type_p (type))
9143 error (_("'POS only defined on discrete types"));
9144
9145 if (!discrete_position (type, value_as_long (val), &result))
9146 error (_("enumeration value is invalid: can't find 'POS"));
9147
9148 return result;
9149 }
9150
9151 static struct value *
9152 value_pos_atr (struct type *type, struct value *arg)
9153 {
9154 return value_from_longest (type, pos_atr (arg));
9155 }
9156
9157 /* Evaluate the TYPE'VAL attribute applied to ARG. */
9158
9159 static struct value *
9160 value_val_atr (struct type *type, struct value *arg)
9161 {
9162 if (!discrete_type_p (type))
9163 error (_("'VAL only defined on discrete types"));
9164 if (!integer_type_p (value_type (arg)))
9165 error (_("'VAL requires integral argument"));
9166
9167 if (TYPE_CODE (type) == TYPE_CODE_ENUM)
9168 {
9169 long pos = value_as_long (arg);
9170
9171 if (pos < 0 || pos >= TYPE_NFIELDS (type))
9172 error (_("argument to 'VAL out of range"));
9173 return value_from_longest (type, TYPE_FIELD_ENUMVAL (type, pos));
9174 }
9175 else
9176 return value_from_longest (type, value_as_long (arg));
9177 }
9178 \f
9179
9180 /* Evaluation */
9181
9182 /* True if TYPE appears to be an Ada character type.
9183 [At the moment, this is true only for Character and Wide_Character;
9184 It is a heuristic test that could stand improvement]. */
9185
9186 bool
9187 ada_is_character_type (struct type *type)
9188 {
9189 const char *name;
9190
9191 /* If the type code says it's a character, then assume it really is,
9192 and don't check any further. */
9193 if (TYPE_CODE (type) == TYPE_CODE_CHAR)
9194 return true;
9195
9196 /* Otherwise, assume it's a character type iff it is a discrete type
9197 with a known character type name. */
9198 name = ada_type_name (type);
9199 return (name != NULL
9200 && (TYPE_CODE (type) == TYPE_CODE_INT
9201 || TYPE_CODE (type) == TYPE_CODE_RANGE)
9202 && (strcmp (name, "character") == 0
9203 || strcmp (name, "wide_character") == 0
9204 || strcmp (name, "wide_wide_character") == 0
9205 || strcmp (name, "unsigned char") == 0));
9206 }
9207
9208 /* True if TYPE appears to be an Ada string type. */
9209
9210 bool
9211 ada_is_string_type (struct type *type)
9212 {
9213 type = ada_check_typedef (type);
9214 if (type != NULL
9215 && TYPE_CODE (type) != TYPE_CODE_PTR
9216 && (ada_is_simple_array_type (type)
9217 || ada_is_array_descriptor_type (type))
9218 && ada_array_arity (type) == 1)
9219 {
9220 struct type *elttype = ada_array_element_type (type, 1);
9221
9222 return ada_is_character_type (elttype);
9223 }
9224 else
9225 return false;
9226 }
9227
9228 /* The compiler sometimes provides a parallel XVS type for a given
9229 PAD type. Normally, it is safe to follow the PAD type directly,
9230 but older versions of the compiler have a bug that causes the offset
9231 of its "F" field to be wrong. Following that field in that case
9232 would lead to incorrect results, but this can be worked around
9233 by ignoring the PAD type and using the associated XVS type instead.
9234
9235 Set to True if the debugger should trust the contents of PAD types.
9236 Otherwise, ignore the PAD type if there is a parallel XVS type. */
9237 static bool trust_pad_over_xvs = true;
9238
9239 /* True if TYPE is a struct type introduced by the compiler to force the
9240 alignment of a value. Such types have a single field with a
9241 distinctive name. */
9242
9243 int
9244 ada_is_aligner_type (struct type *type)
9245 {
9246 type = ada_check_typedef (type);
9247
9248 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
9249 return 0;
9250
9251 return (TYPE_CODE (type) == TYPE_CODE_STRUCT
9252 && TYPE_NFIELDS (type) == 1
9253 && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
9254 }
9255
9256 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
9257 the parallel type. */
9258
9259 struct type *
9260 ada_get_base_type (struct type *raw_type)
9261 {
9262 struct type *real_type_namer;
9263 struct type *raw_real_type;
9264
9265 if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
9266 return raw_type;
9267
9268 if (ada_is_aligner_type (raw_type))
9269 /* The encoding specifies that we should always use the aligner type.
9270 So, even if this aligner type has an associated XVS type, we should
9271 simply ignore it.
9272
9273 According to the compiler gurus, an XVS type parallel to an aligner
9274 type may exist because of a stabs limitation. In stabs, aligner
9275 types are empty because the field has a variable-sized type, and
9276 thus cannot actually be used as an aligner type. As a result,
9277 we need the associated parallel XVS type to decode the type.
9278 Since the policy in the compiler is to not change the internal
9279 representation based on the debugging info format, we sometimes
9280 end up having a redundant XVS type parallel to the aligner type. */
9281 return raw_type;
9282
9283 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9284 if (real_type_namer == NULL
9285 || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
9286 || TYPE_NFIELDS (real_type_namer) != 1)
9287 return raw_type;
9288
9289 if (TYPE_CODE (TYPE_FIELD_TYPE (real_type_namer, 0)) != TYPE_CODE_REF)
9290 {
9291 /* This is an older encoding form where the base type needs to be
9292 looked up by name. We prefer the newer encoding because it is
9293 more efficient. */
9294 raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
9295 if (raw_real_type == NULL)
9296 return raw_type;
9297 else
9298 return raw_real_type;
9299 }
9300
9301 /* The field in our XVS type is a reference to the base type. */
9302 return TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (real_type_namer, 0));
9303 }
9304
9305 /* The type of value designated by TYPE, with all aligners removed. */
9306
9307 struct type *
9308 ada_aligned_type (struct type *type)
9309 {
9310 if (ada_is_aligner_type (type))
9311 return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
9312 else
9313 return ada_get_base_type (type);
9314 }
9315
9316
9317 /* The address of the aligned value in an object at address VALADDR
9318 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9319
9320 const gdb_byte *
9321 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9322 {
9323 if (ada_is_aligner_type (type))
9324 return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
9325 valaddr +
9326 TYPE_FIELD_BITPOS (type,
9327 0) / TARGET_CHAR_BIT);
9328 else
9329 return valaddr;
9330 }
9331
9332
9333
9334 /* The printed representation of an enumeration literal with encoded
9335 name NAME. The value is good to the next call of ada_enum_name. */
9336 const char *
9337 ada_enum_name (const char *name)
9338 {
9339 static char *result;
9340 static size_t result_len = 0;
9341 const char *tmp;
9342
9343 /* First, unqualify the enumeration name:
9344 1. Search for the last '.' character. If we find one, then skip
9345 all the preceding characters, the unqualified name starts
9346 right after that dot.
9347 2. Otherwise, we may be debugging on a target where the compiler
9348 translates dots into "__". Search forward for double underscores,
9349 but stop searching when we hit an overloading suffix, which is
9350 of the form "__" followed by digits. */
9351
9352 tmp = strrchr (name, '.');
9353 if (tmp != NULL)
9354 name = tmp + 1;
9355 else
9356 {
9357 while ((tmp = strstr (name, "__")) != NULL)
9358 {
9359 if (isdigit (tmp[2]))
9360 break;
9361 else
9362 name = tmp + 2;
9363 }
9364 }
9365
9366 if (name[0] == 'Q')
9367 {
9368 int v;
9369
9370 if (name[1] == 'U' || name[1] == 'W')
9371 {
9372 if (sscanf (name + 2, "%x", &v) != 1)
9373 return name;
9374 }
9375 else if (((name[1] >= '0' && name[1] <= '9')
9376 || (name[1] >= 'a' && name[1] <= 'z'))
9377 && name[2] == '\0')
9378 {
9379 GROW_VECT (result, result_len, 4);
9380 xsnprintf (result, result_len, "'%c'", name[1]);
9381 return result;
9382 }
9383 else
9384 return name;
9385
9386 GROW_VECT (result, result_len, 16);
9387 if (isascii (v) && isprint (v))
9388 xsnprintf (result, result_len, "'%c'", v);
9389 else if (name[1] == 'U')
9390 xsnprintf (result, result_len, "[\"%02x\"]", v);
9391 else
9392 xsnprintf (result, result_len, "[\"%04x\"]", v);
9393
9394 return result;
9395 }
9396 else
9397 {
9398 tmp = strstr (name, "__");
9399 if (tmp == NULL)
9400 tmp = strstr (name, "$");
9401 if (tmp != NULL)
9402 {
9403 GROW_VECT (result, result_len, tmp - name + 1);
9404 strncpy (result, name, tmp - name);
9405 result[tmp - name] = '\0';
9406 return result;
9407 }
9408
9409 return name;
9410 }
9411 }
9412
9413 /* Evaluate the subexpression of EXP starting at *POS as for
9414 evaluate_type, updating *POS to point just past the evaluated
9415 expression. */
9416
9417 static struct value *
9418 evaluate_subexp_type (struct expression *exp, int *pos)
9419 {
9420 return evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
9421 }
9422
9423 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9424 value it wraps. */
9425
9426 static struct value *
9427 unwrap_value (struct value *val)
9428 {
9429 struct type *type = ada_check_typedef (value_type (val));
9430
9431 if (ada_is_aligner_type (type))
9432 {
9433 struct value *v = ada_value_struct_elt (val, "F", 0);
9434 struct type *val_type = ada_check_typedef (value_type (v));
9435
9436 if (ada_type_name (val_type) == NULL)
9437 TYPE_NAME (val_type) = ada_type_name (type);
9438
9439 return unwrap_value (v);
9440 }
9441 else
9442 {
9443 struct type *raw_real_type =
9444 ada_check_typedef (ada_get_base_type (type));
9445
9446 /* If there is no parallel XVS or XVE type, then the value is
9447 already unwrapped. Return it without further modification. */
9448 if ((type == raw_real_type)
9449 && ada_find_parallel_type (type, "___XVE") == NULL)
9450 return val;
9451
9452 return
9453 coerce_unspec_val_to_type
9454 (val, ada_to_fixed_type (raw_real_type, 0,
9455 value_address (val),
9456 NULL, 1));
9457 }
9458 }
9459
9460 static struct value *
9461 cast_from_fixed (struct type *type, struct value *arg)
9462 {
9463 struct value *scale = ada_scaling_factor (value_type (arg));
9464 arg = value_cast (value_type (scale), arg);
9465
9466 arg = value_binop (arg, scale, BINOP_MUL);
9467 return value_cast (type, arg);
9468 }
9469
9470 static struct value *
9471 cast_to_fixed (struct type *type, struct value *arg)
9472 {
9473 if (type == value_type (arg))
9474 return arg;
9475
9476 struct value *scale = ada_scaling_factor (type);
9477 if (ada_is_fixed_point_type (value_type (arg)))
9478 arg = cast_from_fixed (value_type (scale), arg);
9479 else
9480 arg = value_cast (value_type (scale), arg);
9481
9482 arg = value_binop (arg, scale, BINOP_DIV);
9483 return value_cast (type, arg);
9484 }
9485
9486 /* Given two array types T1 and T2, return nonzero iff both arrays
9487 contain the same number of elements. */
9488
9489 static int
9490 ada_same_array_size_p (struct type *t1, struct type *t2)
9491 {
9492 LONGEST lo1, hi1, lo2, hi2;
9493
9494 /* Get the array bounds in order to verify that the size of
9495 the two arrays match. */
9496 if (!get_array_bounds (t1, &lo1, &hi1)
9497 || !get_array_bounds (t2, &lo2, &hi2))
9498 error (_("unable to determine array bounds"));
9499
9500 /* To make things easier for size comparison, normalize a bit
9501 the case of empty arrays by making sure that the difference
9502 between upper bound and lower bound is always -1. */
9503 if (lo1 > hi1)
9504 hi1 = lo1 - 1;
9505 if (lo2 > hi2)
9506 hi2 = lo2 - 1;
9507
9508 return (hi1 - lo1 == hi2 - lo2);
9509 }
9510
9511 /* Assuming that VAL is an array of integrals, and TYPE represents
9512 an array with the same number of elements, but with wider integral
9513 elements, return an array "casted" to TYPE. In practice, this
9514 means that the returned array is built by casting each element
9515 of the original array into TYPE's (wider) element type. */
9516
9517 static struct value *
9518 ada_promote_array_of_integrals (struct type *type, struct value *val)
9519 {
9520 struct type *elt_type = TYPE_TARGET_TYPE (type);
9521 LONGEST lo, hi;
9522 struct value *res;
9523 LONGEST i;
9524
9525 /* Verify that both val and type are arrays of scalars, and
9526 that the size of val's elements is smaller than the size
9527 of type's element. */
9528 gdb_assert (TYPE_CODE (type) == TYPE_CODE_ARRAY);
9529 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
9530 gdb_assert (TYPE_CODE (value_type (val)) == TYPE_CODE_ARRAY);
9531 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
9532 gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
9533 > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
9534
9535 if (!get_array_bounds (type, &lo, &hi))
9536 error (_("unable to determine array bounds"));
9537
9538 res = allocate_value (type);
9539
9540 /* Promote each array element. */
9541 for (i = 0; i < hi - lo + 1; i++)
9542 {
9543 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9544
9545 memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
9546 value_contents_all (elt), TYPE_LENGTH (elt_type));
9547 }
9548
9549 return res;
9550 }
9551
9552 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9553 return the converted value. */
9554
9555 static struct value *
9556 coerce_for_assign (struct type *type, struct value *val)
9557 {
9558 struct type *type2 = value_type (val);
9559
9560 if (type == type2)
9561 return val;
9562
9563 type2 = ada_check_typedef (type2);
9564 type = ada_check_typedef (type);
9565
9566 if (TYPE_CODE (type2) == TYPE_CODE_PTR
9567 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
9568 {
9569 val = ada_value_ind (val);
9570 type2 = value_type (val);
9571 }
9572
9573 if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
9574 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
9575 {
9576 if (!ada_same_array_size_p (type, type2))
9577 error (_("cannot assign arrays of different length"));
9578
9579 if (is_integral_type (TYPE_TARGET_TYPE (type))
9580 && is_integral_type (TYPE_TARGET_TYPE (type2))
9581 && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9582 < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9583 {
9584 /* Allow implicit promotion of the array elements to
9585 a wider type. */
9586 return ada_promote_array_of_integrals (type, val);
9587 }
9588
9589 if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9590 != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9591 error (_("Incompatible types in assignment"));
9592 deprecated_set_value_type (val, type);
9593 }
9594 return val;
9595 }
9596
9597 static struct value *
9598 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9599 {
9600 struct value *val;
9601 struct type *type1, *type2;
9602 LONGEST v, v1, v2;
9603
9604 arg1 = coerce_ref (arg1);
9605 arg2 = coerce_ref (arg2);
9606 type1 = get_base_type (ada_check_typedef (value_type (arg1)));
9607 type2 = get_base_type (ada_check_typedef (value_type (arg2)));
9608
9609 if (TYPE_CODE (type1) != TYPE_CODE_INT
9610 || TYPE_CODE (type2) != TYPE_CODE_INT)
9611 return value_binop (arg1, arg2, op);
9612
9613 switch (op)
9614 {
9615 case BINOP_MOD:
9616 case BINOP_DIV:
9617 case BINOP_REM:
9618 break;
9619 default:
9620 return value_binop (arg1, arg2, op);
9621 }
9622
9623 v2 = value_as_long (arg2);
9624 if (v2 == 0)
9625 error (_("second operand of %s must not be zero."), op_string (op));
9626
9627 if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
9628 return value_binop (arg1, arg2, op);
9629
9630 v1 = value_as_long (arg1);
9631 switch (op)
9632 {
9633 case BINOP_DIV:
9634 v = v1 / v2;
9635 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9636 v += v > 0 ? -1 : 1;
9637 break;
9638 case BINOP_REM:
9639 v = v1 % v2;
9640 if (v * v1 < 0)
9641 v -= v2;
9642 break;
9643 default:
9644 /* Should not reach this point. */
9645 v = 0;
9646 }
9647
9648 val = allocate_value (type1);
9649 store_unsigned_integer (value_contents_raw (val),
9650 TYPE_LENGTH (value_type (val)),
9651 type_byte_order (type1), v);
9652 return val;
9653 }
9654
9655 static int
9656 ada_value_equal (struct value *arg1, struct value *arg2)
9657 {
9658 if (ada_is_direct_array_type (value_type (arg1))
9659 || ada_is_direct_array_type (value_type (arg2)))
9660 {
9661 struct type *arg1_type, *arg2_type;
9662
9663 /* Automatically dereference any array reference before
9664 we attempt to perform the comparison. */
9665 arg1 = ada_coerce_ref (arg1);
9666 arg2 = ada_coerce_ref (arg2);
9667
9668 arg1 = ada_coerce_to_simple_array (arg1);
9669 arg2 = ada_coerce_to_simple_array (arg2);
9670
9671 arg1_type = ada_check_typedef (value_type (arg1));
9672 arg2_type = ada_check_typedef (value_type (arg2));
9673
9674 if (TYPE_CODE (arg1_type) != TYPE_CODE_ARRAY
9675 || TYPE_CODE (arg2_type) != TYPE_CODE_ARRAY)
9676 error (_("Attempt to compare array with non-array"));
9677 /* FIXME: The following works only for types whose
9678 representations use all bits (no padding or undefined bits)
9679 and do not have user-defined equality. */
9680 return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9681 && memcmp (value_contents (arg1), value_contents (arg2),
9682 TYPE_LENGTH (arg1_type)) == 0);
9683 }
9684 return value_equal (arg1, arg2);
9685 }
9686
9687 /* Total number of component associations in the aggregate starting at
9688 index PC in EXP. Assumes that index PC is the start of an
9689 OP_AGGREGATE. */
9690
9691 static int
9692 num_component_specs (struct expression *exp, int pc)
9693 {
9694 int n, m, i;
9695
9696 m = exp->elts[pc + 1].longconst;
9697 pc += 3;
9698 n = 0;
9699 for (i = 0; i < m; i += 1)
9700 {
9701 switch (exp->elts[pc].opcode)
9702 {
9703 default:
9704 n += 1;
9705 break;
9706 case OP_CHOICES:
9707 n += exp->elts[pc + 1].longconst;
9708 break;
9709 }
9710 ada_evaluate_subexp (NULL, exp, &pc, EVAL_SKIP);
9711 }
9712 return n;
9713 }
9714
9715 /* Assign the result of evaluating EXP starting at *POS to the INDEXth
9716 component of LHS (a simple array or a record), updating *POS past
9717 the expression, assuming that LHS is contained in CONTAINER. Does
9718 not modify the inferior's memory, nor does it modify LHS (unless
9719 LHS == CONTAINER). */
9720
9721 static void
9722 assign_component (struct value *container, struct value *lhs, LONGEST index,
9723 struct expression *exp, int *pos)
9724 {
9725 struct value *mark = value_mark ();
9726 struct value *elt;
9727 struct type *lhs_type = check_typedef (value_type (lhs));
9728
9729 if (TYPE_CODE (lhs_type) == TYPE_CODE_ARRAY)
9730 {
9731 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9732 struct value *index_val = value_from_longest (index_type, index);
9733
9734 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9735 }
9736 else
9737 {
9738 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9739 elt = ada_to_fixed_value (elt);
9740 }
9741
9742 if (exp->elts[*pos].opcode == OP_AGGREGATE)
9743 assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
9744 else
9745 value_assign_to_component (container, elt,
9746 ada_evaluate_subexp (NULL, exp, pos,
9747 EVAL_NORMAL));
9748
9749 value_free_to_mark (mark);
9750 }
9751
9752 /* Assuming that LHS represents an lvalue having a record or array
9753 type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
9754 of that aggregate's value to LHS, advancing *POS past the
9755 aggregate. NOSIDE is as for evaluate_subexp. CONTAINER is an
9756 lvalue containing LHS (possibly LHS itself). Does not modify
9757 the inferior's memory, nor does it modify the contents of
9758 LHS (unless == CONTAINER). Returns the modified CONTAINER. */
9759
9760 static struct value *
9761 assign_aggregate (struct value *container,
9762 struct value *lhs, struct expression *exp,
9763 int *pos, enum noside noside)
9764 {
9765 struct type *lhs_type;
9766 int n = exp->elts[*pos+1].longconst;
9767 LONGEST low_index, high_index;
9768 int num_specs;
9769 LONGEST *indices;
9770 int max_indices, num_indices;
9771 int i;
9772
9773 *pos += 3;
9774 if (noside != EVAL_NORMAL)
9775 {
9776 for (i = 0; i < n; i += 1)
9777 ada_evaluate_subexp (NULL, exp, pos, noside);
9778 return container;
9779 }
9780
9781 container = ada_coerce_ref (container);
9782 if (ada_is_direct_array_type (value_type (container)))
9783 container = ada_coerce_to_simple_array (container);
9784 lhs = ada_coerce_ref (lhs);
9785 if (!deprecated_value_modifiable (lhs))
9786 error (_("Left operand of assignment is not a modifiable lvalue."));
9787
9788 lhs_type = check_typedef (value_type (lhs));
9789 if (ada_is_direct_array_type (lhs_type))
9790 {
9791 lhs = ada_coerce_to_simple_array (lhs);
9792 lhs_type = check_typedef (value_type (lhs));
9793 low_index = TYPE_ARRAY_LOWER_BOUND_VALUE (lhs_type);
9794 high_index = TYPE_ARRAY_UPPER_BOUND_VALUE (lhs_type);
9795 }
9796 else if (TYPE_CODE (lhs_type) == TYPE_CODE_STRUCT)
9797 {
9798 low_index = 0;
9799 high_index = num_visible_fields (lhs_type) - 1;
9800 }
9801 else
9802 error (_("Left-hand side must be array or record."));
9803
9804 num_specs = num_component_specs (exp, *pos - 3);
9805 max_indices = 4 * num_specs + 4;
9806 indices = XALLOCAVEC (LONGEST, max_indices);
9807 indices[0] = indices[1] = low_index - 1;
9808 indices[2] = indices[3] = high_index + 1;
9809 num_indices = 4;
9810
9811 for (i = 0; i < n; i += 1)
9812 {
9813 switch (exp->elts[*pos].opcode)
9814 {
9815 case OP_CHOICES:
9816 aggregate_assign_from_choices (container, lhs, exp, pos, indices,
9817 &num_indices, max_indices,
9818 low_index, high_index);
9819 break;
9820 case OP_POSITIONAL:
9821 aggregate_assign_positional (container, lhs, exp, pos, indices,
9822 &num_indices, max_indices,
9823 low_index, high_index);
9824 break;
9825 case OP_OTHERS:
9826 if (i != n-1)
9827 error (_("Misplaced 'others' clause"));
9828 aggregate_assign_others (container, lhs, exp, pos, indices,
9829 num_indices, low_index, high_index);
9830 break;
9831 default:
9832 error (_("Internal error: bad aggregate clause"));
9833 }
9834 }
9835
9836 return container;
9837 }
9838
9839 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9840 construct at *POS, updating *POS past the construct, given that
9841 the positions are relative to lower bound LOW, where HIGH is the
9842 upper bound. Record the position in INDICES[0 .. MAX_INDICES-1]
9843 updating *NUM_INDICES as needed. CONTAINER is as for
9844 assign_aggregate. */
9845 static void
9846 aggregate_assign_positional (struct value *container,
9847 struct value *lhs, struct expression *exp,
9848 int *pos, LONGEST *indices, int *num_indices,
9849 int max_indices, LONGEST low, LONGEST high)
9850 {
9851 LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
9852
9853 if (ind - 1 == high)
9854 warning (_("Extra components in aggregate ignored."));
9855 if (ind <= high)
9856 {
9857 add_component_interval (ind, ind, indices, num_indices, max_indices);
9858 *pos += 3;
9859 assign_component (container, lhs, ind, exp, pos);
9860 }
9861 else
9862 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9863 }
9864
9865 /* Assign into the components of LHS indexed by the OP_CHOICES
9866 construct at *POS, updating *POS past the construct, given that
9867 the allowable indices are LOW..HIGH. Record the indices assigned
9868 to in INDICES[0 .. MAX_INDICES-1], updating *NUM_INDICES as
9869 needed. CONTAINER is as for assign_aggregate. */
9870 static void
9871 aggregate_assign_from_choices (struct value *container,
9872 struct value *lhs, struct expression *exp,
9873 int *pos, LONGEST *indices, int *num_indices,
9874 int max_indices, LONGEST low, LONGEST high)
9875 {
9876 int j;
9877 int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
9878 int choice_pos, expr_pc;
9879 int is_array = ada_is_direct_array_type (value_type (lhs));
9880
9881 choice_pos = *pos += 3;
9882
9883 for (j = 0; j < n_choices; j += 1)
9884 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9885 expr_pc = *pos;
9886 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9887
9888 for (j = 0; j < n_choices; j += 1)
9889 {
9890 LONGEST lower, upper;
9891 enum exp_opcode op = exp->elts[choice_pos].opcode;
9892
9893 if (op == OP_DISCRETE_RANGE)
9894 {
9895 choice_pos += 1;
9896 lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
9897 EVAL_NORMAL));
9898 upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
9899 EVAL_NORMAL));
9900 }
9901 else if (is_array)
9902 {
9903 lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos,
9904 EVAL_NORMAL));
9905 upper = lower;
9906 }
9907 else
9908 {
9909 int ind;
9910 const char *name;
9911
9912 switch (op)
9913 {
9914 case OP_NAME:
9915 name = &exp->elts[choice_pos + 2].string;
9916 break;
9917 case OP_VAR_VALUE:
9918 name = exp->elts[choice_pos + 2].symbol->natural_name ();
9919 break;
9920 default:
9921 error (_("Invalid record component association."));
9922 }
9923 ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
9924 ind = 0;
9925 if (! find_struct_field (name, value_type (lhs), 0,
9926 NULL, NULL, NULL, NULL, &ind))
9927 error (_("Unknown component name: %s."), name);
9928 lower = upper = ind;
9929 }
9930
9931 if (lower <= upper && (lower < low || upper > high))
9932 error (_("Index in component association out of bounds."));
9933
9934 add_component_interval (lower, upper, indices, num_indices,
9935 max_indices);
9936 while (lower <= upper)
9937 {
9938 int pos1;
9939
9940 pos1 = expr_pc;
9941 assign_component (container, lhs, lower, exp, &pos1);
9942 lower += 1;
9943 }
9944 }
9945 }
9946
9947 /* Assign the value of the expression in the OP_OTHERS construct in
9948 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9949 have not been previously assigned. The index intervals already assigned
9950 are in INDICES[0 .. NUM_INDICES-1]. Updates *POS to after the
9951 OP_OTHERS clause. CONTAINER is as for assign_aggregate. */
9952 static void
9953 aggregate_assign_others (struct value *container,
9954 struct value *lhs, struct expression *exp,
9955 int *pos, LONGEST *indices, int num_indices,
9956 LONGEST low, LONGEST high)
9957 {
9958 int i;
9959 int expr_pc = *pos + 1;
9960
9961 for (i = 0; i < num_indices - 2; i += 2)
9962 {
9963 LONGEST ind;
9964
9965 for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9966 {
9967 int localpos;
9968
9969 localpos = expr_pc;
9970 assign_component (container, lhs, ind, exp, &localpos);
9971 }
9972 }
9973 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
9974 }
9975
9976 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9977 [ INDICES[0] .. INDICES[1] ],..., [ INDICES[*SIZE-2] .. INDICES[*SIZE-1] ],
9978 modifying *SIZE as needed. It is an error if *SIZE exceeds
9979 MAX_SIZE. The resulting intervals do not overlap. */
9980 static void
9981 add_component_interval (LONGEST low, LONGEST high,
9982 LONGEST* indices, int *size, int max_size)
9983 {
9984 int i, j;
9985
9986 for (i = 0; i < *size; i += 2) {
9987 if (high >= indices[i] && low <= indices[i + 1])
9988 {
9989 int kh;
9990
9991 for (kh = i + 2; kh < *size; kh += 2)
9992 if (high < indices[kh])
9993 break;
9994 if (low < indices[i])
9995 indices[i] = low;
9996 indices[i + 1] = indices[kh - 1];
9997 if (high > indices[i + 1])
9998 indices[i + 1] = high;
9999 memcpy (indices + i + 2, indices + kh, *size - kh);
10000 *size -= kh - i - 2;
10001 return;
10002 }
10003 else if (high < indices[i])
10004 break;
10005 }
10006
10007 if (*size == max_size)
10008 error (_("Internal error: miscounted aggregate components."));
10009 *size += 2;
10010 for (j = *size-1; j >= i+2; j -= 1)
10011 indices[j] = indices[j - 2];
10012 indices[i] = low;
10013 indices[i + 1] = high;
10014 }
10015
10016 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
10017 is different. */
10018
10019 static struct value *
10020 ada_value_cast (struct type *type, struct value *arg2)
10021 {
10022 if (type == ada_check_typedef (value_type (arg2)))
10023 return arg2;
10024
10025 if (ada_is_fixed_point_type (type))
10026 return cast_to_fixed (type, arg2);
10027
10028 if (ada_is_fixed_point_type (value_type (arg2)))
10029 return cast_from_fixed (type, arg2);
10030
10031 return value_cast (type, arg2);
10032 }
10033
10034 /* Evaluating Ada expressions, and printing their result.
10035 ------------------------------------------------------
10036
10037 1. Introduction:
10038 ----------------
10039
10040 We usually evaluate an Ada expression in order to print its value.
10041 We also evaluate an expression in order to print its type, which
10042 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
10043 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
10044 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
10045 the evaluation compared to the EVAL_NORMAL, but is otherwise very
10046 similar.
10047
10048 Evaluating expressions is a little more complicated for Ada entities
10049 than it is for entities in languages such as C. The main reason for
10050 this is that Ada provides types whose definition might be dynamic.
10051 One example of such types is variant records. Or another example
10052 would be an array whose bounds can only be known at run time.
10053
10054 The following description is a general guide as to what should be
10055 done (and what should NOT be done) in order to evaluate an expression
10056 involving such types, and when. This does not cover how the semantic
10057 information is encoded by GNAT as this is covered separatly. For the
10058 document used as the reference for the GNAT encoding, see exp_dbug.ads
10059 in the GNAT sources.
10060
10061 Ideally, we should embed each part of this description next to its
10062 associated code. Unfortunately, the amount of code is so vast right
10063 now that it's hard to see whether the code handling a particular
10064 situation might be duplicated or not. One day, when the code is
10065 cleaned up, this guide might become redundant with the comments
10066 inserted in the code, and we might want to remove it.
10067
10068 2. ``Fixing'' an Entity, the Simple Case:
10069 -----------------------------------------
10070
10071 When evaluating Ada expressions, the tricky issue is that they may
10072 reference entities whose type contents and size are not statically
10073 known. Consider for instance a variant record:
10074
10075 type Rec (Empty : Boolean := True) is record
10076 case Empty is
10077 when True => null;
10078 when False => Value : Integer;
10079 end case;
10080 end record;
10081 Yes : Rec := (Empty => False, Value => 1);
10082 No : Rec := (empty => True);
10083
10084 The size and contents of that record depends on the value of the
10085 descriminant (Rec.Empty). At this point, neither the debugging
10086 information nor the associated type structure in GDB are able to
10087 express such dynamic types. So what the debugger does is to create
10088 "fixed" versions of the type that applies to the specific object.
10089 We also informally refer to this operation as "fixing" an object,
10090 which means creating its associated fixed type.
10091
10092 Example: when printing the value of variable "Yes" above, its fixed
10093 type would look like this:
10094
10095 type Rec is record
10096 Empty : Boolean;
10097 Value : Integer;
10098 end record;
10099
10100 On the other hand, if we printed the value of "No", its fixed type
10101 would become:
10102
10103 type Rec is record
10104 Empty : Boolean;
10105 end record;
10106
10107 Things become a little more complicated when trying to fix an entity
10108 with a dynamic type that directly contains another dynamic type,
10109 such as an array of variant records, for instance. There are
10110 two possible cases: Arrays, and records.
10111
10112 3. ``Fixing'' Arrays:
10113 ---------------------
10114
10115 The type structure in GDB describes an array in terms of its bounds,
10116 and the type of its elements. By design, all elements in the array
10117 have the same type and we cannot represent an array of variant elements
10118 using the current type structure in GDB. When fixing an array,
10119 we cannot fix the array element, as we would potentially need one
10120 fixed type per element of the array. As a result, the best we can do
10121 when fixing an array is to produce an array whose bounds and size
10122 are correct (allowing us to read it from memory), but without having
10123 touched its element type. Fixing each element will be done later,
10124 when (if) necessary.
10125
10126 Arrays are a little simpler to handle than records, because the same
10127 amount of memory is allocated for each element of the array, even if
10128 the amount of space actually used by each element differs from element
10129 to element. Consider for instance the following array of type Rec:
10130
10131 type Rec_Array is array (1 .. 2) of Rec;
10132
10133 The actual amount of memory occupied by each element might be different
10134 from element to element, depending on the value of their discriminant.
10135 But the amount of space reserved for each element in the array remains
10136 fixed regardless. So we simply need to compute that size using
10137 the debugging information available, from which we can then determine
10138 the array size (we multiply the number of elements of the array by
10139 the size of each element).
10140
10141 The simplest case is when we have an array of a constrained element
10142 type. For instance, consider the following type declarations:
10143
10144 type Bounded_String (Max_Size : Integer) is
10145 Length : Integer;
10146 Buffer : String (1 .. Max_Size);
10147 end record;
10148 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
10149
10150 In this case, the compiler describes the array as an array of
10151 variable-size elements (identified by its XVS suffix) for which
10152 the size can be read in the parallel XVZ variable.
10153
10154 In the case of an array of an unconstrained element type, the compiler
10155 wraps the array element inside a private PAD type. This type should not
10156 be shown to the user, and must be "unwrap"'ed before printing. Note
10157 that we also use the adjective "aligner" in our code to designate
10158 these wrapper types.
10159
10160 In some cases, the size allocated for each element is statically
10161 known. In that case, the PAD type already has the correct size,
10162 and the array element should remain unfixed.
10163
10164 But there are cases when this size is not statically known.
10165 For instance, assuming that "Five" is an integer variable:
10166
10167 type Dynamic is array (1 .. Five) of Integer;
10168 type Wrapper (Has_Length : Boolean := False) is record
10169 Data : Dynamic;
10170 case Has_Length is
10171 when True => Length : Integer;
10172 when False => null;
10173 end case;
10174 end record;
10175 type Wrapper_Array is array (1 .. 2) of Wrapper;
10176
10177 Hello : Wrapper_Array := (others => (Has_Length => True,
10178 Data => (others => 17),
10179 Length => 1));
10180
10181
10182 The debugging info would describe variable Hello as being an
10183 array of a PAD type. The size of that PAD type is not statically
10184 known, but can be determined using a parallel XVZ variable.
10185 In that case, a copy of the PAD type with the correct size should
10186 be used for the fixed array.
10187
10188 3. ``Fixing'' record type objects:
10189 ----------------------------------
10190
10191 Things are slightly different from arrays in the case of dynamic
10192 record types. In this case, in order to compute the associated
10193 fixed type, we need to determine the size and offset of each of
10194 its components. This, in turn, requires us to compute the fixed
10195 type of each of these components.
10196
10197 Consider for instance the example:
10198
10199 type Bounded_String (Max_Size : Natural) is record
10200 Str : String (1 .. Max_Size);
10201 Length : Natural;
10202 end record;
10203 My_String : Bounded_String (Max_Size => 10);
10204
10205 In that case, the position of field "Length" depends on the size
10206 of field Str, which itself depends on the value of the Max_Size
10207 discriminant. In order to fix the type of variable My_String,
10208 we need to fix the type of field Str. Therefore, fixing a variant
10209 record requires us to fix each of its components.
10210
10211 However, if a component does not have a dynamic size, the component
10212 should not be fixed. In particular, fields that use a PAD type
10213 should not fixed. Here is an example where this might happen
10214 (assuming type Rec above):
10215
10216 type Container (Big : Boolean) is record
10217 First : Rec;
10218 After : Integer;
10219 case Big is
10220 when True => Another : Integer;
10221 when False => null;
10222 end case;
10223 end record;
10224 My_Container : Container := (Big => False,
10225 First => (Empty => True),
10226 After => 42);
10227
10228 In that example, the compiler creates a PAD type for component First,
10229 whose size is constant, and then positions the component After just
10230 right after it. The offset of component After is therefore constant
10231 in this case.
10232
10233 The debugger computes the position of each field based on an algorithm
10234 that uses, among other things, the actual position and size of the field
10235 preceding it. Let's now imagine that the user is trying to print
10236 the value of My_Container. If the type fixing was recursive, we would
10237 end up computing the offset of field After based on the size of the
10238 fixed version of field First. And since in our example First has
10239 only one actual field, the size of the fixed type is actually smaller
10240 than the amount of space allocated to that field, and thus we would
10241 compute the wrong offset of field After.
10242
10243 To make things more complicated, we need to watch out for dynamic
10244 components of variant records (identified by the ___XVL suffix in
10245 the component name). Even if the target type is a PAD type, the size
10246 of that type might not be statically known. So the PAD type needs
10247 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10248 we might end up with the wrong size for our component. This can be
10249 observed with the following type declarations:
10250
10251 type Octal is new Integer range 0 .. 7;
10252 type Octal_Array is array (Positive range <>) of Octal;
10253 pragma Pack (Octal_Array);
10254
10255 type Octal_Buffer (Size : Positive) is record
10256 Buffer : Octal_Array (1 .. Size);
10257 Length : Integer;
10258 end record;
10259
10260 In that case, Buffer is a PAD type whose size is unset and needs
10261 to be computed by fixing the unwrapped type.
10262
10263 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10264 ----------------------------------------------------------
10265
10266 Lastly, when should the sub-elements of an entity that remained unfixed
10267 thus far, be actually fixed?
10268
10269 The answer is: Only when referencing that element. For instance
10270 when selecting one component of a record, this specific component
10271 should be fixed at that point in time. Or when printing the value
10272 of a record, each component should be fixed before its value gets
10273 printed. Similarly for arrays, the element of the array should be
10274 fixed when printing each element of the array, or when extracting
10275 one element out of that array. On the other hand, fixing should
10276 not be performed on the elements when taking a slice of an array!
10277
10278 Note that one of the side effects of miscomputing the offset and
10279 size of each field is that we end up also miscomputing the size
10280 of the containing type. This can have adverse results when computing
10281 the value of an entity. GDB fetches the value of an entity based
10282 on the size of its type, and thus a wrong size causes GDB to fetch
10283 the wrong amount of memory. In the case where the computed size is
10284 too small, GDB fetches too little data to print the value of our
10285 entity. Results in this case are unpredictable, as we usually read
10286 past the buffer containing the data =:-o. */
10287
10288 /* Evaluate a subexpression of EXP, at index *POS, and return a value
10289 for that subexpression cast to TO_TYPE. Advance *POS over the
10290 subexpression. */
10291
10292 static value *
10293 ada_evaluate_subexp_for_cast (expression *exp, int *pos,
10294 enum noside noside, struct type *to_type)
10295 {
10296 int pc = *pos;
10297
10298 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE
10299 || exp->elts[pc].opcode == OP_VAR_VALUE)
10300 {
10301 (*pos) += 4;
10302
10303 value *val;
10304 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
10305 {
10306 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10307 return value_zero (to_type, not_lval);
10308
10309 val = evaluate_var_msym_value (noside,
10310 exp->elts[pc + 1].objfile,
10311 exp->elts[pc + 2].msymbol);
10312 }
10313 else
10314 val = evaluate_var_value (noside,
10315 exp->elts[pc + 1].block,
10316 exp->elts[pc + 2].symbol);
10317
10318 if (noside == EVAL_SKIP)
10319 return eval_skip_value (exp);
10320
10321 val = ada_value_cast (to_type, val);
10322
10323 /* Follow the Ada language semantics that do not allow taking
10324 an address of the result of a cast (view conversion in Ada). */
10325 if (VALUE_LVAL (val) == lval_memory)
10326 {
10327 if (value_lazy (val))
10328 value_fetch_lazy (val);
10329 VALUE_LVAL (val) = not_lval;
10330 }
10331 return val;
10332 }
10333
10334 value *val = evaluate_subexp (to_type, exp, pos, noside);
10335 if (noside == EVAL_SKIP)
10336 return eval_skip_value (exp);
10337 return ada_value_cast (to_type, val);
10338 }
10339
10340 /* Implement the evaluate_exp routine in the exp_descriptor structure
10341 for the Ada language. */
10342
10343 static struct value *
10344 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
10345 int *pos, enum noside noside)
10346 {
10347 enum exp_opcode op;
10348 int tem;
10349 int pc;
10350 int preeval_pos;
10351 struct value *arg1 = NULL, *arg2 = NULL, *arg3;
10352 struct type *type;
10353 int nargs, oplen;
10354 struct value **argvec;
10355
10356 pc = *pos;
10357 *pos += 1;
10358 op = exp->elts[pc].opcode;
10359
10360 switch (op)
10361 {
10362 default:
10363 *pos -= 1;
10364 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
10365
10366 if (noside == EVAL_NORMAL)
10367 arg1 = unwrap_value (arg1);
10368
10369 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10370 then we need to perform the conversion manually, because
10371 evaluate_subexp_standard doesn't do it. This conversion is
10372 necessary in Ada because the different kinds of float/fixed
10373 types in Ada have different representations.
10374
10375 Similarly, we need to perform the conversion from OP_LONG
10376 ourselves. */
10377 if ((op == OP_FLOAT || op == OP_LONG) && expect_type != NULL)
10378 arg1 = ada_value_cast (expect_type, arg1);
10379
10380 return arg1;
10381
10382 case OP_STRING:
10383 {
10384 struct value *result;
10385
10386 *pos -= 1;
10387 result = evaluate_subexp_standard (expect_type, exp, pos, noside);
10388 /* The result type will have code OP_STRING, bashed there from
10389 OP_ARRAY. Bash it back. */
10390 if (TYPE_CODE (value_type (result)) == TYPE_CODE_STRING)
10391 TYPE_CODE (value_type (result)) = TYPE_CODE_ARRAY;
10392 return result;
10393 }
10394
10395 case UNOP_CAST:
10396 (*pos) += 2;
10397 type = exp->elts[pc + 1].type;
10398 return ada_evaluate_subexp_for_cast (exp, pos, noside, type);
10399
10400 case UNOP_QUAL:
10401 (*pos) += 2;
10402 type = exp->elts[pc + 1].type;
10403 return ada_evaluate_subexp (type, exp, pos, noside);
10404
10405 case BINOP_ASSIGN:
10406 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10407 if (exp->elts[*pos].opcode == OP_AGGREGATE)
10408 {
10409 arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
10410 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
10411 return arg1;
10412 return ada_value_assign (arg1, arg1);
10413 }
10414 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
10415 except if the lhs of our assignment is a convenience variable.
10416 In the case of assigning to a convenience variable, the lhs
10417 should be exactly the result of the evaluation of the rhs. */
10418 type = value_type (arg1);
10419 if (VALUE_LVAL (arg1) == lval_internalvar)
10420 type = NULL;
10421 arg2 = evaluate_subexp (type, exp, pos, noside);
10422 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
10423 return arg1;
10424 if (VALUE_LVAL (arg1) == lval_internalvar)
10425 {
10426 /* Nothing. */
10427 }
10428 else if (ada_is_fixed_point_type (value_type (arg1)))
10429 arg2 = cast_to_fixed (value_type (arg1), arg2);
10430 else if (ada_is_fixed_point_type (value_type (arg2)))
10431 error
10432 (_("Fixed-point values must be assigned to fixed-point variables"));
10433 else
10434 arg2 = coerce_for_assign (value_type (arg1), arg2);
10435 return ada_value_assign (arg1, arg2);
10436
10437 case BINOP_ADD:
10438 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
10439 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
10440 if (noside == EVAL_SKIP)
10441 goto nosideret;
10442 if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
10443 return (value_from_longest
10444 (value_type (arg1),
10445 value_as_long (arg1) + value_as_long (arg2)));
10446 if (TYPE_CODE (value_type (arg2)) == TYPE_CODE_PTR)
10447 return (value_from_longest
10448 (value_type (arg2),
10449 value_as_long (arg1) + value_as_long (arg2)));
10450 if ((ada_is_fixed_point_type (value_type (arg1))
10451 || ada_is_fixed_point_type (value_type (arg2)))
10452 && value_type (arg1) != value_type (arg2))
10453 error (_("Operands of fixed-point addition must have the same type"));
10454 /* Do the addition, and cast the result to the type of the first
10455 argument. We cannot cast the result to a reference type, so if
10456 ARG1 is a reference type, find its underlying type. */
10457 type = value_type (arg1);
10458 while (TYPE_CODE (type) == TYPE_CODE_REF)
10459 type = TYPE_TARGET_TYPE (type);
10460 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10461 return value_cast (type, value_binop (arg1, arg2, BINOP_ADD));
10462
10463 case BINOP_SUB:
10464 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
10465 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
10466 if (noside == EVAL_SKIP)
10467 goto nosideret;
10468 if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
10469 return (value_from_longest
10470 (value_type (arg1),
10471 value_as_long (arg1) - value_as_long (arg2)));
10472 if (TYPE_CODE (value_type (arg2)) == TYPE_CODE_PTR)
10473 return (value_from_longest
10474 (value_type (arg2),
10475 value_as_long (arg1) - value_as_long (arg2)));
10476 if ((ada_is_fixed_point_type (value_type (arg1))
10477 || ada_is_fixed_point_type (value_type (arg2)))
10478 && value_type (arg1) != value_type (arg2))
10479 error (_("Operands of fixed-point subtraction "
10480 "must have the same type"));
10481 /* Do the substraction, and cast the result to the type of the first
10482 argument. We cannot cast the result to a reference type, so if
10483 ARG1 is a reference type, find its underlying type. */
10484 type = value_type (arg1);
10485 while (TYPE_CODE (type) == TYPE_CODE_REF)
10486 type = TYPE_TARGET_TYPE (type);
10487 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10488 return value_cast (type, value_binop (arg1, arg2, BINOP_SUB));
10489
10490 case BINOP_MUL:
10491 case BINOP_DIV:
10492 case BINOP_REM:
10493 case BINOP_MOD:
10494 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10495 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10496 if (noside == EVAL_SKIP)
10497 goto nosideret;
10498 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10499 {
10500 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10501 return value_zero (value_type (arg1), not_lval);
10502 }
10503 else
10504 {
10505 type = builtin_type (exp->gdbarch)->builtin_double;
10506 if (ada_is_fixed_point_type (value_type (arg1)))
10507 arg1 = cast_from_fixed (type, arg1);
10508 if (ada_is_fixed_point_type (value_type (arg2)))
10509 arg2 = cast_from_fixed (type, arg2);
10510 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10511 return ada_value_binop (arg1, arg2, op);
10512 }
10513
10514 case BINOP_EQUAL:
10515 case BINOP_NOTEQUAL:
10516 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10517 arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
10518 if (noside == EVAL_SKIP)
10519 goto nosideret;
10520 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10521 tem = 0;
10522 else
10523 {
10524 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10525 tem = ada_value_equal (arg1, arg2);
10526 }
10527 if (op == BINOP_NOTEQUAL)
10528 tem = !tem;
10529 type = language_bool_type (exp->language_defn, exp->gdbarch);
10530 return value_from_longest (type, (LONGEST) tem);
10531
10532 case UNOP_NEG:
10533 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10534 if (noside == EVAL_SKIP)
10535 goto nosideret;
10536 else if (ada_is_fixed_point_type (value_type (arg1)))
10537 return value_cast (value_type (arg1), value_neg (arg1));
10538 else
10539 {
10540 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10541 return value_neg (arg1);
10542 }
10543
10544 case BINOP_LOGICAL_AND:
10545 case BINOP_LOGICAL_OR:
10546 case UNOP_LOGICAL_NOT:
10547 {
10548 struct value *val;
10549
10550 *pos -= 1;
10551 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
10552 type = language_bool_type (exp->language_defn, exp->gdbarch);
10553 return value_cast (type, val);
10554 }
10555
10556 case BINOP_BITWISE_AND:
10557 case BINOP_BITWISE_IOR:
10558 case BINOP_BITWISE_XOR:
10559 {
10560 struct value *val;
10561
10562 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
10563 *pos = pc;
10564 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
10565
10566 return value_cast (value_type (arg1), val);
10567 }
10568
10569 case OP_VAR_VALUE:
10570 *pos -= 1;
10571
10572 if (noside == EVAL_SKIP)
10573 {
10574 *pos += 4;
10575 goto nosideret;
10576 }
10577
10578 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
10579 /* Only encountered when an unresolved symbol occurs in a
10580 context other than a function call, in which case, it is
10581 invalid. */
10582 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10583 exp->elts[pc + 2].symbol->print_name ());
10584
10585 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10586 {
10587 type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
10588 /* Check to see if this is a tagged type. We also need to handle
10589 the case where the type is a reference to a tagged type, but
10590 we have to be careful to exclude pointers to tagged types.
10591 The latter should be shown as usual (as a pointer), whereas
10592 a reference should mostly be transparent to the user. */
10593 if (ada_is_tagged_type (type, 0)
10594 || (TYPE_CODE (type) == TYPE_CODE_REF
10595 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10596 {
10597 /* Tagged types are a little special in the fact that the real
10598 type is dynamic and can only be determined by inspecting the
10599 object's tag. This means that we need to get the object's
10600 value first (EVAL_NORMAL) and then extract the actual object
10601 type from its tag.
10602
10603 Note that we cannot skip the final step where we extract
10604 the object type from its tag, because the EVAL_NORMAL phase
10605 results in dynamic components being resolved into fixed ones.
10606 This can cause problems when trying to print the type
10607 description of tagged types whose parent has a dynamic size:
10608 We use the type name of the "_parent" component in order
10609 to print the name of the ancestor type in the type description.
10610 If that component had a dynamic size, the resolution into
10611 a fixed type would result in the loss of that type name,
10612 thus preventing us from printing the name of the ancestor
10613 type in the type description. */
10614 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_NORMAL);
10615
10616 if (TYPE_CODE (type) != TYPE_CODE_REF)
10617 {
10618 struct type *actual_type;
10619
10620 actual_type = type_from_tag (ada_value_tag (arg1));
10621 if (actual_type == NULL)
10622 /* If, for some reason, we were unable to determine
10623 the actual type from the tag, then use the static
10624 approximation that we just computed as a fallback.
10625 This can happen if the debugging information is
10626 incomplete, for instance. */
10627 actual_type = type;
10628 return value_zero (actual_type, not_lval);
10629 }
10630 else
10631 {
10632 /* In the case of a ref, ada_coerce_ref takes care
10633 of determining the actual type. But the evaluation
10634 should return a ref as it should be valid to ask
10635 for its address; so rebuild a ref after coerce. */
10636 arg1 = ada_coerce_ref (arg1);
10637 return value_ref (arg1, TYPE_CODE_REF);
10638 }
10639 }
10640
10641 /* Records and unions for which GNAT encodings have been
10642 generated need to be statically fixed as well.
10643 Otherwise, non-static fixing produces a type where
10644 all dynamic properties are removed, which prevents "ptype"
10645 from being able to completely describe the type.
10646 For instance, a case statement in a variant record would be
10647 replaced by the relevant components based on the actual
10648 value of the discriminants. */
10649 if ((TYPE_CODE (type) == TYPE_CODE_STRUCT
10650 && dynamic_template_type (type) != NULL)
10651 || (TYPE_CODE (type) == TYPE_CODE_UNION
10652 && ada_find_parallel_type (type, "___XVU") != NULL))
10653 {
10654 *pos += 4;
10655 return value_zero (to_static_fixed_type (type), not_lval);
10656 }
10657 }
10658
10659 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
10660 return ada_to_fixed_value (arg1);
10661
10662 case OP_FUNCALL:
10663 (*pos) += 2;
10664
10665 /* Allocate arg vector, including space for the function to be
10666 called in argvec[0] and a terminating NULL. */
10667 nargs = longest_to_int (exp->elts[pc + 1].longconst);
10668 argvec = XALLOCAVEC (struct value *, nargs + 2);
10669
10670 if (exp->elts[*pos].opcode == OP_VAR_VALUE
10671 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
10672 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10673 exp->elts[pc + 5].symbol->print_name ());
10674 else
10675 {
10676 for (tem = 0; tem <= nargs; tem += 1)
10677 argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10678 argvec[tem] = 0;
10679
10680 if (noside == EVAL_SKIP)
10681 goto nosideret;
10682 }
10683
10684 if (ada_is_constrained_packed_array_type
10685 (desc_base_type (value_type (argvec[0]))))
10686 argvec[0] = ada_coerce_to_simple_array (argvec[0]);
10687 else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
10688 && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
10689 /* This is a packed array that has already been fixed, and
10690 therefore already coerced to a simple array. Nothing further
10691 to do. */
10692 ;
10693 else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_REF)
10694 {
10695 /* Make sure we dereference references so that all the code below
10696 feels like it's really handling the referenced value. Wrapping
10697 types (for alignment) may be there, so make sure we strip them as
10698 well. */
10699 argvec[0] = ada_to_fixed_value (coerce_ref (argvec[0]));
10700 }
10701 else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
10702 && VALUE_LVAL (argvec[0]) == lval_memory)
10703 argvec[0] = value_addr (argvec[0]);
10704
10705 type = ada_check_typedef (value_type (argvec[0]));
10706
10707 /* Ada allows us to implicitly dereference arrays when subscripting
10708 them. So, if this is an array typedef (encoding use for array
10709 access types encoded as fat pointers), strip it now. */
10710 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
10711 type = ada_typedef_target_type (type);
10712
10713 if (TYPE_CODE (type) == TYPE_CODE_PTR)
10714 {
10715 switch (TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type))))
10716 {
10717 case TYPE_CODE_FUNC:
10718 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10719 break;
10720 case TYPE_CODE_ARRAY:
10721 break;
10722 case TYPE_CODE_STRUCT:
10723 if (noside != EVAL_AVOID_SIDE_EFFECTS)
10724 argvec[0] = ada_value_ind (argvec[0]);
10725 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10726 break;
10727 default:
10728 error (_("cannot subscript or call something of type `%s'"),
10729 ada_type_name (value_type (argvec[0])));
10730 break;
10731 }
10732 }
10733
10734 switch (TYPE_CODE (type))
10735 {
10736 case TYPE_CODE_FUNC:
10737 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10738 {
10739 if (TYPE_TARGET_TYPE (type) == NULL)
10740 error_call_unknown_return_type (NULL);
10741 return allocate_value (TYPE_TARGET_TYPE (type));
10742 }
10743 return call_function_by_hand (argvec[0], NULL,
10744 gdb::make_array_view (argvec + 1,
10745 nargs));
10746 case TYPE_CODE_INTERNAL_FUNCTION:
10747 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10748 /* We don't know anything about what the internal
10749 function might return, but we have to return
10750 something. */
10751 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10752 not_lval);
10753 else
10754 return call_internal_function (exp->gdbarch, exp->language_defn,
10755 argvec[0], nargs, argvec + 1);
10756
10757 case TYPE_CODE_STRUCT:
10758 {
10759 int arity;
10760
10761 arity = ada_array_arity (type);
10762 type = ada_array_element_type (type, nargs);
10763 if (type == NULL)
10764 error (_("cannot subscript or call a record"));
10765 if (arity != nargs)
10766 error (_("wrong number of subscripts; expecting %d"), arity);
10767 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10768 return value_zero (ada_aligned_type (type), lval_memory);
10769 return
10770 unwrap_value (ada_value_subscript
10771 (argvec[0], nargs, argvec + 1));
10772 }
10773 case TYPE_CODE_ARRAY:
10774 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10775 {
10776 type = ada_array_element_type (type, nargs);
10777 if (type == NULL)
10778 error (_("element type of array unknown"));
10779 else
10780 return value_zero (ada_aligned_type (type), lval_memory);
10781 }
10782 return
10783 unwrap_value (ada_value_subscript
10784 (ada_coerce_to_simple_array (argvec[0]),
10785 nargs, argvec + 1));
10786 case TYPE_CODE_PTR: /* Pointer to array */
10787 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10788 {
10789 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
10790 type = ada_array_element_type (type, nargs);
10791 if (type == NULL)
10792 error (_("element type of array unknown"));
10793 else
10794 return value_zero (ada_aligned_type (type), lval_memory);
10795 }
10796 return
10797 unwrap_value (ada_value_ptr_subscript (argvec[0],
10798 nargs, argvec + 1));
10799
10800 default:
10801 error (_("Attempt to index or call something other than an "
10802 "array or function"));
10803 }
10804
10805 case TERNOP_SLICE:
10806 {
10807 struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10808 struct value *low_bound_val =
10809 evaluate_subexp (NULL_TYPE, exp, pos, noside);
10810 struct value *high_bound_val =
10811 evaluate_subexp (NULL_TYPE, exp, pos, noside);
10812 LONGEST low_bound;
10813 LONGEST high_bound;
10814
10815 low_bound_val = coerce_ref (low_bound_val);
10816 high_bound_val = coerce_ref (high_bound_val);
10817 low_bound = value_as_long (low_bound_val);
10818 high_bound = value_as_long (high_bound_val);
10819
10820 if (noside == EVAL_SKIP)
10821 goto nosideret;
10822
10823 /* If this is a reference to an aligner type, then remove all
10824 the aligners. */
10825 if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
10826 && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
10827 TYPE_TARGET_TYPE (value_type (array)) =
10828 ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
10829
10830 if (ada_is_constrained_packed_array_type (value_type (array)))
10831 error (_("cannot slice a packed array"));
10832
10833 /* If this is a reference to an array or an array lvalue,
10834 convert to a pointer. */
10835 if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
10836 || (TYPE_CODE (value_type (array)) == TYPE_CODE_ARRAY
10837 && VALUE_LVAL (array) == lval_memory))
10838 array = value_addr (array);
10839
10840 if (noside == EVAL_AVOID_SIDE_EFFECTS
10841 && ada_is_array_descriptor_type (ada_check_typedef
10842 (value_type (array))))
10843 return empty_array (ada_type_of_array (array, 0), low_bound,
10844 high_bound);
10845
10846 array = ada_coerce_to_simple_array_ptr (array);
10847
10848 /* If we have more than one level of pointer indirection,
10849 dereference the value until we get only one level. */
10850 while (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR
10851 && (TYPE_CODE (TYPE_TARGET_TYPE (value_type (array)))
10852 == TYPE_CODE_PTR))
10853 array = value_ind (array);
10854
10855 /* Make sure we really do have an array type before going further,
10856 to avoid a SEGV when trying to get the index type or the target
10857 type later down the road if the debug info generated by
10858 the compiler is incorrect or incomplete. */
10859 if (!ada_is_simple_array_type (value_type (array)))
10860 error (_("cannot take slice of non-array"));
10861
10862 if (TYPE_CODE (ada_check_typedef (value_type (array)))
10863 == TYPE_CODE_PTR)
10864 {
10865 struct type *type0 = ada_check_typedef (value_type (array));
10866
10867 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10868 return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
10869 else
10870 {
10871 struct type *arr_type0 =
10872 to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
10873
10874 return ada_value_slice_from_ptr (array, arr_type0,
10875 longest_to_int (low_bound),
10876 longest_to_int (high_bound));
10877 }
10878 }
10879 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10880 return array;
10881 else if (high_bound < low_bound)
10882 return empty_array (value_type (array), low_bound, high_bound);
10883 else
10884 return ada_value_slice (array, longest_to_int (low_bound),
10885 longest_to_int (high_bound));
10886 }
10887
10888 case UNOP_IN_RANGE:
10889 (*pos) += 2;
10890 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10891 type = check_typedef (exp->elts[pc + 1].type);
10892
10893 if (noside == EVAL_SKIP)
10894 goto nosideret;
10895
10896 switch (TYPE_CODE (type))
10897 {
10898 default:
10899 lim_warning (_("Membership test incompletely implemented; "
10900 "always returns true"));
10901 type = language_bool_type (exp->language_defn, exp->gdbarch);
10902 return value_from_longest (type, (LONGEST) 1);
10903
10904 case TYPE_CODE_RANGE:
10905 arg2 = value_from_longest (type, TYPE_LOW_BOUND (type));
10906 arg3 = value_from_longest (type, TYPE_HIGH_BOUND (type));
10907 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10908 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10909 type = language_bool_type (exp->language_defn, exp->gdbarch);
10910 return
10911 value_from_longest (type,
10912 (value_less (arg1, arg3)
10913 || value_equal (arg1, arg3))
10914 && (value_less (arg2, arg1)
10915 || value_equal (arg2, arg1)));
10916 }
10917
10918 case BINOP_IN_BOUNDS:
10919 (*pos) += 2;
10920 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10921 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10922
10923 if (noside == EVAL_SKIP)
10924 goto nosideret;
10925
10926 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10927 {
10928 type = language_bool_type (exp->language_defn, exp->gdbarch);
10929 return value_zero (type, not_lval);
10930 }
10931
10932 tem = longest_to_int (exp->elts[pc + 1].longconst);
10933
10934 type = ada_index_type (value_type (arg2), tem, "range");
10935 if (!type)
10936 type = value_type (arg1);
10937
10938 arg3 = value_from_longest (type, ada_array_bound (arg2, tem, 1));
10939 arg2 = value_from_longest (type, ada_array_bound (arg2, tem, 0));
10940
10941 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10942 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10943 type = language_bool_type (exp->language_defn, exp->gdbarch);
10944 return
10945 value_from_longest (type,
10946 (value_less (arg1, arg3)
10947 || value_equal (arg1, arg3))
10948 && (value_less (arg2, arg1)
10949 || value_equal (arg2, arg1)));
10950
10951 case TERNOP_IN_RANGE:
10952 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10953 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10954 arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10955
10956 if (noside == EVAL_SKIP)
10957 goto nosideret;
10958
10959 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10960 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10961 type = language_bool_type (exp->language_defn, exp->gdbarch);
10962 return
10963 value_from_longest (type,
10964 (value_less (arg1, arg3)
10965 || value_equal (arg1, arg3))
10966 && (value_less (arg2, arg1)
10967 || value_equal (arg2, arg1)));
10968
10969 case OP_ATR_FIRST:
10970 case OP_ATR_LAST:
10971 case OP_ATR_LENGTH:
10972 {
10973 struct type *type_arg;
10974
10975 if (exp->elts[*pos].opcode == OP_TYPE)
10976 {
10977 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10978 arg1 = NULL;
10979 type_arg = check_typedef (exp->elts[pc + 2].type);
10980 }
10981 else
10982 {
10983 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10984 type_arg = NULL;
10985 }
10986
10987 if (exp->elts[*pos].opcode != OP_LONG)
10988 error (_("Invalid operand to '%s"), ada_attribute_name (op));
10989 tem = longest_to_int (exp->elts[*pos + 2].longconst);
10990 *pos += 4;
10991
10992 if (noside == EVAL_SKIP)
10993 goto nosideret;
10994 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10995 {
10996 if (type_arg == NULL)
10997 type_arg = value_type (arg1);
10998
10999 if (ada_is_constrained_packed_array_type (type_arg))
11000 type_arg = decode_constrained_packed_array_type (type_arg);
11001
11002 if (!discrete_type_p (type_arg))
11003 {
11004 switch (op)
11005 {
11006 default: /* Should never happen. */
11007 error (_("unexpected attribute encountered"));
11008 case OP_ATR_FIRST:
11009 case OP_ATR_LAST:
11010 type_arg = ada_index_type (type_arg, tem,
11011 ada_attribute_name (op));
11012 break;
11013 case OP_ATR_LENGTH:
11014 type_arg = builtin_type (exp->gdbarch)->builtin_int;
11015 break;
11016 }
11017 }
11018
11019 return value_zero (type_arg, not_lval);
11020 }
11021 else if (type_arg == NULL)
11022 {
11023 arg1 = ada_coerce_ref (arg1);
11024
11025 if (ada_is_constrained_packed_array_type (value_type (arg1)))
11026 arg1 = ada_coerce_to_simple_array (arg1);
11027
11028 if (op == OP_ATR_LENGTH)
11029 type = builtin_type (exp->gdbarch)->builtin_int;
11030 else
11031 {
11032 type = ada_index_type (value_type (arg1), tem,
11033 ada_attribute_name (op));
11034 if (type == NULL)
11035 type = builtin_type (exp->gdbarch)->builtin_int;
11036 }
11037
11038 switch (op)
11039 {
11040 default: /* Should never happen. */
11041 error (_("unexpected attribute encountered"));
11042 case OP_ATR_FIRST:
11043 return value_from_longest
11044 (type, ada_array_bound (arg1, tem, 0));
11045 case OP_ATR_LAST:
11046 return value_from_longest
11047 (type, ada_array_bound (arg1, tem, 1));
11048 case OP_ATR_LENGTH:
11049 return value_from_longest
11050 (type, ada_array_length (arg1, tem));
11051 }
11052 }
11053 else if (discrete_type_p (type_arg))
11054 {
11055 struct type *range_type;
11056 const char *name = ada_type_name (type_arg);
11057
11058 range_type = NULL;
11059 if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
11060 range_type = to_fixed_range_type (type_arg, NULL);
11061 if (range_type == NULL)
11062 range_type = type_arg;
11063 switch (op)
11064 {
11065 default:
11066 error (_("unexpected attribute encountered"));
11067 case OP_ATR_FIRST:
11068 return value_from_longest
11069 (range_type, ada_discrete_type_low_bound (range_type));
11070 case OP_ATR_LAST:
11071 return value_from_longest
11072 (range_type, ada_discrete_type_high_bound (range_type));
11073 case OP_ATR_LENGTH:
11074 error (_("the 'length attribute applies only to array types"));
11075 }
11076 }
11077 else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
11078 error (_("unimplemented type attribute"));
11079 else
11080 {
11081 LONGEST low, high;
11082
11083 if (ada_is_constrained_packed_array_type (type_arg))
11084 type_arg = decode_constrained_packed_array_type (type_arg);
11085
11086 if (op == OP_ATR_LENGTH)
11087 type = builtin_type (exp->gdbarch)->builtin_int;
11088 else
11089 {
11090 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
11091 if (type == NULL)
11092 type = builtin_type (exp->gdbarch)->builtin_int;
11093 }
11094
11095 switch (op)
11096 {
11097 default:
11098 error (_("unexpected attribute encountered"));
11099 case OP_ATR_FIRST:
11100 low = ada_array_bound_from_type (type_arg, tem, 0);
11101 return value_from_longest (type, low);
11102 case OP_ATR_LAST:
11103 high = ada_array_bound_from_type (type_arg, tem, 1);
11104 return value_from_longest (type, high);
11105 case OP_ATR_LENGTH:
11106 low = ada_array_bound_from_type (type_arg, tem, 0);
11107 high = ada_array_bound_from_type (type_arg, tem, 1);
11108 return value_from_longest (type, high - low + 1);
11109 }
11110 }
11111 }
11112
11113 case OP_ATR_TAG:
11114 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11115 if (noside == EVAL_SKIP)
11116 goto nosideret;
11117
11118 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11119 return value_zero (ada_tag_type (arg1), not_lval);
11120
11121 return ada_value_tag (arg1);
11122
11123 case OP_ATR_MIN:
11124 case OP_ATR_MAX:
11125 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11126 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11127 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11128 if (noside == EVAL_SKIP)
11129 goto nosideret;
11130 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11131 return value_zero (value_type (arg1), not_lval);
11132 else
11133 {
11134 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11135 return value_binop (arg1, arg2,
11136 op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
11137 }
11138
11139 case OP_ATR_MODULUS:
11140 {
11141 struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
11142
11143 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11144 if (noside == EVAL_SKIP)
11145 goto nosideret;
11146
11147 if (!ada_is_modular_type (type_arg))
11148 error (_("'modulus must be applied to modular type"));
11149
11150 return value_from_longest (TYPE_TARGET_TYPE (type_arg),
11151 ada_modulus (type_arg));
11152 }
11153
11154
11155 case OP_ATR_POS:
11156 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11157 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11158 if (noside == EVAL_SKIP)
11159 goto nosideret;
11160 type = builtin_type (exp->gdbarch)->builtin_int;
11161 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11162 return value_zero (type, not_lval);
11163 else
11164 return value_pos_atr (type, arg1);
11165
11166 case OP_ATR_SIZE:
11167 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11168 type = value_type (arg1);
11169
11170 /* If the argument is a reference, then dereference its type, since
11171 the user is really asking for the size of the actual object,
11172 not the size of the pointer. */
11173 if (TYPE_CODE (type) == TYPE_CODE_REF)
11174 type = TYPE_TARGET_TYPE (type);
11175
11176 if (noside == EVAL_SKIP)
11177 goto nosideret;
11178 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11179 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
11180 else
11181 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
11182 TARGET_CHAR_BIT * TYPE_LENGTH (type));
11183
11184 case OP_ATR_VAL:
11185 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11186 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11187 type = exp->elts[pc + 2].type;
11188 if (noside == EVAL_SKIP)
11189 goto nosideret;
11190 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11191 return value_zero (type, not_lval);
11192 else
11193 return value_val_atr (type, arg1);
11194
11195 case BINOP_EXP:
11196 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11197 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11198 if (noside == EVAL_SKIP)
11199 goto nosideret;
11200 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11201 return value_zero (value_type (arg1), not_lval);
11202 else
11203 {
11204 /* For integer exponentiation operations,
11205 only promote the first argument. */
11206 if (is_integral_type (value_type (arg2)))
11207 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
11208 else
11209 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11210
11211 return value_binop (arg1, arg2, op);
11212 }
11213
11214 case UNOP_PLUS:
11215 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11216 if (noside == EVAL_SKIP)
11217 goto nosideret;
11218 else
11219 return arg1;
11220
11221 case UNOP_ABS:
11222 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11223 if (noside == EVAL_SKIP)
11224 goto nosideret;
11225 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
11226 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
11227 return value_neg (arg1);
11228 else
11229 return arg1;
11230
11231 case UNOP_IND:
11232 preeval_pos = *pos;
11233 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11234 if (noside == EVAL_SKIP)
11235 goto nosideret;
11236 type = ada_check_typedef (value_type (arg1));
11237 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11238 {
11239 if (ada_is_array_descriptor_type (type))
11240 /* GDB allows dereferencing GNAT array descriptors. */
11241 {
11242 struct type *arrType = ada_type_of_array (arg1, 0);
11243
11244 if (arrType == NULL)
11245 error (_("Attempt to dereference null array pointer."));
11246 return value_at_lazy (arrType, 0);
11247 }
11248 else if (TYPE_CODE (type) == TYPE_CODE_PTR
11249 || TYPE_CODE (type) == TYPE_CODE_REF
11250 /* In C you can dereference an array to get the 1st elt. */
11251 || TYPE_CODE (type) == TYPE_CODE_ARRAY)
11252 {
11253 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11254 only be determined by inspecting the object's tag.
11255 This means that we need to evaluate completely the
11256 expression in order to get its type. */
11257
11258 if ((TYPE_CODE (type) == TYPE_CODE_REF
11259 || TYPE_CODE (type) == TYPE_CODE_PTR)
11260 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11261 {
11262 arg1 = evaluate_subexp (NULL_TYPE, exp, &preeval_pos,
11263 EVAL_NORMAL);
11264 type = value_type (ada_value_ind (arg1));
11265 }
11266 else
11267 {
11268 type = to_static_fixed_type
11269 (ada_aligned_type
11270 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
11271 }
11272 ada_ensure_varsize_limit (type);
11273 return value_zero (type, lval_memory);
11274 }
11275 else if (TYPE_CODE (type) == TYPE_CODE_INT)
11276 {
11277 /* GDB allows dereferencing an int. */
11278 if (expect_type == NULL)
11279 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11280 lval_memory);
11281 else
11282 {
11283 expect_type =
11284 to_static_fixed_type (ada_aligned_type (expect_type));
11285 return value_zero (expect_type, lval_memory);
11286 }
11287 }
11288 else
11289 error (_("Attempt to take contents of a non-pointer value."));
11290 }
11291 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11292 type = ada_check_typedef (value_type (arg1));
11293
11294 if (TYPE_CODE (type) == TYPE_CODE_INT)
11295 /* GDB allows dereferencing an int. If we were given
11296 the expect_type, then use that as the target type.
11297 Otherwise, assume that the target type is an int. */
11298 {
11299 if (expect_type != NULL)
11300 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11301 arg1));
11302 else
11303 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11304 (CORE_ADDR) value_as_address (arg1));
11305 }
11306
11307 if (ada_is_array_descriptor_type (type))
11308 /* GDB allows dereferencing GNAT array descriptors. */
11309 return ada_coerce_to_simple_array (arg1);
11310 else
11311 return ada_value_ind (arg1);
11312
11313 case STRUCTOP_STRUCT:
11314 tem = longest_to_int (exp->elts[pc + 1].longconst);
11315 (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
11316 preeval_pos = *pos;
11317 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11318 if (noside == EVAL_SKIP)
11319 goto nosideret;
11320 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11321 {
11322 struct type *type1 = value_type (arg1);
11323
11324 if (ada_is_tagged_type (type1, 1))
11325 {
11326 type = ada_lookup_struct_elt_type (type1,
11327 &exp->elts[pc + 2].string,
11328 1, 1);
11329
11330 /* If the field is not found, check if it exists in the
11331 extension of this object's type. This means that we
11332 need to evaluate completely the expression. */
11333
11334 if (type == NULL)
11335 {
11336 arg1 = evaluate_subexp (NULL_TYPE, exp, &preeval_pos,
11337 EVAL_NORMAL);
11338 arg1 = ada_value_struct_elt (arg1,
11339 &exp->elts[pc + 2].string,
11340 0);
11341 arg1 = unwrap_value (arg1);
11342 type = value_type (ada_to_fixed_value (arg1));
11343 }
11344 }
11345 else
11346 type =
11347 ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
11348 0);
11349
11350 return value_zero (ada_aligned_type (type), lval_memory);
11351 }
11352 else
11353 {
11354 arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
11355 arg1 = unwrap_value (arg1);
11356 return ada_to_fixed_value (arg1);
11357 }
11358
11359 case OP_TYPE:
11360 /* The value is not supposed to be used. This is here to make it
11361 easier to accommodate expressions that contain types. */
11362 (*pos) += 2;
11363 if (noside == EVAL_SKIP)
11364 goto nosideret;
11365 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11366 return allocate_value (exp->elts[pc + 1].type);
11367 else
11368 error (_("Attempt to use a type name as an expression"));
11369
11370 case OP_AGGREGATE:
11371 case OP_CHOICES:
11372 case OP_OTHERS:
11373 case OP_DISCRETE_RANGE:
11374 case OP_POSITIONAL:
11375 case OP_NAME:
11376 if (noside == EVAL_NORMAL)
11377 switch (op)
11378 {
11379 case OP_NAME:
11380 error (_("Undefined name, ambiguous name, or renaming used in "
11381 "component association: %s."), &exp->elts[pc+2].string);
11382 case OP_AGGREGATE:
11383 error (_("Aggregates only allowed on the right of an assignment"));
11384 default:
11385 internal_error (__FILE__, __LINE__,
11386 _("aggregate apparently mangled"));
11387 }
11388
11389 ada_forward_operator_length (exp, pc, &oplen, &nargs);
11390 *pos += oplen - 1;
11391 for (tem = 0; tem < nargs; tem += 1)
11392 ada_evaluate_subexp (NULL, exp, pos, noside);
11393 goto nosideret;
11394 }
11395
11396 nosideret:
11397 return eval_skip_value (exp);
11398 }
11399 \f
11400
11401 /* Fixed point */
11402
11403 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
11404 type name that encodes the 'small and 'delta information.
11405 Otherwise, return NULL. */
11406
11407 static const char *
11408 fixed_type_info (struct type *type)
11409 {
11410 const char *name = ada_type_name (type);
11411 enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
11412
11413 if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
11414 {
11415 const char *tail = strstr (name, "___XF_");
11416
11417 if (tail == NULL)
11418 return NULL;
11419 else
11420 return tail + 5;
11421 }
11422 else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
11423 return fixed_type_info (TYPE_TARGET_TYPE (type));
11424 else
11425 return NULL;
11426 }
11427
11428 /* Returns non-zero iff TYPE represents an Ada fixed-point type. */
11429
11430 int
11431 ada_is_fixed_point_type (struct type *type)
11432 {
11433 return fixed_type_info (type) != NULL;
11434 }
11435
11436 /* Return non-zero iff TYPE represents a System.Address type. */
11437
11438 int
11439 ada_is_system_address_type (struct type *type)
11440 {
11441 return (TYPE_NAME (type)
11442 && strcmp (TYPE_NAME (type), "system__address") == 0);
11443 }
11444
11445 /* Assuming that TYPE is the representation of an Ada fixed-point
11446 type, return the target floating-point type to be used to represent
11447 of this type during internal computation. */
11448
11449 static struct type *
11450 ada_scaling_type (struct type *type)
11451 {
11452 return builtin_type (get_type_arch (type))->builtin_long_double;
11453 }
11454
11455 /* Assuming that TYPE is the representation of an Ada fixed-point
11456 type, return its delta, or NULL if the type is malformed and the
11457 delta cannot be determined. */
11458
11459 struct value *
11460 ada_delta (struct type *type)
11461 {
11462 const char *encoding = fixed_type_info (type);
11463 struct type *scale_type = ada_scaling_type (type);
11464
11465 long long num, den;
11466
11467 if (sscanf (encoding, "_%lld_%lld", &num, &den) < 2)
11468 return nullptr;
11469 else
11470 return value_binop (value_from_longest (scale_type, num),
11471 value_from_longest (scale_type, den), BINOP_DIV);
11472 }
11473
11474 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
11475 factor ('SMALL value) associated with the type. */
11476
11477 struct value *
11478 ada_scaling_factor (struct type *type)
11479 {
11480 const char *encoding = fixed_type_info (type);
11481 struct type *scale_type = ada_scaling_type (type);
11482
11483 long long num0, den0, num1, den1;
11484 int n;
11485
11486 n = sscanf (encoding, "_%lld_%lld_%lld_%lld",
11487 &num0, &den0, &num1, &den1);
11488
11489 if (n < 2)
11490 return value_from_longest (scale_type, 1);
11491 else if (n == 4)
11492 return value_binop (value_from_longest (scale_type, num1),
11493 value_from_longest (scale_type, den1), BINOP_DIV);
11494 else
11495 return value_binop (value_from_longest (scale_type, num0),
11496 value_from_longest (scale_type, den0), BINOP_DIV);
11497 }
11498
11499 \f
11500
11501 /* Range types */
11502
11503 /* Scan STR beginning at position K for a discriminant name, and
11504 return the value of that discriminant field of DVAL in *PX. If
11505 PNEW_K is not null, put the position of the character beyond the
11506 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11507 not alter *PX and *PNEW_K if unsuccessful. */
11508
11509 static int
11510 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11511 int *pnew_k)
11512 {
11513 static char *bound_buffer = NULL;
11514 static size_t bound_buffer_len = 0;
11515 const char *pstart, *pend, *bound;
11516 struct value *bound_val;
11517
11518 if (dval == NULL || str == NULL || str[k] == '\0')
11519 return 0;
11520
11521 pstart = str + k;
11522 pend = strstr (pstart, "__");
11523 if (pend == NULL)
11524 {
11525 bound = pstart;
11526 k += strlen (bound);
11527 }
11528 else
11529 {
11530 int len = pend - pstart;
11531
11532 /* Strip __ and beyond. */
11533 GROW_VECT (bound_buffer, bound_buffer_len, len + 1);
11534 strncpy (bound_buffer, pstart, len);
11535 bound_buffer[len] = '\0';
11536
11537 bound = bound_buffer;
11538 k = pend - str;
11539 }
11540
11541 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
11542 if (bound_val == NULL)
11543 return 0;
11544
11545 *px = value_as_long (bound_val);
11546 if (pnew_k != NULL)
11547 *pnew_k = k;
11548 return 1;
11549 }
11550
11551 /* Value of variable named NAME in the current environment. If
11552 no such variable found, then if ERR_MSG is null, returns 0, and
11553 otherwise causes an error with message ERR_MSG. */
11554
11555 static struct value *
11556 get_var_value (const char *name, const char *err_msg)
11557 {
11558 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
11559
11560 std::vector<struct block_symbol> syms;
11561 int nsyms = ada_lookup_symbol_list_worker (lookup_name,
11562 get_selected_block (0),
11563 VAR_DOMAIN, &syms, 1);
11564
11565 if (nsyms != 1)
11566 {
11567 if (err_msg == NULL)
11568 return 0;
11569 else
11570 error (("%s"), err_msg);
11571 }
11572
11573 return value_of_variable (syms[0].symbol, syms[0].block);
11574 }
11575
11576 /* Value of integer variable named NAME in the current environment.
11577 If no such variable is found, returns false. Otherwise, sets VALUE
11578 to the variable's value and returns true. */
11579
11580 bool
11581 get_int_var_value (const char *name, LONGEST &value)
11582 {
11583 struct value *var_val = get_var_value (name, 0);
11584
11585 if (var_val == 0)
11586 return false;
11587
11588 value = value_as_long (var_val);
11589 return true;
11590 }
11591
11592
11593 /* Return a range type whose base type is that of the range type named
11594 NAME in the current environment, and whose bounds are calculated
11595 from NAME according to the GNAT range encoding conventions.
11596 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11597 corresponding range type from debug information; fall back to using it
11598 if symbol lookup fails. If a new type must be created, allocate it
11599 like ORIG_TYPE was. The bounds information, in general, is encoded
11600 in NAME, the base type given in the named range type. */
11601
11602 static struct type *
11603 to_fixed_range_type (struct type *raw_type, struct value *dval)
11604 {
11605 const char *name;
11606 struct type *base_type;
11607 const char *subtype_info;
11608
11609 gdb_assert (raw_type != NULL);
11610 gdb_assert (TYPE_NAME (raw_type) != NULL);
11611
11612 if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
11613 base_type = TYPE_TARGET_TYPE (raw_type);
11614 else
11615 base_type = raw_type;
11616
11617 name = TYPE_NAME (raw_type);
11618 subtype_info = strstr (name, "___XD");
11619 if (subtype_info == NULL)
11620 {
11621 LONGEST L = ada_discrete_type_low_bound (raw_type);
11622 LONGEST U = ada_discrete_type_high_bound (raw_type);
11623
11624 if (L < INT_MIN || U > INT_MAX)
11625 return raw_type;
11626 else
11627 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
11628 L, U);
11629 }
11630 else
11631 {
11632 static char *name_buf = NULL;
11633 static size_t name_len = 0;
11634 int prefix_len = subtype_info - name;
11635 LONGEST L, U;
11636 struct type *type;
11637 const char *bounds_str;
11638 int n;
11639
11640 GROW_VECT (name_buf, name_len, prefix_len + 5);
11641 strncpy (name_buf, name, prefix_len);
11642 name_buf[prefix_len] = '\0';
11643
11644 subtype_info += 5;
11645 bounds_str = strchr (subtype_info, '_');
11646 n = 1;
11647
11648 if (*subtype_info == 'L')
11649 {
11650 if (!ada_scan_number (bounds_str, n, &L, &n)
11651 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11652 return raw_type;
11653 if (bounds_str[n] == '_')
11654 n += 2;
11655 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11656 n += 1;
11657 subtype_info += 1;
11658 }
11659 else
11660 {
11661 strcpy (name_buf + prefix_len, "___L");
11662 if (!get_int_var_value (name_buf, L))
11663 {
11664 lim_warning (_("Unknown lower bound, using 1."));
11665 L = 1;
11666 }
11667 }
11668
11669 if (*subtype_info == 'U')
11670 {
11671 if (!ada_scan_number (bounds_str, n, &U, &n)
11672 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11673 return raw_type;
11674 }
11675 else
11676 {
11677 strcpy (name_buf + prefix_len, "___U");
11678 if (!get_int_var_value (name_buf, U))
11679 {
11680 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11681 U = L;
11682 }
11683 }
11684
11685 type = create_static_range_type (alloc_type_copy (raw_type),
11686 base_type, L, U);
11687 /* create_static_range_type alters the resulting type's length
11688 to match the size of the base_type, which is not what we want.
11689 Set it back to the original range type's length. */
11690 TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
11691 TYPE_NAME (type) = name;
11692 return type;
11693 }
11694 }
11695
11696 /* True iff NAME is the name of a range type. */
11697
11698 int
11699 ada_is_range_type_name (const char *name)
11700 {
11701 return (name != NULL && strstr (name, "___XD"));
11702 }
11703 \f
11704
11705 /* Modular types */
11706
11707 /* True iff TYPE is an Ada modular type. */
11708
11709 int
11710 ada_is_modular_type (struct type *type)
11711 {
11712 struct type *subranged_type = get_base_type (type);
11713
11714 return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
11715 && TYPE_CODE (subranged_type) == TYPE_CODE_INT
11716 && TYPE_UNSIGNED (subranged_type));
11717 }
11718
11719 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11720
11721 ULONGEST
11722 ada_modulus (struct type *type)
11723 {
11724 return (ULONGEST) TYPE_HIGH_BOUND (type) + 1;
11725 }
11726 \f
11727
11728 /* Ada exception catchpoint support:
11729 ---------------------------------
11730
11731 We support 3 kinds of exception catchpoints:
11732 . catchpoints on Ada exceptions
11733 . catchpoints on unhandled Ada exceptions
11734 . catchpoints on failed assertions
11735
11736 Exceptions raised during failed assertions, or unhandled exceptions
11737 could perfectly be caught with the general catchpoint on Ada exceptions.
11738 However, we can easily differentiate these two special cases, and having
11739 the option to distinguish these two cases from the rest can be useful
11740 to zero-in on certain situations.
11741
11742 Exception catchpoints are a specialized form of breakpoint,
11743 since they rely on inserting breakpoints inside known routines
11744 of the GNAT runtime. The implementation therefore uses a standard
11745 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11746 of breakpoint_ops.
11747
11748 Support in the runtime for exception catchpoints have been changed
11749 a few times already, and these changes affect the implementation
11750 of these catchpoints. In order to be able to support several
11751 variants of the runtime, we use a sniffer that will determine
11752 the runtime variant used by the program being debugged. */
11753
11754 /* Ada's standard exceptions.
11755
11756 The Ada 83 standard also defined Numeric_Error. But there so many
11757 situations where it was unclear from the Ada 83 Reference Manual
11758 (RM) whether Constraint_Error or Numeric_Error should be raised,
11759 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11760 Interpretation saying that anytime the RM says that Numeric_Error
11761 should be raised, the implementation may raise Constraint_Error.
11762 Ada 95 went one step further and pretty much removed Numeric_Error
11763 from the list of standard exceptions (it made it a renaming of
11764 Constraint_Error, to help preserve compatibility when compiling
11765 an Ada83 compiler). As such, we do not include Numeric_Error from
11766 this list of standard exceptions. */
11767
11768 static const char *standard_exc[] = {
11769 "constraint_error",
11770 "program_error",
11771 "storage_error",
11772 "tasking_error"
11773 };
11774
11775 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11776
11777 /* A structure that describes how to support exception catchpoints
11778 for a given executable. */
11779
11780 struct exception_support_info
11781 {
11782 /* The name of the symbol to break on in order to insert
11783 a catchpoint on exceptions. */
11784 const char *catch_exception_sym;
11785
11786 /* The name of the symbol to break on in order to insert
11787 a catchpoint on unhandled exceptions. */
11788 const char *catch_exception_unhandled_sym;
11789
11790 /* The name of the symbol to break on in order to insert
11791 a catchpoint on failed assertions. */
11792 const char *catch_assert_sym;
11793
11794 /* The name of the symbol to break on in order to insert
11795 a catchpoint on exception handling. */
11796 const char *catch_handlers_sym;
11797
11798 /* Assuming that the inferior just triggered an unhandled exception
11799 catchpoint, this function is responsible for returning the address
11800 in inferior memory where the name of that exception is stored.
11801 Return zero if the address could not be computed. */
11802 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11803 };
11804
11805 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11806 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11807
11808 /* The following exception support info structure describes how to
11809 implement exception catchpoints with the latest version of the
11810 Ada runtime (as of 2019-08-??). */
11811
11812 static const struct exception_support_info default_exception_support_info =
11813 {
11814 "__gnat_debug_raise_exception", /* catch_exception_sym */
11815 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11816 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11817 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11818 ada_unhandled_exception_name_addr
11819 };
11820
11821 /* The following exception support info structure describes how to
11822 implement exception catchpoints with an earlier version of the
11823 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11824
11825 static const struct exception_support_info exception_support_info_v0 =
11826 {
11827 "__gnat_debug_raise_exception", /* catch_exception_sym */
11828 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11829 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11830 "__gnat_begin_handler", /* catch_handlers_sym */
11831 ada_unhandled_exception_name_addr
11832 };
11833
11834 /* The following exception support info structure describes how to
11835 implement exception catchpoints with a slightly older version
11836 of the Ada runtime. */
11837
11838 static const struct exception_support_info exception_support_info_fallback =
11839 {
11840 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11841 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11842 "system__assertions__raise_assert_failure", /* catch_assert_sym */
11843 "__gnat_begin_handler", /* catch_handlers_sym */
11844 ada_unhandled_exception_name_addr_from_raise
11845 };
11846
11847 /* Return nonzero if we can detect the exception support routines
11848 described in EINFO.
11849
11850 This function errors out if an abnormal situation is detected
11851 (for instance, if we find the exception support routines, but
11852 that support is found to be incomplete). */
11853
11854 static int
11855 ada_has_this_exception_support (const struct exception_support_info *einfo)
11856 {
11857 struct symbol *sym;
11858
11859 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11860 that should be compiled with debugging information. As a result, we
11861 expect to find that symbol in the symtabs. */
11862
11863 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11864 if (sym == NULL)
11865 {
11866 /* Perhaps we did not find our symbol because the Ada runtime was
11867 compiled without debugging info, or simply stripped of it.
11868 It happens on some GNU/Linux distributions for instance, where
11869 users have to install a separate debug package in order to get
11870 the runtime's debugging info. In that situation, let the user
11871 know why we cannot insert an Ada exception catchpoint.
11872
11873 Note: Just for the purpose of inserting our Ada exception
11874 catchpoint, we could rely purely on the associated minimal symbol.
11875 But we would be operating in degraded mode anyway, since we are
11876 still lacking the debugging info needed later on to extract
11877 the name of the exception being raised (this name is printed in
11878 the catchpoint message, and is also used when trying to catch
11879 a specific exception). We do not handle this case for now. */
11880 struct bound_minimal_symbol msym
11881 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11882
11883 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11884 error (_("Your Ada runtime appears to be missing some debugging "
11885 "information.\nCannot insert Ada exception catchpoint "
11886 "in this configuration."));
11887
11888 return 0;
11889 }
11890
11891 /* Make sure that the symbol we found corresponds to a function. */
11892
11893 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11894 {
11895 error (_("Symbol \"%s\" is not a function (class = %d)"),
11896 sym->linkage_name (), SYMBOL_CLASS (sym));
11897 return 0;
11898 }
11899
11900 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11901 if (sym == NULL)
11902 {
11903 struct bound_minimal_symbol msym
11904 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11905
11906 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11907 error (_("Your Ada runtime appears to be missing some debugging "
11908 "information.\nCannot insert Ada exception catchpoint "
11909 "in this configuration."));
11910
11911 return 0;
11912 }
11913
11914 /* Make sure that the symbol we found corresponds to a function. */
11915
11916 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11917 {
11918 error (_("Symbol \"%s\" is not a function (class = %d)"),
11919 sym->linkage_name (), SYMBOL_CLASS (sym));
11920 return 0;
11921 }
11922
11923 return 1;
11924 }
11925
11926 /* Inspect the Ada runtime and determine which exception info structure
11927 should be used to provide support for exception catchpoints.
11928
11929 This function will always set the per-inferior exception_info,
11930 or raise an error. */
11931
11932 static void
11933 ada_exception_support_info_sniffer (void)
11934 {
11935 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11936
11937 /* If the exception info is already known, then no need to recompute it. */
11938 if (data->exception_info != NULL)
11939 return;
11940
11941 /* Check the latest (default) exception support info. */
11942 if (ada_has_this_exception_support (&default_exception_support_info))
11943 {
11944 data->exception_info = &default_exception_support_info;
11945 return;
11946 }
11947
11948 /* Try the v0 exception suport info. */
11949 if (ada_has_this_exception_support (&exception_support_info_v0))
11950 {
11951 data->exception_info = &exception_support_info_v0;
11952 return;
11953 }
11954
11955 /* Try our fallback exception suport info. */
11956 if (ada_has_this_exception_support (&exception_support_info_fallback))
11957 {
11958 data->exception_info = &exception_support_info_fallback;
11959 return;
11960 }
11961
11962 /* Sometimes, it is normal for us to not be able to find the routine
11963 we are looking for. This happens when the program is linked with
11964 the shared version of the GNAT runtime, and the program has not been
11965 started yet. Inform the user of these two possible causes if
11966 applicable. */
11967
11968 if (ada_update_initial_language (language_unknown) != language_ada)
11969 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
11970
11971 /* If the symbol does not exist, then check that the program is
11972 already started, to make sure that shared libraries have been
11973 loaded. If it is not started, this may mean that the symbol is
11974 in a shared library. */
11975
11976 if (inferior_ptid.pid () == 0)
11977 error (_("Unable to insert catchpoint. Try to start the program first."));
11978
11979 /* At this point, we know that we are debugging an Ada program and
11980 that the inferior has been started, but we still are not able to
11981 find the run-time symbols. That can mean that we are in
11982 configurable run time mode, or that a-except as been optimized
11983 out by the linker... In any case, at this point it is not worth
11984 supporting this feature. */
11985
11986 error (_("Cannot insert Ada exception catchpoints in this configuration."));
11987 }
11988
11989 /* True iff FRAME is very likely to be that of a function that is
11990 part of the runtime system. This is all very heuristic, but is
11991 intended to be used as advice as to what frames are uninteresting
11992 to most users. */
11993
11994 static int
11995 is_known_support_routine (struct frame_info *frame)
11996 {
11997 enum language func_lang;
11998 int i;
11999 const char *fullname;
12000
12001 /* If this code does not have any debugging information (no symtab),
12002 This cannot be any user code. */
12003
12004 symtab_and_line sal = find_frame_sal (frame);
12005 if (sal.symtab == NULL)
12006 return 1;
12007
12008 /* If there is a symtab, but the associated source file cannot be
12009 located, then assume this is not user code: Selecting a frame
12010 for which we cannot display the code would not be very helpful
12011 for the user. This should also take care of case such as VxWorks
12012 where the kernel has some debugging info provided for a few units. */
12013
12014 fullname = symtab_to_fullname (sal.symtab);
12015 if (access (fullname, R_OK) != 0)
12016 return 1;
12017
12018 /* Check the unit filename against the Ada runtime file naming.
12019 We also check the name of the objfile against the name of some
12020 known system libraries that sometimes come with debugging info
12021 too. */
12022
12023 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
12024 {
12025 re_comp (known_runtime_file_name_patterns[i]);
12026 if (re_exec (lbasename (sal.symtab->filename)))
12027 return 1;
12028 if (SYMTAB_OBJFILE (sal.symtab) != NULL
12029 && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
12030 return 1;
12031 }
12032
12033 /* Check whether the function is a GNAT-generated entity. */
12034
12035 gdb::unique_xmalloc_ptr<char> func_name
12036 = find_frame_funname (frame, &func_lang, NULL);
12037 if (func_name == NULL)
12038 return 1;
12039
12040 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
12041 {
12042 re_comp (known_auxiliary_function_name_patterns[i]);
12043 if (re_exec (func_name.get ()))
12044 return 1;
12045 }
12046
12047 return 0;
12048 }
12049
12050 /* Find the first frame that contains debugging information and that is not
12051 part of the Ada run-time, starting from FI and moving upward. */
12052
12053 void
12054 ada_find_printable_frame (struct frame_info *fi)
12055 {
12056 for (; fi != NULL; fi = get_prev_frame (fi))
12057 {
12058 if (!is_known_support_routine (fi))
12059 {
12060 select_frame (fi);
12061 break;
12062 }
12063 }
12064
12065 }
12066
12067 /* Assuming that the inferior just triggered an unhandled exception
12068 catchpoint, return the address in inferior memory where the name
12069 of the exception is stored.
12070
12071 Return zero if the address could not be computed. */
12072
12073 static CORE_ADDR
12074 ada_unhandled_exception_name_addr (void)
12075 {
12076 return parse_and_eval_address ("e.full_name");
12077 }
12078
12079 /* Same as ada_unhandled_exception_name_addr, except that this function
12080 should be used when the inferior uses an older version of the runtime,
12081 where the exception name needs to be extracted from a specific frame
12082 several frames up in the callstack. */
12083
12084 static CORE_ADDR
12085 ada_unhandled_exception_name_addr_from_raise (void)
12086 {
12087 int frame_level;
12088 struct frame_info *fi;
12089 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12090
12091 /* To determine the name of this exception, we need to select
12092 the frame corresponding to RAISE_SYM_NAME. This frame is
12093 at least 3 levels up, so we simply skip the first 3 frames
12094 without checking the name of their associated function. */
12095 fi = get_current_frame ();
12096 for (frame_level = 0; frame_level < 3; frame_level += 1)
12097 if (fi != NULL)
12098 fi = get_prev_frame (fi);
12099
12100 while (fi != NULL)
12101 {
12102 enum language func_lang;
12103
12104 gdb::unique_xmalloc_ptr<char> func_name
12105 = find_frame_funname (fi, &func_lang, NULL);
12106 if (func_name != NULL)
12107 {
12108 if (strcmp (func_name.get (),
12109 data->exception_info->catch_exception_sym) == 0)
12110 break; /* We found the frame we were looking for... */
12111 }
12112 fi = get_prev_frame (fi);
12113 }
12114
12115 if (fi == NULL)
12116 return 0;
12117
12118 select_frame (fi);
12119 return parse_and_eval_address ("id.full_name");
12120 }
12121
12122 /* Assuming the inferior just triggered an Ada exception catchpoint
12123 (of any type), return the address in inferior memory where the name
12124 of the exception is stored, if applicable.
12125
12126 Assumes the selected frame is the current frame.
12127
12128 Return zero if the address could not be computed, or if not relevant. */
12129
12130 static CORE_ADDR
12131 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
12132 struct breakpoint *b)
12133 {
12134 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12135
12136 switch (ex)
12137 {
12138 case ada_catch_exception:
12139 return (parse_and_eval_address ("e.full_name"));
12140 break;
12141
12142 case ada_catch_exception_unhandled:
12143 return data->exception_info->unhandled_exception_name_addr ();
12144 break;
12145
12146 case ada_catch_handlers:
12147 return 0; /* The runtimes does not provide access to the exception
12148 name. */
12149 break;
12150
12151 case ada_catch_assert:
12152 return 0; /* Exception name is not relevant in this case. */
12153 break;
12154
12155 default:
12156 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12157 break;
12158 }
12159
12160 return 0; /* Should never be reached. */
12161 }
12162
12163 /* Assuming the inferior is stopped at an exception catchpoint,
12164 return the message which was associated to the exception, if
12165 available. Return NULL if the message could not be retrieved.
12166
12167 Note: The exception message can be associated to an exception
12168 either through the use of the Raise_Exception function, or
12169 more simply (Ada 2005 and later), via:
12170
12171 raise Exception_Name with "exception message";
12172
12173 */
12174
12175 static gdb::unique_xmalloc_ptr<char>
12176 ada_exception_message_1 (void)
12177 {
12178 struct value *e_msg_val;
12179 int e_msg_len;
12180
12181 /* For runtimes that support this feature, the exception message
12182 is passed as an unbounded string argument called "message". */
12183 e_msg_val = parse_and_eval ("message");
12184 if (e_msg_val == NULL)
12185 return NULL; /* Exception message not supported. */
12186
12187 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12188 gdb_assert (e_msg_val != NULL);
12189 e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
12190
12191 /* If the message string is empty, then treat it as if there was
12192 no exception message. */
12193 if (e_msg_len <= 0)
12194 return NULL;
12195
12196 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12197 read_memory_string (value_address (e_msg_val), e_msg.get (), e_msg_len + 1);
12198 e_msg.get ()[e_msg_len] = '\0';
12199
12200 return e_msg;
12201 }
12202
12203 /* Same as ada_exception_message_1, except that all exceptions are
12204 contained here (returning NULL instead). */
12205
12206 static gdb::unique_xmalloc_ptr<char>
12207 ada_exception_message (void)
12208 {
12209 gdb::unique_xmalloc_ptr<char> e_msg;
12210
12211 try
12212 {
12213 e_msg = ada_exception_message_1 ();
12214 }
12215 catch (const gdb_exception_error &e)
12216 {
12217 e_msg.reset (nullptr);
12218 }
12219
12220 return e_msg;
12221 }
12222
12223 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12224 any error that ada_exception_name_addr_1 might cause to be thrown.
12225 When an error is intercepted, a warning with the error message is printed,
12226 and zero is returned. */
12227
12228 static CORE_ADDR
12229 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
12230 struct breakpoint *b)
12231 {
12232 CORE_ADDR result = 0;
12233
12234 try
12235 {
12236 result = ada_exception_name_addr_1 (ex, b);
12237 }
12238
12239 catch (const gdb_exception_error &e)
12240 {
12241 warning (_("failed to get exception name: %s"), e.what ());
12242 return 0;
12243 }
12244
12245 return result;
12246 }
12247
12248 static std::string ada_exception_catchpoint_cond_string
12249 (const char *excep_string,
12250 enum ada_exception_catchpoint_kind ex);
12251
12252 /* Ada catchpoints.
12253
12254 In the case of catchpoints on Ada exceptions, the catchpoint will
12255 stop the target on every exception the program throws. When a user
12256 specifies the name of a specific exception, we translate this
12257 request into a condition expression (in text form), and then parse
12258 it into an expression stored in each of the catchpoint's locations.
12259 We then use this condition to check whether the exception that was
12260 raised is the one the user is interested in. If not, then the
12261 target is resumed again. We store the name of the requested
12262 exception, in order to be able to re-set the condition expression
12263 when symbols change. */
12264
12265 /* An instance of this type is used to represent an Ada catchpoint
12266 breakpoint location. */
12267
12268 class ada_catchpoint_location : public bp_location
12269 {
12270 public:
12271 ada_catchpoint_location (breakpoint *owner)
12272 : bp_location (owner, bp_loc_software_breakpoint)
12273 {}
12274
12275 /* The condition that checks whether the exception that was raised
12276 is the specific exception the user specified on catchpoint
12277 creation. */
12278 expression_up excep_cond_expr;
12279 };
12280
12281 /* An instance of this type is used to represent an Ada catchpoint. */
12282
12283 struct ada_catchpoint : public breakpoint
12284 {
12285 explicit ada_catchpoint (enum ada_exception_catchpoint_kind kind)
12286 : m_kind (kind)
12287 {
12288 }
12289
12290 /* The name of the specific exception the user specified. */
12291 std::string excep_string;
12292
12293 /* What kind of catchpoint this is. */
12294 enum ada_exception_catchpoint_kind m_kind;
12295 };
12296
12297 /* Parse the exception condition string in the context of each of the
12298 catchpoint's locations, and store them for later evaluation. */
12299
12300 static void
12301 create_excep_cond_exprs (struct ada_catchpoint *c,
12302 enum ada_exception_catchpoint_kind ex)
12303 {
12304 struct bp_location *bl;
12305
12306 /* Nothing to do if there's no specific exception to catch. */
12307 if (c->excep_string.empty ())
12308 return;
12309
12310 /* Same if there are no locations... */
12311 if (c->loc == NULL)
12312 return;
12313
12314 /* Compute the condition expression in text form, from the specific
12315 expection we want to catch. */
12316 std::string cond_string
12317 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12318
12319 /* Iterate over all the catchpoint's locations, and parse an
12320 expression for each. */
12321 for (bl = c->loc; bl != NULL; bl = bl->next)
12322 {
12323 struct ada_catchpoint_location *ada_loc
12324 = (struct ada_catchpoint_location *) bl;
12325 expression_up exp;
12326
12327 if (!bl->shlib_disabled)
12328 {
12329 const char *s;
12330
12331 s = cond_string.c_str ();
12332 try
12333 {
12334 exp = parse_exp_1 (&s, bl->address,
12335 block_for_pc (bl->address),
12336 0);
12337 }
12338 catch (const gdb_exception_error &e)
12339 {
12340 warning (_("failed to reevaluate internal exception condition "
12341 "for catchpoint %d: %s"),
12342 c->number, e.what ());
12343 }
12344 }
12345
12346 ada_loc->excep_cond_expr = std::move (exp);
12347 }
12348 }
12349
12350 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
12351 structure for all exception catchpoint kinds. */
12352
12353 static struct bp_location *
12354 allocate_location_exception (struct breakpoint *self)
12355 {
12356 return new ada_catchpoint_location (self);
12357 }
12358
12359 /* Implement the RE_SET method in the breakpoint_ops structure for all
12360 exception catchpoint kinds. */
12361
12362 static void
12363 re_set_exception (struct breakpoint *b)
12364 {
12365 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12366
12367 /* Call the base class's method. This updates the catchpoint's
12368 locations. */
12369 bkpt_breakpoint_ops.re_set (b);
12370
12371 /* Reparse the exception conditional expressions. One for each
12372 location. */
12373 create_excep_cond_exprs (c, c->m_kind);
12374 }
12375
12376 /* Returns true if we should stop for this breakpoint hit. If the
12377 user specified a specific exception, we only want to cause a stop
12378 if the program thrown that exception. */
12379
12380 static int
12381 should_stop_exception (const struct bp_location *bl)
12382 {
12383 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12384 const struct ada_catchpoint_location *ada_loc
12385 = (const struct ada_catchpoint_location *) bl;
12386 int stop;
12387
12388 struct internalvar *var = lookup_internalvar ("_ada_exception");
12389 if (c->m_kind == ada_catch_assert)
12390 clear_internalvar (var);
12391 else
12392 {
12393 try
12394 {
12395 const char *expr;
12396
12397 if (c->m_kind == ada_catch_handlers)
12398 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12399 ".all.occurrence.id");
12400 else
12401 expr = "e";
12402
12403 struct value *exc = parse_and_eval (expr);
12404 set_internalvar (var, exc);
12405 }
12406 catch (const gdb_exception_error &ex)
12407 {
12408 clear_internalvar (var);
12409 }
12410 }
12411
12412 /* With no specific exception, should always stop. */
12413 if (c->excep_string.empty ())
12414 return 1;
12415
12416 if (ada_loc->excep_cond_expr == NULL)
12417 {
12418 /* We will have a NULL expression if back when we were creating
12419 the expressions, this location's had failed to parse. */
12420 return 1;
12421 }
12422
12423 stop = 1;
12424 try
12425 {
12426 struct value *mark;
12427
12428 mark = value_mark ();
12429 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
12430 value_free_to_mark (mark);
12431 }
12432 catch (const gdb_exception &ex)
12433 {
12434 exception_fprintf (gdb_stderr, ex,
12435 _("Error in testing exception condition:\n"));
12436 }
12437
12438 return stop;
12439 }
12440
12441 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
12442 for all exception catchpoint kinds. */
12443
12444 static void
12445 check_status_exception (bpstat bs)
12446 {
12447 bs->stop = should_stop_exception (bs->bp_location_at);
12448 }
12449
12450 /* Implement the PRINT_IT method in the breakpoint_ops structure
12451 for all exception catchpoint kinds. */
12452
12453 static enum print_stop_action
12454 print_it_exception (bpstat bs)
12455 {
12456 struct ui_out *uiout = current_uiout;
12457 struct breakpoint *b = bs->breakpoint_at;
12458
12459 annotate_catchpoint (b->number);
12460
12461 if (uiout->is_mi_like_p ())
12462 {
12463 uiout->field_string ("reason",
12464 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12465 uiout->field_string ("disp", bpdisp_text (b->disposition));
12466 }
12467
12468 uiout->text (b->disposition == disp_del
12469 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12470 uiout->field_signed ("bkptno", b->number);
12471 uiout->text (", ");
12472
12473 /* ada_exception_name_addr relies on the selected frame being the
12474 current frame. Need to do this here because this function may be
12475 called more than once when printing a stop, and below, we'll
12476 select the first frame past the Ada run-time (see
12477 ada_find_printable_frame). */
12478 select_frame (get_current_frame ());
12479
12480 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12481 switch (c->m_kind)
12482 {
12483 case ada_catch_exception:
12484 case ada_catch_exception_unhandled:
12485 case ada_catch_handlers:
12486 {
12487 const CORE_ADDR addr = ada_exception_name_addr (c->m_kind, b);
12488 char exception_name[256];
12489
12490 if (addr != 0)
12491 {
12492 read_memory (addr, (gdb_byte *) exception_name,
12493 sizeof (exception_name) - 1);
12494 exception_name [sizeof (exception_name) - 1] = '\0';
12495 }
12496 else
12497 {
12498 /* For some reason, we were unable to read the exception
12499 name. This could happen if the Runtime was compiled
12500 without debugging info, for instance. In that case,
12501 just replace the exception name by the generic string
12502 "exception" - it will read as "an exception" in the
12503 notification we are about to print. */
12504 memcpy (exception_name, "exception", sizeof ("exception"));
12505 }
12506 /* In the case of unhandled exception breakpoints, we print
12507 the exception name as "unhandled EXCEPTION_NAME", to make
12508 it clearer to the user which kind of catchpoint just got
12509 hit. We used ui_out_text to make sure that this extra
12510 info does not pollute the exception name in the MI case. */
12511 if (c->m_kind == ada_catch_exception_unhandled)
12512 uiout->text ("unhandled ");
12513 uiout->field_string ("exception-name", exception_name);
12514 }
12515 break;
12516 case ada_catch_assert:
12517 /* In this case, the name of the exception is not really
12518 important. Just print "failed assertion" to make it clearer
12519 that his program just hit an assertion-failure catchpoint.
12520 We used ui_out_text because this info does not belong in
12521 the MI output. */
12522 uiout->text ("failed assertion");
12523 break;
12524 }
12525
12526 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12527 if (exception_message != NULL)
12528 {
12529 uiout->text (" (");
12530 uiout->field_string ("exception-message", exception_message.get ());
12531 uiout->text (")");
12532 }
12533
12534 uiout->text (" at ");
12535 ada_find_printable_frame (get_current_frame ());
12536
12537 return PRINT_SRC_AND_LOC;
12538 }
12539
12540 /* Implement the PRINT_ONE method in the breakpoint_ops structure
12541 for all exception catchpoint kinds. */
12542
12543 static void
12544 print_one_exception (struct breakpoint *b, struct bp_location **last_loc)
12545 {
12546 struct ui_out *uiout = current_uiout;
12547 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12548 struct value_print_options opts;
12549
12550 get_user_print_options (&opts);
12551
12552 if (opts.addressprint)
12553 uiout->field_skip ("addr");
12554
12555 annotate_field (5);
12556 switch (c->m_kind)
12557 {
12558 case ada_catch_exception:
12559 if (!c->excep_string.empty ())
12560 {
12561 std::string msg = string_printf (_("`%s' Ada exception"),
12562 c->excep_string.c_str ());
12563
12564 uiout->field_string ("what", msg);
12565 }
12566 else
12567 uiout->field_string ("what", "all Ada exceptions");
12568
12569 break;
12570
12571 case ada_catch_exception_unhandled:
12572 uiout->field_string ("what", "unhandled Ada exceptions");
12573 break;
12574
12575 case ada_catch_handlers:
12576 if (!c->excep_string.empty ())
12577 {
12578 uiout->field_fmt ("what",
12579 _("`%s' Ada exception handlers"),
12580 c->excep_string.c_str ());
12581 }
12582 else
12583 uiout->field_string ("what", "all Ada exceptions handlers");
12584 break;
12585
12586 case ada_catch_assert:
12587 uiout->field_string ("what", "failed Ada assertions");
12588 break;
12589
12590 default:
12591 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12592 break;
12593 }
12594 }
12595
12596 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12597 for all exception catchpoint kinds. */
12598
12599 static void
12600 print_mention_exception (struct breakpoint *b)
12601 {
12602 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12603 struct ui_out *uiout = current_uiout;
12604
12605 uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
12606 : _("Catchpoint "));
12607 uiout->field_signed ("bkptno", b->number);
12608 uiout->text (": ");
12609
12610 switch (c->m_kind)
12611 {
12612 case ada_catch_exception:
12613 if (!c->excep_string.empty ())
12614 {
12615 std::string info = string_printf (_("`%s' Ada exception"),
12616 c->excep_string.c_str ());
12617 uiout->text (info.c_str ());
12618 }
12619 else
12620 uiout->text (_("all Ada exceptions"));
12621 break;
12622
12623 case ada_catch_exception_unhandled:
12624 uiout->text (_("unhandled Ada exceptions"));
12625 break;
12626
12627 case ada_catch_handlers:
12628 if (!c->excep_string.empty ())
12629 {
12630 std::string info
12631 = string_printf (_("`%s' Ada exception handlers"),
12632 c->excep_string.c_str ());
12633 uiout->text (info.c_str ());
12634 }
12635 else
12636 uiout->text (_("all Ada exceptions handlers"));
12637 break;
12638
12639 case ada_catch_assert:
12640 uiout->text (_("failed Ada assertions"));
12641 break;
12642
12643 default:
12644 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12645 break;
12646 }
12647 }
12648
12649 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
12650 for all exception catchpoint kinds. */
12651
12652 static void
12653 print_recreate_exception (struct breakpoint *b, struct ui_file *fp)
12654 {
12655 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12656
12657 switch (c->m_kind)
12658 {
12659 case ada_catch_exception:
12660 fprintf_filtered (fp, "catch exception");
12661 if (!c->excep_string.empty ())
12662 fprintf_filtered (fp, " %s", c->excep_string.c_str ());
12663 break;
12664
12665 case ada_catch_exception_unhandled:
12666 fprintf_filtered (fp, "catch exception unhandled");
12667 break;
12668
12669 case ada_catch_handlers:
12670 fprintf_filtered (fp, "catch handlers");
12671 break;
12672
12673 case ada_catch_assert:
12674 fprintf_filtered (fp, "catch assert");
12675 break;
12676
12677 default:
12678 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12679 }
12680 print_recreate_thread (b, fp);
12681 }
12682
12683 /* Virtual tables for various breakpoint types. */
12684 static struct breakpoint_ops catch_exception_breakpoint_ops;
12685 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
12686 static struct breakpoint_ops catch_assert_breakpoint_ops;
12687 static struct breakpoint_ops catch_handlers_breakpoint_ops;
12688
12689 /* See ada-lang.h. */
12690
12691 bool
12692 is_ada_exception_catchpoint (breakpoint *bp)
12693 {
12694 return (bp->ops == &catch_exception_breakpoint_ops
12695 || bp->ops == &catch_exception_unhandled_breakpoint_ops
12696 || bp->ops == &catch_assert_breakpoint_ops
12697 || bp->ops == &catch_handlers_breakpoint_ops);
12698 }
12699
12700 /* Split the arguments specified in a "catch exception" command.
12701 Set EX to the appropriate catchpoint type.
12702 Set EXCEP_STRING to the name of the specific exception if
12703 specified by the user.
12704 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12705 "catch handlers" command. False otherwise.
12706 If a condition is found at the end of the arguments, the condition
12707 expression is stored in COND_STRING (memory must be deallocated
12708 after use). Otherwise COND_STRING is set to NULL. */
12709
12710 static void
12711 catch_ada_exception_command_split (const char *args,
12712 bool is_catch_handlers_cmd,
12713 enum ada_exception_catchpoint_kind *ex,
12714 std::string *excep_string,
12715 std::string *cond_string)
12716 {
12717 std::string exception_name;
12718
12719 exception_name = extract_arg (&args);
12720 if (exception_name == "if")
12721 {
12722 /* This is not an exception name; this is the start of a condition
12723 expression for a catchpoint on all exceptions. So, "un-get"
12724 this token, and set exception_name to NULL. */
12725 exception_name.clear ();
12726 args -= 2;
12727 }
12728
12729 /* Check to see if we have a condition. */
12730
12731 args = skip_spaces (args);
12732 if (startswith (args, "if")
12733 && (isspace (args[2]) || args[2] == '\0'))
12734 {
12735 args += 2;
12736 args = skip_spaces (args);
12737
12738 if (args[0] == '\0')
12739 error (_("Condition missing after `if' keyword"));
12740 *cond_string = args;
12741
12742 args += strlen (args);
12743 }
12744
12745 /* Check that we do not have any more arguments. Anything else
12746 is unexpected. */
12747
12748 if (args[0] != '\0')
12749 error (_("Junk at end of expression"));
12750
12751 if (is_catch_handlers_cmd)
12752 {
12753 /* Catch handling of exceptions. */
12754 *ex = ada_catch_handlers;
12755 *excep_string = exception_name;
12756 }
12757 else if (exception_name.empty ())
12758 {
12759 /* Catch all exceptions. */
12760 *ex = ada_catch_exception;
12761 excep_string->clear ();
12762 }
12763 else if (exception_name == "unhandled")
12764 {
12765 /* Catch unhandled exceptions. */
12766 *ex = ada_catch_exception_unhandled;
12767 excep_string->clear ();
12768 }
12769 else
12770 {
12771 /* Catch a specific exception. */
12772 *ex = ada_catch_exception;
12773 *excep_string = exception_name;
12774 }
12775 }
12776
12777 /* Return the name of the symbol on which we should break in order to
12778 implement a catchpoint of the EX kind. */
12779
12780 static const char *
12781 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12782 {
12783 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12784
12785 gdb_assert (data->exception_info != NULL);
12786
12787 switch (ex)
12788 {
12789 case ada_catch_exception:
12790 return (data->exception_info->catch_exception_sym);
12791 break;
12792 case ada_catch_exception_unhandled:
12793 return (data->exception_info->catch_exception_unhandled_sym);
12794 break;
12795 case ada_catch_assert:
12796 return (data->exception_info->catch_assert_sym);
12797 break;
12798 case ada_catch_handlers:
12799 return (data->exception_info->catch_handlers_sym);
12800 break;
12801 default:
12802 internal_error (__FILE__, __LINE__,
12803 _("unexpected catchpoint kind (%d)"), ex);
12804 }
12805 }
12806
12807 /* Return the breakpoint ops "virtual table" used for catchpoints
12808 of the EX kind. */
12809
12810 static const struct breakpoint_ops *
12811 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
12812 {
12813 switch (ex)
12814 {
12815 case ada_catch_exception:
12816 return (&catch_exception_breakpoint_ops);
12817 break;
12818 case ada_catch_exception_unhandled:
12819 return (&catch_exception_unhandled_breakpoint_ops);
12820 break;
12821 case ada_catch_assert:
12822 return (&catch_assert_breakpoint_ops);
12823 break;
12824 case ada_catch_handlers:
12825 return (&catch_handlers_breakpoint_ops);
12826 break;
12827 default:
12828 internal_error (__FILE__, __LINE__,
12829 _("unexpected catchpoint kind (%d)"), ex);
12830 }
12831 }
12832
12833 /* Return the condition that will be used to match the current exception
12834 being raised with the exception that the user wants to catch. This
12835 assumes that this condition is used when the inferior just triggered
12836 an exception catchpoint.
12837 EX: the type of catchpoints used for catching Ada exceptions. */
12838
12839 static std::string
12840 ada_exception_catchpoint_cond_string (const char *excep_string,
12841 enum ada_exception_catchpoint_kind ex)
12842 {
12843 int i;
12844 bool is_standard_exc = false;
12845 std::string result;
12846
12847 if (ex == ada_catch_handlers)
12848 {
12849 /* For exception handlers catchpoints, the condition string does
12850 not use the same parameter as for the other exceptions. */
12851 result = ("long_integer (GNAT_GCC_exception_Access"
12852 "(gcc_exception).all.occurrence.id)");
12853 }
12854 else
12855 result = "long_integer (e)";
12856
12857 /* The standard exceptions are a special case. They are defined in
12858 runtime units that have been compiled without debugging info; if
12859 EXCEP_STRING is the not-fully-qualified name of a standard
12860 exception (e.g. "constraint_error") then, during the evaluation
12861 of the condition expression, the symbol lookup on this name would
12862 *not* return this standard exception. The catchpoint condition
12863 may then be set only on user-defined exceptions which have the
12864 same not-fully-qualified name (e.g. my_package.constraint_error).
12865
12866 To avoid this unexcepted behavior, these standard exceptions are
12867 systematically prefixed by "standard". This means that "catch
12868 exception constraint_error" is rewritten into "catch exception
12869 standard.constraint_error".
12870
12871 If an exception named constraint_error is defined in another package of
12872 the inferior program, then the only way to specify this exception as a
12873 breakpoint condition is to use its fully-qualified named:
12874 e.g. my_package.constraint_error. */
12875
12876 for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
12877 {
12878 if (strcmp (standard_exc [i], excep_string) == 0)
12879 {
12880 is_standard_exc = true;
12881 break;
12882 }
12883 }
12884
12885 result += " = ";
12886
12887 if (is_standard_exc)
12888 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12889 else
12890 string_appendf (result, "long_integer (&%s)", excep_string);
12891
12892 return result;
12893 }
12894
12895 /* Return the symtab_and_line that should be used to insert an exception
12896 catchpoint of the TYPE kind.
12897
12898 ADDR_STRING returns the name of the function where the real
12899 breakpoint that implements the catchpoints is set, depending on the
12900 type of catchpoint we need to create. */
12901
12902 static struct symtab_and_line
12903 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12904 std::string *addr_string, const struct breakpoint_ops **ops)
12905 {
12906 const char *sym_name;
12907 struct symbol *sym;
12908
12909 /* First, find out which exception support info to use. */
12910 ada_exception_support_info_sniffer ();
12911
12912 /* Then lookup the function on which we will break in order to catch
12913 the Ada exceptions requested by the user. */
12914 sym_name = ada_exception_sym_name (ex);
12915 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12916
12917 if (sym == NULL)
12918 error (_("Catchpoint symbol not found: %s"), sym_name);
12919
12920 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12921 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12922
12923 /* Set ADDR_STRING. */
12924 *addr_string = sym_name;
12925
12926 /* Set OPS. */
12927 *ops = ada_exception_breakpoint_ops (ex);
12928
12929 return find_function_start_sal (sym, 1);
12930 }
12931
12932 /* Create an Ada exception catchpoint.
12933
12934 EX_KIND is the kind of exception catchpoint to be created.
12935
12936 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12937 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
12938 of the exception to which this catchpoint applies.
12939
12940 COND_STRING, if not empty, is the catchpoint condition.
12941
12942 TEMPFLAG, if nonzero, means that the underlying breakpoint
12943 should be temporary.
12944
12945 FROM_TTY is the usual argument passed to all commands implementations. */
12946
12947 void
12948 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12949 enum ada_exception_catchpoint_kind ex_kind,
12950 const std::string &excep_string,
12951 const std::string &cond_string,
12952 int tempflag,
12953 int disabled,
12954 int from_tty)
12955 {
12956 std::string addr_string;
12957 const struct breakpoint_ops *ops = NULL;
12958 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
12959
12960 std::unique_ptr<ada_catchpoint> c (new ada_catchpoint (ex_kind));
12961 init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
12962 ops, tempflag, disabled, from_tty);
12963 c->excep_string = excep_string;
12964 create_excep_cond_exprs (c.get (), ex_kind);
12965 if (!cond_string.empty ())
12966 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty);
12967 install_breakpoint (0, std::move (c), 1);
12968 }
12969
12970 /* Implement the "catch exception" command. */
12971
12972 static void
12973 catch_ada_exception_command (const char *arg_entry, int from_tty,
12974 struct cmd_list_element *command)
12975 {
12976 const char *arg = arg_entry;
12977 struct gdbarch *gdbarch = get_current_arch ();
12978 int tempflag;
12979 enum ada_exception_catchpoint_kind ex_kind;
12980 std::string excep_string;
12981 std::string cond_string;
12982
12983 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12984
12985 if (!arg)
12986 arg = "";
12987 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12988 &cond_string);
12989 create_ada_exception_catchpoint (gdbarch, ex_kind,
12990 excep_string, cond_string,
12991 tempflag, 1 /* enabled */,
12992 from_tty);
12993 }
12994
12995 /* Implement the "catch handlers" command. */
12996
12997 static void
12998 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12999 struct cmd_list_element *command)
13000 {
13001 const char *arg = arg_entry;
13002 struct gdbarch *gdbarch = get_current_arch ();
13003 int tempflag;
13004 enum ada_exception_catchpoint_kind ex_kind;
13005 std::string excep_string;
13006 std::string cond_string;
13007
13008 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13009
13010 if (!arg)
13011 arg = "";
13012 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
13013 &cond_string);
13014 create_ada_exception_catchpoint (gdbarch, ex_kind,
13015 excep_string, cond_string,
13016 tempflag, 1 /* enabled */,
13017 from_tty);
13018 }
13019
13020 /* Completion function for the Ada "catch" commands. */
13021
13022 static void
13023 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
13024 const char *text, const char *word)
13025 {
13026 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
13027
13028 for (const ada_exc_info &info : exceptions)
13029 {
13030 if (startswith (info.name, word))
13031 tracker.add_completion (make_unique_xstrdup (info.name));
13032 }
13033 }
13034
13035 /* Split the arguments specified in a "catch assert" command.
13036
13037 ARGS contains the command's arguments (or the empty string if
13038 no arguments were passed).
13039
13040 If ARGS contains a condition, set COND_STRING to that condition
13041 (the memory needs to be deallocated after use). */
13042
13043 static void
13044 catch_ada_assert_command_split (const char *args, std::string &cond_string)
13045 {
13046 args = skip_spaces (args);
13047
13048 /* Check whether a condition was provided. */
13049 if (startswith (args, "if")
13050 && (isspace (args[2]) || args[2] == '\0'))
13051 {
13052 args += 2;
13053 args = skip_spaces (args);
13054 if (args[0] == '\0')
13055 error (_("condition missing after `if' keyword"));
13056 cond_string.assign (args);
13057 }
13058
13059 /* Otherwise, there should be no other argument at the end of
13060 the command. */
13061 else if (args[0] != '\0')
13062 error (_("Junk at end of arguments."));
13063 }
13064
13065 /* Implement the "catch assert" command. */
13066
13067 static void
13068 catch_assert_command (const char *arg_entry, int from_tty,
13069 struct cmd_list_element *command)
13070 {
13071 const char *arg = arg_entry;
13072 struct gdbarch *gdbarch = get_current_arch ();
13073 int tempflag;
13074 std::string cond_string;
13075
13076 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13077
13078 if (!arg)
13079 arg = "";
13080 catch_ada_assert_command_split (arg, cond_string);
13081 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
13082 "", cond_string,
13083 tempflag, 1 /* enabled */,
13084 from_tty);
13085 }
13086
13087 /* Return non-zero if the symbol SYM is an Ada exception object. */
13088
13089 static int
13090 ada_is_exception_sym (struct symbol *sym)
13091 {
13092 const char *type_name = TYPE_NAME (SYMBOL_TYPE (sym));
13093
13094 return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
13095 && SYMBOL_CLASS (sym) != LOC_BLOCK
13096 && SYMBOL_CLASS (sym) != LOC_CONST
13097 && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
13098 && type_name != NULL && strcmp (type_name, "exception") == 0);
13099 }
13100
13101 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
13102 Ada exception object. This matches all exceptions except the ones
13103 defined by the Ada language. */
13104
13105 static int
13106 ada_is_non_standard_exception_sym (struct symbol *sym)
13107 {
13108 int i;
13109
13110 if (!ada_is_exception_sym (sym))
13111 return 0;
13112
13113 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13114 if (strcmp (sym->linkage_name (), standard_exc[i]) == 0)
13115 return 0; /* A standard exception. */
13116
13117 /* Numeric_Error is also a standard exception, so exclude it.
13118 See the STANDARD_EXC description for more details as to why
13119 this exception is not listed in that array. */
13120 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
13121 return 0;
13122
13123 return 1;
13124 }
13125
13126 /* A helper function for std::sort, comparing two struct ada_exc_info
13127 objects.
13128
13129 The comparison is determined first by exception name, and then
13130 by exception address. */
13131
13132 bool
13133 ada_exc_info::operator< (const ada_exc_info &other) const
13134 {
13135 int result;
13136
13137 result = strcmp (name, other.name);
13138 if (result < 0)
13139 return true;
13140 if (result == 0 && addr < other.addr)
13141 return true;
13142 return false;
13143 }
13144
13145 bool
13146 ada_exc_info::operator== (const ada_exc_info &other) const
13147 {
13148 return addr == other.addr && strcmp (name, other.name) == 0;
13149 }
13150
13151 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13152 routine, but keeping the first SKIP elements untouched.
13153
13154 All duplicates are also removed. */
13155
13156 static void
13157 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13158 int skip)
13159 {
13160 std::sort (exceptions->begin () + skip, exceptions->end ());
13161 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13162 exceptions->end ());
13163 }
13164
13165 /* Add all exceptions defined by the Ada standard whose name match
13166 a regular expression.
13167
13168 If PREG is not NULL, then this regexp_t object is used to
13169 perform the symbol name matching. Otherwise, no name-based
13170 filtering is performed.
13171
13172 EXCEPTIONS is a vector of exceptions to which matching exceptions
13173 gets pushed. */
13174
13175 static void
13176 ada_add_standard_exceptions (compiled_regex *preg,
13177 std::vector<ada_exc_info> *exceptions)
13178 {
13179 int i;
13180
13181 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13182 {
13183 if (preg == NULL
13184 || preg->exec (standard_exc[i], 0, NULL, 0) == 0)
13185 {
13186 struct bound_minimal_symbol msymbol
13187 = ada_lookup_simple_minsym (standard_exc[i]);
13188
13189 if (msymbol.minsym != NULL)
13190 {
13191 struct ada_exc_info info
13192 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};
13193
13194 exceptions->push_back (info);
13195 }
13196 }
13197 }
13198 }
13199
13200 /* Add all Ada exceptions defined locally and accessible from the given
13201 FRAME.
13202
13203 If PREG is not NULL, then this regexp_t object is used to
13204 perform the symbol name matching. Otherwise, no name-based
13205 filtering is performed.
13206
13207 EXCEPTIONS is a vector of exceptions to which matching exceptions
13208 gets pushed. */
13209
13210 static void
13211 ada_add_exceptions_from_frame (compiled_regex *preg,
13212 struct frame_info *frame,
13213 std::vector<ada_exc_info> *exceptions)
13214 {
13215 const struct block *block = get_frame_block (frame, 0);
13216
13217 while (block != 0)
13218 {
13219 struct block_iterator iter;
13220 struct symbol *sym;
13221
13222 ALL_BLOCK_SYMBOLS (block, iter, sym)
13223 {
13224 switch (SYMBOL_CLASS (sym))
13225 {
13226 case LOC_TYPEDEF:
13227 case LOC_BLOCK:
13228 case LOC_CONST:
13229 break;
13230 default:
13231 if (ada_is_exception_sym (sym))
13232 {
13233 struct ada_exc_info info = {sym->print_name (),
13234 SYMBOL_VALUE_ADDRESS (sym)};
13235
13236 exceptions->push_back (info);
13237 }
13238 }
13239 }
13240 if (BLOCK_FUNCTION (block) != NULL)
13241 break;
13242 block = BLOCK_SUPERBLOCK (block);
13243 }
13244 }
13245
13246 /* Return true if NAME matches PREG or if PREG is NULL. */
13247
13248 static bool
13249 name_matches_regex (const char *name, compiled_regex *preg)
13250 {
13251 return (preg == NULL
13252 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
13253 }
13254
13255 /* Add all exceptions defined globally whose name name match
13256 a regular expression, excluding standard exceptions.
13257
13258 The reason we exclude standard exceptions is that they need
13259 to be handled separately: Standard exceptions are defined inside
13260 a runtime unit which is normally not compiled with debugging info,
13261 and thus usually do not show up in our symbol search. However,
13262 if the unit was in fact built with debugging info, we need to
13263 exclude them because they would duplicate the entry we found
13264 during the special loop that specifically searches for those
13265 standard exceptions.
13266
13267 If PREG is not NULL, then this regexp_t object is used to
13268 perform the symbol name matching. Otherwise, no name-based
13269 filtering is performed.
13270
13271 EXCEPTIONS is a vector of exceptions to which matching exceptions
13272 gets pushed. */
13273
13274 static void
13275 ada_add_global_exceptions (compiled_regex *preg,
13276 std::vector<ada_exc_info> *exceptions)
13277 {
13278 /* In Ada, the symbol "search name" is a linkage name, whereas the
13279 regular expression used to do the matching refers to the natural
13280 name. So match against the decoded name. */
13281 expand_symtabs_matching (NULL,
13282 lookup_name_info::match_any (),
13283 [&] (const char *search_name)
13284 {
13285 std::string decoded = ada_decode (search_name);
13286 return name_matches_regex (decoded.c_str (), preg);
13287 },
13288 NULL,
13289 VARIABLES_DOMAIN);
13290
13291 for (objfile *objfile : current_program_space->objfiles ())
13292 {
13293 for (compunit_symtab *s : objfile->compunits ())
13294 {
13295 const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
13296 int i;
13297
13298 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13299 {
13300 const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
13301 struct block_iterator iter;
13302 struct symbol *sym;
13303
13304 ALL_BLOCK_SYMBOLS (b, iter, sym)
13305 if (ada_is_non_standard_exception_sym (sym)
13306 && name_matches_regex (sym->natural_name (), preg))
13307 {
13308 struct ada_exc_info info
13309 = {sym->print_name (), SYMBOL_VALUE_ADDRESS (sym)};
13310
13311 exceptions->push_back (info);
13312 }
13313 }
13314 }
13315 }
13316 }
13317
13318 /* Implements ada_exceptions_list with the regular expression passed
13319 as a regex_t, rather than a string.
13320
13321 If not NULL, PREG is used to filter out exceptions whose names
13322 do not match. Otherwise, all exceptions are listed. */
13323
13324 static std::vector<ada_exc_info>
13325 ada_exceptions_list_1 (compiled_regex *preg)
13326 {
13327 std::vector<ada_exc_info> result;
13328 int prev_len;
13329
13330 /* First, list the known standard exceptions. These exceptions
13331 need to be handled separately, as they are usually defined in
13332 runtime units that have been compiled without debugging info. */
13333
13334 ada_add_standard_exceptions (preg, &result);
13335
13336 /* Next, find all exceptions whose scope is local and accessible
13337 from the currently selected frame. */
13338
13339 if (has_stack_frames ())
13340 {
13341 prev_len = result.size ();
13342 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13343 &result);
13344 if (result.size () > prev_len)
13345 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13346 }
13347
13348 /* Add all exceptions whose scope is global. */
13349
13350 prev_len = result.size ();
13351 ada_add_global_exceptions (preg, &result);
13352 if (result.size () > prev_len)
13353 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13354
13355 return result;
13356 }
13357
13358 /* Return a vector of ada_exc_info.
13359
13360 If REGEXP is NULL, all exceptions are included in the result.
13361 Otherwise, it should contain a valid regular expression,
13362 and only the exceptions whose names match that regular expression
13363 are included in the result.
13364
13365 The exceptions are sorted in the following order:
13366 - Standard exceptions (defined by the Ada language), in
13367 alphabetical order;
13368 - Exceptions only visible from the current frame, in
13369 alphabetical order;
13370 - Exceptions whose scope is global, in alphabetical order. */
13371
13372 std::vector<ada_exc_info>
13373 ada_exceptions_list (const char *regexp)
13374 {
13375 if (regexp == NULL)
13376 return ada_exceptions_list_1 (NULL);
13377
13378 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13379 return ada_exceptions_list_1 (&reg);
13380 }
13381
13382 /* Implement the "info exceptions" command. */
13383
13384 static void
13385 info_exceptions_command (const char *regexp, int from_tty)
13386 {
13387 struct gdbarch *gdbarch = get_current_arch ();
13388
13389 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13390
13391 if (regexp != NULL)
13392 printf_filtered
13393 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13394 else
13395 printf_filtered (_("All defined Ada exceptions:\n"));
13396
13397 for (const ada_exc_info &info : exceptions)
13398 printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13399 }
13400
13401 /* Operators */
13402 /* Information about operators given special treatment in functions
13403 below. */
13404 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>). */
13405
13406 #define ADA_OPERATORS \
13407 OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
13408 OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
13409 OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
13410 OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
13411 OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
13412 OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
13413 OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
13414 OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
13415 OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
13416 OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
13417 OP_DEFN (OP_ATR_POS, 1, 2, 0) \
13418 OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
13419 OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
13420 OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
13421 OP_DEFN (UNOP_QUAL, 3, 1, 0) \
13422 OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
13423 OP_DEFN (OP_OTHERS, 1, 1, 0) \
13424 OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
13425 OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
13426
13427 static void
13428 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
13429 int *argsp)
13430 {
13431 switch (exp->elts[pc - 1].opcode)
13432 {
13433 default:
13434 operator_length_standard (exp, pc, oplenp, argsp);
13435 break;
13436
13437 #define OP_DEFN(op, len, args, binop) \
13438 case op: *oplenp = len; *argsp = args; break;
13439 ADA_OPERATORS;
13440 #undef OP_DEFN
13441
13442 case OP_AGGREGATE:
13443 *oplenp = 3;
13444 *argsp = longest_to_int (exp->elts[pc - 2].longconst);
13445 break;
13446
13447 case OP_CHOICES:
13448 *oplenp = 3;
13449 *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
13450 break;
13451 }
13452 }
13453
13454 /* Implementation of the exp_descriptor method operator_check. */
13455
13456 static int
13457 ada_operator_check (struct expression *exp, int pos,
13458 int (*objfile_func) (struct objfile *objfile, void *data),
13459 void *data)
13460 {
13461 const union exp_element *const elts = exp->elts;
13462 struct type *type = NULL;
13463
13464 switch (elts[pos].opcode)
13465 {
13466 case UNOP_IN_RANGE:
13467 case UNOP_QUAL:
13468 type = elts[pos + 1].type;
13469 break;
13470
13471 default:
13472 return operator_check_standard (exp, pos, objfile_func, data);
13473 }
13474
13475 /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL. */
13476
13477 if (type && TYPE_OBJFILE (type)
13478 && (*objfile_func) (TYPE_OBJFILE (type), data))
13479 return 1;
13480
13481 return 0;
13482 }
13483
13484 static const char *
13485 ada_op_name (enum exp_opcode opcode)
13486 {
13487 switch (opcode)
13488 {
13489 default:
13490 return op_name_standard (opcode);
13491
13492 #define OP_DEFN(op, len, args, binop) case op: return #op;
13493 ADA_OPERATORS;
13494 #undef OP_DEFN
13495
13496 case OP_AGGREGATE:
13497 return "OP_AGGREGATE";
13498 case OP_CHOICES:
13499 return "OP_CHOICES";
13500 case OP_NAME:
13501 return "OP_NAME";
13502 }
13503 }
13504
13505 /* As for operator_length, but assumes PC is pointing at the first
13506 element of the operator, and gives meaningful results only for the
13507 Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise. */
13508
13509 static void
13510 ada_forward_operator_length (struct expression *exp, int pc,
13511 int *oplenp, int *argsp)
13512 {
13513 switch (exp->elts[pc].opcode)
13514 {
13515 default:
13516 *oplenp = *argsp = 0;
13517 break;
13518
13519 #define OP_DEFN(op, len, args, binop) \
13520 case op: *oplenp = len; *argsp = args; break;
13521 ADA_OPERATORS;
13522 #undef OP_DEFN
13523
13524 case OP_AGGREGATE:
13525 *oplenp = 3;
13526 *argsp = longest_to_int (exp->elts[pc + 1].longconst);
13527 break;
13528
13529 case OP_CHOICES:
13530 *oplenp = 3;
13531 *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
13532 break;
13533
13534 case OP_STRING:
13535 case OP_NAME:
13536 {
13537 int len = longest_to_int (exp->elts[pc + 1].longconst);
13538
13539 *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
13540 *argsp = 0;
13541 break;
13542 }
13543 }
13544 }
13545
13546 static int
13547 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
13548 {
13549 enum exp_opcode op = exp->elts[elt].opcode;
13550 int oplen, nargs;
13551 int pc = elt;
13552 int i;
13553
13554 ada_forward_operator_length (exp, elt, &oplen, &nargs);
13555
13556 switch (op)
13557 {
13558 /* Ada attributes ('Foo). */
13559 case OP_ATR_FIRST:
13560 case OP_ATR_LAST:
13561 case OP_ATR_LENGTH:
13562 case OP_ATR_IMAGE:
13563 case OP_ATR_MAX:
13564 case OP_ATR_MIN:
13565 case OP_ATR_MODULUS:
13566 case OP_ATR_POS:
13567 case OP_ATR_SIZE:
13568 case OP_ATR_TAG:
13569 case OP_ATR_VAL:
13570 break;
13571
13572 case UNOP_IN_RANGE:
13573 case UNOP_QUAL:
13574 /* XXX: gdb_sprint_host_address, type_sprint */
13575 fprintf_filtered (stream, _("Type @"));
13576 gdb_print_host_address (exp->elts[pc + 1].type, stream);
13577 fprintf_filtered (stream, " (");
13578 type_print (exp->elts[pc + 1].type, NULL, stream, 0);
13579 fprintf_filtered (stream, ")");
13580 break;
13581 case BINOP_IN_BOUNDS:
13582 fprintf_filtered (stream, " (%d)",
13583 longest_to_int (exp->elts[pc + 2].longconst));
13584 break;
13585 case TERNOP_IN_RANGE:
13586 break;
13587
13588 case OP_AGGREGATE:
13589 case OP_OTHERS:
13590 case OP_DISCRETE_RANGE:
13591 case OP_POSITIONAL:
13592 case OP_CHOICES:
13593 break;
13594
13595 case OP_NAME:
13596 case OP_STRING:
13597 {
13598 char *name = &exp->elts[elt + 2].string;
13599 int len = longest_to_int (exp->elts[elt + 1].longconst);
13600
13601 fprintf_filtered (stream, "Text: `%.*s'", len, name);
13602 break;
13603 }
13604
13605 default:
13606 return dump_subexp_body_standard (exp, stream, elt);
13607 }
13608
13609 elt += oplen;
13610 for (i = 0; i < nargs; i += 1)
13611 elt = dump_subexp (exp, stream, elt);
13612
13613 return elt;
13614 }
13615
13616 /* The Ada extension of print_subexp (q.v.). */
13617
13618 static void
13619 ada_print_subexp (struct expression *exp, int *pos,
13620 struct ui_file *stream, enum precedence prec)
13621 {
13622 int oplen, nargs, i;
13623 int pc = *pos;
13624 enum exp_opcode op = exp->elts[pc].opcode;
13625
13626 ada_forward_operator_length (exp, pc, &oplen, &nargs);
13627
13628 *pos += oplen;
13629 switch (op)
13630 {
13631 default:
13632 *pos -= oplen;
13633 print_subexp_standard (exp, pos, stream, prec);
13634 return;
13635
13636 case OP_VAR_VALUE:
13637 fputs_filtered (exp->elts[pc + 2].symbol->natural_name (), stream);
13638 return;
13639
13640 case BINOP_IN_BOUNDS:
13641 /* XXX: sprint_subexp */
13642 print_subexp (exp, pos, stream, PREC_SUFFIX);
13643 fputs_filtered (" in ", stream);
13644 print_subexp (exp, pos, stream, PREC_SUFFIX);
13645 fputs_filtered ("'range", stream);
13646 if (exp->elts[pc + 1].longconst > 1)
13647 fprintf_filtered (stream, "(%ld)",
13648 (long) exp->elts[pc + 1].longconst);
13649 return;
13650
13651 case TERNOP_IN_RANGE:
13652 if (prec >= PREC_EQUAL)
13653 fputs_filtered ("(", stream);
13654 /* XXX: sprint_subexp */
13655 print_subexp (exp, pos, stream, PREC_SUFFIX);
13656 fputs_filtered (" in ", stream);
13657 print_subexp (exp, pos, stream, PREC_EQUAL);
13658 fputs_filtered (" .. ", stream);
13659 print_subexp (exp, pos, stream, PREC_EQUAL);
13660 if (prec >= PREC_EQUAL)
13661 fputs_filtered (")", stream);
13662 return;
13663
13664 case OP_ATR_FIRST:
13665 case OP_ATR_LAST:
13666 case OP_ATR_LENGTH:
13667 case OP_ATR_IMAGE:
13668 case OP_ATR_MAX:
13669 case OP_ATR_MIN:
13670 case OP_ATR_MODULUS:
13671 case OP_ATR_POS:
13672 case OP_ATR_SIZE:
13673 case OP_ATR_TAG:
13674 case OP_ATR_VAL:
13675 if (exp->elts[*pos].opcode == OP_TYPE)
13676 {
13677 if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
13678 LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
13679 &type_print_raw_options);
13680 *pos += 3;
13681 }
13682 else
13683 print_subexp (exp, pos, stream, PREC_SUFFIX);
13684 fprintf_filtered (stream, "'%s", ada_attribute_name (op));
13685 if (nargs > 1)
13686 {
13687 int tem;
13688
13689 for (tem = 1; tem < nargs; tem += 1)
13690 {
13691 fputs_filtered ((tem == 1) ? " (" : ", ", stream);
13692 print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
13693 }
13694 fputs_filtered (")", stream);
13695 }
13696 return;
13697
13698 case UNOP_QUAL:
13699 type_print (exp->elts[pc + 1].type, "", stream, 0);
13700 fputs_filtered ("'(", stream);
13701 print_subexp (exp, pos, stream, PREC_PREFIX);
13702 fputs_filtered (")", stream);
13703 return;
13704
13705 case UNOP_IN_RANGE:
13706 /* XXX: sprint_subexp */
13707 print_subexp (exp, pos, stream, PREC_SUFFIX);
13708 fputs_filtered (" in ", stream);
13709 LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
13710 &type_print_raw_options);
13711 return;
13712
13713 case OP_DISCRETE_RANGE:
13714 print_subexp (exp, pos, stream, PREC_SUFFIX);
13715 fputs_filtered ("..", stream);
13716 print_subexp (exp, pos, stream, PREC_SUFFIX);
13717 return;
13718
13719 case OP_OTHERS:
13720 fputs_filtered ("others => ", stream);
13721 print_subexp (exp, pos, stream, PREC_SUFFIX);
13722 return;
13723
13724 case OP_CHOICES:
13725 for (i = 0; i < nargs-1; i += 1)
13726 {
13727 if (i > 0)
13728 fputs_filtered ("|", stream);
13729 print_subexp (exp, pos, stream, PREC_SUFFIX);
13730 }
13731 fputs_filtered (" => ", stream);
13732 print_subexp (exp, pos, stream, PREC_SUFFIX);
13733 return;
13734
13735 case OP_POSITIONAL:
13736 print_subexp (exp, pos, stream, PREC_SUFFIX);
13737 return;
13738
13739 case OP_AGGREGATE:
13740 fputs_filtered ("(", stream);
13741 for (i = 0; i < nargs; i += 1)
13742 {
13743 if (i > 0)
13744 fputs_filtered (", ", stream);
13745 print_subexp (exp, pos, stream, PREC_SUFFIX);
13746 }
13747 fputs_filtered (")", stream);
13748 return;
13749 }
13750 }
13751
13752 /* Table mapping opcodes into strings for printing operators
13753 and precedences of the operators. */
13754
13755 static const struct op_print ada_op_print_tab[] = {
13756 {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
13757 {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
13758 {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
13759 {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
13760 {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
13761 {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
13762 {"=", BINOP_EQUAL, PREC_EQUAL, 0},
13763 {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
13764 {"<=", BINOP_LEQ, PREC_ORDER, 0},
13765 {">=", BINOP_GEQ, PREC_ORDER, 0},
13766 {">", BINOP_GTR, PREC_ORDER, 0},
13767 {"<", BINOP_LESS, PREC_ORDER, 0},
13768 {">>", BINOP_RSH, PREC_SHIFT, 0},
13769 {"<<", BINOP_LSH, PREC_SHIFT, 0},
13770 {"+", BINOP_ADD, PREC_ADD, 0},
13771 {"-", BINOP_SUB, PREC_ADD, 0},
13772 {"&", BINOP_CONCAT, PREC_ADD, 0},
13773 {"*", BINOP_MUL, PREC_MUL, 0},
13774 {"/", BINOP_DIV, PREC_MUL, 0},
13775 {"rem", BINOP_REM, PREC_MUL, 0},
13776 {"mod", BINOP_MOD, PREC_MUL, 0},
13777 {"**", BINOP_EXP, PREC_REPEAT, 0},
13778 {"@", BINOP_REPEAT, PREC_REPEAT, 0},
13779 {"-", UNOP_NEG, PREC_PREFIX, 0},
13780 {"+", UNOP_PLUS, PREC_PREFIX, 0},
13781 {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
13782 {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
13783 {"abs ", UNOP_ABS, PREC_PREFIX, 0},
13784 {".all", UNOP_IND, PREC_SUFFIX, 1},
13785 {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
13786 {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
13787 {NULL, OP_NULL, PREC_SUFFIX, 0}
13788 };
13789 \f
13790 enum ada_primitive_types {
13791 ada_primitive_type_int,
13792 ada_primitive_type_long,
13793 ada_primitive_type_short,
13794 ada_primitive_type_char,
13795 ada_primitive_type_float,
13796 ada_primitive_type_double,
13797 ada_primitive_type_void,
13798 ada_primitive_type_long_long,
13799 ada_primitive_type_long_double,
13800 ada_primitive_type_natural,
13801 ada_primitive_type_positive,
13802 ada_primitive_type_system_address,
13803 ada_primitive_type_storage_offset,
13804 nr_ada_primitive_types
13805 };
13806
13807 static void
13808 ada_language_arch_info (struct gdbarch *gdbarch,
13809 struct language_arch_info *lai)
13810 {
13811 const struct builtin_type *builtin = builtin_type (gdbarch);
13812
13813 lai->primitive_type_vector
13814 = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_ada_primitive_types + 1,
13815 struct type *);
13816
13817 lai->primitive_type_vector [ada_primitive_type_int]
13818 = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13819 0, "integer");
13820 lai->primitive_type_vector [ada_primitive_type_long]
13821 = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
13822 0, "long_integer");
13823 lai->primitive_type_vector [ada_primitive_type_short]
13824 = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
13825 0, "short_integer");
13826 lai->string_char_type
13827 = lai->primitive_type_vector [ada_primitive_type_char]
13828 = arch_character_type (gdbarch, TARGET_CHAR_BIT, 0, "character");
13829 lai->primitive_type_vector [ada_primitive_type_float]
13830 = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
13831 "float", gdbarch_float_format (gdbarch));
13832 lai->primitive_type_vector [ada_primitive_type_double]
13833 = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
13834 "long_float", gdbarch_double_format (gdbarch));
13835 lai->primitive_type_vector [ada_primitive_type_long_long]
13836 = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
13837 0, "long_long_integer");
13838 lai->primitive_type_vector [ada_primitive_type_long_double]
13839 = arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
13840 "long_long_float", gdbarch_long_double_format (gdbarch));
13841 lai->primitive_type_vector [ada_primitive_type_natural]
13842 = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13843 0, "natural");
13844 lai->primitive_type_vector [ada_primitive_type_positive]
13845 = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13846 0, "positive");
13847 lai->primitive_type_vector [ada_primitive_type_void]
13848 = builtin->builtin_void;
13849
13850 lai->primitive_type_vector [ada_primitive_type_system_address]
13851 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
13852 "void"));
13853 TYPE_NAME (lai->primitive_type_vector [ada_primitive_type_system_address])
13854 = "system__address";
13855
13856 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13857 type. This is a signed integral type whose size is the same as
13858 the size of addresses. */
13859 {
13860 unsigned int addr_length = TYPE_LENGTH
13861 (lai->primitive_type_vector [ada_primitive_type_system_address]);
13862
13863 lai->primitive_type_vector [ada_primitive_type_storage_offset]
13864 = arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
13865 "storage_offset");
13866 }
13867
13868 lai->bool_type_symbol = NULL;
13869 lai->bool_type_default = builtin->builtin_bool;
13870 }
13871 \f
13872 /* Language vector */
13873
13874 /* Not really used, but needed in the ada_language_defn. */
13875
13876 static void
13877 emit_char (int c, struct type *type, struct ui_file *stream, int quoter)
13878 {
13879 ada_emit_char (c, type, stream, quoter, 1);
13880 }
13881
13882 static int
13883 parse (struct parser_state *ps)
13884 {
13885 warnings_issued = 0;
13886 return ada_parse (ps);
13887 }
13888
13889 static const struct exp_descriptor ada_exp_descriptor = {
13890 ada_print_subexp,
13891 ada_operator_length,
13892 ada_operator_check,
13893 ada_op_name,
13894 ada_dump_subexp_body,
13895 ada_evaluate_subexp
13896 };
13897
13898 /* symbol_name_matcher_ftype adapter for wild_match. */
13899
13900 static bool
13901 do_wild_match (const char *symbol_search_name,
13902 const lookup_name_info &lookup_name,
13903 completion_match_result *comp_match_res)
13904 {
13905 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13906 }
13907
13908 /* symbol_name_matcher_ftype adapter for full_match. */
13909
13910 static bool
13911 do_full_match (const char *symbol_search_name,
13912 const lookup_name_info &lookup_name,
13913 completion_match_result *comp_match_res)
13914 {
13915 return full_match (symbol_search_name, ada_lookup_name (lookup_name));
13916 }
13917
13918 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
13919
13920 static bool
13921 do_exact_match (const char *symbol_search_name,
13922 const lookup_name_info &lookup_name,
13923 completion_match_result *comp_match_res)
13924 {
13925 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13926 }
13927
13928 /* Build the Ada lookup name for LOOKUP_NAME. */
13929
13930 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13931 {
13932 gdb::string_view user_name = lookup_name.name ();
13933
13934 if (user_name[0] == '<')
13935 {
13936 if (user_name.back () == '>')
13937 m_encoded_name
13938 = user_name.substr (1, user_name.size () - 2).to_string ();
13939 else
13940 m_encoded_name
13941 = user_name.substr (1, user_name.size () - 1).to_string ();
13942 m_encoded_p = true;
13943 m_verbatim_p = true;
13944 m_wild_match_p = false;
13945 m_standard_p = false;
13946 }
13947 else
13948 {
13949 m_verbatim_p = false;
13950
13951 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
13952
13953 if (!m_encoded_p)
13954 {
13955 const char *folded = ada_fold_name (user_name);
13956 const char *encoded = ada_encode_1 (folded, false);
13957 if (encoded != NULL)
13958 m_encoded_name = encoded;
13959 else
13960 m_encoded_name = user_name.to_string ();
13961 }
13962 else
13963 m_encoded_name = user_name.to_string ();
13964
13965 /* Handle the 'package Standard' special case. See description
13966 of m_standard_p. */
13967 if (startswith (m_encoded_name.c_str (), "standard__"))
13968 {
13969 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13970 m_standard_p = true;
13971 }
13972 else
13973 m_standard_p = false;
13974
13975 /* If the name contains a ".", then the user is entering a fully
13976 qualified entity name, and the match must not be done in wild
13977 mode. Similarly, if the user wants to complete what looks
13978 like an encoded name, the match must not be done in wild
13979 mode. Also, in the standard__ special case always do
13980 non-wild matching. */
13981 m_wild_match_p
13982 = (lookup_name.match_type () != symbol_name_match_type::FULL
13983 && !m_encoded_p
13984 && !m_standard_p
13985 && user_name.find ('.') == std::string::npos);
13986 }
13987 }
13988
13989 /* symbol_name_matcher_ftype method for Ada. This only handles
13990 completion mode. */
13991
13992 static bool
13993 ada_symbol_name_matches (const char *symbol_search_name,
13994 const lookup_name_info &lookup_name,
13995 completion_match_result *comp_match_res)
13996 {
13997 return lookup_name.ada ().matches (symbol_search_name,
13998 lookup_name.match_type (),
13999 comp_match_res);
14000 }
14001
14002 /* A name matcher that matches the symbol name exactly, with
14003 strcmp. */
14004
14005 static bool
14006 literal_symbol_name_matcher (const char *symbol_search_name,
14007 const lookup_name_info &lookup_name,
14008 completion_match_result *comp_match_res)
14009 {
14010 gdb::string_view name_view = lookup_name.name ();
14011
14012 if (lookup_name.completion_mode ()
14013 ? (strncmp (symbol_search_name, name_view.data (),
14014 name_view.size ()) == 0)
14015 : symbol_search_name == name_view)
14016 {
14017 if (comp_match_res != NULL)
14018 comp_match_res->set_match (symbol_search_name);
14019 return true;
14020 }
14021 else
14022 return false;
14023 }
14024
14025 /* Implement the "la_get_symbol_name_matcher" language_defn method for
14026 Ada. */
14027
14028 static symbol_name_matcher_ftype *
14029 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
14030 {
14031 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
14032 return literal_symbol_name_matcher;
14033
14034 if (lookup_name.completion_mode ())
14035 return ada_symbol_name_matches;
14036 else
14037 {
14038 if (lookup_name.ada ().wild_match_p ())
14039 return do_wild_match;
14040 else if (lookup_name.ada ().verbatim_p ())
14041 return do_exact_match;
14042 else
14043 return do_full_match;
14044 }
14045 }
14046
14047 /* Implement the "la_read_var_value" language_defn method for Ada. */
14048
14049 static struct value *
14050 ada_read_var_value (struct symbol *var, const struct block *var_block,
14051 struct frame_info *frame)
14052 {
14053 /* The only case where default_read_var_value is not sufficient
14054 is when VAR is a renaming... */
14055 if (frame != nullptr)
14056 {
14057 const struct block *frame_block = get_frame_block (frame, NULL);
14058 if (frame_block != nullptr && ada_is_renaming_symbol (var))
14059 return ada_read_renaming_var_value (var, frame_block);
14060 }
14061
14062 /* This is a typical case where we expect the default_read_var_value
14063 function to work. */
14064 return default_read_var_value (var, var_block, frame);
14065 }
14066
14067 static const char *ada_extensions[] =
14068 {
14069 ".adb", ".ads", ".a", ".ada", ".dg", NULL
14070 };
14071
14072 extern const struct language_defn ada_language_defn = {
14073 "ada", /* Language name */
14074 "Ada",
14075 language_ada,
14076 range_check_off,
14077 case_sensitive_on, /* Yes, Ada is case-insensitive, but
14078 that's not quite what this means. */
14079 array_row_major,
14080 macro_expansion_no,
14081 ada_extensions,
14082 &ada_exp_descriptor,
14083 parse,
14084 resolve,
14085 ada_printchar, /* Print a character constant */
14086 ada_printstr, /* Function to print string constant */
14087 emit_char, /* Function to print single char (not used) */
14088 ada_print_type, /* Print a type using appropriate syntax */
14089 ada_print_typedef, /* Print a typedef using appropriate syntax */
14090 ada_value_print_inner, /* la_value_print_inner */
14091 ada_value_print, /* Print a top-level value */
14092 ada_read_var_value, /* la_read_var_value */
14093 NULL, /* Language specific skip_trampoline */
14094 NULL, /* name_of_this */
14095 true, /* la_store_sym_names_in_linkage_form_p */
14096 ada_lookup_symbol_nonlocal, /* Looking up non-local symbols. */
14097 basic_lookup_transparent_type, /* lookup_transparent_type */
14098 ada_la_decode, /* Language specific symbol demangler */
14099 ada_sniff_from_mangled_name,
14100 NULL, /* Language specific
14101 class_name_from_physname */
14102 ada_op_print_tab, /* expression operators for printing */
14103 0, /* c-style arrays */
14104 1, /* String lower bound */
14105 ada_get_gdb_completer_word_break_characters,
14106 ada_collect_symbol_completion_matches,
14107 ada_language_arch_info,
14108 ada_print_array_index,
14109 default_pass_by_reference,
14110 ada_watch_location_expression,
14111 ada_get_symbol_name_matcher, /* la_get_symbol_name_matcher */
14112 ada_iterate_over_symbols,
14113 default_search_name_hash,
14114 &ada_varobj_ops,
14115 NULL,
14116 NULL,
14117 ada_is_string_type,
14118 "(...)" /* la_struct_too_deep_ellipsis */
14119 };
14120
14121 /* Command-list for the "set/show ada" prefix command. */
14122 static struct cmd_list_element *set_ada_list;
14123 static struct cmd_list_element *show_ada_list;
14124
14125 static void
14126 initialize_ada_catchpoint_ops (void)
14127 {
14128 struct breakpoint_ops *ops;
14129
14130 initialize_breakpoint_ops ();
14131
14132 ops = &catch_exception_breakpoint_ops;
14133 *ops = bkpt_breakpoint_ops;
14134 ops->allocate_location = allocate_location_exception;
14135 ops->re_set = re_set_exception;
14136 ops->check_status = check_status_exception;
14137 ops->print_it = print_it_exception;
14138 ops->print_one = print_one_exception;
14139 ops->print_mention = print_mention_exception;
14140 ops->print_recreate = print_recreate_exception;
14141
14142 ops = &catch_exception_unhandled_breakpoint_ops;
14143 *ops = bkpt_breakpoint_ops;
14144 ops->allocate_location = allocate_location_exception;
14145 ops->re_set = re_set_exception;
14146 ops->check_status = check_status_exception;
14147 ops->print_it = print_it_exception;
14148 ops->print_one = print_one_exception;
14149 ops->print_mention = print_mention_exception;
14150 ops->print_recreate = print_recreate_exception;
14151
14152 ops = &catch_assert_breakpoint_ops;
14153 *ops = bkpt_breakpoint_ops;
14154 ops->allocate_location = allocate_location_exception;
14155 ops->re_set = re_set_exception;
14156 ops->check_status = check_status_exception;
14157 ops->print_it = print_it_exception;
14158 ops->print_one = print_one_exception;
14159 ops->print_mention = print_mention_exception;
14160 ops->print_recreate = print_recreate_exception;
14161
14162 ops = &catch_handlers_breakpoint_ops;
14163 *ops = bkpt_breakpoint_ops;
14164 ops->allocate_location = allocate_location_exception;
14165 ops->re_set = re_set_exception;
14166 ops->check_status = check_status_exception;
14167 ops->print_it = print_it_exception;
14168 ops->print_one = print_one_exception;
14169 ops->print_mention = print_mention_exception;
14170 ops->print_recreate = print_recreate_exception;
14171 }
14172
14173 /* This module's 'new_objfile' observer. */
14174
14175 static void
14176 ada_new_objfile_observer (struct objfile *objfile)
14177 {
14178 ada_clear_symbol_cache ();
14179 }
14180
14181 /* This module's 'free_objfile' observer. */
14182
14183 static void
14184 ada_free_objfile_observer (struct objfile *objfile)
14185 {
14186 ada_clear_symbol_cache ();
14187 }
14188
14189 void _initialize_ada_language ();
14190 void
14191 _initialize_ada_language ()
14192 {
14193 initialize_ada_catchpoint_ops ();
14194
14195 add_basic_prefix_cmd ("ada", no_class,
14196 _("Prefix command for changing Ada-specific settings."),
14197 &set_ada_list, "set ada ", 0, &setlist);
14198
14199 add_show_prefix_cmd ("ada", no_class,
14200 _("Generic command for showing Ada-specific settings."),
14201 &show_ada_list, "show ada ", 0, &showlist);
14202
14203 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
14204 &trust_pad_over_xvs, _("\
14205 Enable or disable an optimization trusting PAD types over XVS types."), _("\
14206 Show whether an optimization trusting PAD types over XVS types is activated."),
14207 _("\
14208 This is related to the encoding used by the GNAT compiler. The debugger\n\
14209 should normally trust the contents of PAD types, but certain older versions\n\
14210 of GNAT have a bug that sometimes causes the information in the PAD type\n\
14211 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
14212 work around this bug. It is always safe to turn this option \"off\", but\n\
14213 this incurs a slight performance penalty, so it is recommended to NOT change\n\
14214 this option to \"off\" unless necessary."),
14215 NULL, NULL, &set_ada_list, &show_ada_list);
14216
14217 add_setshow_boolean_cmd ("print-signatures", class_vars,
14218 &print_signatures, _("\
14219 Enable or disable the output of formal and return types for functions in the \
14220 overloads selection menu."), _("\
14221 Show whether the output of formal and return types for functions in the \
14222 overloads selection menu is activated."),
14223 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
14224
14225 add_catch_command ("exception", _("\
14226 Catch Ada exceptions, when raised.\n\
14227 Usage: catch exception [ARG] [if CONDITION]\n\
14228 Without any argument, stop when any Ada exception is raised.\n\
14229 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14230 being raised does not have a handler (and will therefore lead to the task's\n\
14231 termination).\n\
14232 Otherwise, the catchpoint only stops when the name of the exception being\n\
14233 raised is the same as ARG.\n\
14234 CONDITION is a boolean expression that is evaluated to see whether the\n\
14235 exception should cause a stop."),
14236 catch_ada_exception_command,
14237 catch_ada_completer,
14238 CATCH_PERMANENT,
14239 CATCH_TEMPORARY);
14240
14241 add_catch_command ("handlers", _("\
14242 Catch Ada exceptions, when handled.\n\
14243 Usage: catch handlers [ARG] [if CONDITION]\n\
14244 Without any argument, stop when any Ada exception is handled.\n\
14245 With an argument, catch only exceptions with the given name.\n\
14246 CONDITION is a boolean expression that is evaluated to see whether the\n\
14247 exception should cause a stop."),
14248 catch_ada_handlers_command,
14249 catch_ada_completer,
14250 CATCH_PERMANENT,
14251 CATCH_TEMPORARY);
14252 add_catch_command ("assert", _("\
14253 Catch failed Ada assertions, when raised.\n\
14254 Usage: catch assert [if CONDITION]\n\
14255 CONDITION is a boolean expression that is evaluated to see whether the\n\
14256 exception should cause a stop."),
14257 catch_assert_command,
14258 NULL,
14259 CATCH_PERMANENT,
14260 CATCH_TEMPORARY);
14261
14262 varsize_limit = 65536;
14263 add_setshow_uinteger_cmd ("varsize-limit", class_support,
14264 &varsize_limit, _("\
14265 Set the maximum number of bytes allowed in a variable-size object."), _("\
14266 Show the maximum number of bytes allowed in a variable-size object."), _("\
14267 Attempts to access an object whose size is not a compile-time constant\n\
14268 and exceeds this limit will cause an error."),
14269 NULL, NULL, &setlist, &showlist);
14270
14271 add_info ("exceptions", info_exceptions_command,
14272 _("\
14273 List all Ada exception names.\n\
14274 Usage: info exceptions [REGEXP]\n\
14275 If a regular expression is passed as an argument, only those matching\n\
14276 the regular expression are listed."));
14277
14278 add_basic_prefix_cmd ("ada", class_maintenance,
14279 _("Set Ada maintenance-related variables."),
14280 &maint_set_ada_cmdlist, "maintenance set ada ",
14281 0/*allow-unknown*/, &maintenance_set_cmdlist);
14282
14283 add_show_prefix_cmd ("ada", class_maintenance,
14284 _("Show Ada maintenance-related variables."),
14285 &maint_show_ada_cmdlist, "maintenance show ada ",
14286 0/*allow-unknown*/, &maintenance_show_cmdlist);
14287
14288 add_setshow_boolean_cmd
14289 ("ignore-descriptive-types", class_maintenance,
14290 &ada_ignore_descriptive_types_p,
14291 _("Set whether descriptive types generated by GNAT should be ignored."),
14292 _("Show whether descriptive types generated by GNAT should be ignored."),
14293 _("\
14294 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14295 DWARF attribute."),
14296 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14297
14298 decoded_names_store = htab_create_alloc (256, htab_hash_string, streq_hash,
14299 NULL, xcalloc, xfree);
14300
14301 /* The ada-lang observers. */
14302 gdb::observers::new_objfile.attach (ada_new_objfile_observer);
14303 gdb::observers::free_objfile.attach (ada_free_objfile_observer);
14304 gdb::observers::inferior_exit.attach (ada_inferior_exit);
14305 }
This page took 0.355588 seconds and 5 git commands to generate.